SemaDecl.cpp revision c56c977f44d0bd8422a6f0fe87f361cbb728c06b
1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Attr.h"
18#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"
24#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/TargetInfo.h"
26#include "clang/Basic/SourceManager.h"
27// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
28#include "clang/Lex/Preprocessor.h"
29#include "clang/Lex/HeaderSearch.h"
30#include "llvm/ADT/SmallString.h"
31#include "llvm/ADT/SmallSet.h"
32#include "llvm/ADT/DenseSet.h"
33using namespace clang;
34
35Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
36  Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
37
38  if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
39                 isa<ObjCInterfaceDecl>(IIDecl) ||
40                 isa<TagDecl>(IIDecl)))
41    return IIDecl;
42  return 0;
43}
44
45void Sema::PushDeclContext(DeclContext *DC) {
46  assert( ( (isa<ObjCMethodDecl>(DC) && isa<TranslationUnitDecl>(CurContext))
47            || DC->getParent() == CurContext ) &&
48      "The next DeclContext should be directly contained in the current one.");
49  CurContext = DC;
50}
51
52void Sema::PopDeclContext() {
53  assert(CurContext && "DeclContext imbalance!");
54  // If CurContext is a ObjC method, getParent() will return NULL.
55  CurContext = isa<ObjCMethodDecl>(CurContext)
56               ? Context.getTranslationUnitDecl()
57                 :  CurContext->getParent();
58}
59
60/// Add this decl to the scope shadowed decl chains.
61void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
62  S->AddDecl(D);
63
64  // C++ [basic.scope]p4:
65  //   -- exactly one declaration shall declare a class name or
66  //   enumeration name that is not a typedef name and the other
67  //   declarations shall all refer to the same object or
68  //   enumerator, or all refer to functions and function templates;
69  //   in this case the class name or enumeration name is hidden.
70  if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
71    // We are pushing the name of a tag (enum or class).
72    IdentifierResolver::ctx_iterator
73      CIT = IdResolver.ctx_begin(TD->getIdentifier(), TD->getDeclContext());
74    if (CIT != IdResolver.ctx_end(TD->getIdentifier()) &&
75        IdResolver.isDeclInScope(*CIT, TD->getDeclContext(), S)) {
76      // There is already a declaration with the same name in the same
77      // scope. It must be found before we find the new declaration,
78      // so swap the order on the shadowed declaration chain.
79
80      IdResolver.AddShadowedDecl(TD, *CIT);
81      return;
82    }
83  }
84
85  IdResolver.AddDecl(D);
86}
87
88void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
89  if (S->decl_empty()) return;
90  assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
91
92  // We only want to remove the decls from the identifier decl chains for local
93  // scopes, when inside a function/method.
94  if (S->getFnParent() == 0)
95    return;
96
97  for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
98       I != E; ++I) {
99    Decl *TmpD = static_cast<Decl*>(*I);
100    assert(TmpD && "This decl didn't get pushed??");
101    ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
102    assert(D && "This decl isn't a ScopedDecl?");
103
104    IdentifierInfo *II = D->getIdentifier();
105    if (!II) continue;
106
107    // Unlink this decl from the identifier.
108    IdResolver.RemoveDecl(D);
109
110    // This will have to be revisited for C++: there we want to nest stuff in
111    // namespace decls etc.  Even for C, we might want a top-level translation
112    // unit decl or something.
113    if (!CurFunctionDecl)
114      continue;
115
116    // Chain this decl to the containing function, it now owns the memory for
117    // the decl.
118    D->setNext(CurFunctionDecl->getDeclChain());
119    CurFunctionDecl->setDeclChain(D);
120  }
121}
122
123/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
124/// return 0 if one not found.
125ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
126  // The third "scope" argument is 0 since we aren't enabling lazy built-in
127  // creation from this context.
128  Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
129
130  return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
131}
132
133/// LookupDecl - Look up the inner-most declaration in the specified
134/// namespace.
135Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
136                       Scope *S, bool enableLazyBuiltinCreation) {
137  if (II == 0) return 0;
138  unsigned NS = NSI;
139  if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
140    NS |= Decl::IDNS_Tag;
141
142  // Scan up the scope chain looking for a decl that matches this identifier
143  // that is in the appropriate namespace.  This search should not take long, as
144  // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
145  for (IdentifierResolver::iterator
146       I = IdResolver.begin(II, CurContext), E = IdResolver.end(II); I != E; ++I)
147    if ((*I)->getIdentifierNamespace() & NS)
148      return *I;
149
150  // If we didn't find a use of this identifier, and if the identifier
151  // corresponds to a compiler builtin, create the decl object for the builtin
152  // now, injecting it into translation unit scope, and return it.
153  if (NS & Decl::IDNS_Ordinary) {
154    if (enableLazyBuiltinCreation) {
155      // If this is a builtin on this (or all) targets, create the decl.
156      if (unsigned BuiltinID = II->getBuiltinID())
157        return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
158    }
159    if (getLangOptions().ObjC1) {
160      // @interface and @compatibility_alias introduce typedef-like names.
161      // Unlike typedef's, they can only be introduced at file-scope (and are
162      // therefore not scoped decls). They can, however, be shadowed by
163      // other names in IDNS_Ordinary.
164      ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
165      if (IDI != ObjCInterfaceDecls.end())
166        return IDI->second;
167      ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
168      if (I != ObjCAliasDecls.end())
169        return I->second->getClassInterface();
170    }
171  }
172  return 0;
173}
174
175void Sema::InitBuiltinVaListType() {
176  if (!Context.getBuiltinVaListType().isNull())
177    return;
178
179  IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
180  Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
181  TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
182  Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
183}
184
185/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
186/// lazily create a decl for it.
187ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
188                                      Scope *S) {
189  Builtin::ID BID = (Builtin::ID)bid;
190
191  if (BID == Builtin::BI__builtin_va_start ||
192      BID == Builtin::BI__builtin_va_copy ||
193      BID == Builtin::BI__builtin_va_end)
194    InitBuiltinVaListType();
195
196  QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
197  FunctionDecl *New = FunctionDecl::Create(Context,
198                                           Context.getTranslationUnitDecl(),
199                                           SourceLocation(), II, R,
200                                           FunctionDecl::Extern, false, 0);
201
202  // Create Decl objects for each parameter, adding them to the
203  // FunctionDecl.
204  if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
205    llvm::SmallVector<ParmVarDecl*, 16> Params;
206    for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
207      Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
208                                           FT->getArgType(i), VarDecl::None, 0,
209                                           0));
210    New->setParams(&Params[0], Params.size());
211  }
212
213
214
215  // TUScope is the translation-unit scope to insert this function into.
216  PushOnScopeChains(New, TUScope);
217  return New;
218}
219
220/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
221/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
222/// situation, merging decls or emitting diagnostics as appropriate.
223///
224TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
225  // Verify the old decl was also a typedef.
226  TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
227  if (!Old) {
228    Diag(New->getLocation(), diag::err_redefinition_different_kind,
229         New->getName());
230    Diag(OldD->getLocation(), diag::err_previous_definition);
231    return New;
232  }
233
234  // Allow multiple definitions for ObjC built-in typedefs.
235  // FIXME: Verify the underlying types are equivalent!
236  if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
237    return Old;
238
239  // Redeclaration of a type is a constraint violation (6.7.2.3p1).
240  // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
241  // *either* declaration is in a system header. The code below implements
242  // this adhoc compatibility rule. FIXME: The following code will not
243  // work properly when compiling ".i" files (containing preprocessed output).
244  SourceManager &SrcMgr = Context.getSourceManager();
245  const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
246  const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
247  HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
248  DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
249  DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
250
251  // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
252  if ((OldDirType != DirectoryLookup::NormalHeaderDir ||
253       NewDirType != DirectoryLookup::NormalHeaderDir) ||
254      getLangOptions().Microsoft)
255    return New;
256
257  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
258  // TODO: This is totally simplistic.  It should handle merging functions
259  // together etc, merging extern int X; int X; ...
260  Diag(New->getLocation(), diag::err_redefinition, New->getName());
261  Diag(Old->getLocation(), diag::err_previous_definition);
262  return New;
263}
264
265/// DeclhasAttr - returns true if decl Declaration already has the target attribute.
266static bool DeclHasAttr(const Decl *decl, const Attr *target) {
267  for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
268    if (attr->getKind() == target->getKind())
269      return true;
270
271  return false;
272}
273
274/// MergeAttributes - append attributes from the Old decl to the New one.
275static void MergeAttributes(Decl *New, Decl *Old) {
276  Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
277
278// FIXME: fix this code to cleanup the Old attrs correctly
279  while (attr) {
280     tmp = attr;
281     attr = attr->getNext();
282
283    if (!DeclHasAttr(New, tmp)) {
284       New->addAttr(tmp);
285    } else {
286       tmp->setNext(0);
287       delete(tmp);
288    }
289  }
290}
291
292/// MergeFunctionDecl - We just parsed a function 'New' from
293/// declarator D which has the same name and scope as a previous
294/// declaration 'Old'.  Figure out how to resolve this situation,
295/// merging decls or emitting diagnostics as appropriate.
296/// Redeclaration will be set true if thisNew is a redeclaration OldD.
297FunctionDecl *
298Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
299  Redeclaration = false;
300  // Verify the old decl was also a function.
301  FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
302  if (!Old) {
303    Diag(New->getLocation(), diag::err_redefinition_different_kind,
304         New->getName());
305    Diag(OldD->getLocation(), diag::err_previous_definition);
306    return New;
307  }
308
309  QualType OldQType = Context.getCanonicalType(Old->getType());
310  QualType NewQType = Context.getCanonicalType(New->getType());
311
312  // C++ [dcl.fct]p3:
313  //   All declarations for a function shall agree exactly in both the
314  //   return type and the parameter-type-list.
315  if (getLangOptions().CPlusPlus && OldQType == NewQType) {
316    MergeAttributes(New, Old);
317    Redeclaration = true;
318    return MergeCXXFunctionDecl(New, Old);
319  }
320
321  // C: Function types need to be compatible, not identical. This handles
322  // duplicate function decls like "void f(int); void f(enum X);" properly.
323  if (!getLangOptions().CPlusPlus &&
324      Context.functionTypesAreCompatible(OldQType, NewQType)) {
325    MergeAttributes(New, Old);
326    Redeclaration = true;
327    return New;
328  }
329
330  // A function that has already been declared has been redeclared or defined
331  // with a different type- show appropriate diagnostic
332  diag::kind PrevDiag;
333  if (Old->isThisDeclarationADefinition())
334    PrevDiag = diag::err_previous_definition;
335  else if (Old->isImplicit())
336    PrevDiag = diag::err_previous_implicit_declaration;
337  else
338    PrevDiag = diag::err_previous_declaration;
339
340  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
341  // TODO: This is totally simplistic.  It should handle merging functions
342  // together etc, merging extern int X; int X; ...
343  Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
344  Diag(Old->getLocation(), PrevDiag);
345  return New;
346}
347
348/// equivalentArrayTypes - Used to determine whether two array types are
349/// equivalent.
350/// We need to check this explicitly as an incomplete array definition is
351/// considered a VariableArrayType, so will not match a complete array
352/// definition that would be otherwise equivalent.
353static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
354  const ArrayType *NewAT = NewQType->getAsArrayType();
355  const ArrayType *OldAT = OldQType->getAsArrayType();
356
357  if (!NewAT || !OldAT)
358    return false;
359
360  // If either (or both) array types in incomplete we need to strip off the
361  // outer VariableArrayType.  Once the outer VAT is removed the remaining
362  // types must be identical if the array types are to be considered
363  // equivalent.
364  // eg. int[][1] and int[1][1] become
365  //     VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
366  // removing the outermost VAT gives
367  //     CAT(1, int) and CAT(1, int)
368  // which are equal, therefore the array types are equivalent.
369  if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
370    if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
371      return false;
372    NewQType = NewAT->getElementType().getCanonicalType();
373    OldQType = OldAT->getElementType().getCanonicalType();
374  }
375
376  return NewQType == OldQType;
377}
378
379/// MergeVarDecl - We just parsed a variable 'New' which has the same name
380/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
381/// situation, merging decls or emitting diagnostics as appropriate.
382///
383/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
384/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
385///
386VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
387  // Verify the old decl was also a variable.
388  VarDecl *Old = dyn_cast<VarDecl>(OldD);
389  if (!Old) {
390    Diag(New->getLocation(), diag::err_redefinition_different_kind,
391         New->getName());
392    Diag(OldD->getLocation(), diag::err_previous_definition);
393    return New;
394  }
395
396  MergeAttributes(New, Old);
397
398  // Verify the types match.
399  QualType OldCType = Context.getCanonicalType(Old->getType());
400  QualType NewCType = Context.getCanonicalType(New->getType());
401  if (OldCType != NewCType && !areEquivalentArrayTypes(NewCType, OldCType)) {
402    Diag(New->getLocation(), diag::err_redefinition, New->getName());
403    Diag(Old->getLocation(), diag::err_previous_definition);
404    return New;
405  }
406  // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
407  if (New->getStorageClass() == VarDecl::Static &&
408      (Old->getStorageClass() == VarDecl::None ||
409       Old->getStorageClass() == VarDecl::Extern)) {
410    Diag(New->getLocation(), diag::err_static_non_static, New->getName());
411    Diag(Old->getLocation(), diag::err_previous_definition);
412    return New;
413  }
414  // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
415  if (New->getStorageClass() != VarDecl::Static &&
416      Old->getStorageClass() == VarDecl::Static) {
417    Diag(New->getLocation(), diag::err_non_static_static, New->getName());
418    Diag(Old->getLocation(), diag::err_previous_definition);
419    return New;
420  }
421  // We've verified the types match, now handle "tentative" definitions.
422  if (Old->isFileVarDecl() && New->isFileVarDecl()) {
423    // Handle C "tentative" external object definitions (C99 6.9.2).
424    bool OldIsTentative = false;
425    bool NewIsTentative = false;
426
427    if (!Old->getInit() &&
428        (Old->getStorageClass() == VarDecl::None ||
429         Old->getStorageClass() == VarDecl::Static))
430      OldIsTentative = true;
431
432    // FIXME: this check doesn't work (since the initializer hasn't been
433    // attached yet). This check should be moved to FinalizeDeclaratorGroup.
434    // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
435    // thrown out the old decl.
436    if (!New->getInit() &&
437        (New->getStorageClass() == VarDecl::None ||
438         New->getStorageClass() == VarDecl::Static))
439      ; // change to NewIsTentative = true; once the code is moved.
440
441    if (NewIsTentative || OldIsTentative)
442      return New;
443  }
444  // Handle __private_extern__ just like extern.
445  if (Old->getStorageClass() != VarDecl::Extern &&
446      Old->getStorageClass() != VarDecl::PrivateExtern &&
447      New->getStorageClass() != VarDecl::Extern &&
448      New->getStorageClass() != VarDecl::PrivateExtern) {
449    Diag(New->getLocation(), diag::err_redefinition, New->getName());
450    Diag(Old->getLocation(), diag::err_previous_definition);
451  }
452  return New;
453}
454
455/// CheckParmsForFunctionDef - Check that the parameters of the given
456/// function are appropriate for the definition of a function. This
457/// takes care of any checks that cannot be performed on the
458/// declaration itself, e.g., that the types of each of the function
459/// parameters are complete.
460bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
461  bool HasInvalidParm = false;
462  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
463    ParmVarDecl *Param = FD->getParamDecl(p);
464
465    // C99 6.7.5.3p4: the parameters in a parameter type list in a
466    // function declarator that is part of a function definition of
467    // that function shall not have incomplete type.
468    if (Param->getType()->isIncompleteType() &&
469        !Param->isInvalidDecl()) {
470      Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
471           Param->getType().getAsString());
472      Param->setInvalidDecl();
473      HasInvalidParm = true;
474    }
475  }
476
477  return HasInvalidParm;
478}
479
480/// CreateImplicitParameter - Creates an implicit function parameter
481/// in the scope S and with the given type. This routine is used, for
482/// example, to create the implicit "self" parameter in an Objective-C
483/// method.
484ParmVarDecl *
485Sema::CreateImplicitParameter(Scope *S, IdentifierInfo *Id,
486                              SourceLocation IdLoc, QualType Type) {
487  ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, IdLoc, Id, Type,
488                                         VarDecl::None, 0, 0);
489  if (Id)
490    PushOnScopeChains(New, S);
491
492  return New;
493}
494
495/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
496/// no declarator (e.g. "struct foo;") is parsed.
497Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
498  // TODO: emit error on 'int;' or 'const enum foo;'.
499  // TODO: emit error on 'typedef int;'
500  // if (!DS.isMissingDeclaratorOk()) Diag(...);
501
502  return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
503}
504
505bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
506  // Get the type before calling CheckSingleAssignmentConstraints(), since
507  // it can promote the expression.
508  QualType InitType = Init->getType();
509
510  AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
511  return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
512                                  InitType, Init, "initializing");
513}
514
515bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
516                         QualType ElementType) {
517  Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
518  if (CheckSingleInitializer(expr, ElementType))
519    return true; // types weren't compatible.
520
521  if (savExpr != expr) // The type was promoted, update initializer list.
522    IList->setInit(slot, expr);
523  return false;
524}
525
526bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
527  if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
528    // C99 6.7.8p14. We have an array of character type with unknown size
529    // being initialized to a string literal.
530    llvm::APSInt ConstVal(32);
531    ConstVal = strLiteral->getByteLength() + 1;
532    // Return a new array type (C99 6.7.8p22).
533    DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
534                                         ArrayType::Normal, 0);
535  } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
536    // C99 6.7.8p14. We have an array of character type with known size.
537    if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
538      Diag(strLiteral->getSourceRange().getBegin(),
539           diag::warn_initializer_string_for_char_array_too_long,
540           strLiteral->getSourceRange());
541  } else {
542    assert(0 && "HandleStringLiteralInit(): Invalid array type");
543  }
544  // Set type from "char *" to "constant array of char".
545  strLiteral->setType(DeclT);
546  // For now, we always return false (meaning success).
547  return false;
548}
549
550StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
551  const ArrayType *AT = DeclType->getAsArrayType();
552  if (AT && AT->getElementType()->isCharType()) {
553    return dyn_cast<StringLiteral>(Init);
554  }
555  return 0;
556}
557
558// CheckInitializerListTypes - Checks the types of elements of an initializer
559// list. This function is recursive: it calls itself to initialize subelements
560// of aggregate types.  Note that the topLevel parameter essentially refers to
561// whether this expression "owns" the initializer list passed in, or if this
562// initialization is taking elements out of a parent initializer.  Each
563// call to this function adds zero or more to startIndex, reports any errors,
564// and returns true if it found any inconsistent types.
565bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
566                                     bool topLevel, unsigned& startIndex) {
567  bool hadError = false;
568
569  if (DeclType->isScalarType()) {
570    // The simplest case: initializing a single scalar
571    if (topLevel) {
572      Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
573           IList->getSourceRange());
574    }
575    if (startIndex < IList->getNumInits()) {
576      Expr* expr = IList->getInit(startIndex);
577      if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
578        // FIXME: Should an error be reported here instead?
579        unsigned newIndex = 0;
580        CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
581      } else {
582        hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
583      }
584      ++startIndex;
585    }
586    // FIXME: Should an error be reported for empty initializer list + scalar?
587  } else if (DeclType->isVectorType()) {
588    if (startIndex < IList->getNumInits()) {
589      const VectorType *VT = DeclType->getAsVectorType();
590      int maxElements = VT->getNumElements();
591      QualType elementType = VT->getElementType();
592
593      for (int i = 0; i < maxElements; ++i) {
594        // Don't attempt to go past the end of the init list
595        if (startIndex >= IList->getNumInits())
596          break;
597        Expr* expr = IList->getInit(startIndex);
598        if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
599          unsigned newIndex = 0;
600          hadError |= CheckInitializerListTypes(SubInitList, elementType,
601                                                true, newIndex);
602          ++startIndex;
603        } else {
604          hadError |= CheckInitializerListTypes(IList, elementType,
605                                                false, startIndex);
606        }
607      }
608    }
609  } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
610    if (DeclType->isStructureType() || DeclType->isUnionType()) {
611      if (startIndex < IList->getNumInits() && !topLevel &&
612          Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
613                                     DeclType)) {
614        // We found a compatible struct; per the standard, this initializes the
615        // struct.  (The C standard technically says that this only applies for
616        // initializers for declarations with automatic scope; however, this
617        // construct is unambiguous anyway because a struct cannot contain
618        // a type compatible with itself. We'll output an error when we check
619        // if the initializer is constant.)
620        // FIXME: Is a call to CheckSingleInitializer required here?
621        ++startIndex;
622      } else {
623        RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
624
625        // If the record is invalid, some of it's members are invalid. To avoid
626        // confusion, we forgo checking the intializer for the entire record.
627        if (structDecl->isInvalidDecl())
628          return true;
629
630        // If structDecl is a forward declaration, this loop won't do anything;
631        // That's okay, because an error should get printed out elsewhere. It
632        // might be worthwhile to skip over the rest of the initializer, though.
633        int numMembers = structDecl->getNumMembers() -
634                         structDecl->hasFlexibleArrayMember();
635        for (int i = 0; i < numMembers; i++) {
636          // Don't attempt to go past the end of the init list
637          if (startIndex >= IList->getNumInits())
638            break;
639          FieldDecl * curField = structDecl->getMember(i);
640          if (!curField->getIdentifier()) {
641            // Don't initialize unnamed fields, e.g. "int : 20;"
642            continue;
643          }
644          QualType fieldType = curField->getType();
645          Expr* expr = IList->getInit(startIndex);
646          if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
647            unsigned newStart = 0;
648            hadError |= CheckInitializerListTypes(SubInitList, fieldType,
649                                                  true, newStart);
650            ++startIndex;
651          } else {
652            hadError |= CheckInitializerListTypes(IList, fieldType,
653                                                  false, startIndex);
654          }
655          if (DeclType->isUnionType())
656            break;
657        }
658        // FIXME: Implement flexible array initialization GCC extension (it's a
659        // really messy extension to implement, unfortunately...the necessary
660        // information isn't actually even here!)
661      }
662    } else if (DeclType->isArrayType()) {
663      // Check for the special-case of initializing an array with a string.
664      if (startIndex < IList->getNumInits()) {
665        if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
666                                                     DeclType)) {
667          CheckStringLiteralInit(lit, DeclType);
668          ++startIndex;
669          if (topLevel && startIndex < IList->getNumInits()) {
670            // We have leftover initializers; warn
671            Diag(IList->getInit(startIndex)->getLocStart(),
672                 diag::err_excess_initializers_in_char_array_initializer,
673                 IList->getInit(startIndex)->getSourceRange());
674          }
675          return false;
676        }
677      }
678      int maxElements;
679      if (DeclType->isIncompleteArrayType()) {
680        // FIXME: use a proper constant
681        maxElements = 0x7FFFFFFF;
682      } else if (const VariableArrayType *VAT =
683                                DeclType->getAsVariableArrayType()) {
684        // Check for VLAs; in standard C it would be possible to check this
685        // earlier, but I don't know where clang accepts VLAs (gcc accepts
686        // them in all sorts of strange places).
687        Diag(VAT->getSizeExpr()->getLocStart(),
688             diag::err_variable_object_no_init,
689             VAT->getSizeExpr()->getSourceRange());
690        hadError = true;
691        maxElements = 0x7FFFFFFF;
692      } else {
693        const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
694        maxElements = static_cast<int>(CAT->getSize().getZExtValue());
695      }
696      QualType elementType = DeclType->getAsArrayType()->getElementType();
697      int numElements = 0;
698      for (int i = 0; i < maxElements; ++i, ++numElements) {
699        // Don't attempt to go past the end of the init list
700        if (startIndex >= IList->getNumInits())
701          break;
702        Expr* expr = IList->getInit(startIndex);
703        if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
704          unsigned newIndex = 0;
705          hadError |= CheckInitializerListTypes(SubInitList, elementType,
706                                                true, newIndex);
707          ++startIndex;
708        } else {
709          hadError |= CheckInitializerListTypes(IList, elementType,
710                                                false, startIndex);
711        }
712      }
713      if (DeclType->isIncompleteArrayType()) {
714        // If this is an incomplete array type, the actual type needs to
715        // be calculated here
716        if (numElements == 0) {
717          // Sizing an array implicitly to zero is not allowed
718          // (It could in theory be allowed, but it doesn't really matter.)
719          Diag(IList->getLocStart(),
720               diag::err_at_least_one_initializer_needed_to_size_array);
721          hadError = true;
722        } else {
723          llvm::APSInt ConstVal(32);
724          ConstVal = numElements;
725          DeclType = Context.getConstantArrayType(elementType, ConstVal,
726                                                  ArrayType::Normal, 0);
727        }
728      }
729    } else {
730      assert(0 && "Aggregate that isn't a function or array?!");
731    }
732  } else {
733    // In C, all types are either scalars or aggregates, but
734    // additional handling is needed here for C++ (and possibly others?).
735    assert(0 && "Unsupported initializer type");
736  }
737
738  // If this init list is a base list, we set the type; an initializer doesn't
739  // fundamentally have a type, but this makes the ASTs a bit easier to read
740  if (topLevel)
741    IList->setType(DeclType);
742
743  if (topLevel && startIndex < IList->getNumInits()) {
744    // We have leftover initializers; warn
745    Diag(IList->getInit(startIndex)->getLocStart(),
746         diag::warn_excess_initializers,
747         IList->getInit(startIndex)->getSourceRange());
748  }
749  return hadError;
750}
751
752bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
753  // C99 6.7.8p3: The type of the entity to be initialized shall be an array
754  // of unknown size ("[]") or an object type that is not a variable array type.
755  if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
756    return Diag(VAT->getSizeExpr()->getLocStart(),
757                diag::err_variable_object_no_init,
758                VAT->getSizeExpr()->getSourceRange());
759
760  InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
761  if (!InitList) {
762    // FIXME: Handle wide strings
763    if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
764      return CheckStringLiteralInit(strLiteral, DeclType);
765
766    if (DeclType->isArrayType())
767      return Diag(Init->getLocStart(),
768                  diag::err_array_init_list_required,
769                  Init->getSourceRange());
770
771    return CheckSingleInitializer(Init, DeclType);
772  }
773#if 0
774  unsigned newIndex = 0;
775  return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
776#else
777  InitListChecker CheckInitList(this, InitList, DeclType);
778  return CheckInitList.HadError();
779#endif
780}
781
782Sema::DeclTy *
783Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
784  ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
785  IdentifierInfo *II = D.getIdentifier();
786
787  // All of these full declarators require an identifier.  If it doesn't have
788  // one, the ParsedFreeStandingDeclSpec action should be used.
789  if (II == 0) {
790    Diag(D.getDeclSpec().getSourceRange().getBegin(),
791         diag::err_declarator_need_ident,
792         D.getDeclSpec().getSourceRange(), D.getSourceRange());
793    return 0;
794  }
795
796  // The scope passed in may not be a decl scope.  Zip up the scope tree until
797  // we find one that is.
798  while ((S->getFlags() & Scope::DeclScope) == 0)
799    S = S->getParent();
800
801  // See if this is a redefinition of a variable in the same scope.
802  Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
803  ScopedDecl *New;
804  bool InvalidDecl = false;
805
806  // In C++, the previous declaration we find might be a tag type
807  // (class or enum). In this case, the new declaration will hide the
808  // tag type.
809  if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
810    PrevDecl = 0;
811
812  QualType R = GetTypeForDeclarator(D, S);
813  assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
814
815  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
816    // Check that there are no default arguments (C++ only).
817    if (getLangOptions().CPlusPlus)
818      CheckExtraCXXDefaultArguments(D);
819
820    TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
821    if (!NewTD) return 0;
822
823    // Handle attributes prior to checking for duplicates in MergeVarDecl
824    HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
825                         D.getAttributes());
826    // Merge the decl with the existing one if appropriate. If the decl is
827    // in an outer scope, it isn't the same thing.
828    if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
829      NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
830      if (NewTD == 0) return 0;
831    }
832    New = NewTD;
833    if (S->getFnParent() == 0) {
834      // C99 6.7.7p2: If a typedef name specifies a variably modified type
835      // then it shall have block scope.
836      if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
837        // FIXME: Diagnostic needs to be fixed.
838        Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
839        InvalidDecl = true;
840      }
841    }
842  } else if (R.getTypePtr()->isFunctionType()) {
843    FunctionDecl::StorageClass SC = FunctionDecl::None;
844    switch (D.getDeclSpec().getStorageClassSpec()) {
845      default: assert(0 && "Unknown storage class!");
846      case DeclSpec::SCS_auto:
847      case DeclSpec::SCS_register:
848        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
849             R.getAsString());
850        InvalidDecl = true;
851        break;
852      case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
853      case DeclSpec::SCS_extern:      SC = FunctionDecl::Extern; break;
854      case DeclSpec::SCS_static:      SC = FunctionDecl::Static; break;
855      case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
856    }
857
858    bool isInline = D.getDeclSpec().isInlineSpecified();
859    FunctionDecl *NewFD = FunctionDecl::Create(Context, CurContext,
860                                               D.getIdentifierLoc(),
861                                               II, R, SC, isInline,
862                                               LastDeclarator);
863    // Handle attributes.
864    HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
865                         D.getAttributes());
866
867    // Copy the parameter declarations from the declarator D to
868    // the function declaration NewFD, if they are available.
869    if (D.getNumTypeObjects() > 0 &&
870        D.getTypeObject(0).Fun.hasPrototype) {
871      DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
872
873      // Create Decl objects for each parameter, adding them to the
874      // FunctionDecl.
875      llvm::SmallVector<ParmVarDecl*, 16> Params;
876
877      // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
878      // function that takes no arguments, not a function that takes a
879      // single void argument.
880      if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
881          FTI.ArgInfo[0].Param &&
882          !((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
883          ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
884        // empty arg list, don't push any params.
885        ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
886
887        // In C++, the empty parameter-type-list must be spelled "void"; a
888        // typedef of void is not permitted.
889        if (getLangOptions().CPlusPlus &&
890            Param->getType() != Context.VoidTy) {
891          Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
892        }
893
894      } else {
895        for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
896          Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
897      }
898
899      NewFD->setParams(&Params[0], Params.size());
900    }
901
902    // Merge the decl with the existing one if appropriate. Since C functions
903    // are in a flat namespace, make sure we consider decls in outer scopes.
904    if (PrevDecl &&
905        (!getLangOptions().CPlusPlus ||
906         IdResolver.isDeclInScope(PrevDecl, CurContext, S)) ) {
907      bool Redeclaration = false;
908      NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration);
909      if (NewFD == 0) return 0;
910      if (Redeclaration) {
911        // Note that the new declaration is a redeclaration of the
912        // older declaration. Then return the older declaration: the
913        // new one is only kept within the set of previous
914        // declarations for this function.
915        FunctionDecl *OldFD = (FunctionDecl *)PrevDecl;
916        OldFD->AddRedeclaration(NewFD);
917        return OldFD;
918      }
919    }
920    New = NewFD;
921
922    // In C++, check default arguments now that we have merged decls.
923    if (getLangOptions().CPlusPlus)
924      CheckCXXDefaultArguments(NewFD);
925  } else {
926    // Check that there are no default arguments (C++ only).
927    if (getLangOptions().CPlusPlus)
928      CheckExtraCXXDefaultArguments(D);
929
930    if (R.getTypePtr()->isObjCInterfaceType()) {
931      Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
932           D.getIdentifier()->getName());
933      InvalidDecl = true;
934    }
935
936    VarDecl *NewVD;
937    VarDecl::StorageClass SC;
938    switch (D.getDeclSpec().getStorageClassSpec()) {
939    default: assert(0 && "Unknown storage class!");
940    case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
941    case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
942    case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
943    case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
944    case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
945    case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
946    }
947    if (S->getFnParent() == 0) {
948      // C99 6.9p2: The storage-class specifiers auto and register shall not
949      // appear in the declaration specifiers in an external declaration.
950      if (SC == VarDecl::Auto || SC == VarDecl::Register) {
951        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
952             R.getAsString());
953        InvalidDecl = true;
954      }
955      NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
956                              II, R, SC, LastDeclarator);
957    } else {
958      NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
959                              II, R, SC, LastDeclarator);
960    }
961    // Handle attributes prior to checking for duplicates in MergeVarDecl
962    HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
963                         D.getAttributes());
964
965    // Emit an error if an address space was applied to decl with local storage.
966    // This includes arrays of objects with address space qualifiers, but not
967    // automatic variables that point to other address spaces.
968    // ISO/IEC TR 18037 S5.1.2
969    if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
970      Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
971      InvalidDecl = true;
972    }
973    // Merge the decl with the existing one if appropriate. If the decl is
974    // in an outer scope, it isn't the same thing.
975    if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
976      NewVD = MergeVarDecl(NewVD, PrevDecl);
977      if (NewVD == 0) return 0;
978    }
979    New = NewVD;
980  }
981
982  // If this has an identifier, add it to the scope stack.
983  if (II)
984    PushOnScopeChains(New, S);
985  // If any semantic error occurred, mark the decl as invalid.
986  if (D.getInvalidType() || InvalidDecl)
987    New->setInvalidDecl();
988
989  return New;
990}
991
992bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
993  SourceLocation loc;
994  // FIXME: Remove the isReference check and handle assignment to a reference.
995  if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
996    assert(loc.isValid() && "isConstantExpr didn't return a loc!");
997    Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
998    return true;
999  }
1000  return false;
1001}
1002
1003void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
1004  Decl *RealDecl = static_cast<Decl *>(dcl);
1005  Expr *Init = static_cast<Expr *>(init);
1006  assert(Init && "missing initializer");
1007
1008  // If there is no declaration, there was an error parsing it.  Just ignore
1009  // the initializer.
1010  if (RealDecl == 0) {
1011    delete Init;
1012    return;
1013  }
1014
1015  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1016  if (!VDecl) {
1017    Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1018         diag::err_illegal_initializer);
1019    RealDecl->setInvalidDecl();
1020    return;
1021  }
1022  // Get the decls type and save a reference for later, since
1023  // CheckInitializerTypes may change it.
1024  QualType DclT = VDecl->getType(), SavT = DclT;
1025  if (VDecl->isBlockVarDecl()) {
1026    VarDecl::StorageClass SC = VDecl->getStorageClass();
1027    if (SC == VarDecl::Extern) { // C99 6.7.8p5
1028      Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
1029      VDecl->setInvalidDecl();
1030    } else if (!VDecl->isInvalidDecl()) {
1031      if (CheckInitializerTypes(Init, DclT))
1032        VDecl->setInvalidDecl();
1033      if (SC == VarDecl::Static) // C99 6.7.8p4.
1034        CheckForConstantInitializer(Init, DclT);
1035    }
1036  } else if (VDecl->isFileVarDecl()) {
1037    if (VDecl->getStorageClass() == VarDecl::Extern)
1038      Diag(VDecl->getLocation(), diag::warn_extern_init);
1039    if (!VDecl->isInvalidDecl())
1040      if (CheckInitializerTypes(Init, DclT))
1041        VDecl->setInvalidDecl();
1042
1043    // C99 6.7.8p4. All file scoped initializers need to be constant.
1044    CheckForConstantInitializer(Init, DclT);
1045  }
1046  // If the type changed, it means we had an incomplete type that was
1047  // completed by the initializer. For example:
1048  //   int ary[] = { 1, 3, 5 };
1049  // "ary" transitions from a VariableArrayType to a ConstantArrayType.
1050  if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
1051    VDecl->setType(DclT);
1052    Init->setType(DclT);
1053  }
1054
1055  // Attach the initializer to the decl.
1056  VDecl->setInit(Init);
1057  return;
1058}
1059
1060/// The declarators are chained together backwards, reverse the list.
1061Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1062  // Often we have single declarators, handle them quickly.
1063  Decl *GroupDecl = static_cast<Decl*>(group);
1064  if (GroupDecl == 0)
1065    return 0;
1066
1067  ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1068  ScopedDecl *NewGroup = 0;
1069  if (Group->getNextDeclarator() == 0)
1070    NewGroup = Group;
1071  else { // reverse the list.
1072    while (Group) {
1073      ScopedDecl *Next = Group->getNextDeclarator();
1074      Group->setNextDeclarator(NewGroup);
1075      NewGroup = Group;
1076      Group = Next;
1077    }
1078  }
1079  // Perform semantic analysis that depends on having fully processed both
1080  // the declarator and initializer.
1081  for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
1082    VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1083    if (!IDecl)
1084      continue;
1085    QualType T = IDecl->getType();
1086
1087    // C99 6.7.5.2p2: If an identifier is declared to be an object with
1088    // static storage duration, it shall not have a variable length array.
1089    if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1090        IDecl->getStorageClass() == VarDecl::Static) {
1091      if (T->getAsVariableArrayType()) {
1092        Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1093        IDecl->setInvalidDecl();
1094      }
1095    }
1096    // Block scope. C99 6.7p7: If an identifier for an object is declared with
1097    // no linkage (C99 6.2.2p6), the type for the object shall be complete...
1098    if (IDecl->isBlockVarDecl() &&
1099        IDecl->getStorageClass() != VarDecl::Extern) {
1100      if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
1101        Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1102             T.getAsString());
1103        IDecl->setInvalidDecl();
1104      }
1105    }
1106    // File scope. C99 6.9.2p2: A declaration of an identifier for and
1107    // object that has file scope without an initializer, and without a
1108    // storage-class specifier or with the storage-class specifier "static",
1109    // constitutes a tentative definition. Note: A tentative definition with
1110    // external linkage is valid (C99 6.2.2p5).
1111    if (IDecl && !IDecl->getInit() &&
1112        (IDecl->getStorageClass() == VarDecl::Static ||
1113         IDecl->getStorageClass() == VarDecl::None)) {
1114      if (T->isIncompleteArrayType()) {
1115        // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1116        // array to be completed. Don't issue a diagnostic.
1117      } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
1118        // C99 6.9.2p3: If the declaration of an identifier for an object is
1119        // a tentative definition and has internal linkage (C99 6.2.2p3), the
1120        // declared type shall not be an incomplete type.
1121        Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1122             T.getAsString());
1123        IDecl->setInvalidDecl();
1124      }
1125    }
1126  }
1127  return NewGroup;
1128}
1129
1130/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1131/// to introduce parameters into function prototype scope.
1132Sema::DeclTy *
1133Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
1134  DeclSpec &DS = D.getDeclSpec();
1135
1136  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1137  if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1138      DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1139    Diag(DS.getStorageClassSpecLoc(),
1140         diag::err_invalid_storage_class_in_func_decl);
1141    DS.ClearStorageClassSpecs();
1142  }
1143  if (DS.isThreadSpecified()) {
1144    Diag(DS.getThreadSpecLoc(),
1145         diag::err_invalid_storage_class_in_func_decl);
1146    DS.ClearStorageClassSpecs();
1147  }
1148
1149  // Check that there are no default arguments inside the type of this
1150  // parameter (C++ only).
1151  if (getLangOptions().CPlusPlus)
1152    CheckExtraCXXDefaultArguments(D);
1153
1154  // In this context, we *do not* check D.getInvalidType(). If the declarator
1155  // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1156  // though it will not reflect the user specified type.
1157  QualType parmDeclType = GetTypeForDeclarator(D, S);
1158
1159  assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1160
1161  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1162  // Can this happen for params?  We already checked that they don't conflict
1163  // among each other.  Here they can only shadow globals, which is ok.
1164  IdentifierInfo *II = D.getIdentifier();
1165  if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1166    if (S->isDeclScope(PrevDecl)) {
1167      Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1168           dyn_cast<NamedDecl>(PrevDecl)->getName());
1169
1170      // Recover by removing the name
1171      II = 0;
1172      D.SetIdentifier(0, D.getIdentifierLoc());
1173    }
1174  }
1175
1176  // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1177  // Doing the promotion here has a win and a loss. The win is the type for
1178  // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1179  // code generator). The loss is the orginal type isn't preserved. For example:
1180  //
1181  // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1182  //    int blockvardecl[5];
1183  //    sizeof(parmvardecl);  // size == 4
1184  //    sizeof(blockvardecl); // size == 20
1185  // }
1186  //
1187  // For expressions, all implicit conversions are captured using the
1188  // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1189  //
1190  // FIXME: If a source translation tool needs to see the original type, then
1191  // we need to consider storing both types (in ParmVarDecl)...
1192  //
1193  if (parmDeclType->isArrayType()) {
1194    // int x[restrict 4] ->  int *restrict
1195    parmDeclType = Context.getArrayDecayedType(parmDeclType);
1196  } else if (parmDeclType->isFunctionType())
1197    parmDeclType = Context.getPointerType(parmDeclType);
1198
1199  ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1200                                         D.getIdentifierLoc(), II,
1201                                         parmDeclType, VarDecl::None,
1202                                         0, 0);
1203
1204  if (D.getInvalidType())
1205    New->setInvalidDecl();
1206
1207  if (II)
1208    PushOnScopeChains(New, S);
1209
1210  HandleDeclAttributes(New, D.getDeclSpec().getAttributes(),
1211                       D.getAttributes());
1212  return New;
1213
1214}
1215
1216Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
1217  assert(CurFunctionDecl == 0 && "Function parsing confused");
1218  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1219         "Not a function declarator!");
1220  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1221
1222  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1223  // for a K&R function.
1224  if (!FTI.hasPrototype) {
1225    for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1226      if (FTI.ArgInfo[i].Param == 0) {
1227        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1228             FTI.ArgInfo[i].Ident->getName());
1229        // Implicitly declare the argument as type 'int' for lack of a better
1230        // type.
1231        DeclSpec DS;
1232        const char* PrevSpec; // unused
1233        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1234                           PrevSpec);
1235        Declarator ParamD(DS, Declarator::KNRTypeListContext);
1236        ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1237        FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
1238      }
1239    }
1240
1241    // Since this is a function definition, act as though we have information
1242    // about the arguments.
1243    if (FTI.NumArgs)
1244      FTI.hasPrototype = true;
1245  } else {
1246    // FIXME: Diagnose arguments without names in C.
1247  }
1248
1249  Scope *GlobalScope = FnBodyScope->getParent();
1250
1251  // See if this is a redefinition.
1252  Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
1253                             GlobalScope);
1254  if (PrevDcl && IdResolver.isDeclInScope(PrevDcl, CurContext)) {
1255    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) {
1256      const FunctionDecl *Definition;
1257      if (FD->getBody(Definition)) {
1258        Diag(D.getIdentifierLoc(), diag::err_redefinition,
1259             D.getIdentifier()->getName());
1260        Diag(Definition->getLocation(), diag::err_previous_definition);
1261      }
1262    }
1263  }
1264  Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
1265  FunctionDecl *FD = cast<FunctionDecl>(decl);
1266  CurFunctionDecl = FD;
1267  PushDeclContext(FD);
1268
1269  // Check the validity of our function parameters
1270  CheckParmsForFunctionDef(FD);
1271
1272  // Introduce our parameters into the function scope
1273  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1274    ParmVarDecl *Param = FD->getParamDecl(p);
1275    // If this has an identifier, add it to the scope stack.
1276    if (Param->getIdentifier())
1277      PushOnScopeChains(Param, FnBodyScope);
1278  }
1279
1280  return FD;
1281}
1282
1283Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1284  Decl *dcl = static_cast<Decl *>(D);
1285  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1286    FD->setBody((Stmt*)Body);
1287    assert(FD == CurFunctionDecl && "Function parsing confused");
1288    CurFunctionDecl = 0;
1289  } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
1290    MD->setBody((Stmt*)Body);
1291    CurMethodDecl = 0;
1292  }
1293  PopDeclContext();
1294  // Verify and clean out per-function state.
1295
1296  // Check goto/label use.
1297  for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1298       I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1299    // Verify that we have no forward references left.  If so, there was a goto
1300    // or address of a label taken, but no definition of it.  Label fwd
1301    // definitions are indicated with a null substmt.
1302    if (I->second->getSubStmt() == 0) {
1303      LabelStmt *L = I->second;
1304      // Emit error.
1305      Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1306
1307      // At this point, we have gotos that use the bogus label.  Stitch it into
1308      // the function body so that they aren't leaked and that the AST is well
1309      // formed.
1310      if (Body) {
1311        L->setSubStmt(new NullStmt(L->getIdentLoc()));
1312        cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1313      } else {
1314        // The whole function wasn't parsed correctly, just delete this.
1315        delete L;
1316      }
1317    }
1318  }
1319  LabelMap.clear();
1320
1321  return D;
1322}
1323
1324/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1325/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
1326ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1327                                           IdentifierInfo &II, Scope *S) {
1328  // Extension in C99.  Legal in C90, but warn about it.
1329  if (getLangOptions().C99)
1330    Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1331  else
1332    Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1333
1334  // FIXME: handle stuff like:
1335  // void foo() { extern float X(); }
1336  // void bar() { X(); }  <-- implicit decl for X in another scope.
1337
1338  // Set a Declarator for the implicit definition: int foo();
1339  const char *Dummy;
1340  DeclSpec DS;
1341  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1342  Error = Error; // Silence warning.
1343  assert(!Error && "Error setting up implicit decl!");
1344  Declarator D(DS, Declarator::BlockContext);
1345  D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1346  D.SetIdentifier(&II, Loc);
1347
1348  // Insert this function into translation-unit scope.
1349
1350  DeclContext *PrevDC = CurContext;
1351  CurContext = Context.getTranslationUnitDecl();
1352
1353  FunctionDecl *FD =
1354    dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
1355  FD->setImplicit();
1356
1357  CurContext = PrevDC;
1358
1359  return FD;
1360}
1361
1362
1363TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
1364                                    ScopedDecl *LastDeclarator) {
1365  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
1366  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1367
1368  // Scope manipulation handled by caller.
1369  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1370                                           D.getIdentifierLoc(),
1371                                           D.getIdentifier(),
1372                                           T, LastDeclarator);
1373  if (D.getInvalidType())
1374    NewTD->setInvalidDecl();
1375  return NewTD;
1376}
1377
1378/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
1379/// former case, Name will be non-null.  In the later case, Name will be null.
1380/// TagType indicates what kind of tag this is. TK indicates whether this is a
1381/// reference/declaration/definition of a tag.
1382Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
1383                             SourceLocation KWLoc, IdentifierInfo *Name,
1384                             SourceLocation NameLoc, AttributeList *Attr) {
1385  // If this is a use of an existing tag, it must have a name.
1386  assert((Name != 0 || TK == TK_Definition) &&
1387         "Nameless record must be a definition!");
1388
1389  Decl::Kind Kind;
1390  switch (TagType) {
1391  default: assert(0 && "Unknown tag type!");
1392  case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1393  case DeclSpec::TST_union:  Kind = Decl::Union; break;
1394  case DeclSpec::TST_class:  Kind = Decl::Class; break;
1395  case DeclSpec::TST_enum:   Kind = Decl::Enum; break;
1396  }
1397
1398  // If this is a named struct, check to see if there was a previous forward
1399  // declaration or definition.
1400  // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
1401  if (ScopedDecl *PrevDecl =
1402          dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
1403
1404    assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1405            "unexpected Decl type");
1406    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
1407      // If this is a use of a previous tag, or if the tag is already declared in
1408      // the same scope (so that the definition/declaration completes or
1409      // rementions the tag), reuse the decl.
1410      if (TK == TK_Reference ||
1411          IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
1412        // Make sure that this wasn't declared as an enum and now used as a struct
1413        // or something similar.
1414        if (PrevDecl->getKind() != Kind) {
1415          Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1416          Diag(PrevDecl->getLocation(), diag::err_previous_use);
1417        }
1418
1419        // If this is a use or a forward declaration, we're good.
1420        if (TK != TK_Definition)
1421          return PrevDecl;
1422
1423        // Diagnose attempts to redefine a tag.
1424        if (PrevTagDecl->isDefinition()) {
1425          Diag(NameLoc, diag::err_redefinition, Name->getName());
1426          Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1427          // If this is a redefinition, recover by making this struct be
1428          // anonymous, which will make any later references get the previous
1429          // definition.
1430          Name = 0;
1431        } else {
1432          // Okay, this is definition of a previously declared or referenced tag.
1433          // Move the location of the decl to be the definition site.
1434          PrevDecl->setLocation(NameLoc);
1435          return PrevDecl;
1436        }
1437      }
1438      // If we get here, this is a definition of a new struct type in a nested
1439      // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1440      // type.
1441    } else {
1442      // The tag name clashes with a namespace name, issue an error and recover
1443      // by making this tag be anonymous.
1444      Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1445      Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1446      Name = 0;
1447    }
1448  }
1449
1450  // If there is an identifier, use the location of the identifier as the
1451  // location of the decl, otherwise use the location of the struct/union
1452  // keyword.
1453  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1454
1455  // Otherwise, if this is the first time we've seen this tag, create the decl.
1456  TagDecl *New;
1457  switch (Kind) {
1458  default: assert(0 && "Unknown tag kind!");
1459  case Decl::Enum:
1460    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1461    // enum X { A, B, C } D;    D should chain to X.
1462    New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
1463    // If this is an undefined enum, warn.
1464    if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1465    break;
1466  case Decl::Union:
1467  case Decl::Struct:
1468  case Decl::Class:
1469    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1470    // struct X { int A; } D;    D should chain to X.
1471    New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
1472    break;
1473  }
1474
1475  // If this has an identifier, add it to the scope stack.
1476  if (Name) {
1477    // The scope passed in may not be a decl scope.  Zip up the scope tree until
1478    // we find one that is.
1479    while ((S->getFlags() & Scope::DeclScope) == 0)
1480      S = S->getParent();
1481
1482    // Add it to the decl chain.
1483    PushOnScopeChains(New, S);
1484  }
1485
1486  HandleDeclAttributes(New, Attr, 0);
1487  return New;
1488}
1489
1490/// ActOnField - Each field of a struct/union/class is passed into this in order
1491/// to create a FieldDecl object for it.
1492Sema::DeclTy *Sema::ActOnField(Scope *S,
1493                               SourceLocation DeclStart,
1494                               Declarator &D, ExprTy *BitfieldWidth) {
1495  IdentifierInfo *II = D.getIdentifier();
1496  Expr *BitWidth = (Expr*)BitfieldWidth;
1497  SourceLocation Loc = DeclStart;
1498  if (II) Loc = D.getIdentifierLoc();
1499
1500  // FIXME: Unnamed fields can be handled in various different ways, for
1501  // example, unnamed unions inject all members into the struct namespace!
1502
1503
1504  if (BitWidth) {
1505    // TODO: Validate.
1506    //printf("WARNING: BITFIELDS IGNORED!\n");
1507
1508    // 6.7.2.1p3
1509    // 6.7.2.1p4
1510
1511  } else {
1512    // Not a bitfield.
1513
1514    // validate II.
1515
1516  }
1517
1518  QualType T = GetTypeForDeclarator(D, S);
1519  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1520  bool InvalidDecl = false;
1521
1522  // C99 6.7.2.1p8: A member of a structure or union may have any type other
1523  // than a variably modified type.
1524  if (T->isVariablyModifiedType()) {
1525    // FIXME: This diagnostic needs work
1526    Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1527    InvalidDecl = true;
1528  }
1529  // FIXME: Chain fielddecls together.
1530  FieldDecl *NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
1531
1532  HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1533                       D.getAttributes());
1534
1535  if (D.getInvalidType() || InvalidDecl)
1536    NewFD->setInvalidDecl();
1537  return NewFD;
1538}
1539
1540/// TranslateIvarVisibility - Translate visibility from a token ID to an
1541///  AST enum value.
1542static ObjCIvarDecl::AccessControl
1543TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
1544  switch (ivarVisibility) {
1545    case tok::objc_private: return ObjCIvarDecl::Private;
1546    case tok::objc_public: return ObjCIvarDecl::Public;
1547    case tok::objc_protected: return ObjCIvarDecl::Protected;
1548    case tok::objc_package: return ObjCIvarDecl::Package;
1549    default: assert(false && "Unknown visitibility kind");
1550  }
1551}
1552
1553/// ActOnIvar - Each ivar field of an objective-c class is passed into this
1554/// in order to create an IvarDecl object for it.
1555Sema::DeclTy *Sema::ActOnIvar(Scope *S,
1556                              SourceLocation DeclStart,
1557                              Declarator &D, ExprTy *BitfieldWidth,
1558                              tok::ObjCKeywordKind Visibility) {
1559  IdentifierInfo *II = D.getIdentifier();
1560  Expr *BitWidth = (Expr*)BitfieldWidth;
1561  SourceLocation Loc = DeclStart;
1562  if (II) Loc = D.getIdentifierLoc();
1563
1564  // FIXME: Unnamed fields can be handled in various different ways, for
1565  // example, unnamed unions inject all members into the struct namespace!
1566
1567
1568  if (BitWidth) {
1569    // TODO: Validate.
1570    //printf("WARNING: BITFIELDS IGNORED!\n");
1571
1572    // 6.7.2.1p3
1573    // 6.7.2.1p4
1574
1575  } else {
1576    // Not a bitfield.
1577
1578    // validate II.
1579
1580  }
1581
1582  QualType T = GetTypeForDeclarator(D, S);
1583  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1584  bool InvalidDecl = false;
1585
1586  // C99 6.7.2.1p8: A member of a structure or union may have any type other
1587  // than a variably modified type.
1588  if (T->isVariablyModifiedType()) {
1589    // FIXME: This diagnostic needs work
1590    Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1591    InvalidDecl = true;
1592  }
1593
1594  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T);
1595
1596  HandleDeclAttributes(NewID, D.getDeclSpec().getAttributes(),
1597                       D.getAttributes());
1598
1599  if (D.getInvalidType() || InvalidDecl)
1600    NewID->setInvalidDecl();
1601  // If we have visibility info, make sure the AST is set accordingly.
1602  if (Visibility != tok::objc_not_keyword)
1603    NewID->setAccessControl(TranslateIvarVisibility(Visibility));
1604  return NewID;
1605}
1606
1607void Sema::ActOnFields(Scope* S,
1608                       SourceLocation RecLoc, DeclTy *RecDecl,
1609                       DeclTy **Fields, unsigned NumFields,
1610                       SourceLocation LBrac, SourceLocation RBrac) {
1611  Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1612  assert(EnclosingDecl && "missing record or interface decl");
1613  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1614
1615  if (Record && Record->isDefinition()) {
1616    // Diagnose code like:
1617    //     struct S { struct S {} X; };
1618    // We discover this when we complete the outer S.  Reject and ignore the
1619    // outer S.
1620    Diag(Record->getLocation(), diag::err_nested_redefinition,
1621         Record->getKindName());
1622    Diag(RecLoc, diag::err_previous_definition);
1623    Record->setInvalidDecl();
1624    return;
1625  }
1626  // Verify that all the fields are okay.
1627  unsigned NumNamedMembers = 0;
1628  llvm::SmallVector<FieldDecl*, 32> RecFields;
1629  llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
1630
1631  for (unsigned i = 0; i != NumFields; ++i) {
1632
1633    FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1634    assert(FD && "missing field decl");
1635
1636    // Remember all fields.
1637    RecFields.push_back(FD);
1638
1639    // Get the type for the field.
1640    Type *FDTy = FD->getType().getTypePtr();
1641
1642    // C99 6.7.2.1p2 - A field may not be a function type.
1643    if (FDTy->isFunctionType()) {
1644      Diag(FD->getLocation(), diag::err_field_declared_as_function,
1645           FD->getName());
1646      FD->setInvalidDecl();
1647      EnclosingDecl->setInvalidDecl();
1648      continue;
1649    }
1650    // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1651    if (FDTy->isIncompleteType()) {
1652      if (!Record) {  // Incomplete ivar type is always an error.
1653        Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
1654        FD->setInvalidDecl();
1655        EnclosingDecl->setInvalidDecl();
1656        continue;
1657      }
1658      if (i != NumFields-1 ||                   // ... that the last member ...
1659          Record->getKind() != Decl::Struct ||  // ... of a structure ...
1660          !FDTy->isArrayType()) {         //... may have incomplete array type.
1661        Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
1662        FD->setInvalidDecl();
1663        EnclosingDecl->setInvalidDecl();
1664        continue;
1665      }
1666      if (NumNamedMembers < 1) {  //... must have more than named member ...
1667        Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1668             FD->getName());
1669        FD->setInvalidDecl();
1670        EnclosingDecl->setInvalidDecl();
1671        continue;
1672      }
1673      // Okay, we have a legal flexible array member at the end of the struct.
1674      if (Record)
1675        Record->setHasFlexibleArrayMember(true);
1676    }
1677    /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1678    /// field of another structure or the element of an array.
1679    if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
1680      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1681        // If this is a member of a union, then entire union becomes "flexible".
1682        if (Record && Record->getKind() == Decl::Union) {
1683          Record->setHasFlexibleArrayMember(true);
1684        } else {
1685          // If this is a struct/class and this is not the last element, reject
1686          // it.  Note that GCC supports variable sized arrays in the middle of
1687          // structures.
1688          if (i != NumFields-1) {
1689            Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1690                 FD->getName());
1691            FD->setInvalidDecl();
1692            EnclosingDecl->setInvalidDecl();
1693            continue;
1694          }
1695          // We support flexible arrays at the end of structs in other structs
1696          // as an extension.
1697          Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1698               FD->getName());
1699          if (Record)
1700            Record->setHasFlexibleArrayMember(true);
1701        }
1702      }
1703    }
1704    /// A field cannot be an Objective-c object
1705    if (FDTy->isObjCInterfaceType()) {
1706      Diag(FD->getLocation(), diag::err_statically_allocated_object,
1707           FD->getName());
1708      FD->setInvalidDecl();
1709      EnclosingDecl->setInvalidDecl();
1710      continue;
1711    }
1712    // Keep track of the number of named members.
1713    if (IdentifierInfo *II = FD->getIdentifier()) {
1714      // Detect duplicate member names.
1715      if (!FieldIDs.insert(II)) {
1716        Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1717        // Find the previous decl.
1718        SourceLocation PrevLoc;
1719        for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1720          assert(i != e && "Didn't find previous def!");
1721          if (RecFields[i]->getIdentifier() == II) {
1722            PrevLoc = RecFields[i]->getLocation();
1723            break;
1724          }
1725        }
1726        Diag(PrevLoc, diag::err_previous_definition);
1727        FD->setInvalidDecl();
1728        EnclosingDecl->setInvalidDecl();
1729        continue;
1730      }
1731      ++NumNamedMembers;
1732    }
1733  }
1734
1735  // Okay, we successfully defined 'Record'.
1736  if (Record) {
1737    Record->defineBody(&RecFields[0], RecFields.size());
1738    Consumer.HandleTagDeclDefinition(Record);
1739  } else {
1740    ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1741    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
1742      ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
1743    else if (ObjCImplementationDecl *IMPDecl =
1744               dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
1745      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1746      IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
1747      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
1748    }
1749  }
1750}
1751
1752Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
1753                                      DeclTy *lastEnumConst,
1754                                      SourceLocation IdLoc, IdentifierInfo *Id,
1755                                      SourceLocation EqualLoc, ExprTy *val) {
1756  EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
1757  EnumConstantDecl *LastEnumConst =
1758    cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1759  Expr *Val = static_cast<Expr*>(val);
1760
1761  // The scope passed in may not be a decl scope.  Zip up the scope tree until
1762  // we find one that is.
1763  while ((S->getFlags() & Scope::DeclScope) == 0)
1764    S = S->getParent();
1765
1766  // Verify that there isn't already something declared with this name in this
1767  // scope.
1768  if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
1769    if (IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
1770      if (isa<EnumConstantDecl>(PrevDecl))
1771        Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1772      else
1773        Diag(IdLoc, diag::err_redefinition, Id->getName());
1774      Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1775      delete Val;
1776      return 0;
1777    }
1778  }
1779
1780  llvm::APSInt EnumVal(32);
1781  QualType EltTy;
1782  if (Val) {
1783    // Make sure to promote the operand type to int.
1784    UsualUnaryConversions(Val);
1785
1786    // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1787    SourceLocation ExpLoc;
1788    if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
1789      Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1790           Id->getName());
1791      delete Val;
1792      Val = 0;  // Just forget about it.
1793    } else {
1794      EltTy = Val->getType();
1795    }
1796  }
1797
1798  if (!Val) {
1799    if (LastEnumConst) {
1800      // Assign the last value + 1.
1801      EnumVal = LastEnumConst->getInitVal();
1802      ++EnumVal;
1803
1804      // Check for overflow on increment.
1805      if (EnumVal < LastEnumConst->getInitVal())
1806        Diag(IdLoc, diag::warn_enum_value_overflow);
1807
1808      EltTy = LastEnumConst->getType();
1809    } else {
1810      // First value, set to zero.
1811      EltTy = Context.IntTy;
1812      EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
1813    }
1814  }
1815
1816  EnumConstantDecl *New =
1817    EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
1818                             Val, EnumVal,
1819                             LastEnumConst);
1820
1821  // Register this decl in the current scope stack.
1822  PushOnScopeChains(New, S);
1823  return New;
1824}
1825
1826void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
1827                         DeclTy **Elements, unsigned NumElements) {
1828  EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1829  assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1830
1831  // TODO: If the result value doesn't fit in an int, it must be a long or long
1832  // long value.  ISO C does not support this, but GCC does as an extension,
1833  // emit a warning.
1834  unsigned IntWidth = Context.Target.getIntWidth();
1835
1836  // Verify that all the values are okay, compute the size of the values, and
1837  // reverse the list.
1838  unsigned NumNegativeBits = 0;
1839  unsigned NumPositiveBits = 0;
1840
1841  // Keep track of whether all elements have type int.
1842  bool AllElementsInt = true;
1843
1844  EnumConstantDecl *EltList = 0;
1845  for (unsigned i = 0; i != NumElements; ++i) {
1846    EnumConstantDecl *ECD =
1847      cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1848    if (!ECD) continue;  // Already issued a diagnostic.
1849
1850    // If the enum value doesn't fit in an int, emit an extension warning.
1851    const llvm::APSInt &InitVal = ECD->getInitVal();
1852    assert(InitVal.getBitWidth() >= IntWidth &&
1853           "Should have promoted value to int");
1854    if (InitVal.getBitWidth() > IntWidth) {
1855      llvm::APSInt V(InitVal);
1856      V.trunc(IntWidth);
1857      V.extend(InitVal.getBitWidth());
1858      if (V != InitVal)
1859        Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1860             InitVal.toString());
1861    }
1862
1863    // Keep track of the size of positive and negative values.
1864    if (InitVal.isUnsigned() || InitVal.isNonNegative())
1865      NumPositiveBits = std::max(NumPositiveBits,
1866                                 (unsigned)InitVal.getActiveBits());
1867    else
1868      NumNegativeBits = std::max(NumNegativeBits,
1869                                 (unsigned)InitVal.getMinSignedBits());
1870
1871    // Keep track of whether every enum element has type int (very commmon).
1872    if (AllElementsInt)
1873      AllElementsInt = ECD->getType() == Context.IntTy;
1874
1875    ECD->setNextDeclarator(EltList);
1876    EltList = ECD;
1877  }
1878
1879  // Figure out the type that should be used for this enum.
1880  // FIXME: Support attribute(packed) on enums and -fshort-enums.
1881  QualType BestType;
1882  unsigned BestWidth;
1883
1884  if (NumNegativeBits) {
1885    // If there is a negative value, figure out the smallest integer type (of
1886    // int/long/longlong) that fits.
1887    if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
1888      BestType = Context.IntTy;
1889      BestWidth = IntWidth;
1890    } else {
1891      BestWidth = Context.Target.getLongWidth();
1892
1893      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
1894        BestType = Context.LongTy;
1895      else {
1896        BestWidth = Context.Target.getLongLongWidth();
1897
1898        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
1899          Diag(Enum->getLocation(), diag::warn_enum_too_large);
1900        BestType = Context.LongLongTy;
1901      }
1902    }
1903  } else {
1904    // If there is no negative value, figure out which of uint, ulong, ulonglong
1905    // fits.
1906    if (NumPositiveBits <= IntWidth) {
1907      BestType = Context.UnsignedIntTy;
1908      BestWidth = IntWidth;
1909    } else if (NumPositiveBits <=
1910               (BestWidth = Context.Target.getLongWidth())) {
1911      BestType = Context.UnsignedLongTy;
1912    } else {
1913      BestWidth = Context.Target.getLongLongWidth();
1914      assert(NumPositiveBits <= BestWidth &&
1915             "How could an initializer get larger than ULL?");
1916      BestType = Context.UnsignedLongLongTy;
1917    }
1918  }
1919
1920  // Loop over all of the enumerator constants, changing their types to match
1921  // the type of the enum if needed.
1922  for (unsigned i = 0; i != NumElements; ++i) {
1923    EnumConstantDecl *ECD =
1924      cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1925    if (!ECD) continue;  // Already issued a diagnostic.
1926
1927    // Standard C says the enumerators have int type, but we allow, as an
1928    // extension, the enumerators to be larger than int size.  If each
1929    // enumerator value fits in an int, type it as an int, otherwise type it the
1930    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
1931    // that X has type 'int', not 'unsigned'.
1932    if (ECD->getType() == Context.IntTy) {
1933      // Make sure the init value is signed.
1934      llvm::APSInt IV = ECD->getInitVal();
1935      IV.setIsSigned(true);
1936      ECD->setInitVal(IV);
1937      continue;  // Already int type.
1938    }
1939
1940    // Determine whether the value fits into an int.
1941    llvm::APSInt InitVal = ECD->getInitVal();
1942    bool FitsInInt;
1943    if (InitVal.isUnsigned() || !InitVal.isNegative())
1944      FitsInInt = InitVal.getActiveBits() < IntWidth;
1945    else
1946      FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1947
1948    // If it fits into an integer type, force it.  Otherwise force it to match
1949    // the enum decl type.
1950    QualType NewTy;
1951    unsigned NewWidth;
1952    bool NewSign;
1953    if (FitsInInt) {
1954      NewTy = Context.IntTy;
1955      NewWidth = IntWidth;
1956      NewSign = true;
1957    } else if (ECD->getType() == BestType) {
1958      // Already the right type!
1959      continue;
1960    } else {
1961      NewTy = BestType;
1962      NewWidth = BestWidth;
1963      NewSign = BestType->isSignedIntegerType();
1964    }
1965
1966    // Adjust the APSInt value.
1967    InitVal.extOrTrunc(NewWidth);
1968    InitVal.setIsSigned(NewSign);
1969    ECD->setInitVal(InitVal);
1970
1971    // Adjust the Expr initializer and type.
1972    ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1973    ECD->setType(NewTy);
1974  }
1975
1976  Enum->defineElements(EltList, BestType);
1977  Consumer.HandleTagDeclDefinition(Enum);
1978}
1979
1980Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
1981                                          ExprTy *expr) {
1982  StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
1983
1984  return FileScopeAsmDecl::Create(Context, Loc, AsmString);
1985}
1986
1987Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
1988                                     SourceLocation LBrace,
1989                                     SourceLocation RBrace,
1990                                     const char *Lang,
1991                                     unsigned StrSize,
1992                                     DeclTy *D) {
1993  LinkageSpecDecl::LanguageIDs Language;
1994  Decl *dcl = static_cast<Decl *>(D);
1995  if (strncmp(Lang, "\"C\"", StrSize) == 0)
1996    Language = LinkageSpecDecl::lang_c;
1997  else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1998    Language = LinkageSpecDecl::lang_cxx;
1999  else {
2000    Diag(Loc, diag::err_bad_language);
2001    return 0;
2002  }
2003
2004  // FIXME: Add all the various semantics of linkage specifications
2005  return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
2006}
2007
2008void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) {
2009
2010  switch (Attr->getKind()) {
2011  case AttributeList::AT_vector_size:
2012    if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
2013      QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
2014      if (!newType.isNull()) // install the new vector type into the decl
2015        vDecl->setType(newType);
2016    }
2017    if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2018      QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
2019                                                   Attr);
2020      if (!newType.isNull()) // install the new vector type into the decl
2021        tDecl->setUnderlyingType(newType);
2022    }
2023    break;
2024  case AttributeList::AT_ext_vector_type:
2025    if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
2026      HandleExtVectorTypeAttribute(tDecl, Attr);
2027    else
2028      Diag(Attr->getLoc(),
2029           diag::err_typecheck_ext_vector_not_typedef);
2030    break;
2031  case AttributeList::AT_address_space:
2032    if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2033      QualType newType = HandleAddressSpaceTypeAttribute(
2034                                                  tDecl->getUnderlyingType(),
2035                                                  Attr);
2036      tDecl->setUnderlyingType(newType);
2037    } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
2038      QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
2039                                                         Attr);
2040      // install the new addr spaced type into the decl
2041      vDecl->setType(newType);
2042    }
2043    break;
2044  case AttributeList::AT_deprecated:
2045    HandleDeprecatedAttribute(New, Attr);
2046    break;
2047  case AttributeList::AT_visibility:
2048    HandleVisibilityAttribute(New, Attr);
2049    break;
2050  case AttributeList::AT_weak:
2051    HandleWeakAttribute(New, Attr);
2052    break;
2053  case AttributeList::AT_dllimport:
2054    HandleDLLImportAttribute(New, Attr);
2055    break;
2056  case AttributeList::AT_dllexport:
2057    HandleDLLExportAttribute(New, Attr);
2058    break;
2059  case AttributeList::AT_nothrow:
2060    HandleNothrowAttribute(New, Attr);
2061    break;
2062  case AttributeList::AT_stdcall:
2063    HandleStdCallAttribute(New, Attr);
2064    break;
2065  case AttributeList::AT_fastcall:
2066    HandleFastCallAttribute(New, Attr);
2067    break;
2068  case AttributeList::AT_aligned:
2069    HandleAlignedAttribute(New, Attr);
2070    break;
2071  case AttributeList::AT_packed:
2072    HandlePackedAttribute(New, Attr);
2073    break;
2074  case AttributeList::AT_annotate:
2075    HandleAnnotateAttribute(New, Attr);
2076    break;
2077  case AttributeList::AT_noreturn:
2078    HandleNoReturnAttribute(New, Attr);
2079    break;
2080  case AttributeList::AT_format:
2081    HandleFormatAttribute(New, Attr);
2082    break;
2083  case AttributeList::AT_transparent_union:
2084    HandleTransparentUnionAttribute(New, Attr);
2085    break;
2086  default:
2087#if 0
2088    // TODO: when we have the full set of attributes, warn about unknown ones.
2089    Diag(Attr->getLoc(), diag::warn_attribute_ignored,
2090         Attr->getName()->getName());
2091#endif
2092    break;
2093  }
2094}
2095
2096void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
2097                                AttributeList *declarator_postfix) {
2098  while (declspec_prefix) {
2099    HandleDeclAttribute(New, declspec_prefix);
2100    declspec_prefix = declspec_prefix->getNext();
2101  }
2102  while (declarator_postfix) {
2103    HandleDeclAttribute(New, declarator_postfix);
2104    declarator_postfix = declarator_postfix->getNext();
2105  }
2106}
2107
2108void Sema::HandleExtVectorTypeAttribute(TypedefDecl *tDecl,
2109                                        AttributeList *rawAttr) {
2110  QualType curType = tDecl->getUnderlyingType();
2111  // check the attribute arguments.
2112  if (rawAttr->getNumArgs() != 1) {
2113    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2114         std::string("1"));
2115    return;
2116  }
2117  Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2118  llvm::APSInt vecSize(32);
2119  if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
2120    Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
2121         "ext_vector_type", sizeExpr->getSourceRange());
2122    return;
2123  }
2124  // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2125  // in conjunction with complex types (pointers, arrays, functions, etc.).
2126  Type *canonType = curType.getCanonicalType().getTypePtr();
2127  if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
2128    Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
2129         curType.getCanonicalType().getAsString());
2130    return;
2131  }
2132  // unlike gcc's vector_size attribute, the size is specified as the
2133  // number of elements, not the number of bytes.
2134  unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
2135
2136  if (vectorSize == 0) {
2137    Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
2138         sizeExpr->getSourceRange());
2139    return;
2140  }
2141  // Instantiate/Install the vector type, the number of elements is > 0.
2142  tDecl->setUnderlyingType(Context.getExtVectorType(curType, vectorSize));
2143  // Remember this typedef decl, we will need it later for diagnostics.
2144  ExtVectorDecls.push_back(tDecl);
2145}
2146
2147QualType Sema::HandleVectorTypeAttribute(QualType curType,
2148                                         AttributeList *rawAttr) {
2149  // check the attribute arugments.
2150  if (rawAttr->getNumArgs() != 1) {
2151    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2152         std::string("1"));
2153    return QualType();
2154  }
2155  Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2156  llvm::APSInt vecSize(32);
2157  if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
2158    Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
2159         "vector_size", sizeExpr->getSourceRange());
2160    return QualType();
2161  }
2162  // navigate to the base type - we need to provide for vector pointers,
2163  // vector arrays, and functions returning vectors.
2164  Type *canonType = curType.getCanonicalType().getTypePtr();
2165
2166  if (canonType->isPointerType() || canonType->isArrayType() ||
2167      canonType->isFunctionType()) {
2168    assert(0 && "HandleVector(): Complex type construction unimplemented");
2169    /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2170        do {
2171          if (PointerType *PT = dyn_cast<PointerType>(canonType))
2172            canonType = PT->getPointeeType().getTypePtr();
2173          else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2174            canonType = AT->getElementType().getTypePtr();
2175          else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2176            canonType = FT->getResultType().getTypePtr();
2177        } while (canonType->isPointerType() || canonType->isArrayType() ||
2178                 canonType->isFunctionType());
2179    */
2180  }
2181  // the base type must be integer or float.
2182  if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
2183    Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
2184         curType.getCanonicalType().getAsString());
2185    return QualType();
2186  }
2187  unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(curType));
2188  // vecSize is specified in bytes - convert to bits.
2189  unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
2190
2191  // the vector size needs to be an integral multiple of the type size.
2192  if (vectorSize % typeSize) {
2193    Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
2194         sizeExpr->getSourceRange());
2195    return QualType();
2196  }
2197  if (vectorSize == 0) {
2198    Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
2199         sizeExpr->getSourceRange());
2200    return QualType();
2201  }
2202  // Instantiate the vector type, the number of elements is > 0, and not
2203  // required to be a power of 2, unlike GCC.
2204  return Context.getVectorType(curType, vectorSize/typeSize);
2205}
2206
2207void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) {
2208  // check the attribute arguments.
2209  if (rawAttr->getNumArgs() > 0) {
2210    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2211         std::string("0"));
2212    return;
2213  }
2214
2215  if (TagDecl *TD = dyn_cast<TagDecl>(d))
2216    TD->addAttr(new PackedAttr);
2217  else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
2218    // If the alignment is less than or equal to 8 bits, the packed attribute
2219    // has no effect.
2220    if (!FD->getType()->isIncompleteType() &&
2221        Context.getTypeAlign(FD->getType()) <= 8)
2222      Diag(rawAttr->getLoc(),
2223           diag::warn_attribute_ignored_for_field_of_type,
2224           rawAttr->getName()->getName(), FD->getType().getAsString());
2225    else
2226      FD->addAttr(new PackedAttr);
2227  } else
2228    Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
2229         rawAttr->getName()->getName());
2230}
2231
2232void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) {
2233  // check the attribute arguments.
2234  if (rawAttr->getNumArgs() != 0) {
2235    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2236         std::string("0"));
2237    return;
2238  }
2239
2240  FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2241
2242  if (!Fn) {
2243    Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2244         "noreturn", "function");
2245    return;
2246  }
2247
2248  d->addAttr(new NoReturnAttr());
2249}
2250
2251void Sema::HandleDeprecatedAttribute(Decl *d, AttributeList *rawAttr) {
2252  // check the attribute arguments.
2253  if (rawAttr->getNumArgs() != 0) {
2254    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2255         std::string("0"));
2256    return;
2257  }
2258
2259  d->addAttr(new DeprecatedAttr());
2260}
2261
2262void Sema::HandleVisibilityAttribute(Decl *d, AttributeList *rawAttr) {
2263  // check the attribute arguments.
2264  if (rawAttr->getNumArgs() != 1) {
2265    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2266         std::string("1"));
2267    return;
2268  }
2269
2270  Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0));
2271  Arg = Arg->IgnoreParenCasts();
2272  StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2273
2274  if (Str == 0 || Str->isWide()) {
2275    Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2276         "visibility", std::string("1"));
2277    return;
2278  }
2279
2280  const char *TypeStr = Str->getStrData();
2281  unsigned TypeLen = Str->getByteLength();
2282  llvm::GlobalValue::VisibilityTypes type;
2283
2284  if (TypeLen == 7 && !memcmp(TypeStr, "default", 7))
2285    type = llvm::GlobalValue::DefaultVisibility;
2286  else if (TypeLen == 6 && !memcmp(TypeStr, "hidden", 6))
2287    type = llvm::GlobalValue::HiddenVisibility;
2288  else if (TypeLen == 8 && !memcmp(TypeStr, "internal", 8))
2289    type = llvm::GlobalValue::HiddenVisibility; // FIXME
2290  else if (TypeLen == 9 && !memcmp(TypeStr, "protected", 9))
2291    type = llvm::GlobalValue::ProtectedVisibility;
2292  else {
2293    Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2294           "visibility", TypeStr);
2295    return;
2296  }
2297
2298  d->addAttr(new VisibilityAttr(type));
2299}
2300
2301void Sema::HandleWeakAttribute(Decl *d, AttributeList *rawAttr) {
2302  // check the attribute arguments.
2303  if (rawAttr->getNumArgs() != 0) {
2304    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2305         std::string("0"));
2306    return;
2307  }
2308
2309  d->addAttr(new WeakAttr());
2310}
2311
2312void Sema::HandleDLLImportAttribute(Decl *d, AttributeList *rawAttr) {
2313  // check the attribute arguments.
2314  if (rawAttr->getNumArgs() != 0) {
2315    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2316         std::string("0"));
2317    return;
2318  }
2319
2320  d->addAttr(new DLLImportAttr());
2321}
2322
2323void Sema::HandleDLLExportAttribute(Decl *d, AttributeList *rawAttr) {
2324  // check the attribute arguments.
2325  if (rawAttr->getNumArgs() != 0) {
2326    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2327         std::string("0"));
2328    return;
2329  }
2330
2331  d->addAttr(new DLLExportAttr());
2332}
2333
2334void Sema::HandleStdCallAttribute(Decl *d, AttributeList *rawAttr) {
2335  // check the attribute arguments.
2336  if (rawAttr->getNumArgs() != 0) {
2337    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2338         std::string("0"));
2339    return;
2340  }
2341
2342  d->addAttr(new StdCallAttr());
2343}
2344
2345void Sema::HandleFastCallAttribute(Decl *d, AttributeList *rawAttr) {
2346  // check the attribute arguments.
2347  if (rawAttr->getNumArgs() != 0) {
2348    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2349         std::string("0"));
2350    return;
2351  }
2352
2353  d->addAttr(new FastCallAttr());
2354}
2355
2356void Sema::HandleNothrowAttribute(Decl *d, AttributeList *rawAttr) {
2357  // check the attribute arguments.
2358  if (rawAttr->getNumArgs() != 0) {
2359    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2360         std::string("0"));
2361    return;
2362  }
2363
2364  d->addAttr(new NoThrowAttr());
2365}
2366
2367static const FunctionTypeProto *getFunctionProto(Decl *d) {
2368  QualType Ty;
2369
2370  if (ValueDecl *decl = dyn_cast<ValueDecl>(d))
2371    Ty = decl->getType();
2372  else if (FieldDecl *decl = dyn_cast<FieldDecl>(d))
2373    Ty = decl->getType();
2374  else if (TypedefDecl* decl = dyn_cast<TypedefDecl>(d))
2375    Ty = decl->getUnderlyingType();
2376  else
2377    return 0;
2378
2379  if (Ty->isFunctionPointerType()) {
2380    const PointerType *PtrTy = Ty->getAsPointerType();
2381    Ty = PtrTy->getPointeeType();
2382  }
2383
2384  if (const FunctionType *FnTy = Ty->getAsFunctionType())
2385    return dyn_cast<FunctionTypeProto>(FnTy->getAsFunctionType());
2386
2387  return 0;
2388}
2389
2390static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
2391  if (!T->isPointerType())
2392    return false;
2393
2394  T = T->getAsPointerType()->getPointeeType().getCanonicalType();
2395  ObjCInterfaceType* ClsT = dyn_cast<ObjCInterfaceType>(T.getTypePtr());
2396
2397  if (!ClsT)
2398    return false;
2399
2400  IdentifierInfo* ClsName = ClsT->getDecl()->getIdentifier();
2401
2402  // FIXME: Should we walk the chain of classes?
2403  return ClsName == &Ctx.Idents.get("NSString") ||
2404         ClsName == &Ctx.Idents.get("NSMutableString");
2405}
2406
2407/// Handle __attribute__((format(type,idx,firstarg))) attributes
2408/// based on http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2409void Sema::HandleFormatAttribute(Decl *d, AttributeList *rawAttr) {
2410
2411  if (!rawAttr->getParameterName()) {
2412    Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2413           "format", std::string("1"));
2414    return;
2415  }
2416
2417  if (rawAttr->getNumArgs() != 2) {
2418    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2419         std::string("3"));
2420    return;
2421  }
2422
2423  // GCC ignores the format attribute on K&R style function
2424  // prototypes, so we ignore it as well
2425  const FunctionTypeProto *proto = getFunctionProto(d);
2426
2427  if (!proto) {
2428    Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2429           "format", "function");
2430    return;
2431  }
2432
2433  // FIXME: in C++ the implicit 'this' function parameter also counts.
2434  // this is needed in order to be compatible with GCC
2435  // the index must start in 1 and the limit is numargs+1
2436  unsigned NumArgs  = proto->getNumArgs();
2437  unsigned FirstIdx = 1;
2438
2439  const char *Format = rawAttr->getParameterName()->getName();
2440  unsigned FormatLen = rawAttr->getParameterName()->getLength();
2441
2442  // Normalize the argument, __foo__ becomes foo.
2443  if (FormatLen > 4 && Format[0] == '_' && Format[1] == '_' &&
2444      Format[FormatLen - 2] == '_' && Format[FormatLen - 1] == '_') {
2445    Format += 2;
2446    FormatLen -= 4;
2447  }
2448
2449  bool Supported = false;
2450  bool is_NSString = false;
2451  bool is_strftime = false;
2452
2453  switch (FormatLen) {
2454    default: break;
2455    case 5:
2456      Supported = !memcmp(Format, "scanf", 5);
2457      break;
2458    case 6:
2459      Supported = !memcmp(Format, "printf", 6);
2460      break;
2461    case 7:
2462      Supported = !memcmp(Format, "strfmon", 7);
2463      break;
2464    case 8:
2465      Supported = (is_strftime = !memcmp(Format, "strftime", 8)) ||
2466                  (is_NSString = !memcmp(Format, "NSString", 8));
2467      break;
2468  }
2469
2470  if (!Supported) {
2471    Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2472           "format", rawAttr->getParameterName()->getName());
2473    return;
2474  }
2475
2476  // checks for the 2nd argument
2477  Expr *IdxExpr = static_cast<Expr *>(rawAttr->getArg(0));
2478  llvm::APSInt Idx(Context.getTypeSize(IdxExpr->getType()));
2479  if (!IdxExpr->isIntegerConstantExpr(Idx, Context)) {
2480    Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2481           "format", std::string("2"), IdxExpr->getSourceRange());
2482    return;
2483  }
2484
2485  if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
2486    Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2487           "format", std::string("2"), IdxExpr->getSourceRange());
2488    return;
2489  }
2490
2491  // FIXME: Do we need to bounds check?
2492  unsigned ArgIdx = Idx.getZExtValue() - 1;
2493
2494  // make sure the format string is really a string
2495  QualType Ty = proto->getArgType(ArgIdx);
2496
2497  if (is_NSString) {
2498    // FIXME: do we need to check if the type is NSString*?  What are
2499    //  the semantics?
2500    if (!isNSStringType(Ty, Context)) {
2501      // FIXME: Should highlight the actual expression that has the
2502      // wrong type.
2503      Diag(rawAttr->getLoc(), diag::err_format_attribute_not_NSString,
2504           IdxExpr->getSourceRange());
2505      return;
2506    }
2507  }
2508  else if (!Ty->isPointerType() ||
2509      !Ty->getAsPointerType()->getPointeeType()->isCharType()) {
2510    // FIXME: Should highlight the actual expression that has the
2511    // wrong type.
2512    Diag(rawAttr->getLoc(), diag::err_format_attribute_not_string,
2513         IdxExpr->getSourceRange());
2514    return;
2515  }
2516
2517  // check the 3rd argument
2518  Expr *FirstArgExpr = static_cast<Expr *>(rawAttr->getArg(1));
2519  llvm::APSInt FirstArg(Context.getTypeSize(FirstArgExpr->getType()));
2520  if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, Context)) {
2521    Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2522           "format", std::string("3"), FirstArgExpr->getSourceRange());
2523    return;
2524  }
2525
2526  // check if the function is variadic if the 3rd argument non-zero
2527  if (FirstArg != 0) {
2528    if (proto->isVariadic()) {
2529      ++NumArgs; // +1 for ...
2530    } else {
2531      Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
2532      return;
2533    }
2534  }
2535
2536  // strftime requires FirstArg to be 0 because it doesn't read from any variable
2537  // the input is just the current time + the format string
2538  if (is_strftime) {
2539    if (FirstArg != 0) {
2540      Diag(rawAttr->getLoc(), diag::err_format_strftime_third_parameter,
2541             FirstArgExpr->getSourceRange());
2542      return;
2543    }
2544  // if 0 it disables parameter checking (to use with e.g. va_list)
2545  } else if (FirstArg != 0 && FirstArg != NumArgs) {
2546    Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2547           "format", std::string("3"), FirstArgExpr->getSourceRange());
2548    return;
2549  }
2550
2551  d->addAttr(new FormatAttr(std::string(Format, FormatLen),
2552                            Idx.getZExtValue(), FirstArg.getZExtValue()));
2553}
2554
2555void Sema::HandleTransparentUnionAttribute(Decl *d, AttributeList *rawAttr) {
2556  // check the attribute arguments.
2557  if (rawAttr->getNumArgs() != 0) {
2558    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2559         std::string("0"));
2560    return;
2561  }
2562
2563  TypeDecl *decl = dyn_cast<TypeDecl>(d);
2564
2565  if (!decl || !Context.getTypeDeclType(decl)->isUnionType()) {
2566    Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2567         "transparent_union", "union");
2568    return;
2569  }
2570
2571  //QualType QTy = Context.getTypeDeclType(decl);
2572  //const RecordType *Ty = QTy->getAsUnionType();
2573
2574// FIXME
2575// Ty->addAttr(new TransparentUnionAttr());
2576}
2577
2578void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) {
2579  // check the attribute arguments.
2580  if (rawAttr->getNumArgs() != 1) {
2581    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2582         std::string("1"));
2583    return;
2584  }
2585  Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
2586  StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
2587
2588  // Make sure that there is a string literal as the annotation's single
2589  // argument.
2590  if (!SE) {
2591    Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
2592    return;
2593  }
2594  d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
2595                                          SE->getByteLength())));
2596}
2597
2598void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
2599{
2600  // check the attribute arguments.
2601  if (rawAttr->getNumArgs() > 1) {
2602    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2603         std::string("1"));
2604    return;
2605  }
2606
2607  unsigned Align = 0;
2608
2609  if (rawAttr->getNumArgs() == 0) {
2610    // FIXME: This should be the target specific maximum alignment.
2611    // (For now we just use 128 bits which is the maximum on X86.
2612    Align = 128;
2613    return;
2614  } else {
2615    Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
2616    llvm::APSInt alignment(32);
2617    if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
2618      Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
2619           "aligned", alignmentExpr->getSourceRange());
2620      return;
2621    }
2622
2623    Align = alignment.getZExtValue() * 8;
2624  }
2625
2626  d->addAttr(new AlignedAttr(Align));
2627}
2628