SemaDecl.cpp revision 45920e82bd87454545642ee2612e656a4140889d
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/APValue.h"
16#include "clang/AST/ASTConsumer.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/Parse/DeclSpec.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Basic/TargetInfo.h"
23#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
25#include "clang/Lex/Preprocessor.h"
26#include "clang/Lex/HeaderSearch.h"
27#include "llvm/ADT/SmallSet.h"
28#include "llvm/ADT/STLExtras.h"
29
30using namespace clang;
31
32Sema::TypeTy *Sema::isTypeName(IdentifierInfo &II, Scope *S,
33                               const CXXScopeSpec *SS) {
34  DeclContext *DC = 0;
35  if (SS) {
36    if (SS->isInvalid())
37      return 0;
38    DC = static_cast<DeclContext*>(SS->getScopeRep());
39  }
40  Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC, false);
41
42  if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
43                 isa<ObjCInterfaceDecl>(IIDecl) ||
44                 isa<TagDecl>(IIDecl) ||
45		 isa<TemplateTypeParmDecl>(IIDecl)))
46    return IIDecl;
47  return 0;
48}
49
50DeclContext *Sema::getContainingDC(DeclContext *DC) {
51  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
52    // A C++ out-of-line method will return to the file declaration context.
53    if (MD->isOutOfLineDefinition())
54      return MD->getLexicalDeclContext();
55
56    // A C++ inline method is parsed *after* the topmost class it was declared in
57    // is fully parsed (it's "complete").
58    // The parsing of a C++ inline method happens at the declaration context of
59    // the topmost (non-nested) class it is lexically declared in.
60    assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
61    DC = MD->getParent();
62    while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
63      DC = RD;
64
65    // Return the declaration context of the topmost class the inline method is
66    // declared in.
67    return DC;
68  }
69
70  if (isa<ObjCMethodDecl>(DC))
71    return Context.getTranslationUnitDecl();
72
73  if (ScopedDecl *SD = dyn_cast<ScopedDecl>(DC))
74    return SD->getLexicalDeclContext();
75
76  return DC->getLexicalParent();
77}
78
79void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
80  assert(getContainingDC(DC) == CurContext &&
81      "The next DeclContext should be lexically contained in the current one.");
82  CurContext = DC;
83  S->setEntity(DC);
84}
85
86void Sema::PopDeclContext() {
87  assert(CurContext && "DeclContext imbalance!");
88
89  CurContext = getContainingDC(CurContext);
90}
91
92/// Add this decl to the scope shadowed decl chains.
93void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
94  S->AddDecl(D);
95
96  // C++ [basic.scope]p4:
97  //   -- exactly one declaration shall declare a class name or
98  //   enumeration name that is not a typedef name and the other
99  //   declarations shall all refer to the same object or
100  //   enumerator, or all refer to functions and function templates;
101  //   in this case the class name or enumeration name is hidden.
102  if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
103    // We are pushing the name of a tag (enum or class).
104    if (CurContext == TD->getDeclContext()) {
105      // We're pushing the tag into the current context, which might
106      // require some reshuffling in the identifier resolver.
107      IdentifierResolver::iterator
108        I = IdResolver.begin(TD->getIdentifier(), CurContext,
109                            false/*LookInParentCtx*/);
110      if (I != IdResolver.end()) {
111       // There is already a declaration with the same name in the same
112       // scope. It must be found before we find the new declaration,
113       // so swap the order on the shadowed declaration chain.
114       IdResolver.AddShadowedDecl(TD, *I);
115
116       // Add this declaration to the current context.
117       CurContext->addDecl(Context, TD);
118
119       return;
120      }
121    }
122  } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
123    // We are pushing the name of a function, which might be an
124    // overloaded name.
125    FunctionDecl *FD = cast<FunctionDecl>(D);
126    Decl *Prev = LookupDecl(FD->getDeclName(), Decl::IDNS_Ordinary, S,
127                           FD->getDeclContext(), false, false);
128    if (Prev && (isa<OverloadedFunctionDecl>(Prev) || isa<FunctionDecl>(Prev))) {
129      // There is already a declaration with the same name in
130      // the same scope. It must be a function or an overloaded
131      // function.
132      OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(Prev);
133      if (!Ovl) {
134        // We haven't yet overloaded this function. Take the existing
135        // FunctionDecl and put it into an OverloadedFunctionDecl.
136        Ovl = OverloadedFunctionDecl::Create(Context,
137                                             FD->getDeclContext(),
138                                             FD->getDeclName());
139        Ovl->addOverload(cast<FunctionDecl>(Prev));
140
141        // If there is a name binding for the existing FunctionDecl,
142        // remove it.
143        for (IdentifierResolver::iterator I
144               = IdResolver.begin(FD->getDeclName(), FD->getDeclContext(),
145                                  false/*LookInParentCtx*/),
146               E = IdResolver.end(); I != E; ++I) {
147          if (*I == Prev) {
148            IdResolver.RemoveDecl(*I);
149            S->RemoveDecl(*I);
150            break;
151          }
152        }
153
154        // Add the name binding for the OverloadedFunctionDecl.
155        IdResolver.AddDecl(Ovl);
156
157        // Update the context with the newly-created overloaded
158        // function set.
159        FD->getDeclContext()->insert(Context, Ovl);
160
161       S->AddDecl(Ovl);
162      }
163
164      // We added this function declaration to the scope earlier, but
165      // we don't want it there because it is part of the overloaded
166      // function declaration.
167      S->RemoveDecl(FD);
168
169      // We have an OverloadedFunctionDecl. Add the new FunctionDecl
170      // to its list of overloads.
171      Ovl->addOverload(FD);
172
173      // Add this new function declaration to the declaration context.
174      CurContext->addDecl(Context, FD, false);
175
176      return;
177    }
178  }
179
180  // Add scoped declarations into their context, so that they can be
181  // found later. Declarations without a context won't be inserted
182  // into any context.
183  if (ScopedDecl *SD = dyn_cast<ScopedDecl>(D))
184    CurContext->addDecl(Context, SD);
185
186  IdResolver.AddDecl(D);
187}
188
189void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
190  if (S->decl_empty()) return;
191  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
192	 "Scope shouldn't contain decls!");
193
194  for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
195       I != E; ++I) {
196    Decl *TmpD = static_cast<Decl*>(*I);
197    assert(TmpD && "This decl didn't get pushed??");
198
199    assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
200    NamedDecl *D = cast<NamedDecl>(TmpD);
201
202    if (!D->getDeclName()) continue;
203
204    // Remove this name from our lexical scope.
205    IdResolver.RemoveDecl(D);
206  }
207}
208
209/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
210/// return 0 if one not found.
211ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
212  // The third "scope" argument is 0 since we aren't enabling lazy built-in
213  // creation from this context.
214  Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
215
216  return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
217}
218
219/// LookupDecl - Look up the inner-most declaration in the specified
220/// namespace.
221Decl *Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
222                       const DeclContext *LookupCtx,
223                       bool enableLazyBuiltinCreation,
224                       bool LookInParent) {
225  if (!Name) return 0;
226  unsigned NS = NSI;
227  if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
228    NS |= Decl::IDNS_Tag;
229
230  if (LookupCtx == 0 &&
231      (!getLangOptions().CPlusPlus || (NS == Decl::IDNS_Label))) {
232    // Unqualified name lookup in C/Objective-C and name lookup for
233    // labels in C++ is purely lexical, so search in the
234    // declarations attached to the name.
235    assert(!LookupCtx && "Can't perform qualified name lookup here");
236    IdentifierResolver::iterator I
237      = IdResolver.begin(Name, CurContext, LookInParent);
238
239    // Scan up the scope chain looking for a decl that matches this
240    // identifier that is in the appropriate namespace.  This search
241    // should not take long, as shadowing of names is uncommon, and
242    // deep shadowing is extremely uncommon.
243    for (; I != IdResolver.end(); ++I)
244      if ((*I)->getIdentifierNamespace() & NS)
245         return *I;
246  } else if (LookupCtx) {
247    assert(getLangOptions().CPlusPlus && "No qualified name lookup in C");
248
249    // Perform qualified name lookup into the LookupCtx.
250    // FIXME: Will need to look into base classes and such.
251    DeclContext::lookup_const_iterator I, E;
252    for (llvm::tie(I, E) = LookupCtx->lookup(Context, Name); I != E; ++I)
253      if ((*I)->getIdentifierNamespace() & NS)
254       return *I;
255  } else {
256    // Name lookup for ordinary names and tag names in C++ requires
257    // looking into scopes that aren't strictly lexical, and
258    // therefore we walk through the context as well as walking
259    // through the scopes.
260    IdentifierResolver::iterator
261      I = IdResolver.begin(Name, CurContext, true/*LookInParentCtx*/),
262      IEnd = IdResolver.end();
263    for (; S; S = S->getParent()) {
264      // Check whether the IdResolver has anything in this scope.
265      // FIXME: The isDeclScope check could be expensive. Can we do better?
266      for (; I != IEnd && S->isDeclScope(*I); ++I)
267        if ((*I)->getIdentifierNamespace() & NS)
268          return *I;
269
270      // If there is an entity associated with this scope, it's a
271      // DeclContext. We might need to perform qualified lookup into
272      // it.
273      DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
274      while (Ctx && Ctx->isFunctionOrMethod())
275        Ctx = Ctx->getParent();
276      while (Ctx && (Ctx->isNamespace() || Ctx->isCXXRecord())) {
277        // Look for declarations of this name in this scope.
278        DeclContext::lookup_const_iterator I, E;
279        for (llvm::tie(I, E) = Ctx->lookup(Context, Name); I != E; ++I) {
280          // FIXME: Cache this result in the IdResolver
281          if ((*I)->getIdentifierNamespace() & NS)
282            return  *I;
283        }
284
285        Ctx = Ctx->getParent();
286      }
287
288      if (!LookInParent)
289        return 0;
290    }
291  }
292
293  // If we didn't find a use of this identifier, and if the identifier
294  // corresponds to a compiler builtin, create the decl object for the builtin
295  // now, injecting it into translation unit scope, and return it.
296  if (NS & Decl::IDNS_Ordinary) {
297    IdentifierInfo *II = Name.getAsIdentifierInfo();
298    if (enableLazyBuiltinCreation && II &&
299        (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
300      // If this is a builtin on this (or all) targets, create the decl.
301      if (unsigned BuiltinID = II->getBuiltinID())
302        return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
303    }
304    if (getLangOptions().ObjC1 && II) {
305      // @interface and @compatibility_alias introduce typedef-like names.
306      // Unlike typedef's, they can only be introduced at file-scope (and are
307      // therefore not scoped decls). They can, however, be shadowed by
308      // other names in IDNS_Ordinary.
309      ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
310      if (IDI != ObjCInterfaceDecls.end())
311        return IDI->second;
312      ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
313      if (I != ObjCAliasDecls.end())
314        return I->second->getClassInterface();
315    }
316  }
317  return 0;
318}
319
320void Sema::InitBuiltinVaListType() {
321  if (!Context.getBuiltinVaListType().isNull())
322    return;
323
324  IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
325  Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
326  TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
327  Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
328}
329
330/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
331/// lazily create a decl for it.
332ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
333                                      Scope *S) {
334  Builtin::ID BID = (Builtin::ID)bid;
335
336  if (Context.BuiltinInfo.hasVAListUse(BID))
337    InitBuiltinVaListType();
338
339  QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
340  FunctionDecl *New = FunctionDecl::Create(Context,
341                                           Context.getTranslationUnitDecl(),
342                                           SourceLocation(), II, R,
343                                           FunctionDecl::Extern, false, 0);
344
345  // Create Decl objects for each parameter, adding them to the
346  // FunctionDecl.
347  if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
348    llvm::SmallVector<ParmVarDecl*, 16> Params;
349    for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
350      Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
351                                           FT->getArgType(i), VarDecl::None, 0,
352                                           0));
353    New->setParams(&Params[0], Params.size());
354  }
355
356
357
358  // TUScope is the translation-unit scope to insert this function into.
359  PushOnScopeChains(New, TUScope);
360  return New;
361}
362
363/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
364/// everything from the standard library is defined.
365NamespaceDecl *Sema::GetStdNamespace() {
366  if (!StdNamespace) {
367    IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
368    DeclContext *Global = Context.getTranslationUnitDecl();
369    Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Tag | Decl::IDNS_Ordinary,
370                           0, Global, /*enableLazyBuiltinCreation=*/false);
371    StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
372  }
373  return StdNamespace;
374}
375
376/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
377/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
378/// situation, merging decls or emitting diagnostics as appropriate.
379///
380TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
381  // Allow multiple definitions for ObjC built-in typedefs.
382  // FIXME: Verify the underlying types are equivalent!
383  if (getLangOptions().ObjC1) {
384    const IdentifierInfo *TypeID = New->getIdentifier();
385    switch (TypeID->getLength()) {
386    default: break;
387    case 2:
388      if (!TypeID->isStr("id"))
389        break;
390      Context.setObjCIdType(New);
391      return New;
392    case 5:
393      if (!TypeID->isStr("Class"))
394        break;
395      Context.setObjCClassType(New);
396      return New;
397    case 3:
398      if (!TypeID->isStr("SEL"))
399        break;
400      Context.setObjCSelType(New);
401      return New;
402    case 8:
403      if (!TypeID->isStr("Protocol"))
404        break;
405      Context.setObjCProtoType(New->getUnderlyingType());
406      return New;
407    }
408    // Fall through - the typedef name was not a builtin type.
409  }
410  // Verify the old decl was also a typedef.
411  TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
412  if (!Old) {
413    Diag(New->getLocation(), diag::err_redefinition_different_kind)
414      << New->getDeclName();
415    Diag(OldD->getLocation(), diag::note_previous_definition);
416    return New;
417  }
418
419  // If the typedef types are not identical, reject them in all languages and
420  // with any extensions enabled.
421  if (Old->getUnderlyingType() != New->getUnderlyingType() &&
422      Context.getCanonicalType(Old->getUnderlyingType()) !=
423      Context.getCanonicalType(New->getUnderlyingType())) {
424    Diag(New->getLocation(), diag::err_redefinition_different_typedef)
425      << New->getUnderlyingType() << Old->getUnderlyingType();
426    Diag(Old->getLocation(), diag::note_previous_definition);
427    return Old;
428  }
429
430  if (getLangOptions().Microsoft) return New;
431
432  // C++ [dcl.typedef]p2:
433  //   In a given non-class scope, a typedef specifier can be used to
434  //   redefine the name of any type declared in that scope to refer
435  //   to the type to which it already refers.
436  if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
437    return New;
438
439  // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
440  // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
441  // *either* declaration is in a system header. The code below implements
442  // this adhoc compatibility rule. FIXME: The following code will not
443  // work properly when compiling ".i" files (containing preprocessed output).
444  if (PP.getDiagnostics().getSuppressSystemWarnings()) {
445    SourceManager &SrcMgr = Context.getSourceManager();
446    if (SrcMgr.isInSystemHeader(Old->getLocation()))
447      return New;
448    if (SrcMgr.isInSystemHeader(New->getLocation()))
449      return New;
450  }
451
452  Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
453  Diag(Old->getLocation(), diag::note_previous_definition);
454  return New;
455}
456
457/// DeclhasAttr - returns true if decl Declaration already has the target
458/// attribute.
459static bool DeclHasAttr(const Decl *decl, const Attr *target) {
460  for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
461    if (attr->getKind() == target->getKind())
462      return true;
463
464  return false;
465}
466
467/// MergeAttributes - append attributes from the Old decl to the New one.
468static void MergeAttributes(Decl *New, Decl *Old) {
469  Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
470
471  while (attr) {
472     tmp = attr;
473     attr = attr->getNext();
474
475    if (!DeclHasAttr(New, tmp)) {
476       New->addAttr(tmp);
477    } else {
478       tmp->setNext(0);
479       delete(tmp);
480    }
481  }
482
483  Old->invalidateAttrs();
484}
485
486/// MergeFunctionDecl - We just parsed a function 'New' from
487/// declarator D which has the same name and scope as a previous
488/// declaration 'Old'.  Figure out how to resolve this situation,
489/// merging decls or emitting diagnostics as appropriate.
490/// Redeclaration will be set true if this New is a redeclaration OldD.
491///
492/// In C++, New and Old must be declarations that are not
493/// overloaded. Use IsOverload to determine whether New and Old are
494/// overloaded, and to select the Old declaration that New should be
495/// merged with.
496FunctionDecl *
497Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
498  assert(!isa<OverloadedFunctionDecl>(OldD) &&
499         "Cannot merge with an overloaded function declaration");
500
501  Redeclaration = false;
502  // Verify the old decl was also a function.
503  FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
504  if (!Old) {
505    Diag(New->getLocation(), diag::err_redefinition_different_kind)
506      << New->getDeclName();
507    Diag(OldD->getLocation(), diag::note_previous_definition);
508    return New;
509  }
510
511  // Determine whether the previous declaration was a definition,
512  // implicit declaration, or a declaration.
513  diag::kind PrevDiag;
514  if (Old->isThisDeclarationADefinition())
515    PrevDiag = diag::note_previous_definition;
516  else if (Old->isImplicit())
517    PrevDiag = diag::note_previous_implicit_declaration;
518  else
519    PrevDiag = diag::note_previous_declaration;
520
521  QualType OldQType = Context.getCanonicalType(Old->getType());
522  QualType NewQType = Context.getCanonicalType(New->getType());
523
524  if (getLangOptions().CPlusPlus) {
525    // (C++98 13.1p2):
526    //   Certain function declarations cannot be overloaded:
527    //     -- Function declarations that differ only in the return type
528    //        cannot be overloaded.
529    QualType OldReturnType
530      = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
531    QualType NewReturnType
532      = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
533    if (OldReturnType != NewReturnType) {
534      Diag(New->getLocation(), diag::err_ovl_diff_return_type);
535      Diag(Old->getLocation(), PrevDiag);
536      return New;
537    }
538
539    const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
540    const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
541    if (OldMethod && NewMethod) {
542      //    -- Member function declarations with the same name and the
543      //       same parameter types cannot be overloaded if any of them
544      //       is a static member function declaration.
545      if (OldMethod->isStatic() || NewMethod->isStatic()) {
546        Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
547        Diag(Old->getLocation(), PrevDiag);
548        return New;
549      }
550
551      // C++ [class.mem]p1:
552      //   [...] A member shall not be declared twice in the
553      //   member-specification, except that a nested class or member
554      //   class template can be declared and then later defined.
555      if (OldMethod->getLexicalDeclContext() ==
556            NewMethod->getLexicalDeclContext()) {
557        unsigned NewDiag;
558        if (isa<CXXConstructorDecl>(OldMethod))
559          NewDiag = diag::err_constructor_redeclared;
560        else if (isa<CXXDestructorDecl>(NewMethod))
561          NewDiag = diag::err_destructor_redeclared;
562        else if (isa<CXXConversionDecl>(NewMethod))
563          NewDiag = diag::err_conv_function_redeclared;
564        else
565          NewDiag = diag::err_member_redeclared;
566
567        Diag(New->getLocation(), NewDiag);
568        Diag(Old->getLocation(), PrevDiag);
569      }
570    }
571
572    // (C++98 8.3.5p3):
573    //   All declarations for a function shall agree exactly in both the
574    //   return type and the parameter-type-list.
575    if (OldQType == NewQType) {
576      // We have a redeclaration.
577      MergeAttributes(New, Old);
578      Redeclaration = true;
579      return MergeCXXFunctionDecl(New, Old);
580    }
581
582    // Fall through for conflicting redeclarations and redefinitions.
583  }
584
585  // C: Function types need to be compatible, not identical. This handles
586  // duplicate function decls like "void f(int); void f(enum X);" properly.
587  if (!getLangOptions().CPlusPlus &&
588      Context.typesAreCompatible(OldQType, NewQType)) {
589    MergeAttributes(New, Old);
590    Redeclaration = true;
591    return New;
592  }
593
594  // A function that has already been declared has been redeclared or defined
595  // with a different type- show appropriate diagnostic
596
597  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
598  // TODO: This is totally simplistic.  It should handle merging functions
599  // together etc, merging extern int X; int X; ...
600  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
601  Diag(Old->getLocation(), PrevDiag);
602  return New;
603}
604
605/// Predicate for C "tentative" external object definitions (C99 6.9.2).
606static bool isTentativeDefinition(VarDecl *VD) {
607  if (VD->isFileVarDecl())
608    return (!VD->getInit() &&
609            (VD->getStorageClass() == VarDecl::None ||
610             VD->getStorageClass() == VarDecl::Static));
611  return false;
612}
613
614/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
615/// when dealing with C "tentative" external object definitions (C99 6.9.2).
616void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
617  bool VDIsTentative = isTentativeDefinition(VD);
618  bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
619
620  for (IdentifierResolver::iterator
621       I = IdResolver.begin(VD->getIdentifier(),
622                            VD->getDeclContext(), false/*LookInParentCtx*/),
623       E = IdResolver.end(); I != E; ++I) {
624    if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
625      VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
626
627      // Handle the following case:
628      //   int a[10];
629      //   int a[];   - the code below makes sure we set the correct type.
630      //   int a[11]; - this is an error, size isn't 10.
631      if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
632          OldDecl->getType()->isConstantArrayType())
633        VD->setType(OldDecl->getType());
634
635      // Check for "tentative" definitions. We can't accomplish this in
636      // MergeVarDecl since the initializer hasn't been attached.
637      if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
638        continue;
639
640      // Handle __private_extern__ just like extern.
641      if (OldDecl->getStorageClass() != VarDecl::Extern &&
642          OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
643          VD->getStorageClass() != VarDecl::Extern &&
644          VD->getStorageClass() != VarDecl::PrivateExtern) {
645        Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
646        Diag(OldDecl->getLocation(), diag::note_previous_definition);
647      }
648    }
649  }
650}
651
652/// MergeVarDecl - We just parsed a variable 'New' which has the same name
653/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
654/// situation, merging decls or emitting diagnostics as appropriate.
655///
656/// Tentative definition rules (C99 6.9.2p2) are checked by
657/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
658/// definitions here, since the initializer hasn't been attached.
659///
660VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
661  // Verify the old decl was also a variable.
662  VarDecl *Old = dyn_cast<VarDecl>(OldD);
663  if (!Old) {
664    Diag(New->getLocation(), diag::err_redefinition_different_kind)
665      << New->getDeclName();
666    Diag(OldD->getLocation(), diag::note_previous_definition);
667    return New;
668  }
669
670  MergeAttributes(New, Old);
671
672  // Verify the types match.
673  QualType OldCType = Context.getCanonicalType(Old->getType());
674  QualType NewCType = Context.getCanonicalType(New->getType());
675  if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
676    Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
677    Diag(Old->getLocation(), diag::note_previous_definition);
678    return New;
679  }
680  // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
681  if (New->getStorageClass() == VarDecl::Static &&
682      (Old->getStorageClass() == VarDecl::None ||
683       Old->getStorageClass() == VarDecl::Extern)) {
684    Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
685    Diag(Old->getLocation(), diag::note_previous_definition);
686    return New;
687  }
688  // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
689  if (New->getStorageClass() != VarDecl::Static &&
690      Old->getStorageClass() == VarDecl::Static) {
691    Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
692    Diag(Old->getLocation(), diag::note_previous_definition);
693    return New;
694  }
695  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
696  if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
697    Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
698    Diag(Old->getLocation(), diag::note_previous_definition);
699  }
700  return New;
701}
702
703/// CheckParmsForFunctionDef - Check that the parameters of the given
704/// function are appropriate for the definition of a function. This
705/// takes care of any checks that cannot be performed on the
706/// declaration itself, e.g., that the types of each of the function
707/// parameters are complete.
708bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
709  bool HasInvalidParm = false;
710  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
711    ParmVarDecl *Param = FD->getParamDecl(p);
712
713    // C99 6.7.5.3p4: the parameters in a parameter type list in a
714    // function declarator that is part of a function definition of
715    // that function shall not have incomplete type.
716    if (Param->getType()->isIncompleteType() &&
717        !Param->isInvalidDecl()) {
718      Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type)
719        << Param->getType();
720      Param->setInvalidDecl();
721      HasInvalidParm = true;
722    }
723
724    // C99 6.9.1p5: If the declarator includes a parameter type list, the
725    // declaration of each parameter shall include an identifier.
726    if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
727      Diag(Param->getLocation(), diag::err_parameter_name_omitted);
728  }
729
730  return HasInvalidParm;
731}
732
733/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
734/// no declarator (e.g. "struct foo;") is parsed.
735Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
736  // TODO: emit error on 'int;' or 'const enum foo;'.
737  // TODO: emit error on 'typedef int;'
738  // if (!DS.isMissingDeclaratorOk()) Diag(...);
739
740  return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
741}
742
743bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
744  // Get the type before calling CheckSingleAssignmentConstraints(), since
745  // it can promote the expression.
746  QualType InitType = Init->getType();
747
748  if (getLangOptions().CPlusPlus)
749    return PerformCopyInitialization(Init, DeclType, "initializing");
750
751  AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
752  return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
753                                  InitType, Init, "initializing");
754}
755
756bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
757  const ArrayType *AT = Context.getAsArrayType(DeclT);
758
759  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
760    // C99 6.7.8p14. We have an array of character type with unknown size
761    // being initialized to a string literal.
762    llvm::APSInt ConstVal(32);
763    ConstVal = strLiteral->getByteLength() + 1;
764    // Return a new array type (C99 6.7.8p22).
765    DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
766                                         ArrayType::Normal, 0);
767  } else {
768    const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
769    // C99 6.7.8p14. We have an array of character type with known size.
770    // FIXME: Avoid truncation for 64-bit length strings.
771    if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
772      Diag(strLiteral->getSourceRange().getBegin(),
773           diag::warn_initializer_string_for_char_array_too_long)
774        << strLiteral->getSourceRange();
775  }
776  // Set type from "char *" to "constant array of char".
777  strLiteral->setType(DeclT);
778  // For now, we always return false (meaning success).
779  return false;
780}
781
782StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
783  const ArrayType *AT = Context.getAsArrayType(DeclType);
784  if (AT && AT->getElementType()->isCharType()) {
785    return dyn_cast<StringLiteral>(Init);
786  }
787  return 0;
788}
789
790bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
791                                 SourceLocation InitLoc,
792                                 DeclarationName InitEntity) {
793  if (DeclType->isDependentType() || Init->isTypeDependent())
794    return false;
795
796  // C++ [dcl.init.ref]p1:
797  //   A variable declared to be a T&, that is "reference to type T"
798  //   (8.3.2), shall be initialized by an object, or function, of
799  //   type T or by an object that can be converted into a T.
800  if (DeclType->isReferenceType())
801    return CheckReferenceInit(Init, DeclType);
802
803  // C99 6.7.8p3: The type of the entity to be initialized shall be an array
804  // of unknown size ("[]") or an object type that is not a variable array type.
805  if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
806    return Diag(InitLoc,  diag::err_variable_object_no_init)
807      << VAT->getSizeExpr()->getSourceRange();
808
809  InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
810  if (!InitList) {
811    // FIXME: Handle wide strings
812    if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
813      return CheckStringLiteralInit(strLiteral, DeclType);
814
815    // C++ [dcl.init]p14:
816    //   -- If the destination type is a (possibly cv-qualified) class
817    //      type:
818    if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
819      QualType DeclTypeC = Context.getCanonicalType(DeclType);
820      QualType InitTypeC = Context.getCanonicalType(Init->getType());
821
822      //   -- If the initialization is direct-initialization, or if it is
823      //      copy-initialization where the cv-unqualified version of the
824      //      source type is the same class as, or a derived class of, the
825      //      class of the destination, constructors are considered.
826      if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
827          IsDerivedFrom(InitTypeC, DeclTypeC)) {
828        CXXConstructorDecl *Constructor
829          = PerformInitializationByConstructor(DeclType, &Init, 1,
830                                               InitLoc, Init->getSourceRange(),
831                                               InitEntity, IK_Copy);
832        return Constructor == 0;
833      }
834
835      //   -- Otherwise (i.e., for the remaining copy-initialization
836      //      cases), user-defined conversion sequences that can
837      //      convert from the source type to the destination type or
838      //      (when a conversion function is used) to a derived class
839      //      thereof are enumerated as described in 13.3.1.4, and the
840      //      best one is chosen through overload resolution
841      //      (13.3). If the conversion cannot be done or is
842      //      ambiguous, the initialization is ill-formed. The
843      //      function selected is called with the initializer
844      //      expression as its argument; if the function is a
845      //      constructor, the call initializes a temporary of the
846      //      destination type.
847      // FIXME: We're pretending to do copy elision here; return to
848      // this when we have ASTs for such things.
849      if (!PerformImplicitConversion(Init, DeclType, "initializing"))
850        return false;
851
852      return Diag(InitLoc, diag::err_typecheck_convert_incompatible)
853        << DeclType << InitEntity << "initializing"
854        << Init->getSourceRange();
855    }
856
857    // C99 6.7.8p16.
858    if (DeclType->isArrayType())
859      return Diag(Init->getLocStart(), diag::err_array_init_list_required)
860        << Init->getSourceRange();
861
862    return CheckSingleInitializer(Init, DeclType);
863  } else if (getLangOptions().CPlusPlus) {
864    // C++ [dcl.init]p14:
865    //   [...] If the class is an aggregate (8.5.1), and the initializer
866    //   is a brace-enclosed list, see 8.5.1.
867    //
868    // Note: 8.5.1 is handled below; here, we diagnose the case where
869    // we have an initializer list and a destination type that is not
870    // an aggregate.
871    // FIXME: In C++0x, this is yet another form of initialization.
872    if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
873      const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
874      if (!ClassDecl->isAggregate())
875        return Diag(InitLoc, diag::err_init_non_aggr_init_list)
876           << DeclType << Init->getSourceRange();
877    }
878  }
879
880  InitListChecker CheckInitList(this, InitList, DeclType);
881  return CheckInitList.HadError();
882}
883
884/// GetNameForDeclarator - Determine the full declaration name for the
885/// given Declarator.
886DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
887  switch (D.getKind()) {
888  case Declarator::DK_Abstract:
889    assert(D.getIdentifier() == 0 && "abstract declarators have no name");
890    return DeclarationName();
891
892  case Declarator::DK_Normal:
893    assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
894    return DeclarationName(D.getIdentifier());
895
896  case Declarator::DK_Constructor: {
897    QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
898    Ty = Context.getCanonicalType(Ty);
899    return Context.DeclarationNames.getCXXConstructorName(Ty);
900  }
901
902  case Declarator::DK_Destructor: {
903    QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
904    Ty = Context.getCanonicalType(Ty);
905    return Context.DeclarationNames.getCXXDestructorName(Ty);
906  }
907
908  case Declarator::DK_Conversion: {
909    QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
910    Ty = Context.getCanonicalType(Ty);
911    return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
912  }
913
914  case Declarator::DK_Operator:
915    assert(D.getIdentifier() == 0 && "operator names have no identifier");
916    return Context.DeclarationNames.getCXXOperatorName(
917                                                D.getOverloadedOperator());
918  }
919
920  assert(false && "Unknown name kind");
921  return DeclarationName();
922}
923
924/// isNearlyMatchingMemberFunction - Determine whether the C++ member
925/// functions Declaration and Definition are "nearly" matching. This
926/// heuristic is used to improve diagnostics in the case where an
927/// out-of-line member function definition doesn't match any
928/// declaration within the class.
929static bool isNearlyMatchingMemberFunction(ASTContext &Context,
930                                           FunctionDecl *Declaration,
931                                           FunctionDecl *Definition) {
932  if (Declaration->param_size() != Definition->param_size())
933    return false;
934  for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
935    QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
936    QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
937
938    DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
939    DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
940    if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
941      return false;
942  }
943
944  return true;
945}
946
947Sema::DeclTy *
948Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
949                      bool IsFunctionDefinition) {
950  ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
951  DeclarationName Name = GetNameForDeclarator(D);
952
953  // All of these full declarators require an identifier.  If it doesn't have
954  // one, the ParsedFreeStandingDeclSpec action should be used.
955  if (!Name) {
956    if (!D.getInvalidType())  // Reject this if we think it is valid.
957      Diag(D.getDeclSpec().getSourceRange().getBegin(),
958           diag::err_declarator_need_ident)
959        << D.getDeclSpec().getSourceRange() << D.getSourceRange();
960    return 0;
961  }
962
963  // The scope passed in may not be a decl scope.  Zip up the scope tree until
964  // we find one that is.
965  while ((S->getFlags() & Scope::DeclScope) == 0 ||
966        (S->getFlags() & Scope::TemplateParamScope) != 0)
967    S = S->getParent();
968
969  DeclContext *DC;
970  Decl *PrevDecl;
971  ScopedDecl *New;
972  bool InvalidDecl = false;
973
974  // See if this is a redefinition of a variable in the same scope.
975  if (!D.getCXXScopeSpec().isSet()) {
976    DC = CurContext;
977    PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
978  } else { // Something like "int foo::x;"
979    DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
980    PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
981
982    // C++ 7.3.1.2p2:
983    // Members (including explicit specializations of templates) of a named
984    // namespace can also be defined outside that namespace by explicit
985    // qualification of the name being defined, provided that the entity being
986    // defined was already declared in the namespace and the definition appears
987    // after the point of declaration in a namespace that encloses the
988    // declarations namespace.
989    //
990    // Note that we only check the context at this point. We don't yet
991    // have enough information to make sure that PrevDecl is actually
992    // the declaration we want to match. For example, given:
993    //
994    //   class X {
995    //     void f();
996    //     void f(float);
997    //   };
998    //
999    //   void X::f(int) { } // ill-formed
1000    //
1001    // In this case, PrevDecl will point to the overload set
1002    // containing the two f's declared in X, but neither of them
1003    // matches.
1004    if (!CurContext->Encloses(DC)) {
1005      // The qualifying scope doesn't enclose the original declaration.
1006      // Emit diagnostic based on current scope.
1007      SourceLocation L = D.getIdentifierLoc();
1008      SourceRange R = D.getCXXScopeSpec().getRange();
1009      if (isa<FunctionDecl>(CurContext)) {
1010        Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
1011      } else {
1012        Diag(L, diag::err_invalid_declarator_scope)
1013          << Name << cast<NamedDecl>(DC)->getDeclName() << R;
1014      }
1015      InvalidDecl = true;
1016    }
1017  }
1018
1019  if (PrevDecl && PrevDecl->isTemplateParameter()) {
1020    // Maybe we will complain about the shadowed template parameter.
1021    InvalidDecl = InvalidDecl
1022      || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
1023    // Just pretend that we didn't see the previous declaration.
1024    PrevDecl = 0;
1025  }
1026
1027  // In C++, the previous declaration we find might be a tag type
1028  // (class or enum). In this case, the new declaration will hide the
1029  // tag type.
1030  if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
1031    PrevDecl = 0;
1032
1033  QualType R = GetTypeForDeclarator(D, S);
1034  assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1035
1036  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
1037    // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1038    if (D.getCXXScopeSpec().isSet()) {
1039      Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1040        << D.getCXXScopeSpec().getRange();
1041      InvalidDecl = true;
1042      // Pretend we didn't see the scope specifier.
1043      DC = 0;
1044    }
1045
1046    // Check that there are no default arguments (C++ only).
1047    if (getLangOptions().CPlusPlus)
1048      CheckExtraCXXDefaultArguments(D);
1049
1050    TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
1051    if (!NewTD) return 0;
1052
1053    // Handle attributes prior to checking for duplicates in MergeVarDecl
1054    ProcessDeclAttributes(NewTD, D);
1055    // Merge the decl with the existing one if appropriate. If the decl is
1056    // in an outer scope, it isn't the same thing.
1057    if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1058      NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1059      if (NewTD == 0) return 0;
1060    }
1061    New = NewTD;
1062    if (S->getFnParent() == 0) {
1063      // C99 6.7.7p2: If a typedef name specifies a variably modified type
1064      // then it shall have block scope.
1065      if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
1066        if (NewTD->getUnderlyingType()->isVariableArrayType())
1067          Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1068        else
1069          Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1070
1071        InvalidDecl = true;
1072      }
1073    }
1074  } else if (R.getTypePtr()->isFunctionType()) {
1075    FunctionDecl::StorageClass SC = FunctionDecl::None;
1076    switch (D.getDeclSpec().getStorageClassSpec()) {
1077      default: assert(0 && "Unknown storage class!");
1078      case DeclSpec::SCS_auto:
1079      case DeclSpec::SCS_register:
1080      case DeclSpec::SCS_mutable:
1081        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
1082        InvalidDecl = true;
1083        break;
1084      case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1085      case DeclSpec::SCS_extern:      SC = FunctionDecl::Extern; break;
1086      case DeclSpec::SCS_static:      SC = FunctionDecl::Static; break;
1087      case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
1088    }
1089
1090    bool isInline = D.getDeclSpec().isInlineSpecified();
1091    // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1092    bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1093
1094    FunctionDecl *NewFD;
1095    if (D.getKind() == Declarator::DK_Constructor) {
1096      // This is a C++ constructor declaration.
1097      assert(DC->isCXXRecord() &&
1098             "Constructors can only be declared in a member context");
1099
1100      bool isInvalidDecl = CheckConstructorDeclarator(D, R, SC);
1101
1102      // Create the new declaration
1103      NewFD = CXXConstructorDecl::Create(Context,
1104                                         cast<CXXRecordDecl>(DC),
1105                                         D.getIdentifierLoc(), Name, R,
1106                                         isExplicit, isInline,
1107                                         /*isImplicitlyDeclared=*/false);
1108
1109      if (isInvalidDecl)
1110        NewFD->setInvalidDecl();
1111    } else if (D.getKind() == Declarator::DK_Destructor) {
1112      // This is a C++ destructor declaration.
1113      if (DC->isCXXRecord()) {
1114        bool isInvalidDecl = CheckDestructorDeclarator(D, R, SC);
1115
1116        NewFD = CXXDestructorDecl::Create(Context,
1117                                          cast<CXXRecordDecl>(DC),
1118                                          D.getIdentifierLoc(), Name, R,
1119                                          isInline,
1120                                          /*isImplicitlyDeclared=*/false);
1121
1122        if (isInvalidDecl)
1123          NewFD->setInvalidDecl();
1124      } else {
1125        Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1126        // Create a FunctionDecl to satisfy the function definition parsing
1127        // code path.
1128        NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
1129                                     Name, R, SC, isInline, LastDeclarator,
1130                                     // FIXME: Move to DeclGroup...
1131                                   D.getDeclSpec().getSourceRange().getBegin());
1132        NewFD->setInvalidDecl();
1133      }
1134    } else if (D.getKind() == Declarator::DK_Conversion) {
1135      if (!DC->isCXXRecord()) {
1136        Diag(D.getIdentifierLoc(),
1137             diag::err_conv_function_not_member);
1138        return 0;
1139      } else {
1140        bool isInvalidDecl = CheckConversionDeclarator(D, R, SC);
1141
1142        NewFD = CXXConversionDecl::Create(Context,
1143                                          cast<CXXRecordDecl>(DC),
1144                                          D.getIdentifierLoc(), Name, R,
1145                                          isInline, isExplicit);
1146
1147        if (isInvalidDecl)
1148          NewFD->setInvalidDecl();
1149      }
1150    } else if (DC->isCXXRecord()) {
1151      // This is a C++ method declaration.
1152      NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
1153                                    D.getIdentifierLoc(), Name, R,
1154                                    (SC == FunctionDecl::Static), isInline,
1155                                    LastDeclarator);
1156    } else {
1157      NewFD = FunctionDecl::Create(Context, DC,
1158                                   D.getIdentifierLoc(),
1159                                   Name, R, SC, isInline, LastDeclarator,
1160                                   // FIXME: Move to DeclGroup...
1161                                   D.getDeclSpec().getSourceRange().getBegin());
1162    }
1163
1164    // Handle attributes.
1165    ProcessDeclAttributes(NewFD, D);
1166
1167    // Set the lexical context. If the declarator has a C++
1168    // scope specifier, the lexical context will be different
1169    // from the semantic context.
1170    NewFD->setLexicalDeclContext(CurContext);
1171
1172    // Handle GNU asm-label extension (encoded as an attribute).
1173    if (Expr *E = (Expr*) D.getAsmLabel()) {
1174      // The parser guarantees this is a string.
1175      StringLiteral *SE = cast<StringLiteral>(E);
1176      NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1177                                                  SE->getByteLength())));
1178    }
1179
1180    // Copy the parameter declarations from the declarator D to
1181    // the function declaration NewFD, if they are available.
1182    if (D.getNumTypeObjects() > 0) {
1183      DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1184
1185      // Create Decl objects for each parameter, adding them to the
1186      // FunctionDecl.
1187      llvm::SmallVector<ParmVarDecl*, 16> Params;
1188
1189      // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1190      // function that takes no arguments, not a function that takes a
1191      // single void argument.
1192      // We let through "const void" here because Sema::GetTypeForDeclarator
1193      // already checks for that case.
1194      if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1195          FTI.ArgInfo[0].Param &&
1196          ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1197        // empty arg list, don't push any params.
1198        ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1199
1200        // In C++, the empty parameter-type-list must be spelled "void"; a
1201        // typedef of void is not permitted.
1202        if (getLangOptions().CPlusPlus &&
1203            Param->getType().getUnqualifiedType() != Context.VoidTy) {
1204          Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1205        }
1206      } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
1207        for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1208          Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1209      }
1210
1211      NewFD->setParams(&Params[0], Params.size());
1212    } else if (R->getAsTypedefType()) {
1213      // When we're declaring a function with a typedef, as in the
1214      // following example, we'll need to synthesize (unnamed)
1215      // parameters for use in the declaration.
1216      //
1217      // @code
1218      // typedef void fn(int);
1219      // fn f;
1220      // @endcode
1221      const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1222      if (!FT) {
1223        // This is a typedef of a function with no prototype, so we
1224        // don't need to do anything.
1225      } else if ((FT->getNumArgs() == 0) ||
1226          (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1227           FT->getArgType(0)->isVoidType())) {
1228        // This is a zero-argument function. We don't need to do anything.
1229      } else {
1230        // Synthesize a parameter for each argument type.
1231        llvm::SmallVector<ParmVarDecl*, 16> Params;
1232        for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1233             ArgType != FT->arg_type_end(); ++ArgType) {
1234          Params.push_back(ParmVarDecl::Create(Context, DC,
1235                                               SourceLocation(), 0,
1236                                               *ArgType, VarDecl::None,
1237                                               0, 0));
1238        }
1239
1240        NewFD->setParams(&Params[0], Params.size());
1241      }
1242    }
1243
1244    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1245      InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
1246    else if (isa<CXXDestructorDecl>(NewFD))
1247      cast<CXXRecordDecl>(NewFD->getParent())->setUserDeclaredDestructor(true);
1248    else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
1249      ActOnConversionDeclarator(Conversion);
1250
1251    // Extra checking for C++ overloaded operators (C++ [over.oper]).
1252    if (NewFD->isOverloadedOperator() &&
1253        CheckOverloadedOperatorDeclaration(NewFD))
1254      NewFD->setInvalidDecl();
1255
1256    // Merge the decl with the existing one if appropriate. Since C functions
1257    // are in a flat namespace, make sure we consider decls in outer scopes.
1258    if (PrevDecl &&
1259        (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
1260      bool Redeclaration = false;
1261
1262      // If C++, determine whether NewFD is an overload of PrevDecl or
1263      // a declaration that requires merging. If it's an overload,
1264      // there's no more work to do here; we'll just add the new
1265      // function to the scope.
1266      OverloadedFunctionDecl::function_iterator MatchedDecl;
1267      if (!getLangOptions().CPlusPlus ||
1268          !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1269        Decl *OldDecl = PrevDecl;
1270
1271        // If PrevDecl was an overloaded function, extract the
1272        // FunctionDecl that matched.
1273        if (isa<OverloadedFunctionDecl>(PrevDecl))
1274          OldDecl = *MatchedDecl;
1275
1276        // NewFD and PrevDecl represent declarations that need to be
1277        // merged.
1278        NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1279
1280        if (NewFD == 0) return 0;
1281        if (Redeclaration) {
1282          NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1283
1284          if (OldDecl == PrevDecl) {
1285            // Remove the name binding for the previous
1286            // declaration.
1287           if (S->isDeclScope(PrevDecl)) {
1288             IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl));
1289             S->RemoveDecl(PrevDecl);
1290           }
1291
1292           // Introduce the new binding for this declaration.
1293           IdResolver.AddDecl(NewFD);
1294           if (getLangOptions().CPlusPlus && NewFD->getParent())
1295             NewFD->getParent()->insert(Context, NewFD);
1296
1297           // Add the redeclaration to the current scope, since we'll
1298           // be skipping PushOnScopeChains.
1299           S->AddDecl(NewFD);
1300          } else {
1301            // We need to update the OverloadedFunctionDecl with the
1302            // latest declaration of this function, so that name
1303            // lookup will always refer to the latest declaration of
1304            // this function.
1305            *MatchedDecl = NewFD;
1306         }
1307
1308          if (getLangOptions().CPlusPlus) {
1309            // Add this declaration to the current context.
1310            CurContext->addDecl(Context, NewFD, false);
1311
1312            // Check default arguments now that we have merged decls.
1313            CheckCXXDefaultArguments(NewFD);
1314
1315            // An out-of-line member function declaration must also be a
1316            // definition (C++ [dcl.meaning]p1).
1317            if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1318                !InvalidDecl) {
1319              Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1320                << D.getCXXScopeSpec().getRange();
1321              NewFD->setInvalidDecl();
1322            }
1323          }
1324
1325         return NewFD;
1326        }
1327      }
1328
1329      if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1330        // The user tried to provide an out-of-line definition for a
1331        // member function, but there was no such member function
1332        // declared (C++ [class.mfct]p2). For example:
1333        //
1334        // class X {
1335        //   void f() const;
1336        // };
1337        //
1338        // void X::f() { } // ill-formed
1339        //
1340        // Complain about this problem, and attempt to suggest close
1341        // matches (e.g., those that differ only in cv-qualifiers and
1342        // whether the parameter types are references).
1343        Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1344          << cast<CXXRecordDecl>(DC)->getDeclName()
1345          << D.getCXXScopeSpec().getRange();
1346        InvalidDecl = true;
1347
1348        PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
1349        if (!PrevDecl) {
1350          // Nothing to suggest.
1351        } else if (OverloadedFunctionDecl *Ovl
1352                   = dyn_cast<OverloadedFunctionDecl>(PrevDecl)) {
1353          for (OverloadedFunctionDecl::function_iterator
1354                 Func = Ovl->function_begin(),
1355                 FuncEnd = Ovl->function_end();
1356               Func != FuncEnd; ++Func) {
1357            if (isNearlyMatchingMemberFunction(Context, *Func, NewFD))
1358              Diag((*Func)->getLocation(), diag::note_member_def_close_match);
1359
1360          }
1361        } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(PrevDecl)) {
1362          // Suggest this no matter how mismatched it is; it's the only
1363          // thing we have.
1364          unsigned diag;
1365          if (isNearlyMatchingMemberFunction(Context, Method, NewFD))
1366            diag = diag::note_member_def_close_match;
1367          else if (Method->getBody())
1368            diag = diag::note_previous_definition;
1369          else
1370            diag = diag::note_previous_declaration;
1371          Diag(Method->getLocation(), diag);
1372        }
1373
1374        PrevDecl = 0;
1375      }
1376    }
1377    New = NewFD;
1378
1379    if (getLangOptions().CPlusPlus) {
1380      // In C++, check default arguments now that we have merged decls.
1381      CheckCXXDefaultArguments(NewFD);
1382
1383      // An out-of-line member function declaration must also be a
1384      // definition (C++ [dcl.meaning]p1).
1385      if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet()) {
1386        Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1387          << D.getCXXScopeSpec().getRange();
1388        InvalidDecl = true;
1389      }
1390    }
1391  } else {
1392    // Check that there are no default arguments (C++ only).
1393    if (getLangOptions().CPlusPlus)
1394      CheckExtraCXXDefaultArguments(D);
1395
1396    if (R.getTypePtr()->isObjCInterfaceType()) {
1397      Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1398        << D.getIdentifier();
1399      InvalidDecl = true;
1400    }
1401
1402    VarDecl *NewVD;
1403    VarDecl::StorageClass SC;
1404    switch (D.getDeclSpec().getStorageClassSpec()) {
1405    default: assert(0 && "Unknown storage class!");
1406    case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
1407    case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
1408    case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
1409    case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
1410    case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
1411    case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1412    case DeclSpec::SCS_mutable:
1413      // mutable can only appear on non-static class members, so it's always
1414      // an error here
1415      Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1416      InvalidDecl = true;
1417      SC = VarDecl::None;
1418      break;
1419    }
1420
1421    IdentifierInfo *II = Name.getAsIdentifierInfo();
1422    if (!II) {
1423      Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1424       << Name.getAsString();
1425      return 0;
1426    }
1427
1428    if (DC->isCXXRecord()) {
1429      // This is a static data member for a C++ class.
1430      NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
1431                                      D.getIdentifierLoc(), II,
1432                                      R, LastDeclarator);
1433    } else {
1434      bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
1435      if (S->getFnParent() == 0) {
1436        // C99 6.9p2: The storage-class specifiers auto and register shall not
1437        // appear in the declaration specifiers in an external declaration.
1438        if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1439          Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
1440          InvalidDecl = true;
1441        }
1442      }
1443      NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1444                              II, R, SC, LastDeclarator,
1445                              // FIXME: Move to DeclGroup...
1446                              D.getDeclSpec().getSourceRange().getBegin());
1447      NewVD->setThreadSpecified(ThreadSpecified);
1448    }
1449    // Handle attributes prior to checking for duplicates in MergeVarDecl
1450    ProcessDeclAttributes(NewVD, D);
1451
1452    // Handle GNU asm-label extension (encoded as an attribute).
1453    if (Expr *E = (Expr*) D.getAsmLabel()) {
1454      // The parser guarantees this is a string.
1455      StringLiteral *SE = cast<StringLiteral>(E);
1456      NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1457                                                  SE->getByteLength())));
1458    }
1459
1460    // Emit an error if an address space was applied to decl with local storage.
1461    // This includes arrays of objects with address space qualifiers, but not
1462    // automatic variables that point to other address spaces.
1463    // ISO/IEC TR 18037 S5.1.2
1464    if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1465      Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1466      InvalidDecl = true;
1467    }
1468    // Merge the decl with the existing one if appropriate. If the decl is
1469    // in an outer scope, it isn't the same thing.
1470    if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1471      if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1472        // The user tried to define a non-static data member
1473        // out-of-line (C++ [dcl.meaning]p1).
1474        Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1475          << D.getCXXScopeSpec().getRange();
1476        NewVD->Destroy(Context);
1477        return 0;
1478      }
1479
1480      NewVD = MergeVarDecl(NewVD, PrevDecl);
1481      if (NewVD == 0) return 0;
1482
1483      if (D.getCXXScopeSpec().isSet()) {
1484        // No previous declaration in the qualifying scope.
1485        Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1486          << Name << D.getCXXScopeSpec().getRange();
1487        InvalidDecl = true;
1488      }
1489    }
1490    New = NewVD;
1491  }
1492
1493  // Set the lexical context. If the declarator has a C++ scope specifier, the
1494  // lexical context will be different from the semantic context.
1495  New->setLexicalDeclContext(CurContext);
1496
1497  // If this has an identifier, add it to the scope stack.
1498  if (Name)
1499    PushOnScopeChains(New, S);
1500  // If any semantic error occurred, mark the decl as invalid.
1501  if (D.getInvalidType() || InvalidDecl)
1502    New->setInvalidDecl();
1503
1504  return New;
1505}
1506
1507void Sema::InitializerElementNotConstant(const Expr *Init) {
1508  Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1509    << Init->getSourceRange();
1510}
1511
1512bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1513  switch (Init->getStmtClass()) {
1514  default:
1515    InitializerElementNotConstant(Init);
1516    return true;
1517  case Expr::ParenExprClass: {
1518    const ParenExpr* PE = cast<ParenExpr>(Init);
1519    return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1520  }
1521  case Expr::CompoundLiteralExprClass:
1522    return cast<CompoundLiteralExpr>(Init)->isFileScope();
1523  case Expr::DeclRefExprClass: {
1524    const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1525    if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1526      if (VD->hasGlobalStorage())
1527        return false;
1528      InitializerElementNotConstant(Init);
1529      return true;
1530    }
1531    if (isa<FunctionDecl>(D))
1532      return false;
1533    InitializerElementNotConstant(Init);
1534    return true;
1535  }
1536  case Expr::MemberExprClass: {
1537    const MemberExpr *M = cast<MemberExpr>(Init);
1538    if (M->isArrow())
1539      return CheckAddressConstantExpression(M->getBase());
1540    return CheckAddressConstantExpressionLValue(M->getBase());
1541  }
1542  case Expr::ArraySubscriptExprClass: {
1543    // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1544    const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1545    return CheckAddressConstantExpression(ASE->getBase()) ||
1546           CheckArithmeticConstantExpression(ASE->getIdx());
1547  }
1548  case Expr::StringLiteralClass:
1549  case Expr::PredefinedExprClass:
1550    return false;
1551  case Expr::UnaryOperatorClass: {
1552    const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1553
1554    // C99 6.6p9
1555    if (Exp->getOpcode() == UnaryOperator::Deref)
1556      return CheckAddressConstantExpression(Exp->getSubExpr());
1557
1558    InitializerElementNotConstant(Init);
1559    return true;
1560  }
1561  }
1562}
1563
1564bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1565  switch (Init->getStmtClass()) {
1566  default:
1567    InitializerElementNotConstant(Init);
1568    return true;
1569  case Expr::ParenExprClass:
1570    return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
1571  case Expr::StringLiteralClass:
1572  case Expr::ObjCStringLiteralClass:
1573    return false;
1574  case Expr::CallExprClass:
1575  case Expr::CXXOperatorCallExprClass:
1576    // __builtin___CFStringMakeConstantString is a valid constant l-value.
1577    if (cast<CallExpr>(Init)->isBuiltinCall() ==
1578           Builtin::BI__builtin___CFStringMakeConstantString)
1579      return false;
1580
1581    InitializerElementNotConstant(Init);
1582    return true;
1583
1584  case Expr::UnaryOperatorClass: {
1585    const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1586
1587    // C99 6.6p9
1588    if (Exp->getOpcode() == UnaryOperator::AddrOf)
1589      return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1590
1591    if (Exp->getOpcode() == UnaryOperator::Extension)
1592      return CheckAddressConstantExpression(Exp->getSubExpr());
1593
1594    InitializerElementNotConstant(Init);
1595    return true;
1596  }
1597  case Expr::BinaryOperatorClass: {
1598    // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1599    const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1600
1601    Expr *PExp = Exp->getLHS();
1602    Expr *IExp = Exp->getRHS();
1603    if (IExp->getType()->isPointerType())
1604      std::swap(PExp, IExp);
1605
1606    // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1607    return CheckAddressConstantExpression(PExp) ||
1608           CheckArithmeticConstantExpression(IExp);
1609  }
1610  case Expr::ImplicitCastExprClass:
1611  case Expr::CStyleCastExprClass: {
1612    const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
1613    if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1614      // Check for implicit promotion
1615      if (SubExpr->getType()->isFunctionType() ||
1616          SubExpr->getType()->isArrayType())
1617        return CheckAddressConstantExpressionLValue(SubExpr);
1618    }
1619
1620    // Check for pointer->pointer cast
1621    if (SubExpr->getType()->isPointerType())
1622      return CheckAddressConstantExpression(SubExpr);
1623
1624    if (SubExpr->getType()->isIntegralType()) {
1625      // Check for the special-case of a pointer->int->pointer cast;
1626      // this isn't standard, but some code requires it. See
1627      // PR2720 for an example.
1628      if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1629        if (SubCast->getSubExpr()->getType()->isPointerType()) {
1630          unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1631          unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1632          if (IntWidth >= PointerWidth) {
1633            return CheckAddressConstantExpression(SubCast->getSubExpr());
1634          }
1635        }
1636      }
1637    }
1638    if (SubExpr->getType()->isArithmeticType()) {
1639      return CheckArithmeticConstantExpression(SubExpr);
1640    }
1641
1642    InitializerElementNotConstant(Init);
1643    return true;
1644  }
1645  case Expr::ConditionalOperatorClass: {
1646    // FIXME: Should we pedwarn here?
1647    const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1648    if (!Exp->getCond()->getType()->isArithmeticType()) {
1649      InitializerElementNotConstant(Init);
1650      return true;
1651    }
1652    if (CheckArithmeticConstantExpression(Exp->getCond()))
1653      return true;
1654    if (Exp->getLHS() &&
1655        CheckAddressConstantExpression(Exp->getLHS()))
1656      return true;
1657    return CheckAddressConstantExpression(Exp->getRHS());
1658  }
1659  case Expr::AddrLabelExprClass:
1660    return false;
1661  }
1662}
1663
1664static const Expr* FindExpressionBaseAddress(const Expr* E);
1665
1666static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1667  switch (E->getStmtClass()) {
1668  default:
1669    return E;
1670  case Expr::ParenExprClass: {
1671    const ParenExpr* PE = cast<ParenExpr>(E);
1672    return FindExpressionBaseAddressLValue(PE->getSubExpr());
1673  }
1674  case Expr::MemberExprClass: {
1675    const MemberExpr *M = cast<MemberExpr>(E);
1676    if (M->isArrow())
1677      return FindExpressionBaseAddress(M->getBase());
1678    return FindExpressionBaseAddressLValue(M->getBase());
1679  }
1680  case Expr::ArraySubscriptExprClass: {
1681    const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1682    return FindExpressionBaseAddress(ASE->getBase());
1683  }
1684  case Expr::UnaryOperatorClass: {
1685    const UnaryOperator *Exp = cast<UnaryOperator>(E);
1686
1687    if (Exp->getOpcode() == UnaryOperator::Deref)
1688      return FindExpressionBaseAddress(Exp->getSubExpr());
1689
1690    return E;
1691  }
1692  }
1693}
1694
1695static const Expr* FindExpressionBaseAddress(const Expr* E) {
1696  switch (E->getStmtClass()) {
1697  default:
1698    return E;
1699  case Expr::ParenExprClass: {
1700    const ParenExpr* PE = cast<ParenExpr>(E);
1701    return FindExpressionBaseAddress(PE->getSubExpr());
1702  }
1703  case Expr::UnaryOperatorClass: {
1704    const UnaryOperator *Exp = cast<UnaryOperator>(E);
1705
1706    // C99 6.6p9
1707    if (Exp->getOpcode() == UnaryOperator::AddrOf)
1708      return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1709
1710    if (Exp->getOpcode() == UnaryOperator::Extension)
1711      return FindExpressionBaseAddress(Exp->getSubExpr());
1712
1713    return E;
1714  }
1715  case Expr::BinaryOperatorClass: {
1716    const BinaryOperator *Exp = cast<BinaryOperator>(E);
1717
1718    Expr *PExp = Exp->getLHS();
1719    Expr *IExp = Exp->getRHS();
1720    if (IExp->getType()->isPointerType())
1721      std::swap(PExp, IExp);
1722
1723    return FindExpressionBaseAddress(PExp);
1724  }
1725  case Expr::ImplicitCastExprClass: {
1726    const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1727
1728    // Check for implicit promotion
1729    if (SubExpr->getType()->isFunctionType() ||
1730        SubExpr->getType()->isArrayType())
1731      return FindExpressionBaseAddressLValue(SubExpr);
1732
1733    // Check for pointer->pointer cast
1734    if (SubExpr->getType()->isPointerType())
1735      return FindExpressionBaseAddress(SubExpr);
1736
1737    // We assume that we have an arithmetic expression here;
1738    // if we don't, we'll figure it out later
1739    return 0;
1740  }
1741  case Expr::CStyleCastExprClass: {
1742    const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1743
1744    // Check for pointer->pointer cast
1745    if (SubExpr->getType()->isPointerType())
1746      return FindExpressionBaseAddress(SubExpr);
1747
1748    // We assume that we have an arithmetic expression here;
1749    // if we don't, we'll figure it out later
1750    return 0;
1751  }
1752  }
1753}
1754
1755bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1756  switch (Init->getStmtClass()) {
1757  default:
1758    InitializerElementNotConstant(Init);
1759    return true;
1760  case Expr::ParenExprClass: {
1761    const ParenExpr* PE = cast<ParenExpr>(Init);
1762    return CheckArithmeticConstantExpression(PE->getSubExpr());
1763  }
1764  case Expr::FloatingLiteralClass:
1765  case Expr::IntegerLiteralClass:
1766  case Expr::CharacterLiteralClass:
1767  case Expr::ImaginaryLiteralClass:
1768  case Expr::TypesCompatibleExprClass:
1769  case Expr::CXXBoolLiteralExprClass:
1770    return false;
1771  case Expr::CallExprClass:
1772  case Expr::CXXOperatorCallExprClass: {
1773    const CallExpr *CE = cast<CallExpr>(Init);
1774
1775    // Allow any constant foldable calls to builtins.
1776    if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
1777      return false;
1778
1779    InitializerElementNotConstant(Init);
1780    return true;
1781  }
1782  case Expr::DeclRefExprClass: {
1783    const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1784    if (isa<EnumConstantDecl>(D))
1785      return false;
1786    InitializerElementNotConstant(Init);
1787    return true;
1788  }
1789  case Expr::CompoundLiteralExprClass:
1790    // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1791    // but vectors are allowed to be magic.
1792    if (Init->getType()->isVectorType())
1793      return false;
1794    InitializerElementNotConstant(Init);
1795    return true;
1796  case Expr::UnaryOperatorClass: {
1797    const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1798
1799    switch (Exp->getOpcode()) {
1800    // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1801    // See C99 6.6p3.
1802    default:
1803      InitializerElementNotConstant(Init);
1804      return true;
1805    case UnaryOperator::OffsetOf:
1806      if (Exp->getSubExpr()->getType()->isConstantSizeType())
1807        return false;
1808      InitializerElementNotConstant(Init);
1809      return true;
1810    case UnaryOperator::Extension:
1811    case UnaryOperator::LNot:
1812    case UnaryOperator::Plus:
1813    case UnaryOperator::Minus:
1814    case UnaryOperator::Not:
1815      return CheckArithmeticConstantExpression(Exp->getSubExpr());
1816    }
1817  }
1818  case Expr::SizeOfAlignOfExprClass: {
1819    const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
1820    // Special check for void types, which are allowed as an extension
1821    if (Exp->getTypeOfArgument()->isVoidType())
1822      return false;
1823    // alignof always evaluates to a constant.
1824    // FIXME: is sizeof(int[3.0]) a constant expression?
1825    if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
1826      InitializerElementNotConstant(Init);
1827      return true;
1828    }
1829    return false;
1830  }
1831  case Expr::BinaryOperatorClass: {
1832    const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1833
1834    if (Exp->getLHS()->getType()->isArithmeticType() &&
1835        Exp->getRHS()->getType()->isArithmeticType()) {
1836      return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1837             CheckArithmeticConstantExpression(Exp->getRHS());
1838    }
1839
1840    if (Exp->getLHS()->getType()->isPointerType() &&
1841        Exp->getRHS()->getType()->isPointerType()) {
1842      const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1843      const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1844
1845      // Only allow a null (constant integer) base; we could
1846      // allow some additional cases if necessary, but this
1847      // is sufficient to cover offsetof-like constructs.
1848      if (!LHSBase && !RHSBase) {
1849        return CheckAddressConstantExpression(Exp->getLHS()) ||
1850               CheckAddressConstantExpression(Exp->getRHS());
1851      }
1852    }
1853
1854    InitializerElementNotConstant(Init);
1855    return true;
1856  }
1857  case Expr::ImplicitCastExprClass:
1858  case Expr::CStyleCastExprClass: {
1859    const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
1860    if (SubExpr->getType()->isArithmeticType())
1861      return CheckArithmeticConstantExpression(SubExpr);
1862
1863    if (SubExpr->getType()->isPointerType()) {
1864      const Expr* Base = FindExpressionBaseAddress(SubExpr);
1865      // If the pointer has a null base, this is an offsetof-like construct
1866      if (!Base)
1867        return CheckAddressConstantExpression(SubExpr);
1868    }
1869
1870    InitializerElementNotConstant(Init);
1871    return true;
1872  }
1873  case Expr::ConditionalOperatorClass: {
1874    const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1875
1876    // If GNU extensions are disabled, we require all operands to be arithmetic
1877    // constant expressions.
1878    if (getLangOptions().NoExtensions) {
1879      return CheckArithmeticConstantExpression(Exp->getCond()) ||
1880          (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1881             CheckArithmeticConstantExpression(Exp->getRHS());
1882    }
1883
1884    // Otherwise, we have to emulate some of the behavior of fold here.
1885    // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1886    // because it can constant fold things away.  To retain compatibility with
1887    // GCC code, we see if we can fold the condition to a constant (which we
1888    // should always be able to do in theory).  If so, we only require the
1889    // specified arm of the conditional to be a constant.  This is a horrible
1890    // hack, but is require by real world code that uses __builtin_constant_p.
1891    APValue Val;
1892    if (!Exp->getCond()->Evaluate(Val, Context)) {
1893      // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
1894      // won't be able to either.  Use it to emit the diagnostic though.
1895      bool Res = CheckArithmeticConstantExpression(Exp->getCond());
1896      assert(Res && "Evaluate couldn't evaluate this constant?");
1897      return Res;
1898    }
1899
1900    // Verify that the side following the condition is also a constant.
1901    const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
1902    if (Val.getInt() == 0)
1903      std::swap(TrueSide, FalseSide);
1904
1905    if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
1906      return true;
1907
1908    // Okay, the evaluated side evaluates to a constant, so we accept this.
1909    // Check to see if the other side is obviously not a constant.  If so,
1910    // emit a warning that this is a GNU extension.
1911    if (FalseSide && !FalseSide->isEvaluatable(Context))
1912      Diag(Init->getExprLoc(),
1913           diag::ext_typecheck_expression_not_constant_but_accepted)
1914        << FalseSide->getSourceRange();
1915    return false;
1916  }
1917  }
1918}
1919
1920bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
1921  Expr::EvalResult Result;
1922
1923  Init = Init->IgnoreParens();
1924
1925  if (Init->Evaluate(Result, Context) && !Result.HasSideEffects)
1926    return false;
1927
1928  // Look through CXXDefaultArgExprs; they have no meaning in this context.
1929  if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1930    return CheckForConstantInitializer(DAE->getExpr(), DclT);
1931
1932  if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1933    return CheckForConstantInitializer(e->getInitializer(), DclT);
1934
1935  if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1936    unsigned numInits = Exp->getNumInits();
1937    for (unsigned i = 0; i < numInits; i++) {
1938      // FIXME: Need to get the type of the declaration for C++,
1939      // because it could be a reference?
1940      if (CheckForConstantInitializer(Exp->getInit(i),
1941                                      Exp->getInit(i)->getType()))
1942        return true;
1943    }
1944    return false;
1945  }
1946
1947  // FIXME: We can probably remove some of this code below, now that
1948  // Expr::Evaluate is doing the heavy lifting for scalars.
1949
1950  if (Init->isNullPointerConstant(Context))
1951    return false;
1952  if (Init->getType()->isArithmeticType()) {
1953    QualType InitTy = Context.getCanonicalType(Init->getType())
1954                             .getUnqualifiedType();
1955    if (InitTy == Context.BoolTy) {
1956      // Special handling for pointers implicitly cast to bool;
1957      // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1958      if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1959        Expr* SubE = ICE->getSubExpr();
1960        if (SubE->getType()->isPointerType() ||
1961            SubE->getType()->isArrayType() ||
1962            SubE->getType()->isFunctionType()) {
1963          return CheckAddressConstantExpression(Init);
1964        }
1965      }
1966    } else if (InitTy->isIntegralType()) {
1967      Expr* SubE = 0;
1968      if (CastExpr* CE = dyn_cast<CastExpr>(Init))
1969        SubE = CE->getSubExpr();
1970      // Special check for pointer cast to int; we allow as an extension
1971      // an address constant cast to an integer if the integer
1972      // is of an appropriate width (this sort of code is apparently used
1973      // in some places).
1974      // FIXME: Add pedwarn?
1975      // FIXME: Don't allow bitfields here!  Need the FieldDecl for that.
1976      if (SubE && (SubE->getType()->isPointerType() ||
1977                   SubE->getType()->isArrayType() ||
1978                   SubE->getType()->isFunctionType())) {
1979        unsigned IntWidth = Context.getTypeSize(Init->getType());
1980        unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1981        if (IntWidth >= PointerWidth)
1982          return CheckAddressConstantExpression(Init);
1983      }
1984    }
1985
1986    return CheckArithmeticConstantExpression(Init);
1987  }
1988
1989  if (Init->getType()->isPointerType())
1990    return CheckAddressConstantExpression(Init);
1991
1992  // An array type at the top level that isn't an init-list must
1993  // be a string literal
1994  if (Init->getType()->isArrayType())
1995    return false;
1996
1997  if (Init->getType()->isFunctionType())
1998    return false;
1999
2000  // Allow block exprs at top level.
2001  if (Init->getType()->isBlockPointerType())
2002    return false;
2003
2004  InitializerElementNotConstant(Init);
2005  return true;
2006}
2007
2008void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
2009  Decl *RealDecl = static_cast<Decl *>(dcl);
2010  Expr *Init = static_cast<Expr *>(init.release());
2011  assert(Init && "missing initializer");
2012
2013  // If there is no declaration, there was an error parsing it.  Just ignore
2014  // the initializer.
2015  if (RealDecl == 0) {
2016    delete Init;
2017    return;
2018  }
2019
2020  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2021  if (!VDecl) {
2022    Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
2023         diag::err_illegal_initializer);
2024    RealDecl->setInvalidDecl();
2025    return;
2026  }
2027  // Get the decls type and save a reference for later, since
2028  // CheckInitializerTypes may change it.
2029  QualType DclT = VDecl->getType(), SavT = DclT;
2030  if (VDecl->isBlockVarDecl()) {
2031    VarDecl::StorageClass SC = VDecl->getStorageClass();
2032    if (SC == VarDecl::Extern) { // C99 6.7.8p5
2033      Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
2034      VDecl->setInvalidDecl();
2035    } else if (!VDecl->isInvalidDecl()) {
2036      if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
2037                                VDecl->getDeclName()))
2038        VDecl->setInvalidDecl();
2039
2040      // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2041      if (!getLangOptions().CPlusPlus) {
2042        if (SC == VarDecl::Static) // C99 6.7.8p4.
2043          CheckForConstantInitializer(Init, DclT);
2044      }
2045    }
2046  } else if (VDecl->isFileVarDecl()) {
2047    if (VDecl->getStorageClass() == VarDecl::Extern)
2048      Diag(VDecl->getLocation(), diag::warn_extern_init);
2049    if (!VDecl->isInvalidDecl())
2050      if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
2051                                VDecl->getDeclName()))
2052        VDecl->setInvalidDecl();
2053
2054    // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2055    if (!getLangOptions().CPlusPlus) {
2056      // C99 6.7.8p4. All file scoped initializers need to be constant.
2057      CheckForConstantInitializer(Init, DclT);
2058    }
2059  }
2060  // If the type changed, it means we had an incomplete type that was
2061  // completed by the initializer. For example:
2062  //   int ary[] = { 1, 3, 5 };
2063  // "ary" transitions from a VariableArrayType to a ConstantArrayType.
2064  if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
2065    VDecl->setType(DclT);
2066    Init->setType(DclT);
2067  }
2068
2069  // Attach the initializer to the decl.
2070  VDecl->setInit(Init);
2071  return;
2072}
2073
2074void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2075  Decl *RealDecl = static_cast<Decl *>(dcl);
2076
2077  // If there is no declaration, there was an error parsing it. Just ignore it.
2078  if (RealDecl == 0)
2079    return;
2080
2081  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2082    QualType Type = Var->getType();
2083    // C++ [dcl.init.ref]p3:
2084    //   The initializer can be omitted for a reference only in a
2085    //   parameter declaration (8.3.5), in the declaration of a
2086    //   function return type, in the declaration of a class member
2087    //   within its class declaration (9.2), and where the extern
2088    //   specifier is explicitly used.
2089    if (Type->isReferenceType() &&
2090        Var->getStorageClass() != VarDecl::Extern &&
2091        Var->getStorageClass() != VarDecl::PrivateExtern) {
2092      Diag(Var->getLocation(), diag::err_reference_var_requires_init)
2093        << Var->getDeclName()
2094        << SourceRange(Var->getLocation(), Var->getLocation());
2095      Var->setInvalidDecl();
2096      return;
2097    }
2098
2099    // C++ [dcl.init]p9:
2100    //
2101    //   If no initializer is specified for an object, and the object
2102    //   is of (possibly cv-qualified) non-POD class type (or array
2103    //   thereof), the object shall be default-initialized; if the
2104    //   object is of const-qualified type, the underlying class type
2105    //   shall have a user-declared default constructor.
2106    if (getLangOptions().CPlusPlus) {
2107      QualType InitType = Type;
2108      if (const ArrayType *Array = Context.getAsArrayType(Type))
2109        InitType = Array->getElementType();
2110      if (Var->getStorageClass() != VarDecl::Extern &&
2111          Var->getStorageClass() != VarDecl::PrivateExtern &&
2112          InitType->isRecordType()) {
2113        const CXXConstructorDecl *Constructor
2114          = PerformInitializationByConstructor(InitType, 0, 0,
2115                                               Var->getLocation(),
2116                                               SourceRange(Var->getLocation(),
2117                                                           Var->getLocation()),
2118                                               Var->getDeclName(),
2119                                               IK_Default);
2120        if (!Constructor)
2121          Var->setInvalidDecl();
2122      }
2123    }
2124
2125#if 0
2126    // FIXME: Temporarily disabled because we are not properly parsing
2127    // linkage specifications on declarations, e.g.,
2128    //
2129    //   extern "C" const CGPoint CGPointerZero;
2130    //
2131    // C++ [dcl.init]p9:
2132    //
2133    //     If no initializer is specified for an object, and the
2134    //     object is of (possibly cv-qualified) non-POD class type (or
2135    //     array thereof), the object shall be default-initialized; if
2136    //     the object is of const-qualified type, the underlying class
2137    //     type shall have a user-declared default
2138    //     constructor. Otherwise, if no initializer is specified for
2139    //     an object, the object and its subobjects, if any, have an
2140    //     indeterminate initial value; if the object or any of its
2141    //     subobjects are of const-qualified type, the program is
2142    //     ill-formed.
2143    //
2144    // This isn't technically an error in C, so we don't diagnose it.
2145    //
2146    // FIXME: Actually perform the POD/user-defined default
2147    // constructor check.
2148    if (getLangOptions().CPlusPlus &&
2149        Context.getCanonicalType(Type).isConstQualified() &&
2150        Var->getStorageClass() != VarDecl::Extern)
2151      Diag(Var->getLocation(),  diag::err_const_var_requires_init)
2152        << Var->getName()
2153        << SourceRange(Var->getLocation(), Var->getLocation());
2154#endif
2155  }
2156}
2157
2158/// The declarators are chained together backwards, reverse the list.
2159Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2160  // Often we have single declarators, handle them quickly.
2161  Decl *GroupDecl = static_cast<Decl*>(group);
2162  if (GroupDecl == 0)
2163    return 0;
2164
2165  ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
2166  ScopedDecl *NewGroup = 0;
2167  if (Group->getNextDeclarator() == 0)
2168    NewGroup = Group;
2169  else { // reverse the list.
2170    while (Group) {
2171      ScopedDecl *Next = Group->getNextDeclarator();
2172      Group->setNextDeclarator(NewGroup);
2173      NewGroup = Group;
2174      Group = Next;
2175    }
2176  }
2177  // Perform semantic analysis that depends on having fully processed both
2178  // the declarator and initializer.
2179  for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
2180    VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2181    if (!IDecl)
2182      continue;
2183    QualType T = IDecl->getType();
2184
2185    if (T->isVariableArrayType()) {
2186      const VariableArrayType *VAT =
2187        cast<VariableArrayType>(T.getUnqualifiedType());
2188
2189      // FIXME: This won't give the correct result for
2190      // int a[10][n];
2191      SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
2192      if (IDecl->isFileVarDecl()) {
2193        Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2194          SizeRange;
2195
2196        IDecl->setInvalidDecl();
2197      } else {
2198        // C99 6.7.5.2p2: If an identifier is declared to be an object with
2199        // static storage duration, it shall not have a variable length array.
2200        if (IDecl->getStorageClass() == VarDecl::Static) {
2201          Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2202            << SizeRange;
2203          IDecl->setInvalidDecl();
2204        } else if (IDecl->getStorageClass() == VarDecl::Extern) {
2205          Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2206            << SizeRange;
2207          IDecl->setInvalidDecl();
2208        }
2209      }
2210    } else if (T->isVariablyModifiedType()) {
2211      if (IDecl->isFileVarDecl()) {
2212        Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2213        IDecl->setInvalidDecl();
2214      } else {
2215        if (IDecl->getStorageClass() == VarDecl::Extern) {
2216          Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2217          IDecl->setInvalidDecl();
2218        }
2219      }
2220    }
2221
2222    // Block scope. C99 6.7p7: If an identifier for an object is declared with
2223    // no linkage (C99 6.2.2p6), the type for the object shall be complete...
2224    if (IDecl->isBlockVarDecl() &&
2225        IDecl->getStorageClass() != VarDecl::Extern) {
2226      if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
2227        Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
2228        IDecl->setInvalidDecl();
2229      }
2230    }
2231    // File scope. C99 6.9.2p2: A declaration of an identifier for and
2232    // object that has file scope without an initializer, and without a
2233    // storage-class specifier or with the storage-class specifier "static",
2234    // constitutes a tentative definition. Note: A tentative definition with
2235    // external linkage is valid (C99 6.2.2p5).
2236    if (isTentativeDefinition(IDecl)) {
2237      if (T->isIncompleteArrayType()) {
2238        // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2239        // array to be completed. Don't issue a diagnostic.
2240      } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
2241        // C99 6.9.2p3: If the declaration of an identifier for an object is
2242        // a tentative definition and has internal linkage (C99 6.2.2p3), the
2243        // declared type shall not be an incomplete type.
2244        Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
2245        IDecl->setInvalidDecl();
2246      }
2247    }
2248    if (IDecl->isFileVarDecl())
2249      CheckForFileScopedRedefinitions(S, IDecl);
2250  }
2251  return NewGroup;
2252}
2253
2254/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2255/// to introduce parameters into function prototype scope.
2256Sema::DeclTy *
2257Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
2258  const DeclSpec &DS = D.getDeclSpec();
2259
2260  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
2261  VarDecl::StorageClass StorageClass = VarDecl::None;
2262  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2263    StorageClass = VarDecl::Register;
2264  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
2265    Diag(DS.getStorageClassSpecLoc(),
2266         diag::err_invalid_storage_class_in_func_decl);
2267    D.getMutableDeclSpec().ClearStorageClassSpecs();
2268  }
2269  if (DS.isThreadSpecified()) {
2270    Diag(DS.getThreadSpecLoc(),
2271         diag::err_invalid_storage_class_in_func_decl);
2272    D.getMutableDeclSpec().ClearStorageClassSpecs();
2273  }
2274
2275  // Check that there are no default arguments inside the type of this
2276  // parameter (C++ only).
2277  if (getLangOptions().CPlusPlus)
2278    CheckExtraCXXDefaultArguments(D);
2279
2280  // In this context, we *do not* check D.getInvalidType(). If the declarator
2281  // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2282  // though it will not reflect the user specified type.
2283  QualType parmDeclType = GetTypeForDeclarator(D, S);
2284
2285  assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2286
2287  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2288  // Can this happen for params?  We already checked that they don't conflict
2289  // among each other.  Here they can only shadow globals, which is ok.
2290  IdentifierInfo *II = D.getIdentifier();
2291  if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
2292    if (PrevDecl->isTemplateParameter()) {
2293      // Maybe we will complain about the shadowed template parameter.
2294      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2295      // Just pretend that we didn't see the previous declaration.
2296      PrevDecl = 0;
2297    } else if (S->isDeclScope(PrevDecl)) {
2298      Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
2299
2300      // Recover by removing the name
2301      II = 0;
2302      D.SetIdentifier(0, D.getIdentifierLoc());
2303    }
2304  }
2305
2306  // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2307  // Doing the promotion here has a win and a loss. The win is the type for
2308  // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2309  // code generator). The loss is the orginal type isn't preserved. For example:
2310  //
2311  // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2312  //    int blockvardecl[5];
2313  //    sizeof(parmvardecl);  // size == 4
2314  //    sizeof(blockvardecl); // size == 20
2315  // }
2316  //
2317  // For expressions, all implicit conversions are captured using the
2318  // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2319  //
2320  // FIXME: If a source translation tool needs to see the original type, then
2321  // we need to consider storing both types (in ParmVarDecl)...
2322  //
2323  if (parmDeclType->isArrayType()) {
2324    // int x[restrict 4] ->  int *restrict
2325    parmDeclType = Context.getArrayDecayedType(parmDeclType);
2326  } else if (parmDeclType->isFunctionType())
2327    parmDeclType = Context.getPointerType(parmDeclType);
2328
2329  ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2330                                         D.getIdentifierLoc(), II,
2331                                         parmDeclType, StorageClass,
2332                                         0, 0);
2333
2334  if (D.getInvalidType())
2335    New->setInvalidDecl();
2336
2337  // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2338  if (D.getCXXScopeSpec().isSet()) {
2339    Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2340      << D.getCXXScopeSpec().getRange();
2341    New->setInvalidDecl();
2342  }
2343
2344  // Add the parameter declaration into this scope.
2345  S->AddDecl(New);
2346  if (II)
2347    IdResolver.AddDecl(New);
2348
2349  ProcessDeclAttributes(New, D);
2350  return New;
2351
2352}
2353
2354Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
2355  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2356  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2357         "Not a function declarator!");
2358  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2359
2360  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2361  // for a K&R function.
2362  if (!FTI.hasPrototype) {
2363    for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
2364      if (FTI.ArgInfo[i].Param == 0) {
2365        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2366          << FTI.ArgInfo[i].Ident;
2367        // Implicitly declare the argument as type 'int' for lack of a better
2368        // type.
2369        DeclSpec DS;
2370        const char* PrevSpec; // unused
2371        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2372                           PrevSpec);
2373        Declarator ParamD(DS, Declarator::KNRTypeListContext);
2374        ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2375        FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
2376      }
2377    }
2378  } else {
2379    // FIXME: Diagnose arguments without names in C.
2380  }
2381
2382  Scope *ParentScope = FnBodyScope->getParent();
2383
2384  return ActOnStartOfFunctionDef(FnBodyScope,
2385                                 ActOnDeclarator(ParentScope, D, 0,
2386                                                 /*IsFunctionDefinition=*/true));
2387}
2388
2389Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2390  Decl *decl = static_cast<Decl*>(D);
2391  FunctionDecl *FD = cast<FunctionDecl>(decl);
2392
2393  // See if this is a redefinition.
2394  const FunctionDecl *Definition;
2395  if (FD->getBody(Definition)) {
2396    Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
2397    Diag(Definition->getLocation(), diag::note_previous_definition);
2398  }
2399
2400  PushDeclContext(FnBodyScope, FD);
2401
2402  // Check the validity of our function parameters
2403  CheckParmsForFunctionDef(FD);
2404
2405  // Introduce our parameters into the function scope
2406  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2407    ParmVarDecl *Param = FD->getParamDecl(p);
2408    // If this has an identifier, add it to the scope stack.
2409    if (Param->getIdentifier())
2410      PushOnScopeChains(Param, FnBodyScope);
2411  }
2412
2413  return FD;
2414}
2415
2416Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
2417  Decl *dcl = static_cast<Decl *>(D);
2418  Stmt *Body = static_cast<Stmt*>(BodyArg.release());
2419  if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
2420    FD->setBody(Body);
2421    assert(FD == getCurFunctionDecl() && "Function parsing confused");
2422  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
2423    MD->setBody((Stmt*)Body);
2424  } else
2425    return 0;
2426  PopDeclContext();
2427  // Verify and clean out per-function state.
2428
2429  // Check goto/label use.
2430  for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2431       I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2432    // Verify that we have no forward references left.  If so, there was a goto
2433    // or address of a label taken, but no definition of it.  Label fwd
2434    // definitions are indicated with a null substmt.
2435    if (I->second->getSubStmt() == 0) {
2436      LabelStmt *L = I->second;
2437      // Emit error.
2438      Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
2439
2440      // At this point, we have gotos that use the bogus label.  Stitch it into
2441      // the function body so that they aren't leaked and that the AST is well
2442      // formed.
2443      if (Body) {
2444        L->setSubStmt(new NullStmt(L->getIdentLoc()));
2445        cast<CompoundStmt>(Body)->push_back(L);
2446      } else {
2447        // The whole function wasn't parsed correctly, just delete this.
2448        delete L;
2449      }
2450    }
2451  }
2452  LabelMap.clear();
2453
2454  return D;
2455}
2456
2457/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2458/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
2459ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2460                                           IdentifierInfo &II, Scope *S) {
2461  // Extension in C99.  Legal in C90, but warn about it.
2462  if (getLangOptions().C99)
2463    Diag(Loc, diag::ext_implicit_function_decl) << &II;
2464  else
2465    Diag(Loc, diag::warn_implicit_function_decl) << &II;
2466
2467  // FIXME: handle stuff like:
2468  // void foo() { extern float X(); }
2469  // void bar() { X(); }  <-- implicit decl for X in another scope.
2470
2471  // Set a Declarator for the implicit definition: int foo();
2472  const char *Dummy;
2473  DeclSpec DS;
2474  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2475  Error = Error; // Silence warning.
2476  assert(!Error && "Error setting up implicit decl!");
2477  Declarator D(DS, Declarator::BlockContext);
2478  D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
2479  D.SetIdentifier(&II, Loc);
2480
2481  // Insert this function into translation-unit scope.
2482
2483  DeclContext *PrevDC = CurContext;
2484  CurContext = Context.getTranslationUnitDecl();
2485
2486  FunctionDecl *FD =
2487    dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
2488  FD->setImplicit();
2489
2490  CurContext = PrevDC;
2491
2492  return FD;
2493}
2494
2495
2496TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2497                                    ScopedDecl *LastDeclarator) {
2498  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
2499  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2500
2501  // Scope manipulation handled by caller.
2502  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2503                                           D.getIdentifierLoc(),
2504                                           D.getIdentifier(),
2505                                           T, LastDeclarator);
2506  if (D.getInvalidType())
2507    NewTD->setInvalidDecl();
2508  return NewTD;
2509}
2510
2511/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
2512/// former case, Name will be non-null.  In the later case, Name will be null.
2513/// TagType indicates what kind of tag this is. TK indicates whether this is a
2514/// reference/declaration/definition of a tag.
2515Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
2516                             SourceLocation KWLoc, const CXXScopeSpec &SS,
2517                             IdentifierInfo *Name, SourceLocation NameLoc,
2518                             AttributeList *Attr) {
2519  // If this is not a definition, it must have a name.
2520  assert((Name != 0 || TK == TK_Definition) &&
2521         "Nameless record must be a definition!");
2522
2523  TagDecl::TagKind Kind;
2524  switch (TagType) {
2525  default: assert(0 && "Unknown tag type!");
2526  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2527  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
2528  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
2529  case DeclSpec::TST_enum:   Kind = TagDecl::TK_enum; break;
2530  }
2531
2532  DeclContext *DC = CurContext;
2533  ScopedDecl *PrevDecl = 0;
2534
2535  if (Name && SS.isNotEmpty()) {
2536    // We have a nested-name tag ('struct foo::bar').
2537
2538    // Check for invalid 'foo::'.
2539    if (SS.isInvalid()) {
2540      Name = 0;
2541      goto CreateNewDecl;
2542    }
2543
2544    DC = static_cast<DeclContext*>(SS.getScopeRep());
2545    // Look-up name inside 'foo::'.
2546    PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2547
2548    // A tag 'foo::bar' must already exist.
2549    if (PrevDecl == 0) {
2550      Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
2551      Name = 0;
2552      goto CreateNewDecl;
2553    }
2554  } else {
2555    // If this is a named struct, check to see if there was a previous forward
2556    // declaration or definition.
2557    // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2558    PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2559  }
2560
2561  if (PrevDecl && PrevDecl->isTemplateParameter()) {
2562    // Maybe we will complain about the shadowed template parameter.
2563    DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2564    // Just pretend that we didn't see the previous declaration.
2565    PrevDecl = 0;
2566  }
2567
2568  if (PrevDecl) {
2569    assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2570            "unexpected Decl type");
2571    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
2572      // If this is a use of a previous tag, or if the tag is already declared
2573      // in the same scope (so that the definition/declaration completes or
2574      // rementions the tag), reuse the decl.
2575      if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
2576        // Make sure that this wasn't declared as an enum and now used as a
2577        // struct or something similar.
2578        if (PrevTagDecl->getTagKind() != Kind) {
2579          Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
2580          Diag(PrevDecl->getLocation(), diag::note_previous_use);
2581          // Recover by making this an anonymous redefinition.
2582          Name = 0;
2583          PrevDecl = 0;
2584        } else {
2585          // If this is a use, just return the declaration we found.
2586
2587          // FIXME: In the future, return a variant or some other clue
2588          // for the consumer of this Decl to know it doesn't own it.
2589          // For our current ASTs this shouldn't be a problem, but will
2590          // need to be changed with DeclGroups.
2591          if (TK == TK_Reference)
2592            return PrevDecl;
2593
2594          // Diagnose attempts to redefine a tag.
2595          if (TK == TK_Definition) {
2596            if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2597              Diag(NameLoc, diag::err_redefinition) << Name;
2598              Diag(Def->getLocation(), diag::note_previous_definition);
2599              // If this is a redefinition, recover by making this struct be
2600              // anonymous, which will make any later references get the previous
2601              // definition.
2602              Name = 0;
2603              PrevDecl = 0;
2604            }
2605            // Okay, this is definition of a previously declared or referenced
2606            // tag PrevDecl. We're going to create a new Decl for it.
2607          }
2608        }
2609        // If we get here we have (another) forward declaration or we
2610        // have a definition.  Just create a new decl.
2611      } else {
2612        // If we get here, this is a definition of a new tag type in a nested
2613        // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2614        // new decl/type.  We set PrevDecl to NULL so that the entities
2615        // have distinct types.
2616        PrevDecl = 0;
2617      }
2618      // If we get here, we're going to create a new Decl. If PrevDecl
2619      // is non-NULL, it's a definition of the tag declared by
2620      // PrevDecl. If it's NULL, we have a new definition.
2621    } else {
2622      // PrevDecl is a namespace.
2623      if (isDeclInScope(PrevDecl, DC, S)) {
2624        // The tag name clashes with a namespace name, issue an error and
2625        // recover by making this tag be anonymous.
2626        Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2627        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2628        Name = 0;
2629        PrevDecl = 0;
2630      } else {
2631        // The existing declaration isn't relevant to us; we're in a
2632        // new scope, so clear out the previous declaration.
2633        PrevDecl = 0;
2634      }
2635    }
2636  }
2637
2638CreateNewDecl:
2639
2640  // If there is an identifier, use the location of the identifier as the
2641  // location of the decl, otherwise use the location of the struct/union
2642  // keyword.
2643  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2644
2645  // Otherwise, create a new declaration. If there is a previous
2646  // declaration of the same entity, the two will be linked via
2647  // PrevDecl.
2648  TagDecl *New;
2649  if (Kind == TagDecl::TK_enum) {
2650    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2651    // enum X { A, B, C } D;    D should chain to X.
2652    New = EnumDecl::Create(Context, DC, Loc, Name,
2653                           cast_or_null<EnumDecl>(PrevDecl));
2654    // If this is an undefined enum, warn.
2655    if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
2656  } else {
2657    // struct/union/class
2658
2659    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2660    // struct X { int A; } D;    D should chain to X.
2661    if (getLangOptions().CPlusPlus)
2662      // FIXME: Look for a way to use RecordDecl for simple structs.
2663      New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
2664                                  cast_or_null<CXXRecordDecl>(PrevDecl));
2665    else
2666      New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
2667                               cast_or_null<RecordDecl>(PrevDecl));
2668  }
2669
2670  if (Kind != TagDecl::TK_enum) {
2671    // Handle #pragma pack: if the #pragma pack stack has non-default
2672    // alignment, make up a packed attribute for this decl. These
2673    // attributes are checked when the ASTContext lays out the
2674    // structure.
2675    //
2676    // It is important for implementing the correct semantics that this
2677    // happen here (in act on tag decl). The #pragma pack stack is
2678    // maintained as a result of parser callbacks which can occur at
2679    // many points during the parsing of a struct declaration (because
2680    // the #pragma tokens are effectively skipped over during the
2681    // parsing of the struct).
2682    if (unsigned Alignment = PackContext.getAlignment())
2683      New->addAttr(new PackedAttr(Alignment * 8));
2684  }
2685
2686  if (Attr)
2687    ProcessDeclAttributeList(New, Attr);
2688
2689  // Set the lexical context. If the tag has a C++ scope specifier, the
2690  // lexical context will be different from the semantic context.
2691  New->setLexicalDeclContext(CurContext);
2692
2693  // If this has an identifier, add it to the scope stack.
2694  if (Name) {
2695    // The scope passed in may not be a decl scope.  Zip up the scope tree until
2696    // we find one that is.
2697    while ((S->getFlags() & Scope::DeclScope) == 0)
2698      S = S->getParent();
2699
2700    // Add it to the decl chain.
2701    PushOnScopeChains(New, S);
2702  }
2703
2704  return New;
2705}
2706
2707
2708/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2709/// types into constant array types in certain situations which would otherwise
2710/// be errors (for GCC compatibility).
2711static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2712                                                    ASTContext &Context) {
2713  // This method tries to turn a variable array into a constant
2714  // array even when the size isn't an ICE.  This is necessary
2715  // for compatibility with code that depends on gcc's buggy
2716  // constant expression folding, like struct {char x[(int)(char*)2];}
2717  const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2718  if (!VLATy) return QualType();
2719
2720  APValue Result;
2721  if (!VLATy->getSizeExpr() ||
2722      !VLATy->getSizeExpr()->Evaluate(Result, Context))
2723    return QualType();
2724
2725  assert(Result.isInt() && "Size expressions must be integers!");
2726  llvm::APSInt &Res = Result.getInt();
2727  if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2728    return Context.getConstantArrayType(VLATy->getElementType(),
2729                                        Res, ArrayType::Normal, 0);
2730  return QualType();
2731}
2732
2733bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
2734                          QualType FieldTy, const Expr *BitWidth) {
2735  // FIXME: 6.7.2.1p4 - verify the field type.
2736
2737  llvm::APSInt Value;
2738  if (VerifyIntegerConstantExpression(BitWidth, &Value))
2739    return true;
2740
2741  // Zero-width bitfield is ok for anonymous field.
2742  if (Value == 0 && FieldName)
2743    return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
2744
2745  if (Value.isNegative())
2746    return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
2747
2748  uint64_t TypeSize = Context.getTypeSize(FieldTy);
2749  // FIXME: We won't need the 0 size once we check that the field type is valid.
2750  if (TypeSize && Value.getZExtValue() > TypeSize)
2751    return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
2752       << FieldName << (unsigned)TypeSize;
2753
2754  return false;
2755}
2756
2757/// ActOnField - Each field of a struct/union/class is passed into this in order
2758/// to create a FieldDecl object for it.
2759Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
2760                               SourceLocation DeclStart,
2761                               Declarator &D, ExprTy *BitfieldWidth) {
2762  IdentifierInfo *II = D.getIdentifier();
2763  Expr *BitWidth = (Expr*)BitfieldWidth;
2764  SourceLocation Loc = DeclStart;
2765  RecordDecl *Record = (RecordDecl *)TagD;
2766  if (II) Loc = D.getIdentifierLoc();
2767
2768  // FIXME: Unnamed fields can be handled in various different ways, for
2769  // example, unnamed unions inject all members into the struct namespace!
2770
2771  QualType T = GetTypeForDeclarator(D, S);
2772  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2773  bool InvalidDecl = false;
2774
2775  // C99 6.7.2.1p8: A member of a structure or union may have any type other
2776  // than a variably modified type.
2777  if (T->isVariablyModifiedType()) {
2778    QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
2779    if (!FixedTy.isNull()) {
2780      Diag(Loc, diag::warn_illegal_constant_array_size);
2781      T = FixedTy;
2782    } else {
2783      Diag(Loc, diag::err_typecheck_field_variable_size);
2784      T = Context.IntTy;
2785      InvalidDecl = true;
2786    }
2787  }
2788
2789  if (BitWidth) {
2790    if (VerifyBitField(Loc, II, T, BitWidth))
2791      InvalidDecl = true;
2792  } else {
2793    // Not a bitfield.
2794
2795    // validate II.
2796
2797  }
2798
2799  // FIXME: Chain fielddecls together.
2800  FieldDecl *NewFD;
2801
2802  // FIXME: We don't want CurContext for C, do we? No, we'll need some
2803  // other way to determine the current RecordDecl.
2804  NewFD = FieldDecl::Create(Context, Record,
2805                            Loc, II, T, BitWidth,
2806                            D.getDeclSpec().getStorageClassSpec() ==
2807                              DeclSpec::SCS_mutable,
2808                            /*PrevDecl=*/0);
2809
2810  if (getLangOptions().CPlusPlus)
2811    CheckExtraCXXDefaultArguments(D);
2812
2813  ProcessDeclAttributes(NewFD, D);
2814
2815  if (D.getInvalidType() || InvalidDecl)
2816    NewFD->setInvalidDecl();
2817
2818  if (II && getLangOptions().CPlusPlus)
2819    PushOnScopeChains(NewFD, S);
2820  else
2821    Record->addDecl(Context, NewFD);
2822
2823  return NewFD;
2824}
2825
2826/// TranslateIvarVisibility - Translate visibility from a token ID to an
2827///  AST enum value.
2828static ObjCIvarDecl::AccessControl
2829TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
2830  switch (ivarVisibility) {
2831  default: assert(0 && "Unknown visitibility kind");
2832  case tok::objc_private: return ObjCIvarDecl::Private;
2833  case tok::objc_public: return ObjCIvarDecl::Public;
2834  case tok::objc_protected: return ObjCIvarDecl::Protected;
2835  case tok::objc_package: return ObjCIvarDecl::Package;
2836  }
2837}
2838
2839/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2840/// in order to create an IvarDecl object for it.
2841Sema::DeclTy *Sema::ActOnIvar(Scope *S,
2842                              SourceLocation DeclStart,
2843                              Declarator &D, ExprTy *BitfieldWidth,
2844                              tok::ObjCKeywordKind Visibility) {
2845  IdentifierInfo *II = D.getIdentifier();
2846  Expr *BitWidth = (Expr*)BitfieldWidth;
2847  SourceLocation Loc = DeclStart;
2848  if (II) Loc = D.getIdentifierLoc();
2849
2850  // FIXME: Unnamed fields can be handled in various different ways, for
2851  // example, unnamed unions inject all members into the struct namespace!
2852
2853  QualType T = GetTypeForDeclarator(D, S);
2854  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2855  bool InvalidDecl = false;
2856
2857  if (BitWidth) {
2858    // TODO: Validate.
2859    //printf("WARNING: BITFIELDS IGNORED!\n");
2860
2861    // 6.7.2.1p3
2862    // 6.7.2.1p4
2863
2864  } else {
2865    // Not a bitfield.
2866
2867    // validate II.
2868
2869  }
2870
2871  // C99 6.7.2.1p8: A member of a structure or union may have any type other
2872  // than a variably modified type.
2873  if (T->isVariablyModifiedType()) {
2874    Diag(Loc, diag::err_typecheck_ivar_variable_size);
2875    InvalidDecl = true;
2876  }
2877
2878  // Get the visibility (access control) for this ivar.
2879  ObjCIvarDecl::AccessControl ac =
2880    Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2881                                        : ObjCIvarDecl::None;
2882
2883  // Construct the decl.
2884  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
2885                                             (Expr *)BitfieldWidth);
2886
2887  // Process attributes attached to the ivar.
2888  ProcessDeclAttributes(NewID, D);
2889
2890  if (D.getInvalidType() || InvalidDecl)
2891    NewID->setInvalidDecl();
2892
2893  return NewID;
2894}
2895
2896void Sema::ActOnFields(Scope* S,
2897                       SourceLocation RecLoc, DeclTy *RecDecl,
2898                       DeclTy **Fields, unsigned NumFields,
2899                       SourceLocation LBrac, SourceLocation RBrac,
2900                       AttributeList *Attr) {
2901  Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2902  assert(EnclosingDecl && "missing record or interface decl");
2903  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2904
2905  if (Record)
2906    if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2907      // Diagnose code like:
2908      //     struct S { struct S {} X; };
2909      // We discover this when we complete the outer S.  Reject and ignore the
2910      // outer S.
2911      Diag(DefRecord->getLocation(), diag::err_nested_redefinition)
2912        << DefRecord->getDeclName();
2913      Diag(RecLoc, diag::note_previous_definition);
2914      Record->setInvalidDecl();
2915      return;
2916    }
2917
2918  // Verify that all the fields are okay.
2919  unsigned NumNamedMembers = 0;
2920  llvm::SmallVector<FieldDecl*, 32> RecFields;
2921  llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
2922
2923  for (unsigned i = 0; i != NumFields; ++i) {
2924
2925    FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2926    assert(FD && "missing field decl");
2927
2928    // Remember all fields.
2929    RecFields.push_back(FD);
2930
2931    // Get the type for the field.
2932    Type *FDTy = FD->getType().getTypePtr();
2933
2934    // C99 6.7.2.1p2 - A field may not be a function type.
2935    if (FDTy->isFunctionType()) {
2936      Diag(FD->getLocation(), diag::err_field_declared_as_function)
2937        << FD->getDeclName();
2938      FD->setInvalidDecl();
2939      EnclosingDecl->setInvalidDecl();
2940      continue;
2941    }
2942    // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2943    if (FDTy->isIncompleteType()) {
2944      if (!Record) {  // Incomplete ivar type is always an error.
2945        Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
2946        FD->setInvalidDecl();
2947        EnclosingDecl->setInvalidDecl();
2948        continue;
2949      }
2950      if (i != NumFields-1 ||                   // ... that the last member ...
2951          !Record->isStruct() ||  // ... of a structure ...
2952          !FDTy->isArrayType()) {         //... may have incomplete array type.
2953        Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
2954        FD->setInvalidDecl();
2955        EnclosingDecl->setInvalidDecl();
2956        continue;
2957      }
2958      if (NumNamedMembers < 1) {  //... must have more than named member ...
2959        Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
2960          << FD->getDeclName();
2961        FD->setInvalidDecl();
2962        EnclosingDecl->setInvalidDecl();
2963        continue;
2964      }
2965      // Okay, we have a legal flexible array member at the end of the struct.
2966      if (Record)
2967        Record->setHasFlexibleArrayMember(true);
2968    }
2969    /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2970    /// field of another structure or the element of an array.
2971    if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
2972      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2973        // If this is a member of a union, then entire union becomes "flexible".
2974        if (Record && Record->isUnion()) {
2975          Record->setHasFlexibleArrayMember(true);
2976        } else {
2977          // If this is a struct/class and this is not the last element, reject
2978          // it.  Note that GCC supports variable sized arrays in the middle of
2979          // structures.
2980          if (i != NumFields-1) {
2981            Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
2982              << FD->getDeclName();
2983            FD->setInvalidDecl();
2984            EnclosingDecl->setInvalidDecl();
2985            continue;
2986          }
2987          // We support flexible arrays at the end of structs in other structs
2988          // as an extension.
2989          Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
2990            << FD->getDeclName();
2991          if (Record)
2992            Record->setHasFlexibleArrayMember(true);
2993        }
2994      }
2995    }
2996    /// A field cannot be an Objective-c object
2997    if (FDTy->isObjCInterfaceType()) {
2998      Diag(FD->getLocation(), diag::err_statically_allocated_object)
2999        << FD->getDeclName();
3000      FD->setInvalidDecl();
3001      EnclosingDecl->setInvalidDecl();
3002      continue;
3003    }
3004    // Keep track of the number of named members.
3005    if (IdentifierInfo *II = FD->getIdentifier()) {
3006      // Detect duplicate member names.
3007      if (!FieldIDs.insert(II)) {
3008        Diag(FD->getLocation(), diag::err_duplicate_member) << II;
3009        // Find the previous decl.
3010        SourceLocation PrevLoc;
3011        for (unsigned i = 0; ; ++i) {
3012          assert(i != RecFields.size() && "Didn't find previous def!");
3013          if (RecFields[i]->getIdentifier() == II) {
3014            PrevLoc = RecFields[i]->getLocation();
3015            break;
3016          }
3017        }
3018        Diag(PrevLoc, diag::note_previous_definition);
3019        FD->setInvalidDecl();
3020        EnclosingDecl->setInvalidDecl();
3021        continue;
3022      }
3023      ++NumNamedMembers;
3024    }
3025  }
3026
3027  // Okay, we successfully defined 'Record'.
3028  if (Record) {
3029    Record->completeDefinition(Context);
3030    // If this is a C++ record, HandleTagDeclDefinition will be invoked in
3031    // Sema::ActOnFinishCXXClassDef.
3032    if (!isa<CXXRecordDecl>(Record))
3033      Consumer.HandleTagDeclDefinition(Record);
3034  } else {
3035    ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
3036    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
3037      ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
3038      // Must enforce the rule that ivars in the base classes may not be
3039      // duplicates.
3040      if (ID->getSuperClass()) {
3041        for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3042             IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3043          ObjCIvarDecl* Ivar = (*IVI);
3044          IdentifierInfo *II = Ivar->getIdentifier();
3045          ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3046          if (prevIvar) {
3047            Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3048            Diag(prevIvar->getLocation(), diag::note_previous_definition);
3049          }
3050        }
3051      }
3052    }
3053    else if (ObjCImplementationDecl *IMPDecl =
3054               dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
3055      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3056      IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
3057      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
3058    }
3059  }
3060
3061  if (Attr)
3062    ProcessDeclAttributeList(Record, Attr);
3063}
3064
3065Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
3066                                      DeclTy *lastEnumConst,
3067                                      SourceLocation IdLoc, IdentifierInfo *Id,
3068                                      SourceLocation EqualLoc, ExprTy *val) {
3069  EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
3070  EnumConstantDecl *LastEnumConst =
3071    cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3072  Expr *Val = static_cast<Expr*>(val);
3073
3074  // The scope passed in may not be a decl scope.  Zip up the scope tree until
3075  // we find one that is.
3076  while ((S->getFlags() & Scope::DeclScope) == 0)
3077    S = S->getParent();
3078
3079  // Verify that there isn't already something declared with this name in this
3080  // scope.
3081  Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S);
3082  if (PrevDecl && PrevDecl->isTemplateParameter()) {
3083    // Maybe we will complain about the shadowed template parameter.
3084    DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3085    // Just pretend that we didn't see the previous declaration.
3086    PrevDecl = 0;
3087  }
3088
3089  if (PrevDecl) {
3090    // When in C++, we may get a TagDecl with the same name; in this case the
3091    // enum constant will 'hide' the tag.
3092    assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3093           "Received TagDecl when not in C++!");
3094    if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
3095      if (isa<EnumConstantDecl>(PrevDecl))
3096        Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
3097      else
3098        Diag(IdLoc, diag::err_redefinition) << Id;
3099      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3100      delete Val;
3101      return 0;
3102    }
3103  }
3104
3105  llvm::APSInt EnumVal(32);
3106  QualType EltTy;
3107  if (Val) {
3108    // Make sure to promote the operand type to int.
3109    UsualUnaryConversions(Val);
3110
3111    // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3112    SourceLocation ExpLoc;
3113    if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
3114      delete Val;
3115      Val = 0;  // Just forget about it.
3116    } else {
3117      EltTy = Val->getType();
3118    }
3119  }
3120
3121  if (!Val) {
3122    if (LastEnumConst) {
3123      // Assign the last value + 1.
3124      EnumVal = LastEnumConst->getInitVal();
3125      ++EnumVal;
3126
3127      // Check for overflow on increment.
3128      if (EnumVal < LastEnumConst->getInitVal())
3129        Diag(IdLoc, diag::warn_enum_value_overflow);
3130
3131      EltTy = LastEnumConst->getType();
3132    } else {
3133      // First value, set to zero.
3134      EltTy = Context.IntTy;
3135      EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
3136    }
3137  }
3138
3139  EnumConstantDecl *New =
3140    EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
3141                             Val, EnumVal,
3142                             LastEnumConst);
3143
3144  // Register this decl in the current scope stack.
3145  PushOnScopeChains(New, S);
3146
3147  // Add this enumerator into the enum itself.
3148  // FIXME: This means that the enumerator is stored in two
3149  // DeclContexts. This is not a long-term solution.
3150  New->setLexicalDeclContext(TheEnumDecl);
3151  TheEnumDecl->addDecl(Context, New, true);
3152  return New;
3153}
3154
3155// FIXME: For consistency with ActOnFields(), we should have the parser
3156// pass in the source location for the left/right braces.
3157void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
3158                         DeclTy **Elements, unsigned NumElements) {
3159  EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
3160
3161  if (Enum) {
3162    if (EnumDecl *Def = cast_or_null<EnumDecl>(Enum->getDefinition(Context))) {
3163      // Diagnose code like:
3164      //   enum e0 {
3165      //     E0 = sizeof(enum e0 { E1 })
3166      //   };
3167      Diag(Def->getLocation(), diag::err_nested_redefinition)
3168        << Enum->getDeclName();
3169      Diag(Enum->getLocation(), diag::note_previous_definition);
3170      Enum->setInvalidDecl();
3171      return;
3172    }
3173  }
3174  // TODO: If the result value doesn't fit in an int, it must be a long or long
3175  // long value.  ISO C does not support this, but GCC does as an extension,
3176  // emit a warning.
3177  unsigned IntWidth = Context.Target.getIntWidth();
3178
3179  // Verify that all the values are okay, compute the size of the values, and
3180  // reverse the list.
3181  unsigned NumNegativeBits = 0;
3182  unsigned NumPositiveBits = 0;
3183
3184  // Keep track of whether all elements have type int.
3185  bool AllElementsInt = true;
3186
3187  QualType EnumType = Context.getTypeDeclType(Enum);
3188  EnumConstantDecl *EltList = 0;
3189  for (unsigned i = 0; i != NumElements; ++i) {
3190    EnumConstantDecl *ECD =
3191      cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3192    if (!ECD) continue;  // Already issued a diagnostic.
3193
3194    // If the enum value doesn't fit in an int, emit an extension warning.
3195    const llvm::APSInt &InitVal = ECD->getInitVal();
3196    assert(InitVal.getBitWidth() >= IntWidth &&
3197           "Should have promoted value to int");
3198    if (InitVal.getBitWidth() > IntWidth) {
3199      llvm::APSInt V(InitVal);
3200      V.trunc(IntWidth);
3201      V.extend(InitVal.getBitWidth());
3202      if (V != InitVal)
3203        Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3204          << InitVal.toString(10);
3205    }
3206
3207    // Keep track of the size of positive and negative values.
3208    if (InitVal.isUnsigned() || InitVal.isNonNegative())
3209      NumPositiveBits = std::max(NumPositiveBits,
3210                                 (unsigned)InitVal.getActiveBits());
3211    else
3212      NumNegativeBits = std::max(NumNegativeBits,
3213                                 (unsigned)InitVal.getMinSignedBits());
3214
3215    // Keep track of whether every enum element has type int (very commmon).
3216    if (AllElementsInt)
3217      AllElementsInt = ECD->getType() == Context.IntTy;
3218
3219    ECD->setNextDeclarator(EltList);
3220    EltList = ECD;
3221  }
3222
3223  // Figure out the type that should be used for this enum.
3224  // FIXME: Support attribute(packed) on enums and -fshort-enums.
3225  QualType BestType;
3226  unsigned BestWidth;
3227
3228  if (NumNegativeBits) {
3229    // If there is a negative value, figure out the smallest integer type (of
3230    // int/long/longlong) that fits.
3231    if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
3232      BestType = Context.IntTy;
3233      BestWidth = IntWidth;
3234    } else {
3235      BestWidth = Context.Target.getLongWidth();
3236
3237      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
3238        BestType = Context.LongTy;
3239      else {
3240        BestWidth = Context.Target.getLongLongWidth();
3241
3242        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
3243          Diag(Enum->getLocation(), diag::warn_enum_too_large);
3244        BestType = Context.LongLongTy;
3245      }
3246    }
3247  } else {
3248    // If there is no negative value, figure out which of uint, ulong, ulonglong
3249    // fits.
3250    if (NumPositiveBits <= IntWidth) {
3251      BestType = Context.UnsignedIntTy;
3252      BestWidth = IntWidth;
3253    } else if (NumPositiveBits <=
3254               (BestWidth = Context.Target.getLongWidth())) {
3255      BestType = Context.UnsignedLongTy;
3256    } else {
3257      BestWidth = Context.Target.getLongLongWidth();
3258      assert(NumPositiveBits <= BestWidth &&
3259             "How could an initializer get larger than ULL?");
3260      BestType = Context.UnsignedLongLongTy;
3261    }
3262  }
3263
3264  // Loop over all of the enumerator constants, changing their types to match
3265  // the type of the enum if needed.
3266  for (unsigned i = 0; i != NumElements; ++i) {
3267    EnumConstantDecl *ECD =
3268      cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3269    if (!ECD) continue;  // Already issued a diagnostic.
3270
3271    // Standard C says the enumerators have int type, but we allow, as an
3272    // extension, the enumerators to be larger than int size.  If each
3273    // enumerator value fits in an int, type it as an int, otherwise type it the
3274    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
3275    // that X has type 'int', not 'unsigned'.
3276    if (ECD->getType() == Context.IntTy) {
3277      // Make sure the init value is signed.
3278      llvm::APSInt IV = ECD->getInitVal();
3279      IV.setIsSigned(true);
3280      ECD->setInitVal(IV);
3281
3282      if (getLangOptions().CPlusPlus)
3283        // C++ [dcl.enum]p4: Following the closing brace of an
3284        // enum-specifier, each enumerator has the type of its
3285        // enumeration.
3286        ECD->setType(EnumType);
3287      continue;  // Already int type.
3288    }
3289
3290    // Determine whether the value fits into an int.
3291    llvm::APSInt InitVal = ECD->getInitVal();
3292    bool FitsInInt;
3293    if (InitVal.isUnsigned() || !InitVal.isNegative())
3294      FitsInInt = InitVal.getActiveBits() < IntWidth;
3295    else
3296      FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3297
3298    // If it fits into an integer type, force it.  Otherwise force it to match
3299    // the enum decl type.
3300    QualType NewTy;
3301    unsigned NewWidth;
3302    bool NewSign;
3303    if (FitsInInt) {
3304      NewTy = Context.IntTy;
3305      NewWidth = IntWidth;
3306      NewSign = true;
3307    } else if (ECD->getType() == BestType) {
3308      // Already the right type!
3309      if (getLangOptions().CPlusPlus)
3310        // C++ [dcl.enum]p4: Following the closing brace of an
3311        // enum-specifier, each enumerator has the type of its
3312        // enumeration.
3313        ECD->setType(EnumType);
3314      continue;
3315    } else {
3316      NewTy = BestType;
3317      NewWidth = BestWidth;
3318      NewSign = BestType->isSignedIntegerType();
3319    }
3320
3321    // Adjust the APSInt value.
3322    InitVal.extOrTrunc(NewWidth);
3323    InitVal.setIsSigned(NewSign);
3324    ECD->setInitVal(InitVal);
3325
3326    // Adjust the Expr initializer and type.
3327    ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3328                                          /*isLvalue=*/false));
3329    if (getLangOptions().CPlusPlus)
3330      // C++ [dcl.enum]p4: Following the closing brace of an
3331      // enum-specifier, each enumerator has the type of its
3332      // enumeration.
3333      ECD->setType(EnumType);
3334    else
3335      ECD->setType(NewTy);
3336  }
3337
3338  Enum->completeDefinition(Context, BestType);
3339  Consumer.HandleTagDeclDefinition(Enum);
3340}
3341
3342Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
3343                                          ExprArg expr) {
3344  StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3345
3346  return FileScopeAsmDecl::Create(Context, Loc, AsmString);
3347}
3348
3349
3350void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3351                           ExprTy *alignment, SourceLocation PragmaLoc,
3352                           SourceLocation LParenLoc, SourceLocation RParenLoc) {
3353  Expr *Alignment = static_cast<Expr *>(alignment);
3354
3355  // If specified then alignment must be a "small" power of two.
3356  unsigned AlignmentVal = 0;
3357  if (Alignment) {
3358    llvm::APSInt Val;
3359    if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3360        !Val.isPowerOf2() ||
3361        Val.getZExtValue() > 16) {
3362      Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3363      delete Alignment;
3364      return; // Ignore
3365    }
3366
3367    AlignmentVal = (unsigned) Val.getZExtValue();
3368  }
3369
3370  switch (Kind) {
3371  case Action::PPK_Default: // pack([n])
3372    PackContext.setAlignment(AlignmentVal);
3373    break;
3374
3375  case Action::PPK_Show: // pack(show)
3376    // Show the current alignment, making sure to show the right value
3377    // for the default.
3378    AlignmentVal = PackContext.getAlignment();
3379    // FIXME: This should come from the target.
3380    if (AlignmentVal == 0)
3381      AlignmentVal = 8;
3382    Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
3383    break;
3384
3385  case Action::PPK_Push: // pack(push [, id] [, [n])
3386    PackContext.push(Name);
3387    // Set the new alignment if specified.
3388    if (Alignment)
3389      PackContext.setAlignment(AlignmentVal);
3390    break;
3391
3392  case Action::PPK_Pop: // pack(pop [, id] [,  n])
3393    // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3394    // "#pragma pack(pop, identifier, n) is undefined"
3395    if (Alignment && Name)
3396      Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3397
3398    // Do the pop.
3399    if (!PackContext.pop(Name)) {
3400      // If a name was specified then failure indicates the name
3401      // wasn't found. Otherwise failure indicates the stack was
3402      // empty.
3403      Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3404        << (Name ? "no record matching name" : "stack empty");
3405
3406      // FIXME: Warn about popping named records as MSVC does.
3407    } else {
3408      // Pop succeeded, set the new alignment if specified.
3409      if (Alignment)
3410        PackContext.setAlignment(AlignmentVal);
3411    }
3412    break;
3413
3414  default:
3415    assert(0 && "Invalid #pragma pack kind.");
3416  }
3417}
3418
3419bool PragmaPackStack::pop(IdentifierInfo *Name) {
3420  if (Stack.empty())
3421    return false;
3422
3423  // If name is empty just pop top.
3424  if (!Name) {
3425    Alignment = Stack.back().first;
3426    Stack.pop_back();
3427    return true;
3428  }
3429
3430  // Otherwise, find the named record.
3431  for (unsigned i = Stack.size(); i != 0; ) {
3432    --i;
3433    if (Stack[i].second == Name) {
3434      // Found it, pop up to and including this record.
3435      Alignment = Stack[i].first;
3436      Stack.erase(Stack.begin() + i, Stack.end());
3437      return true;
3438    }
3439  }
3440
3441  return false;
3442}
3443