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