blob: eb0abafcaaa29cdf2a06ef987355c48c7cb7eea2 [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
279// FIXME: fix this code to cleanup the Old attrs correctly
280 while (attr) {
281 tmp = attr;
282 attr = attr->getNext();
283
284 if (!DeclHasAttr(New, tmp)) {
285 New->addAttr(tmp);
286 } else {
287 tmp->setNext(0);
288 delete(tmp);
289 }
290 }
291}
292
Chris Lattner04421082008-04-08 04:40:51 +0000293/// MergeFunctionDecl - We just parsed a function 'New' from
294/// declarator D which has the same name and scope as a previous
295/// declaration 'Old'. Figure out how to resolve this situation,
296/// merging decls or emitting diagnostics as appropriate.
Douglas Gregorf0097952008-04-21 02:02:58 +0000297/// Redeclaration will be set true if thisNew is a redeclaration OldD.
298FunctionDecl *
299Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
300 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000301 // Verify the old decl was also a function.
302 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
303 if (!Old) {
304 Diag(New->getLocation(), diag::err_redefinition_different_kind,
305 New->getName());
306 Diag(OldD->getLocation(), diag::err_previous_definition);
307 return New;
308 }
Chris Lattner04421082008-04-08 04:40:51 +0000309
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000310 QualType OldQType = Context.getCanonicalType(Old->getType());
311 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000312
Chris Lattner04421082008-04-08 04:40:51 +0000313 // C++ [dcl.fct]p3:
314 // All declarations for a function shall agree exactly in both the
315 // return type and the parameter-type-list.
Douglas Gregorf0097952008-04-21 02:02:58 +0000316 if (getLangOptions().CPlusPlus && OldQType == NewQType) {
317 MergeAttributes(New, Old);
318 Redeclaration = true;
Chris Lattner04421082008-04-08 04:40:51 +0000319 return MergeCXXFunctionDecl(New, Old);
Douglas Gregorf0097952008-04-21 02:02:58 +0000320 }
Chris Lattner04421082008-04-08 04:40:51 +0000321
322 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000323 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000324 if (!getLangOptions().CPlusPlus &&
325 Context.functionTypesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000326 MergeAttributes(New, Old);
327 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000328 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000329 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000330
Steve Naroff837618c2008-01-16 15:01:34 +0000331 // A function that has already been declared has been redeclared or defined
332 // with a different type- show appropriate diagnostic
Steve Naroffe2ef8152008-04-04 14:32:09 +0000333 diag::kind PrevDiag;
Douglas Gregorf0097952008-04-21 02:02:58 +0000334 if (Old->isThisDeclarationADefinition())
Steve Naroffe2ef8152008-04-04 14:32:09 +0000335 PrevDiag = diag::err_previous_definition;
336 else if (Old->isImplicit())
337 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000338 else
Steve Naroffe2ef8152008-04-04 14:32:09 +0000339 PrevDiag = diag::err_previous_declaration;
Steve Naroff837618c2008-01-16 15:01:34 +0000340
Reid Spencer5f016e22007-07-11 17:01:13 +0000341 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
342 // TODO: This is totally simplistic. It should handle merging functions
343 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000344 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
345 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000346 return New;
347}
348
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000349/// equivalentArrayTypes - Used to determine whether two array types are
350/// equivalent.
351/// We need to check this explicitly as an incomplete array definition is
352/// considered a VariableArrayType, so will not match a complete array
353/// definition that would be otherwise equivalent.
354static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
355 const ArrayType *NewAT = NewQType->getAsArrayType();
356 const ArrayType *OldAT = OldQType->getAsArrayType();
357
358 if (!NewAT || !OldAT)
359 return false;
360
361 // If either (or both) array types in incomplete we need to strip off the
362 // outer VariableArrayType. Once the outer VAT is removed the remaining
363 // types must be identical if the array types are to be considered
364 // equivalent.
365 // eg. int[][1] and int[1][1] become
366 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
367 // removing the outermost VAT gives
368 // CAT(1, int) and CAT(1, int)
369 // which are equal, therefore the array types are equivalent.
Eli Friedman9db13972008-02-15 12:53:51 +0000370 if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000371 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
372 return false;
Eli Friedman04930252008-01-29 07:51:12 +0000373 NewQType = NewAT->getElementType().getCanonicalType();
374 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000375 }
376
377 return NewQType == OldQType;
378}
379
Reid Spencer5f016e22007-07-11 17:01:13 +0000380/// MergeVarDecl - We just parsed a variable 'New' which has the same name
381/// and scope as a previous declaration 'Old'. Figure out how to resolve this
382/// situation, merging decls or emitting diagnostics as appropriate.
383///
384/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
385/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
386///
Steve Naroffe8043c32008-04-01 23:04:06 +0000387VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000388 // Verify the old decl was also a variable.
389 VarDecl *Old = dyn_cast<VarDecl>(OldD);
390 if (!Old) {
391 Diag(New->getLocation(), diag::err_redefinition_different_kind,
392 New->getName());
393 Diag(OldD->getLocation(), diag::err_previous_definition);
394 return New;
395 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000396
397 MergeAttributes(New, Old);
398
Reid Spencer5f016e22007-07-11 17:01:13 +0000399 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000400 QualType OldCType = Context.getCanonicalType(Old->getType());
401 QualType NewCType = Context.getCanonicalType(New->getType());
402 if (OldCType != NewCType && !areEquivalentArrayTypes(NewCType, OldCType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000403 Diag(New->getLocation(), diag::err_redefinition, New->getName());
404 Diag(Old->getLocation(), diag::err_previous_definition);
405 return New;
406 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000407 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
408 if (New->getStorageClass() == VarDecl::Static &&
409 (Old->getStorageClass() == VarDecl::None ||
410 Old->getStorageClass() == VarDecl::Extern)) {
411 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
412 Diag(Old->getLocation(), diag::err_previous_definition);
413 return New;
414 }
415 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
416 if (New->getStorageClass() != VarDecl::Static &&
417 Old->getStorageClass() == VarDecl::Static) {
418 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
419 Diag(Old->getLocation(), diag::err_previous_definition);
420 return New;
421 }
422 // We've verified the types match, now handle "tentative" definitions.
Steve Naroff248a7532008-04-15 22:42:06 +0000423 if (Old->isFileVarDecl() && New->isFileVarDecl()) {
Steve Naroffb7b032e2008-01-30 00:44:01 +0000424 // Handle C "tentative" external object definitions (C99 6.9.2).
425 bool OldIsTentative = false;
426 bool NewIsTentative = false;
427
Steve Naroff248a7532008-04-15 22:42:06 +0000428 if (!Old->getInit() &&
429 (Old->getStorageClass() == VarDecl::None ||
430 Old->getStorageClass() == VarDecl::Static))
Steve Naroffb7b032e2008-01-30 00:44:01 +0000431 OldIsTentative = true;
432
433 // FIXME: this check doesn't work (since the initializer hasn't been
434 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
435 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
436 // thrown out the old decl.
Steve Naroff248a7532008-04-15 22:42:06 +0000437 if (!New->getInit() &&
438 (New->getStorageClass() == VarDecl::None ||
439 New->getStorageClass() == VarDecl::Static))
Steve Naroffb7b032e2008-01-30 00:44:01 +0000440 ; // change to NewIsTentative = true; once the code is moved.
441
442 if (NewIsTentative || OldIsTentative)
443 return New;
444 }
Steve Naroff235549c2008-05-12 22:36:43 +0000445 // Handle __private_extern__ just like extern.
Steve Naroffb7b032e2008-01-30 00:44:01 +0000446 if (Old->getStorageClass() != VarDecl::Extern &&
Steve Naroff235549c2008-05-12 22:36:43 +0000447 Old->getStorageClass() != VarDecl::PrivateExtern &&
448 New->getStorageClass() != VarDecl::Extern &&
449 New->getStorageClass() != VarDecl::PrivateExtern) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000450 Diag(New->getLocation(), diag::err_redefinition, New->getName());
451 Diag(Old->getLocation(), diag::err_previous_definition);
452 }
453 return New;
454}
455
Chris Lattner04421082008-04-08 04:40:51 +0000456/// CheckParmsForFunctionDef - Check that the parameters of the given
457/// function are appropriate for the definition of a function. This
458/// takes care of any checks that cannot be performed on the
459/// declaration itself, e.g., that the types of each of the function
460/// parameters are complete.
461bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
462 bool HasInvalidParm = false;
463 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
464 ParmVarDecl *Param = FD->getParamDecl(p);
465
466 // C99 6.7.5.3p4: the parameters in a parameter type list in a
467 // function declarator that is part of a function definition of
468 // that function shall not have incomplete type.
469 if (Param->getType()->isIncompleteType() &&
470 !Param->isInvalidDecl()) {
471 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
472 Param->getType().getAsString());
473 Param->setInvalidDecl();
474 HasInvalidParm = true;
475 }
476 }
477
478 return HasInvalidParm;
479}
480
481/// CreateImplicitParameter - Creates an implicit function parameter
482/// in the scope S and with the given type. This routine is used, for
483/// example, to create the implicit "self" parameter in an Objective-C
484/// method.
485ParmVarDecl *
486Sema::CreateImplicitParameter(Scope *S, IdentifierInfo *Id,
487 SourceLocation IdLoc, QualType Type) {
488 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, IdLoc, Id, Type,
489 VarDecl::None, 0, 0);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000490 if (Id)
491 PushOnScopeChains(New, S);
Chris Lattner04421082008-04-08 04:40:51 +0000492
493 return New;
494}
495
Reid Spencer5f016e22007-07-11 17:01:13 +0000496/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
497/// no declarator (e.g. "struct foo;") is parsed.
498Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
499 // TODO: emit error on 'int;' or 'const enum foo;'.
500 // TODO: emit error on 'typedef int;'
501 // if (!DS.isMissingDeclaratorOk()) Diag(...);
502
Steve Naroff92199282007-11-17 21:37:36 +0000503 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000504}
505
Steve Naroffd0091aa2008-01-10 22:15:12 +0000506bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000507 // Get the type before calling CheckSingleAssignmentConstraints(), since
508 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000509 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000510
Chris Lattner5cf216b2008-01-04 18:04:52 +0000511 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
512 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
513 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000514}
515
Steve Naroff9e8925e2007-09-04 14:36:54 +0000516bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
Steve Naroffd0091aa2008-01-10 22:15:12 +0000517 QualType ElementType) {
Chris Lattner33b7b062007-12-11 23:15:04 +0000518 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroffd0091aa2008-01-10 22:15:12 +0000519 if (CheckSingleInitializer(expr, ElementType))
Chris Lattner33b7b062007-12-11 23:15:04 +0000520 return true; // types weren't compatible.
521
Steve Naroff9e8925e2007-09-04 14:36:54 +0000522 if (savExpr != expr) // The type was promoted, update initializer list.
523 IList->setInit(slot, expr);
Steve Naroff371227d2007-09-04 02:20:04 +0000524 return false;
525}
526
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000527bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Eli Friedmanc5773c42008-02-15 18:16:39 +0000528 if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000529 // C99 6.7.8p14. We have an array of character type with unknown size
530 // being initialized to a string literal.
531 llvm::APSInt ConstVal(32);
532 ConstVal = strLiteral->getByteLength() + 1;
533 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000534 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000535 ArrayType::Normal, 0);
536 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
537 // C99 6.7.8p14. We have an array of character type with known size.
538 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
539 Diag(strLiteral->getSourceRange().getBegin(),
540 diag::warn_initializer_string_for_char_array_too_long,
541 strLiteral->getSourceRange());
542 } else {
543 assert(0 && "HandleStringLiteralInit(): Invalid array type");
544 }
545 // Set type from "char *" to "constant array of char".
546 strLiteral->setType(DeclT);
547 // For now, we always return false (meaning success).
548 return false;
549}
550
551StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000552 const ArrayType *AT = DeclType->getAsArrayType();
Steve Naroffa9960332008-01-25 00:51:06 +0000553 if (AT && AT->getElementType()->isCharType()) {
554 return dyn_cast<StringLiteral>(Init);
555 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000556 return 0;
557}
558
Steve Naroffa9960332008-01-25 00:51:06 +0000559// CheckInitializerListTypes - Checks the types of elements of an initializer
560// list. This function is recursive: it calls itself to initialize subelements
561// of aggregate types. Note that the topLevel parameter essentially refers to
562// whether this expression "owns" the initializer list passed in, or if this
563// initialization is taking elements out of a parent initializer. Each
564// call to this function adds zero or more to startIndex, reports any errors,
565// and returns true if it found any inconsistent types.
566bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
567 bool topLevel, unsigned& startIndex) {
Steve Naroff2fdc3742007-12-10 22:44:33 +0000568 bool hadError = false;
Steve Naroffa9960332008-01-25 00:51:06 +0000569
570 if (DeclType->isScalarType()) {
571 // The simplest case: initializing a single scalar
572 if (topLevel) {
573 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
574 IList->getSourceRange());
575 }
576 if (startIndex < IList->getNumInits()) {
577 Expr* expr = IList->getInit(startIndex);
578 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
579 // FIXME: Should an error be reported here instead?
580 unsigned newIndex = 0;
581 CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
582 } else {
583 hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
584 }
585 ++startIndex;
586 }
587 // FIXME: Should an error be reported for empty initializer list + scalar?
588 } else if (DeclType->isVectorType()) {
589 if (startIndex < IList->getNumInits()) {
590 const VectorType *VT = DeclType->getAsVectorType();
591 int maxElements = VT->getNumElements();
592 QualType elementType = VT->getElementType();
593
594 for (int i = 0; i < maxElements; ++i) {
595 // Don't attempt to go past the end of the init list
596 if (startIndex >= IList->getNumInits())
597 break;
598 Expr* expr = IList->getInit(startIndex);
599 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
600 unsigned newIndex = 0;
601 hadError |= CheckInitializerListTypes(SubInitList, elementType,
602 true, newIndex);
603 ++startIndex;
604 } else {
605 hadError |= CheckInitializerListTypes(IList, elementType,
606 false, startIndex);
607 }
608 }
609 }
610 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
611 if (DeclType->isStructureType() || DeclType->isUnionType()) {
Steve Naroff578edc62008-01-28 02:00:41 +0000612 if (startIndex < IList->getNumInits() && !topLevel &&
613 Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
614 DeclType)) {
Steve Naroffa9960332008-01-25 00:51:06 +0000615 // We found a compatible struct; per the standard, this initializes the
616 // struct. (The C standard technically says that this only applies for
617 // initializers for declarations with automatic scope; however, this
618 // construct is unambiguous anyway because a struct cannot contain
619 // a type compatible with itself. We'll output an error when we check
620 // if the initializer is constant.)
621 // FIXME: Is a call to CheckSingleInitializer required here?
622 ++startIndex;
623 } else {
624 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffb43eaa52008-02-11 00:06:17 +0000625
Steve Naroff406db932008-02-11 21:52:37 +0000626 // If the record is invalid, some of it's members are invalid. To avoid
627 // confusion, we forgo checking the intializer for the entire record.
Steve Naroffb43eaa52008-02-11 00:06:17 +0000628 if (structDecl->isInvalidDecl())
629 return true;
630
Steve Naroffa9960332008-01-25 00:51:06 +0000631 // If structDecl is a forward declaration, this loop won't do anything;
632 // That's okay, because an error should get printed out elsewhere. It
633 // might be worthwhile to skip over the rest of the initializer, though.
634 int numMembers = structDecl->getNumMembers() -
635 structDecl->hasFlexibleArrayMember();
636 for (int i = 0; i < numMembers; i++) {
637 // Don't attempt to go past the end of the init list
638 if (startIndex >= IList->getNumInits())
639 break;
640 FieldDecl * curField = structDecl->getMember(i);
641 if (!curField->getIdentifier()) {
642 // Don't initialize unnamed fields, e.g. "int : 20;"
643 continue;
644 }
645 QualType fieldType = curField->getType();
646 Expr* expr = IList->getInit(startIndex);
647 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
648 unsigned newStart = 0;
649 hadError |= CheckInitializerListTypes(SubInitList, fieldType,
650 true, newStart);
651 ++startIndex;
652 } else {
653 hadError |= CheckInitializerListTypes(IList, fieldType,
654 false, startIndex);
655 }
656 if (DeclType->isUnionType())
657 break;
658 }
659 // FIXME: Implement flexible array initialization GCC extension (it's a
660 // really messy extension to implement, unfortunately...the necessary
661 // information isn't actually even here!)
662 }
663 } else if (DeclType->isArrayType()) {
664 // Check for the special-case of initializing an array with a string.
665 if (startIndex < IList->getNumInits()) {
666 if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
667 DeclType)) {
668 CheckStringLiteralInit(lit, DeclType);
669 ++startIndex;
670 if (topLevel && startIndex < IList->getNumInits()) {
671 // We have leftover initializers; warn
672 Diag(IList->getInit(startIndex)->getLocStart(),
673 diag::err_excess_initializers_in_char_array_initializer,
674 IList->getInit(startIndex)->getSourceRange());
675 }
676 return false;
677 }
678 }
679 int maxElements;
Eli Friedmanc5773c42008-02-15 18:16:39 +0000680 if (DeclType->isIncompleteArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000681 // FIXME: use a proper constant
682 maxElements = 0x7FFFFFFF;
Chris Lattner212839c2008-02-20 23:17:35 +0000683 } else if (const VariableArrayType *VAT =
684 DeclType->getAsVariableArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000685 // Check for VLAs; in standard C it would be possible to check this
686 // earlier, but I don't know where clang accepts VLAs (gcc accepts
687 // them in all sorts of strange places).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000688 Diag(VAT->getSizeExpr()->getLocStart(),
689 diag::err_variable_object_no_init,
690 VAT->getSizeExpr()->getSourceRange());
691 hadError = true;
692 maxElements = 0x7FFFFFFF;
Steve Naroffa9960332008-01-25 00:51:06 +0000693 } else {
694 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
695 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
696 }
697 QualType elementType = DeclType->getAsArrayType()->getElementType();
698 int numElements = 0;
699 for (int i = 0; i < maxElements; ++i, ++numElements) {
700 // Don't attempt to go past the end of the init list
701 if (startIndex >= IList->getNumInits())
702 break;
703 Expr* expr = IList->getInit(startIndex);
704 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
705 unsigned newIndex = 0;
706 hadError |= CheckInitializerListTypes(SubInitList, elementType,
707 true, newIndex);
708 ++startIndex;
709 } else {
710 hadError |= CheckInitializerListTypes(IList, elementType,
711 false, startIndex);
712 }
713 }
Eli Friedman9db13972008-02-15 12:53:51 +0000714 if (DeclType->isIncompleteArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000715 // If this is an incomplete array type, the actual type needs to
716 // be calculated here
717 if (numElements == 0) {
718 // Sizing an array implicitly to zero is not allowed
719 // (It could in theory be allowed, but it doesn't really matter.)
720 Diag(IList->getLocStart(),
721 diag::err_at_least_one_initializer_needed_to_size_array);
722 hadError = true;
723 } else {
724 llvm::APSInt ConstVal(32);
725 ConstVal = numElements;
726 DeclType = Context.getConstantArrayType(elementType, ConstVal,
727 ArrayType::Normal, 0);
728 }
729 }
730 } else {
731 assert(0 && "Aggregate that isn't a function or array?!");
732 }
733 } else {
734 // In C, all types are either scalars or aggregates, but
735 // additional handling is needed here for C++ (and possibly others?).
736 assert(0 && "Unsupported initializer type");
737 }
738
739 // If this init list is a base list, we set the type; an initializer doesn't
740 // fundamentally have a type, but this makes the ASTs a bit easier to read
741 if (topLevel)
742 IList->setType(DeclType);
743
744 if (topLevel && startIndex < IList->getNumInits()) {
745 // We have leftover initializers; warn
746 Diag(IList->getInit(startIndex)->getLocStart(),
747 diag::warn_excess_initializers,
748 IList->getInit(startIndex)->getSourceRange());
749 }
750 return hadError;
751}
752
753bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffca107302008-01-21 23:53:58 +0000754 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
755 // of unknown size ("[]") or an object type that is not a variable array type.
Eli Friedmanc5773c42008-02-15 18:16:39 +0000756 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
Steve Naroffca107302008-01-21 23:53:58 +0000757 return Diag(VAT->getSizeExpr()->getLocStart(),
758 diag::err_variable_object_no_init,
759 VAT->getSizeExpr()->getSourceRange());
760
Steve Naroff2fdc3742007-12-10 22:44:33 +0000761 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
762 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000763 // FIXME: Handle wide strings
764 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
765 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000766
767 if (DeclType->isArrayType())
768 return Diag(Init->getLocStart(),
769 diag::err_array_init_list_required,
770 Init->getSourceRange());
771
Steve Naroffd0091aa2008-01-10 22:15:12 +0000772 return CheckSingleInitializer(Init, DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000773 }
Eli Friedmanc56c9772008-05-19 20:29:35 +0000774#if 0
Steve Naroffa9960332008-01-25 00:51:06 +0000775 unsigned newIndex = 0;
776 return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000777#else
778 InitListChecker CheckInitList(this, InitList, DeclType);
779 return CheckInitList.HadError();
780#endif
Steve Narofff0090632007-09-02 02:04:30 +0000781}
782
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000783Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000784Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000785 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000786 IdentifierInfo *II = D.getIdentifier();
787
Chris Lattnere80a59c2007-07-25 00:24:17 +0000788 // All of these full declarators require an identifier. If it doesn't have
789 // one, the ParsedFreeStandingDeclSpec action should be used.
790 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000791 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000792 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000793 D.getDeclSpec().getSourceRange(), D.getSourceRange());
794 return 0;
795 }
796
Chris Lattner31e05722007-08-26 06:24:45 +0000797 // The scope passed in may not be a decl scope. Zip up the scope tree until
798 // we find one that is.
799 while ((S->getFlags() & Scope::DeclScope) == 0)
800 S = S->getParent();
801
Reid Spencer5f016e22007-07-11 17:01:13 +0000802 // See if this is a redefinition of a variable in the same scope.
Steve Naroffb327ce02008-04-02 14:35:35 +0000803 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffc752d042007-09-13 18:10:37 +0000804 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000805 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000806
807 // In C++, the previous declaration we find might be a tag type
808 // (class or enum). In this case, the new declaration will hide the
809 // tag type.
810 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
811 PrevDecl = 0;
812
Chris Lattner41af0932007-11-14 06:34:38 +0000813 QualType R = GetTypeForDeclarator(D, S);
814 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
815
Reid Spencer5f016e22007-07-11 17:01:13 +0000816 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000817 // Check that there are no default arguments (C++ only).
818 if (getLangOptions().CPlusPlus)
819 CheckExtraCXXDefaultArguments(D);
820
Chris Lattner41af0932007-11-14 06:34:38 +0000821 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000822 if (!NewTD) return 0;
823
824 // Handle attributes prior to checking for duplicates in MergeVarDecl
825 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
826 D.getAttributes());
Steve Naroffffce4d52008-01-09 23:34:55 +0000827 // Merge the decl with the existing one if appropriate. If the decl is
828 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000829 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000830 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
831 if (NewTD == 0) return 0;
832 }
833 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000834 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000835 // C99 6.7.7p2: If a typedef name specifies a variably modified type
836 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000837 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
838 // FIXME: Diagnostic needs to be fixed.
839 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000840 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000841 }
842 }
Chris Lattner41af0932007-11-14 06:34:38 +0000843 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000844 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000845 switch (D.getDeclSpec().getStorageClassSpec()) {
846 default: assert(0 && "Unknown storage class!");
847 case DeclSpec::SCS_auto:
848 case DeclSpec::SCS_register:
849 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
850 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000851 InvalidDecl = true;
852 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000853 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
854 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
855 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000856 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000857 }
858
Chris Lattnera98e58d2008-03-15 21:24:04 +0000859 bool isInline = D.getDeclSpec().isInlineSpecified();
Chris Lattner0ed844b2008-04-04 06:12:32 +0000860 FunctionDecl *NewFD = FunctionDecl::Create(Context, CurContext,
861 D.getIdentifierLoc(),
Chris Lattnera98e58d2008-03-15 21:24:04 +0000862 II, R, SC, isInline,
863 LastDeclarator);
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000864 // Handle attributes.
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000865 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
866 D.getAttributes());
Chris Lattner04421082008-04-08 04:40:51 +0000867
868 // Copy the parameter declarations from the declarator D to
869 // the function declaration NewFD, if they are available.
870 if (D.getNumTypeObjects() > 0 &&
871 D.getTypeObject(0).Fun.hasPrototype) {
872 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
873
874 // Create Decl objects for each parameter, adding them to the
875 // FunctionDecl.
876 llvm::SmallVector<ParmVarDecl*, 16> Params;
877
878 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
879 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +0000880 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000881 // We let through "const void" here because Sema::GetTypeForDeclarator
882 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +0000883 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
884 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +0000885 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
886 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +0000887 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
888
Chris Lattnerdef026a2008-04-10 02:26:16 +0000889 // In C++, the empty parameter-type-list must be spelled "void"; a
890 // typedef of void is not permitted.
891 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000892 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +0000893 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
894 }
895
Chris Lattner04421082008-04-08 04:40:51 +0000896 } else {
897 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
898 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
899 }
900
901 NewFD->setParams(&Params[0], Params.size());
902 }
903
Steve Naroffffce4d52008-01-09 23:34:55 +0000904 // Merge the decl with the existing one if appropriate. Since C functions
905 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000906 if (PrevDecl &&
907 (!getLangOptions().CPlusPlus ||
908 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) ) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000909 bool Redeclaration = false;
910 NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration);
Reid Spencer5f016e22007-07-11 17:01:13 +0000911 if (NewFD == 0) return 0;
Douglas Gregorf0097952008-04-21 02:02:58 +0000912 if (Redeclaration) {
Eli Friedman27424962008-05-27 05:07:37 +0000913 NewFD->setPreviousDeclaration(cast<FunctionDecl>(PrevDecl));
Douglas Gregorf0097952008-04-21 02:02:58 +0000914 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000915 }
916 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +0000917
918 // In C++, check default arguments now that we have merged decls.
919 if (getLangOptions().CPlusPlus)
920 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000921 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000922 // Check that there are no default arguments (C++ only).
923 if (getLangOptions().CPlusPlus)
924 CheckExtraCXXDefaultArguments(D);
925
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000926 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +0000927 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
928 D.getIdentifier()->getName());
929 InvalidDecl = true;
930 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000931
932 VarDecl *NewVD;
933 VarDecl::StorageClass SC;
934 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +0000935 default: assert(0 && "Unknown storage class!");
936 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
937 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
938 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
939 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
940 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
941 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000942 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000943 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000944 // C99 6.9p2: The storage-class specifiers auto and register shall not
945 // appear in the declaration specifiers in an external declaration.
946 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
947 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
948 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000949 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000950 }
Steve Naroff248a7532008-04-15 22:42:06 +0000951 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
952 II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000953 } else {
Steve Naroff248a7532008-04-15 22:42:06 +0000954 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
955 II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000956 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000957 // Handle attributes prior to checking for duplicates in MergeVarDecl
958 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
959 D.getAttributes());
Nate Begemanc8e89a82008-03-14 18:07:10 +0000960
961 // Emit an error if an address space was applied to decl with local storage.
962 // This includes arrays of objects with address space qualifiers, but not
963 // automatic variables that point to other address spaces.
964 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +0000965 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
966 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
967 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +0000968 }
Steve Naroffffce4d52008-01-09 23:34:55 +0000969 // Merge the decl with the existing one if appropriate. If the decl is
970 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000971 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000972 NewVD = MergeVarDecl(NewVD, PrevDecl);
973 if (NewVD == 0) return 0;
974 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000975 New = NewVD;
976 }
977
978 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000979 if (II)
980 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000981 // If any semantic error occurred, mark the decl as invalid.
982 if (D.getInvalidType() || InvalidDecl)
983 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000984
985 return New;
986}
987
Eli Friedmanc594b322008-05-20 13:48:25 +0000988bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
989 switch (Init->getStmtClass()) {
990 default:
991 Diag(Init->getExprLoc(),
992 diag::err_init_element_not_constant, Init->getSourceRange());
993 return true;
994 case Expr::ParenExprClass: {
995 const ParenExpr* PE = cast<ParenExpr>(Init);
996 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
997 }
998 case Expr::CompoundLiteralExprClass:
999 return cast<CompoundLiteralExpr>(Init)->isFileScope();
1000 case Expr::DeclRefExprClass: {
1001 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001002 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1003 if (VD->hasGlobalStorage())
1004 return false;
1005 Diag(Init->getExprLoc(),
1006 diag::err_init_element_not_constant, Init->getSourceRange());
1007 return true;
1008 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001009 if (isa<FunctionDecl>(D))
1010 return false;
1011 Diag(Init->getExprLoc(),
1012 diag::err_init_element_not_constant, Init->getSourceRange());
Steve Naroffd0091aa2008-01-10 22:15:12 +00001013 return true;
1014 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001015 case Expr::MemberExprClass: {
1016 const MemberExpr *M = cast<MemberExpr>(Init);
1017 if (M->isArrow())
1018 return CheckAddressConstantExpression(M->getBase());
1019 return CheckAddressConstantExpressionLValue(M->getBase());
1020 }
1021 case Expr::ArraySubscriptExprClass: {
1022 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1023 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1024 return CheckAddressConstantExpression(ASE->getBase()) ||
1025 CheckArithmeticConstantExpression(ASE->getIdx());
1026 }
1027 case Expr::StringLiteralClass:
1028 case Expr::PreDefinedExprClass:
1029 return false;
1030 case Expr::UnaryOperatorClass: {
1031 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1032
1033 // C99 6.6p9
1034 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001035 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001036
1037 Diag(Init->getExprLoc(),
1038 diag::err_init_element_not_constant, Init->getSourceRange());
1039 return true;
1040 }
1041 }
1042}
1043
1044bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1045 switch (Init->getStmtClass()) {
1046 default:
1047 Diag(Init->getExprLoc(),
1048 diag::err_init_element_not_constant, Init->getSourceRange());
1049 return true;
1050 case Expr::ParenExprClass: {
1051 const ParenExpr* PE = cast<ParenExpr>(Init);
1052 return CheckAddressConstantExpression(PE->getSubExpr());
1053 }
1054 case Expr::StringLiteralClass:
1055 case Expr::ObjCStringLiteralClass:
1056 return false;
1057 case Expr::CallExprClass: {
1058 const CallExpr *CE = cast<CallExpr>(Init);
1059 if (CE->isBuiltinConstantExpr())
1060 return false;
1061 Diag(Init->getExprLoc(),
1062 diag::err_init_element_not_constant, Init->getSourceRange());
1063 return true;
1064 }
1065 case Expr::UnaryOperatorClass: {
1066 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1067
1068 // C99 6.6p9
1069 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1070 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1071
1072 if (Exp->getOpcode() == UnaryOperator::Extension)
1073 return CheckAddressConstantExpression(Exp->getSubExpr());
1074
1075 Diag(Init->getExprLoc(),
1076 diag::err_init_element_not_constant, Init->getSourceRange());
1077 return true;
1078 }
1079 case Expr::BinaryOperatorClass: {
1080 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1081 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1082
1083 Expr *PExp = Exp->getLHS();
1084 Expr *IExp = Exp->getRHS();
1085 if (IExp->getType()->isPointerType())
1086 std::swap(PExp, IExp);
1087
1088 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1089 return CheckAddressConstantExpression(PExp) ||
1090 CheckArithmeticConstantExpression(IExp);
1091 }
1092 case Expr::ImplicitCastExprClass: {
1093 const Expr* SubExpr = cast<ImplicitCastExpr>(Init)->getSubExpr();
1094
1095 // Check for implicit promotion
1096 if (SubExpr->getType()->isFunctionType() ||
1097 SubExpr->getType()->isArrayType())
1098 return CheckAddressConstantExpressionLValue(SubExpr);
1099
1100 // Check for pointer->pointer cast
1101 if (SubExpr->getType()->isPointerType())
1102 return CheckAddressConstantExpression(SubExpr);
1103
1104 if (SubExpr->getType()->isArithmeticType())
1105 return CheckArithmeticConstantExpression(SubExpr);
1106
1107 Diag(Init->getExprLoc(),
1108 diag::err_init_element_not_constant, Init->getSourceRange());
1109 return true;
1110 }
1111 case Expr::CastExprClass: {
1112 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
1113
1114 // Check for pointer->pointer cast
1115 if (SubExpr->getType()->isPointerType())
1116 return CheckAddressConstantExpression(SubExpr);
1117
1118 // FIXME: Should we pedwarn for (int*)(0+0)?
1119 if (SubExpr->getType()->isArithmeticType())
1120 return CheckArithmeticConstantExpression(SubExpr);
1121
1122 Diag(Init->getExprLoc(),
1123 diag::err_init_element_not_constant, Init->getSourceRange());
1124 return true;
1125 }
1126 case Expr::ConditionalOperatorClass: {
1127 // FIXME: Should we pedwarn here?
1128 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1129 if (!Exp->getCond()->getType()->isArithmeticType()) {
1130 Diag(Init->getExprLoc(),
1131 diag::err_init_element_not_constant, Init->getSourceRange());
1132 return true;
1133 }
1134 if (CheckArithmeticConstantExpression(Exp->getCond()))
1135 return true;
1136 if (Exp->getLHS() &&
1137 CheckAddressConstantExpression(Exp->getLHS()))
1138 return true;
1139 return CheckAddressConstantExpression(Exp->getRHS());
1140 }
1141 case Expr::AddrLabelExprClass:
1142 return false;
1143 }
1144}
1145
1146bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1147 switch (Init->getStmtClass()) {
1148 default:
1149 Diag(Init->getExprLoc(),
1150 diag::err_init_element_not_constant, Init->getSourceRange());
1151 return true;
1152 case Expr::ParenExprClass: {
1153 const ParenExpr* PE = cast<ParenExpr>(Init);
1154 return CheckArithmeticConstantExpression(PE->getSubExpr());
1155 }
1156 case Expr::FloatingLiteralClass:
1157 case Expr::IntegerLiteralClass:
1158 case Expr::CharacterLiteralClass:
1159 case Expr::ImaginaryLiteralClass:
1160 case Expr::TypesCompatibleExprClass:
1161 case Expr::CXXBoolLiteralExprClass:
1162 return false;
1163 case Expr::CallExprClass: {
1164 const CallExpr *CE = cast<CallExpr>(Init);
1165 if (CE->isBuiltinConstantExpr())
1166 return false;
1167 Diag(Init->getExprLoc(),
1168 diag::err_init_element_not_constant, Init->getSourceRange());
1169 return true;
1170 }
1171 case Expr::DeclRefExprClass: {
1172 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1173 if (isa<EnumConstantDecl>(D))
1174 return false;
1175 Diag(Init->getExprLoc(),
1176 diag::err_init_element_not_constant, Init->getSourceRange());
1177 return true;
1178 }
1179 case Expr::CompoundLiteralExprClass:
1180 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1181 // but vectors are allowed to be magic.
1182 if (Init->getType()->isVectorType())
1183 return false;
1184 Diag(Init->getExprLoc(),
1185 diag::err_init_element_not_constant, Init->getSourceRange());
1186 return true;
1187 case Expr::UnaryOperatorClass: {
1188 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1189
1190 switch (Exp->getOpcode()) {
1191 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1192 // See C99 6.6p3.
1193 default:
1194 Diag(Init->getExprLoc(),
1195 diag::err_init_element_not_constant, Init->getSourceRange());
1196 return true;
1197 case UnaryOperator::SizeOf:
1198 case UnaryOperator::AlignOf:
1199 case UnaryOperator::OffsetOf:
1200 // sizeof(E) is a constantexpr if and only if E is not evaluted.
1201 // See C99 6.5.3.4p2 and 6.6p3.
1202 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1203 return false;
1204 Diag(Init->getExprLoc(),
1205 diag::err_init_element_not_constant, Init->getSourceRange());
1206 return true;
1207 case UnaryOperator::Extension:
1208 case UnaryOperator::LNot:
1209 case UnaryOperator::Plus:
1210 case UnaryOperator::Minus:
1211 case UnaryOperator::Not:
1212 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1213 }
1214 }
1215 case Expr::SizeOfAlignOfTypeExprClass: {
1216 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1217 // Special check for void types, which are allowed as an extension
1218 if (Exp->getArgumentType()->isVoidType())
1219 return false;
1220 // alignof always evaluates to a constant.
1221 // FIXME: is sizeof(int[3.0]) a constant expression?
1222 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
1223 Diag(Init->getExprLoc(),
1224 diag::err_init_element_not_constant, Init->getSourceRange());
1225 return true;
1226 }
1227 return false;
1228 }
1229 case Expr::BinaryOperatorClass: {
1230 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1231
1232 if (Exp->getLHS()->getType()->isArithmeticType() &&
1233 Exp->getRHS()->getType()->isArithmeticType()) {
1234 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1235 CheckArithmeticConstantExpression(Exp->getRHS());
1236 }
1237
1238 Diag(Init->getExprLoc(),
1239 diag::err_init_element_not_constant, Init->getSourceRange());
1240 return true;
1241 }
1242 case Expr::ImplicitCastExprClass:
1243 case Expr::CastExprClass: {
1244 const Expr *SubExpr;
1245 if (const CastExpr *C = dyn_cast<CastExpr>(Init)) {
1246 SubExpr = C->getSubExpr();
1247 } else {
1248 SubExpr = cast<ImplicitCastExpr>(Init)->getSubExpr();
1249 }
1250
1251 if (SubExpr->getType()->isArithmeticType())
1252 return CheckArithmeticConstantExpression(SubExpr);
1253
1254 Diag(Init->getExprLoc(),
1255 diag::err_init_element_not_constant, Init->getSourceRange());
1256 return true;
1257 }
1258 case Expr::ConditionalOperatorClass: {
1259 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1260 if (CheckArithmeticConstantExpression(Exp->getCond()))
1261 return true;
1262 if (Exp->getLHS() &&
1263 CheckArithmeticConstantExpression(Exp->getLHS()))
1264 return true;
1265 return CheckArithmeticConstantExpression(Exp->getRHS());
1266 }
1267 }
1268}
1269
1270bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
1271 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1272 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1273 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1274
1275 if (Init->getType()->isReferenceType()) {
1276 // FIXME: Work out how the heck reference types work
1277 return false;
1278#if 0
1279 // A reference is constant if the address of the expression
1280 // is constant
1281 // We look through initlists here to simplify
1282 // CheckAddressConstantExpressionLValue.
1283 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1284 assert(Exp->getNumInits() > 0 &&
1285 "Refernce initializer cannot be empty");
1286 Init = Exp->getInit(0);
1287 }
1288 return CheckAddressConstantExpressionLValue(Init);
1289#endif
1290 }
1291
1292 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1293 unsigned numInits = Exp->getNumInits();
1294 for (unsigned i = 0; i < numInits; i++) {
1295 // FIXME: Need to get the type of the declaration for C++,
1296 // because it could be a reference?
1297 if (CheckForConstantInitializer(Exp->getInit(i),
1298 Exp->getInit(i)->getType()))
1299 return true;
1300 }
1301 return false;
1302 }
1303
1304 if (Init->isNullPointerConstant(Context))
1305 return false;
1306 if (Init->getType()->isArithmeticType()) {
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001307 QualType InitTy = Init->getType().getCanonicalType().getUnqualifiedType();
1308 if (InitTy == Context.BoolTy) {
1309 // Special handling for pointers implicitly cast to bool;
1310 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1311 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1312 Expr* SubE = ICE->getSubExpr();
1313 if (SubE->getType()->isPointerType() ||
1314 SubE->getType()->isArrayType() ||
1315 SubE->getType()->isFunctionType()) {
1316 return CheckAddressConstantExpression(Init);
1317 }
1318 }
1319 } else if (InitTy->isIntegralType()) {
1320 Expr* SubE = 0;
1321 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init))
1322 SubE = ICE->getSubExpr();
1323 else if (CastExpr* CE = dyn_cast<CastExpr>(Init))
1324 SubE = CE->getSubExpr();
1325 // Special check for pointer cast to int; we allow as an extension
1326 // an address constant cast to an integer if the integer
1327 // is of an appropriate width (this sort of code is apparently used
1328 // in some places).
1329 // FIXME: Add pedwarn?
1330 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1331 if (SubE && (SubE->getType()->isPointerType() ||
1332 SubE->getType()->isArrayType() ||
1333 SubE->getType()->isFunctionType())) {
1334 unsigned IntWidth = Context.getTypeSize(Init->getType());
1335 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1336 if (IntWidth >= PointerWidth)
1337 return CheckAddressConstantExpression(Init);
1338 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001339 }
1340
1341 return CheckArithmeticConstantExpression(Init);
1342 }
1343
1344 if (Init->getType()->isPointerType())
1345 return CheckAddressConstantExpression(Init);
1346
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001347 // An array type at the top level that isn't an init-list must
1348 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00001349 if (Init->getType()->isArrayType())
1350 return false;
1351
1352 Diag(Init->getExprLoc(), diag::err_init_element_not_constant,
1353 Init->getSourceRange());
1354 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00001355}
1356
Steve Naroffbb204692007-09-12 14:07:44 +00001357void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001358 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +00001359 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001360 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00001361
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001362 // If there is no declaration, there was an error parsing it. Just ignore
1363 // the initializer.
1364 if (RealDecl == 0) {
1365 delete Init;
1366 return;
1367 }
Steve Naroffbb204692007-09-12 14:07:44 +00001368
Steve Naroff410e3e22007-09-12 20:13:48 +00001369 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1370 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00001371 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1372 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00001373 RealDecl->setInvalidDecl();
1374 return;
1375 }
Steve Naroffbb204692007-09-12 14:07:44 +00001376 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00001377 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00001378 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00001379 if (VDecl->isBlockVarDecl()) {
1380 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00001381 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00001382 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001383 VDecl->setInvalidDecl();
1384 } else if (!VDecl->isInvalidDecl()) {
Steve Naroffa9960332008-01-25 00:51:06 +00001385 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001386 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001387 if (SC == VarDecl::Static) // C99 6.7.8p4.
1388 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +00001389 }
Steve Naroff248a7532008-04-15 22:42:06 +00001390 } else if (VDecl->isFileVarDecl()) {
1391 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00001392 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001393 if (!VDecl->isInvalidDecl())
Steve Naroffa9960332008-01-25 00:51:06 +00001394 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001395 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001396
1397 // C99 6.7.8p4. All file scoped initializers need to be constant.
1398 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +00001399 }
1400 // If the type changed, it means we had an incomplete type that was
1401 // completed by the initializer. For example:
1402 // int ary[] = { 1, 3, 5 };
1403 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00001404 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001405 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00001406 Init->setType(DclT);
1407 }
Steve Naroffbb204692007-09-12 14:07:44 +00001408
1409 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00001410 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00001411 return;
1412}
1413
Reid Spencer5f016e22007-07-11 17:01:13 +00001414/// The declarators are chained together backwards, reverse the list.
1415Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1416 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00001417 Decl *GroupDecl = static_cast<Decl*>(group);
1418 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00001419 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00001420
1421 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1422 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00001423 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00001424 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00001425 else { // reverse the list.
1426 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00001427 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00001428 Group->setNextDeclarator(NewGroup);
1429 NewGroup = Group;
1430 Group = Next;
1431 }
1432 }
1433 // Perform semantic analysis that depends on having fully processed both
1434 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00001435 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001436 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1437 if (!IDecl)
1438 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00001439 QualType T = IDecl->getType();
1440
1441 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1442 // static storage duration, it shall not have a variable length array.
Steve Naroff248a7532008-04-15 22:42:06 +00001443 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1444 IDecl->getStorageClass() == VarDecl::Static) {
Eli Friedman3fe02932008-02-15 19:53:52 +00001445 if (T->getAsVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001446 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1447 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00001448 }
1449 }
1450 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1451 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00001452 if (IDecl->isBlockVarDecl() &&
1453 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001454 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +00001455 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1456 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001457 IDecl->setInvalidDecl();
1458 }
1459 }
1460 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1461 // object that has file scope without an initializer, and without a
1462 // storage-class specifier or with the storage-class specifier "static",
1463 // constitutes a tentative definition. Note: A tentative definition with
1464 // external linkage is valid (C99 6.2.2p5).
Steve Naroff248a7532008-04-15 22:42:06 +00001465 if (IDecl && !IDecl->getInit() &&
1466 (IDecl->getStorageClass() == VarDecl::Static ||
1467 IDecl->getStorageClass() == VarDecl::None)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001468 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001469 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1470 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001471 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001472 // C99 6.9.2p3: If the declaration of an identifier for an object is
1473 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1474 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +00001475 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1476 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001477 IDecl->setInvalidDecl();
1478 }
1479 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001480 }
1481 return NewGroup;
1482}
Steve Naroffe1223f72007-08-28 03:03:08 +00001483
Chris Lattner04421082008-04-08 04:40:51 +00001484/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1485/// to introduce parameters into function prototype scope.
1486Sema::DeclTy *
1487Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
1488 DeclSpec &DS = D.getDeclSpec();
1489
1490 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1491 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1492 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1493 Diag(DS.getStorageClassSpecLoc(),
1494 diag::err_invalid_storage_class_in_func_decl);
1495 DS.ClearStorageClassSpecs();
1496 }
1497 if (DS.isThreadSpecified()) {
1498 Diag(DS.getThreadSpecLoc(),
1499 diag::err_invalid_storage_class_in_func_decl);
1500 DS.ClearStorageClassSpecs();
1501 }
1502
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001503 // Check that there are no default arguments inside the type of this
1504 // parameter (C++ only).
1505 if (getLangOptions().CPlusPlus)
1506 CheckExtraCXXDefaultArguments(D);
1507
Chris Lattner04421082008-04-08 04:40:51 +00001508 // In this context, we *do not* check D.getInvalidType(). If the declarator
1509 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1510 // though it will not reflect the user specified type.
1511 QualType parmDeclType = GetTypeForDeclarator(D, S);
1512
1513 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1514
Reid Spencer5f016e22007-07-11 17:01:13 +00001515 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1516 // Can this happen for params? We already checked that they don't conflict
1517 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00001518 IdentifierInfo *II = D.getIdentifier();
1519 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1520 if (S->isDeclScope(PrevDecl)) {
1521 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1522 dyn_cast<NamedDecl>(PrevDecl)->getName());
1523
1524 // Recover by removing the name
1525 II = 0;
1526 D.SetIdentifier(0, D.getIdentifierLoc());
1527 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001528 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001529
1530 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1531 // Doing the promotion here has a win and a loss. The win is the type for
1532 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1533 // code generator). The loss is the orginal type isn't preserved. For example:
1534 //
1535 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1536 // int blockvardecl[5];
1537 // sizeof(parmvardecl); // size == 4
1538 // sizeof(blockvardecl); // size == 20
1539 // }
1540 //
1541 // For expressions, all implicit conversions are captured using the
1542 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1543 //
1544 // FIXME: If a source translation tool needs to see the original type, then
1545 // we need to consider storing both types (in ParmVarDecl)...
1546 //
Chris Lattnere6327742008-04-02 05:18:44 +00001547 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00001548 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00001549 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00001550 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001551 parmDeclType = Context.getPointerType(parmDeclType);
1552
Chris Lattner04421082008-04-08 04:40:51 +00001553 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1554 D.getIdentifierLoc(), II,
1555 parmDeclType, VarDecl::None,
1556 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001557
Chris Lattner04421082008-04-08 04:40:51 +00001558 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00001559 New->setInvalidDecl();
1560
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001561 if (II)
1562 PushOnScopeChains(New, S);
Nate Begemanb7894b52008-02-17 21:20:31 +00001563
Nate Begemanfc584522008-05-09 16:56:01 +00001564 HandleDeclAttributes(New, D.getDeclSpec().getAttributes(),
1565 D.getAttributes());
Reid Spencer5f016e22007-07-11 17:01:13 +00001566 return New;
Chris Lattner04421082008-04-08 04:40:51 +00001567
Reid Spencer5f016e22007-07-11 17:01:13 +00001568}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001569
Chris Lattnerb652cea2007-10-09 17:14:05 +00001570Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001571 assert(CurFunctionDecl == 0 && "Function parsing confused");
1572 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1573 "Not a function declarator!");
1574 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00001575
Reid Spencer5f016e22007-07-11 17:01:13 +00001576 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1577 // for a K&R function.
1578 if (!FTI.hasPrototype) {
1579 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00001580 if (FTI.ArgInfo[i].Param == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001581 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1582 FTI.ArgInfo[i].Ident->getName());
1583 // Implicitly declare the argument as type 'int' for lack of a better
1584 // type.
Chris Lattner04421082008-04-08 04:40:51 +00001585 DeclSpec DS;
1586 const char* PrevSpec; // unused
1587 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1588 PrevSpec);
1589 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1590 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1591 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001592 }
1593 }
Chris Lattner52804082008-02-17 19:31:09 +00001594
Reid Spencer5f016e22007-07-11 17:01:13 +00001595 // Since this is a function definition, act as though we have information
1596 // about the arguments.
Chris Lattner52804082008-02-17 19:31:09 +00001597 if (FTI.NumArgs)
1598 FTI.hasPrototype = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001599 } else {
Chris Lattner04421082008-04-08 04:40:51 +00001600 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00001601 }
1602
1603 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001604
1605 // See if this is a redefinition.
Steve Naroffe8043c32008-04-01 23:04:06 +00001606 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroffb327ce02008-04-02 14:35:35 +00001607 GlobalScope);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001608 if (PrevDcl && IdResolver.isDeclInScope(PrevDcl, CurContext)) {
1609 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) {
1610 const FunctionDecl *Definition;
1611 if (FD->getBody(Definition)) {
1612 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1613 D.getIdentifier()->getName());
1614 Diag(Definition->getLocation(), diag::err_previous_definition);
1615 }
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001616 }
1617 }
Steve Narofffabbc342008-02-12 01:09:36 +00001618 Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattnere9ba3232008-02-16 01:20:36 +00001619 FunctionDecl *FD = cast<FunctionDecl>(decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001620 CurFunctionDecl = FD;
Chris Lattnerb048c982008-04-06 04:47:34 +00001621 PushDeclContext(FD);
Chris Lattner04421082008-04-08 04:40:51 +00001622
1623 // Check the validity of our function parameters
1624 CheckParmsForFunctionDef(FD);
1625
1626 // Introduce our parameters into the function scope
1627 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1628 ParmVarDecl *Param = FD->getParamDecl(p);
1629 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001630 if (Param->getIdentifier())
1631 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00001632 }
Chris Lattner04421082008-04-08 04:40:51 +00001633
Reid Spencer5f016e22007-07-11 17:01:13 +00001634 return FD;
1635}
1636
Steve Naroffd6d054d2007-11-11 23:20:51 +00001637Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1638 Decl *dcl = static_cast<Decl *>(D);
1639 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1640 FD->setBody((Stmt*)Body);
1641 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff4d832202007-12-13 18:18:56 +00001642 CurFunctionDecl = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001643 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001644 MD->setBody((Stmt*)Body);
Steve Naroff03300712007-11-12 13:56:41 +00001645 CurMethodDecl = 0;
Steve Naroff4d832202007-12-13 18:18:56 +00001646 }
Chris Lattnerb048c982008-04-06 04:47:34 +00001647 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00001648 // Verify and clean out per-function state.
1649
1650 // Check goto/label use.
1651 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1652 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1653 // Verify that we have no forward references left. If so, there was a goto
1654 // or address of a label taken, but no definition of it. Label fwd
1655 // definitions are indicated with a null substmt.
1656 if (I->second->getSubStmt() == 0) {
1657 LabelStmt *L = I->second;
1658 // Emit error.
1659 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1660
1661 // At this point, we have gotos that use the bogus label. Stitch it into
1662 // the function body so that they aren't leaked and that the AST is well
1663 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001664 if (Body) {
1665 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1666 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1667 } else {
1668 // The whole function wasn't parsed correctly, just delete this.
1669 delete L;
1670 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001671 }
1672 }
1673 LabelMap.clear();
1674
Steve Naroffd6d054d2007-11-11 23:20:51 +00001675 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001676}
1677
Reid Spencer5f016e22007-07-11 17:01:13 +00001678/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1679/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001680ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1681 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00001682 // Extension in C99. Legal in C90, but warn about it.
1683 if (getLangOptions().C99)
Reid Spencer5f016e22007-07-11 17:01:13 +00001684 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattner37d10842008-05-05 21:18:06 +00001685 else
Reid Spencer5f016e22007-07-11 17:01:13 +00001686 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1687
1688 // FIXME: handle stuff like:
1689 // void foo() { extern float X(); }
1690 // void bar() { X(); } <-- implicit decl for X in another scope.
1691
1692 // Set a Declarator for the implicit definition: int foo();
1693 const char *Dummy;
1694 DeclSpec DS;
1695 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1696 Error = Error; // Silence warning.
1697 assert(!Error && "Error setting up implicit decl!");
1698 Declarator D(DS, Declarator::BlockContext);
1699 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1700 D.SetIdentifier(&II, Loc);
1701
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001702 // Insert this function into translation-unit scope.
1703
1704 DeclContext *PrevDC = CurContext;
1705 CurContext = Context.getTranslationUnitDecl();
1706
Steve Naroffe2ef8152008-04-04 14:32:09 +00001707 FunctionDecl *FD =
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001708 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00001709 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001710
1711 CurContext = PrevDC;
1712
Steve Naroffe2ef8152008-04-04 14:32:09 +00001713 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001714}
1715
1716
Chris Lattner41af0932007-11-14 06:34:38 +00001717TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001718 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001719 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001720 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001721
1722 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001723 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1724 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001725 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001726 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00001727 if (D.getInvalidType())
1728 NewTD->setInvalidDecl();
1729 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001730}
1731
Steve Naroff08d92e42007-09-15 18:49:24 +00001732/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001733/// former case, Name will be non-null. In the later case, Name will be null.
1734/// TagType indicates what kind of tag this is. TK indicates whether this is a
1735/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001736Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001737 SourceLocation KWLoc, IdentifierInfo *Name,
1738 SourceLocation NameLoc, AttributeList *Attr) {
1739 // If this is a use of an existing tag, it must have a name.
1740 assert((Name != 0 || TK == TK_Definition) &&
1741 "Nameless record must be a definition!");
1742
1743 Decl::Kind Kind;
1744 switch (TagType) {
1745 default: assert(0 && "Unknown tag type!");
1746 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1747 case DeclSpec::TST_union: Kind = Decl::Union; break;
Chris Lattner99dc9142008-04-13 18:59:07 +00001748 case DeclSpec::TST_class: Kind = Decl::Class; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001749 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1750 }
1751
1752 // If this is a named struct, check to see if there was a previous forward
1753 // declaration or definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001754 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
1755 if (ScopedDecl *PrevDecl =
1756 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001757
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001758 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1759 "unexpected Decl type");
1760 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
1761 // If this is a use of a previous tag, or if the tag is already declared in
1762 // the same scope (so that the definition/declaration completes or
1763 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001764 if (TK == TK_Reference ||
1765 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001766 // Make sure that this wasn't declared as an enum and now used as a struct
1767 // or something similar.
1768 if (PrevDecl->getKind() != Kind) {
1769 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1770 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1771 }
1772
1773 // If this is a use or a forward declaration, we're good.
1774 if (TK != TK_Definition)
1775 return PrevDecl;
Reid Spencer5f016e22007-07-11 17:01:13 +00001776
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001777 // Diagnose attempts to redefine a tag.
1778 if (PrevTagDecl->isDefinition()) {
1779 Diag(NameLoc, diag::err_redefinition, Name->getName());
1780 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1781 // If this is a redefinition, recover by making this struct be
1782 // anonymous, which will make any later references get the previous
1783 // definition.
1784 Name = 0;
1785 } else {
1786 // Okay, this is definition of a previously declared or referenced tag.
1787 // Move the location of the decl to be the definition site.
1788 PrevDecl->setLocation(NameLoc);
1789 return PrevDecl;
1790 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001791 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001792 // If we get here, this is a definition of a new struct type in a nested
1793 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1794 // type.
1795 } else {
1796 // The tag name clashes with a namespace name, issue an error and recover
1797 // by making this tag be anonymous.
1798 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1799 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1800 Name = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001801 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001802 }
1803
1804 // If there is an identifier, use the location of the identifier as the
1805 // location of the decl, otherwise use the location of the struct/union
1806 // keyword.
1807 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1808
1809 // Otherwise, if this is the first time we've seen this tag, create the decl.
1810 TagDecl *New;
1811 switch (Kind) {
1812 default: assert(0 && "Unknown tag kind!");
1813 case Decl::Enum:
1814 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1815 // enum X { A, B, C } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001816 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001817 // If this is an undefined enum, warn.
1818 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1819 break;
1820 case Decl::Union:
1821 case Decl::Struct:
1822 case Decl::Class:
1823 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1824 // struct X { int A; } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001825 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001826 break;
1827 }
1828
1829 // If this has an identifier, add it to the scope stack.
1830 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001831 // The scope passed in may not be a decl scope. Zip up the scope tree until
1832 // we find one that is.
1833 while ((S->getFlags() & Scope::DeclScope) == 0)
1834 S = S->getParent();
1835
1836 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001837 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001838 }
Chris Lattnere1e79852008-02-06 00:51:33 +00001839
Anders Carlssonad148062008-02-16 00:29:18 +00001840 HandleDeclAttributes(New, Attr, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001841 return New;
1842}
1843
Steve Naroff08d92e42007-09-15 18:49:24 +00001844/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001845/// to create a FieldDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001846Sema::DeclTy *Sema::ActOnField(Scope *S,
Reid Spencer5f016e22007-07-11 17:01:13 +00001847 SourceLocation DeclStart,
1848 Declarator &D, ExprTy *BitfieldWidth) {
1849 IdentifierInfo *II = D.getIdentifier();
1850 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001851 SourceLocation Loc = DeclStart;
1852 if (II) Loc = D.getIdentifierLoc();
1853
1854 // FIXME: Unnamed fields can be handled in various different ways, for
1855 // example, unnamed unions inject all members into the struct namespace!
1856
1857
1858 if (BitWidth) {
1859 // TODO: Validate.
1860 //printf("WARNING: BITFIELDS IGNORED!\n");
1861
1862 // 6.7.2.1p3
1863 // 6.7.2.1p4
1864
1865 } else {
1866 // Not a bitfield.
1867
1868 // validate II.
1869
1870 }
1871
1872 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001873 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1874 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001875
Reid Spencer5f016e22007-07-11 17:01:13 +00001876 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1877 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00001878 if (T->isVariablyModifiedType()) {
1879 // FIXME: This diagnostic needs work
1880 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
Steve Naroffd7444aa2007-08-31 17:20:07 +00001881 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001882 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001883 // FIXME: Chain fielddecls together.
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001884 FieldDecl *NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff44739212007-09-11 21:17:26 +00001885
Anders Carlssonad148062008-02-16 00:29:18 +00001886 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1887 D.getAttributes());
1888
Steve Naroff5912a352007-08-28 20:14:24 +00001889 if (D.getInvalidType() || InvalidDecl)
1890 NewFD->setInvalidDecl();
1891 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001892}
1893
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001894/// TranslateIvarVisibility - Translate visibility from a token ID to an
1895/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001896static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001897TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001898 switch (ivarVisibility) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001899 case tok::objc_private: return ObjCIvarDecl::Private;
1900 case tok::objc_public: return ObjCIvarDecl::Public;
1901 case tok::objc_protected: return ObjCIvarDecl::Protected;
1902 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001903 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001904 }
1905}
1906
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001907/// ActOnIvar - Each ivar field of an objective-c class is passed into this
1908/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001909Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001910 SourceLocation DeclStart,
1911 Declarator &D, ExprTy *BitfieldWidth,
1912 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001913 IdentifierInfo *II = D.getIdentifier();
1914 Expr *BitWidth = (Expr*)BitfieldWidth;
1915 SourceLocation Loc = DeclStart;
1916 if (II) Loc = D.getIdentifierLoc();
1917
1918 // FIXME: Unnamed fields can be handled in various different ways, for
1919 // example, unnamed unions inject all members into the struct namespace!
1920
1921
1922 if (BitWidth) {
1923 // TODO: Validate.
1924 //printf("WARNING: BITFIELDS IGNORED!\n");
1925
1926 // 6.7.2.1p3
1927 // 6.7.2.1p4
1928
1929 } else {
1930 // Not a bitfield.
1931
1932 // validate II.
1933
1934 }
1935
1936 QualType T = GetTypeForDeclarator(D, S);
1937 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1938 bool InvalidDecl = false;
1939
1940 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1941 // than a variably modified type.
1942 if (T->isVariablyModifiedType()) {
1943 // FIXME: This diagnostic needs work
1944 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1945 InvalidDecl = true;
1946 }
1947
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001948 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001949
1950 HandleDeclAttributes(NewID, D.getDeclSpec().getAttributes(),
1951 D.getAttributes());
1952
1953 if (D.getInvalidType() || InvalidDecl)
1954 NewID->setInvalidDecl();
1955 // If we have visibility info, make sure the AST is set accordingly.
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001956 if (Visibility != tok::objc_not_keyword)
1957 NewID->setAccessControl(TranslateIvarVisibility(Visibility));
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001958 return NewID;
1959}
1960
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001961void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001962 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001963 DeclTy **Fields, unsigned NumFields,
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001964 SourceLocation LBrac, SourceLocation RBrac) {
Steve Naroff74216642007-09-14 22:20:54 +00001965 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1966 assert(EnclosingDecl && "missing record or interface decl");
1967 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1968
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001969 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001970 // Diagnose code like:
1971 // struct S { struct S {} X; };
1972 // We discover this when we complete the outer S. Reject and ignore the
1973 // outer S.
1974 Diag(Record->getLocation(), diag::err_nested_redefinition,
1975 Record->getKindName());
1976 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001977 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001978 return;
1979 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001980 // Verify that all the fields are okay.
1981 unsigned NumNamedMembers = 0;
1982 llvm::SmallVector<FieldDecl*, 32> RecFields;
1983 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001984
Reid Spencer5f016e22007-07-11 17:01:13 +00001985 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001986
Steve Naroff74216642007-09-14 22:20:54 +00001987 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1988 assert(FD && "missing field decl");
1989
1990 // Remember all fields.
1991 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001992
1993 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001994 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00001995
Reid Spencer5f016e22007-07-11 17:01:13 +00001996 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001997 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001998 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001999 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002000 FD->setInvalidDecl();
2001 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002002 continue;
2003 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002004 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2005 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002006 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002007 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002008 FD->setInvalidDecl();
2009 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002010 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002011 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002012 if (i != NumFields-1 || // ... that the last member ...
2013 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00002014 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002015 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002016 FD->setInvalidDecl();
2017 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002018 continue;
2019 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002020 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00002021 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2022 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002023 FD->setInvalidDecl();
2024 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002025 continue;
2026 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002027 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002028 if (Record)
2029 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002030 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002031 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2032 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00002033 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002034 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2035 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002036 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002037 Record->setHasFlexibleArrayMember(true);
2038 } else {
2039 // If this is a struct/class and this is not the last element, reject
2040 // it. Note that GCC supports variable sized arrays in the middle of
2041 // structures.
2042 if (i != NumFields-1) {
2043 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2044 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002045 FD->setInvalidDecl();
2046 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002047 continue;
2048 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002049 // We support flexible arrays at the end of structs in other structs
2050 // as an extension.
2051 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2052 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002053 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002054 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002055 }
2056 }
2057 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002058 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002059 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002060 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2061 FD->getName());
2062 FD->setInvalidDecl();
2063 EnclosingDecl->setInvalidDecl();
2064 continue;
2065 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002066 // Keep track of the number of named members.
2067 if (IdentifierInfo *II = FD->getIdentifier()) {
2068 // Detect duplicate member names.
2069 if (!FieldIDs.insert(II)) {
2070 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2071 // Find the previous decl.
2072 SourceLocation PrevLoc;
2073 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
2074 assert(i != e && "Didn't find previous def!");
2075 if (RecFields[i]->getIdentifier() == II) {
2076 PrevLoc = RecFields[i]->getLocation();
2077 break;
2078 }
2079 }
2080 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00002081 FD->setInvalidDecl();
2082 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002083 continue;
2084 }
2085 ++NumNamedMembers;
2086 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002087 }
2088
Reid Spencer5f016e22007-07-11 17:01:13 +00002089 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00002090 if (Record) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002091 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattnere1e79852008-02-06 00:51:33 +00002092 Consumer.HandleTagDeclDefinition(Record);
2093 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00002094 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2095 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2096 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2097 else if (ObjCImplementationDecl *IMPDecl =
2098 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002099 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2100 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00002101 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00002102 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00002103 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002104}
2105
Steve Naroff08d92e42007-09-15 18:49:24 +00002106Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00002107 DeclTy *lastEnumConst,
2108 SourceLocation IdLoc, IdentifierInfo *Id,
2109 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00002110 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002111 EnumConstantDecl *LastEnumConst =
2112 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2113 Expr *Val = static_cast<Expr*>(val);
2114
Chris Lattner31e05722007-08-26 06:24:45 +00002115 // The scope passed in may not be a decl scope. Zip up the scope tree until
2116 // we find one that is.
2117 while ((S->getFlags() & Scope::DeclScope) == 0)
2118 S = S->getParent();
2119
Reid Spencer5f016e22007-07-11 17:01:13 +00002120 // Verify that there isn't already something declared with this name in this
2121 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00002122 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00002123 if (IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002124 if (isa<EnumConstantDecl>(PrevDecl))
2125 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2126 else
2127 Diag(IdLoc, diag::err_redefinition, Id->getName());
2128 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00002129 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00002130 return 0;
2131 }
2132 }
2133
2134 llvm::APSInt EnumVal(32);
2135 QualType EltTy;
2136 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00002137 // Make sure to promote the operand type to int.
2138 UsualUnaryConversions(Val);
2139
Reid Spencer5f016e22007-07-11 17:01:13 +00002140 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2141 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00002142 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002143 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2144 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00002145 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00002146 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00002147 } else {
2148 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002149 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00002150 }
2151
2152 if (!Val) {
2153 if (LastEnumConst) {
2154 // Assign the last value + 1.
2155 EnumVal = LastEnumConst->getInitVal();
2156 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00002157
2158 // Check for overflow on increment.
2159 if (EnumVal < LastEnumConst->getInitVal())
2160 Diag(IdLoc, diag::warn_enum_value_overflow);
2161
Chris Lattnerb7416f92007-08-27 17:37:24 +00002162 EltTy = LastEnumConst->getType();
2163 } else {
2164 // First value, set to zero.
2165 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002166 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00002167 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002168 }
2169
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002170 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00002171 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2172 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002173 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00002174
2175 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002176 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002177 return New;
2178}
2179
Steve Naroff08d92e42007-09-15 18:49:24 +00002180void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00002181 DeclTy **Elements, unsigned NumElements) {
2182 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
2183 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
2184
Chris Lattnere37f0be2007-08-28 05:10:31 +00002185 // TODO: If the result value doesn't fit in an int, it must be a long or long
2186 // long value. ISO C does not support this, but GCC does as an extension,
2187 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00002188 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00002189
Chris Lattnerac609682007-08-28 06:15:15 +00002190 // Verify that all the values are okay, compute the size of the values, and
2191 // reverse the list.
2192 unsigned NumNegativeBits = 0;
2193 unsigned NumPositiveBits = 0;
2194
2195 // Keep track of whether all elements have type int.
2196 bool AllElementsInt = true;
2197
Reid Spencer5f016e22007-07-11 17:01:13 +00002198 EnumConstantDecl *EltList = 0;
2199 for (unsigned i = 0; i != NumElements; ++i) {
2200 EnumConstantDecl *ECD =
2201 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2202 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00002203
2204 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00002205 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00002206 assert(InitVal.getBitWidth() >= IntWidth &&
2207 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00002208 if (InitVal.getBitWidth() > IntWidth) {
2209 llvm::APSInt V(InitVal);
2210 V.trunc(IntWidth);
2211 V.extend(InitVal.getBitWidth());
2212 if (V != InitVal)
2213 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
2214 InitVal.toString());
2215 }
Chris Lattnerac609682007-08-28 06:15:15 +00002216
2217 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00002218 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00002219 NumPositiveBits = std::max(NumPositiveBits,
2220 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00002221 else
Chris Lattner21dd8212008-01-14 21:47:29 +00002222 NumNegativeBits = std::max(NumNegativeBits,
2223 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00002224
Chris Lattnerac609682007-08-28 06:15:15 +00002225 // Keep track of whether every enum element has type int (very commmon).
2226 if (AllElementsInt)
2227 AllElementsInt = ECD->getType() == Context.IntTy;
2228
Reid Spencer5f016e22007-07-11 17:01:13 +00002229 ECD->setNextDeclarator(EltList);
2230 EltList = ECD;
2231 }
2232
Chris Lattnerac609682007-08-28 06:15:15 +00002233 // Figure out the type that should be used for this enum.
2234 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2235 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002236 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00002237
2238 if (NumNegativeBits) {
2239 // If there is a negative value, figure out the smallest integer type (of
2240 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002241 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002242 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002243 BestWidth = IntWidth;
2244 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00002245 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002246
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002247 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002248 BestType = Context.LongTy;
2249 else {
Chris Lattner98be4942008-03-05 18:54:05 +00002250 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002251
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002252 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002253 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2254 BestType = Context.LongLongTy;
2255 }
2256 }
2257 } else {
2258 // If there is no negative value, figure out which of uint, ulong, ulonglong
2259 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002260 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002261 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002262 BestWidth = IntWidth;
2263 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00002264 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00002265 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002266 } else {
2267 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002268 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00002269 "How could an initializer get larger than ULL?");
2270 BestType = Context.UnsignedLongLongTy;
2271 }
2272 }
2273
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002274 // Loop over all of the enumerator constants, changing their types to match
2275 // the type of the enum if needed.
2276 for (unsigned i = 0; i != NumElements; ++i) {
2277 EnumConstantDecl *ECD =
2278 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2279 if (!ECD) continue; // Already issued a diagnostic.
2280
2281 // Standard C says the enumerators have int type, but we allow, as an
2282 // extension, the enumerators to be larger than int size. If each
2283 // enumerator value fits in an int, type it as an int, otherwise type it the
2284 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2285 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00002286 if (ECD->getType() == Context.IntTy) {
2287 // Make sure the init value is signed.
2288 llvm::APSInt IV = ECD->getInitVal();
2289 IV.setIsSigned(true);
2290 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002291 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00002292 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002293
2294 // Determine whether the value fits into an int.
2295 llvm::APSInt InitVal = ECD->getInitVal();
2296 bool FitsInInt;
2297 if (InitVal.isUnsigned() || !InitVal.isNegative())
2298 FitsInInt = InitVal.getActiveBits() < IntWidth;
2299 else
2300 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2301
2302 // If it fits into an integer type, force it. Otherwise force it to match
2303 // the enum decl type.
2304 QualType NewTy;
2305 unsigned NewWidth;
2306 bool NewSign;
2307 if (FitsInInt) {
2308 NewTy = Context.IntTy;
2309 NewWidth = IntWidth;
2310 NewSign = true;
2311 } else if (ECD->getType() == BestType) {
2312 // Already the right type!
2313 continue;
2314 } else {
2315 NewTy = BestType;
2316 NewWidth = BestWidth;
2317 NewSign = BestType->isSignedIntegerType();
2318 }
2319
2320 // Adjust the APSInt value.
2321 InitVal.extOrTrunc(NewWidth);
2322 InitVal.setIsSigned(NewSign);
2323 ECD->setInitVal(InitVal);
2324
2325 // Adjust the Expr initializer and type.
2326 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2327 ECD->setType(NewTy);
2328 }
Chris Lattnerac609682007-08-28 06:15:15 +00002329
Chris Lattnere00b18c2007-08-28 18:24:31 +00002330 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00002331 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00002332}
2333
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002334Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
2335 ExprTy *expr) {
2336 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
2337
Chris Lattner8e25d862008-03-16 00:16:02 +00002338 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002339}
2340
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002341Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00002342 SourceLocation LBrace,
2343 SourceLocation RBrace,
2344 const char *Lang,
2345 unsigned StrSize,
2346 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002347 LinkageSpecDecl::LanguageIDs Language;
2348 Decl *dcl = static_cast<Decl *>(D);
2349 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2350 Language = LinkageSpecDecl::lang_c;
2351 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2352 Language = LinkageSpecDecl::lang_cxx;
2353 else {
2354 Diag(Loc, diag::err_bad_language);
2355 return 0;
2356 }
2357
2358 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00002359 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002360}
2361
Chris Lattner74788ba2008-02-21 00:48:22 +00002362void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) {
Anders Carlsson6ede0ff2007-12-19 06:16:30 +00002363
Chris Lattner74788ba2008-02-21 00:48:22 +00002364 switch (Attr->getKind()) {
Chris Lattner212839c2008-02-20 23:17:35 +00002365 case AttributeList::AT_vector_size:
Reid Spencer5f016e22007-07-11 17:01:13 +00002366 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Chris Lattner74788ba2008-02-21 00:48:22 +00002367 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002368 if (!newType.isNull()) // install the new vector type into the decl
2369 vDecl->setType(newType);
2370 }
2371 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2372 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00002373 Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002374 if (!newType.isNull()) // install the new vector type into the decl
2375 tDecl->setUnderlyingType(newType);
2376 }
Chris Lattner212839c2008-02-20 23:17:35 +00002377 break;
Nate Begeman213541a2008-04-18 23:10:10 +00002378 case AttributeList::AT_ext_vector_type:
Steve Naroffbea0b342007-07-29 16:33:31 +00002379 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
Nate Begeman213541a2008-04-18 23:10:10 +00002380 HandleExtVectorTypeAttribute(tDecl, Attr);
Steve Naroffbea0b342007-07-29 16:33:31 +00002381 else
Chris Lattner74788ba2008-02-21 00:48:22 +00002382 Diag(Attr->getLoc(),
Nate Begeman213541a2008-04-18 23:10:10 +00002383 diag::err_typecheck_ext_vector_not_typedef);
Chris Lattner212839c2008-02-20 23:17:35 +00002384 break;
2385 case AttributeList::AT_address_space:
Christopher Lambebb97e92008-02-04 02:31:56 +00002386 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2387 QualType newType = HandleAddressSpaceTypeAttribute(
2388 tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00002389 Attr);
2390 tDecl->setUnderlyingType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00002391 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
2392 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00002393 Attr);
2394 // install the new addr spaced type into the decl
2395 vDecl->setType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00002396 }
Chris Lattner212839c2008-02-20 23:17:35 +00002397 break;
Eli Friedman3c0eb162008-05-27 03:33:27 +00002398 case AttributeList::AT_mode:
2399 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2400 QualType newType = HandleModeTypeAttribute(tDecl->getUnderlyingType(),
2401 Attr);
2402 tDecl->setUnderlyingType(newType);
2403 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
2404 QualType newType = HandleModeTypeAttribute(vDecl->getType(), Attr);
2405 vDecl->setType(newType);
2406 }
2407 // FIXME: Diagnostic?
2408 break;
Chris Lattner7e669b22008-02-29 16:48:43 +00002409 case AttributeList::AT_deprecated:
Chris Lattnerddee4232008-03-03 03:28:21 +00002410 HandleDeprecatedAttribute(New, Attr);
2411 break;
2412 case AttributeList::AT_visibility:
2413 HandleVisibilityAttribute(New, Attr);
2414 break;
2415 case AttributeList::AT_weak:
2416 HandleWeakAttribute(New, Attr);
2417 break;
2418 case AttributeList::AT_dllimport:
2419 HandleDLLImportAttribute(New, Attr);
2420 break;
2421 case AttributeList::AT_dllexport:
2422 HandleDLLExportAttribute(New, Attr);
2423 break;
2424 case AttributeList::AT_nothrow:
2425 HandleNothrowAttribute(New, Attr);
Chris Lattner7e669b22008-02-29 16:48:43 +00002426 break;
Nate Begeman440b4562008-03-07 20:04:22 +00002427 case AttributeList::AT_stdcall:
2428 HandleStdCallAttribute(New, Attr);
2429 break;
2430 case AttributeList::AT_fastcall:
2431 HandleFastCallAttribute(New, Attr);
2432 break;
Chris Lattner212839c2008-02-20 23:17:35 +00002433 case AttributeList::AT_aligned:
Chris Lattner74788ba2008-02-21 00:48:22 +00002434 HandleAlignedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00002435 break;
2436 case AttributeList::AT_packed:
Chris Lattner74788ba2008-02-21 00:48:22 +00002437 HandlePackedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00002438 break;
Nate Begemanc398f0b2008-02-21 19:30:49 +00002439 case AttributeList::AT_annotate:
2440 HandleAnnotateAttribute(New, Attr);
2441 break;
Ted Kremenekaecb3832008-02-27 20:43:06 +00002442 case AttributeList::AT_noreturn:
2443 HandleNoReturnAttribute(New, Attr);
2444 break;
Chris Lattnerddee4232008-03-03 03:28:21 +00002445 case AttributeList::AT_format:
2446 HandleFormatAttribute(New, Attr);
2447 break;
Nuno Lopes27ae6c62008-04-25 09:32:00 +00002448 case AttributeList::AT_transparent_union:
2449 HandleTransparentUnionAttribute(New, Attr);
2450 break;
Chris Lattner212839c2008-02-20 23:17:35 +00002451 default:
Chris Lattner7e669b22008-02-29 16:48:43 +00002452#if 0
2453 // TODO: when we have the full set of attributes, warn about unknown ones.
2454 Diag(Attr->getLoc(), diag::warn_attribute_ignored,
2455 Attr->getName()->getName());
2456#endif
Chris Lattner212839c2008-02-20 23:17:35 +00002457 break;
2458 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002459}
2460
2461void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
2462 AttributeList *declarator_postfix) {
2463 while (declspec_prefix) {
2464 HandleDeclAttribute(New, declspec_prefix);
2465 declspec_prefix = declspec_prefix->getNext();
2466 }
2467 while (declarator_postfix) {
2468 HandleDeclAttribute(New, declarator_postfix);
2469 declarator_postfix = declarator_postfix->getNext();
2470 }
2471}
2472
Nate Begeman213541a2008-04-18 23:10:10 +00002473void Sema::HandleExtVectorTypeAttribute(TypedefDecl *tDecl,
Steve Naroffbea0b342007-07-29 16:33:31 +00002474 AttributeList *rawAttr) {
2475 QualType curType = tDecl->getUnderlyingType();
Anders Carlsson78aaae92007-12-19 07:19:40 +00002476 // check the attribute arguments.
Steve Naroff73322922007-07-18 18:00:27 +00002477 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002478 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Steve Naroff73322922007-07-18 18:00:27 +00002479 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00002480 return;
Steve Naroff73322922007-07-18 18:00:27 +00002481 }
2482 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2483 llvm::APSInt vecSize(32);
2484 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002485 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Nate Begeman213541a2008-04-18 23:10:10 +00002486 "ext_vector_type", sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002487 return;
Steve Naroff73322922007-07-18 18:00:27 +00002488 }
2489 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2490 // in conjunction with complex types (pointers, arrays, functions, etc.).
2491 Type *canonType = curType.getCanonicalType().getTypePtr();
2492 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00002493 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Steve Naroff73322922007-07-18 18:00:27 +00002494 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00002495 return;
Steve Naroff73322922007-07-18 18:00:27 +00002496 }
2497 // unlike gcc's vector_size attribute, the size is specified as the
2498 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002499 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00002500
2501 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002502 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Steve Naroff73322922007-07-18 18:00:27 +00002503 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002504 return;
Steve Naroff73322922007-07-18 18:00:27 +00002505 }
Steve Naroffbea0b342007-07-29 16:33:31 +00002506 // Instantiate/Install the vector type, the number of elements is > 0.
Nate Begeman213541a2008-04-18 23:10:10 +00002507 tDecl->setUnderlyingType(Context.getExtVectorType(curType, vectorSize));
Steve Naroffbea0b342007-07-29 16:33:31 +00002508 // Remember this typedef decl, we will need it later for diagnostics.
Nate Begeman213541a2008-04-18 23:10:10 +00002509 ExtVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00002510}
2511
Reid Spencer5f016e22007-07-11 17:01:13 +00002512QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00002513 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002514 // check the attribute arugments.
2515 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002516 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Reid Spencer5f016e22007-07-11 17:01:13 +00002517 std::string("1"));
2518 return QualType();
2519 }
2520 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2521 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00002522 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002523 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002524 "vector_size", sizeExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002525 return QualType();
2526 }
2527 // navigate to the base type - we need to provide for vector pointers,
2528 // vector arrays, and functions returning vectors.
2529 Type *canonType = curType.getCanonicalType().getTypePtr();
2530
Steve Naroff73322922007-07-18 18:00:27 +00002531 if (canonType->isPointerType() || canonType->isArrayType() ||
2532 canonType->isFunctionType()) {
Chris Lattner54b263b2007-12-19 05:38:06 +00002533 assert(0 && "HandleVector(): Complex type construction unimplemented");
Steve Naroff73322922007-07-18 18:00:27 +00002534 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2535 do {
2536 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2537 canonType = PT->getPointeeType().getTypePtr();
2538 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2539 canonType = AT->getElementType().getTypePtr();
2540 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2541 canonType = FT->getResultType().getTypePtr();
2542 } while (canonType->isPointerType() || canonType->isArrayType() ||
2543 canonType->isFunctionType());
2544 */
Reid Spencer5f016e22007-07-11 17:01:13 +00002545 }
2546 // the base type must be integer or float.
2547 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00002548 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Reid Spencer5f016e22007-07-11 17:01:13 +00002549 curType.getCanonicalType().getAsString());
2550 return QualType();
2551 }
Chris Lattner98be4942008-03-05 18:54:05 +00002552 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(curType));
Reid Spencer5f016e22007-07-11 17:01:13 +00002553 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002554 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00002555
2556 // the vector size needs to be an integral multiple of the type size.
2557 if (vectorSize % typeSize) {
Chris Lattner2070d802008-02-20 23:25:22 +00002558 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00002559 sizeExpr->getSourceRange());
2560 return QualType();
2561 }
2562 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002563 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00002564 sizeExpr->getSourceRange());
2565 return QualType();
2566 }
Nate Begemanc398f0b2008-02-21 19:30:49 +00002567 // Instantiate the vector type, the number of elements is > 0, and not
2568 // required to be a power of 2, unlike GCC.
Steve Naroff73322922007-07-18 18:00:27 +00002569 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00002570}
2571
Chris Lattner2070d802008-02-20 23:25:22 +00002572void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) {
Anders Carlssonad148062008-02-16 00:29:18 +00002573 // check the attribute arguments.
2574 if (rawAttr->getNumArgs() > 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002575 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlssonad148062008-02-16 00:29:18 +00002576 std::string("0"));
2577 return;
2578 }
2579
2580 if (TagDecl *TD = dyn_cast<TagDecl>(d))
2581 TD->addAttr(new PackedAttr);
2582 else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
2583 // If the alignment is less than or equal to 8 bits, the packed attribute
2584 // has no effect.
Chris Lattnerabb57582008-05-09 05:34:49 +00002585 if (!FD->getType()->isIncompleteType() &&
2586 Context.getTypeAlign(FD->getType()) <= 8)
Chris Lattner2070d802008-02-20 23:25:22 +00002587 Diag(rawAttr->getLoc(),
Anders Carlssonad148062008-02-16 00:29:18 +00002588 diag::warn_attribute_ignored_for_field_of_type,
Chris Lattner2070d802008-02-20 23:25:22 +00002589 rawAttr->getName()->getName(), FD->getType().getAsString());
Anders Carlssonad148062008-02-16 00:29:18 +00002590 else
Anders Carlsson425a6092008-02-16 00:39:40 +00002591 FD->addAttr(new PackedAttr);
Anders Carlssonad148062008-02-16 00:29:18 +00002592 } else
Chris Lattner2070d802008-02-20 23:25:22 +00002593 Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
2594 rawAttr->getName()->getName());
Anders Carlssonad148062008-02-16 00:29:18 +00002595}
Nate Begemanc398f0b2008-02-21 19:30:49 +00002596
Ted Kremenekaecb3832008-02-27 20:43:06 +00002597void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) {
2598 // check the attribute arguments.
2599 if (rawAttr->getNumArgs() != 0) {
2600 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2601 std::string("0"));
2602 return;
2603 }
2604
Ted Kremenek3465fb32008-03-03 16:52:27 +00002605 FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2606
2607 if (!Fn) {
2608 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2609 "noreturn", "function");
2610 return;
2611 }
2612
Ted Kremenekaecb3832008-02-27 20:43:06 +00002613 d->addAttr(new NoReturnAttr());
2614}
2615
Chris Lattnerddee4232008-03-03 03:28:21 +00002616void Sema::HandleDeprecatedAttribute(Decl *d, AttributeList *rawAttr) {
2617 // check the attribute arguments.
2618 if (rawAttr->getNumArgs() != 0) {
2619 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2620 std::string("0"));
2621 return;
2622 }
2623
2624 d->addAttr(new DeprecatedAttr());
2625}
2626
2627void Sema::HandleVisibilityAttribute(Decl *d, AttributeList *rawAttr) {
2628 // check the attribute arguments.
Chris Lattner7b937ae2008-03-04 18:08:48 +00002629 if (rawAttr->getNumArgs() != 1) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002630 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2631 std::string("1"));
2632 return;
2633 }
2634
Chris Lattner7b937ae2008-03-04 18:08:48 +00002635 Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0));
2636 Arg = Arg->IgnoreParenCasts();
2637 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2638
2639 if (Str == 0 || Str->isWide()) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002640 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002641 "visibility", std::string("1"));
Chris Lattnerddee4232008-03-03 03:28:21 +00002642 return;
2643 }
2644
Chris Lattner7b937ae2008-03-04 18:08:48 +00002645 const char *TypeStr = Str->getStrData();
2646 unsigned TypeLen = Str->getByteLength();
Dan Gohman4f8d1232008-05-22 00:50:06 +00002647 VisibilityAttr::VisibilityTypes type;
Chris Lattnerddee4232008-03-03 03:28:21 +00002648
Chris Lattner7b937ae2008-03-04 18:08:48 +00002649 if (TypeLen == 7 && !memcmp(TypeStr, "default", 7))
Dan Gohman4f8d1232008-05-22 00:50:06 +00002650 type = VisibilityAttr::DefaultVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002651 else if (TypeLen == 6 && !memcmp(TypeStr, "hidden", 6))
Dan Gohman4f8d1232008-05-22 00:50:06 +00002652 type = VisibilityAttr::HiddenVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002653 else if (TypeLen == 8 && !memcmp(TypeStr, "internal", 8))
Dan Gohman4f8d1232008-05-22 00:50:06 +00002654 type = VisibilityAttr::HiddenVisibility; // FIXME
Chris Lattner7b937ae2008-03-04 18:08:48 +00002655 else if (TypeLen == 9 && !memcmp(TypeStr, "protected", 9))
Dan Gohman4f8d1232008-05-22 00:50:06 +00002656 type = VisibilityAttr::ProtectedVisibility;
Chris Lattnerddee4232008-03-03 03:28:21 +00002657 else {
2658 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002659 "visibility", TypeStr);
Chris Lattnerddee4232008-03-03 03:28:21 +00002660 return;
2661 }
2662
2663 d->addAttr(new VisibilityAttr(type));
2664}
2665
2666void Sema::HandleWeakAttribute(Decl *d, AttributeList *rawAttr) {
2667 // check the attribute arguments.
2668 if (rawAttr->getNumArgs() != 0) {
2669 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2670 std::string("0"));
2671 return;
2672 }
2673
2674 d->addAttr(new WeakAttr());
2675}
2676
2677void Sema::HandleDLLImportAttribute(Decl *d, AttributeList *rawAttr) {
2678 // check the attribute arguments.
2679 if (rawAttr->getNumArgs() != 0) {
2680 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2681 std::string("0"));
2682 return;
2683 }
2684
2685 d->addAttr(new DLLImportAttr());
2686}
2687
2688void Sema::HandleDLLExportAttribute(Decl *d, AttributeList *rawAttr) {
2689 // check the attribute arguments.
2690 if (rawAttr->getNumArgs() != 0) {
2691 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2692 std::string("0"));
2693 return;
2694 }
2695
2696 d->addAttr(new DLLExportAttr());
2697}
2698
Nate Begeman440b4562008-03-07 20:04:22 +00002699void Sema::HandleStdCallAttribute(Decl *d, AttributeList *rawAttr) {
2700 // check the attribute arguments.
2701 if (rawAttr->getNumArgs() != 0) {
2702 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2703 std::string("0"));
2704 return;
2705 }
2706
2707 d->addAttr(new StdCallAttr());
2708}
2709
2710void Sema::HandleFastCallAttribute(Decl *d, AttributeList *rawAttr) {
2711 // check the attribute arguments.
2712 if (rawAttr->getNumArgs() != 0) {
2713 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2714 std::string("0"));
2715 return;
2716 }
2717
2718 d->addAttr(new FastCallAttr());
2719}
2720
Chris Lattnerddee4232008-03-03 03:28:21 +00002721void Sema::HandleNothrowAttribute(Decl *d, AttributeList *rawAttr) {
2722 // check the attribute arguments.
2723 if (rawAttr->getNumArgs() != 0) {
2724 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2725 std::string("0"));
2726 return;
2727 }
2728
2729 d->addAttr(new NoThrowAttr());
2730}
2731
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002732static const FunctionTypeProto *getFunctionProto(Decl *d) {
Nuno Lopes59b6d5a2008-04-18 22:43:39 +00002733 QualType Ty;
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002734
Nuno Lopes59b6d5a2008-04-18 22:43:39 +00002735 if (ValueDecl *decl = dyn_cast<ValueDecl>(d))
2736 Ty = decl->getType();
2737 else if (FieldDecl *decl = dyn_cast<FieldDecl>(d))
2738 Ty = decl->getType();
Ted Kremenek72786e02008-05-09 17:36:24 +00002739 else if (TypedefDecl* decl = dyn_cast<TypedefDecl>(d))
2740 Ty = decl->getUnderlyingType();
Nuno Lopes59b6d5a2008-04-18 22:43:39 +00002741 else
2742 return 0;
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002743
2744 if (Ty->isFunctionPointerType()) {
2745 const PointerType *PtrTy = Ty->getAsPointerType();
2746 Ty = PtrTy->getPointeeType();
2747 }
2748
2749 if (const FunctionType *FnTy = Ty->getAsFunctionType())
2750 return dyn_cast<FunctionTypeProto>(FnTy->getAsFunctionType());
2751
2752 return 0;
2753}
2754
Ted Kremenekc5f551f2008-05-08 19:43:35 +00002755static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
2756 if (!T->isPointerType())
2757 return false;
2758
2759 T = T->getAsPointerType()->getPointeeType().getCanonicalType();
2760 ObjCInterfaceType* ClsT = dyn_cast<ObjCInterfaceType>(T.getTypePtr());
2761
2762 if (!ClsT)
2763 return false;
2764
2765 IdentifierInfo* ClsName = ClsT->getDecl()->getIdentifier();
2766
2767 // FIXME: Should we walk the chain of classes?
2768 return ClsName == &Ctx.Idents.get("NSString") ||
2769 ClsName == &Ctx.Idents.get("NSMutableString");
2770}
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002771
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002772/// Handle __attribute__((format(type,idx,firstarg))) attributes
2773/// based on http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chris Lattnerddee4232008-03-03 03:28:21 +00002774void Sema::HandleFormatAttribute(Decl *d, AttributeList *rawAttr) {
2775
2776 if (!rawAttr->getParameterName()) {
2777 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2778 "format", std::string("1"));
2779 return;
2780 }
2781
2782 if (rawAttr->getNumArgs() != 2) {
2783 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2784 std::string("3"));
2785 return;
2786 }
2787
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002788 // GCC ignores the format attribute on K&R style function
2789 // prototypes, so we ignore it as well
2790 const FunctionTypeProto *proto = getFunctionProto(d);
2791
2792 if (!proto) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002793 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2794 "format", "function");
2795 return;
2796 }
2797
2798 // FIXME: in C++ the implicit 'this' function parameter also counts.
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002799 // this is needed in order to be compatible with GCC
Chris Lattnerddee4232008-03-03 03:28:21 +00002800 // the index must start in 1 and the limit is numargs+1
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002801 unsigned NumArgs = proto->getNumArgs();
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002802 unsigned FirstIdx = 1;
Chris Lattnerddee4232008-03-03 03:28:21 +00002803
2804 const char *Format = rawAttr->getParameterName()->getName();
2805 unsigned FormatLen = rawAttr->getParameterName()->getLength();
2806
2807 // Normalize the argument, __foo__ becomes foo.
2808 if (FormatLen > 4 && Format[0] == '_' && Format[1] == '_' &&
2809 Format[FormatLen - 2] == '_' && Format[FormatLen - 1] == '_') {
2810 Format += 2;
2811 FormatLen -= 4;
2812 }
2813
Ted Kremenekc5f551f2008-05-08 19:43:35 +00002814 bool Supported = false;
2815 bool is_NSString = false;
2816 bool is_strftime = false;
2817
2818 switch (FormatLen) {
2819 default: break;
2820 case 5:
2821 Supported = !memcmp(Format, "scanf", 5);
2822 break;
2823 case 6:
2824 Supported = !memcmp(Format, "printf", 6);
2825 break;
2826 case 7:
2827 Supported = !memcmp(Format, "strfmon", 7);
2828 break;
2829 case 8:
2830 Supported = (is_strftime = !memcmp(Format, "strftime", 8)) ||
2831 (is_NSString = !memcmp(Format, "NSString", 8));
2832 break;
2833 }
2834
2835 if (!Supported) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002836 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2837 "format", rawAttr->getParameterName()->getName());
2838 return;
2839 }
2840
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002841 // checks for the 2nd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002842 Expr *IdxExpr = static_cast<Expr *>(rawAttr->getArg(0));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002843 llvm::APSInt Idx(Context.getTypeSize(IdxExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002844 if (!IdxExpr->isIntegerConstantExpr(Idx, Context)) {
2845 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2846 "format", std::string("2"), IdxExpr->getSourceRange());
2847 return;
2848 }
2849
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002850 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002851 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2852 "format", std::string("2"), IdxExpr->getSourceRange());
2853 return;
2854 }
2855
Ted Kremenekc5f551f2008-05-08 19:43:35 +00002856 // FIXME: Do we need to bounds check?
2857 unsigned ArgIdx = Idx.getZExtValue() - 1;
2858
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002859 // make sure the format string is really a string
Ted Kremenekc5f551f2008-05-08 19:43:35 +00002860 QualType Ty = proto->getArgType(ArgIdx);
2861
2862 if (is_NSString) {
2863 // FIXME: do we need to check if the type is NSString*? What are
2864 // the semantics?
2865 if (!isNSStringType(Ty, Context)) {
2866 // FIXME: Should highlight the actual expression that has the
2867 // wrong type.
2868 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_NSString,
2869 IdxExpr->getSourceRange());
2870 return;
2871 }
2872 }
2873 else if (!Ty->isPointerType() ||
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002874 !Ty->getAsPointerType()->getPointeeType()->isCharType()) {
Ted Kremenekc5f551f2008-05-08 19:43:35 +00002875 // FIXME: Should highlight the actual expression that has the
2876 // wrong type.
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002877 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_string,
2878 IdxExpr->getSourceRange());
2879 return;
2880 }
2881
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002882 // check the 3rd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002883 Expr *FirstArgExpr = static_cast<Expr *>(rawAttr->getArg(1));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002884 llvm::APSInt FirstArg(Context.getTypeSize(FirstArgExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002885 if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, Context)) {
2886 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2887 "format", std::string("3"), FirstArgExpr->getSourceRange());
2888 return;
2889 }
2890
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002891 // check if the function is variadic if the 3rd argument non-zero
2892 if (FirstArg != 0) {
2893 if (proto->isVariadic()) {
2894 ++NumArgs; // +1 for ...
2895 } else {
2896 Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
2897 return;
2898 }
2899 }
2900
2901 // strftime requires FirstArg to be 0 because it doesn't read from any variable
2902 // the input is just the current time + the format string
Ted Kremenekc5f551f2008-05-08 19:43:35 +00002903 if (is_strftime) {
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002904 if (FirstArg != 0) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002905 Diag(rawAttr->getLoc(), diag::err_format_strftime_third_parameter,
2906 FirstArgExpr->getSourceRange());
2907 return;
2908 }
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002909 // if 0 it disables parameter checking (to use with e.g. va_list)
2910 } else if (FirstArg != 0 && FirstArg != NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002911 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2912 "format", std::string("3"), FirstArgExpr->getSourceRange());
2913 return;
2914 }
2915
2916 d->addAttr(new FormatAttr(std::string(Format, FormatLen),
2917 Idx.getZExtValue(), FirstArg.getZExtValue()));
2918}
2919
Nuno Lopes27ae6c62008-04-25 09:32:00 +00002920void Sema::HandleTransparentUnionAttribute(Decl *d, AttributeList *rawAttr) {
2921 // check the attribute arguments.
2922 if (rawAttr->getNumArgs() != 0) {
2923 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2924 std::string("0"));
2925 return;
2926 }
2927
2928 TypeDecl *decl = dyn_cast<TypeDecl>(d);
2929
2930 if (!decl || !Context.getTypeDeclType(decl)->isUnionType()) {
2931 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2932 "transparent_union", "union");
2933 return;
2934 }
2935
Chris Lattner22624942008-04-30 16:04:01 +00002936 //QualType QTy = Context.getTypeDeclType(decl);
2937 //const RecordType *Ty = QTy->getAsUnionType();
Nuno Lopes27ae6c62008-04-25 09:32:00 +00002938
2939// FIXME
2940// Ty->addAttr(new TransparentUnionAttr());
2941}
2942
Nate Begemanc398f0b2008-02-21 19:30:49 +00002943void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) {
2944 // check the attribute arguments.
2945 if (rawAttr->getNumArgs() != 1) {
2946 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2947 std::string("1"));
2948 return;
2949 }
2950 Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
2951 StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
Anders Carlssonad148062008-02-16 00:29:18 +00002952
Nate Begemanc398f0b2008-02-21 19:30:49 +00002953 // Make sure that there is a string literal as the annotation's single
2954 // argument.
2955 if (!SE) {
2956 Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
2957 return;
2958 }
2959 d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
2960 SE->getByteLength())));
2961}
2962
Anders Carlsson78aaae92007-12-19 07:19:40 +00002963void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
2964{
2965 // check the attribute arguments.
Eli Friedman4ca08672008-01-30 17:38:42 +00002966 if (rawAttr->getNumArgs() > 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002967 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlsson78aaae92007-12-19 07:19:40 +00002968 std::string("1"));
2969 return;
2970 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002971
Anders Carlsson042c4e72008-02-16 19:51:27 +00002972 unsigned Align = 0;
2973
2974 if (rawAttr->getNumArgs() == 0) {
2975 // FIXME: This should be the target specific maximum alignment.
2976 // (For now we just use 128 bits which is the maximum on X86.
2977 Align = 128;
Eli Friedman4ca08672008-01-30 17:38:42 +00002978 return;
Anders Carlsson042c4e72008-02-16 19:51:27 +00002979 } else {
2980 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
2981 llvm::APSInt alignment(32);
2982 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002983 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002984 "aligned", alignmentExpr->getSourceRange());
2985 return;
2986 }
2987
2988 Align = alignment.getZExtValue() * 8;
2989 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002990
Anders Carlsson042c4e72008-02-16 19:51:27 +00002991 d->addAttr(new AlignedAttr(Align));
Anders Carlsson78aaae92007-12-19 07:19:40 +00002992}