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