blob: f8153289b2b0a25d3c4b4952c33b9a3b10d289ce [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Chris Lattner33aad6e2008-02-06 00:51:33 +000015#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#include "clang/AST/ASTContext.h"
Anders Carlsson3f70c542008-02-15 07:04:12 +000017#include "clang/AST/Attr.h"
Chris Lattner4b009652007-07-25 00:24:17 +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"
Chris Lattner4b009652007-07-25 00:24:17 +000024#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/TargetInfo.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000026#include "clang/Basic/SourceManager.h"
Eli Friedman02c22ce2008-05-20 13:48:25 +000027#include "clang/AST/ExprCXX.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000028// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattner33aad6e2008-02-06 00:51:33 +000029#include "clang/Lex/Preprocessor.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000030#include "clang/Lex/HeaderSearch.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000031#include "llvm/ADT/SmallString.h"
Chris Lattner4b009652007-07-25 00:24:17 +000032#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian67907bd2007-10-05 18:00:57 +000033#include "llvm/ADT/DenseSet.h"
Chris Lattner4b009652007-07-25 00:24:17 +000034using namespace clang;
35
Steve Naroff6384a012008-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 Gregor1d661552008-04-13 21:07:44 +000039 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
40 isa<ObjCInterfaceDecl>(IIDecl) ||
41 isa<TagDecl>(IIDecl)))
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000042 return IIDecl;
Steve Naroff81f1bba2007-09-06 21:24:23 +000043 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000044}
45
Chris Lattneref87a202008-04-22 18:39:57 +000046void Sema::PushDeclContext(DeclContext *DC) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +000047 assert( ( (isa<ObjCMethodDecl>(DC) && isa<TranslationUnitDecl>(CurContext))
Chris Lattneref87a202008-04-22 18:39:57 +000048 || DC->getParent() == CurContext ) &&
Chris Lattnerf3874bc2008-04-06 04:47:34 +000049 "The next DeclContext should be directly contained in the current one.");
Chris Lattneref87a202008-04-22 18:39:57 +000050 CurContext = DC;
Chris Lattnereee57c02008-04-04 06:12:32 +000051}
52
Chris Lattnerf3874bc2008-04-06 04:47:34 +000053void Sema::PopDeclContext() {
54 assert(CurContext && "DeclContext imbalance!");
Argiris Kirtzidisd3586002008-04-17 14:40:12 +000055 // If CurContext is a ObjC method, getParent() will return NULL.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +000056 CurContext = isa<ObjCMethodDecl>(CurContext)
Argiris Kirtzidisd3586002008-04-17 14:40:12 +000057 ? Context.getTranslationUnitDecl()
58 : CurContext->getParent();
Chris Lattnereee57c02008-04-04 06:12:32 +000059}
60
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000061/// Add this decl to the scope shadowed decl chains.
62void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000063 S->AddDecl(D);
Argiris Kirtzidis59a9afb2008-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);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000087}
88
Steve Naroff9637a9b2007-10-09 22:01:59 +000089void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +000090 if (S->decl_empty()) return;
91 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argiris Kirtzidis59a9afb2008-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 Lattnera7549902007-08-26 06:24:45 +000097
Chris Lattner4b009652007-07-25 00:24:17 +000098 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
99 I != E; ++I) {
Steve Naroffd21bc0d2007-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
Chris Lattner4b009652007-07-25 00:24:17 +0000105 IdentifierInfo *II = D->getIdentifier();
106 if (!II) continue;
107
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000108 // Unlink this decl from the identifier.
109 IdResolver.RemoveDecl(D);
110
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroffe57c21a2008-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 Naroffe57c21a2008-04-01 23:04:06 +0000126ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff15208162008-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 Jahaniandc36dc12007-10-12 19:38:20 +0000130
Steve Naroff6384a012008-04-02 14:35:35 +0000131 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000132}
133
Steve Naroffe57c21a2008-04-01 23:04:06 +0000134/// LookupDecl - Look up the inner-most declaration in the specified
Chris Lattner4b009652007-07-25 00:24:17 +0000135/// namespace.
Steve Naroff6384a012008-04-02 14:35:35 +0000136Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
137 Scope *S, bool enableLazyBuiltinCreation) {
Chris Lattner4b009652007-07-25 00:24:17 +0000138 if (II == 0) return 0;
Douglas Gregor1d661552008-04-13 21:07:44 +0000139 unsigned NS = NSI;
140 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
141 NS |= Decl::IDNS_Tag;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000142
Chris Lattner4b009652007-07-25 00:24:17 +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.
Argiris Kirtzidis59a9afb2008-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 Lattner2a1e2ed2008-04-11 07:00:53 +0000150
Chris Lattner4b009652007-07-25 00:24:17 +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 Gregor1d661552008-04-13 21:07:44 +0000154 if (NS & Decl::IDNS_Ordinary) {
Steve Naroff6384a012008-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 Naroffe57c21a2008-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 Naroff64334ea2008-04-02 00:39:51 +0000163 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe57c21a2008-04-01 23:04:06 +0000164 // other names in IDNS_Ordinary.
Steve Naroff15208162008-04-02 18:30:49 +0000165 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
166 if (IDI != ObjCInterfaceDecls.end())
167 return IDI->second;
Steve Naroffe57c21a2008-04-01 23:04:06 +0000168 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
169 if (I != ObjCAliasDecls.end())
170 return I->second->getClassInterface();
171 }
Chris Lattner4b009652007-07-25 00:24:17 +0000172 }
173 return 0;
174}
175
Chris Lattnera9c87f22008-05-05 22:18:14 +0000176void Sema::InitBuiltinVaListType() {
Anders Carlsson36760332007-10-15 20:28:48 +0000177 if (!Context.getBuiltinVaListType().isNull())
178 return;
179
180 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroff6384a012008-04-02 14:35:35 +0000181 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000182 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000183 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
184}
185
Chris Lattner4b009652007-07-25 00:24:17 +0000186/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
187/// lazily create a decl for it.
Chris Lattner71c01112007-10-10 23:42:28 +0000188ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
189 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000190 Builtin::ID BID = (Builtin::ID)bid;
191
Anders Carlsson36760332007-10-15 20:28:48 +0000192 if (BID == Builtin::BI__builtin_va_start ||
Chris Lattnera9c87f22008-05-05 22:18:14 +0000193 BID == Builtin::BI__builtin_va_copy ||
194 BID == Builtin::BI__builtin_va_end)
Anders Carlsson36760332007-10-15 20:28:48 +0000195 InitBuiltinVaListType();
196
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000197 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argiris Kirtzidis9d0d8bf2008-04-17 14:47:13 +0000198 FunctionDecl *New = FunctionDecl::Create(Context,
199 Context.getTranslationUnitDecl(),
Chris Lattnereee57c02008-04-04 06:12:32 +0000200 SourceLocation(), II, R,
Chris Lattner4c7802b2008-03-15 21:24:04 +0000201 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000202
Chris Lattnera9c87f22008-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 Lattner2a1e2ed2008-04-11 07:00:53 +0000216 // TUScope is the translation-unit scope to insert this function into.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000217 PushOnScopeChains(New, TUScope);
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroffe57c21a2008-04-01 23:04:06 +0000225TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroffae84af82007-10-31 18:42:27 +0000235 // Allow multiple definitions for ObjC built-in typedefs.
236 // FIXME: Verify the underlying types are equivalent!
Ted Kremenek42730c52008-01-07 19:49:32 +0000237 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroffae84af82007-10-31 18:42:27 +0000238 return Old;
Steve Naroffa9eae582008-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 Naroff1997d2c2008-03-26 21:27:00 +0000252 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
253 if ((OldDirType != DirectoryLookup::NormalHeaderDir ||
254 NewDirType != DirectoryLookup::NormalHeaderDir) ||
Steve Naroff73a07032008-02-07 03:50:06 +0000255 getLangOptions().Microsoft)
Steve Naroffa9eae582008-01-30 23:46:05 +0000256 return New;
Steve Naroff1997d2c2008-03-26 21:27:00 +0000257
Chris Lattner4b009652007-07-25 00:24:17 +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; ...
Steve Naroff93f64652008-05-23 20:57:38 +0000261 // FIXME: temporarily removing this diagnostic (5/23/08). Will put back
262 // next week (which the .i file FIXME above is nailed).
263 //Diag(New->getLocation(), diag::err_redefinition, New->getName());
264 //Diag(Old->getLocation(), diag::err_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000265 return New;
266}
267
Chris Lattner402b3372008-03-03 03:28:21 +0000268/// DeclhasAttr - returns true if decl Declaration already has the target attribute.
269static bool DeclHasAttr(const Decl *decl, const Attr *target) {
270 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
271 if (attr->getKind() == target->getKind())
272 return true;
273
274 return false;
275}
276
277/// MergeAttributes - append attributes from the Old decl to the New one.
278static void MergeAttributes(Decl *New, Decl *Old) {
279 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
280
281// FIXME: fix this code to cleanup the Old attrs correctly
282 while (attr) {
283 tmp = attr;
284 attr = attr->getNext();
285
286 if (!DeclHasAttr(New, tmp)) {
287 New->addAttr(tmp);
288 } else {
289 tmp->setNext(0);
290 delete(tmp);
291 }
292 }
293}
294
Chris Lattner3e254fb2008-04-08 04:40:51 +0000295/// MergeFunctionDecl - We just parsed a function 'New' from
296/// declarator D which has the same name and scope as a previous
297/// declaration 'Old'. Figure out how to resolve this situation,
298/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor42214c52008-04-21 02:02:58 +0000299/// Redeclaration will be set true if thisNew is a redeclaration OldD.
300FunctionDecl *
301Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
302 Redeclaration = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000303 // Verify the old decl was also a function.
304 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
305 if (!Old) {
306 Diag(New->getLocation(), diag::err_redefinition_different_kind,
307 New->getName());
308 Diag(OldD->getLocation(), diag::err_previous_definition);
309 return New;
310 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000311
Chris Lattner42a21742008-04-06 23:10:54 +0000312 QualType OldQType = Context.getCanonicalType(Old->getType());
313 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner60476ff2007-11-20 19:04:50 +0000314
Chris Lattner3e254fb2008-04-08 04:40:51 +0000315 // C++ [dcl.fct]p3:
316 // All declarations for a function shall agree exactly in both the
317 // return type and the parameter-type-list.
Douglas Gregor42214c52008-04-21 02:02:58 +0000318 if (getLangOptions().CPlusPlus && OldQType == NewQType) {
319 MergeAttributes(New, Old);
320 Redeclaration = true;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000321 return MergeCXXFunctionDecl(New, Old);
Douglas Gregor42214c52008-04-21 02:02:58 +0000322 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000323
324 // C: Function types need to be compatible, not identical. This handles
Steve Naroff1d5bd642008-01-14 20:51:29 +0000325 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000326 if (!getLangOptions().CPlusPlus &&
327 Context.functionTypesAreCompatible(OldQType, NewQType)) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000328 MergeAttributes(New, Old);
329 Redeclaration = true;
Steve Naroff1d5bd642008-01-14 20:51:29 +0000330 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000331 }
Chris Lattner1470b072007-11-06 06:07:26 +0000332
Steve Naroff6c9e7922008-01-16 15:01:34 +0000333 // A function that has already been declared has been redeclared or defined
334 // with a different type- show appropriate diagnostic
Steve Naroff9104f3c2008-04-04 14:32:09 +0000335 diag::kind PrevDiag;
Douglas Gregor42214c52008-04-21 02:02:58 +0000336 if (Old->isThisDeclarationADefinition())
Steve Naroff9104f3c2008-04-04 14:32:09 +0000337 PrevDiag = diag::err_previous_definition;
338 else if (Old->isImplicit())
339 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000340 else
Steve Naroff9104f3c2008-04-04 14:32:09 +0000341 PrevDiag = diag::err_previous_declaration;
Steve Naroff6c9e7922008-01-16 15:01:34 +0000342
Chris Lattner4b009652007-07-25 00:24:17 +0000343 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
344 // TODO: This is totally simplistic. It should handle merging functions
345 // together etc, merging extern int X; int X; ...
Steve Naroff6c9e7922008-01-16 15:01:34 +0000346 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
347 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000348 return New;
349}
350
Chris Lattnerf9167d12007-11-06 04:28:31 +0000351/// equivalentArrayTypes - Used to determine whether two array types are
352/// equivalent.
353/// We need to check this explicitly as an incomplete array definition is
354/// considered a VariableArrayType, so will not match a complete array
355/// definition that would be otherwise equivalent.
356static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
357 const ArrayType *NewAT = NewQType->getAsArrayType();
358 const ArrayType *OldAT = OldQType->getAsArrayType();
359
360 if (!NewAT || !OldAT)
361 return false;
362
363 // If either (or both) array types in incomplete we need to strip off the
364 // outer VariableArrayType. Once the outer VAT is removed the remaining
365 // types must be identical if the array types are to be considered
366 // equivalent.
367 // eg. int[][1] and int[1][1] become
368 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
369 // removing the outermost VAT gives
370 // CAT(1, int) and CAT(1, int)
371 // which are equal, therefore the array types are equivalent.
Eli Friedmane0079792008-02-15 12:53:51 +0000372 if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
Chris Lattnerf9167d12007-11-06 04:28:31 +0000373 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
374 return false;
Eli Friedmand32157f2008-01-29 07:51:12 +0000375 NewQType = NewAT->getElementType().getCanonicalType();
376 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattnerf9167d12007-11-06 04:28:31 +0000377 }
378
379 return NewQType == OldQType;
380}
381
Chris Lattner4b009652007-07-25 00:24:17 +0000382/// MergeVarDecl - We just parsed a variable 'New' which has the same name
383/// and scope as a previous declaration 'Old'. Figure out how to resolve this
384/// situation, merging decls or emitting diagnostics as appropriate.
385///
386/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
387/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
388///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000389VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000390 // Verify the old decl was also a variable.
391 VarDecl *Old = dyn_cast<VarDecl>(OldD);
392 if (!Old) {
393 Diag(New->getLocation(), diag::err_redefinition_different_kind,
394 New->getName());
395 Diag(OldD->getLocation(), diag::err_previous_definition);
396 return New;
397 }
Chris Lattner402b3372008-03-03 03:28:21 +0000398
399 MergeAttributes(New, Old);
400
Chris Lattner4b009652007-07-25 00:24:17 +0000401 // Verify the types match.
Chris Lattner42a21742008-04-06 23:10:54 +0000402 QualType OldCType = Context.getCanonicalType(Old->getType());
403 QualType NewCType = Context.getCanonicalType(New->getType());
404 if (OldCType != NewCType && !areEquivalentArrayTypes(NewCType, OldCType)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000405 Diag(New->getLocation(), diag::err_redefinition, New->getName());
406 Diag(Old->getLocation(), diag::err_previous_definition);
407 return New;
408 }
Steve Naroffb00247f2008-01-30 00:44:01 +0000409 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
410 if (New->getStorageClass() == VarDecl::Static &&
411 (Old->getStorageClass() == VarDecl::None ||
412 Old->getStorageClass() == VarDecl::Extern)) {
413 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
414 Diag(Old->getLocation(), diag::err_previous_definition);
415 return New;
416 }
417 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
418 if (New->getStorageClass() != VarDecl::Static &&
419 Old->getStorageClass() == VarDecl::Static) {
420 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
421 Diag(Old->getLocation(), diag::err_previous_definition);
422 return New;
423 }
424 // We've verified the types match, now handle "tentative" definitions.
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000425 if (Old->isFileVarDecl() && New->isFileVarDecl()) {
Steve Naroffb00247f2008-01-30 00:44:01 +0000426 // Handle C "tentative" external object definitions (C99 6.9.2).
427 bool OldIsTentative = false;
428 bool NewIsTentative = false;
429
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000430 if (!Old->getInit() &&
431 (Old->getStorageClass() == VarDecl::None ||
432 Old->getStorageClass() == VarDecl::Static))
Steve Naroffb00247f2008-01-30 00:44:01 +0000433 OldIsTentative = true;
434
435 // FIXME: this check doesn't work (since the initializer hasn't been
436 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
437 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
438 // thrown out the old decl.
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000439 if (!New->getInit() &&
440 (New->getStorageClass() == VarDecl::None ||
441 New->getStorageClass() == VarDecl::Static))
Steve Naroffb00247f2008-01-30 00:44:01 +0000442 ; // change to NewIsTentative = true; once the code is moved.
443
444 if (NewIsTentative || OldIsTentative)
445 return New;
446 }
Steve Naroff89301de2008-05-12 22:36:43 +0000447 // Handle __private_extern__ just like extern.
Steve Naroffb00247f2008-01-30 00:44:01 +0000448 if (Old->getStorageClass() != VarDecl::Extern &&
Steve Naroff89301de2008-05-12 22:36:43 +0000449 Old->getStorageClass() != VarDecl::PrivateExtern &&
450 New->getStorageClass() != VarDecl::Extern &&
451 New->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner4b009652007-07-25 00:24:17 +0000452 Diag(New->getLocation(), diag::err_redefinition, New->getName());
453 Diag(Old->getLocation(), diag::err_previous_definition);
454 }
455 return New;
456}
457
Chris Lattner3e254fb2008-04-08 04:40:51 +0000458/// CheckParmsForFunctionDef - Check that the parameters of the given
459/// function are appropriate for the definition of a function. This
460/// takes care of any checks that cannot be performed on the
461/// declaration itself, e.g., that the types of each of the function
462/// parameters are complete.
463bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
464 bool HasInvalidParm = false;
465 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
466 ParmVarDecl *Param = FD->getParamDecl(p);
467
468 // C99 6.7.5.3p4: the parameters in a parameter type list in a
469 // function declarator that is part of a function definition of
470 // that function shall not have incomplete type.
471 if (Param->getType()->isIncompleteType() &&
472 !Param->isInvalidDecl()) {
473 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
474 Param->getType().getAsString());
475 Param->setInvalidDecl();
476 HasInvalidParm = true;
477 }
478 }
479
480 return HasInvalidParm;
481}
482
483/// CreateImplicitParameter - Creates an implicit function parameter
484/// in the scope S and with the given type. This routine is used, for
485/// example, to create the implicit "self" parameter in an Objective-C
486/// method.
487ParmVarDecl *
488Sema::CreateImplicitParameter(Scope *S, IdentifierInfo *Id,
489 SourceLocation IdLoc, QualType Type) {
490 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, IdLoc, Id, Type,
491 VarDecl::None, 0, 0);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000492 if (Id)
493 PushOnScopeChains(New, S);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000494
495 return New;
496}
497
Chris Lattner4b009652007-07-25 00:24:17 +0000498/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
499/// no declarator (e.g. "struct foo;") is parsed.
500Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
501 // TODO: emit error on 'int;' or 'const enum foo;'.
502 // TODO: emit error on 'typedef int;'
503 // if (!DS.isMissingDeclaratorOk()) Diag(...);
504
Steve Naroffedafc0b2007-11-17 21:37:36 +0000505 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Chris Lattner4b009652007-07-25 00:24:17 +0000506}
507
Steve Narofff0b23542008-01-10 22:15:12 +0000508bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000509 // Get the type before calling CheckSingleAssignmentConstraints(), since
510 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +0000511 QualType InitType = Init->getType();
Steve Naroffe14e5542007-09-02 02:04:30 +0000512
Chris Lattner005ed752008-01-04 18:04:52 +0000513 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
514 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
515 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +0000516}
517
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000518bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
Steve Narofff0b23542008-01-10 22:15:12 +0000519 QualType ElementType) {
Chris Lattnerba0f1cb2007-12-11 23:15:04 +0000520 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Narofff0b23542008-01-10 22:15:12 +0000521 if (CheckSingleInitializer(expr, ElementType))
Chris Lattnerba0f1cb2007-12-11 23:15:04 +0000522 return true; // types weren't compatible.
523
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000524 if (savExpr != expr) // The type was promoted, update initializer list.
525 IList->setInit(slot, expr);
Steve Naroff509d0b52007-09-04 02:20:04 +0000526 return false;
527}
528
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000529bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Eli Friedman8ff07782008-02-15 18:16:39 +0000530 if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000531 // C99 6.7.8p14. We have an array of character type with unknown size
532 // being initialized to a string literal.
533 llvm::APSInt ConstVal(32);
534 ConstVal = strLiteral->getByteLength() + 1;
535 // Return a new array type (C99 6.7.8p22).
Eli Friedman8ff07782008-02-15 18:16:39 +0000536 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000537 ArrayType::Normal, 0);
538 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
539 // C99 6.7.8p14. We have an array of character type with known size.
540 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
541 Diag(strLiteral->getSourceRange().getBegin(),
542 diag::warn_initializer_string_for_char_array_too_long,
543 strLiteral->getSourceRange());
544 } else {
545 assert(0 && "HandleStringLiteralInit(): Invalid array type");
546 }
547 // Set type from "char *" to "constant array of char".
548 strLiteral->setType(DeclT);
549 // For now, we always return false (meaning success).
550 return false;
551}
552
553StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000554 const ArrayType *AT = DeclType->getAsArrayType();
Steve Narofff3cb5142008-01-25 00:51:06 +0000555 if (AT && AT->getElementType()->isCharType()) {
556 return dyn_cast<StringLiteral>(Init);
557 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000558 return 0;
559}
560
Steve Narofff3cb5142008-01-25 00:51:06 +0000561// CheckInitializerListTypes - Checks the types of elements of an initializer
562// list. This function is recursive: it calls itself to initialize subelements
563// of aggregate types. Note that the topLevel parameter essentially refers to
564// whether this expression "owns" the initializer list passed in, or if this
565// initialization is taking elements out of a parent initializer. Each
566// call to this function adds zero or more to startIndex, reports any errors,
567// and returns true if it found any inconsistent types.
568bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
569 bool topLevel, unsigned& startIndex) {
Steve Naroffcb69fb72007-12-10 22:44:33 +0000570 bool hadError = false;
Steve Narofff3cb5142008-01-25 00:51:06 +0000571
572 if (DeclType->isScalarType()) {
573 // The simplest case: initializing a single scalar
574 if (topLevel) {
575 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
576 IList->getSourceRange());
577 }
578 if (startIndex < IList->getNumInits()) {
579 Expr* expr = IList->getInit(startIndex);
580 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
581 // FIXME: Should an error be reported here instead?
582 unsigned newIndex = 0;
583 CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
584 } else {
585 hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
586 }
587 ++startIndex;
588 }
589 // FIXME: Should an error be reported for empty initializer list + scalar?
590 } else if (DeclType->isVectorType()) {
591 if (startIndex < IList->getNumInits()) {
592 const VectorType *VT = DeclType->getAsVectorType();
593 int maxElements = VT->getNumElements();
594 QualType elementType = VT->getElementType();
595
596 for (int i = 0; i < maxElements; ++i) {
597 // Don't attempt to go past the end of the init list
598 if (startIndex >= IList->getNumInits())
599 break;
600 Expr* expr = IList->getInit(startIndex);
601 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
602 unsigned newIndex = 0;
603 hadError |= CheckInitializerListTypes(SubInitList, elementType,
604 true, newIndex);
605 ++startIndex;
606 } else {
607 hadError |= CheckInitializerListTypes(IList, elementType,
608 false, startIndex);
609 }
610 }
611 }
612 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
613 if (DeclType->isStructureType() || DeclType->isUnionType()) {
Steve Naroffedce4ec2008-01-28 02:00:41 +0000614 if (startIndex < IList->getNumInits() && !topLevel &&
615 Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
616 DeclType)) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000617 // We found a compatible struct; per the standard, this initializes the
618 // struct. (The C standard technically says that this only applies for
619 // initializers for declarations with automatic scope; however, this
620 // construct is unambiguous anyway because a struct cannot contain
621 // a type compatible with itself. We'll output an error when we check
622 // if the initializer is constant.)
623 // FIXME: Is a call to CheckSingleInitializer required here?
624 ++startIndex;
625 } else {
626 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffee467032008-02-11 00:06:17 +0000627
Steve Naroff576df292008-02-11 21:52:37 +0000628 // If the record is invalid, some of it's members are invalid. To avoid
629 // confusion, we forgo checking the intializer for the entire record.
Steve Naroffee467032008-02-11 00:06:17 +0000630 if (structDecl->isInvalidDecl())
631 return true;
632
Steve Narofff3cb5142008-01-25 00:51:06 +0000633 // If structDecl is a forward declaration, this loop won't do anything;
634 // That's okay, because an error should get printed out elsewhere. It
635 // might be worthwhile to skip over the rest of the initializer, though.
636 int numMembers = structDecl->getNumMembers() -
637 structDecl->hasFlexibleArrayMember();
638 for (int i = 0; i < numMembers; i++) {
639 // Don't attempt to go past the end of the init list
640 if (startIndex >= IList->getNumInits())
641 break;
642 FieldDecl * curField = structDecl->getMember(i);
643 if (!curField->getIdentifier()) {
644 // Don't initialize unnamed fields, e.g. "int : 20;"
645 continue;
646 }
647 QualType fieldType = curField->getType();
648 Expr* expr = IList->getInit(startIndex);
649 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
650 unsigned newStart = 0;
651 hadError |= CheckInitializerListTypes(SubInitList, fieldType,
652 true, newStart);
653 ++startIndex;
654 } else {
655 hadError |= CheckInitializerListTypes(IList, fieldType,
656 false, startIndex);
657 }
658 if (DeclType->isUnionType())
659 break;
660 }
661 // FIXME: Implement flexible array initialization GCC extension (it's a
662 // really messy extension to implement, unfortunately...the necessary
663 // information isn't actually even here!)
664 }
665 } else if (DeclType->isArrayType()) {
666 // Check for the special-case of initializing an array with a string.
667 if (startIndex < IList->getNumInits()) {
668 if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
669 DeclType)) {
670 CheckStringLiteralInit(lit, DeclType);
671 ++startIndex;
672 if (topLevel && startIndex < IList->getNumInits()) {
673 // We have leftover initializers; warn
674 Diag(IList->getInit(startIndex)->getLocStart(),
675 diag::err_excess_initializers_in_char_array_initializer,
676 IList->getInit(startIndex)->getSourceRange());
677 }
678 return false;
679 }
680 }
681 int maxElements;
Eli Friedman8ff07782008-02-15 18:16:39 +0000682 if (DeclType->isIncompleteArrayType()) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000683 // FIXME: use a proper constant
684 maxElements = 0x7FFFFFFF;
Chris Lattnerb9716a62008-02-20 23:17:35 +0000685 } else if (const VariableArrayType *VAT =
686 DeclType->getAsVariableArrayType()) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000687 // Check for VLAs; in standard C it would be possible to check this
688 // earlier, but I don't know where clang accepts VLAs (gcc accepts
689 // them in all sorts of strange places).
Eli Friedman8ff07782008-02-15 18:16:39 +0000690 Diag(VAT->getSizeExpr()->getLocStart(),
691 diag::err_variable_object_no_init,
692 VAT->getSizeExpr()->getSourceRange());
693 hadError = true;
694 maxElements = 0x7FFFFFFF;
Steve Narofff3cb5142008-01-25 00:51:06 +0000695 } else {
696 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
697 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
698 }
699 QualType elementType = DeclType->getAsArrayType()->getElementType();
700 int numElements = 0;
701 for (int i = 0; i < maxElements; ++i, ++numElements) {
702 // Don't attempt to go past the end of the init list
703 if (startIndex >= IList->getNumInits())
704 break;
705 Expr* expr = IList->getInit(startIndex);
706 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
707 unsigned newIndex = 0;
708 hadError |= CheckInitializerListTypes(SubInitList, elementType,
709 true, newIndex);
710 ++startIndex;
711 } else {
712 hadError |= CheckInitializerListTypes(IList, elementType,
713 false, startIndex);
714 }
715 }
Eli Friedmane0079792008-02-15 12:53:51 +0000716 if (DeclType->isIncompleteArrayType()) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000717 // If this is an incomplete array type, the actual type needs to
718 // be calculated here
719 if (numElements == 0) {
720 // Sizing an array implicitly to zero is not allowed
721 // (It could in theory be allowed, but it doesn't really matter.)
722 Diag(IList->getLocStart(),
723 diag::err_at_least_one_initializer_needed_to_size_array);
724 hadError = true;
725 } else {
726 llvm::APSInt ConstVal(32);
727 ConstVal = numElements;
728 DeclType = Context.getConstantArrayType(elementType, ConstVal,
729 ArrayType::Normal, 0);
730 }
731 }
732 } else {
733 assert(0 && "Aggregate that isn't a function or array?!");
734 }
735 } else {
736 // In C, all types are either scalars or aggregates, but
737 // additional handling is needed here for C++ (and possibly others?).
738 assert(0 && "Unsupported initializer type");
739 }
740
741 // If this init list is a base list, we set the type; an initializer doesn't
742 // fundamentally have a type, but this makes the ASTs a bit easier to read
743 if (topLevel)
744 IList->setType(DeclType);
745
746 if (topLevel && startIndex < IList->getNumInits()) {
747 // We have leftover initializers; warn
748 Diag(IList->getInit(startIndex)->getLocStart(),
749 diag::warn_excess_initializers,
750 IList->getInit(startIndex)->getSourceRange());
751 }
752 return hadError;
753}
754
755bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroff8e9337f2008-01-21 23:53:58 +0000756 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
757 // of unknown size ("[]") or an object type that is not a variable array type.
Eli Friedman8ff07782008-02-15 18:16:39 +0000758 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
Steve Naroff8e9337f2008-01-21 23:53:58 +0000759 return Diag(VAT->getSizeExpr()->getLocStart(),
760 diag::err_variable_object_no_init,
761 VAT->getSizeExpr()->getSourceRange());
762
Steve Naroffcb69fb72007-12-10 22:44:33 +0000763 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
764 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000765 // FIXME: Handle wide strings
766 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
767 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +0000768
769 if (DeclType->isArrayType())
770 return Diag(Init->getLocStart(),
771 diag::err_array_init_list_required,
772 Init->getSourceRange());
773
Steve Narofff0b23542008-01-10 22:15:12 +0000774 return CheckSingleInitializer(Init, DeclType);
Steve Naroffcb69fb72007-12-10 22:44:33 +0000775 }
Eli Friedman0fecfde2008-05-19 20:29:35 +0000776#if 0
Steve Narofff3cb5142008-01-25 00:51:06 +0000777 unsigned newIndex = 0;
778 return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000779#else
780 InitListChecker CheckInitList(this, InitList, DeclType);
781 return CheckInitList.HadError();
782#endif
Steve Naroffe14e5542007-09-02 02:04:30 +0000783}
784
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +0000785Sema::DeclTy *
Steve Naroff0acc9c92007-09-15 18:49:24 +0000786Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000787 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattner4b009652007-07-25 00:24:17 +0000788 IdentifierInfo *II = D.getIdentifier();
789
790 // All of these full declarators require an identifier. If it doesn't have
791 // one, the ParsedFreeStandingDeclSpec action should be used.
792 if (II == 0) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000793 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner87492f42007-08-28 06:17:15 +0000794 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000795 D.getDeclSpec().getSourceRange(), D.getSourceRange());
796 return 0;
797 }
798
Chris Lattnera7549902007-08-26 06:24:45 +0000799 // The scope passed in may not be a decl scope. Zip up the scope tree until
800 // we find one that is.
801 while ((S->getFlags() & Scope::DeclScope) == 0)
802 S = S->getParent();
803
Chris Lattner4b009652007-07-25 00:24:17 +0000804 // See if this is a redefinition of a variable in the same scope.
Steve Naroff6384a012008-04-02 14:35:35 +0000805 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000806 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000807 bool InvalidDecl = false;
Douglas Gregor1d661552008-04-13 21:07:44 +0000808
809 // In C++, the previous declaration we find might be a tag type
810 // (class or enum). In this case, the new declaration will hide the
811 // tag type.
812 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
813 PrevDecl = 0;
814
Chris Lattner82bb4792007-11-14 06:34:38 +0000815 QualType R = GetTypeForDeclarator(D, S);
816 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
817
Chris Lattner4b009652007-07-25 00:24:17 +0000818 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000819 // Check that there are no default arguments (C++ only).
820 if (getLangOptions().CPlusPlus)
821 CheckExtraCXXDefaultArguments(D);
822
Chris Lattner82bb4792007-11-14 06:34:38 +0000823 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner4b009652007-07-25 00:24:17 +0000824 if (!NewTD) return 0;
825
826 // Handle attributes prior to checking for duplicates in MergeVarDecl
827 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
828 D.getAttributes());
Steve Narofff8a09432008-01-09 23:34:55 +0000829 // Merge the decl with the existing one if appropriate. If the decl is
830 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000831 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000832 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
833 if (NewTD == 0) return 0;
834 }
835 New = NewTD;
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000836 if (S->getFnParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000837 // C99 6.7.7p2: If a typedef name specifies a variably modified type
838 // then it shall have block scope.
Eli Friedmane0079792008-02-15 12:53:51 +0000839 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
840 // FIXME: Diagnostic needs to be fixed.
841 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroff5eb879b2007-08-31 17:20:07 +0000842 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000843 }
844 }
Chris Lattner82bb4792007-11-14 06:34:38 +0000845 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner265c8172007-09-27 15:15:46 +0000846 FunctionDecl::StorageClass SC = FunctionDecl::None;
Chris Lattner4b009652007-07-25 00:24:17 +0000847 switch (D.getDeclSpec().getStorageClassSpec()) {
848 default: assert(0 && "Unknown storage class!");
849 case DeclSpec::SCS_auto:
850 case DeclSpec::SCS_register:
851 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
852 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000853 InvalidDecl = true;
854 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000855 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
856 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
857 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroffd404c352008-01-28 21:57:15 +0000858 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Chris Lattner4b009652007-07-25 00:24:17 +0000859 }
860
Chris Lattner4c7802b2008-03-15 21:24:04 +0000861 bool isInline = D.getDeclSpec().isInlineSpecified();
Chris Lattnereee57c02008-04-04 06:12:32 +0000862 FunctionDecl *NewFD = FunctionDecl::Create(Context, CurContext,
863 D.getIdentifierLoc(),
Chris Lattner4c7802b2008-03-15 21:24:04 +0000864 II, R, SC, isInline,
865 LastDeclarator);
Ted Kremenek117f1862008-02-27 22:18:07 +0000866 // Handle attributes.
Ted Kremenek117f1862008-02-27 22:18:07 +0000867 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
868 D.getAttributes());
Chris Lattner3e254fb2008-04-08 04:40:51 +0000869
870 // Copy the parameter declarations from the declarator D to
871 // the function declaration NewFD, if they are available.
872 if (D.getNumTypeObjects() > 0 &&
873 D.getTypeObject(0).Fun.hasPrototype) {
874 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
875
876 // Create Decl objects for each parameter, adding them to the
877 // FunctionDecl.
878 llvm::SmallVector<ParmVarDecl*, 16> Params;
879
880 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
881 // function that takes no arguments, not a function that takes a
Chris Lattner97316c02008-04-10 02:22:51 +0000882 // single void argument.
Eli Friedman910758e2008-05-22 08:54:03 +0000883 // We let through "const void" here because Sema::GetTypeForDeclarator
884 // already checks for that case.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000885 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
886 FTI.ArgInfo[0].Param &&
Chris Lattner3e254fb2008-04-08 04:40:51 +0000887 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
888 // empty arg list, don't push any params.
Chris Lattner97316c02008-04-10 02:22:51 +0000889 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
890
Chris Lattnerda7b5f02008-04-10 02:26:16 +0000891 // In C++, the empty parameter-type-list must be spelled "void"; a
892 // typedef of void is not permitted.
893 if (getLangOptions().CPlusPlus &&
Eli Friedman910758e2008-05-22 08:54:03 +0000894 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner97316c02008-04-10 02:22:51 +0000895 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
896 }
897
Chris Lattner3e254fb2008-04-08 04:40:51 +0000898 } else {
899 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
900 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
901 }
902
903 NewFD->setParams(&Params[0], Params.size());
904 }
905
Steve Narofff8a09432008-01-09 23:34:55 +0000906 // Merge the decl with the existing one if appropriate. Since C functions
907 // are in a flat namespace, make sure we consider decls in outer scopes.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000908 if (PrevDecl &&
909 (!getLangOptions().CPlusPlus ||
910 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) ) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000911 bool Redeclaration = false;
912 NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration);
Chris Lattner4b009652007-07-25 00:24:17 +0000913 if (NewFD == 0) return 0;
Douglas Gregor42214c52008-04-21 02:02:58 +0000914 if (Redeclaration) {
915 // Note that the new declaration is a redeclaration of the
916 // older declaration. Then return the older declaration: the
917 // new one is only kept within the set of previous
918 // declarations for this function.
919 FunctionDecl *OldFD = (FunctionDecl *)PrevDecl;
920 OldFD->AddRedeclaration(NewFD);
921 return OldFD;
922 }
Chris Lattner4b009652007-07-25 00:24:17 +0000923 }
924 New = NewFD;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000925
926 // In C++, check default arguments now that we have merged decls.
927 if (getLangOptions().CPlusPlus)
928 CheckCXXDefaultArguments(NewFD);
Chris Lattner4b009652007-07-25 00:24:17 +0000929 } else {
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000930 // Check that there are no default arguments (C++ only).
931 if (getLangOptions().CPlusPlus)
932 CheckExtraCXXDefaultArguments(D);
933
Ted Kremenek42730c52008-01-07 19:49:32 +0000934 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +0000935 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
936 D.getIdentifier()->getName());
937 InvalidDecl = true;
938 }
Chris Lattner4b009652007-07-25 00:24:17 +0000939
940 VarDecl *NewVD;
941 VarDecl::StorageClass SC;
942 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner48d225c2008-03-15 21:10:16 +0000943 default: assert(0 && "Unknown storage class!");
944 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
945 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
946 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
947 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
948 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
949 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000950 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000951 if (S->getFnParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000952 // C99 6.9p2: The storage-class specifiers auto and register shall not
953 // appear in the declaration specifiers in an external declaration.
954 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
955 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
956 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000957 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000958 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000959 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
960 II, R, SC, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +0000961 } else {
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000962 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
963 II, R, SC, LastDeclarator);
Steve Naroffcae537d2007-08-28 18:45:29 +0000964 }
Chris Lattner4b009652007-07-25 00:24:17 +0000965 // Handle attributes prior to checking for duplicates in MergeVarDecl
966 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
967 D.getAttributes());
Nate Begemanea583262008-03-14 18:07:10 +0000968
969 // Emit an error if an address space was applied to decl with local storage.
970 // This includes arrays of objects with address space qualifiers, but not
971 // automatic variables that point to other address spaces.
972 // ISO/IEC TR 18037 S5.1.2
Nate Begemanefc11212008-03-25 18:36:32 +0000973 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
974 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
975 InvalidDecl = true;
Nate Begeman06068192008-03-14 00:22:18 +0000976 }
Steve Narofff8a09432008-01-09 23:34:55 +0000977 // Merge the decl with the existing one if appropriate. If the decl is
978 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000979 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000980 NewVD = MergeVarDecl(NewVD, PrevDecl);
981 if (NewVD == 0) return 0;
982 }
Chris Lattner4b009652007-07-25 00:24:17 +0000983 New = NewVD;
984 }
985
986 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000987 if (II)
988 PushOnScopeChains(New, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000989 // If any semantic error occurred, mark the decl as invalid.
990 if (D.getInvalidType() || InvalidDecl)
991 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +0000992
993 return New;
994}
995
Eli Friedman02c22ce2008-05-20 13:48:25 +0000996bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
997 switch (Init->getStmtClass()) {
998 default:
999 Diag(Init->getExprLoc(),
1000 diag::err_init_element_not_constant, Init->getSourceRange());
1001 return true;
1002 case Expr::ParenExprClass: {
1003 const ParenExpr* PE = cast<ParenExpr>(Init);
1004 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1005 }
1006 case Expr::CompoundLiteralExprClass:
1007 return cast<CompoundLiteralExpr>(Init)->isFileScope();
1008 case Expr::DeclRefExprClass: {
1009 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman8cb86e32008-05-21 03:39:11 +00001010 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1011 if (VD->hasGlobalStorage())
1012 return false;
1013 Diag(Init->getExprLoc(),
1014 diag::err_init_element_not_constant, Init->getSourceRange());
1015 return true;
1016 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001017 if (isa<FunctionDecl>(D))
1018 return false;
1019 Diag(Init->getExprLoc(),
1020 diag::err_init_element_not_constant, Init->getSourceRange());
Steve Narofff0b23542008-01-10 22:15:12 +00001021 return true;
1022 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001023 case Expr::MemberExprClass: {
1024 const MemberExpr *M = cast<MemberExpr>(Init);
1025 if (M->isArrow())
1026 return CheckAddressConstantExpression(M->getBase());
1027 return CheckAddressConstantExpressionLValue(M->getBase());
1028 }
1029 case Expr::ArraySubscriptExprClass: {
1030 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1031 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1032 return CheckAddressConstantExpression(ASE->getBase()) ||
1033 CheckArithmeticConstantExpression(ASE->getIdx());
1034 }
1035 case Expr::StringLiteralClass:
1036 case Expr::PreDefinedExprClass:
1037 return false;
1038 case Expr::UnaryOperatorClass: {
1039 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1040
1041 // C99 6.6p9
1042 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman8cb86e32008-05-21 03:39:11 +00001043 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001044
1045 Diag(Init->getExprLoc(),
1046 diag::err_init_element_not_constant, Init->getSourceRange());
1047 return true;
1048 }
1049 }
1050}
1051
1052bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1053 switch (Init->getStmtClass()) {
1054 default:
1055 Diag(Init->getExprLoc(),
1056 diag::err_init_element_not_constant, Init->getSourceRange());
1057 return true;
1058 case Expr::ParenExprClass: {
1059 const ParenExpr* PE = cast<ParenExpr>(Init);
1060 return CheckAddressConstantExpression(PE->getSubExpr());
1061 }
1062 case Expr::StringLiteralClass:
1063 case Expr::ObjCStringLiteralClass:
1064 return false;
1065 case Expr::CallExprClass: {
1066 const CallExpr *CE = cast<CallExpr>(Init);
1067 if (CE->isBuiltinConstantExpr())
1068 return false;
1069 Diag(Init->getExprLoc(),
1070 diag::err_init_element_not_constant, Init->getSourceRange());
1071 return true;
1072 }
1073 case Expr::UnaryOperatorClass: {
1074 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1075
1076 // C99 6.6p9
1077 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1078 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1079
1080 if (Exp->getOpcode() == UnaryOperator::Extension)
1081 return CheckAddressConstantExpression(Exp->getSubExpr());
1082
1083 Diag(Init->getExprLoc(),
1084 diag::err_init_element_not_constant, Init->getSourceRange());
1085 return true;
1086 }
1087 case Expr::BinaryOperatorClass: {
1088 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1089 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1090
1091 Expr *PExp = Exp->getLHS();
1092 Expr *IExp = Exp->getRHS();
1093 if (IExp->getType()->isPointerType())
1094 std::swap(PExp, IExp);
1095
1096 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1097 return CheckAddressConstantExpression(PExp) ||
1098 CheckArithmeticConstantExpression(IExp);
1099 }
1100 case Expr::ImplicitCastExprClass: {
1101 const Expr* SubExpr = cast<ImplicitCastExpr>(Init)->getSubExpr();
1102
1103 // Check for implicit promotion
1104 if (SubExpr->getType()->isFunctionType() ||
1105 SubExpr->getType()->isArrayType())
1106 return CheckAddressConstantExpressionLValue(SubExpr);
1107
1108 // Check for pointer->pointer cast
1109 if (SubExpr->getType()->isPointerType())
1110 return CheckAddressConstantExpression(SubExpr);
1111
1112 if (SubExpr->getType()->isArithmeticType())
1113 return CheckArithmeticConstantExpression(SubExpr);
1114
1115 Diag(Init->getExprLoc(),
1116 diag::err_init_element_not_constant, Init->getSourceRange());
1117 return true;
1118 }
1119 case Expr::CastExprClass: {
1120 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
1121
1122 // Check for pointer->pointer cast
1123 if (SubExpr->getType()->isPointerType())
1124 return CheckAddressConstantExpression(SubExpr);
1125
1126 // FIXME: Should we pedwarn for (int*)(0+0)?
1127 if (SubExpr->getType()->isArithmeticType())
1128 return CheckArithmeticConstantExpression(SubExpr);
1129
1130 Diag(Init->getExprLoc(),
1131 diag::err_init_element_not_constant, Init->getSourceRange());
1132 return true;
1133 }
1134 case Expr::ConditionalOperatorClass: {
1135 // FIXME: Should we pedwarn here?
1136 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1137 if (!Exp->getCond()->getType()->isArithmeticType()) {
1138 Diag(Init->getExprLoc(),
1139 diag::err_init_element_not_constant, Init->getSourceRange());
1140 return true;
1141 }
1142 if (CheckArithmeticConstantExpression(Exp->getCond()))
1143 return true;
1144 if (Exp->getLHS() &&
1145 CheckAddressConstantExpression(Exp->getLHS()))
1146 return true;
1147 return CheckAddressConstantExpression(Exp->getRHS());
1148 }
1149 case Expr::AddrLabelExprClass:
1150 return false;
1151 }
1152}
1153
1154bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1155 switch (Init->getStmtClass()) {
1156 default:
1157 Diag(Init->getExprLoc(),
1158 diag::err_init_element_not_constant, Init->getSourceRange());
1159 return true;
1160 case Expr::ParenExprClass: {
1161 const ParenExpr* PE = cast<ParenExpr>(Init);
1162 return CheckArithmeticConstantExpression(PE->getSubExpr());
1163 }
1164 case Expr::FloatingLiteralClass:
1165 case Expr::IntegerLiteralClass:
1166 case Expr::CharacterLiteralClass:
1167 case Expr::ImaginaryLiteralClass:
1168 case Expr::TypesCompatibleExprClass:
1169 case Expr::CXXBoolLiteralExprClass:
1170 return false;
1171 case Expr::CallExprClass: {
1172 const CallExpr *CE = cast<CallExpr>(Init);
1173 if (CE->isBuiltinConstantExpr())
1174 return false;
1175 Diag(Init->getExprLoc(),
1176 diag::err_init_element_not_constant, Init->getSourceRange());
1177 return true;
1178 }
1179 case Expr::DeclRefExprClass: {
1180 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1181 if (isa<EnumConstantDecl>(D))
1182 return false;
1183 Diag(Init->getExprLoc(),
1184 diag::err_init_element_not_constant, Init->getSourceRange());
1185 return true;
1186 }
1187 case Expr::CompoundLiteralExprClass:
1188 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1189 // but vectors are allowed to be magic.
1190 if (Init->getType()->isVectorType())
1191 return false;
1192 Diag(Init->getExprLoc(),
1193 diag::err_init_element_not_constant, Init->getSourceRange());
1194 return true;
1195 case Expr::UnaryOperatorClass: {
1196 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1197
1198 switch (Exp->getOpcode()) {
1199 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1200 // See C99 6.6p3.
1201 default:
1202 Diag(Init->getExprLoc(),
1203 diag::err_init_element_not_constant, Init->getSourceRange());
1204 return true;
1205 case UnaryOperator::SizeOf:
1206 case UnaryOperator::AlignOf:
1207 case UnaryOperator::OffsetOf:
1208 // sizeof(E) is a constantexpr if and only if E is not evaluted.
1209 // See C99 6.5.3.4p2 and 6.6p3.
1210 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1211 return false;
1212 Diag(Init->getExprLoc(),
1213 diag::err_init_element_not_constant, Init->getSourceRange());
1214 return true;
1215 case UnaryOperator::Extension:
1216 case UnaryOperator::LNot:
1217 case UnaryOperator::Plus:
1218 case UnaryOperator::Minus:
1219 case UnaryOperator::Not:
1220 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1221 }
1222 }
1223 case Expr::SizeOfAlignOfTypeExprClass: {
1224 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1225 // Special check for void types, which are allowed as an extension
1226 if (Exp->getArgumentType()->isVoidType())
1227 return false;
1228 // alignof always evaluates to a constant.
1229 // FIXME: is sizeof(int[3.0]) a constant expression?
1230 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
1231 Diag(Init->getExprLoc(),
1232 diag::err_init_element_not_constant, Init->getSourceRange());
1233 return true;
1234 }
1235 return false;
1236 }
1237 case Expr::BinaryOperatorClass: {
1238 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1239
1240 if (Exp->getLHS()->getType()->isArithmeticType() &&
1241 Exp->getRHS()->getType()->isArithmeticType()) {
1242 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1243 CheckArithmeticConstantExpression(Exp->getRHS());
1244 }
1245
1246 Diag(Init->getExprLoc(),
1247 diag::err_init_element_not_constant, Init->getSourceRange());
1248 return true;
1249 }
1250 case Expr::ImplicitCastExprClass:
1251 case Expr::CastExprClass: {
1252 const Expr *SubExpr;
1253 if (const CastExpr *C = dyn_cast<CastExpr>(Init)) {
1254 SubExpr = C->getSubExpr();
1255 } else {
1256 SubExpr = cast<ImplicitCastExpr>(Init)->getSubExpr();
1257 }
1258
1259 if (SubExpr->getType()->isArithmeticType())
1260 return CheckArithmeticConstantExpression(SubExpr);
1261
1262 Diag(Init->getExprLoc(),
1263 diag::err_init_element_not_constant, Init->getSourceRange());
1264 return true;
1265 }
1266 case Expr::ConditionalOperatorClass: {
1267 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1268 if (CheckArithmeticConstantExpression(Exp->getCond()))
1269 return true;
1270 if (Exp->getLHS() &&
1271 CheckArithmeticConstantExpression(Exp->getLHS()))
1272 return true;
1273 return CheckArithmeticConstantExpression(Exp->getRHS());
1274 }
1275 }
1276}
1277
1278bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
1279 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1280 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1281 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1282
1283 if (Init->getType()->isReferenceType()) {
1284 // FIXME: Work out how the heck reference types work
1285 return false;
1286#if 0
1287 // A reference is constant if the address of the expression
1288 // is constant
1289 // We look through initlists here to simplify
1290 // CheckAddressConstantExpressionLValue.
1291 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1292 assert(Exp->getNumInits() > 0 &&
1293 "Refernce initializer cannot be empty");
1294 Init = Exp->getInit(0);
1295 }
1296 return CheckAddressConstantExpressionLValue(Init);
1297#endif
1298 }
1299
1300 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1301 unsigned numInits = Exp->getNumInits();
1302 for (unsigned i = 0; i < numInits; i++) {
1303 // FIXME: Need to get the type of the declaration for C++,
1304 // because it could be a reference?
1305 if (CheckForConstantInitializer(Exp->getInit(i),
1306 Exp->getInit(i)->getType()))
1307 return true;
1308 }
1309 return false;
1310 }
1311
1312 if (Init->isNullPointerConstant(Context))
1313 return false;
1314 if (Init->getType()->isArithmeticType()) {
1315 // Special check for pointer cast to int; we allow
1316 // an address constant cast to an integer if the integer
1317 // is of an appropriate width (this sort of code is apparently used
1318 // in some places).
1319 // FIXME: Add pedwarn?
Nuno Lopesa85587a2008-05-20 18:03:51 +00001320 Expr* SubE = 0;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001321 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 if (SubE && (SubE->getType()->isPointerType() ||
1326 SubE->getType()->isArrayType() ||
1327 SubE->getType()->isFunctionType())) {
1328 unsigned IntWidth = Context.getTypeSize(Init->getType());
1329 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1330 if (IntWidth >= PointerWidth)
1331 return CheckAddressConstantExpression(Init);
1332 }
1333
1334 return CheckArithmeticConstantExpression(Init);
1335 }
1336
1337 if (Init->getType()->isPointerType())
1338 return CheckAddressConstantExpression(Init);
1339
1340 if (Init->getType()->isArrayType())
1341 return false;
1342
1343 Diag(Init->getExprLoc(), diag::err_init_element_not_constant,
1344 Init->getSourceRange());
1345 return true;
Steve Narofff0b23542008-01-10 22:15:12 +00001346}
1347
Steve Naroff6a0e2092007-09-12 14:07:44 +00001348void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001349 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001350 Expr *Init = static_cast<Expr *>(init);
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001351 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +00001352
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001353 // If there is no declaration, there was an error parsing it. Just ignore
1354 // the initializer.
1355 if (RealDecl == 0) {
1356 delete Init;
1357 return;
1358 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001359
Steve Naroff420d0f52007-09-12 20:13:48 +00001360 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1361 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +00001362 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1363 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +00001364 RealDecl->setInvalidDecl();
1365 return;
1366 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001367 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +00001368 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +00001369 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001370 if (VDecl->isBlockVarDecl()) {
1371 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001372 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +00001373 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001374 VDecl->setInvalidDecl();
1375 } else if (!VDecl->isInvalidDecl()) {
Steve Narofff3cb5142008-01-25 00:51:06 +00001376 if (CheckInitializerTypes(Init, DclT))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001377 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00001378 if (SC == VarDecl::Static) // C99 6.7.8p4.
1379 CheckForConstantInitializer(Init, DclT);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001380 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001381 } else if (VDecl->isFileVarDecl()) {
1382 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +00001383 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001384 if (!VDecl->isInvalidDecl())
Steve Narofff3cb5142008-01-25 00:51:06 +00001385 if (CheckInitializerTypes(Init, DclT))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001386 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00001387
1388 // C99 6.7.8p4. All file scoped initializers need to be constant.
1389 CheckForConstantInitializer(Init, DclT);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001390 }
1391 // If the type changed, it means we had an incomplete type that was
1392 // completed by the initializer. For example:
1393 // int ary[] = { 1, 3, 5 };
1394 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +00001395 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001396 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +00001397 Init->setType(DclT);
1398 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001399
1400 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +00001401 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001402 return;
1403}
1404
Chris Lattner4b009652007-07-25 00:24:17 +00001405/// The declarators are chained together backwards, reverse the list.
1406Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1407 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001408 Decl *GroupDecl = static_cast<Decl*>(group);
1409 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +00001410 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +00001411
1412 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1413 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001414 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +00001415 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001416 else { // reverse the list.
1417 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +00001418 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001419 Group->setNextDeclarator(NewGroup);
1420 NewGroup = Group;
1421 Group = Next;
1422 }
1423 }
1424 // Perform semantic analysis that depends on having fully processed both
1425 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001426 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +00001427 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1428 if (!IDecl)
1429 continue;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001430 QualType T = IDecl->getType();
1431
1432 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1433 // static storage duration, it shall not have a variable length array.
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001434 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1435 IDecl->getStorageClass() == VarDecl::Static) {
Eli Friedman70f414d2008-02-15 19:53:52 +00001436 if (T->getAsVariableArrayType()) {
Eli Friedman8ff07782008-02-15 18:16:39 +00001437 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1438 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001439 }
1440 }
1441 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1442 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001443 if (IDecl->isBlockVarDecl() &&
1444 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001445 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner2f72aa02007-12-02 07:50:03 +00001446 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1447 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001448 IDecl->setInvalidDecl();
1449 }
1450 }
1451 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1452 // object that has file scope without an initializer, and without a
1453 // storage-class specifier or with the storage-class specifier "static",
1454 // constitutes a tentative definition. Note: A tentative definition with
1455 // external linkage is valid (C99 6.2.2p5).
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001456 if (IDecl && !IDecl->getInit() &&
1457 (IDecl->getStorageClass() == VarDecl::Static ||
1458 IDecl->getStorageClass() == VarDecl::None)) {
Eli Friedmane0079792008-02-15 12:53:51 +00001459 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +00001460 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1461 // array to be completed. Don't issue a diagnostic.
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001462 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff60685462008-01-18 20:40:52 +00001463 // C99 6.9.2p3: If the declaration of an identifier for an object is
1464 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1465 // declared type shall not be an incomplete type.
Chris Lattner2f72aa02007-12-02 07:50:03 +00001466 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1467 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001468 IDecl->setInvalidDecl();
1469 }
1470 }
Chris Lattner4b009652007-07-25 00:24:17 +00001471 }
1472 return NewGroup;
1473}
Steve Naroff91b03f72007-08-28 03:03:08 +00001474
Chris Lattner3e254fb2008-04-08 04:40:51 +00001475/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1476/// to introduce parameters into function prototype scope.
1477Sema::DeclTy *
1478Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
1479 DeclSpec &DS = D.getDeclSpec();
1480
1481 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1482 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1483 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1484 Diag(DS.getStorageClassSpecLoc(),
1485 diag::err_invalid_storage_class_in_func_decl);
1486 DS.ClearStorageClassSpecs();
1487 }
1488 if (DS.isThreadSpecified()) {
1489 Diag(DS.getThreadSpecLoc(),
1490 diag::err_invalid_storage_class_in_func_decl);
1491 DS.ClearStorageClassSpecs();
1492 }
1493
Douglas Gregor2b9422f2008-05-07 04:49:29 +00001494 // Check that there are no default arguments inside the type of this
1495 // parameter (C++ only).
1496 if (getLangOptions().CPlusPlus)
1497 CheckExtraCXXDefaultArguments(D);
1498
Chris Lattner3e254fb2008-04-08 04:40:51 +00001499 // In this context, we *do not* check D.getInvalidType(). If the declarator
1500 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1501 // though it will not reflect the user specified type.
1502 QualType parmDeclType = GetTypeForDeclarator(D, S);
1503
1504 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1505
Chris Lattner4b009652007-07-25 00:24:17 +00001506 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1507 // Can this happen for params? We already checked that they don't conflict
1508 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001509 IdentifierInfo *II = D.getIdentifier();
1510 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1511 if (S->isDeclScope(PrevDecl)) {
1512 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1513 dyn_cast<NamedDecl>(PrevDecl)->getName());
1514
1515 // Recover by removing the name
1516 II = 0;
1517 D.SetIdentifier(0, D.getIdentifierLoc());
1518 }
Chris Lattner4b009652007-07-25 00:24:17 +00001519 }
Steve Naroff94cd93f2007-08-07 22:44:21 +00001520
1521 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1522 // Doing the promotion here has a win and a loss. The win is the type for
1523 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1524 // code generator). The loss is the orginal type isn't preserved. For example:
1525 //
1526 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1527 // int blockvardecl[5];
1528 // sizeof(parmvardecl); // size == 4
1529 // sizeof(blockvardecl); // size == 20
1530 // }
1531 //
1532 // For expressions, all implicit conversions are captured using the
1533 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1534 //
1535 // FIXME: If a source translation tool needs to see the original type, then
1536 // we need to consider storing both types (in ParmVarDecl)...
1537 //
Chris Lattner19eb97e2008-04-02 05:18:44 +00001538 if (parmDeclType->isArrayType()) {
Chris Lattnerc08564a2008-01-02 22:50:48 +00001539 // int x[restrict 4] -> int *restrict
Chris Lattner19eb97e2008-04-02 05:18:44 +00001540 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattnerc08564a2008-01-02 22:50:48 +00001541 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00001542 parmDeclType = Context.getPointerType(parmDeclType);
1543
Chris Lattner3e254fb2008-04-08 04:40:51 +00001544 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1545 D.getIdentifierLoc(), II,
1546 parmDeclType, VarDecl::None,
1547 0, 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +00001548
Chris Lattner3e254fb2008-04-08 04:40:51 +00001549 if (D.getInvalidType())
Steve Naroffcae537d2007-08-28 18:45:29 +00001550 New->setInvalidDecl();
1551
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001552 if (II)
1553 PushOnScopeChains(New, S);
Nate Begeman9f3c4bb2008-02-17 21:20:31 +00001554
Nate Begemanc5b66682008-05-09 16:56:01 +00001555 HandleDeclAttributes(New, D.getDeclSpec().getAttributes(),
1556 D.getAttributes());
Chris Lattner4b009652007-07-25 00:24:17 +00001557 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001558
Chris Lattner4b009652007-07-25 00:24:17 +00001559}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00001560
Chris Lattnerea148702007-10-09 17:14:05 +00001561Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Chris Lattner4b009652007-07-25 00:24:17 +00001562 assert(CurFunctionDecl == 0 && "Function parsing confused");
1563 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1564 "Not a function declarator!");
1565 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001566
Chris Lattner4b009652007-07-25 00:24:17 +00001567 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1568 // for a K&R function.
1569 if (!FTI.hasPrototype) {
1570 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001571 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +00001572 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1573 FTI.ArgInfo[i].Ident->getName());
1574 // Implicitly declare the argument as type 'int' for lack of a better
1575 // type.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001576 DeclSpec DS;
1577 const char* PrevSpec; // unused
1578 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1579 PrevSpec);
1580 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1581 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1582 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Chris Lattner4b009652007-07-25 00:24:17 +00001583 }
1584 }
Chris Lattnerec9361f2008-02-17 19:31:09 +00001585
Chris Lattner4b009652007-07-25 00:24:17 +00001586 // Since this is a function definition, act as though we have information
1587 // about the arguments.
Chris Lattnerec9361f2008-02-17 19:31:09 +00001588 if (FTI.NumArgs)
1589 FTI.hasPrototype = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001590 } else {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001591 // FIXME: Diagnose arguments without names in C.
Chris Lattner4b009652007-07-25 00:24:17 +00001592 }
1593
1594 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00001595
1596 // See if this is a redefinition.
Steve Naroffe57c21a2008-04-01 23:04:06 +00001597 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroff6384a012008-04-02 14:35:35 +00001598 GlobalScope);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001599 if (PrevDcl && IdResolver.isDeclInScope(PrevDcl, CurContext)) {
1600 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) {
1601 const FunctionDecl *Definition;
1602 if (FD->getBody(Definition)) {
1603 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1604 D.getIdentifier()->getName());
1605 Diag(Definition->getLocation(), diag::err_previous_definition);
1606 }
Steve Naroff1d5bd642008-01-14 20:51:29 +00001607 }
1608 }
Steve Naroff4a712442008-02-12 01:09:36 +00001609 Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattner2d2216b2008-02-16 01:20:36 +00001610 FunctionDecl *FD = cast<FunctionDecl>(decl);
Chris Lattner4b009652007-07-25 00:24:17 +00001611 CurFunctionDecl = FD;
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001612 PushDeclContext(FD);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001613
1614 // Check the validity of our function parameters
1615 CheckParmsForFunctionDef(FD);
1616
1617 // Introduce our parameters into the function scope
1618 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1619 ParmVarDecl *Param = FD->getParamDecl(p);
1620 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001621 if (Param->getIdentifier())
1622 PushOnScopeChains(Param, FnBodyScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001623 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001624
Chris Lattner4b009652007-07-25 00:24:17 +00001625 return FD;
1626}
1627
Steve Naroff99ee4302007-11-11 23:20:51 +00001628Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1629 Decl *dcl = static_cast<Decl *>(D);
1630 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1631 FD->setBody((Stmt*)Body);
1632 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff8ba51142007-12-13 18:18:56 +00001633 CurFunctionDecl = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001634 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00001635 MD->setBody((Stmt*)Body);
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001636 CurMethodDecl = 0;
Steve Naroff8ba51142007-12-13 18:18:56 +00001637 }
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001638 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00001639 // Verify and clean out per-function state.
1640
1641 // Check goto/label use.
1642 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1643 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1644 // Verify that we have no forward references left. If so, there was a goto
1645 // or address of a label taken, but no definition of it. Label fwd
1646 // definitions are indicated with a null substmt.
1647 if (I->second->getSubStmt() == 0) {
1648 LabelStmt *L = I->second;
1649 // Emit error.
1650 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1651
1652 // At this point, we have gotos that use the bogus label. Stitch it into
1653 // the function body so that they aren't leaked and that the AST is well
1654 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00001655 if (Body) {
1656 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1657 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1658 } else {
1659 // The whole function wasn't parsed correctly, just delete this.
1660 delete L;
1661 }
Chris Lattner4b009652007-07-25 00:24:17 +00001662 }
1663 }
1664 LabelMap.clear();
1665
Steve Naroff99ee4302007-11-11 23:20:51 +00001666 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00001667}
1668
Chris Lattner4b009652007-07-25 00:24:17 +00001669/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1670/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +00001671ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1672 IdentifierInfo &II, Scope *S) {
Chris Lattnerdea31bf2008-05-05 21:18:06 +00001673 // Extension in C99. Legal in C90, but warn about it.
1674 if (getLangOptions().C99)
Chris Lattner4b009652007-07-25 00:24:17 +00001675 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattnerdea31bf2008-05-05 21:18:06 +00001676 else
Chris Lattner4b009652007-07-25 00:24:17 +00001677 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1678
1679 // FIXME: handle stuff like:
1680 // void foo() { extern float X(); }
1681 // void bar() { X(); } <-- implicit decl for X in another scope.
1682
1683 // Set a Declarator for the implicit definition: int foo();
1684 const char *Dummy;
1685 DeclSpec DS;
1686 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1687 Error = Error; // Silence warning.
1688 assert(!Error && "Error setting up implicit decl!");
1689 Declarator D(DS, Declarator::BlockContext);
1690 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1691 D.SetIdentifier(&II, Loc);
1692
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00001693 // Insert this function into translation-unit scope.
1694
1695 DeclContext *PrevDC = CurContext;
1696 CurContext = Context.getTranslationUnitDecl();
1697
Steve Naroff9104f3c2008-04-04 14:32:09 +00001698 FunctionDecl *FD =
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00001699 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroff9104f3c2008-04-04 14:32:09 +00001700 FD->setImplicit();
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00001701
1702 CurContext = PrevDC;
1703
Steve Naroff9104f3c2008-04-04 14:32:09 +00001704 return FD;
Chris Lattner4b009652007-07-25 00:24:17 +00001705}
1706
1707
Chris Lattner82bb4792007-11-14 06:34:38 +00001708TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff2591e1b2007-09-13 23:52:58 +00001709 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00001710 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001711 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00001712
1713 // Scope manipulation handled by caller.
Chris Lattnereee57c02008-04-04 06:12:32 +00001714 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1715 D.getIdentifierLoc(),
Chris Lattnere4650482008-03-15 06:12:44 +00001716 D.getIdentifier(),
Chris Lattner58114f02008-03-15 21:32:50 +00001717 T, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001718 if (D.getInvalidType())
1719 NewTD->setInvalidDecl();
1720 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00001721}
1722
Steve Naroff0acc9c92007-09-15 18:49:24 +00001723/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00001724/// former case, Name will be non-null. In the later case, Name will be null.
1725/// TagType indicates what kind of tag this is. TK indicates whether this is a
1726/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001727Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattner4b009652007-07-25 00:24:17 +00001728 SourceLocation KWLoc, IdentifierInfo *Name,
1729 SourceLocation NameLoc, AttributeList *Attr) {
1730 // If this is a use of an existing tag, it must have a name.
1731 assert((Name != 0 || TK == TK_Definition) &&
1732 "Nameless record must be a definition!");
1733
1734 Decl::Kind Kind;
1735 switch (TagType) {
1736 default: assert(0 && "Unknown tag type!");
1737 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1738 case DeclSpec::TST_union: Kind = Decl::Union; break;
Chris Lattner2e78db32008-04-13 18:59:07 +00001739 case DeclSpec::TST_class: Kind = Decl::Class; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001740 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1741 }
1742
1743 // If this is a named struct, check to see if there was a previous forward
1744 // declaration or definition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001745 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
1746 if (ScopedDecl *PrevDecl =
1747 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
Chris Lattner4b009652007-07-25 00:24:17 +00001748
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001749 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1750 "unexpected Decl type");
1751 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
1752 // If this is a use of a previous tag, or if the tag is already declared in
1753 // the same scope (so that the definition/declaration completes or
1754 // rementions the tag), reuse the decl.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001755 if (TK == TK_Reference ||
1756 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001757 // Make sure that this wasn't declared as an enum and now used as a struct
1758 // or something similar.
1759 if (PrevDecl->getKind() != Kind) {
1760 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1761 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1762 }
1763
1764 // If this is a use or a forward declaration, we're good.
1765 if (TK != TK_Definition)
1766 return PrevDecl;
Chris Lattner4b009652007-07-25 00:24:17 +00001767
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001768 // Diagnose attempts to redefine a tag.
1769 if (PrevTagDecl->isDefinition()) {
1770 Diag(NameLoc, diag::err_redefinition, Name->getName());
1771 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1772 // If this is a redefinition, recover by making this struct be
1773 // anonymous, which will make any later references get the previous
1774 // definition.
1775 Name = 0;
1776 } else {
1777 // Okay, this is definition of a previously declared or referenced tag.
1778 // Move the location of the decl to be the definition site.
1779 PrevDecl->setLocation(NameLoc);
1780 return PrevDecl;
1781 }
Chris Lattner4b009652007-07-25 00:24:17 +00001782 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001783 // If we get here, this is a definition of a new struct type in a nested
1784 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1785 // type.
1786 } else {
1787 // The tag name clashes with a namespace name, issue an error and recover
1788 // by making this tag be anonymous.
1789 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1790 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1791 Name = 0;
Chris Lattner4b009652007-07-25 00:24:17 +00001792 }
Chris Lattner4b009652007-07-25 00:24:17 +00001793 }
1794
1795 // If there is an identifier, use the location of the identifier as the
1796 // location of the decl, otherwise use the location of the struct/union
1797 // keyword.
1798 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1799
1800 // Otherwise, if this is the first time we've seen this tag, create the decl.
1801 TagDecl *New;
1802 switch (Kind) {
1803 default: assert(0 && "Unknown tag kind!");
1804 case Decl::Enum:
1805 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1806 // enum X { A, B, C } D; D should chain to X.
Chris Lattnereee57c02008-04-04 06:12:32 +00001807 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001808 // If this is an undefined enum, warn.
1809 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1810 break;
1811 case Decl::Union:
1812 case Decl::Struct:
1813 case Decl::Class:
1814 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1815 // struct X { int A; } D; D should chain to X.
Chris Lattnereee57c02008-04-04 06:12:32 +00001816 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001817 break;
1818 }
1819
1820 // If this has an identifier, add it to the scope stack.
1821 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00001822 // The scope passed in may not be a decl scope. Zip up the scope tree until
1823 // we find one that is.
1824 while ((S->getFlags() & Scope::DeclScope) == 0)
1825 S = S->getParent();
1826
1827 // Add it to the decl chain.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001828 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00001829 }
Chris Lattner33aad6e2008-02-06 00:51:33 +00001830
Anders Carlsson136cdc32008-02-16 00:29:18 +00001831 HandleDeclAttributes(New, Attr, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001832 return New;
1833}
1834
Steve Naroff0acc9c92007-09-15 18:49:24 +00001835/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00001836/// to create a FieldDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001837Sema::DeclTy *Sema::ActOnField(Scope *S,
Chris Lattner4b009652007-07-25 00:24:17 +00001838 SourceLocation DeclStart,
1839 Declarator &D, ExprTy *BitfieldWidth) {
1840 IdentifierInfo *II = D.getIdentifier();
1841 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00001842 SourceLocation Loc = DeclStart;
1843 if (II) Loc = D.getIdentifierLoc();
1844
1845 // FIXME: Unnamed fields can be handled in various different ways, for
1846 // example, unnamed unions inject all members into the struct namespace!
1847
1848
1849 if (BitWidth) {
1850 // TODO: Validate.
1851 //printf("WARNING: BITFIELDS IGNORED!\n");
1852
1853 // 6.7.2.1p3
1854 // 6.7.2.1p4
1855
1856 } else {
1857 // Not a bitfield.
1858
1859 // validate II.
1860
1861 }
1862
1863 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001864 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1865 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00001866
Chris Lattner4b009652007-07-25 00:24:17 +00001867 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1868 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00001869 if (T->isVariablyModifiedType()) {
1870 // FIXME: This diagnostic needs work
1871 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
Steve Naroff5eb879b2007-08-31 17:20:07 +00001872 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001873 }
Chris Lattner4b009652007-07-25 00:24:17 +00001874 // FIXME: Chain fielddecls together.
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00001875 FieldDecl *NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff75494892007-09-11 21:17:26 +00001876
Anders Carlsson136cdc32008-02-16 00:29:18 +00001877 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1878 D.getAttributes());
1879
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001880 if (D.getInvalidType() || InvalidDecl)
1881 NewFD->setInvalidDecl();
1882 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00001883}
1884
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001885/// TranslateIvarVisibility - Translate visibility from a token ID to an
1886/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00001887static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001888TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00001889 switch (ivarVisibility) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001890 case tok::objc_private: return ObjCIvarDecl::Private;
1891 case tok::objc_public: return ObjCIvarDecl::Public;
1892 case tok::objc_protected: return ObjCIvarDecl::Protected;
1893 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001894 default: assert(false && "Unknown visitibility kind");
Steve Naroffffeaa552007-09-14 23:09:53 +00001895 }
1896}
1897
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00001898/// ActOnIvar - Each ivar field of an objective-c class is passed into this
1899/// in order to create an IvarDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001900Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00001901 SourceLocation DeclStart,
1902 Declarator &D, ExprTy *BitfieldWidth,
1903 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001904 IdentifierInfo *II = D.getIdentifier();
1905 Expr *BitWidth = (Expr*)BitfieldWidth;
1906 SourceLocation Loc = DeclStart;
1907 if (II) Loc = D.getIdentifierLoc();
1908
1909 // FIXME: Unnamed fields can be handled in various different ways, for
1910 // example, unnamed unions inject all members into the struct namespace!
1911
1912
1913 if (BitWidth) {
1914 // TODO: Validate.
1915 //printf("WARNING: BITFIELDS IGNORED!\n");
1916
1917 // 6.7.2.1p3
1918 // 6.7.2.1p4
1919
1920 } else {
1921 // Not a bitfield.
1922
1923 // validate II.
1924
1925 }
1926
1927 QualType T = GetTypeForDeclarator(D, S);
1928 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1929 bool InvalidDecl = false;
1930
1931 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1932 // than a variably modified type.
1933 if (T->isVariablyModifiedType()) {
1934 // FIXME: This diagnostic needs work
1935 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1936 InvalidDecl = true;
1937 }
1938
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00001939 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001940
1941 HandleDeclAttributes(NewID, D.getDeclSpec().getAttributes(),
1942 D.getAttributes());
1943
1944 if (D.getInvalidType() || InvalidDecl)
1945 NewID->setInvalidDecl();
1946 // If we have visibility info, make sure the AST is set accordingly.
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00001947 if (Visibility != tok::objc_not_keyword)
1948 NewID->setAccessControl(TranslateIvarVisibility(Visibility));
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001949 return NewID;
1950}
1951
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00001952void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001953 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00001954 DeclTy **Fields, unsigned NumFields,
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001955 SourceLocation LBrac, SourceLocation RBrac) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001956 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1957 assert(EnclosingDecl && "missing record or interface decl");
1958 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1959
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001960 if (Record && Record->isDefinition()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001961 // Diagnose code like:
1962 // struct S { struct S {} X; };
1963 // We discover this when we complete the outer S. Reject and ignore the
1964 // outer S.
1965 Diag(Record->getLocation(), diag::err_nested_redefinition,
1966 Record->getKindName());
1967 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00001968 Record->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001969 return;
1970 }
Chris Lattner4b009652007-07-25 00:24:17 +00001971 // Verify that all the fields are okay.
1972 unsigned NumNamedMembers = 0;
1973 llvm::SmallVector<FieldDecl*, 32> RecFields;
1974 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00001975
Chris Lattner4b009652007-07-25 00:24:17 +00001976 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001977
Steve Naroff9bb759f2007-09-14 22:20:54 +00001978 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1979 assert(FD && "missing field decl");
1980
1981 // Remember all fields.
1982 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00001983
1984 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00001985 Type *FDTy = FD->getType().getTypePtr();
Steve Naroffffeaa552007-09-14 23:09:53 +00001986
Chris Lattner4b009652007-07-25 00:24:17 +00001987 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00001988 if (FDTy->isFunctionType()) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001989 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattner4b009652007-07-25 00:24:17 +00001990 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001991 FD->setInvalidDecl();
1992 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001993 continue;
1994 }
Chris Lattner4b009652007-07-25 00:24:17 +00001995 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1996 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001997 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001998 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001999 FD->setInvalidDecl();
2000 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002001 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002002 }
Chris Lattner4b009652007-07-25 00:24:17 +00002003 if (i != NumFields-1 || // ... that the last member ...
2004 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00002005 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00002006 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002007 FD->setInvalidDecl();
2008 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002009 continue;
2010 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002011 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner4b009652007-07-25 00:24:17 +00002012 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2013 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002014 FD->setInvalidDecl();
2015 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002016 continue;
2017 }
Chris Lattner4b009652007-07-25 00:24:17 +00002018 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002019 if (Record)
2020 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002021 }
Chris Lattner4b009652007-07-25 00:24:17 +00002022 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2023 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00002024 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002025 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2026 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002027 if (Record && Record->getKind() == Decl::Union) {
Chris Lattner4b009652007-07-25 00:24:17 +00002028 Record->setHasFlexibleArrayMember(true);
2029 } else {
2030 // If this is a struct/class and this is not the last element, reject
2031 // it. Note that GCC supports variable sized arrays in the middle of
2032 // structures.
2033 if (i != NumFields-1) {
2034 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2035 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002036 FD->setInvalidDecl();
2037 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002038 continue;
2039 }
Chris Lattner4b009652007-07-25 00:24:17 +00002040 // We support flexible arrays at the end of structs in other structs
2041 // as an extension.
2042 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2043 FD->getName());
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002044 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002045 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002046 }
2047 }
2048 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002049 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00002050 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002051 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2052 FD->getName());
2053 FD->setInvalidDecl();
2054 EnclosingDecl->setInvalidDecl();
2055 continue;
2056 }
Chris Lattner4b009652007-07-25 00:24:17 +00002057 // Keep track of the number of named members.
2058 if (IdentifierInfo *II = FD->getIdentifier()) {
2059 // Detect duplicate member names.
2060 if (!FieldIDs.insert(II)) {
2061 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2062 // Find the previous decl.
2063 SourceLocation PrevLoc;
2064 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
2065 assert(i != e && "Didn't find previous def!");
2066 if (RecFields[i]->getIdentifier() == II) {
2067 PrevLoc = RecFields[i]->getLocation();
2068 break;
2069 }
2070 }
2071 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00002072 FD->setInvalidDecl();
2073 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002074 continue;
2075 }
2076 ++NumNamedMembers;
2077 }
Chris Lattner4b009652007-07-25 00:24:17 +00002078 }
2079
Chris Lattner4b009652007-07-25 00:24:17 +00002080 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00002081 if (Record) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002082 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattner33aad6e2008-02-06 00:51:33 +00002083 Consumer.HandleTagDeclDefinition(Record);
2084 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00002085 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2086 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2087 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2088 else if (ObjCImplementationDecl *IMPDecl =
2089 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002090 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2091 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00002092 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00002093 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00002094 }
Chris Lattner4b009652007-07-25 00:24:17 +00002095}
2096
Steve Naroff0acc9c92007-09-15 18:49:24 +00002097Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00002098 DeclTy *lastEnumConst,
2099 SourceLocation IdLoc, IdentifierInfo *Id,
2100 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnereee57c02008-04-04 06:12:32 +00002101 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00002102 EnumConstantDecl *LastEnumConst =
2103 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2104 Expr *Val = static_cast<Expr*>(val);
2105
Chris Lattnera7549902007-08-26 06:24:45 +00002106 // The scope passed in may not be a decl scope. Zip up the scope tree until
2107 // we find one that is.
2108 while ((S->getFlags() & Scope::DeclScope) == 0)
2109 S = S->getParent();
2110
Chris Lattner4b009652007-07-25 00:24:17 +00002111 // Verify that there isn't already something declared with this name in this
2112 // scope.
Steve Naroff6384a012008-04-02 14:35:35 +00002113 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00002114 if (IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002115 if (isa<EnumConstantDecl>(PrevDecl))
2116 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2117 else
2118 Diag(IdLoc, diag::err_redefinition, Id->getName());
2119 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002120 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00002121 return 0;
2122 }
2123 }
2124
2125 llvm::APSInt EnumVal(32);
2126 QualType EltTy;
2127 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00002128 // Make sure to promote the operand type to int.
2129 UsualUnaryConversions(Val);
2130
Chris Lattner4b009652007-07-25 00:24:17 +00002131 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2132 SourceLocation ExpLoc;
2133 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
2134 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2135 Id->getName());
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002136 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00002137 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00002138 } else {
2139 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002140 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00002141 }
2142
2143 if (!Val) {
2144 if (LastEnumConst) {
2145 // Assign the last value + 1.
2146 EnumVal = LastEnumConst->getInitVal();
2147 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00002148
2149 // Check for overflow on increment.
2150 if (EnumVal < LastEnumConst->getInitVal())
2151 Diag(IdLoc, diag::warn_enum_value_overflow);
2152
Chris Lattnere7f53a42007-08-27 17:37:24 +00002153 EltTy = LastEnumConst->getType();
2154 } else {
2155 // First value, set to zero.
2156 EltTy = Context.IntTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002157 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00002158 }
Chris Lattner4b009652007-07-25 00:24:17 +00002159 }
2160
Chris Lattnere4650482008-03-15 06:12:44 +00002161 EnumConstantDecl *New =
Chris Lattnereee57c02008-04-04 06:12:32 +00002162 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2163 Val, EnumVal,
Chris Lattner58114f02008-03-15 21:32:50 +00002164 LastEnumConst);
Chris Lattner4b009652007-07-25 00:24:17 +00002165
2166 // Register this decl in the current scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002167 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00002168 return New;
2169}
2170
Steve Naroff0acc9c92007-09-15 18:49:24 +00002171void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00002172 DeclTy **Elements, unsigned NumElements) {
2173 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
2174 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
2175
Chris Lattner435c3fd2007-08-28 05:10:31 +00002176 // TODO: If the result value doesn't fit in an int, it must be a long or long
2177 // long value. ISO C does not support this, but GCC does as an extension,
2178 // emit a warning.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002179 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner435c3fd2007-08-28 05:10:31 +00002180
Chris Lattner206754a2007-08-28 06:15:15 +00002181 // Verify that all the values are okay, compute the size of the values, and
2182 // reverse the list.
2183 unsigned NumNegativeBits = 0;
2184 unsigned NumPositiveBits = 0;
2185
2186 // Keep track of whether all elements have type int.
2187 bool AllElementsInt = true;
2188
Chris Lattner4b009652007-07-25 00:24:17 +00002189 EnumConstantDecl *EltList = 0;
2190 for (unsigned i = 0; i != NumElements; ++i) {
2191 EnumConstantDecl *ECD =
2192 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2193 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00002194
2195 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00002196 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002197 assert(InitVal.getBitWidth() >= IntWidth &&
2198 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00002199 if (InitVal.getBitWidth() > IntWidth) {
2200 llvm::APSInt V(InitVal);
2201 V.trunc(IntWidth);
2202 V.extend(InitVal.getBitWidth());
2203 if (V != InitVal)
2204 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
2205 InitVal.toString());
2206 }
Chris Lattner206754a2007-08-28 06:15:15 +00002207
2208 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002209 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00002210 NumPositiveBits = std::max(NumPositiveBits,
2211 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00002212 else
Chris Lattneraff63f02008-01-14 21:47:29 +00002213 NumNegativeBits = std::max(NumNegativeBits,
2214 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00002215
Chris Lattner206754a2007-08-28 06:15:15 +00002216 // Keep track of whether every enum element has type int (very commmon).
2217 if (AllElementsInt)
2218 AllElementsInt = ECD->getType() == Context.IntTy;
2219
Chris Lattner4b009652007-07-25 00:24:17 +00002220 ECD->setNextDeclarator(EltList);
2221 EltList = ECD;
2222 }
2223
Chris Lattner206754a2007-08-28 06:15:15 +00002224 // Figure out the type that should be used for this enum.
2225 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2226 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002227 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00002228
2229 if (NumNegativeBits) {
2230 // If there is a negative value, figure out the smallest integer type (of
2231 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002232 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00002233 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002234 BestWidth = IntWidth;
2235 } else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002236 BestWidth = Context.Target.getLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00002237
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002238 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00002239 BestType = Context.LongTy;
2240 else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002241 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00002242
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002243 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00002244 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2245 BestType = Context.LongLongTy;
2246 }
2247 }
2248 } else {
2249 // If there is no negative value, figure out which of uint, ulong, ulonglong
2250 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002251 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00002252 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002253 BestWidth = IntWidth;
2254 } else if (NumPositiveBits <=
Chris Lattner8cd0e932008-03-05 18:54:05 +00002255 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattner206754a2007-08-28 06:15:15 +00002256 BestType = Context.UnsignedLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002257 } else {
2258 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002259 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00002260 "How could an initializer get larger than ULL?");
2261 BestType = Context.UnsignedLongLongTy;
2262 }
2263 }
2264
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002265 // Loop over all of the enumerator constants, changing their types to match
2266 // the type of the enum if needed.
2267 for (unsigned i = 0; i != NumElements; ++i) {
2268 EnumConstantDecl *ECD =
2269 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2270 if (!ECD) continue; // Already issued a diagnostic.
2271
2272 // Standard C says the enumerators have int type, but we allow, as an
2273 // extension, the enumerators to be larger than int size. If each
2274 // enumerator value fits in an int, type it as an int, otherwise type it the
2275 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2276 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002277 if (ECD->getType() == Context.IntTy) {
2278 // Make sure the init value is signed.
2279 llvm::APSInt IV = ECD->getInitVal();
2280 IV.setIsSigned(true);
2281 ECD->setInitVal(IV);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002282 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002283 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002284
2285 // Determine whether the value fits into an int.
2286 llvm::APSInt InitVal = ECD->getInitVal();
2287 bool FitsInInt;
2288 if (InitVal.isUnsigned() || !InitVal.isNegative())
2289 FitsInInt = InitVal.getActiveBits() < IntWidth;
2290 else
2291 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2292
2293 // If it fits into an integer type, force it. Otherwise force it to match
2294 // the enum decl type.
2295 QualType NewTy;
2296 unsigned NewWidth;
2297 bool NewSign;
2298 if (FitsInInt) {
2299 NewTy = Context.IntTy;
2300 NewWidth = IntWidth;
2301 NewSign = true;
2302 } else if (ECD->getType() == BestType) {
2303 // Already the right type!
2304 continue;
2305 } else {
2306 NewTy = BestType;
2307 NewWidth = BestWidth;
2308 NewSign = BestType->isSignedIntegerType();
2309 }
2310
2311 // Adjust the APSInt value.
2312 InitVal.extOrTrunc(NewWidth);
2313 InitVal.setIsSigned(NewSign);
2314 ECD->setInitVal(InitVal);
2315
2316 // Adjust the Expr initializer and type.
2317 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2318 ECD->setType(NewTy);
2319 }
Chris Lattner206754a2007-08-28 06:15:15 +00002320
Chris Lattner90a018d2007-08-28 18:24:31 +00002321 Enum->defineElements(EltList, BestType);
Chris Lattner33aad6e2008-02-06 00:51:33 +00002322 Consumer.HandleTagDeclDefinition(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00002323}
2324
Anders Carlsson4f7f4412008-02-08 00:33:21 +00002325Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
2326 ExprTy *expr) {
2327 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
2328
Chris Lattner81db64a2008-03-16 00:16:02 +00002329 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlsson4f7f4412008-02-08 00:33:21 +00002330}
2331
Chris Lattner806a5f52008-01-12 07:05:38 +00002332Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattner43b885f2008-02-25 21:04:36 +00002333 SourceLocation LBrace,
2334 SourceLocation RBrace,
2335 const char *Lang,
2336 unsigned StrSize,
2337 DeclTy *D) {
Chris Lattner806a5f52008-01-12 07:05:38 +00002338 LinkageSpecDecl::LanguageIDs Language;
2339 Decl *dcl = static_cast<Decl *>(D);
2340 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2341 Language = LinkageSpecDecl::lang_c;
2342 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2343 Language = LinkageSpecDecl::lang_cxx;
2344 else {
2345 Diag(Loc, diag::err_bad_language);
2346 return 0;
2347 }
2348
2349 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner81db64a2008-03-16 00:16:02 +00002350 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattner806a5f52008-01-12 07:05:38 +00002351}
2352
Chris Lattner49d15cb2008-02-21 00:48:22 +00002353void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) {
Anders Carlsson28e34e32007-12-19 06:16:30 +00002354
Chris Lattner49d15cb2008-02-21 00:48:22 +00002355 switch (Attr->getKind()) {
Chris Lattnerb9716a62008-02-20 23:17:35 +00002356 case AttributeList::AT_vector_size:
Chris Lattner4b009652007-07-25 00:24:17 +00002357 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Chris Lattner49d15cb2008-02-21 00:48:22 +00002358 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00002359 if (!newType.isNull()) // install the new vector type into the decl
2360 vDecl->setType(newType);
2361 }
2362 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2363 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
Chris Lattner49d15cb2008-02-21 00:48:22 +00002364 Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00002365 if (!newType.isNull()) // install the new vector type into the decl
2366 tDecl->setUnderlyingType(newType);
2367 }
Chris Lattnerb9716a62008-02-20 23:17:35 +00002368 break;
Nate Begemanaf6ed502008-04-18 23:10:10 +00002369 case AttributeList::AT_ext_vector_type:
Steve Naroff82113e32007-07-29 16:33:31 +00002370 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
Nate Begemanaf6ed502008-04-18 23:10:10 +00002371 HandleExtVectorTypeAttribute(tDecl, Attr);
Steve Naroff82113e32007-07-29 16:33:31 +00002372 else
Chris Lattner49d15cb2008-02-21 00:48:22 +00002373 Diag(Attr->getLoc(),
Nate Begemanaf6ed502008-04-18 23:10:10 +00002374 diag::err_typecheck_ext_vector_not_typedef);
Chris Lattnerb9716a62008-02-20 23:17:35 +00002375 break;
2376 case AttributeList::AT_address_space:
Christopher Lamb2a72bb32008-02-04 02:31:56 +00002377 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2378 QualType newType = HandleAddressSpaceTypeAttribute(
2379 tDecl->getUnderlyingType(),
Chris Lattner49d15cb2008-02-21 00:48:22 +00002380 Attr);
2381 tDecl->setUnderlyingType(newType);
Christopher Lamb2a72bb32008-02-04 02:31:56 +00002382 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
2383 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
Chris Lattner49d15cb2008-02-21 00:48:22 +00002384 Attr);
2385 // install the new addr spaced type into the decl
2386 vDecl->setType(newType);
Christopher Lamb2a72bb32008-02-04 02:31:56 +00002387 }
Chris Lattnerb9716a62008-02-20 23:17:35 +00002388 break;
Chris Lattneree4c3bf2008-02-29 16:48:43 +00002389 case AttributeList::AT_deprecated:
Chris Lattner402b3372008-03-03 03:28:21 +00002390 HandleDeprecatedAttribute(New, Attr);
2391 break;
2392 case AttributeList::AT_visibility:
2393 HandleVisibilityAttribute(New, Attr);
2394 break;
2395 case AttributeList::AT_weak:
2396 HandleWeakAttribute(New, Attr);
2397 break;
2398 case AttributeList::AT_dllimport:
2399 HandleDLLImportAttribute(New, Attr);
2400 break;
2401 case AttributeList::AT_dllexport:
2402 HandleDLLExportAttribute(New, Attr);
2403 break;
2404 case AttributeList::AT_nothrow:
2405 HandleNothrowAttribute(New, Attr);
Chris Lattneree4c3bf2008-02-29 16:48:43 +00002406 break;
Nate Begemand75d28b2008-03-07 20:04:22 +00002407 case AttributeList::AT_stdcall:
2408 HandleStdCallAttribute(New, Attr);
2409 break;
2410 case AttributeList::AT_fastcall:
2411 HandleFastCallAttribute(New, Attr);
2412 break;
Chris Lattnerb9716a62008-02-20 23:17:35 +00002413 case AttributeList::AT_aligned:
Chris Lattner49d15cb2008-02-21 00:48:22 +00002414 HandleAlignedAttribute(New, Attr);
Chris Lattnerb9716a62008-02-20 23:17:35 +00002415 break;
2416 case AttributeList::AT_packed:
Chris Lattner49d15cb2008-02-21 00:48:22 +00002417 HandlePackedAttribute(New, Attr);
Chris Lattnerb9716a62008-02-20 23:17:35 +00002418 break;
Nate Begeman754d3fc2008-02-21 19:30:49 +00002419 case AttributeList::AT_annotate:
2420 HandleAnnotateAttribute(New, Attr);
2421 break;
Ted Kremenek13bfae62008-02-27 20:43:06 +00002422 case AttributeList::AT_noreturn:
2423 HandleNoReturnAttribute(New, Attr);
2424 break;
Chris Lattner402b3372008-03-03 03:28:21 +00002425 case AttributeList::AT_format:
2426 HandleFormatAttribute(New, Attr);
2427 break;
Nuno Lopes463ec842008-04-25 09:32:00 +00002428 case AttributeList::AT_transparent_union:
2429 HandleTransparentUnionAttribute(New, Attr);
2430 break;
Chris Lattnerb9716a62008-02-20 23:17:35 +00002431 default:
Chris Lattneree4c3bf2008-02-29 16:48:43 +00002432#if 0
2433 // TODO: when we have the full set of attributes, warn about unknown ones.
2434 Diag(Attr->getLoc(), diag::warn_attribute_ignored,
2435 Attr->getName()->getName());
2436#endif
Chris Lattnerb9716a62008-02-20 23:17:35 +00002437 break;
2438 }
Chris Lattner4b009652007-07-25 00:24:17 +00002439}
2440
2441void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
2442 AttributeList *declarator_postfix) {
2443 while (declspec_prefix) {
2444 HandleDeclAttribute(New, declspec_prefix);
2445 declspec_prefix = declspec_prefix->getNext();
2446 }
2447 while (declarator_postfix) {
2448 HandleDeclAttribute(New, declarator_postfix);
2449 declarator_postfix = declarator_postfix->getNext();
2450 }
2451}
2452
Nate Begemanaf6ed502008-04-18 23:10:10 +00002453void Sema::HandleExtVectorTypeAttribute(TypedefDecl *tDecl,
Steve Naroff82113e32007-07-29 16:33:31 +00002454 AttributeList *rawAttr) {
2455 QualType curType = tDecl->getUnderlyingType();
Anders Carlssonc8b44122007-12-19 07:19:40 +00002456 // check the attribute arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002457 if (rawAttr->getNumArgs() != 1) {
Chris Lattner9384f502008-02-20 23:25:22 +00002458 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Chris Lattner4b009652007-07-25 00:24:17 +00002459 std::string("1"));
Steve Naroff82113e32007-07-29 16:33:31 +00002460 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002461 }
2462 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2463 llvm::APSInt vecSize(32);
2464 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner9384f502008-02-20 23:25:22 +00002465 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Nate Begemanaf6ed502008-04-18 23:10:10 +00002466 "ext_vector_type", sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00002467 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002468 }
2469 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2470 // in conjunction with complex types (pointers, arrays, functions, etc.).
2471 Type *canonType = curType.getCanonicalType().getTypePtr();
2472 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner9384f502008-02-20 23:25:22 +00002473 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Chris Lattner4b009652007-07-25 00:24:17 +00002474 curType.getCanonicalType().getAsString());
Steve Naroff82113e32007-07-29 16:33:31 +00002475 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002476 }
2477 // unlike gcc's vector_size attribute, the size is specified as the
2478 // number of elements, not the number of bytes.
Chris Lattner3496d522007-09-04 02:45:27 +00002479 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Chris Lattner4b009652007-07-25 00:24:17 +00002480
2481 if (vectorSize == 0) {
Chris Lattner9384f502008-02-20 23:25:22 +00002482 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Chris Lattner4b009652007-07-25 00:24:17 +00002483 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00002484 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002485 }
Steve Naroff82113e32007-07-29 16:33:31 +00002486 // Instantiate/Install the vector type, the number of elements is > 0.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002487 tDecl->setUnderlyingType(Context.getExtVectorType(curType, vectorSize));
Steve Naroff82113e32007-07-29 16:33:31 +00002488 // Remember this typedef decl, we will need it later for diagnostics.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002489 ExtVectorDecls.push_back(tDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00002490}
2491
2492QualType Sema::HandleVectorTypeAttribute(QualType curType,
2493 AttributeList *rawAttr) {
2494 // check the attribute arugments.
2495 if (rawAttr->getNumArgs() != 1) {
Chris Lattner9384f502008-02-20 23:25:22 +00002496 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Chris Lattner4b009652007-07-25 00:24:17 +00002497 std::string("1"));
2498 return QualType();
2499 }
2500 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2501 llvm::APSInt vecSize(32);
2502 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner9384f502008-02-20 23:25:22 +00002503 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson7dce0292008-02-16 19:51:27 +00002504 "vector_size", sizeExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002505 return QualType();
2506 }
2507 // navigate to the base type - we need to provide for vector pointers,
2508 // vector arrays, and functions returning vectors.
2509 Type *canonType = curType.getCanonicalType().getTypePtr();
2510
2511 if (canonType->isPointerType() || canonType->isArrayType() ||
2512 canonType->isFunctionType()) {
Chris Lattner5b5e1982007-12-19 05:38:06 +00002513 assert(0 && "HandleVector(): Complex type construction unimplemented");
Chris Lattner4b009652007-07-25 00:24:17 +00002514 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2515 do {
2516 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2517 canonType = PT->getPointeeType().getTypePtr();
2518 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2519 canonType = AT->getElementType().getTypePtr();
2520 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2521 canonType = FT->getResultType().getTypePtr();
2522 } while (canonType->isPointerType() || canonType->isArrayType() ||
2523 canonType->isFunctionType());
2524 */
2525 }
2526 // the base type must be integer or float.
2527 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner9384f502008-02-20 23:25:22 +00002528 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Chris Lattner4b009652007-07-25 00:24:17 +00002529 curType.getCanonicalType().getAsString());
2530 return QualType();
2531 }
Chris Lattner8cd0e932008-03-05 18:54:05 +00002532 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(curType));
Chris Lattner4b009652007-07-25 00:24:17 +00002533 // vecSize is specified in bytes - convert to bits.
Chris Lattner3496d522007-09-04 02:45:27 +00002534 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Chris Lattner4b009652007-07-25 00:24:17 +00002535
2536 // the vector size needs to be an integral multiple of the type size.
2537 if (vectorSize % typeSize) {
Chris Lattner9384f502008-02-20 23:25:22 +00002538 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
Chris Lattner4b009652007-07-25 00:24:17 +00002539 sizeExpr->getSourceRange());
2540 return QualType();
2541 }
2542 if (vectorSize == 0) {
Chris Lattner9384f502008-02-20 23:25:22 +00002543 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Chris Lattner4b009652007-07-25 00:24:17 +00002544 sizeExpr->getSourceRange());
2545 return QualType();
2546 }
Nate Begeman754d3fc2008-02-21 19:30:49 +00002547 // Instantiate the vector type, the number of elements is > 0, and not
2548 // required to be a power of 2, unlike GCC.
Chris Lattner4b009652007-07-25 00:24:17 +00002549 return Context.getVectorType(curType, vectorSize/typeSize);
2550}
2551
Chris Lattner9384f502008-02-20 23:25:22 +00002552void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) {
Anders Carlsson136cdc32008-02-16 00:29:18 +00002553 // check the attribute arguments.
2554 if (rawAttr->getNumArgs() > 0) {
Chris Lattner9384f502008-02-20 23:25:22 +00002555 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlsson136cdc32008-02-16 00:29:18 +00002556 std::string("0"));
2557 return;
2558 }
2559
2560 if (TagDecl *TD = dyn_cast<TagDecl>(d))
2561 TD->addAttr(new PackedAttr);
2562 else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
2563 // If the alignment is less than or equal to 8 bits, the packed attribute
2564 // has no effect.
Chris Lattner8bb7dd52008-05-09 05:34:49 +00002565 if (!FD->getType()->isIncompleteType() &&
2566 Context.getTypeAlign(FD->getType()) <= 8)
Chris Lattner9384f502008-02-20 23:25:22 +00002567 Diag(rawAttr->getLoc(),
Anders Carlsson136cdc32008-02-16 00:29:18 +00002568 diag::warn_attribute_ignored_for_field_of_type,
Chris Lattner9384f502008-02-20 23:25:22 +00002569 rawAttr->getName()->getName(), FD->getType().getAsString());
Anders Carlsson136cdc32008-02-16 00:29:18 +00002570 else
Anders Carlssonca133d92008-02-16 00:39:40 +00002571 FD->addAttr(new PackedAttr);
Anders Carlsson136cdc32008-02-16 00:29:18 +00002572 } else
Chris Lattner9384f502008-02-20 23:25:22 +00002573 Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
2574 rawAttr->getName()->getName());
Anders Carlsson136cdc32008-02-16 00:29:18 +00002575}
Nate Begeman754d3fc2008-02-21 19:30:49 +00002576
Ted Kremenek13bfae62008-02-27 20:43:06 +00002577void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) {
2578 // check the attribute arguments.
2579 if (rawAttr->getNumArgs() != 0) {
2580 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2581 std::string("0"));
2582 return;
2583 }
2584
Ted Kremenek40b95e52008-03-03 16:52:27 +00002585 FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2586
2587 if (!Fn) {
2588 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2589 "noreturn", "function");
2590 return;
2591 }
2592
Ted Kremenek13bfae62008-02-27 20:43:06 +00002593 d->addAttr(new NoReturnAttr());
2594}
2595
Chris Lattner402b3372008-03-03 03:28:21 +00002596void Sema::HandleDeprecatedAttribute(Decl *d, AttributeList *rawAttr) {
2597 // check the attribute arguments.
2598 if (rawAttr->getNumArgs() != 0) {
2599 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2600 std::string("0"));
2601 return;
2602 }
2603
2604 d->addAttr(new DeprecatedAttr());
2605}
2606
2607void Sema::HandleVisibilityAttribute(Decl *d, AttributeList *rawAttr) {
2608 // check the attribute arguments.
Chris Lattnere9d83be2008-03-04 18:08:48 +00002609 if (rawAttr->getNumArgs() != 1) {
Chris Lattner402b3372008-03-03 03:28:21 +00002610 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2611 std::string("1"));
2612 return;
2613 }
2614
Chris Lattnere9d83be2008-03-04 18:08:48 +00002615 Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0));
2616 Arg = Arg->IgnoreParenCasts();
2617 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2618
2619 if (Str == 0 || Str->isWide()) {
Chris Lattner402b3372008-03-03 03:28:21 +00002620 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
Chris Lattnere9d83be2008-03-04 18:08:48 +00002621 "visibility", std::string("1"));
Chris Lattner402b3372008-03-03 03:28:21 +00002622 return;
2623 }
2624
Chris Lattnere9d83be2008-03-04 18:08:48 +00002625 const char *TypeStr = Str->getStrData();
2626 unsigned TypeLen = Str->getByteLength();
Dan Gohman4751a3a2008-05-22 00:50:06 +00002627 VisibilityAttr::VisibilityTypes type;
Chris Lattner402b3372008-03-03 03:28:21 +00002628
Chris Lattnere9d83be2008-03-04 18:08:48 +00002629 if (TypeLen == 7 && !memcmp(TypeStr, "default", 7))
Dan Gohman4751a3a2008-05-22 00:50:06 +00002630 type = VisibilityAttr::DefaultVisibility;
Chris Lattnere9d83be2008-03-04 18:08:48 +00002631 else if (TypeLen == 6 && !memcmp(TypeStr, "hidden", 6))
Dan Gohman4751a3a2008-05-22 00:50:06 +00002632 type = VisibilityAttr::HiddenVisibility;
Chris Lattnere9d83be2008-03-04 18:08:48 +00002633 else if (TypeLen == 8 && !memcmp(TypeStr, "internal", 8))
Dan Gohman4751a3a2008-05-22 00:50:06 +00002634 type = VisibilityAttr::HiddenVisibility; // FIXME
Chris Lattnere9d83be2008-03-04 18:08:48 +00002635 else if (TypeLen == 9 && !memcmp(TypeStr, "protected", 9))
Dan Gohman4751a3a2008-05-22 00:50:06 +00002636 type = VisibilityAttr::ProtectedVisibility;
Chris Lattner402b3372008-03-03 03:28:21 +00002637 else {
2638 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
Chris Lattnere9d83be2008-03-04 18:08:48 +00002639 "visibility", TypeStr);
Chris Lattner402b3372008-03-03 03:28:21 +00002640 return;
2641 }
2642
2643 d->addAttr(new VisibilityAttr(type));
2644}
2645
2646void Sema::HandleWeakAttribute(Decl *d, AttributeList *rawAttr) {
2647 // check the attribute arguments.
2648 if (rawAttr->getNumArgs() != 0) {
2649 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2650 std::string("0"));
2651 return;
2652 }
2653
2654 d->addAttr(new WeakAttr());
2655}
2656
2657void Sema::HandleDLLImportAttribute(Decl *d, AttributeList *rawAttr) {
2658 // check the attribute arguments.
2659 if (rawAttr->getNumArgs() != 0) {
2660 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2661 std::string("0"));
2662 return;
2663 }
2664
2665 d->addAttr(new DLLImportAttr());
2666}
2667
2668void Sema::HandleDLLExportAttribute(Decl *d, AttributeList *rawAttr) {
2669 // check the attribute arguments.
2670 if (rawAttr->getNumArgs() != 0) {
2671 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2672 std::string("0"));
2673 return;
2674 }
2675
2676 d->addAttr(new DLLExportAttr());
2677}
2678
Nate Begemand75d28b2008-03-07 20:04:22 +00002679void Sema::HandleStdCallAttribute(Decl *d, AttributeList *rawAttr) {
2680 // check the attribute arguments.
2681 if (rawAttr->getNumArgs() != 0) {
2682 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2683 std::string("0"));
2684 return;
2685 }
2686
2687 d->addAttr(new StdCallAttr());
2688}
2689
2690void Sema::HandleFastCallAttribute(Decl *d, AttributeList *rawAttr) {
2691 // check the attribute arguments.
2692 if (rawAttr->getNumArgs() != 0) {
2693 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2694 std::string("0"));
2695 return;
2696 }
2697
2698 d->addAttr(new FastCallAttr());
2699}
2700
Chris Lattner402b3372008-03-03 03:28:21 +00002701void Sema::HandleNothrowAttribute(Decl *d, AttributeList *rawAttr) {
2702 // check the attribute arguments.
2703 if (rawAttr->getNumArgs() != 0) {
2704 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2705 std::string("0"));
2706 return;
2707 }
2708
2709 d->addAttr(new NoThrowAttr());
2710}
2711
Nuno Lopes02564e52008-03-25 23:01:48 +00002712static const FunctionTypeProto *getFunctionProto(Decl *d) {
Nuno Lopesc3cf4502008-04-18 22:43:39 +00002713 QualType Ty;
Nuno Lopes02564e52008-03-25 23:01:48 +00002714
Nuno Lopesc3cf4502008-04-18 22:43:39 +00002715 if (ValueDecl *decl = dyn_cast<ValueDecl>(d))
2716 Ty = decl->getType();
2717 else if (FieldDecl *decl = dyn_cast<FieldDecl>(d))
2718 Ty = decl->getType();
Ted Kremenek1e0fb9b2008-05-09 17:36:24 +00002719 else if (TypedefDecl* decl = dyn_cast<TypedefDecl>(d))
2720 Ty = decl->getUnderlyingType();
Nuno Lopesc3cf4502008-04-18 22:43:39 +00002721 else
2722 return 0;
Nuno Lopes02564e52008-03-25 23:01:48 +00002723
2724 if (Ty->isFunctionPointerType()) {
2725 const PointerType *PtrTy = Ty->getAsPointerType();
2726 Ty = PtrTy->getPointeeType();
2727 }
2728
2729 if (const FunctionType *FnTy = Ty->getAsFunctionType())
2730 return dyn_cast<FunctionTypeProto>(FnTy->getAsFunctionType());
2731
2732 return 0;
2733}
2734
Ted Kremenek9df18da2008-05-08 19:43:35 +00002735static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
2736 if (!T->isPointerType())
2737 return false;
2738
2739 T = T->getAsPointerType()->getPointeeType().getCanonicalType();
2740 ObjCInterfaceType* ClsT = dyn_cast<ObjCInterfaceType>(T.getTypePtr());
2741
2742 if (!ClsT)
2743 return false;
2744
2745 IdentifierInfo* ClsName = ClsT->getDecl()->getIdentifier();
2746
2747 // FIXME: Should we walk the chain of classes?
2748 return ClsName == &Ctx.Idents.get("NSString") ||
2749 ClsName == &Ctx.Idents.get("NSMutableString");
2750}
Nuno Lopes02564e52008-03-25 23:01:48 +00002751
Ted Kremeneke5769412008-03-07 18:43:49 +00002752/// Handle __attribute__((format(type,idx,firstarg))) attributes
2753/// based on http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chris Lattner402b3372008-03-03 03:28:21 +00002754void Sema::HandleFormatAttribute(Decl *d, AttributeList *rawAttr) {
2755
2756 if (!rawAttr->getParameterName()) {
2757 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2758 "format", std::string("1"));
2759 return;
2760 }
2761
2762 if (rawAttr->getNumArgs() != 2) {
2763 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2764 std::string("3"));
2765 return;
2766 }
2767
Nuno Lopes02564e52008-03-25 23:01:48 +00002768 // GCC ignores the format attribute on K&R style function
2769 // prototypes, so we ignore it as well
2770 const FunctionTypeProto *proto = getFunctionProto(d);
2771
2772 if (!proto) {
Chris Lattner402b3372008-03-03 03:28:21 +00002773 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2774 "format", "function");
2775 return;
2776 }
2777
2778 // FIXME: in C++ the implicit 'this' function parameter also counts.
Ted Kremeneke5769412008-03-07 18:43:49 +00002779 // this is needed in order to be compatible with GCC
Chris Lattner402b3372008-03-03 03:28:21 +00002780 // the index must start in 1 and the limit is numargs+1
Nuno Lopes02564e52008-03-25 23:01:48 +00002781 unsigned NumArgs = proto->getNumArgs();
Ted Kremeneke5769412008-03-07 18:43:49 +00002782 unsigned FirstIdx = 1;
Chris Lattner402b3372008-03-03 03:28:21 +00002783
2784 const char *Format = rawAttr->getParameterName()->getName();
2785 unsigned FormatLen = rawAttr->getParameterName()->getLength();
2786
2787 // Normalize the argument, __foo__ becomes foo.
2788 if (FormatLen > 4 && Format[0] == '_' && Format[1] == '_' &&
2789 Format[FormatLen - 2] == '_' && Format[FormatLen - 1] == '_') {
2790 Format += 2;
2791 FormatLen -= 4;
2792 }
2793
Ted Kremenek9df18da2008-05-08 19:43:35 +00002794 bool Supported = false;
2795 bool is_NSString = false;
2796 bool is_strftime = false;
2797
2798 switch (FormatLen) {
2799 default: break;
2800 case 5:
2801 Supported = !memcmp(Format, "scanf", 5);
2802 break;
2803 case 6:
2804 Supported = !memcmp(Format, "printf", 6);
2805 break;
2806 case 7:
2807 Supported = !memcmp(Format, "strfmon", 7);
2808 break;
2809 case 8:
2810 Supported = (is_strftime = !memcmp(Format, "strftime", 8)) ||
2811 (is_NSString = !memcmp(Format, "NSString", 8));
2812 break;
2813 }
2814
2815 if (!Supported) {
Chris Lattner402b3372008-03-03 03:28:21 +00002816 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2817 "format", rawAttr->getParameterName()->getName());
2818 return;
2819 }
2820
Ted Kremeneke5769412008-03-07 18:43:49 +00002821 // checks for the 2nd argument
Chris Lattner402b3372008-03-03 03:28:21 +00002822 Expr *IdxExpr = static_cast<Expr *>(rawAttr->getArg(0));
Ted Kremeneke5769412008-03-07 18:43:49 +00002823 llvm::APSInt Idx(Context.getTypeSize(IdxExpr->getType()));
Chris Lattner402b3372008-03-03 03:28:21 +00002824 if (!IdxExpr->isIntegerConstantExpr(Idx, Context)) {
2825 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2826 "format", std::string("2"), IdxExpr->getSourceRange());
2827 return;
2828 }
2829
Ted Kremeneke5769412008-03-07 18:43:49 +00002830 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
Chris Lattner402b3372008-03-03 03:28:21 +00002831 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2832 "format", std::string("2"), IdxExpr->getSourceRange());
2833 return;
2834 }
2835
Ted Kremenek9df18da2008-05-08 19:43:35 +00002836 // FIXME: Do we need to bounds check?
2837 unsigned ArgIdx = Idx.getZExtValue() - 1;
2838
Ted Kremeneke5769412008-03-07 18:43:49 +00002839 // make sure the format string is really a string
Ted Kremenek9df18da2008-05-08 19:43:35 +00002840 QualType Ty = proto->getArgType(ArgIdx);
2841
2842 if (is_NSString) {
2843 // FIXME: do we need to check if the type is NSString*? What are
2844 // the semantics?
2845 if (!isNSStringType(Ty, Context)) {
2846 // FIXME: Should highlight the actual expression that has the
2847 // wrong type.
2848 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_NSString,
2849 IdxExpr->getSourceRange());
2850 return;
2851 }
2852 }
2853 else if (!Ty->isPointerType() ||
Ted Kremeneke5769412008-03-07 18:43:49 +00002854 !Ty->getAsPointerType()->getPointeeType()->isCharType()) {
Ted Kremenek9df18da2008-05-08 19:43:35 +00002855 // FIXME: Should highlight the actual expression that has the
2856 // wrong type.
Ted Kremeneke5769412008-03-07 18:43:49 +00002857 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_string,
2858 IdxExpr->getSourceRange());
2859 return;
2860 }
2861
Ted Kremeneke5769412008-03-07 18:43:49 +00002862 // check the 3rd argument
Chris Lattner402b3372008-03-03 03:28:21 +00002863 Expr *FirstArgExpr = static_cast<Expr *>(rawAttr->getArg(1));
Ted Kremeneke5769412008-03-07 18:43:49 +00002864 llvm::APSInt FirstArg(Context.getTypeSize(FirstArgExpr->getType()));
Chris Lattner402b3372008-03-03 03:28:21 +00002865 if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, Context)) {
2866 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2867 "format", std::string("3"), FirstArgExpr->getSourceRange());
2868 return;
2869 }
2870
Ted Kremeneke5769412008-03-07 18:43:49 +00002871 // check if the function is variadic if the 3rd argument non-zero
2872 if (FirstArg != 0) {
2873 if (proto->isVariadic()) {
2874 ++NumArgs; // +1 for ...
2875 } else {
2876 Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
2877 return;
2878 }
2879 }
2880
2881 // strftime requires FirstArg to be 0 because it doesn't read from any variable
2882 // the input is just the current time + the format string
Ted Kremenek9df18da2008-05-08 19:43:35 +00002883 if (is_strftime) {
Ted Kremeneke5769412008-03-07 18:43:49 +00002884 if (FirstArg != 0) {
Chris Lattner402b3372008-03-03 03:28:21 +00002885 Diag(rawAttr->getLoc(), diag::err_format_strftime_third_parameter,
2886 FirstArgExpr->getSourceRange());
2887 return;
2888 }
Ted Kremeneke5769412008-03-07 18:43:49 +00002889 // if 0 it disables parameter checking (to use with e.g. va_list)
2890 } else if (FirstArg != 0 && FirstArg != NumArgs) {
Chris Lattner402b3372008-03-03 03:28:21 +00002891 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2892 "format", std::string("3"), FirstArgExpr->getSourceRange());
2893 return;
2894 }
2895
2896 d->addAttr(new FormatAttr(std::string(Format, FormatLen),
2897 Idx.getZExtValue(), FirstArg.getZExtValue()));
2898}
2899
Nuno Lopes463ec842008-04-25 09:32:00 +00002900void Sema::HandleTransparentUnionAttribute(Decl *d, AttributeList *rawAttr) {
2901 // check the attribute arguments.
2902 if (rawAttr->getNumArgs() != 0) {
2903 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2904 std::string("0"));
2905 return;
2906 }
2907
2908 TypeDecl *decl = dyn_cast<TypeDecl>(d);
2909
2910 if (!decl || !Context.getTypeDeclType(decl)->isUnionType()) {
2911 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2912 "transparent_union", "union");
2913 return;
2914 }
2915
Chris Lattner46f83552008-04-30 16:04:01 +00002916 //QualType QTy = Context.getTypeDeclType(decl);
2917 //const RecordType *Ty = QTy->getAsUnionType();
Nuno Lopes463ec842008-04-25 09:32:00 +00002918
2919// FIXME
2920// Ty->addAttr(new TransparentUnionAttr());
2921}
2922
Nate Begeman754d3fc2008-02-21 19:30:49 +00002923void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) {
2924 // check the attribute arguments.
2925 if (rawAttr->getNumArgs() != 1) {
2926 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2927 std::string("1"));
2928 return;
2929 }
2930 Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
2931 StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
Anders Carlsson136cdc32008-02-16 00:29:18 +00002932
Nate Begeman754d3fc2008-02-21 19:30:49 +00002933 // Make sure that there is a string literal as the annotation's single
2934 // argument.
2935 if (!SE) {
2936 Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
2937 return;
2938 }
2939 d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
2940 SE->getByteLength())));
2941}
2942
Anders Carlssonc8b44122007-12-19 07:19:40 +00002943void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
2944{
2945 // check the attribute arguments.
Eli Friedman74820702008-01-30 17:38:42 +00002946 if (rawAttr->getNumArgs() > 1) {
Chris Lattner9384f502008-02-20 23:25:22 +00002947 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlssonc8b44122007-12-19 07:19:40 +00002948 std::string("1"));
2949 return;
2950 }
Eli Friedman74820702008-01-30 17:38:42 +00002951
Anders Carlsson7dce0292008-02-16 19:51:27 +00002952 unsigned Align = 0;
2953
2954 if (rawAttr->getNumArgs() == 0) {
2955 // FIXME: This should be the target specific maximum alignment.
2956 // (For now we just use 128 bits which is the maximum on X86.
2957 Align = 128;
Eli Friedman74820702008-01-30 17:38:42 +00002958 return;
Anders Carlsson7dce0292008-02-16 19:51:27 +00002959 } else {
2960 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
2961 llvm::APSInt alignment(32);
2962 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
Chris Lattner9384f502008-02-20 23:25:22 +00002963 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson7dce0292008-02-16 19:51:27 +00002964 "aligned", alignmentExpr->getSourceRange());
2965 return;
2966 }
2967
2968 Align = alignment.getZExtValue() * 8;
2969 }
Eli Friedman74820702008-01-30 17:38:42 +00002970
Anders Carlsson7dce0292008-02-16 19:51:27 +00002971 d->addAttr(new AlignedAttr(Align));
Anders Carlssonc8b44122007-12-19 07:19:40 +00002972}