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