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