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