SemaDecl.cpp revision 2224f84658fb9b3725a31f2680edb64ae73bf705
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/DeclTemplate.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/Parse/DeclSpec.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#include <algorithm>
30#include <functional>
31using namespace clang;
32
33/// \brief If the identifier refers to a type name within this scope,
34/// return the declaration of that type.
35///
36/// This routine performs ordinary name lookup of the identifier II
37/// within the given scope, with optional C++ scope specifier SS, to
38/// determine whether the name refers to a type. If so, returns an
39/// opaque pointer (actually a QualType) corresponding to that
40/// type. Otherwise, returns NULL.
41///
42/// If name lookup results in an ambiguity, this routine will complain
43/// and then return NULL.
44Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
45                                Scope *S, const CXXScopeSpec *SS) {
46  NamedDecl *IIDecl = 0;
47  LookupResult Result = LookupParsedName(S, SS, &II, LookupOrdinaryName,
48                                         false, false);
49  switch (Result.getKind()) {
50  case LookupResult::NotFound:
51  case LookupResult::FoundOverloaded:
52    return 0;
53
54  case LookupResult::AmbiguousBaseSubobjectTypes:
55  case LookupResult::AmbiguousBaseSubobjects:
56  case LookupResult::AmbiguousReference:
57    DiagnoseAmbiguousLookup(Result, DeclarationName(&II), NameLoc);
58    return 0;
59
60  case LookupResult::Found:
61    IIDecl = Result.getAsDecl();
62    break;
63  }
64
65  if (IIDecl) {
66    if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
67      // Check whether we can use this type
68      (void)DiagnoseUseOfDecl(IIDecl, NameLoc);
69
70      return Context.getTypeDeclType(TD).getAsOpaquePtr();
71    }
72
73    if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
74      // Check whether we can use this interface.
75      (void)DiagnoseUseOfDecl(IIDecl, NameLoc);
76
77      return Context.getObjCInterfaceType(IDecl).getAsOpaquePtr();
78    }
79
80    // Otherwise, could be a variable, function etc.
81  }
82  return 0;
83}
84
85DeclContext *Sema::getContainingDC(DeclContext *DC) {
86  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
87    // A C++ out-of-line method will return to the file declaration context.
88    if (MD->isOutOfLineDefinition())
89      return MD->getLexicalDeclContext();
90
91    // A C++ inline method is parsed *after* the topmost class it was declared
92    // in is fully parsed (it's "complete").
93    // The parsing of a C++ inline method happens at the declaration context of
94    // the topmost (non-nested) class it is lexically declared in.
95    assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
96    DC = MD->getParent();
97    while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
98      DC = RD;
99
100    // Return the declaration context of the topmost class the inline method is
101    // declared in.
102    return DC;
103  }
104
105  if (isa<ObjCMethodDecl>(DC))
106    return Context.getTranslationUnitDecl();
107
108  return DC->getLexicalParent();
109}
110
111void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
112  assert(getContainingDC(DC) == CurContext &&
113      "The next DeclContext should be lexically contained in the current one.");
114  CurContext = DC;
115  S->setEntity(DC);
116}
117
118void Sema::PopDeclContext() {
119  assert(CurContext && "DeclContext imbalance!");
120
121  CurContext = getContainingDC(CurContext);
122}
123
124/// \brief Determine whether we allow overloading of the function
125/// PrevDecl with another declaration.
126///
127/// This routine determines whether overloading is possible, not
128/// whether some new function is actually an overload. It will return
129/// true in C++ (where we can always provide overloads) or, as an
130/// extension, in C when the previous function is already an
131/// overloaded function declaration or has the "overloadable"
132/// attribute.
133static bool AllowOverloadingOfFunction(Decl *PrevDecl, ASTContext &Context) {
134  if (Context.getLangOptions().CPlusPlus)
135    return true;
136
137  if (isa<OverloadedFunctionDecl>(PrevDecl))
138    return true;
139
140  return PrevDecl->getAttr<OverloadableAttr>() != 0;
141}
142
143/// Add this decl to the scope shadowed decl chains.
144void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
145  // Move up the scope chain until we find the nearest enclosing
146  // non-transparent context. The declaration will be introduced into this
147  // scope.
148  while (S->getEntity() &&
149         ((DeclContext *)S->getEntity())->isTransparentContext())
150    S = S->getParent();
151
152  S->AddDecl(D);
153
154  // Add scoped declarations into their context, so that they can be
155  // found later. Declarations without a context won't be inserted
156  // into any context.
157  CurContext->addDecl(D);
158
159  // C++ [basic.scope]p4:
160  //   -- exactly one declaration shall declare a class name or
161  //   enumeration name that is not a typedef name and the other
162  //   declarations shall all refer to the same object or
163  //   enumerator, or all refer to functions and function templates;
164  //   in this case the class name or enumeration name is hidden.
165  if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
166    // We are pushing the name of a tag (enum or class).
167    if (CurContext->getLookupContext()
168          == TD->getDeclContext()->getLookupContext()) {
169      // We're pushing the tag into the current context, which might
170      // require some reshuffling in the identifier resolver.
171      IdentifierResolver::iterator
172        I = IdResolver.begin(TD->getDeclName()),
173        IEnd = IdResolver.end();
174      if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
175        NamedDecl *PrevDecl = *I;
176        for (; I != IEnd && isDeclInScope(*I, CurContext, S);
177             PrevDecl = *I, ++I) {
178          if (TD->declarationReplaces(*I)) {
179            // This is a redeclaration. Remove it from the chain and
180            // break out, so that we'll add in the shadowed
181            // declaration.
182            S->RemoveDecl(*I);
183            if (PrevDecl == *I) {
184              IdResolver.RemoveDecl(*I);
185              IdResolver.AddDecl(TD);
186              return;
187            } else {
188              IdResolver.RemoveDecl(*I);
189              break;
190            }
191          }
192        }
193
194        // There is already a declaration with the same name in the same
195        // scope, which is not a tag declaration. It must be found
196        // before we find the new declaration, so insert the new
197        // declaration at the end of the chain.
198        IdResolver.AddShadowedDecl(TD, PrevDecl);
199
200        return;
201      }
202    }
203  } else if (isa<FunctionDecl>(D) &&
204             AllowOverloadingOfFunction(D, Context)) {
205    // We are pushing the name of a function, which might be an
206    // overloaded name.
207    FunctionDecl *FD = cast<FunctionDecl>(D);
208    IdentifierResolver::iterator Redecl
209      = std::find_if(IdResolver.begin(FD->getDeclName()),
210                     IdResolver.end(),
211                     std::bind1st(std::mem_fun(&NamedDecl::declarationReplaces),
212                                  FD));
213    if (Redecl != IdResolver.end() && S->isDeclScope(*Redecl)) {
214      // There is already a declaration of a function on our
215      // IdResolver chain. Replace it with this declaration.
216      S->RemoveDecl(*Redecl);
217      IdResolver.RemoveDecl(*Redecl);
218    }
219  }
220
221  IdResolver.AddDecl(D);
222}
223
224void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
225  if (S->decl_empty()) return;
226  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
227	 "Scope shouldn't contain decls!");
228
229  for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
230       I != E; ++I) {
231    Decl *TmpD = static_cast<Decl*>(*I);
232    assert(TmpD && "This decl didn't get pushed??");
233
234    assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
235    NamedDecl *D = cast<NamedDecl>(TmpD);
236
237    if (!D->getDeclName()) continue;
238
239    // Remove this name from our lexical scope.
240    IdResolver.RemoveDecl(D);
241  }
242}
243
244/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
245/// return 0 if one not found.
246ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
247  // The third "scope" argument is 0 since we aren't enabling lazy built-in
248  // creation from this context.
249  NamedDecl *IDecl = LookupName(TUScope, Id, LookupOrdinaryName);
250
251  return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
252}
253
254/// getNonFieldDeclScope - Retrieves the innermost scope, starting
255/// from S, where a non-field would be declared. This routine copes
256/// with the difference between C and C++ scoping rules in structs and
257/// unions. For example, the following code is well-formed in C but
258/// ill-formed in C++:
259/// @code
260/// struct S6 {
261///   enum { BAR } e;
262/// };
263///
264/// void test_S6() {
265///   struct S6 a;
266///   a.e = BAR;
267/// }
268/// @endcode
269/// For the declaration of BAR, this routine will return a different
270/// scope. The scope S will be the scope of the unnamed enumeration
271/// within S6. In C++, this routine will return the scope associated
272/// with S6, because the enumeration's scope is a transparent
273/// context but structures can contain non-field names. In C, this
274/// routine will return the translation unit scope, since the
275/// enumeration's scope is a transparent context and structures cannot
276/// contain non-field names.
277Scope *Sema::getNonFieldDeclScope(Scope *S) {
278  while (((S->getFlags() & Scope::DeclScope) == 0) ||
279         (S->getEntity() &&
280          ((DeclContext *)S->getEntity())->isTransparentContext()) ||
281         (S->isClassScope() && !getLangOptions().CPlusPlus))
282    S = S->getParent();
283  return S;
284}
285
286void Sema::InitBuiltinVaListType() {
287  if (!Context.getBuiltinVaListType().isNull())
288    return;
289
290  IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
291  NamedDecl *VaDecl = LookupName(TUScope, VaIdent, LookupOrdinaryName);
292  TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
293  Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
294}
295
296/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
297/// file scope.  lazily create a decl for it. ForRedeclaration is true
298/// if we're creating this built-in in anticipation of redeclaring the
299/// built-in.
300NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
301                                     Scope *S, bool ForRedeclaration,
302                                     SourceLocation Loc) {
303  Builtin::ID BID = (Builtin::ID)bid;
304
305  if (Context.BuiltinInfo.hasVAListUse(BID))
306    InitBuiltinVaListType();
307
308  Builtin::Context::GetBuiltinTypeError Error;
309  QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context, Error);
310  switch (Error) {
311  case Builtin::Context::GE_None:
312    // Okay
313    break;
314
315  case Builtin::Context::GE_Missing_FILE:
316    if (ForRedeclaration)
317      Diag(Loc, diag::err_implicit_decl_requires_stdio)
318        << Context.BuiltinInfo.GetName(BID);
319    return 0;
320  }
321
322  if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
323    Diag(Loc, diag::ext_implicit_lib_function_decl)
324      << Context.BuiltinInfo.GetName(BID)
325      << R;
326    if (Context.BuiltinInfo.getHeaderName(BID) &&
327        Diags.getDiagnosticMapping(diag::ext_implicit_lib_function_decl)
328          != diag::MAP_IGNORE)
329      Diag(Loc, diag::note_please_include_header)
330        << Context.BuiltinInfo.getHeaderName(BID)
331        << Context.BuiltinInfo.GetName(BID);
332  }
333
334  FunctionDecl *New = FunctionDecl::Create(Context,
335                                           Context.getTranslationUnitDecl(),
336                                           Loc, II, R,
337                                           FunctionDecl::Extern, false,
338                                           /*hasPrototype=*/true);
339  New->setImplicit();
340
341  // Create Decl objects for each parameter, adding them to the
342  // FunctionDecl.
343  if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
344    llvm::SmallVector<ParmVarDecl*, 16> Params;
345    for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
346      Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
347                                           FT->getArgType(i), VarDecl::None, 0));
348    New->setParams(Context, &Params[0], Params.size());
349  }
350
351  AddKnownFunctionAttributes(New);
352
353  // TUScope is the translation-unit scope to insert this function into.
354  // FIXME: This is hideous. We need to teach PushOnScopeChains to
355  // relate Scopes to DeclContexts, and probably eliminate CurContext
356  // entirely, but we're not there yet.
357  DeclContext *SavedContext = CurContext;
358  CurContext = Context.getTranslationUnitDecl();
359  PushOnScopeChains(New, TUScope);
360  CurContext = SavedContext;
361  return New;
362}
363
364/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
365/// everything from the standard library is defined.
366NamespaceDecl *Sema::GetStdNamespace() {
367  if (!StdNamespace) {
368    IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
369    DeclContext *Global = Context.getTranslationUnitDecl();
370    Decl *Std = LookupQualifiedName(Global, StdIdent, LookupNamespaceName);
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
377/// same name and scope as a previous declaration 'Old'.  Figure out
378/// how to resolve this situation, merging decls or emitting
379/// diagnostics as appropriate. Returns true if there was an error,
380/// false otherwise.
381///
382bool Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
383  bool objc_types = false;
384  // Allow multiple definitions for ObjC built-in typedefs.
385  // FIXME: Verify the underlying types are equivalent!
386  if (getLangOptions().ObjC1) {
387    const IdentifierInfo *TypeID = New->getIdentifier();
388    switch (TypeID->getLength()) {
389    default: break;
390    case 2:
391      if (!TypeID->isStr("id"))
392        break;
393      Context.setObjCIdType(New);
394      objc_types = true;
395      break;
396    case 5:
397      if (!TypeID->isStr("Class"))
398        break;
399      Context.setObjCClassType(New);
400      objc_types = true;
401      return false;
402    case 3:
403      if (!TypeID->isStr("SEL"))
404        break;
405      Context.setObjCSelType(New);
406      objc_types = true;
407      return false;
408    case 8:
409      if (!TypeID->isStr("Protocol"))
410        break;
411      Context.setObjCProtoType(New->getUnderlyingType());
412      objc_types = true;
413      return false;
414    }
415    // Fall through - the typedef name was not a builtin type.
416  }
417  // Verify the old decl was also a type.
418  TypeDecl *Old = dyn_cast<TypeDecl>(OldD);
419  if (!Old) {
420    Diag(New->getLocation(), diag::err_redefinition_different_kind)
421      << New->getDeclName();
422    if (!objc_types)
423      Diag(OldD->getLocation(), diag::note_previous_definition);
424    return true;
425  }
426
427  // Determine the "old" type we'll use for checking and diagnostics.
428  QualType OldType;
429  if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
430    OldType = OldTypedef->getUnderlyingType();
431  else
432    OldType = Context.getTypeDeclType(Old);
433
434  // If the typedef types are not identical, reject them in all languages and
435  // with any extensions enabled.
436
437  if (OldType != New->getUnderlyingType() &&
438      Context.getCanonicalType(OldType) !=
439      Context.getCanonicalType(New->getUnderlyingType())) {
440    Diag(New->getLocation(), diag::err_redefinition_different_typedef)
441      << New->getUnderlyingType() << OldType;
442    if (!objc_types)
443      Diag(Old->getLocation(), diag::note_previous_definition);
444    return true;
445  }
446  if (objc_types) return false;
447  if (getLangOptions().Microsoft) return false;
448
449  // C++ [dcl.typedef]p2:
450  //   In a given non-class scope, a typedef specifier can be used to
451  //   redefine the name of any type declared in that scope to refer
452  //   to the type to which it already refers.
453  if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
454    return false;
455
456  // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
457  // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
458  // *either* declaration is in a system header. The code below implements
459  // this adhoc compatibility rule. FIXME: The following code will not
460  // work properly when compiling ".i" files (containing preprocessed output).
461  if (PP.getDiagnostics().getSuppressSystemWarnings()) {
462    SourceManager &SrcMgr = Context.getSourceManager();
463    if (SrcMgr.isInSystemHeader(Old->getLocation()))
464      return false;
465    if (SrcMgr.isInSystemHeader(New->getLocation()))
466      return false;
467  }
468
469  Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
470  Diag(Old->getLocation(), diag::note_previous_definition);
471  return true;
472}
473
474/// DeclhasAttr - returns true if decl Declaration already has the target
475/// attribute.
476static bool DeclHasAttr(const Decl *decl, const Attr *target) {
477  for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
478    if (attr->getKind() == target->getKind())
479      return true;
480
481  return false;
482}
483
484/// MergeAttributes - append attributes from the Old decl to the New one.
485static void MergeAttributes(Decl *New, Decl *Old) {
486  Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
487
488  while (attr) {
489    tmp = attr;
490    attr = attr->getNext();
491
492    if (!DeclHasAttr(New, tmp) && tmp->isMerged()) {
493      tmp->setInherited(true);
494      New->addAttr(tmp);
495    } else {
496      tmp->setNext(0);
497      delete(tmp);
498    }
499  }
500
501  Old->invalidateAttrs();
502}
503
504/// MergeFunctionDecl - We just parsed a function 'New' from
505/// declarator D which has the same name and scope as a previous
506/// declaration 'Old'.  Figure out how to resolve this situation,
507/// merging decls or emitting diagnostics as appropriate.
508///
509/// In C++, New and Old must be declarations that are not
510/// overloaded. Use IsOverload to determine whether New and Old are
511/// overloaded, and to select the Old declaration that New should be
512/// merged with.
513///
514/// Returns true if there was an error, false otherwise.
515bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
516  assert(!isa<OverloadedFunctionDecl>(OldD) &&
517         "Cannot merge with an overloaded function declaration");
518
519  // Verify the old decl was also a function.
520  FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
521  if (!Old) {
522    Diag(New->getLocation(), diag::err_redefinition_different_kind)
523      << New->getDeclName();
524    Diag(OldD->getLocation(), diag::note_previous_definition);
525    return true;
526  }
527
528  // Determine whether the previous declaration was a definition,
529  // implicit declaration, or a declaration.
530  diag::kind PrevDiag;
531  if (Old->isThisDeclarationADefinition())
532    PrevDiag = diag::note_previous_definition;
533  else if (Old->isImplicit())
534    PrevDiag = diag::note_previous_implicit_declaration;
535  else
536    PrevDiag = diag::note_previous_declaration;
537
538  QualType OldQType = Context.getCanonicalType(Old->getType());
539  QualType NewQType = Context.getCanonicalType(New->getType());
540
541  if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
542      New->getStorageClass() == FunctionDecl::Static &&
543      Old->getStorageClass() != FunctionDecl::Static) {
544    Diag(New->getLocation(), diag::err_static_non_static)
545      << New;
546    Diag(Old->getLocation(), PrevDiag);
547    return true;
548  }
549
550  if (getLangOptions().CPlusPlus) {
551    // (C++98 13.1p2):
552    //   Certain function declarations cannot be overloaded:
553    //     -- Function declarations that differ only in the return type
554    //        cannot be overloaded.
555    QualType OldReturnType
556      = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
557    QualType NewReturnType
558      = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
559    if (OldReturnType != NewReturnType) {
560      Diag(New->getLocation(), diag::err_ovl_diff_return_type);
561      Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
562      return true;
563    }
564
565    const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
566    const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
567    if (OldMethod && NewMethod) {
568      //    -- Member function declarations with the same name and the
569      //       same parameter types cannot be overloaded if any of them
570      //       is a static member function declaration.
571      if (OldMethod->isStatic() || NewMethod->isStatic()) {
572        Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
573        Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
574        return true;
575      }
576
577      // C++ [class.mem]p1:
578      //   [...] A member shall not be declared twice in the
579      //   member-specification, except that a nested class or member
580      //   class template can be declared and then later defined.
581      if (OldMethod->getLexicalDeclContext() ==
582            NewMethod->getLexicalDeclContext()) {
583        unsigned NewDiag;
584        if (isa<CXXConstructorDecl>(OldMethod))
585          NewDiag = diag::err_constructor_redeclared;
586        else if (isa<CXXDestructorDecl>(NewMethod))
587          NewDiag = diag::err_destructor_redeclared;
588        else if (isa<CXXConversionDecl>(NewMethod))
589          NewDiag = diag::err_conv_function_redeclared;
590        else
591          NewDiag = diag::err_member_redeclared;
592
593        Diag(New->getLocation(), NewDiag);
594        Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
595      }
596    }
597
598    // (C++98 8.3.5p3):
599    //   All declarations for a function shall agree exactly in both the
600    //   return type and the parameter-type-list.
601    if (OldQType == NewQType)
602      return MergeCompatibleFunctionDecls(New, Old);
603
604    // Fall through for conflicting redeclarations and redefinitions.
605  }
606
607  // C: Function types need to be compatible, not identical. This handles
608  // duplicate function decls like "void f(int); void f(enum X);" properly.
609  if (!getLangOptions().CPlusPlus &&
610      Context.typesAreCompatible(OldQType, NewQType)) {
611    const FunctionType *NewFuncType = NewQType->getAsFunctionType();
612    const FunctionTypeProto *OldProto = 0;
613    if (isa<FunctionTypeNoProto>(NewFuncType) &&
614        (OldProto = OldQType->getAsFunctionTypeProto())) {
615      // The old declaration provided a function prototype, but the
616      // new declaration does not. Merge in the prototype.
617      llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
618                                                 OldProto->arg_type_end());
619      NewQType = Context.getFunctionType(NewFuncType->getResultType(),
620                                         &ParamTypes[0], ParamTypes.size(),
621                                         OldProto->isVariadic(),
622                                         OldProto->getTypeQuals());
623      New->setType(NewQType);
624      New->setInheritedPrototype();
625
626      // Synthesize a parameter for each argument type.
627      llvm::SmallVector<ParmVarDecl*, 16> Params;
628      for (FunctionTypeProto::arg_type_iterator
629             ParamType = OldProto->arg_type_begin(),
630             ParamEnd = OldProto->arg_type_end();
631           ParamType != ParamEnd; ++ParamType) {
632        ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
633                                                 SourceLocation(), 0,
634                                                 *ParamType, VarDecl::None,
635                                                 0);
636        Param->setImplicit();
637        Params.push_back(Param);
638      }
639
640      New->setParams(Context, &Params[0], Params.size());
641
642    }
643
644    return MergeCompatibleFunctionDecls(New, Old);
645  }
646
647  // A function that has already been declared has been redeclared or defined
648  // with a different type- show appropriate diagnostic
649  if (unsigned BuiltinID = Old->getBuiltinID(Context)) {
650    // The user has declared a builtin function with an incompatible
651    // signature.
652    if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
653      // The function the user is redeclaring is a library-defined
654      // function like 'malloc' or 'printf'. Warn about the
655      // redeclaration, then ignore it.
656      Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
657      Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
658        << Old << Old->getType();
659      return true;
660    }
661
662    PrevDiag = diag::note_previous_builtin_declaration;
663  }
664
665  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
666  Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
667  return true;
668}
669
670/// \brief Completes the merge of two function declarations that are
671/// known to be compatible.
672///
673/// This routine handles the merging of attributes and other
674/// properties of function declarations form the old declaration to
675/// the new declaration, once we know that New is in fact a
676/// redeclaration of Old.
677///
678/// \returns false
679bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
680  // Merge the attributes
681  MergeAttributes(New, Old);
682
683  // Merge the storage class.
684  New->setStorageClass(Old->getStorageClass());
685
686  // FIXME: need to implement inline semantics
687
688  // Merge "pure" flag.
689  if (Old->isPure())
690    New->setPure();
691
692  // Merge the "deleted" flag.
693  if (Old->isDeleted())
694    New->setDeleted();
695
696  if (getLangOptions().CPlusPlus)
697    return MergeCXXFunctionDecl(New, Old);
698
699  return false;
700}
701
702/// Predicate for C "tentative" external object definitions (C99 6.9.2).
703static bool isTentativeDefinition(VarDecl *VD) {
704  if (VD->isFileVarDecl())
705    return (!VD->getInit() &&
706            (VD->getStorageClass() == VarDecl::None ||
707             VD->getStorageClass() == VarDecl::Static));
708  return false;
709}
710
711/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
712/// when dealing with C "tentative" external object definitions (C99 6.9.2).
713void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
714  bool VDIsTentative = isTentativeDefinition(VD);
715  bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
716
717  // FIXME: I don't think this will actually see all of the
718  // redefinitions. Can't we check this property on-the-fly?
719  for (IdentifierResolver::iterator I = IdResolver.begin(VD->getIdentifier()),
720                                    E = IdResolver.end();
721       I != E; ++I) {
722    if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
723      VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
724
725      // Handle the following case:
726      //   int a[10];
727      //   int a[];   - the code below makes sure we set the correct type.
728      //   int a[11]; - this is an error, size isn't 10.
729      if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
730          OldDecl->getType()->isConstantArrayType())
731        VD->setType(OldDecl->getType());
732
733      // Check for "tentative" definitions. We can't accomplish this in
734      // MergeVarDecl since the initializer hasn't been attached.
735      if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
736        continue;
737
738      // Handle __private_extern__ just like extern.
739      if (OldDecl->getStorageClass() != VarDecl::Extern &&
740          OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
741          VD->getStorageClass() != VarDecl::Extern &&
742          VD->getStorageClass() != VarDecl::PrivateExtern) {
743        Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
744        Diag(OldDecl->getLocation(), diag::note_previous_definition);
745        // One redefinition error is enough.
746        break;
747      }
748    }
749  }
750}
751
752/// MergeVarDecl - We just parsed a variable 'New' which has the same name
753/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
754/// situation, merging decls or emitting diagnostics as appropriate.
755///
756/// Tentative definition rules (C99 6.9.2p2) are checked by
757/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
758/// definitions here, since the initializer hasn't been attached.
759///
760bool Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
761  // Verify the old decl was also a variable.
762  VarDecl *Old = dyn_cast<VarDecl>(OldD);
763  if (!Old) {
764    Diag(New->getLocation(), diag::err_redefinition_different_kind)
765      << New->getDeclName();
766    Diag(OldD->getLocation(), diag::note_previous_definition);
767    return true;
768  }
769
770  MergeAttributes(New, Old);
771
772  // Merge the types
773  QualType MergedT = Context.mergeTypes(New->getType(), Old->getType());
774  if (MergedT.isNull()) {
775    Diag(New->getLocation(), diag::err_redefinition_different_type)
776      << New->getDeclName();
777    Diag(Old->getLocation(), diag::note_previous_definition);
778    return true;
779  }
780  New->setType(MergedT);
781  // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
782  if (New->getStorageClass() == VarDecl::Static &&
783      (Old->getStorageClass() == VarDecl::None ||
784       Old->getStorageClass() == VarDecl::Extern)) {
785    Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
786    Diag(Old->getLocation(), diag::note_previous_definition);
787    return true;
788  }
789  // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
790  if (New->getStorageClass() != VarDecl::Static &&
791      Old->getStorageClass() == VarDecl::Static) {
792    Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
793    Diag(Old->getLocation(), diag::note_previous_definition);
794    return true;
795  }
796  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
797  if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
798    Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
799    Diag(Old->getLocation(), diag::note_previous_definition);
800    return true;
801  }
802  return false;
803}
804
805/// CheckParmsForFunctionDef - Check that the parameters of the given
806/// function are appropriate for the definition of a function. This
807/// takes care of any checks that cannot be performed on the
808/// declaration itself, e.g., that the types of each of the function
809/// parameters are complete.
810bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
811  bool HasInvalidParm = false;
812  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
813    ParmVarDecl *Param = FD->getParamDecl(p);
814
815    // C99 6.7.5.3p4: the parameters in a parameter type list in a
816    // function declarator that is part of a function definition of
817    // that function shall not have incomplete type.
818    if (!Param->isInvalidDecl() &&
819        DiagnoseIncompleteType(Param->getLocation(), Param->getType(),
820                               diag::err_typecheck_decl_incomplete_type)) {
821      Param->setInvalidDecl();
822      HasInvalidParm = true;
823    }
824
825    // C99 6.9.1p5: If the declarator includes a parameter type list, the
826    // declaration of each parameter shall include an identifier.
827    if (Param->getIdentifier() == 0 &&
828        !Param->isImplicit() &&
829        !getLangOptions().CPlusPlus)
830      Diag(Param->getLocation(), diag::err_parameter_name_omitted);
831  }
832
833  return HasInvalidParm;
834}
835
836/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
837/// no declarator (e.g. "struct foo;") is parsed.
838Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
839  TagDecl *Tag = 0;
840  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
841      DS.getTypeSpecType() == DeclSpec::TST_struct ||
842      DS.getTypeSpecType() == DeclSpec::TST_union ||
843      DS.getTypeSpecType() == DeclSpec::TST_enum)
844    Tag = dyn_cast<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
845
846  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
847    if (!Record->getDeclName() && Record->isDefinition() &&
848        DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
849      return BuildAnonymousStructOrUnion(S, DS, Record);
850
851    // Microsoft allows unnamed struct/union fields. Don't complain
852    // about them.
853    // FIXME: Should we support Microsoft's extensions in this area?
854    if (Record->getDeclName() && getLangOptions().Microsoft)
855      return Tag;
856  }
857
858  if (!DS.isMissingDeclaratorOk() &&
859      DS.getTypeSpecType() != DeclSpec::TST_error) {
860    // Warn about typedefs of enums without names, since this is an
861    // extension in both Microsoft an GNU.
862    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
863        Tag && isa<EnumDecl>(Tag)) {
864      Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
865        << DS.getSourceRange();
866      return Tag;
867    }
868
869    Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
870      << DS.getSourceRange();
871    return 0;
872  }
873
874  return Tag;
875}
876
877/// InjectAnonymousStructOrUnionMembers - Inject the members of the
878/// anonymous struct or union AnonRecord into the owning context Owner
879/// and scope S. This routine will be invoked just after we realize
880/// that an unnamed union or struct is actually an anonymous union or
881/// struct, e.g.,
882///
883/// @code
884/// union {
885///   int i;
886///   float f;
887/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
888///    // f into the surrounding scope.x
889/// @endcode
890///
891/// This routine is recursive, injecting the names of nested anonymous
892/// structs/unions into the owning context and scope as well.
893bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
894                                               RecordDecl *AnonRecord) {
895  bool Invalid = false;
896  for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
897                               FEnd = AnonRecord->field_end();
898       F != FEnd; ++F) {
899    if ((*F)->getDeclName()) {
900      NamedDecl *PrevDecl = LookupQualifiedName(Owner, (*F)->getDeclName(),
901                                                LookupOrdinaryName, true);
902      if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
903        // C++ [class.union]p2:
904        //   The names of the members of an anonymous union shall be
905        //   distinct from the names of any other entity in the
906        //   scope in which the anonymous union is declared.
907        unsigned diagKind
908          = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
909                                 : diag::err_anonymous_struct_member_redecl;
910        Diag((*F)->getLocation(), diagKind)
911          << (*F)->getDeclName();
912        Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
913        Invalid = true;
914      } else {
915        // C++ [class.union]p2:
916        //   For the purpose of name lookup, after the anonymous union
917        //   definition, the members of the anonymous union are
918        //   considered to have been defined in the scope in which the
919        //   anonymous union is declared.
920        Owner->makeDeclVisibleInContext(*F);
921        S->AddDecl(*F);
922        IdResolver.AddDecl(*F);
923      }
924    } else if (const RecordType *InnerRecordType
925                 = (*F)->getType()->getAsRecordType()) {
926      RecordDecl *InnerRecord = InnerRecordType->getDecl();
927      if (InnerRecord->isAnonymousStructOrUnion())
928        Invalid = Invalid ||
929          InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
930    }
931  }
932
933  return Invalid;
934}
935
936/// ActOnAnonymousStructOrUnion - Handle the declaration of an
937/// anonymous structure or union. Anonymous unions are a C++ feature
938/// (C++ [class.union]) and a GNU C extension; anonymous structures
939/// are a GNU C and GNU C++ extension.
940Sema::DeclTy *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
941                                                RecordDecl *Record) {
942  DeclContext *Owner = Record->getDeclContext();
943
944  // Diagnose whether this anonymous struct/union is an extension.
945  if (Record->isUnion() && !getLangOptions().CPlusPlus)
946    Diag(Record->getLocation(), diag::ext_anonymous_union);
947  else if (!Record->isUnion())
948    Diag(Record->getLocation(), diag::ext_anonymous_struct);
949
950  // C and C++ require different kinds of checks for anonymous
951  // structs/unions.
952  bool Invalid = false;
953  if (getLangOptions().CPlusPlus) {
954    const char* PrevSpec = 0;
955    // C++ [class.union]p3:
956    //   Anonymous unions declared in a named namespace or in the
957    //   global namespace shall be declared static.
958    if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
959        (isa<TranslationUnitDecl>(Owner) ||
960         (isa<NamespaceDecl>(Owner) &&
961          cast<NamespaceDecl>(Owner)->getDeclName()))) {
962      Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
963      Invalid = true;
964
965      // Recover by adding 'static'.
966      DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
967    }
968    // C++ [class.union]p3:
969    //   A storage class is not allowed in a declaration of an
970    //   anonymous union in a class scope.
971    else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
972             isa<RecordDecl>(Owner)) {
973      Diag(DS.getStorageClassSpecLoc(),
974           diag::err_anonymous_union_with_storage_spec);
975      Invalid = true;
976
977      // Recover by removing the storage specifier.
978      DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
979                             PrevSpec);
980    }
981
982    // C++ [class.union]p2:
983    //   The member-specification of an anonymous union shall only
984    //   define non-static data members. [Note: nested types and
985    //   functions cannot be declared within an anonymous union. ]
986    for (DeclContext::decl_iterator Mem = Record->decls_begin(),
987                                 MemEnd = Record->decls_end();
988         Mem != MemEnd; ++Mem) {
989      if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
990        // C++ [class.union]p3:
991        //   An anonymous union shall not have private or protected
992        //   members (clause 11).
993        if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
994          Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
995            << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
996          Invalid = true;
997        }
998      } else if ((*Mem)->isImplicit()) {
999        // Any implicit members are fine.
1000      } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
1001        // This is a type that showed up in an
1002        // elaborated-type-specifier inside the anonymous struct or
1003        // union, but which actually declares a type outside of the
1004        // anonymous struct or union. It's okay.
1005      } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
1006        if (!MemRecord->isAnonymousStructOrUnion() &&
1007            MemRecord->getDeclName()) {
1008          // This is a nested type declaration.
1009          Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
1010            << (int)Record->isUnion();
1011          Invalid = true;
1012        }
1013      } else {
1014        // We have something that isn't a non-static data
1015        // member. Complain about it.
1016        unsigned DK = diag::err_anonymous_record_bad_member;
1017        if (isa<TypeDecl>(*Mem))
1018          DK = diag::err_anonymous_record_with_type;
1019        else if (isa<FunctionDecl>(*Mem))
1020          DK = diag::err_anonymous_record_with_function;
1021        else if (isa<VarDecl>(*Mem))
1022          DK = diag::err_anonymous_record_with_static;
1023        Diag((*Mem)->getLocation(), DK)
1024            << (int)Record->isUnion();
1025          Invalid = true;
1026      }
1027    }
1028  } else {
1029    // FIXME: Check GNU C semantics
1030    if (Record->isUnion() && !Owner->isRecord()) {
1031      Diag(Record->getLocation(), diag::err_anonymous_union_not_member)
1032        << (int)getLangOptions().CPlusPlus;
1033      Invalid = true;
1034    }
1035  }
1036
1037  if (!Record->isUnion() && !Owner->isRecord()) {
1038    Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
1039      << (int)getLangOptions().CPlusPlus;
1040    Invalid = true;
1041  }
1042
1043  // Create a declaration for this anonymous struct/union.
1044  NamedDecl *Anon = 0;
1045  if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
1046    Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
1047                             /*IdentifierInfo=*/0,
1048                             Context.getTypeDeclType(Record),
1049                             /*BitWidth=*/0, /*Mutable=*/false);
1050    Anon->setAccess(AS_public);
1051    if (getLangOptions().CPlusPlus)
1052      FieldCollector->Add(cast<FieldDecl>(Anon));
1053  } else {
1054    VarDecl::StorageClass SC;
1055    switch (DS.getStorageClassSpec()) {
1056    default: assert(0 && "Unknown storage class!");
1057    case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
1058    case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
1059    case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
1060    case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
1061    case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
1062    case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1063    case DeclSpec::SCS_mutable:
1064      // mutable can only appear on non-static class members, so it's always
1065      // an error here
1066      Diag(Record->getLocation(), diag::err_mutable_nonmember);
1067      Invalid = true;
1068      SC = VarDecl::None;
1069      break;
1070    }
1071
1072    Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
1073                           /*IdentifierInfo=*/0,
1074                           Context.getTypeDeclType(Record),
1075                           SC, DS.getSourceRange().getBegin());
1076  }
1077  Anon->setImplicit();
1078
1079  // Add the anonymous struct/union object to the current
1080  // context. We'll be referencing this object when we refer to one of
1081  // its members.
1082  Owner->addDecl(Anon);
1083
1084  // Inject the members of the anonymous struct/union into the owning
1085  // context and into the identifier resolver chain for name lookup
1086  // purposes.
1087  if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
1088    Invalid = true;
1089
1090  // Mark this as an anonymous struct/union type. Note that we do not
1091  // do this until after we have already checked and injected the
1092  // members of this anonymous struct/union type, because otherwise
1093  // the members could be injected twice: once by DeclContext when it
1094  // builds its lookup table, and once by
1095  // InjectAnonymousStructOrUnionMembers.
1096  Record->setAnonymousStructOrUnion(true);
1097
1098  if (Invalid)
1099    Anon->setInvalidDecl();
1100
1101  return Anon;
1102}
1103
1104
1105/// GetNameForDeclarator - Determine the full declaration name for the
1106/// given Declarator.
1107DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1108  switch (D.getKind()) {
1109  case Declarator::DK_Abstract:
1110    assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1111    return DeclarationName();
1112
1113  case Declarator::DK_Normal:
1114    assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1115    return DeclarationName(D.getIdentifier());
1116
1117  case Declarator::DK_Constructor: {
1118    QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1119    Ty = Context.getCanonicalType(Ty);
1120    return Context.DeclarationNames.getCXXConstructorName(Ty);
1121  }
1122
1123  case Declarator::DK_Destructor: {
1124    QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1125    Ty = Context.getCanonicalType(Ty);
1126    return Context.DeclarationNames.getCXXDestructorName(Ty);
1127  }
1128
1129  case Declarator::DK_Conversion: {
1130    // FIXME: We'd like to keep the non-canonical type for diagnostics!
1131    QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1132    Ty = Context.getCanonicalType(Ty);
1133    return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1134  }
1135
1136  case Declarator::DK_Operator:
1137    assert(D.getIdentifier() == 0 && "operator names have no identifier");
1138    return Context.DeclarationNames.getCXXOperatorName(
1139                                                D.getOverloadedOperator());
1140  }
1141
1142  assert(false && "Unknown name kind");
1143  return DeclarationName();
1144}
1145
1146/// isNearlyMatchingFunction - Determine whether the C++ functions
1147/// Declaration and Definition are "nearly" matching. This heuristic
1148/// is used to improve diagnostics in the case where an out-of-line
1149/// function definition doesn't match any declaration within
1150/// the class or namespace.
1151static bool isNearlyMatchingFunction(ASTContext &Context,
1152                                     FunctionDecl *Declaration,
1153                                     FunctionDecl *Definition) {
1154  if (Declaration->param_size() != Definition->param_size())
1155    return false;
1156  for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1157    QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1158    QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1159
1160    DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1161    DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1162    if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1163      return false;
1164  }
1165
1166  return true;
1167}
1168
1169Sema::DeclTy *
1170Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1171                      bool IsFunctionDefinition) {
1172  NamedDecl *LastDeclarator = dyn_cast_or_null<NamedDecl>((Decl *)lastDecl);
1173  DeclarationName Name = GetNameForDeclarator(D);
1174
1175  // All of these full declarators require an identifier.  If it doesn't have
1176  // one, the ParsedFreeStandingDeclSpec action should be used.
1177  if (!Name) {
1178    if (!D.getInvalidType())  // Reject this if we think it is valid.
1179      Diag(D.getDeclSpec().getSourceRange().getBegin(),
1180           diag::err_declarator_need_ident)
1181        << D.getDeclSpec().getSourceRange() << D.getSourceRange();
1182    return 0;
1183  }
1184
1185  // The scope passed in may not be a decl scope.  Zip up the scope tree until
1186  // we find one that is.
1187  while ((S->getFlags() & Scope::DeclScope) == 0 ||
1188         (S->getFlags() & Scope::TemplateParamScope) != 0)
1189    S = S->getParent();
1190
1191  DeclContext *DC;
1192  NamedDecl *PrevDecl;
1193  NamedDecl *New;
1194  bool InvalidDecl = false;
1195
1196  QualType R = GetTypeForDeclarator(D, S);
1197  if (R.isNull()) {
1198    InvalidDecl = true;
1199    R = Context.IntTy;
1200  }
1201
1202  // See if this is a redefinition of a variable in the same scope.
1203  if (!D.getCXXScopeSpec().isSet() && !D.getCXXScopeSpec().isInvalid()) {
1204    LookupNameKind NameKind = LookupOrdinaryName;
1205
1206    // If the declaration we're planning to build will be a function
1207    // or object with linkage, then look for another declaration with
1208    // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
1209    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1210      /* Do nothing*/;
1211    else if (R->isFunctionType()) {
1212      if (CurContext->isFunctionOrMethod())
1213        NameKind = LookupRedeclarationWithLinkage;
1214    } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
1215      NameKind = LookupRedeclarationWithLinkage;
1216
1217    DC = CurContext;
1218    PrevDecl = LookupName(S, Name, NameKind, true,
1219                          D.getDeclSpec().getStorageClassSpec() !=
1220                            DeclSpec::SCS_static,
1221                          D.getIdentifierLoc());
1222  } else { // Something like "int foo::x;"
1223    DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
1224    PrevDecl = LookupQualifiedName(DC, Name, LookupOrdinaryName, true);
1225
1226    // C++ 7.3.1.2p2:
1227    // Members (including explicit specializations of templates) of a named
1228    // namespace can also be defined outside that namespace by explicit
1229    // qualification of the name being defined, provided that the entity being
1230    // defined was already declared in the namespace and the definition appears
1231    // after the point of declaration in a namespace that encloses the
1232    // declarations namespace.
1233    //
1234    // Note that we only check the context at this point. We don't yet
1235    // have enough information to make sure that PrevDecl is actually
1236    // the declaration we want to match. For example, given:
1237    //
1238    //   class X {
1239    //     void f();
1240    //     void f(float);
1241    //   };
1242    //
1243    //   void X::f(int) { } // ill-formed
1244    //
1245    // In this case, PrevDecl will point to the overload set
1246    // containing the two f's declared in X, but neither of them
1247    // matches.
1248
1249    // First check whether we named the global scope.
1250    if (isa<TranslationUnitDecl>(DC)) {
1251      Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
1252        << Name << D.getCXXScopeSpec().getRange();
1253    } else if (!CurContext->Encloses(DC)) {
1254      // The qualifying scope doesn't enclose the original declaration.
1255      // Emit diagnostic based on current scope.
1256      SourceLocation L = D.getIdentifierLoc();
1257      SourceRange R = D.getCXXScopeSpec().getRange();
1258      if (isa<FunctionDecl>(CurContext))
1259        Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
1260      else
1261        Diag(L, diag::err_invalid_declarator_scope)
1262          << Name << cast<NamedDecl>(DC) << R;
1263      InvalidDecl = true;
1264    }
1265  }
1266
1267  if (PrevDecl && PrevDecl->isTemplateParameter()) {
1268    // Maybe we will complain about the shadowed template parameter.
1269    InvalidDecl = InvalidDecl
1270      || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
1271    // Just pretend that we didn't see the previous declaration.
1272    PrevDecl = 0;
1273  }
1274
1275  // In C++, the previous declaration we find might be a tag type
1276  // (class or enum). In this case, the new declaration will hide the
1277  // tag type. Note that this does does not apply if we're declaring a
1278  // typedef (C++ [dcl.typedef]p4).
1279  if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag &&
1280      D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
1281    PrevDecl = 0;
1282
1283  bool Redeclaration = false;
1284  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
1285    New = ActOnTypedefDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1286                                 InvalidDecl, Redeclaration);
1287  } else if (R->isFunctionType()) {
1288    New = ActOnFunctionDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1289                                  IsFunctionDefinition, InvalidDecl,
1290                                  Redeclaration);
1291  } else {
1292    New = ActOnVariableDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1293                                  InvalidDecl, Redeclaration);
1294  }
1295
1296  if (New == 0)
1297    return 0;
1298
1299  // Set the lexical context. If the declarator has a C++ scope specifier, the
1300  // lexical context will be different from the semantic context.
1301  New->setLexicalDeclContext(CurContext);
1302
1303  // If this has an identifier and is not an invalid redeclaration,
1304  // add it to the scope stack.
1305  if (Name && !(Redeclaration && InvalidDecl))
1306    PushOnScopeChains(New, S);
1307  // If any semantic error occurred, mark the decl as invalid.
1308  if (D.getInvalidType() || InvalidDecl)
1309    New->setInvalidDecl();
1310
1311  return New;
1312}
1313
1314/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
1315/// types into constant array types in certain situations which would otherwise
1316/// be errors (for GCC compatibility).
1317static QualType TryToFixInvalidVariablyModifiedType(QualType T,
1318                                                    ASTContext &Context,
1319                                                    bool &SizeIsNegative) {
1320  // This method tries to turn a variable array into a constant
1321  // array even when the size isn't an ICE.  This is necessary
1322  // for compatibility with code that depends on gcc's buggy
1323  // constant expression folding, like struct {char x[(int)(char*)2];}
1324  SizeIsNegative = false;
1325
1326  if (const PointerType* PTy = dyn_cast<PointerType>(T)) {
1327    QualType Pointee = PTy->getPointeeType();
1328    QualType FixedType =
1329        TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative);
1330    if (FixedType.isNull()) return FixedType;
1331    FixedType = Context.getPointerType(FixedType);
1332    FixedType.setCVRQualifiers(T.getCVRQualifiers());
1333    return FixedType;
1334  }
1335
1336  const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
1337  if (!VLATy) return QualType();
1338
1339  Expr::EvalResult EvalResult;
1340  if (!VLATy->getSizeExpr() ||
1341      !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
1342    return QualType();
1343
1344  assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
1345  llvm::APSInt &Res = EvalResult.Val.getInt();
1346  if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
1347    return Context.getConstantArrayType(VLATy->getElementType(),
1348                                        Res, ArrayType::Normal, 0);
1349
1350  SizeIsNegative = true;
1351  return QualType();
1352}
1353
1354NamedDecl*
1355Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1356                             QualType R, Decl* LastDeclarator,
1357                             Decl* PrevDecl, bool& InvalidDecl,
1358                             bool &Redeclaration) {
1359  // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1360  if (D.getCXXScopeSpec().isSet()) {
1361    Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1362      << D.getCXXScopeSpec().getRange();
1363    InvalidDecl = true;
1364    // Pretend we didn't see the scope specifier.
1365    DC = 0;
1366  }
1367
1368  // Check that there are no default arguments (C++ only).
1369  if (getLangOptions().CPlusPlus)
1370    CheckExtraCXXDefaultArguments(D);
1371
1372  TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
1373  if (!NewTD) return 0;
1374
1375  // Handle attributes prior to checking for duplicates in MergeVarDecl
1376  ProcessDeclAttributes(NewTD, D);
1377  // Merge the decl with the existing one if appropriate. If the decl is
1378  // in an outer scope, it isn't the same thing.
1379  if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1380    Redeclaration = true;
1381    if (MergeTypeDefDecl(NewTD, PrevDecl))
1382      InvalidDecl = true;
1383  }
1384
1385  if (S->getFnParent() == 0) {
1386    QualType T = NewTD->getUnderlyingType();
1387    // C99 6.7.7p2: If a typedef name specifies a variably modified type
1388    // then it shall have block scope.
1389    if (T->isVariablyModifiedType()) {
1390      bool SizeIsNegative;
1391      QualType FixedTy =
1392          TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
1393      if (!FixedTy.isNull()) {
1394        Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size);
1395        NewTD->setUnderlyingType(FixedTy);
1396      } else {
1397        if (SizeIsNegative)
1398          Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size);
1399        else if (T->isVariableArrayType())
1400          Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1401        else
1402          Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1403        InvalidDecl = true;
1404      }
1405    }
1406  }
1407  return NewTD;
1408}
1409
1410/// \brief Determines whether the given declaration is an out-of-scope
1411/// previous declaration.
1412///
1413/// This routine should be invoked when name lookup has found a
1414/// previous declaration (PrevDecl) that is not in the scope where a
1415/// new declaration by the same name is being introduced. If the new
1416/// declaration occurs in a local scope, previous declarations with
1417/// linkage may still be considered previous declarations (C99
1418/// 6.2.2p4-5, C++ [basic.link]p6).
1419///
1420/// \param PrevDecl the previous declaration found by name
1421/// lookup
1422///
1423/// \param DC the context in which the new declaration is being
1424/// declared.
1425///
1426/// \returns true if PrevDecl is an out-of-scope previous declaration
1427/// for a new delcaration with the same name.
1428static bool
1429isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
1430                                ASTContext &Context) {
1431  if (!PrevDecl)
1432    return 0;
1433
1434  // FIXME: PrevDecl could be an OverloadedFunctionDecl, in which
1435  // case we need to check each of the overloaded functions.
1436  if (!PrevDecl->hasLinkage())
1437    return false;
1438
1439  if (Context.getLangOptions().CPlusPlus) {
1440    // C++ [basic.link]p6:
1441    //   If there is a visible declaration of an entity with linkage
1442    //   having the same name and type, ignoring entities declared
1443    //   outside the innermost enclosing namespace scope, the block
1444    //   scope declaration declares that same entity and receives the
1445    //   linkage of the previous declaration.
1446    DeclContext *OuterContext = DC->getLookupContext();
1447    if (!OuterContext->isFunctionOrMethod())
1448      // This rule only applies to block-scope declarations.
1449      return false;
1450    else {
1451      DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
1452      if (PrevOuterContext->isRecord())
1453        // We found a member function: ignore it.
1454        return false;
1455      else {
1456        // Find the innermost enclosing namespace for the new and
1457        // previous declarations.
1458        while (!OuterContext->isFileContext())
1459          OuterContext = OuterContext->getParent();
1460        while (!PrevOuterContext->isFileContext())
1461          PrevOuterContext = PrevOuterContext->getParent();
1462
1463        // The previous declaration is in a different namespace, so it
1464        // isn't the same function.
1465        if (OuterContext->getPrimaryContext() !=
1466            PrevOuterContext->getPrimaryContext())
1467          return false;
1468      }
1469    }
1470  }
1471
1472  return true;
1473}
1474
1475/// \brief Inject a locally-scoped declaration with external linkage
1476/// into the appropriate namespace scope.
1477///
1478/// Given a declaration of an entity with linkage that occurs within a
1479/// local scope, this routine inject that declaration into top-level
1480/// scope so that it will be visible for later uses and declarations
1481/// of the same entity.
1482void Sema::InjectLocallyScopedExternalDeclaration(ValueDecl *VD) {
1483  // FIXME: We don't do this in C++ because, although we would like
1484  // to get the extra checking that this operation implies,
1485  // the declaration itself is not visible according to C++'s rules.
1486  assert(!getLangOptions().CPlusPlus &&
1487         "Can't inject locally-scoped declarations in C++");
1488  IdentifierResolver::iterator I = IdResolver.begin(VD->getDeclName()),
1489                            IEnd = IdResolver.end();
1490  NamedDecl *PrevDecl = 0;
1491  while (I != IEnd && !isa<TranslationUnitDecl>((*I)->getDeclContext())) {
1492    PrevDecl = *I;
1493    ++I;
1494  }
1495
1496  if (I == IEnd) {
1497    // No name with this identifier has been declared at translation
1498    // unit scope. Add this name into the appropriate scope.
1499    if (PrevDecl)
1500      IdResolver.AddShadowedDecl(VD, PrevDecl);
1501    else
1502      IdResolver.AddDecl(VD);
1503    TUScope->AddDecl(VD);
1504    return;
1505  }
1506
1507  if (isa<TagDecl>(*I)) {
1508    // The first thing we found was a tag declaration, so insert
1509    // this function so that it will be found before the tag
1510    // declaration.
1511    if (PrevDecl)
1512      IdResolver.AddShadowedDecl(VD, PrevDecl);
1513    else
1514      IdResolver.AddDecl(VD);
1515    TUScope->AddDecl(VD);
1516    return;
1517  }
1518
1519  if (VD->declarationReplaces(*I)) {
1520    // We found a previous declaration of the same entity. Replace
1521    // that declaration with this one.
1522    TUScope->RemoveDecl(*I);
1523    TUScope->AddDecl(VD);
1524    IdResolver.RemoveDecl(*I);
1525    if (PrevDecl)
1526      IdResolver.AddShadowedDecl(VD, PrevDecl);
1527    else
1528      IdResolver.AddDecl(VD);
1529  }
1530}
1531
1532NamedDecl*
1533Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1534                              QualType R, Decl* LastDeclarator,
1535                              NamedDecl* PrevDecl, bool& InvalidDecl,
1536                              bool &Redeclaration) {
1537  DeclarationName Name = GetNameForDeclarator(D);
1538
1539  // Check that there are no default arguments (C++ only).
1540  if (getLangOptions().CPlusPlus)
1541    CheckExtraCXXDefaultArguments(D);
1542
1543  if (R.getTypePtr()->isObjCInterfaceType()) {
1544    Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object);
1545    InvalidDecl = true;
1546  }
1547
1548  VarDecl *NewVD;
1549  VarDecl::StorageClass SC;
1550  switch (D.getDeclSpec().getStorageClassSpec()) {
1551  default: assert(0 && "Unknown storage class!");
1552  case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
1553  case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
1554  case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
1555  case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
1556  case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
1557  case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1558  case DeclSpec::SCS_mutable:
1559    // mutable can only appear on non-static class members, so it's always
1560    // an error here
1561    Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1562    InvalidDecl = true;
1563    SC = VarDecl::None;
1564    break;
1565  }
1566
1567  IdentifierInfo *II = Name.getAsIdentifierInfo();
1568  if (!II) {
1569    Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1570      << Name.getAsString();
1571    return 0;
1572  }
1573
1574  if (DC->isRecord()) {
1575    // This is a static data member for a C++ class.
1576    NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
1577                                    D.getIdentifierLoc(), II,
1578                                    R);
1579  } else {
1580    bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
1581    if (S->getFnParent() == 0) {
1582      // C99 6.9p2: The storage-class specifiers auto and register shall not
1583      // appear in the declaration specifiers in an external declaration.
1584      if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1585        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
1586        InvalidDecl = true;
1587      }
1588    }
1589    NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1590                            II, R, SC,
1591                            // FIXME: Move to DeclGroup...
1592                            D.getDeclSpec().getSourceRange().getBegin());
1593    NewVD->setThreadSpecified(ThreadSpecified);
1594  }
1595  NewVD->setNextDeclarator(LastDeclarator);
1596
1597  // Handle attributes prior to checking for duplicates in MergeVarDecl
1598  ProcessDeclAttributes(NewVD, D);
1599
1600  // Handle GNU asm-label extension (encoded as an attribute).
1601  if (Expr *E = (Expr*) D.getAsmLabel()) {
1602    // The parser guarantees this is a string.
1603    StringLiteral *SE = cast<StringLiteral>(E);
1604    NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1605                                                SE->getByteLength())));
1606  }
1607
1608  // Emit an error if an address space was applied to decl with local storage.
1609  // This includes arrays of objects with address space qualifiers, but not
1610  // automatic variables that point to other address spaces.
1611  // ISO/IEC TR 18037 S5.1.2
1612  if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1613    Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1614    InvalidDecl = true;
1615  }
1616
1617  if (NewVD->hasLocalStorage() && NewVD->getType().isObjCGCWeak()) {
1618    Diag(D.getIdentifierLoc(), diag::warn_attribute_weak_on_local);
1619  }
1620
1621  // If name lookup finds a previous declaration that is not in the
1622  // same scope as the new declaration, this may still be an
1623  // acceptable redeclaration.
1624  if (PrevDecl && !isDeclInScope(PrevDecl, DC, S) &&
1625      !(NewVD->hasLinkage() &&
1626        isOutOfScopePreviousDeclaration(PrevDecl, DC, Context)))
1627    PrevDecl = 0;
1628
1629  // Merge the decl with the existing one if appropriate.
1630  if (PrevDecl) {
1631    if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1632      // The user tried to define a non-static data member
1633      // out-of-line (C++ [dcl.meaning]p1).
1634      Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1635        << D.getCXXScopeSpec().getRange();
1636      NewVD->Destroy(Context);
1637      return 0;
1638    }
1639
1640    Redeclaration = true;
1641    if (MergeVarDecl(NewVD, PrevDecl))
1642      InvalidDecl = true;
1643
1644    if (D.getCXXScopeSpec().isSet()) {
1645      // No previous declaration in the qualifying scope.
1646      Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1647        << Name << D.getCXXScopeSpec().getRange();
1648      InvalidDecl = true;
1649    }
1650  }
1651
1652  // If this is a locally-scoped extern variable in C, inject a
1653  // declaration into translation unit scope so that all external
1654  // declarations are visible.
1655  if (!getLangOptions().CPlusPlus && CurContext->isFunctionOrMethod() &&
1656      NewVD->hasLinkage())
1657    InjectLocallyScopedExternalDeclaration(NewVD);
1658
1659  return NewVD;
1660}
1661
1662NamedDecl*
1663Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1664                              QualType R, Decl *LastDeclarator,
1665                              NamedDecl* PrevDecl, bool IsFunctionDefinition,
1666                              bool& InvalidDecl, bool &Redeclaration) {
1667  assert(R.getTypePtr()->isFunctionType());
1668
1669  DeclarationName Name = GetNameForDeclarator(D);
1670  FunctionDecl::StorageClass SC = FunctionDecl::None;
1671  switch (D.getDeclSpec().getStorageClassSpec()) {
1672  default: assert(0 && "Unknown storage class!");
1673  case DeclSpec::SCS_auto:
1674  case DeclSpec::SCS_register:
1675  case DeclSpec::SCS_mutable:
1676    Diag(D.getDeclSpec().getStorageClassSpecLoc(),
1677         diag::err_typecheck_sclass_func);
1678    InvalidDecl = true;
1679    break;
1680  case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1681  case DeclSpec::SCS_extern:      SC = FunctionDecl::Extern; break;
1682  case DeclSpec::SCS_static: {
1683    if (DC->getLookupContext()->isFunctionOrMethod()) {
1684      // C99 6.7.1p5:
1685      //   The declaration of an identifier for a function that has
1686      //   block scope shall have no explicit storage-class specifier
1687      //   other than extern
1688      // See also (C++ [dcl.stc]p4).
1689      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
1690           diag::err_static_block_func);
1691      SC = FunctionDecl::None;
1692    } else
1693      SC = FunctionDecl::Static;
1694    break;
1695  }
1696  case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
1697  }
1698
1699  bool isInline = D.getDeclSpec().isInlineSpecified();
1700  // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1701  bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1702
1703  FunctionDecl *NewFD;
1704  if (D.getKind() == Declarator::DK_Constructor) {
1705    // This is a C++ constructor declaration.
1706    assert(DC->isRecord() &&
1707           "Constructors can only be declared in a member context");
1708
1709    InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
1710
1711    // Create the new declaration
1712    NewFD = CXXConstructorDecl::Create(Context,
1713                                       cast<CXXRecordDecl>(DC),
1714                                       D.getIdentifierLoc(), Name, R,
1715                                       isExplicit, isInline,
1716                                       /*isImplicitlyDeclared=*/false);
1717
1718    if (InvalidDecl)
1719      NewFD->setInvalidDecl();
1720  } else if (D.getKind() == Declarator::DK_Destructor) {
1721    // This is a C++ destructor declaration.
1722    if (DC->isRecord()) {
1723      InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
1724
1725      NewFD = CXXDestructorDecl::Create(Context,
1726                                        cast<CXXRecordDecl>(DC),
1727                                        D.getIdentifierLoc(), Name, R,
1728                                        isInline,
1729                                        /*isImplicitlyDeclared=*/false);
1730
1731      if (InvalidDecl)
1732        NewFD->setInvalidDecl();
1733    } else {
1734      Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1735
1736      // Create a FunctionDecl to satisfy the function definition parsing
1737      // code path.
1738      NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
1739                                   Name, R, SC, isInline,
1740                                   /*hasPrototype=*/true,
1741                                   // FIXME: Move to DeclGroup...
1742                                   D.getDeclSpec().getSourceRange().getBegin());
1743      InvalidDecl = true;
1744      NewFD->setInvalidDecl();
1745    }
1746  } else if (D.getKind() == Declarator::DK_Conversion) {
1747    if (!DC->isRecord()) {
1748      Diag(D.getIdentifierLoc(),
1749           diag::err_conv_function_not_member);
1750      return 0;
1751    } else {
1752      InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
1753
1754      NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
1755                                        D.getIdentifierLoc(), Name, R,
1756                                        isInline, isExplicit);
1757
1758      if (InvalidDecl)
1759        NewFD->setInvalidDecl();
1760    }
1761  } else if (DC->isRecord()) {
1762    // This is a C++ method declaration.
1763    NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
1764                                  D.getIdentifierLoc(), Name, R,
1765                                  (SC == FunctionDecl::Static), isInline);
1766  } else {
1767    NewFD = FunctionDecl::Create(Context, DC,
1768                                 D.getIdentifierLoc(),
1769                                 Name, R, SC, isInline,
1770                                 /*hasPrototype=*/
1771                                   (getLangOptions().CPlusPlus ||
1772                                    (D.getNumTypeObjects() &&
1773                                     D.getTypeObject(0).Fun.hasPrototype)),
1774                                 // FIXME: Move to DeclGroup...
1775                                 D.getDeclSpec().getSourceRange().getBegin());
1776  }
1777  NewFD->setNextDeclarator(LastDeclarator);
1778
1779  // Set the lexical context. If the declarator has a C++
1780  // scope specifier, the lexical context will be different
1781  // from the semantic context.
1782  NewFD->setLexicalDeclContext(CurContext);
1783
1784  // Handle GNU asm-label extension (encoded as an attribute).
1785  if (Expr *E = (Expr*) D.getAsmLabel()) {
1786    // The parser guarantees this is a string.
1787    StringLiteral *SE = cast<StringLiteral>(E);
1788    NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1789                                                SE->getByteLength())));
1790  }
1791
1792  // Copy the parameter declarations from the declarator D to
1793  // the function declaration NewFD, if they are available.
1794  if (D.getNumTypeObjects() > 0) {
1795    DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1796
1797    // Create Decl objects for each parameter, adding them to the
1798    // FunctionDecl.
1799    llvm::SmallVector<ParmVarDecl*, 16> Params;
1800
1801    // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1802    // function that takes no arguments, not a function that takes a
1803    // single void argument.
1804    // We let through "const void" here because Sema::GetTypeForDeclarator
1805    // already checks for that case.
1806    if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1807        FTI.ArgInfo[0].Param &&
1808        ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1809      // empty arg list, don't push any params.
1810      ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1811
1812      // In C++, the empty parameter-type-list must be spelled "void"; a
1813      // typedef of void is not permitted.
1814      if (getLangOptions().CPlusPlus &&
1815          Param->getType().getUnqualifiedType() != Context.VoidTy) {
1816        Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1817      }
1818    } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
1819      for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1820        Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1821    }
1822
1823    NewFD->setParams(Context, &Params[0], Params.size());
1824  } else if (R->getAsTypedefType()) {
1825    // When we're declaring a function with a typedef, as in the
1826    // following example, we'll need to synthesize (unnamed)
1827    // parameters for use in the declaration.
1828    //
1829    // @code
1830    // typedef void fn(int);
1831    // fn f;
1832    // @endcode
1833    const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1834    if (!FT) {
1835      // This is a typedef of a function with no prototype, so we
1836      // don't need to do anything.
1837    } else if ((FT->getNumArgs() == 0) ||
1838               (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1839                FT->getArgType(0)->isVoidType())) {
1840      // This is a zero-argument function. We don't need to do anything.
1841    } else {
1842      // Synthesize a parameter for each argument type.
1843      llvm::SmallVector<ParmVarDecl*, 16> Params;
1844      for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1845           ArgType != FT->arg_type_end(); ++ArgType) {
1846        ParmVarDecl *Param = ParmVarDecl::Create(Context, DC,
1847                                                 SourceLocation(), 0,
1848                                                 *ArgType, VarDecl::None,
1849                                                 0);
1850        Param->setImplicit();
1851        Params.push_back(Param);
1852      }
1853
1854      NewFD->setParams(Context, &Params[0], Params.size());
1855    }
1856  }
1857
1858  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1859    InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
1860  else if (isa<CXXDestructorDecl>(NewFD)) {
1861    CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1862    Record->setUserDeclaredDestructor(true);
1863    // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1864    // user-defined destructor.
1865    Record->setPOD(false);
1866  } else if (CXXConversionDecl *Conversion =
1867             dyn_cast<CXXConversionDecl>(NewFD))
1868    ActOnConversionDeclarator(Conversion);
1869
1870  // Extra checking for C++ overloaded operators (C++ [over.oper]).
1871  if (NewFD->isOverloadedOperator() &&
1872      CheckOverloadedOperatorDeclaration(NewFD))
1873    NewFD->setInvalidDecl();
1874
1875  // If name lookup finds a previous declaration that is not in the
1876  // same scope as the new declaration, this may still be an
1877  // acceptable redeclaration.
1878  if (PrevDecl && !isDeclInScope(PrevDecl, DC, S) &&
1879      !(NewFD->hasLinkage() &&
1880        isOutOfScopePreviousDeclaration(PrevDecl, DC, Context)))
1881    PrevDecl = 0;
1882
1883  // Merge or overload the declaration with an existing declaration of
1884  // the same name, if appropriate.
1885  bool OverloadableAttrRequired = false;
1886  if (PrevDecl) {
1887    // Determine whether NewFD is an overload of PrevDecl or
1888    // a declaration that requires merging. If it's an overload,
1889    // there's no more work to do here; we'll just add the new
1890    // function to the scope.
1891    OverloadedFunctionDecl::function_iterator MatchedDecl;
1892
1893    if (!getLangOptions().CPlusPlus &&
1894        AllowOverloadingOfFunction(PrevDecl, Context)) {
1895      OverloadableAttrRequired = true;
1896
1897      // Functions marked "overloadable" must have a prototype (that
1898      // we can't get through declaration merging).
1899      if (!R->getAsFunctionTypeProto()) {
1900        Diag(NewFD->getLocation(), diag::err_attribute_overloadable_no_prototype)
1901          << NewFD;
1902        InvalidDecl = true;
1903        Redeclaration = true;
1904
1905        // Turn this into a variadic function with no parameters.
1906        R = Context.getFunctionType(R->getAsFunctionType()->getResultType(),
1907                                    0, 0, true, 0);
1908        NewFD->setType(R);
1909      }
1910    }
1911
1912    if (PrevDecl &&
1913        (!AllowOverloadingOfFunction(PrevDecl, Context) ||
1914         !IsOverload(NewFD, PrevDecl, MatchedDecl))) {
1915      Redeclaration = true;
1916      Decl *OldDecl = PrevDecl;
1917
1918      // If PrevDecl was an overloaded function, extract the
1919      // FunctionDecl that matched.
1920      if (isa<OverloadedFunctionDecl>(PrevDecl))
1921        OldDecl = *MatchedDecl;
1922
1923      // NewFD and PrevDecl represent declarations that need to be
1924      // merged.
1925      if (MergeFunctionDecl(NewFD, OldDecl))
1926        InvalidDecl = true;
1927
1928      if (!InvalidDecl) {
1929        NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1930
1931        // An out-of-line member function declaration must also be a
1932        // definition (C++ [dcl.meaning]p1).
1933        if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1934            !InvalidDecl) {
1935          Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1936            << D.getCXXScopeSpec().getRange();
1937          NewFD->setInvalidDecl();
1938        }
1939      }
1940    }
1941  }
1942
1943  if (D.getCXXScopeSpec().isSet() &&
1944      (!PrevDecl || !Redeclaration)) {
1945    // The user tried to provide an out-of-line definition for a
1946    // function that is a member of a class or namespace, but there
1947    // was no such member function declared (C++ [class.mfct]p2,
1948    // C++ [namespace.memdef]p2). For example:
1949    //
1950    // class X {
1951    //   void f() const;
1952    // };
1953    //
1954    // void X::f() { } // ill-formed
1955    //
1956    // Complain about this problem, and attempt to suggest close
1957    // matches (e.g., those that differ only in cv-qualifiers and
1958    // whether the parameter types are references).
1959    Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1960      << cast<NamedDecl>(DC) << D.getCXXScopeSpec().getRange();
1961    InvalidDecl = true;
1962
1963    LookupResult Prev = LookupQualifiedName(DC, Name, LookupOrdinaryName,
1964                                            true);
1965    assert(!Prev.isAmbiguous() &&
1966           "Cannot have an ambiguity in previous-declaration lookup");
1967    for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
1968         Func != FuncEnd; ++Func) {
1969      if (isa<FunctionDecl>(*Func) &&
1970          isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD))
1971        Diag((*Func)->getLocation(), diag::note_member_def_close_match);
1972    }
1973
1974    PrevDecl = 0;
1975  }
1976
1977  // Handle attributes. We need to have merged decls when handling attributes
1978  // (for example to check for conflicts, etc).
1979  ProcessDeclAttributes(NewFD, D);
1980  AddKnownFunctionAttributes(NewFD);
1981
1982  if (OverloadableAttrRequired && !NewFD->getAttr<OverloadableAttr>()) {
1983    // If a function name is overloadable in C, then every function
1984    // with that name must be marked "overloadable".
1985    Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
1986      << Redeclaration << NewFD;
1987    if (PrevDecl)
1988      Diag(PrevDecl->getLocation(),
1989           diag::note_attribute_overloadable_prev_overload);
1990    NewFD->addAttr(new OverloadableAttr);
1991  }
1992
1993  if (getLangOptions().CPlusPlus) {
1994    // In C++, check default arguments now that we have merged decls. Unless
1995    // the lexical context is the class, because in this case this is done
1996    // during delayed parsing anyway.
1997    if (!CurContext->isRecord())
1998      CheckCXXDefaultArguments(NewFD);
1999
2000    // An out-of-line member function declaration must also be a
2001    // definition (C++ [dcl.meaning]p1).
2002    if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
2003      Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
2004        << D.getCXXScopeSpec().getRange();
2005      InvalidDecl = true;
2006    }
2007  }
2008
2009  // If this is a locally-scoped function in C, inject a declaration
2010  // into translation unit scope so that all external declarations are
2011  // visible.
2012  if (!getLangOptions().CPlusPlus && CurContext->isFunctionOrMethod())
2013    InjectLocallyScopedExternalDeclaration(NewFD);
2014
2015  return NewFD;
2016}
2017
2018void Sema::InitializerElementNotConstant(const Expr *Init) {
2019  Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
2020    << Init->getSourceRange();
2021}
2022
2023bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
2024  switch (Init->getStmtClass()) {
2025  default:
2026    InitializerElementNotConstant(Init);
2027    return true;
2028  case Expr::ParenExprClass: {
2029    const ParenExpr* PE = cast<ParenExpr>(Init);
2030    return CheckAddressConstantExpressionLValue(PE->getSubExpr());
2031  }
2032  case Expr::CompoundLiteralExprClass:
2033    return cast<CompoundLiteralExpr>(Init)->isFileScope();
2034  case Expr::DeclRefExprClass:
2035  case Expr::QualifiedDeclRefExprClass: {
2036    const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
2037    if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2038      if (VD->hasGlobalStorage())
2039        return false;
2040      InitializerElementNotConstant(Init);
2041      return true;
2042    }
2043    if (isa<FunctionDecl>(D))
2044      return false;
2045    InitializerElementNotConstant(Init);
2046    return true;
2047  }
2048  case Expr::MemberExprClass: {
2049    const MemberExpr *M = cast<MemberExpr>(Init);
2050    if (M->isArrow())
2051      return CheckAddressConstantExpression(M->getBase());
2052    return CheckAddressConstantExpressionLValue(M->getBase());
2053  }
2054  case Expr::ArraySubscriptExprClass: {
2055    // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
2056    const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
2057    return CheckAddressConstantExpression(ASE->getBase()) ||
2058           CheckArithmeticConstantExpression(ASE->getIdx());
2059  }
2060  case Expr::StringLiteralClass:
2061  case Expr::ObjCEncodeExprClass:
2062  case Expr::PredefinedExprClass:
2063    return false;
2064  case Expr::UnaryOperatorClass: {
2065    const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2066
2067    // C99 6.6p9
2068    if (Exp->getOpcode() == UnaryOperator::Deref)
2069      return CheckAddressConstantExpression(Exp->getSubExpr());
2070
2071    InitializerElementNotConstant(Init);
2072    return true;
2073  }
2074  }
2075}
2076
2077bool Sema::CheckAddressConstantExpression(const Expr* Init) {
2078  switch (Init->getStmtClass()) {
2079  default:
2080    InitializerElementNotConstant(Init);
2081    return true;
2082  case Expr::ParenExprClass:
2083    return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
2084  case Expr::StringLiteralClass:
2085  case Expr::ObjCEncodeExprClass:
2086  case Expr::ObjCStringLiteralClass:
2087    return false;
2088  case Expr::CallExprClass:
2089  case Expr::CXXOperatorCallExprClass:
2090    // __builtin___CFStringMakeConstantString is a valid constant l-value.
2091    if (cast<CallExpr>(Init)->isBuiltinCall(Context) ==
2092           Builtin::BI__builtin___CFStringMakeConstantString)
2093      return false;
2094
2095    InitializerElementNotConstant(Init);
2096    return true;
2097
2098  case Expr::UnaryOperatorClass: {
2099    const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2100
2101    // C99 6.6p9
2102    if (Exp->getOpcode() == UnaryOperator::AddrOf)
2103      return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
2104
2105    if (Exp->getOpcode() == UnaryOperator::Extension)
2106      return CheckAddressConstantExpression(Exp->getSubExpr());
2107
2108    InitializerElementNotConstant(Init);
2109    return true;
2110  }
2111  case Expr::BinaryOperatorClass: {
2112    // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
2113    const BinaryOperator *Exp = cast<BinaryOperator>(Init);
2114
2115    Expr *PExp = Exp->getLHS();
2116    Expr *IExp = Exp->getRHS();
2117    if (IExp->getType()->isPointerType())
2118      std::swap(PExp, IExp);
2119
2120    // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
2121    return CheckAddressConstantExpression(PExp) ||
2122           CheckArithmeticConstantExpression(IExp);
2123  }
2124  case Expr::ImplicitCastExprClass:
2125  case Expr::CStyleCastExprClass: {
2126    const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
2127    if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
2128      // Check for implicit promotion
2129      if (SubExpr->getType()->isFunctionType() ||
2130          SubExpr->getType()->isArrayType())
2131        return CheckAddressConstantExpressionLValue(SubExpr);
2132    }
2133
2134    // Check for pointer->pointer cast
2135    if (SubExpr->getType()->isPointerType())
2136      return CheckAddressConstantExpression(SubExpr);
2137
2138    if (SubExpr->getType()->isIntegralType()) {
2139      // Check for the special-case of a pointer->int->pointer cast;
2140      // this isn't standard, but some code requires it. See
2141      // PR2720 for an example.
2142      if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
2143        if (SubCast->getSubExpr()->getType()->isPointerType()) {
2144          unsigned IntWidth = Context.getIntWidth(SubCast->getType());
2145          unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2146          if (IntWidth >= PointerWidth) {
2147            return CheckAddressConstantExpression(SubCast->getSubExpr());
2148          }
2149        }
2150      }
2151    }
2152    if (SubExpr->getType()->isArithmeticType()) {
2153      return CheckArithmeticConstantExpression(SubExpr);
2154    }
2155
2156    InitializerElementNotConstant(Init);
2157    return true;
2158  }
2159  case Expr::ConditionalOperatorClass: {
2160    // FIXME: Should we pedwarn here?
2161    const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
2162    if (!Exp->getCond()->getType()->isArithmeticType()) {
2163      InitializerElementNotConstant(Init);
2164      return true;
2165    }
2166    if (CheckArithmeticConstantExpression(Exp->getCond()))
2167      return true;
2168    if (Exp->getLHS() &&
2169        CheckAddressConstantExpression(Exp->getLHS()))
2170      return true;
2171    return CheckAddressConstantExpression(Exp->getRHS());
2172  }
2173  case Expr::AddrLabelExprClass:
2174    return false;
2175  }
2176}
2177
2178static const Expr* FindExpressionBaseAddress(const Expr* E);
2179
2180static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
2181  switch (E->getStmtClass()) {
2182  default:
2183    return E;
2184  case Expr::ParenExprClass: {
2185    const ParenExpr* PE = cast<ParenExpr>(E);
2186    return FindExpressionBaseAddressLValue(PE->getSubExpr());
2187  }
2188  case Expr::MemberExprClass: {
2189    const MemberExpr *M = cast<MemberExpr>(E);
2190    if (M->isArrow())
2191      return FindExpressionBaseAddress(M->getBase());
2192    return FindExpressionBaseAddressLValue(M->getBase());
2193  }
2194  case Expr::ArraySubscriptExprClass: {
2195    const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
2196    return FindExpressionBaseAddress(ASE->getBase());
2197  }
2198  case Expr::UnaryOperatorClass: {
2199    const UnaryOperator *Exp = cast<UnaryOperator>(E);
2200
2201    if (Exp->getOpcode() == UnaryOperator::Deref)
2202      return FindExpressionBaseAddress(Exp->getSubExpr());
2203
2204    return E;
2205  }
2206  }
2207}
2208
2209static const Expr* FindExpressionBaseAddress(const Expr* E) {
2210  switch (E->getStmtClass()) {
2211  default:
2212    return E;
2213  case Expr::ParenExprClass: {
2214    const ParenExpr* PE = cast<ParenExpr>(E);
2215    return FindExpressionBaseAddress(PE->getSubExpr());
2216  }
2217  case Expr::UnaryOperatorClass: {
2218    const UnaryOperator *Exp = cast<UnaryOperator>(E);
2219
2220    // C99 6.6p9
2221    if (Exp->getOpcode() == UnaryOperator::AddrOf)
2222      return FindExpressionBaseAddressLValue(Exp->getSubExpr());
2223
2224    if (Exp->getOpcode() == UnaryOperator::Extension)
2225      return FindExpressionBaseAddress(Exp->getSubExpr());
2226
2227    return E;
2228  }
2229  case Expr::BinaryOperatorClass: {
2230    const BinaryOperator *Exp = cast<BinaryOperator>(E);
2231
2232    Expr *PExp = Exp->getLHS();
2233    Expr *IExp = Exp->getRHS();
2234    if (IExp->getType()->isPointerType())
2235      std::swap(PExp, IExp);
2236
2237    return FindExpressionBaseAddress(PExp);
2238  }
2239  case Expr::ImplicitCastExprClass: {
2240    const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
2241
2242    // Check for implicit promotion
2243    if (SubExpr->getType()->isFunctionType() ||
2244        SubExpr->getType()->isArrayType())
2245      return FindExpressionBaseAddressLValue(SubExpr);
2246
2247    // Check for pointer->pointer cast
2248    if (SubExpr->getType()->isPointerType())
2249      return FindExpressionBaseAddress(SubExpr);
2250
2251    // We assume that we have an arithmetic expression here;
2252    // if we don't, we'll figure it out later
2253    return 0;
2254  }
2255  case Expr::CStyleCastExprClass: {
2256    const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
2257
2258    // Check for pointer->pointer cast
2259    if (SubExpr->getType()->isPointerType())
2260      return FindExpressionBaseAddress(SubExpr);
2261
2262    // We assume that we have an arithmetic expression here;
2263    // if we don't, we'll figure it out later
2264    return 0;
2265  }
2266  }
2267}
2268
2269bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
2270  switch (Init->getStmtClass()) {
2271  default:
2272    InitializerElementNotConstant(Init);
2273    return true;
2274  case Expr::ParenExprClass: {
2275    const ParenExpr* PE = cast<ParenExpr>(Init);
2276    return CheckArithmeticConstantExpression(PE->getSubExpr());
2277  }
2278  case Expr::FloatingLiteralClass:
2279  case Expr::IntegerLiteralClass:
2280  case Expr::CharacterLiteralClass:
2281  case Expr::ImaginaryLiteralClass:
2282  case Expr::TypesCompatibleExprClass:
2283  case Expr::CXXBoolLiteralExprClass:
2284    return false;
2285  case Expr::CallExprClass:
2286  case Expr::CXXOperatorCallExprClass: {
2287    const CallExpr *CE = cast<CallExpr>(Init);
2288
2289    // Allow any constant foldable calls to builtins.
2290    if (CE->isBuiltinCall(Context) && CE->isEvaluatable(Context))
2291      return false;
2292
2293    InitializerElementNotConstant(Init);
2294    return true;
2295  }
2296  case Expr::DeclRefExprClass:
2297  case Expr::QualifiedDeclRefExprClass: {
2298    const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
2299    if (isa<EnumConstantDecl>(D))
2300      return false;
2301    InitializerElementNotConstant(Init);
2302    return true;
2303  }
2304  case Expr::CompoundLiteralExprClass:
2305    // Allow "(vector type){2,4}"; normal C constraints don't allow this,
2306    // but vectors are allowed to be magic.
2307    if (Init->getType()->isVectorType())
2308      return false;
2309    InitializerElementNotConstant(Init);
2310    return true;
2311  case Expr::UnaryOperatorClass: {
2312    const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2313
2314    switch (Exp->getOpcode()) {
2315    // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2316    // See C99 6.6p3.
2317    default:
2318      InitializerElementNotConstant(Init);
2319      return true;
2320    case UnaryOperator::OffsetOf:
2321      if (Exp->getSubExpr()->getType()->isConstantSizeType())
2322        return false;
2323      InitializerElementNotConstant(Init);
2324      return true;
2325    case UnaryOperator::Extension:
2326    case UnaryOperator::LNot:
2327    case UnaryOperator::Plus:
2328    case UnaryOperator::Minus:
2329    case UnaryOperator::Not:
2330      return CheckArithmeticConstantExpression(Exp->getSubExpr());
2331    }
2332  }
2333  case Expr::SizeOfAlignOfExprClass: {
2334    const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
2335    // Special check for void types, which are allowed as an extension
2336    if (Exp->getTypeOfArgument()->isVoidType())
2337      return false;
2338    // alignof always evaluates to a constant.
2339    // FIXME: is sizeof(int[3.0]) a constant expression?
2340    if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
2341      InitializerElementNotConstant(Init);
2342      return true;
2343    }
2344    return false;
2345  }
2346  case Expr::BinaryOperatorClass: {
2347    const BinaryOperator *Exp = cast<BinaryOperator>(Init);
2348
2349    if (Exp->getLHS()->getType()->isArithmeticType() &&
2350        Exp->getRHS()->getType()->isArithmeticType()) {
2351      return CheckArithmeticConstantExpression(Exp->getLHS()) ||
2352             CheckArithmeticConstantExpression(Exp->getRHS());
2353    }
2354
2355    if (Exp->getLHS()->getType()->isPointerType() &&
2356        Exp->getRHS()->getType()->isPointerType()) {
2357      const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
2358      const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
2359
2360      // Only allow a null (constant integer) base; we could
2361      // allow some additional cases if necessary, but this
2362      // is sufficient to cover offsetof-like constructs.
2363      if (!LHSBase && !RHSBase) {
2364        return CheckAddressConstantExpression(Exp->getLHS()) ||
2365               CheckAddressConstantExpression(Exp->getRHS());
2366      }
2367    }
2368
2369    InitializerElementNotConstant(Init);
2370    return true;
2371  }
2372  case Expr::ImplicitCastExprClass:
2373  case Expr::CStyleCastExprClass: {
2374    const CastExpr *CE = cast<CastExpr>(Init);
2375    const Expr *SubExpr = CE->getSubExpr();
2376
2377    if (SubExpr->getType()->isArithmeticType())
2378      return CheckArithmeticConstantExpression(SubExpr);
2379
2380    if (SubExpr->getType()->isPointerType()) {
2381      const Expr* Base = FindExpressionBaseAddress(SubExpr);
2382      if (Base) {
2383        // the cast is only valid if done to a wide enough type
2384        if (Context.getTypeSize(CE->getType()) >=
2385            Context.getTypeSize(SubExpr->getType()))
2386          return false;
2387      } else {
2388        // If the pointer has a null base, this is an offsetof-like construct
2389        return CheckAddressConstantExpression(SubExpr);
2390      }
2391    }
2392
2393    InitializerElementNotConstant(Init);
2394    return true;
2395  }
2396  case Expr::ConditionalOperatorClass: {
2397    const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
2398
2399    // If GNU extensions are disabled, we require all operands to be arithmetic
2400    // constant expressions.
2401    if (getLangOptions().NoExtensions) {
2402      return CheckArithmeticConstantExpression(Exp->getCond()) ||
2403          (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
2404             CheckArithmeticConstantExpression(Exp->getRHS());
2405    }
2406
2407    // Otherwise, we have to emulate some of the behavior of fold here.
2408    // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
2409    // because it can constant fold things away.  To retain compatibility with
2410    // GCC code, we see if we can fold the condition to a constant (which we
2411    // should always be able to do in theory).  If so, we only require the
2412    // specified arm of the conditional to be a constant.  This is a horrible
2413    // hack, but is require by real world code that uses __builtin_constant_p.
2414    Expr::EvalResult EvalResult;
2415    if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
2416        EvalResult.HasSideEffects) {
2417      // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
2418      // won't be able to either.  Use it to emit the diagnostic though.
2419      bool Res = CheckArithmeticConstantExpression(Exp->getCond());
2420      assert(Res && "Evaluate couldn't evaluate this constant?");
2421      return Res;
2422    }
2423
2424    // Verify that the side following the condition is also a constant.
2425    const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
2426    if (EvalResult.Val.getInt() == 0)
2427      std::swap(TrueSide, FalseSide);
2428
2429    if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
2430      return true;
2431
2432    // Okay, the evaluated side evaluates to a constant, so we accept this.
2433    // Check to see if the other side is obviously not a constant.  If so,
2434    // emit a warning that this is a GNU extension.
2435    if (FalseSide && !FalseSide->isEvaluatable(Context))
2436      Diag(Init->getExprLoc(),
2437           diag::ext_typecheck_expression_not_constant_but_accepted)
2438        << FalseSide->getSourceRange();
2439    return false;
2440  }
2441  }
2442}
2443
2444bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
2445  if (Init->isConstantInitializer(Context))
2446    return false;
2447  InitializerElementNotConstant(Init);
2448  return true;
2449
2450  if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init))
2451    Init = DIE->getInit();
2452
2453  Init = Init->IgnoreParens();
2454
2455  if (Init->isEvaluatable(Context))
2456    return false;
2457
2458  // Look through CXXDefaultArgExprs; they have no meaning in this context.
2459  if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
2460    return CheckForConstantInitializer(DAE->getExpr(), DclT);
2461
2462  if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
2463    return CheckForConstantInitializer(e->getInitializer(), DclT);
2464
2465  if (isa<ImplicitValueInitExpr>(Init)) {
2466    // FIXME: In C++, check for non-POD types.
2467    return false;
2468  }
2469
2470  if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
2471    unsigned numInits = Exp->getNumInits();
2472    for (unsigned i = 0; i < numInits; i++) {
2473      // FIXME: Need to get the type of the declaration for C++,
2474      // because it could be a reference?
2475
2476      if (CheckForConstantInitializer(Exp->getInit(i),
2477                                      Exp->getInit(i)->getType()))
2478        return true;
2479    }
2480    return false;
2481  }
2482
2483  // FIXME: We can probably remove some of this code below, now that
2484  // Expr::Evaluate is doing the heavy lifting for scalars.
2485
2486  if (Init->isNullPointerConstant(Context))
2487    return false;
2488  if (Init->getType()->isArithmeticType()) {
2489    QualType InitTy = Context.getCanonicalType(Init->getType())
2490                             .getUnqualifiedType();
2491    if (InitTy == Context.BoolTy) {
2492      // Special handling for pointers implicitly cast to bool;
2493      // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
2494      if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
2495        Expr* SubE = ICE->getSubExpr();
2496        if (SubE->getType()->isPointerType() ||
2497            SubE->getType()->isArrayType() ||
2498            SubE->getType()->isFunctionType()) {
2499          return CheckAddressConstantExpression(Init);
2500        }
2501      }
2502    } else if (InitTy->isIntegralType()) {
2503      Expr* SubE = 0;
2504      if (CastExpr* CE = dyn_cast<CastExpr>(Init))
2505        SubE = CE->getSubExpr();
2506      // Special check for pointer cast to int; we allow as an extension
2507      // an address constant cast to an integer if the integer
2508      // is of an appropriate width (this sort of code is apparently used
2509      // in some places).
2510      // FIXME: Add pedwarn?
2511      // FIXME: Don't allow bitfields here!  Need the FieldDecl for that.
2512      if (SubE && (SubE->getType()->isPointerType() ||
2513                   SubE->getType()->isArrayType() ||
2514                   SubE->getType()->isFunctionType())) {
2515        unsigned IntWidth = Context.getTypeSize(Init->getType());
2516        unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2517        if (IntWidth >= PointerWidth)
2518          return CheckAddressConstantExpression(Init);
2519      }
2520    }
2521
2522    return CheckArithmeticConstantExpression(Init);
2523  }
2524
2525  if (Init->getType()->isPointerType())
2526    return CheckAddressConstantExpression(Init);
2527
2528  // An array type at the top level that isn't an init-list must
2529  // be a string literal
2530  if (Init->getType()->isArrayType())
2531    return false;
2532
2533  if (Init->getType()->isFunctionType())
2534    return false;
2535
2536  // Allow block exprs at top level.
2537  if (Init->getType()->isBlockPointerType())
2538    return false;
2539
2540  // GCC cast to union extension
2541  // note: the validity of the cast expr is checked by CheckCastTypes()
2542  if (CastExpr *C = dyn_cast<CastExpr>(Init)) {
2543    QualType T = C->getType();
2544    return T->isUnionType() && CheckForConstantInitializer(C->getSubExpr(), T);
2545  }
2546
2547  InitializerElementNotConstant(Init);
2548  return true;
2549}
2550
2551void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
2552  AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
2553}
2554
2555/// AddInitializerToDecl - Adds the initializer Init to the
2556/// declaration dcl. If DirectInit is true, this is C++ direct
2557/// initialization rather than copy initialization.
2558void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init, bool DirectInit) {
2559  Decl *RealDecl = static_cast<Decl *>(dcl);
2560  Expr *Init = static_cast<Expr *>(init.release());
2561  assert(Init && "missing initializer");
2562
2563  // If there is no declaration, there was an error parsing it.  Just ignore
2564  // the initializer.
2565  if (RealDecl == 0) {
2566    Init->Destroy(Context);
2567    return;
2568  }
2569
2570  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2571  if (!VDecl) {
2572    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
2573    RealDecl->setInvalidDecl();
2574    return;
2575  }
2576  // Get the decls type and save a reference for later, since
2577  // CheckInitializerTypes may change it.
2578  QualType DclT = VDecl->getType(), SavT = DclT;
2579  if (VDecl->isBlockVarDecl()) {
2580    VarDecl::StorageClass SC = VDecl->getStorageClass();
2581    if (SC == VarDecl::Extern) { // C99 6.7.8p5
2582      Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
2583      VDecl->setInvalidDecl();
2584    } else if (!VDecl->isInvalidDecl()) {
2585      if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
2586                                VDecl->getDeclName(), DirectInit))
2587        VDecl->setInvalidDecl();
2588
2589      // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2590      // Don't check invalid declarations to avoid emitting useless diagnostics.
2591      if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
2592        if (SC == VarDecl::Static) // C99 6.7.8p4.
2593          CheckForConstantInitializer(Init, DclT);
2594      }
2595    }
2596  } else if (VDecl->isFileVarDecl()) {
2597    if (VDecl->getStorageClass() == VarDecl::Extern)
2598      Diag(VDecl->getLocation(), diag::warn_extern_init);
2599    if (!VDecl->isInvalidDecl())
2600      if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
2601                                VDecl->getDeclName(), DirectInit))
2602        VDecl->setInvalidDecl();
2603
2604    // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2605    // Don't check invalid declarations to avoid emitting useless diagnostics.
2606    if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
2607      // C99 6.7.8p4. All file scoped initializers need to be constant.
2608      CheckForConstantInitializer(Init, DclT);
2609    }
2610  }
2611  // If the type changed, it means we had an incomplete type that was
2612  // completed by the initializer. For example:
2613  //   int ary[] = { 1, 3, 5 };
2614  // "ary" transitions from a VariableArrayType to a ConstantArrayType.
2615  if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
2616    VDecl->setType(DclT);
2617    Init->setType(DclT);
2618  }
2619
2620  // Attach the initializer to the decl.
2621  VDecl->setInit(Init);
2622  return;
2623}
2624
2625void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2626  Decl *RealDecl = static_cast<Decl *>(dcl);
2627
2628  // If there is no declaration, there was an error parsing it. Just ignore it.
2629  if (RealDecl == 0)
2630    return;
2631
2632  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2633    QualType Type = Var->getType();
2634    // C++ [dcl.init.ref]p3:
2635    //   The initializer can be omitted for a reference only in a
2636    //   parameter declaration (8.3.5), in the declaration of a
2637    //   function return type, in the declaration of a class member
2638    //   within its class declaration (9.2), and where the extern
2639    //   specifier is explicitly used.
2640    if (Type->isReferenceType() &&
2641        Var->getStorageClass() != VarDecl::Extern &&
2642        Var->getStorageClass() != VarDecl::PrivateExtern) {
2643      Diag(Var->getLocation(), diag::err_reference_var_requires_init)
2644        << Var->getDeclName()
2645        << SourceRange(Var->getLocation(), Var->getLocation());
2646      Var->setInvalidDecl();
2647      return;
2648    }
2649
2650    // C++ [dcl.init]p9:
2651    //
2652    //   If no initializer is specified for an object, and the object
2653    //   is of (possibly cv-qualified) non-POD class type (or array
2654    //   thereof), the object shall be default-initialized; if the
2655    //   object is of const-qualified type, the underlying class type
2656    //   shall have a user-declared default constructor.
2657    if (getLangOptions().CPlusPlus) {
2658      QualType InitType = Type;
2659      if (const ArrayType *Array = Context.getAsArrayType(Type))
2660        InitType = Array->getElementType();
2661      if (Var->getStorageClass() != VarDecl::Extern &&
2662          Var->getStorageClass() != VarDecl::PrivateExtern &&
2663          InitType->isRecordType()) {
2664        const CXXConstructorDecl *Constructor
2665          = PerformInitializationByConstructor(InitType, 0, 0,
2666                                               Var->getLocation(),
2667                                               SourceRange(Var->getLocation(),
2668                                                           Var->getLocation()),
2669                                               Var->getDeclName(),
2670                                               IK_Default);
2671        if (!Constructor)
2672          Var->setInvalidDecl();
2673      }
2674    }
2675
2676#if 0
2677    // FIXME: Temporarily disabled because we are not properly parsing
2678    // linkage specifications on declarations, e.g.,
2679    //
2680    //   extern "C" const CGPoint CGPointerZero;
2681    //
2682    // C++ [dcl.init]p9:
2683    //
2684    //     If no initializer is specified for an object, and the
2685    //     object is of (possibly cv-qualified) non-POD class type (or
2686    //     array thereof), the object shall be default-initialized; if
2687    //     the object is of const-qualified type, the underlying class
2688    //     type shall have a user-declared default
2689    //     constructor. Otherwise, if no initializer is specified for
2690    //     an object, the object and its subobjects, if any, have an
2691    //     indeterminate initial value; if the object or any of its
2692    //     subobjects are of const-qualified type, the program is
2693    //     ill-formed.
2694    //
2695    // This isn't technically an error in C, so we don't diagnose it.
2696    //
2697    // FIXME: Actually perform the POD/user-defined default
2698    // constructor check.
2699    if (getLangOptions().CPlusPlus &&
2700        Context.getCanonicalType(Type).isConstQualified() &&
2701        Var->getStorageClass() != VarDecl::Extern)
2702      Diag(Var->getLocation(),  diag::err_const_var_requires_init)
2703        << Var->getName()
2704        << SourceRange(Var->getLocation(), Var->getLocation());
2705#endif
2706  }
2707}
2708
2709/// The declarators are chained together backwards, reverse the list.
2710Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2711  // Often we have single declarators, handle them quickly.
2712  Decl *Group = static_cast<Decl*>(group);
2713  if (Group == 0)
2714    return 0;
2715
2716  Decl *NewGroup = 0;
2717  if (Group->getNextDeclarator() == 0)
2718    NewGroup = Group;
2719  else { // reverse the list.
2720    while (Group) {
2721      Decl *Next = Group->getNextDeclarator();
2722      Group->setNextDeclarator(NewGroup);
2723      NewGroup = Group;
2724      Group = Next;
2725    }
2726  }
2727  // Perform semantic analysis that depends on having fully processed both
2728  // the declarator and initializer.
2729  for (Decl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
2730    VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2731    if (!IDecl)
2732      continue;
2733    QualType T = IDecl->getType();
2734
2735    if (T->isVariableArrayType()) {
2736      const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
2737
2738      // FIXME: This won't give the correct result for
2739      // int a[10][n];
2740      SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
2741      if (IDecl->isFileVarDecl()) {
2742        Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2743          SizeRange;
2744
2745        IDecl->setInvalidDecl();
2746      } else {
2747        // C99 6.7.5.2p2: If an identifier is declared to be an object with
2748        // static storage duration, it shall not have a variable length array.
2749        if (IDecl->getStorageClass() == VarDecl::Static) {
2750          Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2751            << SizeRange;
2752          IDecl->setInvalidDecl();
2753        } else if (IDecl->getStorageClass() == VarDecl::Extern) {
2754          Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2755            << SizeRange;
2756          IDecl->setInvalidDecl();
2757        }
2758      }
2759    } else if (T->isVariablyModifiedType()) {
2760      if (IDecl->isFileVarDecl()) {
2761        Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2762        IDecl->setInvalidDecl();
2763      } else {
2764        if (IDecl->getStorageClass() == VarDecl::Extern) {
2765          Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2766          IDecl->setInvalidDecl();
2767        }
2768      }
2769    }
2770
2771    // Block scope. C99 6.7p7: If an identifier for an object is declared with
2772    // no linkage (C99 6.2.2p6), the type for the object shall be complete...
2773    if (IDecl->isBlockVarDecl() &&
2774        IDecl->getStorageClass() != VarDecl::Extern) {
2775      if (!IDecl->isInvalidDecl() &&
2776          DiagnoseIncompleteType(IDecl->getLocation(), T,
2777                                 diag::err_typecheck_decl_incomplete_type))
2778        IDecl->setInvalidDecl();
2779    }
2780    // File scope. C99 6.9.2p2: A declaration of an identifier for and
2781    // object that has file scope without an initializer, and without a
2782    // storage-class specifier or with the storage-class specifier "static",
2783    // constitutes a tentative definition. Note: A tentative definition with
2784    // external linkage is valid (C99 6.2.2p5).
2785    if (isTentativeDefinition(IDecl)) {
2786      if (T->isIncompleteArrayType()) {
2787        // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2788        // array to be completed. Don't issue a diagnostic.
2789      } else if (!IDecl->isInvalidDecl() &&
2790                 DiagnoseIncompleteType(IDecl->getLocation(), T,
2791                                        diag::err_typecheck_decl_incomplete_type))
2792        // C99 6.9.2p3: If the declaration of an identifier for an object is
2793        // a tentative definition and has internal linkage (C99 6.2.2p3), the
2794        // declared type shall not be an incomplete type.
2795        IDecl->setInvalidDecl();
2796    }
2797    if (IDecl->isFileVarDecl())
2798      CheckForFileScopedRedefinitions(S, IDecl);
2799  }
2800  return NewGroup;
2801}
2802
2803/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2804/// to introduce parameters into function prototype scope.
2805Sema::DeclTy *
2806Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
2807  const DeclSpec &DS = D.getDeclSpec();
2808
2809  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
2810  VarDecl::StorageClass StorageClass = VarDecl::None;
2811  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2812    StorageClass = VarDecl::Register;
2813  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
2814    Diag(DS.getStorageClassSpecLoc(),
2815         diag::err_invalid_storage_class_in_func_decl);
2816    D.getMutableDeclSpec().ClearStorageClassSpecs();
2817  }
2818  if (DS.isThreadSpecified()) {
2819    Diag(DS.getThreadSpecLoc(),
2820         diag::err_invalid_storage_class_in_func_decl);
2821    D.getMutableDeclSpec().ClearStorageClassSpecs();
2822  }
2823
2824  // Check that there are no default arguments inside the type of this
2825  // parameter (C++ only).
2826  if (getLangOptions().CPlusPlus)
2827    CheckExtraCXXDefaultArguments(D);
2828
2829  // In this context, we *do not* check D.getInvalidType(). If the declarator
2830  // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2831  // though it will not reflect the user specified type.
2832  QualType parmDeclType = GetTypeForDeclarator(D, S);
2833
2834  assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2835
2836  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2837  // Can this happen for params?  We already checked that they don't conflict
2838  // among each other.  Here they can only shadow globals, which is ok.
2839  IdentifierInfo *II = D.getIdentifier();
2840  if (II) {
2841    if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
2842      if (PrevDecl->isTemplateParameter()) {
2843        // Maybe we will complain about the shadowed template parameter.
2844        DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2845        // Just pretend that we didn't see the previous declaration.
2846        PrevDecl = 0;
2847      } else if (S->isDeclScope(PrevDecl)) {
2848        Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
2849
2850        // Recover by removing the name
2851        II = 0;
2852        D.SetIdentifier(0, D.getIdentifierLoc());
2853      }
2854    }
2855  }
2856
2857  // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2858  // Doing the promotion here has a win and a loss. The win is the type for
2859  // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2860  // code generator). The loss is the orginal type isn't preserved. For example:
2861  //
2862  // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2863  //    int blockvardecl[5];
2864  //    sizeof(parmvardecl);  // size == 4
2865  //    sizeof(blockvardecl); // size == 20
2866  // }
2867  //
2868  // For expressions, all implicit conversions are captured using the
2869  // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2870  //
2871  // FIXME: If a source translation tool needs to see the original type, then
2872  // we need to consider storing both types (in ParmVarDecl)...
2873  //
2874  if (parmDeclType->isArrayType()) {
2875    // int x[restrict 4] ->  int *restrict
2876    parmDeclType = Context.getArrayDecayedType(parmDeclType);
2877  } else if (parmDeclType->isFunctionType())
2878    parmDeclType = Context.getPointerType(parmDeclType);
2879
2880  ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2881                                         D.getIdentifierLoc(), II,
2882                                         parmDeclType, StorageClass,
2883                                         0);
2884
2885  if (D.getInvalidType())
2886    New->setInvalidDecl();
2887
2888  // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2889  if (D.getCXXScopeSpec().isSet()) {
2890    Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2891      << D.getCXXScopeSpec().getRange();
2892    New->setInvalidDecl();
2893  }
2894  // Parameter declarators cannot be interface types. All ObjC objects are
2895  // passed by reference.
2896  if (parmDeclType->isObjCInterfaceType()) {
2897    Diag(D.getIdentifierLoc(), diag::err_object_cannot_be_by_value)
2898         << "passed";
2899    New->setInvalidDecl();
2900  }
2901
2902  // Add the parameter declaration into this scope.
2903  S->AddDecl(New);
2904  if (II)
2905    IdResolver.AddDecl(New);
2906
2907  ProcessDeclAttributes(New, D);
2908  return New;
2909
2910}
2911
2912void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D) {
2913  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2914         "Not a function declarator!");
2915  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2916
2917  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2918  // for a K&R function.
2919  if (!FTI.hasPrototype) {
2920    for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
2921      if (FTI.ArgInfo[i].Param == 0) {
2922        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2923          << FTI.ArgInfo[i].Ident;
2924        // Implicitly declare the argument as type 'int' for lack of a better
2925        // type.
2926        DeclSpec DS;
2927        const char* PrevSpec; // unused
2928        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2929                           PrevSpec);
2930        Declarator ParamD(DS, Declarator::KNRTypeListContext);
2931        ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2932        FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
2933      }
2934    }
2935  }
2936}
2937
2938Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
2939  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2940  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2941         "Not a function declarator!");
2942  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2943
2944  if (FTI.hasPrototype) {
2945    // FIXME: Diagnose arguments without names in C.
2946  }
2947
2948  Scope *ParentScope = FnBodyScope->getParent();
2949
2950  return ActOnStartOfFunctionDef(FnBodyScope,
2951                                 ActOnDeclarator(ParentScope, D, 0,
2952                                                 /*IsFunctionDefinition=*/true));
2953}
2954
2955Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2956  Decl *decl = static_cast<Decl*>(D);
2957  FunctionDecl *FD = cast<FunctionDecl>(decl);
2958
2959  // See if this is a redefinition.
2960  const FunctionDecl *Definition;
2961  if (FD->getBody(Definition)) {
2962    Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
2963    Diag(Definition->getLocation(), diag::note_previous_definition);
2964  }
2965
2966  // Builtin functions cannot be defined.
2967  if (unsigned BuiltinID = FD->getBuiltinID(Context)) {
2968    if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2969      Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
2970      FD->setInvalidDecl();
2971    }
2972  }
2973
2974  PushDeclContext(FnBodyScope, FD);
2975
2976  // Check the validity of our function parameters
2977  CheckParmsForFunctionDef(FD);
2978
2979  // Introduce our parameters into the function scope
2980  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2981    ParmVarDecl *Param = FD->getParamDecl(p);
2982    Param->setOwningFunction(FD);
2983
2984    // If this has an identifier, add it to the scope stack.
2985    if (Param->getIdentifier())
2986      PushOnScopeChains(Param, FnBodyScope);
2987  }
2988
2989  // Checking attributes of current function definition
2990  // dllimport attribute.
2991  if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2992    // dllimport attribute cannot be applied to definition.
2993    if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2994      Diag(FD->getLocation(),
2995           diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2996        << "dllimport";
2997      FD->setInvalidDecl();
2998      return FD;
2999    } else {
3000      // If a symbol previously declared dllimport is later defined, the
3001      // attribute is ignored in subsequent references, and a warning is
3002      // emitted.
3003      Diag(FD->getLocation(),
3004           diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
3005        << FD->getNameAsCString() << "dllimport";
3006    }
3007  }
3008  return FD;
3009}
3010
3011Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
3012  Decl *dcl = static_cast<Decl *>(D);
3013  Stmt *Body = static_cast<Stmt*>(BodyArg.release());
3014  if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
3015    FD->setBody(Body);
3016    assert(FD == getCurFunctionDecl() && "Function parsing confused");
3017  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
3018    assert(MD == getCurMethodDecl() && "Method parsing confused");
3019    MD->setBody((Stmt*)Body);
3020  } else {
3021    Body->Destroy(Context);
3022    return 0;
3023  }
3024  PopDeclContext();
3025  // Verify and clean out per-function state.
3026
3027  // Check goto/label use.
3028  for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
3029       I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
3030    // Verify that we have no forward references left.  If so, there was a goto
3031    // or address of a label taken, but no definition of it.  Label fwd
3032    // definitions are indicated with a null substmt.
3033    if (I->second->getSubStmt() == 0) {
3034      LabelStmt *L = I->second;
3035      // Emit error.
3036      Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
3037
3038      // At this point, we have gotos that use the bogus label.  Stitch it into
3039      // the function body so that they aren't leaked and that the AST is well
3040      // formed.
3041      if (Body) {
3042#if 0
3043        // FIXME: Why do this?  Having a 'push_back' in CompoundStmt is ugly,
3044        // and the AST is malformed anyway.  We should just blow away 'L'.
3045        L->setSubStmt(new (Context) NullStmt(L->getIdentLoc()));
3046        cast<CompoundStmt>(Body)->push_back(L);
3047#else
3048        L->Destroy(Context);
3049#endif
3050      } else {
3051        // The whole function wasn't parsed correctly, just delete this.
3052        L->Destroy(Context);
3053      }
3054    }
3055  }
3056  LabelMap.clear();
3057
3058  return D;
3059}
3060
3061/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
3062/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
3063NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
3064                                          IdentifierInfo &II, Scope *S) {
3065  // Extension in C99.  Legal in C90, but warn about it.
3066  if (getLangOptions().C99)
3067    Diag(Loc, diag::ext_implicit_function_decl) << &II;
3068  else
3069    Diag(Loc, diag::warn_implicit_function_decl) << &II;
3070
3071  // FIXME: handle stuff like:
3072  // void foo() { extern float X(); }
3073  // void bar() { X(); }  <-- implicit decl for X in another scope.
3074
3075  // Set a Declarator for the implicit definition: int foo();
3076  const char *Dummy;
3077  DeclSpec DS;
3078  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
3079  Error = Error; // Silence warning.
3080  assert(!Error && "Error setting up implicit decl!");
3081  Declarator D(DS, Declarator::BlockContext);
3082  D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(),
3083                                             0, 0, 0, Loc, D),
3084                SourceLocation());
3085  D.SetIdentifier(&II, Loc);
3086
3087  // Insert this function into translation-unit scope.
3088
3089  DeclContext *PrevDC = CurContext;
3090  CurContext = Context.getTranslationUnitDecl();
3091
3092  FunctionDecl *FD =
3093    dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
3094  FD->setImplicit();
3095
3096  CurContext = PrevDC;
3097
3098  AddKnownFunctionAttributes(FD);
3099
3100  return FD;
3101}
3102
3103/// \brief Adds any function attributes that we know a priori based on
3104/// the declaration of this function.
3105///
3106/// These attributes can apply both to implicitly-declared builtins
3107/// (like __builtin___printf_chk) or to library-declared functions
3108/// like NSLog or printf.
3109void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
3110  if (FD->isInvalidDecl())
3111    return;
3112
3113  // If this is a built-in function, map its builtin attributes to
3114  // actual attributes.
3115  if (unsigned BuiltinID = FD->getBuiltinID(Context)) {
3116    // Handle printf-formatting attributes.
3117    unsigned FormatIdx;
3118    bool HasVAListArg;
3119    if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
3120      if (!FD->getAttr<FormatAttr>())
3121        FD->addAttr(new FormatAttr("printf", FormatIdx + 1, FormatIdx + 2));
3122    }
3123
3124    // Mark const if we don't care about errno and that is the only
3125    // thing preventing the function from being const. This allows
3126    // IRgen to use LLVM intrinsics for such functions.
3127    if (!getLangOptions().MathErrno &&
3128        Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
3129      if (!FD->getAttr<ConstAttr>())
3130        FD->addAttr(new ConstAttr());
3131    }
3132  }
3133
3134  IdentifierInfo *Name = FD->getIdentifier();
3135  if (!Name)
3136    return;
3137  if ((!getLangOptions().CPlusPlus &&
3138       FD->getDeclContext()->isTranslationUnit()) ||
3139      (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
3140       cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
3141       LinkageSpecDecl::lang_c)) {
3142    // Okay: this could be a libc/libm/Objective-C function we know
3143    // about.
3144  } else
3145    return;
3146
3147  unsigned KnownID;
3148  for (KnownID = 0; KnownID != id_num_known_functions; ++KnownID)
3149    if (KnownFunctionIDs[KnownID] == Name)
3150      break;
3151
3152  switch (KnownID) {
3153  case id_NSLog:
3154  case id_NSLogv:
3155    if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
3156      // FIXME: We known better than our headers.
3157      const_cast<FormatAttr *>(Format)->setType("printf");
3158    } else
3159      FD->addAttr(new FormatAttr("printf", 1, 2));
3160    break;
3161
3162  case id_asprintf:
3163  case id_vasprintf:
3164    if (!FD->getAttr<FormatAttr>())
3165      FD->addAttr(new FormatAttr("printf", 2, 3));
3166    break;
3167
3168  default:
3169    // Unknown function or known function without any attributes to
3170    // add. Do nothing.
3171    break;
3172  }
3173}
3174
3175TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
3176                                    Decl *LastDeclarator) {
3177  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
3178  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3179
3180  // Scope manipulation handled by caller.
3181  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
3182                                           D.getIdentifierLoc(),
3183                                           D.getIdentifier(),
3184                                           T);
3185  NewTD->setNextDeclarator(LastDeclarator);
3186  if (D.getInvalidType())
3187    NewTD->setInvalidDecl();
3188  return NewTD;
3189}
3190
3191/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
3192/// former case, Name will be non-null.  In the later case, Name will be null.
3193/// TagSpec indicates what kind of tag this is. TK indicates whether this is a
3194/// reference/declaration/definition of a tag.
3195Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagKind TK,
3196                             SourceLocation KWLoc, const CXXScopeSpec &SS,
3197                             IdentifierInfo *Name, SourceLocation NameLoc,
3198                             AttributeList *Attr) {
3199  // If this is not a definition, it must have a name.
3200  assert((Name != 0 || TK == TK_Definition) &&
3201         "Nameless record must be a definition!");
3202
3203  TagDecl::TagKind Kind;
3204  switch (TagSpec) {
3205  default: assert(0 && "Unknown tag type!");
3206  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3207  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
3208  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
3209  case DeclSpec::TST_enum:   Kind = TagDecl::TK_enum; break;
3210  }
3211
3212  DeclContext *SearchDC = CurContext;
3213  DeclContext *DC = CurContext;
3214  NamedDecl *PrevDecl = 0;
3215
3216  bool Invalid = false;
3217
3218  if (Name && SS.isNotEmpty()) {
3219    // We have a nested-name tag ('struct foo::bar').
3220
3221    // Check for invalid 'foo::'.
3222    if (SS.isInvalid()) {
3223      Name = 0;
3224      goto CreateNewDecl;
3225    }
3226
3227    DC = static_cast<DeclContext*>(SS.getScopeRep());
3228    SearchDC = DC;
3229    // Look-up name inside 'foo::'.
3230    PrevDecl = dyn_cast_or_null<TagDecl>(
3231                 LookupQualifiedName(DC, Name, LookupTagName, true).getAsDecl());
3232
3233    // A tag 'foo::bar' must already exist.
3234    if (PrevDecl == 0) {
3235      Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
3236      Name = 0;
3237      goto CreateNewDecl;
3238    }
3239  } else if (Name) {
3240    // If this is a named struct, check to see if there was a previous forward
3241    // declaration or definition.
3242    // FIXME: We're looking into outer scopes here, even when we
3243    // shouldn't be. Doing so can result in ambiguities that we
3244    // shouldn't be diagnosing.
3245    LookupResult R = LookupName(S, Name, LookupTagName,
3246                                /*RedeclarationOnly=*/(TK != TK_Reference));
3247    if (R.isAmbiguous()) {
3248      DiagnoseAmbiguousLookup(R, Name, NameLoc);
3249      // FIXME: This is not best way to recover from case like:
3250      //
3251      // struct S s;
3252      //
3253      // causes needless err_ovl_no_viable_function_in_init latter.
3254      Name = 0;
3255      PrevDecl = 0;
3256      Invalid = true;
3257    }
3258    else
3259      PrevDecl = R;
3260
3261    if (!getLangOptions().CPlusPlus && TK != TK_Reference) {
3262      // FIXME: This makes sure that we ignore the contexts associated
3263      // with C structs, unions, and enums when looking for a matching
3264      // tag declaration or definition. See the similar lookup tweak
3265      // in Sema::LookupName; is there a better way to deal with this?
3266      while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
3267        SearchDC = SearchDC->getParent();
3268    }
3269  }
3270
3271  if (PrevDecl && PrevDecl->isTemplateParameter()) {
3272    // Maybe we will complain about the shadowed template parameter.
3273    DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
3274    // Just pretend that we didn't see the previous declaration.
3275    PrevDecl = 0;
3276  }
3277
3278  if (PrevDecl) {
3279    // Check whether the previous declaration is usable.
3280    (void)DiagnoseUseOfDecl(PrevDecl, NameLoc);
3281
3282    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
3283      // If this is a use of a previous tag, or if the tag is already declared
3284      // in the same scope (so that the definition/declaration completes or
3285      // rementions the tag), reuse the decl.
3286      if (TK == TK_Reference || isDeclInScope(PrevDecl, SearchDC, S)) {
3287        // Make sure that this wasn't declared as an enum and now used as a
3288        // struct or something similar.
3289        if (PrevTagDecl->getTagKind() != Kind) {
3290          Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
3291          Diag(PrevDecl->getLocation(), diag::note_previous_use);
3292          // Recover by making this an anonymous redefinition.
3293          Name = 0;
3294          PrevDecl = 0;
3295          Invalid = true;
3296        } else {
3297          // If this is a use, just return the declaration we found.
3298
3299          // FIXME: In the future, return a variant or some other clue
3300          // for the consumer of this Decl to know it doesn't own it.
3301          // For our current ASTs this shouldn't be a problem, but will
3302          // need to be changed with DeclGroups.
3303          if (TK == TK_Reference)
3304            return PrevDecl;
3305
3306          // Diagnose attempts to redefine a tag.
3307          if (TK == TK_Definition) {
3308            if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
3309              Diag(NameLoc, diag::err_redefinition) << Name;
3310              Diag(Def->getLocation(), diag::note_previous_definition);
3311              // If this is a redefinition, recover by making this
3312              // struct be anonymous, which will make any later
3313              // references get the previous definition.
3314              Name = 0;
3315              PrevDecl = 0;
3316              Invalid = true;
3317            } else {
3318              // If the type is currently being defined, complain
3319              // about a nested redefinition.
3320              TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
3321              if (Tag->isBeingDefined()) {
3322                Diag(NameLoc, diag::err_nested_redefinition) << Name;
3323                Diag(PrevTagDecl->getLocation(),
3324                     diag::note_previous_definition);
3325                Name = 0;
3326                PrevDecl = 0;
3327                Invalid = true;
3328              }
3329            }
3330
3331            // Okay, this is definition of a previously declared or referenced
3332            // tag PrevDecl. We're going to create a new Decl for it.
3333          }
3334        }
3335        // If we get here we have (another) forward declaration or we
3336        // have a definition.  Just create a new decl.
3337      } else {
3338        // If we get here, this is a definition of a new tag type in a nested
3339        // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
3340        // new decl/type.  We set PrevDecl to NULL so that the entities
3341        // have distinct types.
3342        PrevDecl = 0;
3343      }
3344      // If we get here, we're going to create a new Decl. If PrevDecl
3345      // is non-NULL, it's a definition of the tag declared by
3346      // PrevDecl. If it's NULL, we have a new definition.
3347    } else {
3348      // PrevDecl is a namespace, template, or anything else
3349      // that lives in the IDNS_Tag identifier namespace.
3350      if (isDeclInScope(PrevDecl, SearchDC, S)) {
3351        // The tag name clashes with a namespace name, issue an error and
3352        // recover by making this tag be anonymous.
3353        Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
3354        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3355        Name = 0;
3356        PrevDecl = 0;
3357        Invalid = true;
3358      } else {
3359        // The existing declaration isn't relevant to us; we're in a
3360        // new scope, so clear out the previous declaration.
3361        PrevDecl = 0;
3362      }
3363    }
3364  } else if (TK == TK_Reference && SS.isEmpty() && Name &&
3365             (Kind != TagDecl::TK_enum))  {
3366    // C++ [basic.scope.pdecl]p5:
3367    //   -- for an elaborated-type-specifier of the form
3368    //
3369    //          class-key identifier
3370    //
3371    //      if the elaborated-type-specifier is used in the
3372    //      decl-specifier-seq or parameter-declaration-clause of a
3373    //      function defined in namespace scope, the identifier is
3374    //      declared as a class-name in the namespace that contains
3375    //      the declaration; otherwise, except as a friend
3376    //      declaration, the identifier is declared in the smallest
3377    //      non-class, non-function-prototype scope that contains the
3378    //      declaration.
3379    //
3380    // C99 6.7.2.3p8 has a similar (but not identical!) provision for
3381    // C structs and unions.
3382
3383    // Find the context where we'll be declaring the tag.
3384    // FIXME: We would like to maintain the current DeclContext as the
3385    // lexical context,
3386    while (SearchDC->isRecord())
3387      SearchDC = SearchDC->getParent();
3388
3389    // Find the scope where we'll be declaring the tag.
3390    while (S->isClassScope() ||
3391           (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
3392           ((S->getFlags() & Scope::DeclScope) == 0) ||
3393           (S->getEntity() &&
3394            ((DeclContext *)S->getEntity())->isTransparentContext()))
3395      S = S->getParent();
3396  }
3397
3398CreateNewDecl:
3399
3400  // If there is an identifier, use the location of the identifier as the
3401  // location of the decl, otherwise use the location of the struct/union
3402  // keyword.
3403  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
3404
3405  // Otherwise, create a new declaration. If there is a previous
3406  // declaration of the same entity, the two will be linked via
3407  // PrevDecl.
3408  TagDecl *New;
3409
3410  if (Kind == TagDecl::TK_enum) {
3411    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3412    // enum X { A, B, C } D;    D should chain to X.
3413    New = EnumDecl::Create(Context, SearchDC, Loc, Name,
3414                           cast_or_null<EnumDecl>(PrevDecl));
3415    // If this is an undefined enum, warn.
3416    if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
3417  } else {
3418    // struct/union/class
3419
3420    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3421    // struct X { int A; } D;    D should chain to X.
3422    if (getLangOptions().CPlusPlus)
3423      // FIXME: Look for a way to use RecordDecl for simple structs.
3424      New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name,
3425                                  cast_or_null<CXXRecordDecl>(PrevDecl));
3426    else
3427      New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name,
3428                               cast_or_null<RecordDecl>(PrevDecl));
3429  }
3430
3431  if (Kind != TagDecl::TK_enum) {
3432    // Handle #pragma pack: if the #pragma pack stack has non-default
3433    // alignment, make up a packed attribute for this decl. These
3434    // attributes are checked when the ASTContext lays out the
3435    // structure.
3436    //
3437    // It is important for implementing the correct semantics that this
3438    // happen here (in act on tag decl). The #pragma pack stack is
3439    // maintained as a result of parser callbacks which can occur at
3440    // many points during the parsing of a struct declaration (because
3441    // the #pragma tokens are effectively skipped over during the
3442    // parsing of the struct).
3443    if (unsigned Alignment = getPragmaPackAlignment())
3444      New->addAttr(new PackedAttr(Alignment * 8));
3445  }
3446
3447  if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) {
3448    // C++ [dcl.typedef]p3:
3449    //   [...] Similarly, in a given scope, a class or enumeration
3450    //   shall not be declared with the same name as a typedef-name
3451    //   that is declared in that scope and refers to a type other
3452    //   than the class or enumeration itself.
3453    LookupResult Lookup = LookupName(S, Name, LookupOrdinaryName, true);
3454    TypedefDecl *PrevTypedef = 0;
3455    if (Lookup.getKind() == LookupResult::Found)
3456      PrevTypedef = dyn_cast<TypedefDecl>(Lookup.getAsDecl());
3457
3458    if (PrevTypedef && isDeclInScope(PrevTypedef, SearchDC, S) &&
3459        Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) !=
3460          Context.getCanonicalType(Context.getTypeDeclType(New))) {
3461      Diag(Loc, diag::err_tag_definition_of_typedef)
3462        << Context.getTypeDeclType(New)
3463        << PrevTypedef->getUnderlyingType();
3464      Diag(PrevTypedef->getLocation(), diag::note_previous_definition);
3465      Invalid = true;
3466    }
3467  }
3468
3469  if (Invalid)
3470    New->setInvalidDecl();
3471
3472  if (Attr)
3473    ProcessDeclAttributeList(New, Attr);
3474
3475  // If we're declaring or defining a tag in function prototype scope
3476  // in C, note that this type can only be used within the function.
3477  if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
3478    Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
3479
3480  // Set the lexical context. If the tag has a C++ scope specifier, the
3481  // lexical context will be different from the semantic context.
3482  New->setLexicalDeclContext(CurContext);
3483
3484  if (TK == TK_Definition)
3485    New->startDefinition();
3486
3487  // If this has an identifier, add it to the scope stack.
3488  if (Name) {
3489    S = getNonFieldDeclScope(S);
3490    PushOnScopeChains(New, S);
3491  } else {
3492    CurContext->addDecl(New);
3493  }
3494
3495  return New;
3496}
3497
3498void Sema::ActOnTagStartDefinition(Scope *S, DeclTy *TagD) {
3499  AdjustDeclIfTemplate(TagD);
3500  TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3501
3502  // Enter the tag context.
3503  PushDeclContext(S, Tag);
3504
3505  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
3506    FieldCollector->StartClass();
3507
3508    if (Record->getIdentifier()) {
3509      // C++ [class]p2:
3510      //   [...] The class-name is also inserted into the scope of the
3511      //   class itself; this is known as the injected-class-name. For
3512      //   purposes of access checking, the injected-class-name is treated
3513      //   as if it were a public member name.
3514      RecordDecl *InjectedClassName
3515        = CXXRecordDecl::Create(Context, Record->getTagKind(),
3516                                CurContext, Record->getLocation(),
3517                                Record->getIdentifier(), Record);
3518      InjectedClassName->setImplicit();
3519      PushOnScopeChains(InjectedClassName, S);
3520    }
3521  }
3522}
3523
3524void Sema::ActOnTagFinishDefinition(Scope *S, DeclTy *TagD) {
3525  AdjustDeclIfTemplate(TagD);
3526  TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3527
3528  if (isa<CXXRecordDecl>(Tag))
3529    FieldCollector->FinishClass();
3530
3531  // Exit this scope of this tag's definition.
3532  PopDeclContext();
3533
3534  // Notify the consumer that we've defined a tag.
3535  Consumer.HandleTagDeclDefinition(Tag);
3536}
3537
3538bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
3539                          QualType FieldTy, const Expr *BitWidth) {
3540  // FIXME: 6.7.2.1p4 - verify the field type.
3541
3542  llvm::APSInt Value;
3543  if (VerifyIntegerConstantExpression(BitWidth, &Value))
3544    return true;
3545
3546  // Zero-width bitfield is ok for anonymous field.
3547  if (Value == 0 && FieldName)
3548    return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3549
3550  if (Value.isNegative())
3551    return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
3552
3553  uint64_t TypeSize = Context.getTypeSize(FieldTy);
3554  // FIXME: We won't need the 0 size once we check that the field type is valid.
3555  if (TypeSize && Value.getZExtValue() > TypeSize)
3556    return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3557       << FieldName << (unsigned)TypeSize;
3558
3559  return false;
3560}
3561
3562/// ActOnField - Each field of a struct/union/class is passed into this in order
3563/// to create a FieldDecl object for it.
3564Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
3565                               SourceLocation DeclStart,
3566                               Declarator &D, ExprTy *BitfieldWidth) {
3567  IdentifierInfo *II = D.getIdentifier();
3568  Expr *BitWidth = (Expr*)BitfieldWidth;
3569  SourceLocation Loc = DeclStart;
3570  RecordDecl *Record = (RecordDecl *)TagD;
3571  if (II) Loc = D.getIdentifierLoc();
3572
3573  // FIXME: Unnamed fields can be handled in various different ways, for
3574  // example, unnamed unions inject all members into the struct namespace!
3575
3576  QualType T = GetTypeForDeclarator(D, S);
3577  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3578  bool InvalidDecl = false;
3579
3580  // C99 6.7.2.1p8: A member of a structure or union may have any type other
3581  // than a variably modified type.
3582  if (T->isVariablyModifiedType()) {
3583    bool SizeIsNegative;
3584    QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
3585                                                           SizeIsNegative);
3586    if (!FixedTy.isNull()) {
3587      Diag(Loc, diag::warn_illegal_constant_array_size);
3588      T = FixedTy;
3589    } else {
3590      if (SizeIsNegative)
3591        Diag(Loc, diag::err_typecheck_negative_array_size);
3592      else
3593        Diag(Loc, diag::err_typecheck_field_variable_size);
3594      T = Context.IntTy;
3595      InvalidDecl = true;
3596    }
3597  }
3598
3599  if (BitWidth) {
3600    if (VerifyBitField(Loc, II, T, BitWidth))
3601      InvalidDecl = true;
3602  } else {
3603    // Not a bitfield.
3604
3605    // validate II.
3606
3607  }
3608
3609  FieldDecl *NewFD = FieldDecl::Create(Context, Record,
3610                                       Loc, II, T, BitWidth,
3611                                       D.getDeclSpec().getStorageClassSpec() ==
3612                                       DeclSpec::SCS_mutable);
3613
3614  if (II) {
3615    NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true);
3616    if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3617        && !isa<TagDecl>(PrevDecl)) {
3618      Diag(Loc, diag::err_duplicate_member) << II;
3619      Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3620      NewFD->setInvalidDecl();
3621      Record->setInvalidDecl();
3622    }
3623  }
3624
3625  if (getLangOptions().CPlusPlus) {
3626    CheckExtraCXXDefaultArguments(D);
3627    if (!T->isPODType())
3628      cast<CXXRecordDecl>(Record)->setPOD(false);
3629  }
3630
3631  ProcessDeclAttributes(NewFD, D);
3632  if (T.isObjCGCWeak())
3633    Diag(Loc, diag::warn_attribute_weak_on_field);
3634
3635  if (D.getInvalidType() || InvalidDecl)
3636    NewFD->setInvalidDecl();
3637
3638  if (II) {
3639    PushOnScopeChains(NewFD, S);
3640  } else
3641    Record->addDecl(NewFD);
3642
3643  return NewFD;
3644}
3645
3646/// TranslateIvarVisibility - Translate visibility from a token ID to an
3647///  AST enum value.
3648static ObjCIvarDecl::AccessControl
3649TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
3650  switch (ivarVisibility) {
3651  default: assert(0 && "Unknown visitibility kind");
3652  case tok::objc_private: return ObjCIvarDecl::Private;
3653  case tok::objc_public: return ObjCIvarDecl::Public;
3654  case tok::objc_protected: return ObjCIvarDecl::Protected;
3655  case tok::objc_package: return ObjCIvarDecl::Package;
3656  }
3657}
3658
3659/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3660/// in order to create an IvarDecl object for it.
3661Sema::DeclTy *Sema::ActOnIvar(Scope *S,
3662                              SourceLocation DeclStart,
3663                              Declarator &D, ExprTy *BitfieldWidth,
3664                              tok::ObjCKeywordKind Visibility) {
3665
3666  IdentifierInfo *II = D.getIdentifier();
3667  Expr *BitWidth = (Expr*)BitfieldWidth;
3668  SourceLocation Loc = DeclStart;
3669  if (II) Loc = D.getIdentifierLoc();
3670
3671  // FIXME: Unnamed fields can be handled in various different ways, for
3672  // example, unnamed unions inject all members into the struct namespace!
3673
3674  QualType T = GetTypeForDeclarator(D, S);
3675  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3676  bool InvalidDecl = false;
3677
3678  if (BitWidth) {
3679    // 6.7.2.1p3, 6.7.2.1p4
3680    if (VerifyBitField(Loc, II, T, BitWidth))
3681      InvalidDecl = true;
3682  } else {
3683    // Not a bitfield.
3684
3685    // validate II.
3686
3687  }
3688
3689  // C99 6.7.2.1p8: A member of a structure or union may have any type other
3690  // than a variably modified type.
3691  if (T->isVariablyModifiedType()) {
3692    Diag(Loc, diag::err_typecheck_ivar_variable_size);
3693    InvalidDecl = true;
3694  }
3695
3696  // Get the visibility (access control) for this ivar.
3697  ObjCIvarDecl::AccessControl ac =
3698    Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3699                                        : ObjCIvarDecl::None;
3700
3701  // Construct the decl.
3702  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, CurContext, Loc, II, T,ac,
3703                                             (Expr *)BitfieldWidth);
3704
3705  if (II) {
3706    NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true);
3707    if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3708        && !isa<TagDecl>(PrevDecl)) {
3709      Diag(Loc, diag::err_duplicate_member) << II;
3710      Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3711      NewID->setInvalidDecl();
3712    }
3713  }
3714
3715  // Process attributes attached to the ivar.
3716  ProcessDeclAttributes(NewID, D);
3717
3718  if (D.getInvalidType() || InvalidDecl)
3719    NewID->setInvalidDecl();
3720
3721  if (II) {
3722    // FIXME: When interfaces are DeclContexts, we'll need to add
3723    // these to the interface.
3724    S->AddDecl(NewID);
3725    IdResolver.AddDecl(NewID);
3726  }
3727
3728  return NewID;
3729}
3730
3731void Sema::ActOnFields(Scope* S,
3732                       SourceLocation RecLoc, DeclTy *RecDecl,
3733                       DeclTy **Fields, unsigned NumFields,
3734                       SourceLocation LBrac, SourceLocation RBrac,
3735                       AttributeList *Attr) {
3736  Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
3737  assert(EnclosingDecl && "missing record or interface decl");
3738
3739  // If the decl this is being inserted into is invalid, then it may be a
3740  // redeclaration or some other bogus case.  Don't try to add fields to it.
3741  if (EnclosingDecl->isInvalidDecl()) {
3742    // FIXME: Deallocate fields?
3743    return;
3744  }
3745
3746
3747  // Verify that all the fields are okay.
3748  unsigned NumNamedMembers = 0;
3749  llvm::SmallVector<FieldDecl*, 32> RecFields;
3750
3751  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
3752  for (unsigned i = 0; i != NumFields; ++i) {
3753    FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
3754    assert(FD && "missing field decl");
3755
3756    // Get the type for the field.
3757    Type *FDTy = FD->getType().getTypePtr();
3758
3759    if (!FD->isAnonymousStructOrUnion()) {
3760      // Remember all fields written by the user.
3761      RecFields.push_back(FD);
3762    }
3763
3764    // C99 6.7.2.1p2 - A field may not be a function type.
3765    if (FDTy->isFunctionType()) {
3766      Diag(FD->getLocation(), diag::err_field_declared_as_function)
3767        << FD->getDeclName();
3768      FD->setInvalidDecl();
3769      EnclosingDecl->setInvalidDecl();
3770      continue;
3771    }
3772    // C99 6.7.2.1p2 - A field may not be an incomplete type except...
3773    if (FDTy->isIncompleteType()) {
3774      if (!Record) {  // Incomplete ivar type is always an error.
3775        DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3776                               diag::err_field_incomplete);
3777        FD->setInvalidDecl();
3778        EnclosingDecl->setInvalidDecl();
3779        continue;
3780      }
3781      if (i != NumFields-1 ||                   // ... that the last member ...
3782          !Record->isStruct() ||  // ... of a structure ...
3783          !FDTy->isArrayType()) {         //... may have incomplete array type.
3784        DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3785                               diag::err_field_incomplete);
3786        FD->setInvalidDecl();
3787        EnclosingDecl->setInvalidDecl();
3788        continue;
3789      }
3790      if (NumNamedMembers < 1) {  //... must have more than named member ...
3791        Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
3792          << FD->getDeclName();
3793        FD->setInvalidDecl();
3794        EnclosingDecl->setInvalidDecl();
3795        continue;
3796      }
3797      // Okay, we have a legal flexible array member at the end of the struct.
3798      if (Record)
3799        Record->setHasFlexibleArrayMember(true);
3800    }
3801    /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3802    /// field of another structure or the element of an array.
3803    if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
3804      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3805        // If this is a member of a union, then entire union becomes "flexible".
3806        if (Record && Record->isUnion()) {
3807          Record->setHasFlexibleArrayMember(true);
3808        } else {
3809          // If this is a struct/class and this is not the last element, reject
3810          // it.  Note that GCC supports variable sized arrays in the middle of
3811          // structures.
3812          if (i != NumFields-1) {
3813            Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
3814              << FD->getDeclName();
3815            FD->setInvalidDecl();
3816            EnclosingDecl->setInvalidDecl();
3817            continue;
3818          }
3819          // We support flexible arrays at the end of structs in other structs
3820          // as an extension.
3821          Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
3822            << FD->getDeclName();
3823          if (Record)
3824            Record->setHasFlexibleArrayMember(true);
3825        }
3826      }
3827    }
3828    /// A field cannot be an Objective-c object
3829    if (FDTy->isObjCInterfaceType()) {
3830      Diag(FD->getLocation(), diag::err_statically_allocated_object);
3831      FD->setInvalidDecl();
3832      EnclosingDecl->setInvalidDecl();
3833      continue;
3834    }
3835    // Keep track of the number of named members.
3836    if (FD->getIdentifier())
3837      ++NumNamedMembers;
3838  }
3839
3840  // Okay, we successfully defined 'Record'.
3841  if (Record) {
3842    Record->completeDefinition(Context);
3843  } else {
3844    ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
3845    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
3846      ID->setIVarList(ClsFields, RecFields.size(), Context);
3847      ID->setLocEnd(RBrac);
3848
3849      // Must enforce the rule that ivars in the base classes may not be
3850      // duplicates.
3851      if (ID->getSuperClass()) {
3852        for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3853             IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3854          ObjCIvarDecl* Ivar = (*IVI);
3855          IdentifierInfo *II = Ivar->getIdentifier();
3856          ObjCIvarDecl* prevIvar = ID->getSuperClass()->lookupInstanceVariable(II);
3857          if (prevIvar) {
3858            Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3859            Diag(prevIvar->getLocation(), diag::note_previous_declaration);
3860          }
3861        }
3862      }
3863    } else if (ObjCImplementationDecl *IMPDecl =
3864                  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
3865      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3866      IMPDecl->setIVarList(ClsFields, RecFields.size(), Context);
3867      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
3868    }
3869  }
3870
3871  if (Attr)
3872    ProcessDeclAttributeList(Record, Attr);
3873}
3874
3875Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
3876                                      DeclTy *lastEnumConst,
3877                                      SourceLocation IdLoc, IdentifierInfo *Id,
3878                                      SourceLocation EqualLoc, ExprTy *val) {
3879  EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
3880  EnumConstantDecl *LastEnumConst =
3881    cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3882  Expr *Val = static_cast<Expr*>(val);
3883
3884  // The scope passed in may not be a decl scope.  Zip up the scope tree until
3885  // we find one that is.
3886  S = getNonFieldDeclScope(S);
3887
3888  // Verify that there isn't already something declared with this name in this
3889  // scope.
3890  NamedDecl *PrevDecl = LookupName(S, Id, LookupOrdinaryName);
3891  if (PrevDecl && PrevDecl->isTemplateParameter()) {
3892    // Maybe we will complain about the shadowed template parameter.
3893    DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3894    // Just pretend that we didn't see the previous declaration.
3895    PrevDecl = 0;
3896  }
3897
3898  if (PrevDecl) {
3899    // When in C++, we may get a TagDecl with the same name; in this case the
3900    // enum constant will 'hide' the tag.
3901    assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3902           "Received TagDecl when not in C++!");
3903    if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
3904      if (isa<EnumConstantDecl>(PrevDecl))
3905        Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
3906      else
3907        Diag(IdLoc, diag::err_redefinition) << Id;
3908      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3909      Val->Destroy(Context);
3910      return 0;
3911    }
3912  }
3913
3914  llvm::APSInt EnumVal(32);
3915  QualType EltTy;
3916  if (Val) {
3917    // Make sure to promote the operand type to int.
3918    UsualUnaryConversions(Val);
3919
3920    // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3921    SourceLocation ExpLoc;
3922    if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
3923      Val->Destroy(Context);
3924      Val = 0;  // Just forget about it.
3925    } else {
3926      EltTy = Val->getType();
3927    }
3928  }
3929
3930  if (!Val) {
3931    if (LastEnumConst) {
3932      // Assign the last value + 1.
3933      EnumVal = LastEnumConst->getInitVal();
3934      ++EnumVal;
3935
3936      // Check for overflow on increment.
3937      if (EnumVal < LastEnumConst->getInitVal())
3938        Diag(IdLoc, diag::warn_enum_value_overflow);
3939
3940      EltTy = LastEnumConst->getType();
3941    } else {
3942      // First value, set to zero.
3943      EltTy = Context.IntTy;
3944      EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
3945    }
3946  }
3947
3948  EnumConstantDecl *New =
3949    EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
3950                             Val, EnumVal);
3951
3952  // Register this decl in the current scope stack.
3953  PushOnScopeChains(New, S);
3954
3955  return New;
3956}
3957
3958// FIXME: For consistency with ActOnFields(), we should have the parser
3959// pass in the source location for the left/right braces.
3960void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
3961                         DeclTy **Elements, unsigned NumElements) {
3962  EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
3963  QualType EnumType = Context.getTypeDeclType(Enum);
3964
3965  // TODO: If the result value doesn't fit in an int, it must be a long or long
3966  // long value.  ISO C does not support this, but GCC does as an extension,
3967  // emit a warning.
3968  unsigned IntWidth = Context.Target.getIntWidth();
3969
3970  // Verify that all the values are okay, compute the size of the values, and
3971  // reverse the list.
3972  unsigned NumNegativeBits = 0;
3973  unsigned NumPositiveBits = 0;
3974
3975  // Keep track of whether all elements have type int.
3976  bool AllElementsInt = true;
3977
3978  for (unsigned i = 0; i != NumElements; ++i) {
3979    EnumConstantDecl *ECD =
3980      cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3981    if (!ECD) continue;  // Already issued a diagnostic.
3982
3983    // If the enum value doesn't fit in an int, emit an extension warning.
3984    const llvm::APSInt &InitVal = ECD->getInitVal();
3985    assert(InitVal.getBitWidth() >= IntWidth &&
3986           "Should have promoted value to int");
3987    if (InitVal.getBitWidth() > IntWidth) {
3988      llvm::APSInt V(InitVal);
3989      V.trunc(IntWidth);
3990      V.extend(InitVal.getBitWidth());
3991      if (V != InitVal)
3992        Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3993          << InitVal.toString(10);
3994    }
3995
3996    // Keep track of the size of positive and negative values.
3997    if (InitVal.isUnsigned() || InitVal.isNonNegative())
3998      NumPositiveBits = std::max(NumPositiveBits,
3999                                 (unsigned)InitVal.getActiveBits());
4000    else
4001      NumNegativeBits = std::max(NumNegativeBits,
4002                                 (unsigned)InitVal.getMinSignedBits());
4003
4004    // Keep track of whether every enum element has type int (very commmon).
4005    if (AllElementsInt)
4006      AllElementsInt = ECD->getType() == Context.IntTy;
4007  }
4008
4009  // Figure out the type that should be used for this enum.
4010  // FIXME: Support attribute(packed) on enums and -fshort-enums.
4011  QualType BestType;
4012  unsigned BestWidth;
4013
4014  if (NumNegativeBits) {
4015    // If there is a negative value, figure out the smallest integer type (of
4016    // int/long/longlong) that fits.
4017    if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
4018      BestType = Context.IntTy;
4019      BestWidth = IntWidth;
4020    } else {
4021      BestWidth = Context.Target.getLongWidth();
4022
4023      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
4024        BestType = Context.LongTy;
4025      else {
4026        BestWidth = Context.Target.getLongLongWidth();
4027
4028        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
4029          Diag(Enum->getLocation(), diag::warn_enum_too_large);
4030        BestType = Context.LongLongTy;
4031      }
4032    }
4033  } else {
4034    // If there is no negative value, figure out which of uint, ulong, ulonglong
4035    // fits.
4036    if (NumPositiveBits <= IntWidth) {
4037      BestType = Context.UnsignedIntTy;
4038      BestWidth = IntWidth;
4039    } else if (NumPositiveBits <=
4040               (BestWidth = Context.Target.getLongWidth())) {
4041      BestType = Context.UnsignedLongTy;
4042    } else {
4043      BestWidth = Context.Target.getLongLongWidth();
4044      assert(NumPositiveBits <= BestWidth &&
4045             "How could an initializer get larger than ULL?");
4046      BestType = Context.UnsignedLongLongTy;
4047    }
4048  }
4049
4050  // Loop over all of the enumerator constants, changing their types to match
4051  // the type of the enum if needed.
4052  for (unsigned i = 0; i != NumElements; ++i) {
4053    EnumConstantDecl *ECD =
4054      cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
4055    if (!ECD) continue;  // Already issued a diagnostic.
4056
4057    // Standard C says the enumerators have int type, but we allow, as an
4058    // extension, the enumerators to be larger than int size.  If each
4059    // enumerator value fits in an int, type it as an int, otherwise type it the
4060    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
4061    // that X has type 'int', not 'unsigned'.
4062    if (ECD->getType() == Context.IntTy) {
4063      // Make sure the init value is signed.
4064      llvm::APSInt IV = ECD->getInitVal();
4065      IV.setIsSigned(true);
4066      ECD->setInitVal(IV);
4067
4068      if (getLangOptions().CPlusPlus)
4069        // C++ [dcl.enum]p4: Following the closing brace of an
4070        // enum-specifier, each enumerator has the type of its
4071        // enumeration.
4072        ECD->setType(EnumType);
4073      continue;  // Already int type.
4074    }
4075
4076    // Determine whether the value fits into an int.
4077    llvm::APSInt InitVal = ECD->getInitVal();
4078    bool FitsInInt;
4079    if (InitVal.isUnsigned() || !InitVal.isNegative())
4080      FitsInInt = InitVal.getActiveBits() < IntWidth;
4081    else
4082      FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
4083
4084    // If it fits into an integer type, force it.  Otherwise force it to match
4085    // the enum decl type.
4086    QualType NewTy;
4087    unsigned NewWidth;
4088    bool NewSign;
4089    if (FitsInInt) {
4090      NewTy = Context.IntTy;
4091      NewWidth = IntWidth;
4092      NewSign = true;
4093    } else if (ECD->getType() == BestType) {
4094      // Already the right type!
4095      if (getLangOptions().CPlusPlus)
4096        // C++ [dcl.enum]p4: Following the closing brace of an
4097        // enum-specifier, each enumerator has the type of its
4098        // enumeration.
4099        ECD->setType(EnumType);
4100      continue;
4101    } else {
4102      NewTy = BestType;
4103      NewWidth = BestWidth;
4104      NewSign = BestType->isSignedIntegerType();
4105    }
4106
4107    // Adjust the APSInt value.
4108    InitVal.extOrTrunc(NewWidth);
4109    InitVal.setIsSigned(NewSign);
4110    ECD->setInitVal(InitVal);
4111
4112    // Adjust the Expr initializer and type.
4113    if (ECD->getInitExpr())
4114      ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy, ECD->getInitExpr(),
4115                                                      /*isLvalue=*/false));
4116    if (getLangOptions().CPlusPlus)
4117      // C++ [dcl.enum]p4: Following the closing brace of an
4118      // enum-specifier, each enumerator has the type of its
4119      // enumeration.
4120      ECD->setType(EnumType);
4121    else
4122      ECD->setType(NewTy);
4123  }
4124
4125  Enum->completeDefinition(Context, BestType);
4126}
4127
4128Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
4129                                          ExprArg expr) {
4130  StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
4131
4132  return FileScopeAsmDecl::Create(Context, CurContext, Loc, AsmString);
4133}
4134
4135