SemaDecl.cpp revision 4bde1e13d39e43581f7da872e4d7676ebf4a3ee7
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 "SemaInit.h"
16#include "Lookup.h"
17#include "clang/AST/APValue.h"
18#include "clang/AST/ASTConsumer.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/CXXInheritance.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/StmtCXX.h"
24#include "clang/Parse/DeclSpec.h"
25#include "clang/Parse/ParseDiagnostic.h"
26#include "clang/Parse/Template.h"
27#include "clang/Basic/PartialDiagnostic.h"
28#include "clang/Basic/SourceManager.h"
29#include "clang/Basic/TargetInfo.h"
30// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
31#include "clang/Lex/Preprocessor.h"
32#include "clang/Lex/HeaderSearch.h"
33#include "llvm/ADT/Triple.h"
34#include <algorithm>
35#include <cstring>
36#include <functional>
37using namespace clang;
38
39/// getDeclName - Return a pretty name for the specified decl if possible, or
40/// an empty string if not.  This is used for pretty crash reporting.
41std::string Sema::getDeclName(DeclPtrTy d) {
42  Decl *D = d.getAs<Decl>();
43  if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(D))
44    return DN->getQualifiedNameAsString();
45  return "";
46}
47
48Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(DeclPtrTy Ptr) {
49  return DeclGroupPtrTy::make(DeclGroupRef(Ptr.getAs<Decl>()));
50}
51
52/// \brief If the identifier refers to a type name within this scope,
53/// return the declaration of that type.
54///
55/// This routine performs ordinary name lookup of the identifier II
56/// within the given scope, with optional C++ scope specifier SS, to
57/// determine whether the name refers to a type. If so, returns an
58/// opaque pointer (actually a QualType) corresponding to that
59/// type. Otherwise, returns NULL.
60///
61/// If name lookup results in an ambiguity, this routine will complain
62/// and then return NULL.
63Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
64                                Scope *S, CXXScopeSpec *SS,
65                                bool isClassName,
66                                TypeTy *ObjectTypePtr) {
67  // Determine where we will perform name lookup.
68  DeclContext *LookupCtx = 0;
69  if (ObjectTypePtr) {
70    QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
71    if (ObjectType->isRecordType())
72      LookupCtx = computeDeclContext(ObjectType);
73  } else if (SS && SS->isNotEmpty()) {
74    LookupCtx = computeDeclContext(*SS, false);
75
76    if (!LookupCtx) {
77      if (isDependentScopeSpecifier(*SS)) {
78        // C++ [temp.res]p3:
79        //   A qualified-id that refers to a type and in which the
80        //   nested-name-specifier depends on a template-parameter (14.6.2)
81        //   shall be prefixed by the keyword typename to indicate that the
82        //   qualified-id denotes a type, forming an
83        //   elaborated-type-specifier (7.1.5.3).
84        //
85        // We therefore do not perform any name lookup if the result would
86        // refer to a member of an unknown specialization.
87        if (!isClassName)
88          return 0;
89
90        // We know from the grammar that this name refers to a type, so build a
91        // DependentNameType node to describe the type.
92        return CheckTypenameType(ETK_None,
93                                 (NestedNameSpecifier *)SS->getScopeRep(), II,
94                                 SourceLocation(), SS->getRange(), NameLoc
95                                 ).getAsOpaquePtr();
96      }
97
98      return 0;
99    }
100
101    if (!LookupCtx->isDependentContext() &&
102        RequireCompleteDeclContext(*SS, LookupCtx))
103      return 0;
104  }
105
106  // FIXME: LookupNestedNameSpecifierName isn't the right kind of
107  // lookup for class-names.
108  LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
109                                      LookupOrdinaryName;
110  LookupResult Result(*this, &II, NameLoc, Kind);
111  if (LookupCtx) {
112    // Perform "qualified" name lookup into the declaration context we
113    // computed, which is either the type of the base of a member access
114    // expression or the declaration context associated with a prior
115    // nested-name-specifier.
116    LookupQualifiedName(Result, LookupCtx);
117
118    if (ObjectTypePtr && Result.empty()) {
119      // C++ [basic.lookup.classref]p3:
120      //   If the unqualified-id is ~type-name, the type-name is looked up
121      //   in the context of the entire postfix-expression. If the type T of
122      //   the object expression is of a class type C, the type-name is also
123      //   looked up in the scope of class C. At least one of the lookups shall
124      //   find a name that refers to (possibly cv-qualified) T.
125      LookupName(Result, S);
126    }
127  } else {
128    // Perform unqualified name lookup.
129    LookupName(Result, S);
130  }
131
132  NamedDecl *IIDecl = 0;
133  switch (Result.getResultKind()) {
134  case LookupResult::NotFound:
135  case LookupResult::NotFoundInCurrentInstantiation:
136  case LookupResult::FoundOverloaded:
137  case LookupResult::FoundUnresolvedValue:
138    Result.suppressDiagnostics();
139    return 0;
140
141  case LookupResult::Ambiguous:
142    // Recover from type-hiding ambiguities by hiding the type.  We'll
143    // do the lookup again when looking for an object, and we can
144    // diagnose the error then.  If we don't do this, then the error
145    // about hiding the type will be immediately followed by an error
146    // that only makes sense if the identifier was treated like a type.
147    if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
148      Result.suppressDiagnostics();
149      return 0;
150    }
151
152    // Look to see if we have a type anywhere in the list of results.
153    for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
154         Res != ResEnd; ++Res) {
155      if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
156        if (!IIDecl ||
157            (*Res)->getLocation().getRawEncoding() <
158              IIDecl->getLocation().getRawEncoding())
159          IIDecl = *Res;
160      }
161    }
162
163    if (!IIDecl) {
164      // None of the entities we found is a type, so there is no way
165      // to even assume that the result is a type. In this case, don't
166      // complain about the ambiguity. The parser will either try to
167      // perform this lookup again (e.g., as an object name), which
168      // will produce the ambiguity, or will complain that it expected
169      // a type name.
170      Result.suppressDiagnostics();
171      return 0;
172    }
173
174    // We found a type within the ambiguous lookup; diagnose the
175    // ambiguity and then return that type. This might be the right
176    // answer, or it might not be, but it suppresses any attempt to
177    // perform the name lookup again.
178    break;
179
180  case LookupResult::Found:
181    IIDecl = Result.getFoundDecl();
182    break;
183  }
184
185  assert(IIDecl && "Didn't find decl");
186
187  QualType T;
188  if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
189    DiagnoseUseOfDecl(IIDecl, NameLoc);
190
191    if (T.isNull())
192      T = Context.getTypeDeclType(TD);
193
194    if (SS)
195      T = getElaboratedType(ETK_None, *SS, T);
196
197  } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
198    T = Context.getObjCInterfaceType(IDecl);
199  } else if (UnresolvedUsingTypenameDecl *UUDecl =
200               dyn_cast<UnresolvedUsingTypenameDecl>(IIDecl)) {
201    // FIXME: preserve source structure information.
202    T = Context.getDependentNameType(ETK_None,
203                                     UUDecl->getTargetNestedNameSpecifier(),
204                                     &II);
205  } else {
206    // If it's not plausibly a type, suppress diagnostics.
207    Result.suppressDiagnostics();
208    return 0;
209  }
210
211  return T.getAsOpaquePtr();
212}
213
214/// isTagName() - This method is called *for error recovery purposes only*
215/// to determine if the specified name is a valid tag name ("struct foo").  If
216/// so, this returns the TST for the tag corresponding to it (TST_enum,
217/// TST_union, TST_struct, TST_class).  This is used to diagnose cases in C
218/// where the user forgot to specify the tag.
219DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
220  // Do a tag name lookup in this scope.
221  LookupResult R(*this, &II, SourceLocation(), LookupTagName);
222  LookupName(R, S, false);
223  R.suppressDiagnostics();
224  if (R.getResultKind() == LookupResult::Found)
225    if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
226      switch (TD->getTagKind()) {
227      default:         return DeclSpec::TST_unspecified;
228      case TTK_Struct: return DeclSpec::TST_struct;
229      case TTK_Union:  return DeclSpec::TST_union;
230      case TTK_Class:  return DeclSpec::TST_class;
231      case TTK_Enum:   return DeclSpec::TST_enum;
232      }
233    }
234
235  return DeclSpec::TST_unspecified;
236}
237
238bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II,
239                                   SourceLocation IILoc,
240                                   Scope *S,
241                                   CXXScopeSpec *SS,
242                                   TypeTy *&SuggestedType) {
243  // We don't have anything to suggest (yet).
244  SuggestedType = 0;
245
246  // There may have been a typo in the name of the type. Look up typo
247  // results, in case we have something that we can suggest.
248  LookupResult Lookup(*this, &II, IILoc, LookupOrdinaryName,
249                      NotForRedeclaration);
250
251  if (DeclarationName Corrected = CorrectTypo(Lookup, S, SS, 0, 0, CTC_Type)) {
252    if (NamedDecl *Result = Lookup.getAsSingle<NamedDecl>()) {
253      if ((isa<TypeDecl>(Result) || isa<ObjCInterfaceDecl>(Result)) &&
254          !Result->isInvalidDecl()) {
255        // We found a similarly-named type or interface; suggest that.
256        if (!SS || !SS->isSet())
257          Diag(IILoc, diag::err_unknown_typename_suggest)
258            << &II << Lookup.getLookupName()
259            << FixItHint::CreateReplacement(SourceRange(IILoc),
260                                            Result->getNameAsString());
261        else if (DeclContext *DC = computeDeclContext(*SS, false))
262          Diag(IILoc, diag::err_unknown_nested_typename_suggest)
263            << &II << DC << Lookup.getLookupName() << SS->getRange()
264            << FixItHint::CreateReplacement(SourceRange(IILoc),
265                                            Result->getNameAsString());
266        else
267          llvm_unreachable("could not have corrected a typo here");
268
269        Diag(Result->getLocation(), diag::note_previous_decl)
270          << Result->getDeclName();
271
272        SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS);
273        return true;
274      }
275    } else if (Lookup.empty()) {
276      // We corrected to a keyword.
277      // FIXME: Actually recover with the keyword we suggest, and emit a fix-it.
278      Diag(IILoc, diag::err_unknown_typename_suggest)
279        << &II << Corrected;
280      return true;
281    }
282  }
283
284  if (getLangOptions().CPlusPlus) {
285    // See if II is a class template that the user forgot to pass arguments to.
286    UnqualifiedId Name;
287    Name.setIdentifier(&II, IILoc);
288    CXXScopeSpec EmptySS;
289    TemplateTy TemplateResult;
290    bool MemberOfUnknownSpecialization;
291    if (isTemplateName(S, SS ? *SS : EmptySS, Name, 0, true, TemplateResult,
292                       MemberOfUnknownSpecialization) == TNK_Type_template) {
293      TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
294      Diag(IILoc, diag::err_template_missing_args) << TplName;
295      if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
296        Diag(TplDecl->getLocation(), diag::note_template_decl_here)
297          << TplDecl->getTemplateParameters()->getSourceRange();
298      }
299      return true;
300    }
301  }
302
303  // FIXME: Should we move the logic that tries to recover from a missing tag
304  // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
305
306  if (!SS || (!SS->isSet() && !SS->isInvalid()))
307    Diag(IILoc, diag::err_unknown_typename) << &II;
308  else if (DeclContext *DC = computeDeclContext(*SS, false))
309    Diag(IILoc, diag::err_typename_nested_not_found)
310      << &II << DC << SS->getRange();
311  else if (isDependentScopeSpecifier(*SS)) {
312    Diag(SS->getRange().getBegin(), diag::err_typename_missing)
313      << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
314      << SourceRange(SS->getRange().getBegin(), IILoc)
315      << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
316    SuggestedType = ActOnTypenameType(SourceLocation(), *SS, II, IILoc).get();
317  } else {
318    assert(SS && SS->isInvalid() &&
319           "Invalid scope specifier has already been diagnosed");
320  }
321
322  return true;
323}
324
325// Determines the context to return to after temporarily entering a
326// context.  This depends in an unnecessarily complicated way on the
327// exact ordering of callbacks from the parser.
328DeclContext *Sema::getContainingDC(DeclContext *DC) {
329
330  // Functions defined inline within classes aren't parsed until we've
331  // finished parsing the top-level class, so the top-level class is
332  // the context we'll need to return to.
333  if (isa<FunctionDecl>(DC)) {
334    DC = DC->getLexicalParent();
335
336    // A function not defined within a class will always return to its
337    // lexical context.
338    if (!isa<CXXRecordDecl>(DC))
339      return DC;
340
341    // A C++ inline method/friend is parsed *after* the topmost class
342    // it was declared in is fully parsed ("complete");  the topmost
343    // class is the context we need to return to.
344    while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
345      DC = RD;
346
347    // Return the declaration context of the topmost class the inline method is
348    // declared in.
349    return DC;
350  }
351
352  if (isa<ObjCMethodDecl>(DC))
353    return Context.getTranslationUnitDecl();
354
355  return DC->getLexicalParent();
356}
357
358void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
359  assert(getContainingDC(DC) == CurContext &&
360      "The next DeclContext should be lexically contained in the current one.");
361  CurContext = DC;
362  S->setEntity(DC);
363}
364
365void Sema::PopDeclContext() {
366  assert(CurContext && "DeclContext imbalance!");
367
368  CurContext = getContainingDC(CurContext);
369}
370
371/// EnterDeclaratorContext - Used when we must lookup names in the context
372/// of a declarator's nested name specifier.
373///
374void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
375  // C++0x [basic.lookup.unqual]p13:
376  //   A name used in the definition of a static data member of class
377  //   X (after the qualified-id of the static member) is looked up as
378  //   if the name was used in a member function of X.
379  // C++0x [basic.lookup.unqual]p14:
380  //   If a variable member of a namespace is defined outside of the
381  //   scope of its namespace then any name used in the definition of
382  //   the variable member (after the declarator-id) is looked up as
383  //   if the definition of the variable member occurred in its
384  //   namespace.
385  // Both of these imply that we should push a scope whose context
386  // is the semantic context of the declaration.  We can't use
387  // PushDeclContext here because that context is not necessarily
388  // lexically contained in the current context.  Fortunately,
389  // the containing scope should have the appropriate information.
390
391  assert(!S->getEntity() && "scope already has entity");
392
393#ifndef NDEBUG
394  Scope *Ancestor = S->getParent();
395  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
396  assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
397#endif
398
399  CurContext = DC;
400  S->setEntity(DC);
401}
402
403void Sema::ExitDeclaratorContext(Scope *S) {
404  assert(S->getEntity() == CurContext && "Context imbalance!");
405
406  // Switch back to the lexical context.  The safety of this is
407  // enforced by an assert in EnterDeclaratorContext.
408  Scope *Ancestor = S->getParent();
409  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
410  CurContext = (DeclContext*) Ancestor->getEntity();
411
412  // We don't need to do anything with the scope, which is going to
413  // disappear.
414}
415
416/// \brief Determine whether we allow overloading of the function
417/// PrevDecl with another declaration.
418///
419/// This routine determines whether overloading is possible, not
420/// whether some new function is actually an overload. It will return
421/// true in C++ (where we can always provide overloads) or, as an
422/// extension, in C when the previous function is already an
423/// overloaded function declaration or has the "overloadable"
424/// attribute.
425static bool AllowOverloadingOfFunction(LookupResult &Previous,
426                                       ASTContext &Context) {
427  if (Context.getLangOptions().CPlusPlus)
428    return true;
429
430  if (Previous.getResultKind() == LookupResult::FoundOverloaded)
431    return true;
432
433  return (Previous.getResultKind() == LookupResult::Found
434          && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
435}
436
437/// Add this decl to the scope shadowed decl chains.
438void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
439  // Move up the scope chain until we find the nearest enclosing
440  // non-transparent context. The declaration will be introduced into this
441  // scope.
442  while (S->getEntity() &&
443         ((DeclContext *)S->getEntity())->isTransparentContext())
444    S = S->getParent();
445
446  // Add scoped declarations into their context, so that they can be
447  // found later. Declarations without a context won't be inserted
448  // into any context.
449  if (AddToContext)
450    CurContext->addDecl(D);
451
452  // Out-of-line definitions shouldn't be pushed into scope in C++.
453  // Out-of-line variable and function definitions shouldn't even in C.
454  if ((getLangOptions().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
455      D->isOutOfLine())
456    return;
457
458  // Template instantiations should also not be pushed into scope.
459  if (isa<FunctionDecl>(D) &&
460      cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
461    return;
462
463  // If this replaces anything in the current scope,
464  IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
465                               IEnd = IdResolver.end();
466  for (; I != IEnd; ++I) {
467    if (S->isDeclScope(DeclPtrTy::make(*I)) && D->declarationReplaces(*I)) {
468      S->RemoveDecl(DeclPtrTy::make(*I));
469      IdResolver.RemoveDecl(*I);
470
471      // Should only need to replace one decl.
472      break;
473    }
474  }
475
476  S->AddDecl(DeclPtrTy::make(D));
477  IdResolver.AddDecl(D);
478}
479
480bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S) {
481  return IdResolver.isDeclInScope(D, Ctx, Context, S);
482}
483
484static bool isOutOfScopePreviousDeclaration(NamedDecl *,
485                                            DeclContext*,
486                                            ASTContext&);
487
488/// Filters out lookup results that don't fall within the given scope
489/// as determined by isDeclInScope.
490static void FilterLookupForScope(Sema &SemaRef, LookupResult &R,
491                                 DeclContext *Ctx, Scope *S,
492                                 bool ConsiderLinkage) {
493  LookupResult::Filter F = R.makeFilter();
494  while (F.hasNext()) {
495    NamedDecl *D = F.next();
496
497    if (SemaRef.isDeclInScope(D, Ctx, S))
498      continue;
499
500    if (ConsiderLinkage &&
501        isOutOfScopePreviousDeclaration(D, Ctx, SemaRef.Context))
502      continue;
503
504    F.erase();
505  }
506
507  F.done();
508}
509
510static bool isUsingDecl(NamedDecl *D) {
511  return isa<UsingShadowDecl>(D) ||
512         isa<UnresolvedUsingTypenameDecl>(D) ||
513         isa<UnresolvedUsingValueDecl>(D);
514}
515
516/// Removes using shadow declarations from the lookup results.
517static void RemoveUsingDecls(LookupResult &R) {
518  LookupResult::Filter F = R.makeFilter();
519  while (F.hasNext())
520    if (isUsingDecl(F.next()))
521      F.erase();
522
523  F.done();
524}
525
526static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
527  if (D->isInvalidDecl())
528    return false;
529
530  if (D->isUsed() || D->hasAttr<UnusedAttr>())
531    return false;
532
533  // White-list anything that isn't a local variable.
534  if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
535      !D->getDeclContext()->isFunctionOrMethod())
536    return false;
537
538  // Types of valid local variables should be complete, so this should succeed.
539  if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
540
541    // White-list anything with an __attribute__((unused)) type.
542    QualType Ty = VD->getType();
543
544    // Only look at the outermost level of typedef.
545    if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) {
546      if (TT->getDecl()->hasAttr<UnusedAttr>())
547        return false;
548    }
549
550    // If we failed to complete the type for some reason, or if the type is
551    // dependent, don't diagnose the variable.
552    if (Ty->isIncompleteType() || Ty->isDependentType())
553      return false;
554
555    if (const TagType *TT = Ty->getAs<TagType>()) {
556      const TagDecl *Tag = TT->getDecl();
557      if (Tag->hasAttr<UnusedAttr>())
558        return false;
559
560      if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
561        // FIXME: Checking for the presence of a user-declared constructor
562        // isn't completely accurate; we'd prefer to check that the initializer
563        // has no side effects.
564        if (RD->hasUserDeclaredConstructor() || !RD->hasTrivialDestructor())
565          return false;
566      }
567    }
568
569    // TODO: __attribute__((unused)) templates?
570  }
571
572  return true;
573}
574
575void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
576  if (!ShouldDiagnoseUnusedDecl(D))
577    return;
578
579  if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
580    Diag(D->getLocation(), diag::warn_unused_exception_param)
581    << D->getDeclName();
582  else
583    Diag(D->getLocation(), diag::warn_unused_variable)
584    << D->getDeclName();
585}
586
587void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
588  if (S->decl_empty()) return;
589  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
590         "Scope shouldn't contain decls!");
591
592  for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
593       I != E; ++I) {
594    Decl *TmpD = (*I).getAs<Decl>();
595    assert(TmpD && "This decl didn't get pushed??");
596
597    assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
598    NamedDecl *D = cast<NamedDecl>(TmpD);
599
600    if (!D->getDeclName()) continue;
601
602    // Diagnose unused variables in this scope.
603    if (S->getNumErrorsAtStart() == getDiagnostics().getNumErrors())
604      DiagnoseUnusedDecl(D);
605
606    // Remove this name from our lexical scope.
607    IdResolver.RemoveDecl(D);
608  }
609}
610
611/// \brief Look for an Objective-C class in the translation unit.
612///
613/// \param Id The name of the Objective-C class we're looking for. If
614/// typo-correction fixes this name, the Id will be updated
615/// to the fixed name.
616///
617/// \param IdLoc The location of the name in the translation unit.
618///
619/// \param TypoCorrection If true, this routine will attempt typo correction
620/// if there is no class with the given name.
621///
622/// \returns The declaration of the named Objective-C class, or NULL if the
623/// class could not be found.
624ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
625                                              SourceLocation IdLoc,
626                                              bool TypoCorrection) {
627  // The third "scope" argument is 0 since we aren't enabling lazy built-in
628  // creation from this context.
629  NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
630
631  if (!IDecl && TypoCorrection) {
632    // Perform typo correction at the given location, but only if we
633    // find an Objective-C class name.
634    LookupResult R(*this, Id, IdLoc, LookupOrdinaryName);
635    if (CorrectTypo(R, TUScope, 0, 0, false, CTC_NoKeywords) &&
636        (IDecl = R.getAsSingle<ObjCInterfaceDecl>())) {
637      Diag(IdLoc, diag::err_undef_interface_suggest)
638        << Id << IDecl->getDeclName()
639        << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
640      Diag(IDecl->getLocation(), diag::note_previous_decl)
641        << IDecl->getDeclName();
642
643      Id = IDecl->getIdentifier();
644    }
645  }
646
647  return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
648}
649
650/// getNonFieldDeclScope - Retrieves the innermost scope, starting
651/// from S, where a non-field would be declared. This routine copes
652/// with the difference between C and C++ scoping rules in structs and
653/// unions. For example, the following code is well-formed in C but
654/// ill-formed in C++:
655/// @code
656/// struct S6 {
657///   enum { BAR } e;
658/// };
659///
660/// void test_S6() {
661///   struct S6 a;
662///   a.e = BAR;
663/// }
664/// @endcode
665/// For the declaration of BAR, this routine will return a different
666/// scope. The scope S will be the scope of the unnamed enumeration
667/// within S6. In C++, this routine will return the scope associated
668/// with S6, because the enumeration's scope is a transparent
669/// context but structures can contain non-field names. In C, this
670/// routine will return the translation unit scope, since the
671/// enumeration's scope is a transparent context and structures cannot
672/// contain non-field names.
673Scope *Sema::getNonFieldDeclScope(Scope *S) {
674  while (((S->getFlags() & Scope::DeclScope) == 0) ||
675         (S->getEntity() &&
676          ((DeclContext *)S->getEntity())->isTransparentContext()) ||
677         (S->isClassScope() && !getLangOptions().CPlusPlus))
678    S = S->getParent();
679  return S;
680}
681
682void Sema::InitBuiltinVaListType() {
683  if (!Context.getBuiltinVaListType().isNull())
684    return;
685
686  IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
687  NamedDecl *VaDecl = LookupSingleName(TUScope, VaIdent, SourceLocation(),
688                                       LookupOrdinaryName, ForRedeclaration);
689  TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
690  Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
691}
692
693/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
694/// file scope.  lazily create a decl for it. ForRedeclaration is true
695/// if we're creating this built-in in anticipation of redeclaring the
696/// built-in.
697NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
698                                     Scope *S, bool ForRedeclaration,
699                                     SourceLocation Loc) {
700  Builtin::ID BID = (Builtin::ID)bid;
701
702  if (Context.BuiltinInfo.hasVAListUse(BID))
703    InitBuiltinVaListType();
704
705  ASTContext::GetBuiltinTypeError Error;
706  QualType R = Context.GetBuiltinType(BID, Error);
707  switch (Error) {
708  case ASTContext::GE_None:
709    // Okay
710    break;
711
712  case ASTContext::GE_Missing_stdio:
713    if (ForRedeclaration)
714      Diag(Loc, diag::err_implicit_decl_requires_stdio)
715        << Context.BuiltinInfo.GetName(BID);
716    return 0;
717
718  case ASTContext::GE_Missing_setjmp:
719    if (ForRedeclaration)
720      Diag(Loc, diag::err_implicit_decl_requires_setjmp)
721        << Context.BuiltinInfo.GetName(BID);
722    return 0;
723  }
724
725  if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
726    Diag(Loc, diag::ext_implicit_lib_function_decl)
727      << Context.BuiltinInfo.GetName(BID)
728      << R;
729    if (Context.BuiltinInfo.getHeaderName(BID) &&
730        Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl)
731          != Diagnostic::Ignored)
732      Diag(Loc, diag::note_please_include_header)
733        << Context.BuiltinInfo.getHeaderName(BID)
734        << Context.BuiltinInfo.GetName(BID);
735  }
736
737  FunctionDecl *New = FunctionDecl::Create(Context,
738                                           Context.getTranslationUnitDecl(),
739                                           Loc, II, R, /*TInfo=*/0,
740                                           FunctionDecl::Extern,
741                                           FunctionDecl::None, false,
742                                           /*hasPrototype=*/true);
743  New->setImplicit();
744
745  // Create Decl objects for each parameter, adding them to the
746  // FunctionDecl.
747  if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
748    llvm::SmallVector<ParmVarDecl*, 16> Params;
749    for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
750      Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
751                                           FT->getArgType(i), /*TInfo=*/0,
752                                           VarDecl::None, VarDecl::None, 0));
753    New->setParams(Params.data(), Params.size());
754  }
755
756  AddKnownFunctionAttributes(New);
757
758  // TUScope is the translation-unit scope to insert this function into.
759  // FIXME: This is hideous. We need to teach PushOnScopeChains to
760  // relate Scopes to DeclContexts, and probably eliminate CurContext
761  // entirely, but we're not there yet.
762  DeclContext *SavedContext = CurContext;
763  CurContext = Context.getTranslationUnitDecl();
764  PushOnScopeChains(New, TUScope);
765  CurContext = SavedContext;
766  return New;
767}
768
769/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the
770/// same name and scope as a previous declaration 'Old'.  Figure out
771/// how to resolve this situation, merging decls or emitting
772/// diagnostics as appropriate. If there was an error, set New to be invalid.
773///
774void Sema::MergeTypeDefDecl(TypedefDecl *New, LookupResult &OldDecls) {
775  // If the new decl is known invalid already, don't bother doing any
776  // merging checks.
777  if (New->isInvalidDecl()) return;
778
779  // Allow multiple definitions for ObjC built-in typedefs.
780  // FIXME: Verify the underlying types are equivalent!
781  if (getLangOptions().ObjC1) {
782    const IdentifierInfo *TypeID = New->getIdentifier();
783    switch (TypeID->getLength()) {
784    default: break;
785    case 2:
786      if (!TypeID->isStr("id"))
787        break;
788      Context.ObjCIdRedefinitionType = New->getUnderlyingType();
789      // Install the built-in type for 'id', ignoring the current definition.
790      New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
791      return;
792    case 5:
793      if (!TypeID->isStr("Class"))
794        break;
795      Context.ObjCClassRedefinitionType = New->getUnderlyingType();
796      // Install the built-in type for 'Class', ignoring the current definition.
797      New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
798      return;
799    case 3:
800      if (!TypeID->isStr("SEL"))
801        break;
802      Context.ObjCSelRedefinitionType = New->getUnderlyingType();
803      // Install the built-in type for 'SEL', ignoring the current definition.
804      New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
805      return;
806    case 8:
807      if (!TypeID->isStr("Protocol"))
808        break;
809      Context.setObjCProtoType(New->getUnderlyingType());
810      return;
811    }
812    // Fall through - the typedef name was not a builtin type.
813  }
814
815  // Verify the old decl was also a type.
816  TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
817  if (!Old) {
818    Diag(New->getLocation(), diag::err_redefinition_different_kind)
819      << New->getDeclName();
820
821    NamedDecl *OldD = OldDecls.getRepresentativeDecl();
822    if (OldD->getLocation().isValid())
823      Diag(OldD->getLocation(), diag::note_previous_definition);
824
825    return New->setInvalidDecl();
826  }
827
828  // If the old declaration is invalid, just give up here.
829  if (Old->isInvalidDecl())
830    return New->setInvalidDecl();
831
832  // Determine the "old" type we'll use for checking and diagnostics.
833  QualType OldType;
834  if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
835    OldType = OldTypedef->getUnderlyingType();
836  else
837    OldType = Context.getTypeDeclType(Old);
838
839  // If the typedef types are not identical, reject them in all languages and
840  // with any extensions enabled.
841
842  if (OldType != New->getUnderlyingType() &&
843      Context.getCanonicalType(OldType) !=
844      Context.getCanonicalType(New->getUnderlyingType())) {
845    Diag(New->getLocation(), diag::err_redefinition_different_typedef)
846      << New->getUnderlyingType() << OldType;
847    if (Old->getLocation().isValid())
848      Diag(Old->getLocation(), diag::note_previous_definition);
849    return New->setInvalidDecl();
850  }
851
852  // The types match.  Link up the redeclaration chain if the old
853  // declaration was a typedef.
854  // FIXME: this is a potential source of wierdness if the type
855  // spellings don't match exactly.
856  if (isa<TypedefDecl>(Old))
857    New->setPreviousDeclaration(cast<TypedefDecl>(Old));
858
859  if (getLangOptions().Microsoft)
860    return;
861
862  if (getLangOptions().CPlusPlus) {
863    // C++ [dcl.typedef]p2:
864    //   In a given non-class scope, a typedef specifier can be used to
865    //   redefine the name of any type declared in that scope to refer
866    //   to the type to which it already refers.
867    if (!isa<CXXRecordDecl>(CurContext))
868      return;
869
870    // C++0x [dcl.typedef]p4:
871    //   In a given class scope, a typedef specifier can be used to redefine
872    //   any class-name declared in that scope that is not also a typedef-name
873    //   to refer to the type to which it already refers.
874    //
875    // This wording came in via DR424, which was a correction to the
876    // wording in DR56, which accidentally banned code like:
877    //
878    //   struct S {
879    //     typedef struct A { } A;
880    //   };
881    //
882    // in the C++03 standard. We implement the C++0x semantics, which
883    // allow the above but disallow
884    //
885    //   struct S {
886    //     typedef int I;
887    //     typedef int I;
888    //   };
889    //
890    // since that was the intent of DR56.
891    if (!isa<TypedefDecl >(Old))
892      return;
893
894    Diag(New->getLocation(), diag::err_redefinition)
895      << New->getDeclName();
896    Diag(Old->getLocation(), diag::note_previous_definition);
897    return New->setInvalidDecl();
898  }
899
900  // If we have a redefinition of a typedef in C, emit a warning.  This warning
901  // is normally mapped to an error, but can be controlled with
902  // -Wtypedef-redefinition.  If either the original or the redefinition is
903  // in a system header, don't emit this for compatibility with GCC.
904  if (getDiagnostics().getSuppressSystemWarnings() &&
905      (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
906       Context.getSourceManager().isInSystemHeader(New->getLocation())))
907    return;
908
909  Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
910    << New->getDeclName();
911  Diag(Old->getLocation(), diag::note_previous_definition);
912  return;
913}
914
915/// DeclhasAttr - returns true if decl Declaration already has the target
916/// attribute.
917static bool
918DeclHasAttr(const Decl *decl, const Attr *target) {
919  for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
920    if (attr->getKind() == target->getKind())
921      return true;
922
923  return false;
924}
925
926/// MergeAttributes - append attributes from the Old decl to the New one.
927static void MergeAttributes(Decl *New, Decl *Old, ASTContext &C) {
928  for (const Attr *attr = Old->getAttrs(); attr; attr = attr->getNext()) {
929    if (!DeclHasAttr(New, attr) && attr->isMerged()) {
930      Attr *NewAttr = attr->clone(C);
931      NewAttr->setInherited(true);
932      New->addAttr(NewAttr);
933    }
934  }
935}
936
937/// Used in MergeFunctionDecl to keep track of function parameters in
938/// C.
939struct GNUCompatibleParamWarning {
940  ParmVarDecl *OldParm;
941  ParmVarDecl *NewParm;
942  QualType PromotedType;
943};
944
945
946/// getSpecialMember - get the special member enum for a method.
947Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
948  if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
949    if (Ctor->isCopyConstructor())
950      return Sema::CXXCopyConstructor;
951
952    return Sema::CXXConstructor;
953  }
954
955  if (isa<CXXDestructorDecl>(MD))
956    return Sema::CXXDestructor;
957
958  assert(MD->isCopyAssignment() && "Must have copy assignment operator");
959  return Sema::CXXCopyAssignment;
960}
961
962/// canREdefineFunction - checks if a function can be redefined. Currently,
963/// only extern inline functions can be redefined, and even then only in
964/// GNU89 mode.
965static bool canRedefineFunction(const FunctionDecl *FD,
966                                const LangOptions& LangOpts) {
967  return (LangOpts.GNUMode && !LangOpts.C99 && !LangOpts.CPlusPlus &&
968          FD->isInlineSpecified() &&
969          FD->getStorageClass() == FunctionDecl::Extern);
970}
971
972/// MergeFunctionDecl - We just parsed a function 'New' from
973/// declarator D which has the same name and scope as a previous
974/// declaration 'Old'.  Figure out how to resolve this situation,
975/// merging decls or emitting diagnostics as appropriate.
976///
977/// In C++, New and Old must be declarations that are not
978/// overloaded. Use IsOverload to determine whether New and Old are
979/// overloaded, and to select the Old declaration that New should be
980/// merged with.
981///
982/// Returns true if there was an error, false otherwise.
983bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
984  // Verify the old decl was also a function.
985  FunctionDecl *Old = 0;
986  if (FunctionTemplateDecl *OldFunctionTemplate
987        = dyn_cast<FunctionTemplateDecl>(OldD))
988    Old = OldFunctionTemplate->getTemplatedDecl();
989  else
990    Old = dyn_cast<FunctionDecl>(OldD);
991  if (!Old) {
992    if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
993      Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
994      Diag(Shadow->getTargetDecl()->getLocation(),
995           diag::note_using_decl_target);
996      Diag(Shadow->getUsingDecl()->getLocation(),
997           diag::note_using_decl) << 0;
998      return true;
999    }
1000
1001    Diag(New->getLocation(), diag::err_redefinition_different_kind)
1002      << New->getDeclName();
1003    Diag(OldD->getLocation(), diag::note_previous_definition);
1004    return true;
1005  }
1006
1007  // Determine whether the previous declaration was a definition,
1008  // implicit declaration, or a declaration.
1009  diag::kind PrevDiag;
1010  if (Old->isThisDeclarationADefinition())
1011    PrevDiag = diag::note_previous_definition;
1012  else if (Old->isImplicit())
1013    PrevDiag = diag::note_previous_implicit_declaration;
1014  else
1015    PrevDiag = diag::note_previous_declaration;
1016
1017  QualType OldQType = Context.getCanonicalType(Old->getType());
1018  QualType NewQType = Context.getCanonicalType(New->getType());
1019
1020  // Don't complain about this if we're in GNU89 mode and the old function
1021  // is an extern inline function.
1022  if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
1023      New->getStorageClass() == FunctionDecl::Static &&
1024      Old->getStorageClass() != FunctionDecl::Static &&
1025      !canRedefineFunction(Old, getLangOptions())) {
1026    Diag(New->getLocation(), diag::err_static_non_static)
1027      << New;
1028    Diag(Old->getLocation(), PrevDiag);
1029    return true;
1030  }
1031
1032  // If a function is first declared with a calling convention, but is
1033  // later declared or defined without one, the second decl assumes the
1034  // calling convention of the first.
1035  //
1036  // For the new decl, we have to look at the NON-canonical type to tell the
1037  // difference between a function that really doesn't have a calling
1038  // convention and one that is declared cdecl. That's because in
1039  // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
1040  // because it is the default calling convention.
1041  //
1042  // Note also that we DO NOT return at this point, because we still have
1043  // other tests to run.
1044  const FunctionType *OldType = OldQType->getAs<FunctionType>();
1045  const FunctionType *NewType = New->getType()->getAs<FunctionType>();
1046  const FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
1047  const FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
1048  if (OldTypeInfo.getCC() != CC_Default &&
1049      NewTypeInfo.getCC() == CC_Default) {
1050    NewQType = Context.getCallConvType(NewQType, OldTypeInfo.getCC());
1051    New->setType(NewQType);
1052    NewQType = Context.getCanonicalType(NewQType);
1053  } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
1054                                     NewTypeInfo.getCC())) {
1055    // Calling conventions really aren't compatible, so complain.
1056    Diag(New->getLocation(), diag::err_cconv_change)
1057      << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
1058      << (OldTypeInfo.getCC() == CC_Default)
1059      << (OldTypeInfo.getCC() == CC_Default ? "" :
1060          FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
1061    Diag(Old->getLocation(), diag::note_previous_declaration);
1062    return true;
1063  }
1064
1065  // FIXME: diagnose the other way around?
1066  if (OldType->getNoReturnAttr() &&
1067      !NewType->getNoReturnAttr()) {
1068    NewQType = Context.getNoReturnType(NewQType);
1069    New->setType(NewQType);
1070    assert(NewQType.isCanonical());
1071  }
1072
1073  if (getLangOptions().CPlusPlus) {
1074    // (C++98 13.1p2):
1075    //   Certain function declarations cannot be overloaded:
1076    //     -- Function declarations that differ only in the return type
1077    //        cannot be overloaded.
1078    QualType OldReturnType
1079      = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
1080    QualType NewReturnType
1081      = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
1082    QualType ResQT;
1083    if (OldReturnType != NewReturnType) {
1084      if (NewReturnType->isObjCObjectPointerType()
1085          && OldReturnType->isObjCObjectPointerType())
1086        ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
1087      if (ResQT.isNull()) {
1088        Diag(New->getLocation(), diag::err_ovl_diff_return_type);
1089        Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1090        return true;
1091      }
1092      else
1093        NewQType = ResQT;
1094    }
1095
1096    const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
1097    CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
1098    if (OldMethod && NewMethod) {
1099      // Preserve triviality.
1100      NewMethod->setTrivial(OldMethod->isTrivial());
1101
1102      bool isFriend = NewMethod->getFriendObjectKind();
1103
1104      if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord()) {
1105        //    -- Member function declarations with the same name and the
1106        //       same parameter types cannot be overloaded if any of them
1107        //       is a static member function declaration.
1108        if (OldMethod->isStatic() || NewMethod->isStatic()) {
1109          Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
1110          Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1111          return true;
1112        }
1113
1114        // C++ [class.mem]p1:
1115        //   [...] A member shall not be declared twice in the
1116        //   member-specification, except that a nested class or member
1117        //   class template can be declared and then later defined.
1118        unsigned NewDiag;
1119        if (isa<CXXConstructorDecl>(OldMethod))
1120          NewDiag = diag::err_constructor_redeclared;
1121        else if (isa<CXXDestructorDecl>(NewMethod))
1122          NewDiag = diag::err_destructor_redeclared;
1123        else if (isa<CXXConversionDecl>(NewMethod))
1124          NewDiag = diag::err_conv_function_redeclared;
1125        else
1126          NewDiag = diag::err_member_redeclared;
1127
1128        Diag(New->getLocation(), NewDiag);
1129        Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1130
1131      // Complain if this is an explicit declaration of a special
1132      // member that was initially declared implicitly.
1133      //
1134      // As an exception, it's okay to befriend such methods in order
1135      // to permit the implicit constructor/destructor/operator calls.
1136      } else if (OldMethod->isImplicit()) {
1137        if (isFriend) {
1138          NewMethod->setImplicit();
1139        } else {
1140          Diag(NewMethod->getLocation(),
1141               diag::err_definition_of_implicitly_declared_member)
1142            << New << getSpecialMember(OldMethod);
1143          return true;
1144        }
1145      }
1146    }
1147
1148    // (C++98 8.3.5p3):
1149    //   All declarations for a function shall agree exactly in both the
1150    //   return type and the parameter-type-list.
1151    // attributes should be ignored when comparing.
1152    if (Context.getNoReturnType(OldQType, false) ==
1153        Context.getNoReturnType(NewQType, false))
1154      return MergeCompatibleFunctionDecls(New, Old);
1155
1156    // Fall through for conflicting redeclarations and redefinitions.
1157  }
1158
1159  // C: Function types need to be compatible, not identical. This handles
1160  // duplicate function decls like "void f(int); void f(enum X);" properly.
1161  if (!getLangOptions().CPlusPlus &&
1162      Context.typesAreCompatible(OldQType, NewQType)) {
1163    const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
1164    const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
1165    const FunctionProtoType *OldProto = 0;
1166    if (isa<FunctionNoProtoType>(NewFuncType) &&
1167        (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
1168      // The old declaration provided a function prototype, but the
1169      // new declaration does not. Merge in the prototype.
1170      assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
1171      llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
1172                                                 OldProto->arg_type_end());
1173      NewQType = Context.getFunctionType(NewFuncType->getResultType(),
1174                                         ParamTypes.data(), ParamTypes.size(),
1175                                         OldProto->isVariadic(),
1176                                         OldProto->getTypeQuals(),
1177                                         false, false, 0, 0,
1178                                         OldProto->getExtInfo());
1179      New->setType(NewQType);
1180      New->setHasInheritedPrototype();
1181
1182      // Synthesize a parameter for each argument type.
1183      llvm::SmallVector<ParmVarDecl*, 16> Params;
1184      for (FunctionProtoType::arg_type_iterator
1185             ParamType = OldProto->arg_type_begin(),
1186             ParamEnd = OldProto->arg_type_end();
1187           ParamType != ParamEnd; ++ParamType) {
1188        ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
1189                                                 SourceLocation(), 0,
1190                                                 *ParamType, /*TInfo=*/0,
1191                                                 VarDecl::None, VarDecl::None,
1192                                                 0);
1193        Param->setImplicit();
1194        Params.push_back(Param);
1195      }
1196
1197      New->setParams(Params.data(), Params.size());
1198    }
1199
1200    return MergeCompatibleFunctionDecls(New, Old);
1201  }
1202
1203  // GNU C permits a K&R definition to follow a prototype declaration
1204  // if the declared types of the parameters in the K&R definition
1205  // match the types in the prototype declaration, even when the
1206  // promoted types of the parameters from the K&R definition differ
1207  // from the types in the prototype. GCC then keeps the types from
1208  // the prototype.
1209  //
1210  // If a variadic prototype is followed by a non-variadic K&R definition,
1211  // the K&R definition becomes variadic.  This is sort of an edge case, but
1212  // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
1213  // C99 6.9.1p8.
1214  if (!getLangOptions().CPlusPlus &&
1215      Old->hasPrototype() && !New->hasPrototype() &&
1216      New->getType()->getAs<FunctionProtoType>() &&
1217      Old->getNumParams() == New->getNumParams()) {
1218    llvm::SmallVector<QualType, 16> ArgTypes;
1219    llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings;
1220    const FunctionProtoType *OldProto
1221      = Old->getType()->getAs<FunctionProtoType>();
1222    const FunctionProtoType *NewProto
1223      = New->getType()->getAs<FunctionProtoType>();
1224
1225    // Determine whether this is the GNU C extension.
1226    QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
1227                                               NewProto->getResultType());
1228    bool LooseCompatible = !MergedReturn.isNull();
1229    for (unsigned Idx = 0, End = Old->getNumParams();
1230         LooseCompatible && Idx != End; ++Idx) {
1231      ParmVarDecl *OldParm = Old->getParamDecl(Idx);
1232      ParmVarDecl *NewParm = New->getParamDecl(Idx);
1233      if (Context.typesAreCompatible(OldParm->getType(),
1234                                     NewProto->getArgType(Idx))) {
1235        ArgTypes.push_back(NewParm->getType());
1236      } else if (Context.typesAreCompatible(OldParm->getType(),
1237                                            NewParm->getType())) {
1238        GNUCompatibleParamWarning Warn
1239          = { OldParm, NewParm, NewProto->getArgType(Idx) };
1240        Warnings.push_back(Warn);
1241        ArgTypes.push_back(NewParm->getType());
1242      } else
1243        LooseCompatible = false;
1244    }
1245
1246    if (LooseCompatible) {
1247      for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
1248        Diag(Warnings[Warn].NewParm->getLocation(),
1249             diag::ext_param_promoted_not_compatible_with_prototype)
1250          << Warnings[Warn].PromotedType
1251          << Warnings[Warn].OldParm->getType();
1252        Diag(Warnings[Warn].OldParm->getLocation(),
1253             diag::note_previous_declaration);
1254      }
1255
1256      New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
1257                                           ArgTypes.size(),
1258                                           OldProto->isVariadic(), 0,
1259                                           false, false, 0, 0,
1260                                           OldProto->getExtInfo()));
1261      return MergeCompatibleFunctionDecls(New, Old);
1262    }
1263
1264    // Fall through to diagnose conflicting types.
1265  }
1266
1267  // A function that has already been declared has been redeclared or defined
1268  // with a different type- show appropriate diagnostic
1269  if (unsigned BuiltinID = Old->getBuiltinID()) {
1270    // The user has declared a builtin function with an incompatible
1271    // signature.
1272    if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
1273      // The function the user is redeclaring is a library-defined
1274      // function like 'malloc' or 'printf'. Warn about the
1275      // redeclaration, then pretend that we don't know about this
1276      // library built-in.
1277      Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
1278      Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
1279        << Old << Old->getType();
1280      New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
1281      Old->setInvalidDecl();
1282      return false;
1283    }
1284
1285    PrevDiag = diag::note_previous_builtin_declaration;
1286  }
1287
1288  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
1289  Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1290  return true;
1291}
1292
1293/// \brief Completes the merge of two function declarations that are
1294/// known to be compatible.
1295///
1296/// This routine handles the merging of attributes and other
1297/// properties of function declarations form the old declaration to
1298/// the new declaration, once we know that New is in fact a
1299/// redeclaration of Old.
1300///
1301/// \returns false
1302bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
1303  // Merge the attributes
1304  MergeAttributes(New, Old, Context);
1305
1306  // Merge the storage class.
1307  if (Old->getStorageClass() != FunctionDecl::Extern &&
1308      Old->getStorageClass() != FunctionDecl::None)
1309    New->setStorageClass(Old->getStorageClass());
1310
1311  // Merge "pure" flag.
1312  if (Old->isPure())
1313    New->setPure();
1314
1315  // Merge the "deleted" flag.
1316  if (Old->isDeleted())
1317    New->setDeleted();
1318
1319  if (getLangOptions().CPlusPlus)
1320    return MergeCXXFunctionDecl(New, Old);
1321
1322  return false;
1323}
1324
1325/// MergeVarDecl - We just parsed a variable 'New' which has the same name
1326/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
1327/// situation, merging decls or emitting diagnostics as appropriate.
1328///
1329/// Tentative definition rules (C99 6.9.2p2) are checked by
1330/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
1331/// definitions here, since the initializer hasn't been attached.
1332///
1333void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
1334  // If the new decl is already invalid, don't do any other checking.
1335  if (New->isInvalidDecl())
1336    return;
1337
1338  // Verify the old decl was also a variable.
1339  VarDecl *Old = 0;
1340  if (!Previous.isSingleResult() ||
1341      !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
1342    Diag(New->getLocation(), diag::err_redefinition_different_kind)
1343      << New->getDeclName();
1344    Diag(Previous.getRepresentativeDecl()->getLocation(),
1345         diag::note_previous_definition);
1346    return New->setInvalidDecl();
1347  }
1348
1349  MergeAttributes(New, Old, Context);
1350
1351  // Merge the types
1352  QualType MergedT;
1353  if (getLangOptions().CPlusPlus) {
1354    if (Context.hasSameType(New->getType(), Old->getType()))
1355      MergedT = New->getType();
1356    // C++ [basic.link]p10:
1357    //   [...] the types specified by all declarations referring to a given
1358    //   object or function shall be identical, except that declarations for an
1359    //   array object can specify array types that differ by the presence or
1360    //   absence of a major array bound (8.3.4).
1361    else if (Old->getType()->isIncompleteArrayType() &&
1362             New->getType()->isArrayType()) {
1363      CanQual<ArrayType> OldArray
1364        = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1365      CanQual<ArrayType> NewArray
1366        = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1367      if (OldArray->getElementType() == NewArray->getElementType())
1368        MergedT = New->getType();
1369    } else if (Old->getType()->isArrayType() &&
1370             New->getType()->isIncompleteArrayType()) {
1371      CanQual<ArrayType> OldArray
1372        = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1373      CanQual<ArrayType> NewArray
1374        = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1375      if (OldArray->getElementType() == NewArray->getElementType())
1376        MergedT = Old->getType();
1377    } else if (New->getType()->isObjCObjectPointerType()
1378               && Old->getType()->isObjCObjectPointerType()) {
1379        MergedT = Context.mergeObjCGCQualifiers(New->getType(), Old->getType());
1380    }
1381  } else {
1382    MergedT = Context.mergeTypes(New->getType(), Old->getType());
1383  }
1384  if (MergedT.isNull()) {
1385    Diag(New->getLocation(), diag::err_redefinition_different_type)
1386      << New->getDeclName();
1387    Diag(Old->getLocation(), diag::note_previous_definition);
1388    return New->setInvalidDecl();
1389  }
1390  New->setType(MergedT);
1391
1392  // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
1393  if (New->getStorageClass() == VarDecl::Static &&
1394      (Old->getStorageClass() == VarDecl::None || Old->hasExternalStorage())) {
1395    Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
1396    Diag(Old->getLocation(), diag::note_previous_definition);
1397    return New->setInvalidDecl();
1398  }
1399  // C99 6.2.2p4:
1400  //   For an identifier declared with the storage-class specifier
1401  //   extern in a scope in which a prior declaration of that
1402  //   identifier is visible,23) if the prior declaration specifies
1403  //   internal or external linkage, the linkage of the identifier at
1404  //   the later declaration is the same as the linkage specified at
1405  //   the prior declaration. If no prior declaration is visible, or
1406  //   if the prior declaration specifies no linkage, then the
1407  //   identifier has external linkage.
1408  if (New->hasExternalStorage() && Old->hasLinkage())
1409    /* Okay */;
1410  else if (New->getStorageClass() != VarDecl::Static &&
1411           Old->getStorageClass() == VarDecl::Static) {
1412    Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
1413    Diag(Old->getLocation(), diag::note_previous_definition);
1414    return New->setInvalidDecl();
1415  }
1416
1417  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
1418
1419  // FIXME: The test for external storage here seems wrong? We still
1420  // need to check for mismatches.
1421  if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
1422      // Don't complain about out-of-line definitions of static members.
1423      !(Old->getLexicalDeclContext()->isRecord() &&
1424        !New->getLexicalDeclContext()->isRecord())) {
1425    Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
1426    Diag(Old->getLocation(), diag::note_previous_definition);
1427    return New->setInvalidDecl();
1428  }
1429
1430  if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
1431    Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
1432    Diag(Old->getLocation(), diag::note_previous_definition);
1433  } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
1434    Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
1435    Diag(Old->getLocation(), diag::note_previous_definition);
1436  }
1437
1438  // C++ doesn't have tentative definitions, so go right ahead and check here.
1439  const VarDecl *Def;
1440  if (getLangOptions().CPlusPlus &&
1441      New->isThisDeclarationADefinition() == VarDecl::Definition &&
1442      (Def = Old->getDefinition())) {
1443    Diag(New->getLocation(), diag::err_redefinition)
1444      << New->getDeclName();
1445    Diag(Def->getLocation(), diag::note_previous_definition);
1446    New->setInvalidDecl();
1447    return;
1448  }
1449
1450  // Keep a chain of previous declarations.
1451  New->setPreviousDeclaration(Old);
1452
1453  // Inherit access appropriately.
1454  New->setAccess(Old->getAccess());
1455}
1456
1457/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
1458/// no declarator (e.g. "struct foo;") is parsed.
1459Sema::DeclPtrTy Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1460                                                 DeclSpec &DS) {
1461  // FIXME: Error on auto/register at file scope
1462  // FIXME: Error on inline/virtual/explicit
1463  // FIXME: Warn on useless __thread
1464  // FIXME: Warn on useless const/volatile
1465  // FIXME: Warn on useless static/extern/typedef/private_extern/mutable
1466  // FIXME: Warn on useless attributes
1467  Decl *TagD = 0;
1468  TagDecl *Tag = 0;
1469  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
1470      DS.getTypeSpecType() == DeclSpec::TST_struct ||
1471      DS.getTypeSpecType() == DeclSpec::TST_union ||
1472      DS.getTypeSpecType() == DeclSpec::TST_enum) {
1473    TagD = static_cast<Decl *>(DS.getTypeRep());
1474
1475    if (!TagD) // We probably had an error
1476      return DeclPtrTy();
1477
1478    // Note that the above type specs guarantee that the
1479    // type rep is a Decl, whereas in many of the others
1480    // it's a Type.
1481    Tag = dyn_cast<TagDecl>(TagD);
1482  }
1483
1484  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1485    // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
1486    // or incomplete types shall not be restrict-qualified."
1487    if (TypeQuals & DeclSpec::TQ_restrict)
1488      Diag(DS.getRestrictSpecLoc(),
1489           diag::err_typecheck_invalid_restrict_not_pointer_noarg)
1490           << DS.getSourceRange();
1491  }
1492
1493  if (DS.isFriendSpecified()) {
1494    // If we're dealing with a class template decl, assume that the
1495    // template routines are handling it.
1496    if (TagD && isa<ClassTemplateDecl>(TagD))
1497      return DeclPtrTy();
1498    return ActOnFriendTypeDecl(S, DS, MultiTemplateParamsArg(*this, 0, 0));
1499  }
1500
1501  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
1502    // If there are attributes in the DeclSpec, apply them to the record.
1503    if (const AttributeList *AL = DS.getAttributes())
1504      ProcessDeclAttributeList(S, Record, AL);
1505
1506    if (!Record->getDeclName() && Record->isDefinition() &&
1507        DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
1508      if (getLangOptions().CPlusPlus ||
1509          Record->getDeclContext()->isRecord())
1510        return BuildAnonymousStructOrUnion(S, DS, AS, Record);
1511
1512      Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
1513        << DS.getSourceRange();
1514    }
1515
1516    // Microsoft allows unnamed struct/union fields. Don't complain
1517    // about them.
1518    // FIXME: Should we support Microsoft's extensions in this area?
1519    if (Record->getDeclName() && getLangOptions().Microsoft)
1520      return DeclPtrTy::make(Tag);
1521  }
1522
1523  if (!DS.isMissingDeclaratorOk() &&
1524      DS.getTypeSpecType() != DeclSpec::TST_error) {
1525    // Warn about typedefs of enums without names, since this is an
1526    // extension in both Microsoft an GNU.
1527    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
1528        Tag && isa<EnumDecl>(Tag)) {
1529      Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
1530        << DS.getSourceRange();
1531      return DeclPtrTy::make(Tag);
1532    }
1533
1534    Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
1535      << DS.getSourceRange();
1536  }
1537
1538  return DeclPtrTy::make(Tag);
1539}
1540
1541/// We are trying to inject an anonymous member into the given scope;
1542/// check if there's an existing declaration that can't be overloaded.
1543///
1544/// \return true if this is a forbidden redeclaration
1545static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
1546                                         Scope *S,
1547                                         DeclContext *Owner,
1548                                         DeclarationName Name,
1549                                         SourceLocation NameLoc,
1550                                         unsigned diagnostic) {
1551  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
1552                 Sema::ForRedeclaration);
1553  if (!SemaRef.LookupName(R, S)) return false;
1554
1555  if (R.getAsSingle<TagDecl>())
1556    return false;
1557
1558  // Pick a representative declaration.
1559  NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
1560  if (PrevDecl && Owner->isRecord()) {
1561    RecordDecl *Record = cast<RecordDecl>(Owner);
1562    if (!SemaRef.isDeclInScope(PrevDecl, Record, S))
1563      return false;
1564  }
1565
1566  SemaRef.Diag(NameLoc, diagnostic) << Name;
1567  SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
1568
1569  return true;
1570}
1571
1572/// InjectAnonymousStructOrUnionMembers - Inject the members of the
1573/// anonymous struct or union AnonRecord into the owning context Owner
1574/// and scope S. This routine will be invoked just after we realize
1575/// that an unnamed union or struct is actually an anonymous union or
1576/// struct, e.g.,
1577///
1578/// @code
1579/// union {
1580///   int i;
1581///   float f;
1582/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
1583///    // f into the surrounding scope.x
1584/// @endcode
1585///
1586/// This routine is recursive, injecting the names of nested anonymous
1587/// structs/unions into the owning context and scope as well.
1588static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
1589                                                DeclContext *Owner,
1590                                                RecordDecl *AnonRecord,
1591                                                AccessSpecifier AS) {
1592  unsigned diagKind
1593    = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
1594                            : diag::err_anonymous_struct_member_redecl;
1595
1596  bool Invalid = false;
1597  for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
1598                               FEnd = AnonRecord->field_end();
1599       F != FEnd; ++F) {
1600    if ((*F)->getDeclName()) {
1601      if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, (*F)->getDeclName(),
1602                                       (*F)->getLocation(), diagKind)) {
1603        // C++ [class.union]p2:
1604        //   The names of the members of an anonymous union shall be
1605        //   distinct from the names of any other entity in the
1606        //   scope in which the anonymous union is declared.
1607        Invalid = true;
1608      } else {
1609        // C++ [class.union]p2:
1610        //   For the purpose of name lookup, after the anonymous union
1611        //   definition, the members of the anonymous union are
1612        //   considered to have been defined in the scope in which the
1613        //   anonymous union is declared.
1614        Owner->makeDeclVisibleInContext(*F);
1615        S->AddDecl(Sema::DeclPtrTy::make(*F));
1616        SemaRef.IdResolver.AddDecl(*F);
1617
1618        // That includes picking up the appropriate access specifier.
1619        if (AS != AS_none) (*F)->setAccess(AS);
1620      }
1621    } else if (const RecordType *InnerRecordType
1622                 = (*F)->getType()->getAs<RecordType>()) {
1623      RecordDecl *InnerRecord = InnerRecordType->getDecl();
1624      if (InnerRecord->isAnonymousStructOrUnion())
1625        Invalid = Invalid ||
1626          InjectAnonymousStructOrUnionMembers(SemaRef, S, Owner,
1627                                              InnerRecord, AS);
1628    }
1629  }
1630
1631  return Invalid;
1632}
1633
1634/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
1635/// a VarDecl::StorageClass. Any error reporting is up to the caller:
1636/// illegal input values are mapped to VarDecl::None.
1637/// If the input declaration context is a linkage specification
1638/// with no braces, then Extern is mapped to None.
1639static VarDecl::StorageClass
1640StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec,
1641                                      DeclContext *DC) {
1642  switch (StorageClassSpec) {
1643  case DeclSpec::SCS_unspecified:    return VarDecl::None;
1644  case DeclSpec::SCS_extern:
1645    // If the current context is a C++ linkage specification
1646    // having no braces, then the keyword "extern" is properly part
1647    // of the linkage specification itself, rather than being
1648    // the written storage class specifier.
1649    return (DC && isa<LinkageSpecDecl>(DC) &&
1650            !cast<LinkageSpecDecl>(DC)->hasBraces())
1651      ? VarDecl::None : VarDecl::Extern;
1652  case DeclSpec::SCS_static:         return VarDecl::Static;
1653  case DeclSpec::SCS_auto:           return VarDecl::Auto;
1654  case DeclSpec::SCS_register:       return VarDecl::Register;
1655  case DeclSpec::SCS_private_extern: return VarDecl::PrivateExtern;
1656    // Illegal SCSs map to None: error reporting is up to the caller.
1657  case DeclSpec::SCS_mutable:        // Fall through.
1658  case DeclSpec::SCS_typedef:        return VarDecl::None;
1659  }
1660  llvm_unreachable("unknown storage class specifier");
1661}
1662
1663/// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
1664/// a FunctionDecl::StorageClass. Any error reporting is up to the caller:
1665/// illegal input values are mapped to FunctionDecl::None.
1666/// If the input declaration context is a linkage specification
1667/// with no braces, then Extern is mapped to None.
1668static FunctionDecl::StorageClass
1669StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec,
1670                                           DeclContext *DC) {
1671  switch (StorageClassSpec) {
1672  case DeclSpec::SCS_unspecified:    return FunctionDecl::None;
1673  case DeclSpec::SCS_extern:
1674    // If the current context is a C++ linkage specification
1675    // having no braces, then the keyword "extern" is properly part
1676    // of the linkage specification itself, rather than being
1677    // the written storage class specifier.
1678    return (DC && isa<LinkageSpecDecl>(DC) &&
1679            !cast<LinkageSpecDecl>(DC)->hasBraces())
1680      ? FunctionDecl::None : FunctionDecl::Extern;
1681  case DeclSpec::SCS_static:         return FunctionDecl::Static;
1682  case DeclSpec::SCS_private_extern: return FunctionDecl::PrivateExtern;
1683    // Illegal SCSs map to None: error reporting is up to the caller.
1684  case DeclSpec::SCS_auto:           // Fall through.
1685  case DeclSpec::SCS_mutable:        // Fall through.
1686  case DeclSpec::SCS_register:       // Fall through.
1687  case DeclSpec::SCS_typedef:        return FunctionDecl::None;
1688  }
1689  llvm_unreachable("unknown storage class specifier");
1690}
1691
1692/// ActOnAnonymousStructOrUnion - Handle the declaration of an
1693/// anonymous structure or union. Anonymous unions are a C++ feature
1694/// (C++ [class.union]) and a GNU C extension; anonymous structures
1695/// are a GNU C and GNU C++ extension.
1696Sema::DeclPtrTy Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1697                                                  AccessSpecifier AS,
1698                                                  RecordDecl *Record) {
1699  DeclContext *Owner = Record->getDeclContext();
1700
1701  // Diagnose whether this anonymous struct/union is an extension.
1702  if (Record->isUnion() && !getLangOptions().CPlusPlus)
1703    Diag(Record->getLocation(), diag::ext_anonymous_union);
1704  else if (!Record->isUnion())
1705    Diag(Record->getLocation(), diag::ext_anonymous_struct);
1706
1707  // C and C++ require different kinds of checks for anonymous
1708  // structs/unions.
1709  bool Invalid = false;
1710  if (getLangOptions().CPlusPlus) {
1711    const char* PrevSpec = 0;
1712    unsigned DiagID;
1713    // C++ [class.union]p3:
1714    //   Anonymous unions declared in a named namespace or in the
1715    //   global namespace shall be declared static.
1716    if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
1717        (isa<TranslationUnitDecl>(Owner) ||
1718         (isa<NamespaceDecl>(Owner) &&
1719          cast<NamespaceDecl>(Owner)->getDeclName()))) {
1720      Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
1721      Invalid = true;
1722
1723      // Recover by adding 'static'.
1724      DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(),
1725                             PrevSpec, DiagID);
1726    }
1727    // C++ [class.union]p3:
1728    //   A storage class is not allowed in a declaration of an
1729    //   anonymous union in a class scope.
1730    else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1731             isa<RecordDecl>(Owner)) {
1732      Diag(DS.getStorageClassSpecLoc(),
1733           diag::err_anonymous_union_with_storage_spec);
1734      Invalid = true;
1735
1736      // Recover by removing the storage specifier.
1737      DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
1738                             PrevSpec, DiagID);
1739    }
1740
1741    // C++ [class.union]p2:
1742    //   The member-specification of an anonymous union shall only
1743    //   define non-static data members. [Note: nested types and
1744    //   functions cannot be declared within an anonymous union. ]
1745    for (DeclContext::decl_iterator Mem = Record->decls_begin(),
1746                                 MemEnd = Record->decls_end();
1747         Mem != MemEnd; ++Mem) {
1748      if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
1749        // C++ [class.union]p3:
1750        //   An anonymous union shall not have private or protected
1751        //   members (clause 11).
1752        assert(FD->getAccess() != AS_none);
1753        if (FD->getAccess() != AS_public) {
1754          Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
1755            << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
1756          Invalid = true;
1757        }
1758      } else if ((*Mem)->isImplicit()) {
1759        // Any implicit members are fine.
1760      } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
1761        // This is a type that showed up in an
1762        // elaborated-type-specifier inside the anonymous struct or
1763        // union, but which actually declares a type outside of the
1764        // anonymous struct or union. It's okay.
1765      } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
1766        if (!MemRecord->isAnonymousStructOrUnion() &&
1767            MemRecord->getDeclName()) {
1768          // This is a nested type declaration.
1769          Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
1770            << (int)Record->isUnion();
1771          Invalid = true;
1772        }
1773      } else {
1774        // We have something that isn't a non-static data
1775        // member. Complain about it.
1776        unsigned DK = diag::err_anonymous_record_bad_member;
1777        if (isa<TypeDecl>(*Mem))
1778          DK = diag::err_anonymous_record_with_type;
1779        else if (isa<FunctionDecl>(*Mem))
1780          DK = diag::err_anonymous_record_with_function;
1781        else if (isa<VarDecl>(*Mem))
1782          DK = diag::err_anonymous_record_with_static;
1783        Diag((*Mem)->getLocation(), DK)
1784            << (int)Record->isUnion();
1785          Invalid = true;
1786      }
1787    }
1788  }
1789
1790  if (!Record->isUnion() && !Owner->isRecord()) {
1791    Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
1792      << (int)getLangOptions().CPlusPlus;
1793    Invalid = true;
1794  }
1795
1796  // Mock up a declarator.
1797  Declarator Dc(DS, Declarator::TypeNameContext);
1798  TypeSourceInfo *TInfo = 0;
1799  GetTypeForDeclarator(Dc, S, &TInfo);
1800  assert(TInfo && "couldn't build declarator info for anonymous struct/union");
1801
1802  // Create a declaration for this anonymous struct/union.
1803  NamedDecl *Anon = 0;
1804  if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
1805    Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
1806                             /*IdentifierInfo=*/0,
1807                             Context.getTypeDeclType(Record),
1808                             TInfo,
1809                             /*BitWidth=*/0, /*Mutable=*/false);
1810    Anon->setAccess(AS);
1811    if (getLangOptions().CPlusPlus) {
1812      FieldCollector->Add(cast<FieldDecl>(Anon));
1813      if (!cast<CXXRecordDecl>(Record)->isEmpty())
1814        cast<CXXRecordDecl>(OwningClass)->setEmpty(false);
1815    }
1816  } else {
1817    DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
1818    assert(SCSpec != DeclSpec::SCS_typedef &&
1819           "Parser allowed 'typedef' as storage class VarDecl.");
1820    VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec, 0);
1821    if (SCSpec == DeclSpec::SCS_mutable) {
1822      // mutable can only appear on non-static class members, so it's always
1823      // an error here
1824      Diag(Record->getLocation(), diag::err_mutable_nonmember);
1825      Invalid = true;
1826      SC = VarDecl::None;
1827    }
1828    SCSpec = DS.getStorageClassSpecAsWritten();
1829    VarDecl::StorageClass SCAsWritten
1830      = StorageClassSpecToVarDeclStorageClass(SCSpec, 0);
1831
1832    Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
1833                           /*IdentifierInfo=*/0,
1834                           Context.getTypeDeclType(Record),
1835                           TInfo, SC, SCAsWritten);
1836  }
1837  Anon->setImplicit();
1838
1839  // Add the anonymous struct/union object to the current
1840  // context. We'll be referencing this object when we refer to one of
1841  // its members.
1842  Owner->addDecl(Anon);
1843
1844  // Inject the members of the anonymous struct/union into the owning
1845  // context and into the identifier resolver chain for name lookup
1846  // purposes.
1847  if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS))
1848    Invalid = true;
1849
1850  // Mark this as an anonymous struct/union type. Note that we do not
1851  // do this until after we have already checked and injected the
1852  // members of this anonymous struct/union type, because otherwise
1853  // the members could be injected twice: once by DeclContext when it
1854  // builds its lookup table, and once by
1855  // InjectAnonymousStructOrUnionMembers.
1856  Record->setAnonymousStructOrUnion(true);
1857
1858  if (Invalid)
1859    Anon->setInvalidDecl();
1860
1861  return DeclPtrTy::make(Anon);
1862}
1863
1864
1865/// GetNameForDeclarator - Determine the full declaration name for the
1866/// given Declarator.
1867DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1868  return GetNameFromUnqualifiedId(D.getName());
1869}
1870
1871/// \brief Retrieves the canonicalized name from a parsed unqualified-id.
1872DeclarationName Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
1873  switch (Name.getKind()) {
1874    case UnqualifiedId::IK_Identifier:
1875      return DeclarationName(Name.Identifier);
1876
1877    case UnqualifiedId::IK_OperatorFunctionId:
1878      return Context.DeclarationNames.getCXXOperatorName(
1879                                              Name.OperatorFunctionId.Operator);
1880
1881    case UnqualifiedId::IK_LiteralOperatorId:
1882      return Context.DeclarationNames.getCXXLiteralOperatorName(
1883                                                               Name.Identifier);
1884
1885    case UnqualifiedId::IK_ConversionFunctionId: {
1886      QualType Ty = GetTypeFromParser(Name.ConversionFunctionId);
1887      if (Ty.isNull())
1888        return DeclarationName();
1889
1890      return Context.DeclarationNames.getCXXConversionFunctionName(
1891                                                  Context.getCanonicalType(Ty));
1892    }
1893
1894    case UnqualifiedId::IK_ConstructorName: {
1895      QualType Ty = GetTypeFromParser(Name.ConstructorName);
1896      if (Ty.isNull())
1897        return DeclarationName();
1898
1899      return Context.DeclarationNames.getCXXConstructorName(
1900                                                  Context.getCanonicalType(Ty));
1901    }
1902
1903    case UnqualifiedId::IK_ConstructorTemplateId: {
1904      // In well-formed code, we can only have a constructor
1905      // template-id that refers to the current context, so go there
1906      // to find the actual type being constructed.
1907      CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
1908      if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
1909        return DeclarationName();
1910
1911      // Determine the type of the class being constructed.
1912      QualType CurClassType = Context.getTypeDeclType(CurClass);
1913
1914      // FIXME: Check two things: that the template-id names the same type as
1915      // CurClassType, and that the template-id does not occur when the name
1916      // was qualified.
1917
1918      return Context.DeclarationNames.getCXXConstructorName(
1919                                       Context.getCanonicalType(CurClassType));
1920    }
1921
1922    case UnqualifiedId::IK_DestructorName: {
1923      QualType Ty = GetTypeFromParser(Name.DestructorName);
1924      if (Ty.isNull())
1925        return DeclarationName();
1926
1927      return Context.DeclarationNames.getCXXDestructorName(
1928                                                           Context.getCanonicalType(Ty));
1929    }
1930
1931    case UnqualifiedId::IK_TemplateId: {
1932      TemplateName TName
1933        = TemplateName::getFromVoidPointer(Name.TemplateId->Template);
1934      return Context.getNameForTemplate(TName);
1935    }
1936  }
1937
1938  assert(false && "Unknown name kind");
1939  return DeclarationName();
1940}
1941
1942/// isNearlyMatchingFunction - Determine whether the C++ functions
1943/// Declaration and Definition are "nearly" matching. This heuristic
1944/// is used to improve diagnostics in the case where an out-of-line
1945/// function definition doesn't match any declaration within
1946/// the class or namespace.
1947static bool isNearlyMatchingFunction(ASTContext &Context,
1948                                     FunctionDecl *Declaration,
1949                                     FunctionDecl *Definition) {
1950  if (Declaration->param_size() != Definition->param_size())
1951    return false;
1952  for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1953    QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1954    QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1955
1956    if (!Context.hasSameUnqualifiedType(DeclParamTy.getNonReferenceType(),
1957                                        DefParamTy.getNonReferenceType()))
1958      return false;
1959  }
1960
1961  return true;
1962}
1963
1964/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
1965/// declarator needs to be rebuilt in the current instantiation.
1966/// Any bits of declarator which appear before the name are valid for
1967/// consideration here.  That's specifically the type in the decl spec
1968/// and the base type in any member-pointer chunks.
1969static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
1970                                                    DeclarationName Name) {
1971  // The types we specifically need to rebuild are:
1972  //   - typenames, typeofs, and decltypes
1973  //   - types which will become injected class names
1974  // Of course, we also need to rebuild any type referencing such a
1975  // type.  It's safest to just say "dependent", but we call out a
1976  // few cases here.
1977
1978  DeclSpec &DS = D.getMutableDeclSpec();
1979  switch (DS.getTypeSpecType()) {
1980  case DeclSpec::TST_typename:
1981  case DeclSpec::TST_typeofType:
1982  case DeclSpec::TST_typeofExpr:
1983  case DeclSpec::TST_decltype: {
1984    // Grab the type from the parser.
1985    TypeSourceInfo *TSI = 0;
1986    QualType T = S.GetTypeFromParser(DS.getTypeRep(), &TSI);
1987    if (T.isNull() || !T->isDependentType()) break;
1988
1989    // Make sure there's a type source info.  This isn't really much
1990    // of a waste; most dependent types should have type source info
1991    // attached already.
1992    if (!TSI)
1993      TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
1994
1995    // Rebuild the type in the current instantiation.
1996    TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
1997    if (!TSI) return true;
1998
1999    // Store the new type back in the decl spec.
2000    QualType LocType = S.CreateLocInfoType(TSI->getType(), TSI);
2001    DS.UpdateTypeRep(LocType.getAsOpaquePtr());
2002    break;
2003  }
2004
2005  default:
2006    // Nothing to do for these decl specs.
2007    break;
2008  }
2009
2010  // It doesn't matter what order we do this in.
2011  for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
2012    DeclaratorChunk &Chunk = D.getTypeObject(I);
2013
2014    // The only type information in the declarator which can come
2015    // before the declaration name is the base type of a member
2016    // pointer.
2017    if (Chunk.Kind != DeclaratorChunk::MemberPointer)
2018      continue;
2019
2020    // Rebuild the scope specifier in-place.
2021    CXXScopeSpec &SS = Chunk.Mem.Scope();
2022    if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
2023      return true;
2024  }
2025
2026  return false;
2027}
2028
2029Sema::DeclPtrTy
2030Sema::HandleDeclarator(Scope *S, Declarator &D,
2031                       MultiTemplateParamsArg TemplateParamLists,
2032                       bool IsFunctionDefinition) {
2033  DeclarationName Name = GetNameForDeclarator(D);
2034
2035  // All of these full declarators require an identifier.  If it doesn't have
2036  // one, the ParsedFreeStandingDeclSpec action should be used.
2037  if (!Name) {
2038    if (!D.isInvalidType())  // Reject this if we think it is valid.
2039      Diag(D.getDeclSpec().getSourceRange().getBegin(),
2040           diag::err_declarator_need_ident)
2041        << D.getDeclSpec().getSourceRange() << D.getSourceRange();
2042    return DeclPtrTy();
2043  }
2044
2045  // The scope passed in may not be a decl scope.  Zip up the scope tree until
2046  // we find one that is.
2047  while ((S->getFlags() & Scope::DeclScope) == 0 ||
2048         (S->getFlags() & Scope::TemplateParamScope) != 0)
2049    S = S->getParent();
2050
2051  DeclContext *DC = CurContext;
2052  if (D.getCXXScopeSpec().isInvalid())
2053    D.setInvalidType();
2054  else if (D.getCXXScopeSpec().isSet()) {
2055    bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
2056    DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
2057    if (!DC) {
2058      // If we could not compute the declaration context, it's because the
2059      // declaration context is dependent but does not refer to a class,
2060      // class template, or class template partial specialization. Complain
2061      // and return early, to avoid the coming semantic disaster.
2062      Diag(D.getIdentifierLoc(),
2063           diag::err_template_qualified_declarator_no_match)
2064        << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
2065        << D.getCXXScopeSpec().getRange();
2066      return DeclPtrTy();
2067    }
2068
2069    bool IsDependentContext = DC->isDependentContext();
2070
2071    if (!IsDependentContext &&
2072        RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
2073      return DeclPtrTy();
2074
2075    if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
2076      Diag(D.getIdentifierLoc(),
2077           diag::err_member_def_undefined_record)
2078        << Name << DC << D.getCXXScopeSpec().getRange();
2079      D.setInvalidType();
2080    }
2081
2082    // Check whether we need to rebuild the type of the given
2083    // declaration in the current instantiation.
2084    if (EnteringContext && IsDependentContext &&
2085        TemplateParamLists.size() != 0) {
2086      ContextRAII SavedContext(*this, DC);
2087      if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
2088        D.setInvalidType();
2089    }
2090  }
2091
2092  NamedDecl *New;
2093
2094  TypeSourceInfo *TInfo = 0;
2095  QualType R = GetTypeForDeclarator(D, S, &TInfo);
2096
2097  LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
2098                        ForRedeclaration);
2099
2100  // See if this is a redefinition of a variable in the same scope.
2101  if (!D.getCXXScopeSpec().isSet()) {
2102    bool IsLinkageLookup = false;
2103
2104    // If the declaration we're planning to build will be a function
2105    // or object with linkage, then look for another declaration with
2106    // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
2107    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2108      /* Do nothing*/;
2109    else if (R->isFunctionType()) {
2110      if (CurContext->isFunctionOrMethod() ||
2111          D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
2112        IsLinkageLookup = true;
2113    } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
2114      IsLinkageLookup = true;
2115    else if (CurContext->getLookupContext()->isTranslationUnit() &&
2116             D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
2117      IsLinkageLookup = true;
2118
2119    if (IsLinkageLookup)
2120      Previous.clear(LookupRedeclarationWithLinkage);
2121
2122    LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
2123  } else { // Something like "int foo::x;"
2124    LookupQualifiedName(Previous, DC);
2125
2126    // Don't consider using declarations as previous declarations for
2127    // out-of-line members.
2128    RemoveUsingDecls(Previous);
2129
2130    // C++ 7.3.1.2p2:
2131    // Members (including explicit specializations of templates) of a named
2132    // namespace can also be defined outside that namespace by explicit
2133    // qualification of the name being defined, provided that the entity being
2134    // defined was already declared in the namespace and the definition appears
2135    // after the point of declaration in a namespace that encloses the
2136    // declarations namespace.
2137    //
2138    // Note that we only check the context at this point. We don't yet
2139    // have enough information to make sure that PrevDecl is actually
2140    // the declaration we want to match. For example, given:
2141    //
2142    //   class X {
2143    //     void f();
2144    //     void f(float);
2145    //   };
2146    //
2147    //   void X::f(int) { } // ill-formed
2148    //
2149    // In this case, PrevDecl will point to the overload set
2150    // containing the two f's declared in X, but neither of them
2151    // matches.
2152
2153    // First check whether we named the global scope.
2154    if (isa<TranslationUnitDecl>(DC)) {
2155      Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
2156        << Name << D.getCXXScopeSpec().getRange();
2157    } else {
2158      DeclContext *Cur = CurContext;
2159      while (isa<LinkageSpecDecl>(Cur))
2160        Cur = Cur->getParent();
2161      if (!Cur->Encloses(DC)) {
2162        // The qualifying scope doesn't enclose the original declaration.
2163        // Emit diagnostic based on current scope.
2164        SourceLocation L = D.getIdentifierLoc();
2165        SourceRange R = D.getCXXScopeSpec().getRange();
2166        if (isa<FunctionDecl>(Cur))
2167          Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
2168        else
2169          Diag(L, diag::err_invalid_declarator_scope)
2170            << Name << cast<NamedDecl>(DC) << R;
2171        D.setInvalidType();
2172      }
2173    }
2174  }
2175
2176  if (Previous.isSingleResult() &&
2177      Previous.getFoundDecl()->isTemplateParameter()) {
2178    // Maybe we will complain about the shadowed template parameter.
2179    if (!D.isInvalidType())
2180      if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
2181                                          Previous.getFoundDecl()))
2182        D.setInvalidType();
2183
2184    // Just pretend that we didn't see the previous declaration.
2185    Previous.clear();
2186  }
2187
2188  // In C++, the previous declaration we find might be a tag type
2189  // (class or enum). In this case, the new declaration will hide the
2190  // tag type. Note that this does does not apply if we're declaring a
2191  // typedef (C++ [dcl.typedef]p4).
2192  if (Previous.isSingleTagDecl() &&
2193      D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
2194    Previous.clear();
2195
2196  bool Redeclaration = false;
2197  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
2198    if (TemplateParamLists.size()) {
2199      Diag(D.getIdentifierLoc(), diag::err_template_typedef);
2200      return DeclPtrTy();
2201    }
2202
2203    New = ActOnTypedefDeclarator(S, D, DC, R, TInfo, Previous, Redeclaration);
2204  } else if (R->isFunctionType()) {
2205    New = ActOnFunctionDeclarator(S, D, DC, R, TInfo, Previous,
2206                                  move(TemplateParamLists),
2207                                  IsFunctionDefinition, Redeclaration);
2208  } else {
2209    New = ActOnVariableDeclarator(S, D, DC, R, TInfo, Previous,
2210                                  move(TemplateParamLists),
2211                                  Redeclaration);
2212  }
2213
2214  if (New == 0)
2215    return DeclPtrTy();
2216
2217  // If this has an identifier and is not an invalid redeclaration or
2218  // function template specialization, add it to the scope stack.
2219  if (Name && !(Redeclaration && New->isInvalidDecl()))
2220    PushOnScopeChains(New, S);
2221
2222  return DeclPtrTy::make(New);
2223}
2224
2225/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2226/// types into constant array types in certain situations which would otherwise
2227/// be errors (for GCC compatibility).
2228static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2229                                                    ASTContext &Context,
2230                                                    bool &SizeIsNegative) {
2231  // This method tries to turn a variable array into a constant
2232  // array even when the size isn't an ICE.  This is necessary
2233  // for compatibility with code that depends on gcc's buggy
2234  // constant expression folding, like struct {char x[(int)(char*)2];}
2235  SizeIsNegative = false;
2236
2237  QualifierCollector Qs;
2238  const Type *Ty = Qs.strip(T);
2239
2240  if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
2241    QualType Pointee = PTy->getPointeeType();
2242    QualType FixedType =
2243        TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative);
2244    if (FixedType.isNull()) return FixedType;
2245    FixedType = Context.getPointerType(FixedType);
2246    return Qs.apply(FixedType);
2247  }
2248
2249  const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2250  if (!VLATy)
2251    return QualType();
2252  // FIXME: We should probably handle this case
2253  if (VLATy->getElementType()->isVariablyModifiedType())
2254    return QualType();
2255
2256  Expr::EvalResult EvalResult;
2257  if (!VLATy->getSizeExpr() ||
2258      !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) ||
2259      !EvalResult.Val.isInt())
2260    return QualType();
2261
2262  llvm::APSInt &Res = EvalResult.Val.getInt();
2263  if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned())) {
2264    // TODO: preserve the size expression in declarator info
2265    return Context.getConstantArrayType(VLATy->getElementType(),
2266                                        Res, ArrayType::Normal, 0);
2267  }
2268
2269  SizeIsNegative = true;
2270  return QualType();
2271}
2272
2273/// \brief Register the given locally-scoped external C declaration so
2274/// that it can be found later for redeclarations
2275void
2276Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
2277                                       const LookupResult &Previous,
2278                                       Scope *S) {
2279  assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
2280         "Decl is not a locally-scoped decl!");
2281  // Note that we have a locally-scoped external with this name.
2282  LocallyScopedExternalDecls[ND->getDeclName()] = ND;
2283
2284  if (!Previous.isSingleResult())
2285    return;
2286
2287  NamedDecl *PrevDecl = Previous.getFoundDecl();
2288
2289  // If there was a previous declaration of this variable, it may be
2290  // in our identifier chain. Update the identifier chain with the new
2291  // declaration.
2292  if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
2293    // The previous declaration was found on the identifer resolver
2294    // chain, so remove it from its scope.
2295    while (S && !S->isDeclScope(DeclPtrTy::make(PrevDecl)))
2296      S = S->getParent();
2297
2298    if (S)
2299      S->RemoveDecl(DeclPtrTy::make(PrevDecl));
2300  }
2301}
2302
2303/// \brief Diagnose function specifiers on a declaration of an identifier that
2304/// does not identify a function.
2305void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
2306  // FIXME: We should probably indicate the identifier in question to avoid
2307  // confusion for constructs like "inline int a(), b;"
2308  if (D.getDeclSpec().isInlineSpecified())
2309    Diag(D.getDeclSpec().getInlineSpecLoc(),
2310         diag::err_inline_non_function);
2311
2312  if (D.getDeclSpec().isVirtualSpecified())
2313    Diag(D.getDeclSpec().getVirtualSpecLoc(),
2314         diag::err_virtual_non_function);
2315
2316  if (D.getDeclSpec().isExplicitSpecified())
2317    Diag(D.getDeclSpec().getExplicitSpecLoc(),
2318         diag::err_explicit_non_function);
2319}
2320
2321NamedDecl*
2322Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2323                             QualType R,  TypeSourceInfo *TInfo,
2324                             LookupResult &Previous, bool &Redeclaration) {
2325  // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
2326  if (D.getCXXScopeSpec().isSet()) {
2327    Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
2328      << D.getCXXScopeSpec().getRange();
2329    D.setInvalidType();
2330    // Pretend we didn't see the scope specifier.
2331    DC = CurContext;
2332    Previous.clear();
2333  }
2334
2335  if (getLangOptions().CPlusPlus) {
2336    // Check that there are no default arguments (C++ only).
2337    CheckExtraCXXDefaultArguments(D);
2338  }
2339
2340  DiagnoseFunctionSpecifiers(D);
2341
2342  if (D.getDeclSpec().isThreadSpecified())
2343    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2344
2345  TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, TInfo);
2346  if (!NewTD) return 0;
2347
2348  // Handle attributes prior to checking for duplicates in MergeVarDecl
2349  ProcessDeclAttributes(S, NewTD, D);
2350
2351  // Merge the decl with the existing one if appropriate. If the decl is
2352  // in an outer scope, it isn't the same thing.
2353  FilterLookupForScope(*this, Previous, DC, S, /*ConsiderLinkage*/ false);
2354  if (!Previous.empty()) {
2355    Redeclaration = true;
2356    MergeTypeDefDecl(NewTD, Previous);
2357  }
2358
2359  // C99 6.7.7p2: If a typedef name specifies a variably modified type
2360  // then it shall have block scope.
2361  QualType T = NewTD->getUnderlyingType();
2362  if (T->isVariablyModifiedType()) {
2363    FunctionNeedsScopeChecking() = true;
2364
2365    if (S->getFnParent() == 0) {
2366      bool SizeIsNegative;
2367      QualType FixedTy =
2368          TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
2369      if (!FixedTy.isNull()) {
2370        Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size);
2371        NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
2372      } else {
2373        if (SizeIsNegative)
2374          Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size);
2375        else if (T->isVariableArrayType())
2376          Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
2377        else
2378          Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
2379        NewTD->setInvalidDecl();
2380      }
2381    }
2382  }
2383
2384  // If this is the C FILE type, notify the AST context.
2385  if (IdentifierInfo *II = NewTD->getIdentifier())
2386    if (!NewTD->isInvalidDecl() &&
2387        NewTD->getDeclContext()->getLookupContext()->isTranslationUnit()) {
2388      if (II->isStr("FILE"))
2389        Context.setFILEDecl(NewTD);
2390      else if (II->isStr("jmp_buf"))
2391        Context.setjmp_bufDecl(NewTD);
2392      else if (II->isStr("sigjmp_buf"))
2393        Context.setsigjmp_bufDecl(NewTD);
2394    }
2395
2396  return NewTD;
2397}
2398
2399/// \brief Determines whether the given declaration is an out-of-scope
2400/// previous declaration.
2401///
2402/// This routine should be invoked when name lookup has found a
2403/// previous declaration (PrevDecl) that is not in the scope where a
2404/// new declaration by the same name is being introduced. If the new
2405/// declaration occurs in a local scope, previous declarations with
2406/// linkage may still be considered previous declarations (C99
2407/// 6.2.2p4-5, C++ [basic.link]p6).
2408///
2409/// \param PrevDecl the previous declaration found by name
2410/// lookup
2411///
2412/// \param DC the context in which the new declaration is being
2413/// declared.
2414///
2415/// \returns true if PrevDecl is an out-of-scope previous declaration
2416/// for a new delcaration with the same name.
2417static bool
2418isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
2419                                ASTContext &Context) {
2420  if (!PrevDecl)
2421    return 0;
2422
2423  if (!PrevDecl->hasLinkage())
2424    return false;
2425
2426  if (Context.getLangOptions().CPlusPlus) {
2427    // C++ [basic.link]p6:
2428    //   If there is a visible declaration of an entity with linkage
2429    //   having the same name and type, ignoring entities declared
2430    //   outside the innermost enclosing namespace scope, the block
2431    //   scope declaration declares that same entity and receives the
2432    //   linkage of the previous declaration.
2433    DeclContext *OuterContext = DC->getLookupContext();
2434    if (!OuterContext->isFunctionOrMethod())
2435      // This rule only applies to block-scope declarations.
2436      return false;
2437    else {
2438      DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
2439      if (PrevOuterContext->isRecord())
2440        // We found a member function: ignore it.
2441        return false;
2442      else {
2443        // Find the innermost enclosing namespace for the new and
2444        // previous declarations.
2445        while (!OuterContext->isFileContext())
2446          OuterContext = OuterContext->getParent();
2447        while (!PrevOuterContext->isFileContext())
2448          PrevOuterContext = PrevOuterContext->getParent();
2449
2450        // The previous declaration is in a different namespace, so it
2451        // isn't the same function.
2452        if (OuterContext->getPrimaryContext() !=
2453            PrevOuterContext->getPrimaryContext())
2454          return false;
2455      }
2456    }
2457  }
2458
2459  return true;
2460}
2461
2462static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
2463  CXXScopeSpec &SS = D.getCXXScopeSpec();
2464  if (!SS.isSet()) return;
2465  DD->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2466                       SS.getRange());
2467}
2468
2469NamedDecl*
2470Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2471                              QualType R, TypeSourceInfo *TInfo,
2472                              LookupResult &Previous,
2473                              MultiTemplateParamsArg TemplateParamLists,
2474                              bool &Redeclaration) {
2475  DeclarationName Name = GetNameForDeclarator(D);
2476
2477  // Check that there are no default arguments (C++ only).
2478  if (getLangOptions().CPlusPlus)
2479    CheckExtraCXXDefaultArguments(D);
2480
2481  DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
2482  assert(SCSpec != DeclSpec::SCS_typedef &&
2483         "Parser allowed 'typedef' as storage class VarDecl.");
2484  VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec, 0);
2485  if (SCSpec == DeclSpec::SCS_mutable) {
2486    // mutable can only appear on non-static class members, so it's always
2487    // an error here
2488    Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
2489    D.setInvalidType();
2490    SC = VarDecl::None;
2491  }
2492  SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
2493  VarDecl::StorageClass SCAsWritten
2494    = StorageClassSpecToVarDeclStorageClass(SCSpec, DC);
2495
2496  IdentifierInfo *II = Name.getAsIdentifierInfo();
2497  if (!II) {
2498    Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
2499      << Name.getAsString();
2500    return 0;
2501  }
2502
2503  DiagnoseFunctionSpecifiers(D);
2504
2505  if (!DC->isRecord() && S->getFnParent() == 0) {
2506    // C99 6.9p2: The storage-class specifiers auto and register shall not
2507    // appear in the declaration specifiers in an external declaration.
2508    if (SC == VarDecl::Auto || SC == VarDecl::Register) {
2509
2510      // If this is a register variable with an asm label specified, then this
2511      // is a GNU extension.
2512      if (SC == VarDecl::Register && D.getAsmLabel())
2513        Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
2514      else
2515        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
2516      D.setInvalidType();
2517    }
2518  }
2519  if (DC->isRecord() && !CurContext->isRecord()) {
2520    // This is an out-of-line definition of a static data member.
2521    if (SC == VarDecl::Static) {
2522      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2523           diag::err_static_out_of_line)
2524        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
2525    } else if (SC == VarDecl::None)
2526      SC = VarDecl::Static;
2527  }
2528  if (SC == VarDecl::Static) {
2529    if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
2530      if (RD->isLocalClass())
2531        Diag(D.getIdentifierLoc(),
2532             diag::err_static_data_member_not_allowed_in_local_class)
2533          << Name << RD->getDeclName();
2534    }
2535  }
2536
2537  // Match up the template parameter lists with the scope specifier, then
2538  // determine whether we have a template or a template specialization.
2539  bool isExplicitSpecialization = false;
2540  if (TemplateParameterList *TemplateParams
2541        = MatchTemplateParametersToScopeSpecifier(
2542                                  D.getDeclSpec().getSourceRange().getBegin(),
2543                                                  D.getCXXScopeSpec(),
2544                        (TemplateParameterList**)TemplateParamLists.get(),
2545                                                   TemplateParamLists.size(),
2546                                                  /*never a friend*/ false,
2547                                                  isExplicitSpecialization)) {
2548    if (TemplateParams->size() > 0) {
2549      // There is no such thing as a variable template.
2550      Diag(D.getIdentifierLoc(), diag::err_template_variable)
2551        << II
2552        << SourceRange(TemplateParams->getTemplateLoc(),
2553                       TemplateParams->getRAngleLoc());
2554      return 0;
2555    } else {
2556      // There is an extraneous 'template<>' for this variable. Complain
2557      // about it, but allow the declaration of the variable.
2558      Diag(TemplateParams->getTemplateLoc(),
2559           diag::err_template_variable_noparams)
2560        << II
2561        << SourceRange(TemplateParams->getTemplateLoc(),
2562                       TemplateParams->getRAngleLoc());
2563
2564      isExplicitSpecialization = true;
2565    }
2566  }
2567
2568  VarDecl *NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
2569                                   II, R, TInfo, SC, SCAsWritten);
2570
2571  if (D.isInvalidType())
2572    NewVD->setInvalidDecl();
2573
2574  SetNestedNameSpecifier(NewVD, D);
2575
2576  if (D.getDeclSpec().isThreadSpecified()) {
2577    if (NewVD->hasLocalStorage())
2578      Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
2579    else if (!Context.Target.isTLSSupported())
2580      Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
2581    else
2582      NewVD->setThreadSpecified(true);
2583  }
2584
2585  // Set the lexical context. If the declarator has a C++ scope specifier, the
2586  // lexical context will be different from the semantic context.
2587  NewVD->setLexicalDeclContext(CurContext);
2588
2589  // Handle attributes prior to checking for duplicates in MergeVarDecl
2590  ProcessDeclAttributes(S, NewVD, D);
2591
2592  // Handle GNU asm-label extension (encoded as an attribute).
2593  if (Expr *E = (Expr*) D.getAsmLabel()) {
2594    // The parser guarantees this is a string.
2595    StringLiteral *SE = cast<StringLiteral>(E);
2596    NewVD->addAttr(::new (Context) AsmLabelAttr(Context, SE->getString()));
2597  }
2598
2599  // Diagnose shadowed variables before filtering for scope.
2600  if (!D.getCXXScopeSpec().isSet())
2601    CheckShadow(S, NewVD, Previous);
2602
2603  // Don't consider existing declarations that are in a different
2604  // scope and are out-of-semantic-context declarations (if the new
2605  // declaration has linkage).
2606  FilterLookupForScope(*this, Previous, DC, S, NewVD->hasLinkage());
2607
2608  // Merge the decl with the existing one if appropriate.
2609  if (!Previous.empty()) {
2610    if (Previous.isSingleResult() &&
2611        isa<FieldDecl>(Previous.getFoundDecl()) &&
2612        D.getCXXScopeSpec().isSet()) {
2613      // The user tried to define a non-static data member
2614      // out-of-line (C++ [dcl.meaning]p1).
2615      Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
2616        << D.getCXXScopeSpec().getRange();
2617      Previous.clear();
2618      NewVD->setInvalidDecl();
2619    }
2620  } else if (D.getCXXScopeSpec().isSet()) {
2621    // No previous declaration in the qualifying scope.
2622    Diag(D.getIdentifierLoc(), diag::err_no_member)
2623      << Name << computeDeclContext(D.getCXXScopeSpec(), true)
2624      << D.getCXXScopeSpec().getRange();
2625    NewVD->setInvalidDecl();
2626  }
2627
2628  CheckVariableDeclaration(NewVD, Previous, Redeclaration);
2629
2630  // This is an explicit specialization of a static data member. Check it.
2631  if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
2632      CheckMemberSpecialization(NewVD, Previous))
2633    NewVD->setInvalidDecl();
2634
2635  // attributes declared post-definition are currently ignored
2636  if (Previous.isSingleResult()) {
2637    VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl());
2638    if (Def && (Def = Def->getDefinition()) &&
2639        Def != NewVD && D.hasAttributes()) {
2640      Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
2641      Diag(Def->getLocation(), diag::note_previous_definition);
2642    }
2643  }
2644
2645  // If this is a locally-scoped extern C variable, update the map of
2646  // such variables.
2647  if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
2648      !NewVD->isInvalidDecl())
2649    RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
2650
2651  return NewVD;
2652}
2653
2654/// \brief Diagnose variable or built-in function shadowing.  Implements
2655/// -Wshadow.
2656///
2657/// This method is called whenever a VarDecl is added to a "useful"
2658/// scope.
2659///
2660/// \param S the scope in which the shadowing name is being declared
2661/// \param R the lookup of the name
2662///
2663void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
2664  // Return if warning is ignored.
2665  if (Diags.getDiagnosticLevel(diag::warn_decl_shadow) == Diagnostic::Ignored)
2666    return;
2667
2668  // Don't diagnose declarations at file scope.  The scope might not
2669  // have a DeclContext if (e.g.) we're parsing a function prototype.
2670  DeclContext *NewDC = static_cast<DeclContext*>(S->getEntity());
2671  if (NewDC && NewDC->isFileContext())
2672    return;
2673
2674  // Only diagnose if we're shadowing an unambiguous field or variable.
2675  if (R.getResultKind() != LookupResult::Found)
2676    return;
2677
2678  NamedDecl* ShadowedDecl = R.getFoundDecl();
2679  if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
2680    return;
2681
2682  DeclContext *OldDC = ShadowedDecl->getDeclContext();
2683
2684  // Only warn about certain kinds of shadowing for class members.
2685  if (NewDC && NewDC->isRecord()) {
2686    // In particular, don't warn about shadowing non-class members.
2687    if (!OldDC->isRecord())
2688      return;
2689
2690    // TODO: should we warn about static data members shadowing
2691    // static data members from base classes?
2692
2693    // TODO: don't diagnose for inaccessible shadowed members.
2694    // This is hard to do perfectly because we might friend the
2695    // shadowing context, but that's just a false negative.
2696  }
2697
2698  // Determine what kind of declaration we're shadowing.
2699  unsigned Kind;
2700  if (isa<RecordDecl>(OldDC)) {
2701    if (isa<FieldDecl>(ShadowedDecl))
2702      Kind = 3; // field
2703    else
2704      Kind = 2; // static data member
2705  } else if (OldDC->isFileContext())
2706    Kind = 1; // global
2707  else
2708    Kind = 0; // local
2709
2710  DeclarationName Name = R.getLookupName();
2711
2712  // Emit warning and note.
2713  Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
2714  Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
2715}
2716
2717/// \brief Check -Wshadow without the advantage of a previous lookup.
2718void Sema::CheckShadow(Scope *S, VarDecl *D) {
2719  LookupResult R(*this, D->getDeclName(), D->getLocation(),
2720                 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
2721  LookupName(R, S);
2722  CheckShadow(S, D, R);
2723}
2724
2725/// \brief Perform semantic checking on a newly-created variable
2726/// declaration.
2727///
2728/// This routine performs all of the type-checking required for a
2729/// variable declaration once it has been built. It is used both to
2730/// check variables after they have been parsed and their declarators
2731/// have been translated into a declaration, and to check variables
2732/// that have been instantiated from a template.
2733///
2734/// Sets NewVD->isInvalidDecl() if an error was encountered.
2735void Sema::CheckVariableDeclaration(VarDecl *NewVD,
2736                                    LookupResult &Previous,
2737                                    bool &Redeclaration) {
2738  // If the decl is already known invalid, don't check it.
2739  if (NewVD->isInvalidDecl())
2740    return;
2741
2742  QualType T = NewVD->getType();
2743
2744  if (T->isObjCObjectType()) {
2745    Diag(NewVD->getLocation(), diag::err_statically_allocated_object);
2746    return NewVD->setInvalidDecl();
2747  }
2748
2749  // Emit an error if an address space was applied to decl with local storage.
2750  // This includes arrays of objects with address space qualifiers, but not
2751  // automatic variables that point to other address spaces.
2752  // ISO/IEC TR 18037 S5.1.2
2753  if (NewVD->hasLocalStorage() && (T.getAddressSpace() != 0)) {
2754    Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
2755    return NewVD->setInvalidDecl();
2756  }
2757
2758  if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
2759      && !NewVD->hasAttr<BlocksAttr>())
2760    Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
2761
2762  bool isVM = T->isVariablyModifiedType();
2763  if (isVM || NewVD->hasAttr<CleanupAttr>() ||
2764      NewVD->hasAttr<BlocksAttr>() ||
2765      // FIXME: We need to diagnose jumps passed initialized variables in C++.
2766      // However, this turns on the scope checker for everything with a variable
2767      // which may impact compile time.  See if we can find a better solution
2768      // to this, perhaps only checking functions that contain gotos in C++?
2769      (LangOpts.CPlusPlus && NewVD->hasLocalStorage()))
2770    FunctionNeedsScopeChecking() = true;
2771
2772  if ((isVM && NewVD->hasLinkage()) ||
2773      (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
2774    bool SizeIsNegative;
2775    QualType FixedTy =
2776        TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
2777
2778    if (FixedTy.isNull() && T->isVariableArrayType()) {
2779      const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
2780      // FIXME: This won't give the correct result for
2781      // int a[10][n];
2782      SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
2783
2784      if (NewVD->isFileVarDecl())
2785        Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
2786        << SizeRange;
2787      else if (NewVD->getStorageClass() == VarDecl::Static)
2788        Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
2789        << SizeRange;
2790      else
2791        Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
2792        << SizeRange;
2793      return NewVD->setInvalidDecl();
2794    }
2795
2796    if (FixedTy.isNull()) {
2797      if (NewVD->isFileVarDecl())
2798        Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
2799      else
2800        Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
2801      return NewVD->setInvalidDecl();
2802    }
2803
2804    Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
2805    NewVD->setType(FixedTy);
2806  }
2807
2808  if (Previous.empty() && NewVD->isExternC()) {
2809    // Since we did not find anything by this name and we're declaring
2810    // an extern "C" variable, look for a non-visible extern "C"
2811    // declaration with the same name.
2812    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
2813      = LocallyScopedExternalDecls.find(NewVD->getDeclName());
2814    if (Pos != LocallyScopedExternalDecls.end())
2815      Previous.addDecl(Pos->second);
2816  }
2817
2818  if (T->isVoidType() && !NewVD->hasExternalStorage()) {
2819    Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
2820      << T;
2821    return NewVD->setInvalidDecl();
2822  }
2823
2824  if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
2825    Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
2826    return NewVD->setInvalidDecl();
2827  }
2828
2829  if (isVM && NewVD->hasAttr<BlocksAttr>()) {
2830    Diag(NewVD->getLocation(), diag::err_block_on_vm);
2831    return NewVD->setInvalidDecl();
2832  }
2833
2834  if (!Previous.empty()) {
2835    Redeclaration = true;
2836    MergeVarDecl(NewVD, Previous);
2837  }
2838}
2839
2840/// \brief Data used with FindOverriddenMethod
2841struct FindOverriddenMethodData {
2842  Sema *S;
2843  CXXMethodDecl *Method;
2844};
2845
2846/// \brief Member lookup function that determines whether a given C++
2847/// method overrides a method in a base class, to be used with
2848/// CXXRecordDecl::lookupInBases().
2849static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
2850                                 CXXBasePath &Path,
2851                                 void *UserData) {
2852  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
2853
2854  FindOverriddenMethodData *Data
2855    = reinterpret_cast<FindOverriddenMethodData*>(UserData);
2856
2857  DeclarationName Name = Data->Method->getDeclName();
2858
2859  // FIXME: Do we care about other names here too?
2860  if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
2861    // We really want to find the base class constructor here.
2862    QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
2863    CanQualType CT = Data->S->Context.getCanonicalType(T);
2864
2865    Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
2866  }
2867
2868  for (Path.Decls = BaseRecord->lookup(Name);
2869       Path.Decls.first != Path.Decls.second;
2870       ++Path.Decls.first) {
2871    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*Path.Decls.first)) {
2872      if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD))
2873        return true;
2874    }
2875  }
2876
2877  return false;
2878}
2879
2880/// AddOverriddenMethods - See if a method overrides any in the base classes,
2881/// and if so, check that it's a valid override and remember it.
2882void Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
2883  // Look for virtual methods in base classes that this method might override.
2884  CXXBasePaths Paths;
2885  FindOverriddenMethodData Data;
2886  Data.Method = MD;
2887  Data.S = this;
2888  if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
2889    for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
2890         E = Paths.found_decls_end(); I != E; ++I) {
2891      if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
2892        if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
2893            !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
2894            !CheckOverridingFunctionAttributes(MD, OldMD))
2895          MD->addOverriddenMethod(OldMD->getCanonicalDecl());
2896      }
2897    }
2898  }
2899}
2900
2901NamedDecl*
2902Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2903                              QualType R, TypeSourceInfo *TInfo,
2904                              LookupResult &Previous,
2905                              MultiTemplateParamsArg TemplateParamLists,
2906                              bool IsFunctionDefinition, bool &Redeclaration) {
2907  assert(R.getTypePtr()->isFunctionType());
2908
2909  DeclarationName Name = GetNameForDeclarator(D);
2910  FunctionDecl::StorageClass SC = FunctionDecl::None;
2911  switch (D.getDeclSpec().getStorageClassSpec()) {
2912  default: assert(0 && "Unknown storage class!");
2913  case DeclSpec::SCS_auto:
2914  case DeclSpec::SCS_register:
2915  case DeclSpec::SCS_mutable:
2916    Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2917         diag::err_typecheck_sclass_func);
2918    D.setInvalidType();
2919    break;
2920  case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
2921  case DeclSpec::SCS_extern:      SC = FunctionDecl::Extern; break;
2922  case DeclSpec::SCS_static: {
2923    if (CurContext->getLookupContext()->isFunctionOrMethod()) {
2924      // C99 6.7.1p5:
2925      //   The declaration of an identifier for a function that has
2926      //   block scope shall have no explicit storage-class specifier
2927      //   other than extern
2928      // See also (C++ [dcl.stc]p4).
2929      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2930           diag::err_static_block_func);
2931      SC = FunctionDecl::None;
2932    } else
2933      SC = FunctionDecl::Static;
2934    break;
2935  }
2936  case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
2937  }
2938
2939  if (D.getDeclSpec().isThreadSpecified())
2940    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2941
2942  bool isFriend = D.getDeclSpec().isFriendSpecified();
2943  bool isInline = D.getDeclSpec().isInlineSpecified();
2944  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
2945  bool isExplicit = D.getDeclSpec().isExplicitSpecified();
2946
2947  DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
2948  FunctionDecl::StorageClass SCAsWritten
2949    = StorageClassSpecToFunctionDeclStorageClass(SCSpec, DC);
2950
2951  // Check that the return type is not an abstract class type.
2952  // For record types, this is done by the AbstractClassUsageDiagnoser once
2953  // the class has been completely parsed.
2954  if (!DC->isRecord() &&
2955      RequireNonAbstractType(D.getIdentifierLoc(),
2956                             R->getAs<FunctionType>()->getResultType(),
2957                             diag::err_abstract_type_in_decl,
2958                             AbstractReturnType))
2959    D.setInvalidType();
2960
2961  // Do not allow returning a objc interface by-value.
2962  if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) {
2963    Diag(D.getIdentifierLoc(),
2964         diag::err_object_cannot_be_passed_returned_by_value) << 0
2965      << R->getAs<FunctionType>()->getResultType();
2966    D.setInvalidType();
2967  }
2968
2969  bool isVirtualOkay = false;
2970  FunctionDecl *NewFD;
2971
2972  if (isFriend) {
2973    // C++ [class.friend]p5
2974    //   A function can be defined in a friend declaration of a
2975    //   class . . . . Such a function is implicitly inline.
2976    isInline |= IsFunctionDefinition;
2977  }
2978
2979  if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
2980    // This is a C++ constructor declaration.
2981    assert(DC->isRecord() &&
2982           "Constructors can only be declared in a member context");
2983
2984    R = CheckConstructorDeclarator(D, R, SC);
2985
2986    // Create the new declaration
2987    NewFD = CXXConstructorDecl::Create(Context,
2988                                       cast<CXXRecordDecl>(DC),
2989                                       D.getIdentifierLoc(), Name, R, TInfo,
2990                                       isExplicit, isInline,
2991                                       /*isImplicitlyDeclared=*/false);
2992  } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
2993    // This is a C++ destructor declaration.
2994    if (DC->isRecord()) {
2995      R = CheckDestructorDeclarator(D, SC);
2996
2997      NewFD = CXXDestructorDecl::Create(Context,
2998                                        cast<CXXRecordDecl>(DC),
2999                                        D.getIdentifierLoc(), Name, R,
3000                                        isInline,
3001                                        /*isImplicitlyDeclared=*/false);
3002      NewFD->setTypeSourceInfo(TInfo);
3003
3004      isVirtualOkay = true;
3005    } else {
3006      Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
3007
3008      // Create a FunctionDecl to satisfy the function definition parsing
3009      // code path.
3010      NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
3011                                   Name, R, TInfo, SC, SCAsWritten, isInline,
3012                                   /*hasPrototype=*/true);
3013      D.setInvalidType();
3014    }
3015  } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
3016    if (!DC->isRecord()) {
3017      Diag(D.getIdentifierLoc(),
3018           diag::err_conv_function_not_member);
3019      return 0;
3020    }
3021
3022    CheckConversionDeclarator(D, R, SC);
3023    NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
3024                                      D.getIdentifierLoc(), Name, R, TInfo,
3025                                      isInline, isExplicit);
3026
3027    isVirtualOkay = true;
3028  } else if (DC->isRecord()) {
3029    // If the of the function is the same as the name of the record, then this
3030    // must be an invalid constructor that has a return type.
3031    // (The parser checks for a return type and makes the declarator a
3032    // constructor if it has no return type).
3033    // must have an invalid constructor that has a return type
3034    if (Name.getAsIdentifierInfo() &&
3035        Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
3036      Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
3037        << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3038        << SourceRange(D.getIdentifierLoc());
3039      return 0;
3040    }
3041
3042    bool isStatic = SC == FunctionDecl::Static;
3043
3044    // [class.free]p1:
3045    // Any allocation function for a class T is a static member
3046    // (even if not explicitly declared static).
3047    if (Name.getCXXOverloadedOperator() == OO_New ||
3048        Name.getCXXOverloadedOperator() == OO_Array_New)
3049      isStatic = true;
3050
3051    // [class.free]p6 Any deallocation function for a class X is a static member
3052    // (even if not explicitly declared static).
3053    if (Name.getCXXOverloadedOperator() == OO_Delete ||
3054        Name.getCXXOverloadedOperator() == OO_Array_Delete)
3055      isStatic = true;
3056
3057    // This is a C++ method declaration.
3058    NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
3059                                  D.getIdentifierLoc(), Name, R, TInfo,
3060                                  isStatic, SCAsWritten, isInline);
3061
3062    isVirtualOkay = !isStatic;
3063  } else {
3064    // Determine whether the function was written with a
3065    // prototype. This true when:
3066    //   - we're in C++ (where every function has a prototype),
3067    //   - there is a prototype in the declarator, or
3068    //   - the type R of the function is some kind of typedef or other reference
3069    //     to a type name (which eventually refers to a function type).
3070    bool HasPrototype =
3071       getLangOptions().CPlusPlus ||
3072       (D.getNumTypeObjects() && D.getTypeObject(0).Fun.hasPrototype) ||
3073       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
3074
3075    NewFD = FunctionDecl::Create(Context, DC,
3076                                 D.getIdentifierLoc(),
3077                                 Name, R, TInfo, SC, SCAsWritten, isInline,
3078                                 HasPrototype);
3079  }
3080
3081  if (D.isInvalidType())
3082    NewFD->setInvalidDecl();
3083
3084  SetNestedNameSpecifier(NewFD, D);
3085
3086  // Set the lexical context. If the declarator has a C++
3087  // scope specifier, or is the object of a friend declaration, the
3088  // lexical context will be different from the semantic context.
3089  NewFD->setLexicalDeclContext(CurContext);
3090
3091  // Match up the template parameter lists with the scope specifier, then
3092  // determine whether we have a template or a template specialization.
3093  FunctionTemplateDecl *FunctionTemplate = 0;
3094  bool isExplicitSpecialization = false;
3095  bool isFunctionTemplateSpecialization = false;
3096  if (TemplateParameterList *TemplateParams
3097        = MatchTemplateParametersToScopeSpecifier(
3098                                  D.getDeclSpec().getSourceRange().getBegin(),
3099                                  D.getCXXScopeSpec(),
3100                           (TemplateParameterList**)TemplateParamLists.get(),
3101                                                  TemplateParamLists.size(),
3102                                                  isFriend,
3103                                                  isExplicitSpecialization)) {
3104    if (TemplateParams->size() > 0) {
3105      // This is a function template
3106
3107      // Check that we can declare a template here.
3108      if (CheckTemplateDeclScope(S, TemplateParams))
3109        return 0;
3110
3111      FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
3112                                                      NewFD->getLocation(),
3113                                                      Name, TemplateParams,
3114                                                      NewFD);
3115      FunctionTemplate->setLexicalDeclContext(CurContext);
3116      NewFD->setDescribedFunctionTemplate(FunctionTemplate);
3117    } else {
3118      // This is a function template specialization.
3119      isFunctionTemplateSpecialization = true;
3120
3121      // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
3122      if (isFriend && isFunctionTemplateSpecialization) {
3123        // We want to remove the "template<>", found here.
3124        SourceRange RemoveRange = TemplateParams->getSourceRange();
3125
3126        // If we remove the template<> and the name is not a
3127        // template-id, we're actually silently creating a problem:
3128        // the friend declaration will refer to an untemplated decl,
3129        // and clearly the user wants a template specialization.  So
3130        // we need to insert '<>' after the name.
3131        SourceLocation InsertLoc;
3132        if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
3133          InsertLoc = D.getName().getSourceRange().getEnd();
3134          InsertLoc = PP.getLocForEndOfToken(InsertLoc);
3135        }
3136
3137        Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
3138          << Name << RemoveRange
3139          << FixItHint::CreateRemoval(RemoveRange)
3140          << FixItHint::CreateInsertion(InsertLoc, "<>");
3141      }
3142    }
3143
3144    // FIXME: Free this memory properly.
3145    TemplateParamLists.release();
3146  }
3147
3148  // C++ [dcl.fct.spec]p5:
3149  //   The virtual specifier shall only be used in declarations of
3150  //   nonstatic class member functions that appear within a
3151  //   member-specification of a class declaration; see 10.3.
3152  //
3153  if (isVirtual && !NewFD->isInvalidDecl()) {
3154    if (!isVirtualOkay) {
3155       Diag(D.getDeclSpec().getVirtualSpecLoc(),
3156           diag::err_virtual_non_function);
3157    } else if (!CurContext->isRecord()) {
3158      // 'virtual' was specified outside of the class.
3159      Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_out_of_class)
3160        << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
3161    } else {
3162      // Okay: Add virtual to the method.
3163      CXXRecordDecl *CurClass = cast<CXXRecordDecl>(DC);
3164      CurClass->setMethodAsVirtual(NewFD);
3165    }
3166  }
3167
3168  // C++ [dcl.fct.spec]p6:
3169  //  The explicit specifier shall be used only in the declaration of a
3170  //  constructor or conversion function within its class definition; see 12.3.1
3171  //  and 12.3.2.
3172  if (isExplicit && !NewFD->isInvalidDecl()) {
3173    if (!CurContext->isRecord()) {
3174      // 'explicit' was specified outside of the class.
3175      Diag(D.getDeclSpec().getExplicitSpecLoc(),
3176           diag::err_explicit_out_of_class)
3177        << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
3178    } else if (!isa<CXXConstructorDecl>(NewFD) &&
3179               !isa<CXXConversionDecl>(NewFD)) {
3180      // 'explicit' was specified on a function that wasn't a constructor
3181      // or conversion function.
3182      Diag(D.getDeclSpec().getExplicitSpecLoc(),
3183           diag::err_explicit_non_ctor_or_conv_function)
3184        << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
3185    }
3186  }
3187
3188  // Filter out previous declarations that don't match the scope.
3189  FilterLookupForScope(*this, Previous, DC, S, NewFD->hasLinkage());
3190
3191  if (isFriend) {
3192    // DC is the namespace in which the function is being declared.
3193    assert((DC->isFileContext() || !Previous.empty()) &&
3194           "previously-undeclared friend function being created "
3195           "in a non-namespace context");
3196
3197    // For now, claim that the objects have no previous declaration.
3198    if (FunctionTemplate) {
3199      FunctionTemplate->setObjectOfFriendDecl(false);
3200      FunctionTemplate->setAccess(AS_public);
3201    }
3202    NewFD->setObjectOfFriendDecl(false);
3203    NewFD->setAccess(AS_public);
3204  }
3205
3206  if (SC == FunctionDecl::Static && isa<CXXMethodDecl>(NewFD) &&
3207      !CurContext->isRecord()) {
3208    // C++ [class.static]p1:
3209    //   A data or function member of a class may be declared static
3210    //   in a class definition, in which case it is a static member of
3211    //   the class.
3212
3213    // Complain about the 'static' specifier if it's on an out-of-line
3214    // member function definition.
3215    Diag(D.getDeclSpec().getStorageClassSpecLoc(),
3216         diag::err_static_out_of_line)
3217      << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3218  }
3219
3220  // Handle GNU asm-label extension (encoded as an attribute).
3221  if (Expr *E = (Expr*) D.getAsmLabel()) {
3222    // The parser guarantees this is a string.
3223    StringLiteral *SE = cast<StringLiteral>(E);
3224    NewFD->addAttr(::new (Context) AsmLabelAttr(Context, SE->getString()));
3225  }
3226
3227  // Copy the parameter declarations from the declarator D to the function
3228  // declaration NewFD, if they are available.  First scavenge them into Params.
3229  llvm::SmallVector<ParmVarDecl*, 16> Params;
3230  if (D.getNumTypeObjects() > 0) {
3231    DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3232
3233    // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
3234    // function that takes no arguments, not a function that takes a
3235    // single void argument.
3236    // We let through "const void" here because Sema::GetTypeForDeclarator
3237    // already checks for that case.
3238    if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3239        FTI.ArgInfo[0].Param &&
3240        FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()) {
3241      // Empty arg list, don't push any params.
3242      ParmVarDecl *Param = FTI.ArgInfo[0].Param.getAs<ParmVarDecl>();
3243
3244      // In C++, the empty parameter-type-list must be spelled "void"; a
3245      // typedef of void is not permitted.
3246      if (getLangOptions().CPlusPlus &&
3247          Param->getType().getUnqualifiedType() != Context.VoidTy)
3248        Diag(Param->getLocation(), diag::err_param_typedef_of_void);
3249      // FIXME: Leaks decl?
3250    } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
3251      for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
3252        ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
3253        assert(Param->getDeclContext() != NewFD && "Was set before ?");
3254        Param->setDeclContext(NewFD);
3255        Params.push_back(Param);
3256
3257        if (Param->isInvalidDecl())
3258          NewFD->setInvalidDecl();
3259      }
3260    }
3261
3262  } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
3263    // When we're declaring a function with a typedef, typeof, etc as in the
3264    // following example, we'll need to synthesize (unnamed)
3265    // parameters for use in the declaration.
3266    //
3267    // @code
3268    // typedef void fn(int);
3269    // fn f;
3270    // @endcode
3271
3272    // Synthesize a parameter for each argument type.
3273    for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
3274         AE = FT->arg_type_end(); AI != AE; ++AI) {
3275      ParmVarDecl *Param = ParmVarDecl::Create(Context, NewFD,
3276                                               D.getIdentifierLoc(), 0,
3277                                               *AI,
3278                                         Context.getTrivialTypeSourceInfo(*AI,
3279                                                          D.getIdentifierLoc()),
3280                                               VarDecl::None,
3281                                               VarDecl::None, 0);
3282      Param->setImplicit();
3283      Params.push_back(Param);
3284    }
3285  } else {
3286    assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
3287           "Should not need args for typedef of non-prototype fn");
3288  }
3289  // Finally, we know we have the right number of parameters, install them.
3290  NewFD->setParams(Params.data(), Params.size());
3291
3292  // If the declarator is a template-id, translate the parser's template
3293  // argument list into our AST format.
3294  bool HasExplicitTemplateArgs = false;
3295  TemplateArgumentListInfo TemplateArgs;
3296  if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
3297    TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
3298    TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
3299    TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
3300    ASTTemplateArgsPtr TemplateArgsPtr(*this,
3301                                       TemplateId->getTemplateArgs(),
3302                                       TemplateId->NumArgs);
3303    translateTemplateArguments(TemplateArgsPtr,
3304                               TemplateArgs);
3305    TemplateArgsPtr.release();
3306
3307    HasExplicitTemplateArgs = true;
3308
3309    if (FunctionTemplate) {
3310      // FIXME: Diagnose function template with explicit template
3311      // arguments.
3312      HasExplicitTemplateArgs = false;
3313    } else if (!isFunctionTemplateSpecialization &&
3314               !D.getDeclSpec().isFriendSpecified()) {
3315      // We have encountered something that the user meant to be a
3316      // specialization (because it has explicitly-specified template
3317      // arguments) but that was not introduced with a "template<>" (or had
3318      // too few of them).
3319      Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
3320        << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
3321        << FixItHint::CreateInsertion(
3322                                   D.getDeclSpec().getSourceRange().getBegin(),
3323                                                 "template<> ");
3324      isFunctionTemplateSpecialization = true;
3325    } else {
3326      // "friend void foo<>(int);" is an implicit specialization decl.
3327      isFunctionTemplateSpecialization = true;
3328    }
3329  } else if (isFriend && isFunctionTemplateSpecialization) {
3330    // This combination is only possible in a recovery case;  the user
3331    // wrote something like:
3332    //   template <> friend void foo(int);
3333    // which we're recovering from as if the user had written:
3334    //   friend void foo<>(int);
3335    // Go ahead and fake up a template id.
3336    HasExplicitTemplateArgs = true;
3337    TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
3338    TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
3339  }
3340
3341  // If it's a friend (and only if it's a friend), it's possible
3342  // that either the specialized function type or the specialized
3343  // template is dependent, and therefore matching will fail.  In
3344  // this case, don't check the specialization yet.
3345  if (isFunctionTemplateSpecialization && isFriend &&
3346      (NewFD->getType()->isDependentType() || DC->isDependentContext())) {
3347    assert(HasExplicitTemplateArgs &&
3348           "friend function specialization without template args");
3349    if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
3350                                                     Previous))
3351      NewFD->setInvalidDecl();
3352  } else if (isFunctionTemplateSpecialization) {
3353    if (CheckFunctionTemplateSpecialization(NewFD,
3354                               (HasExplicitTemplateArgs ? &TemplateArgs : 0),
3355                                            Previous))
3356      NewFD->setInvalidDecl();
3357  } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
3358    if (CheckMemberSpecialization(NewFD, Previous))
3359      NewFD->setInvalidDecl();
3360  }
3361
3362  // Perform semantic checking on the function declaration.
3363  bool OverloadableAttrRequired = false; // FIXME: HACK!
3364  CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization,
3365                           Redeclaration, /*FIXME:*/OverloadableAttrRequired);
3366
3367  assert((NewFD->isInvalidDecl() || !Redeclaration ||
3368          Previous.getResultKind() != LookupResult::FoundOverloaded) &&
3369         "previous declaration set still overloaded");
3370
3371  NamedDecl *PrincipalDecl = (FunctionTemplate
3372                              ? cast<NamedDecl>(FunctionTemplate)
3373                              : NewFD);
3374
3375  if (isFriend && Redeclaration) {
3376    AccessSpecifier Access = AS_public;
3377    if (!NewFD->isInvalidDecl())
3378      Access = NewFD->getPreviousDeclaration()->getAccess();
3379
3380    NewFD->setAccess(Access);
3381    if (FunctionTemplate) FunctionTemplate->setAccess(Access);
3382
3383    PrincipalDecl->setObjectOfFriendDecl(true);
3384  }
3385
3386  if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
3387      PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
3388    PrincipalDecl->setNonMemberOperator();
3389
3390  // If we have a function template, check the template parameter
3391  // list. This will check and merge default template arguments.
3392  if (FunctionTemplate) {
3393    FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDeclaration();
3394    CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
3395                      PrevTemplate? PrevTemplate->getTemplateParameters() : 0,
3396             D.getDeclSpec().isFriendSpecified()? TPC_FriendFunctionTemplate
3397                                                : TPC_FunctionTemplate);
3398  }
3399
3400  if (D.getCXXScopeSpec().isSet() && !NewFD->isInvalidDecl()) {
3401    // Fake up an access specifier if it's supposed to be a class member.
3402    if (!Redeclaration && isa<CXXRecordDecl>(NewFD->getDeclContext()))
3403      NewFD->setAccess(AS_public);
3404
3405    // An out-of-line member function declaration must also be a
3406    // definition (C++ [dcl.meaning]p1).
3407    // Note that this is not the case for explicit specializations of
3408    // function templates or member functions of class templates, per
3409    // C++ [temp.expl.spec]p2.
3410    if (!IsFunctionDefinition && !isFriend &&
3411        !isFunctionTemplateSpecialization && !isExplicitSpecialization) {
3412      Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
3413        << D.getCXXScopeSpec().getRange();
3414      NewFD->setInvalidDecl();
3415    } else if (!Redeclaration &&
3416               !(isFriend && CurContext->isDependentContext())) {
3417      // The user tried to provide an out-of-line definition for a
3418      // function that is a member of a class or namespace, but there
3419      // was no such member function declared (C++ [class.mfct]p2,
3420      // C++ [namespace.memdef]p2). For example:
3421      //
3422      // class X {
3423      //   void f() const;
3424      // };
3425      //
3426      // void X::f() { } // ill-formed
3427      //
3428      // Complain about this problem, and attempt to suggest close
3429      // matches (e.g., those that differ only in cv-qualifiers and
3430      // whether the parameter types are references).
3431      Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
3432        << Name << DC << D.getCXXScopeSpec().getRange();
3433      NewFD->setInvalidDecl();
3434
3435      LookupResult Prev(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
3436                        ForRedeclaration);
3437      LookupQualifiedName(Prev, DC);
3438      assert(!Prev.isAmbiguous() &&
3439             "Cannot have an ambiguity in previous-declaration lookup");
3440      for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
3441           Func != FuncEnd; ++Func) {
3442        if (isa<FunctionDecl>(*Func) &&
3443            isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD))
3444          Diag((*Func)->getLocation(), diag::note_member_def_close_match);
3445      }
3446    }
3447  }
3448
3449  // Handle attributes. We need to have merged decls when handling attributes
3450  // (for example to check for conflicts, etc).
3451  // FIXME: This needs to happen before we merge declarations. Then,
3452  // let attribute merging cope with attribute conflicts.
3453  ProcessDeclAttributes(S, NewFD, D);
3454
3455  // attributes declared post-definition are currently ignored
3456  if (Redeclaration && Previous.isSingleResult()) {
3457    const FunctionDecl *Def;
3458    FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
3459    if (PrevFD && PrevFD->getBody(Def) && D.hasAttributes()) {
3460      Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
3461      Diag(Def->getLocation(), diag::note_previous_definition);
3462    }
3463  }
3464
3465  AddKnownFunctionAttributes(NewFD);
3466
3467  if (OverloadableAttrRequired && !NewFD->getAttr<OverloadableAttr>()) {
3468    // If a function name is overloadable in C, then every function
3469    // with that name must be marked "overloadable".
3470    Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
3471      << Redeclaration << NewFD;
3472    if (!Previous.empty())
3473      Diag(Previous.getRepresentativeDecl()->getLocation(),
3474           diag::note_attribute_overloadable_prev_overload);
3475    NewFD->addAttr(::new (Context) OverloadableAttr());
3476  }
3477
3478  // If this is a locally-scoped extern C function, update the
3479  // map of such names.
3480  if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
3481      && !NewFD->isInvalidDecl())
3482    RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
3483
3484  // Set this FunctionDecl's range up to the right paren.
3485  NewFD->setLocEnd(D.getSourceRange().getEnd());
3486
3487  if (FunctionTemplate && NewFD->isInvalidDecl())
3488    FunctionTemplate->setInvalidDecl();
3489
3490  if (FunctionTemplate)
3491    return FunctionTemplate;
3492
3493
3494  // Keep track of static, non-inlined function definitions that
3495  // have not been used. We will warn later.
3496  // FIXME: Also include static functions declared but not defined.
3497  if (!NewFD->isInvalidDecl() && IsFunctionDefinition
3498      && !NewFD->isInlined() && NewFD->getLinkage() == InternalLinkage
3499      && !NewFD->isUsed() && !NewFD->hasAttr<UnusedAttr>()
3500      && !NewFD->hasAttr<ConstructorAttr>()
3501      && !NewFD->hasAttr<DestructorAttr>())
3502    UnusedStaticFuncs.push_back(NewFD);
3503
3504  return NewFD;
3505}
3506
3507/// \brief Perform semantic checking of a new function declaration.
3508///
3509/// Performs semantic analysis of the new function declaration
3510/// NewFD. This routine performs all semantic checking that does not
3511/// require the actual declarator involved in the declaration, and is
3512/// used both for the declaration of functions as they are parsed
3513/// (called via ActOnDeclarator) and for the declaration of functions
3514/// that have been instantiated via C++ template instantiation (called
3515/// via InstantiateDecl).
3516///
3517/// \param IsExplicitSpecialiation whether this new function declaration is
3518/// an explicit specialization of the previous declaration.
3519///
3520/// This sets NewFD->isInvalidDecl() to true if there was an error.
3521void Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
3522                                    LookupResult &Previous,
3523                                    bool IsExplicitSpecialization,
3524                                    bool &Redeclaration,
3525                                    bool &OverloadableAttrRequired) {
3526  // If NewFD is already known erroneous, don't do any of this checking.
3527  if (NewFD->isInvalidDecl())
3528    return;
3529
3530  if (NewFD->getResultType()->isVariablyModifiedType()) {
3531    // Functions returning a variably modified type violate C99 6.7.5.2p2
3532    // because all functions have linkage.
3533    Diag(NewFD->getLocation(), diag::err_vm_func_decl);
3534    return NewFD->setInvalidDecl();
3535  }
3536
3537  if (NewFD->isMain())
3538    CheckMain(NewFD);
3539
3540  // Check for a previous declaration of this name.
3541  if (Previous.empty() && NewFD->isExternC()) {
3542    // Since we did not find anything by this name and we're declaring
3543    // an extern "C" function, look for a non-visible extern "C"
3544    // declaration with the same name.
3545    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
3546      = LocallyScopedExternalDecls.find(NewFD->getDeclName());
3547    if (Pos != LocallyScopedExternalDecls.end())
3548      Previous.addDecl(Pos->second);
3549  }
3550
3551  // Merge or overload the declaration with an existing declaration of
3552  // the same name, if appropriate.
3553  if (!Previous.empty()) {
3554    // Determine whether NewFD is an overload of PrevDecl or
3555    // a declaration that requires merging. If it's an overload,
3556    // there's no more work to do here; we'll just add the new
3557    // function to the scope.
3558
3559    NamedDecl *OldDecl = 0;
3560    if (!AllowOverloadingOfFunction(Previous, Context)) {
3561      Redeclaration = true;
3562      OldDecl = Previous.getFoundDecl();
3563    } else {
3564      if (!getLangOptions().CPlusPlus) {
3565        OverloadableAttrRequired = true;
3566
3567        // Functions marked "overloadable" must have a prototype (that
3568        // we can't get through declaration merging).
3569        if (!NewFD->getType()->getAs<FunctionProtoType>()) {
3570          Diag(NewFD->getLocation(),
3571               diag::err_attribute_overloadable_no_prototype)
3572            << NewFD;
3573          Redeclaration = true;
3574
3575          // Turn this into a variadic function with no parameters.
3576          QualType R = Context.getFunctionType(
3577                     NewFD->getType()->getAs<FunctionType>()->getResultType(),
3578                     0, 0, true, 0, false, false, 0, 0,
3579                     FunctionType::ExtInfo());
3580          NewFD->setType(R);
3581          return NewFD->setInvalidDecl();
3582        }
3583      }
3584
3585      switch (CheckOverload(NewFD, Previous, OldDecl)) {
3586      case Ovl_Match:
3587        Redeclaration = true;
3588        if (isa<UsingShadowDecl>(OldDecl) && CurContext->isRecord()) {
3589          HideUsingShadowDecl(S, cast<UsingShadowDecl>(OldDecl));
3590          Redeclaration = false;
3591        }
3592        break;
3593
3594      case Ovl_NonFunction:
3595        Redeclaration = true;
3596        break;
3597
3598      case Ovl_Overload:
3599        Redeclaration = false;
3600        break;
3601      }
3602    }
3603
3604    if (Redeclaration) {
3605      // NewFD and OldDecl represent declarations that need to be
3606      // merged.
3607      if (MergeFunctionDecl(NewFD, OldDecl))
3608        return NewFD->setInvalidDecl();
3609
3610      Previous.clear();
3611      Previous.addDecl(OldDecl);
3612
3613      if (FunctionTemplateDecl *OldTemplateDecl
3614                                    = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
3615        NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
3616        FunctionTemplateDecl *NewTemplateDecl
3617          = NewFD->getDescribedFunctionTemplate();
3618        assert(NewTemplateDecl && "Template/non-template mismatch");
3619        if (CXXMethodDecl *Method
3620              = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
3621          Method->setAccess(OldTemplateDecl->getAccess());
3622          NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
3623        }
3624
3625        // If this is an explicit specialization of a member that is a function
3626        // template, mark it as a member specialization.
3627        if (IsExplicitSpecialization &&
3628            NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
3629          NewTemplateDecl->setMemberSpecialization();
3630          assert(OldTemplateDecl->isMemberSpecialization());
3631        }
3632      } else {
3633        if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
3634          NewFD->setAccess(OldDecl->getAccess());
3635        NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
3636      }
3637    }
3638  }
3639
3640  // Semantic checking for this function declaration (in isolation).
3641  if (getLangOptions().CPlusPlus) {
3642    // C++-specific checks.
3643    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
3644      CheckConstructor(Constructor);
3645    } else if (CXXDestructorDecl *Destructor =
3646                dyn_cast<CXXDestructorDecl>(NewFD)) {
3647      CXXRecordDecl *Record = Destructor->getParent();
3648      QualType ClassType = Context.getTypeDeclType(Record);
3649
3650      // FIXME: Shouldn't we be able to perform thisc heck even when the class
3651      // type is dependent? Both gcc and edg can handle that.
3652      if (!ClassType->isDependentType()) {
3653        DeclarationName Name
3654          = Context.DeclarationNames.getCXXDestructorName(
3655                                        Context.getCanonicalType(ClassType));
3656        if (NewFD->getDeclName() != Name) {
3657          Diag(NewFD->getLocation(), diag::err_destructor_name);
3658          return NewFD->setInvalidDecl();
3659        }
3660      }
3661
3662      Record->setUserDeclaredDestructor(true);
3663      // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
3664      // user-defined destructor.
3665      Record->setPOD(false);
3666
3667      // C++ [class.dtor]p3: A destructor is trivial if it is an implicitly-
3668      // declared destructor.
3669      // FIXME: C++0x: don't do this for "= default" destructors
3670      Record->setHasTrivialDestructor(false);
3671    } else if (CXXConversionDecl *Conversion
3672               = dyn_cast<CXXConversionDecl>(NewFD)) {
3673      ActOnConversionDeclarator(Conversion);
3674    }
3675
3676    // Find any virtual functions that this function overrides.
3677    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
3678      if (!Method->isFunctionTemplateSpecialization() &&
3679          !Method->getDescribedFunctionTemplate())
3680        AddOverriddenMethods(Method->getParent(), Method);
3681    }
3682
3683    // Additional checks for the destructor; make sure we do this after we
3684    // figure out whether the destructor is virtual.
3685    if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
3686      if (!Destructor->getParent()->isDependentType())
3687        CheckDestructor(Destructor);
3688
3689    // Extra checking for C++ overloaded operators (C++ [over.oper]).
3690    if (NewFD->isOverloadedOperator() &&
3691        CheckOverloadedOperatorDeclaration(NewFD))
3692      return NewFD->setInvalidDecl();
3693
3694    // Extra checking for C++0x literal operators (C++0x [over.literal]).
3695    if (NewFD->getLiteralIdentifier() &&
3696        CheckLiteralOperatorDeclaration(NewFD))
3697      return NewFD->setInvalidDecl();
3698
3699    // In C++, check default arguments now that we have merged decls. Unless
3700    // the lexical context is the class, because in this case this is done
3701    // during delayed parsing anyway.
3702    if (!CurContext->isRecord())
3703      CheckCXXDefaultArguments(NewFD);
3704  }
3705}
3706
3707void Sema::CheckMain(FunctionDecl* FD) {
3708  // C++ [basic.start.main]p3:  A program that declares main to be inline
3709  //   or static is ill-formed.
3710  // C99 6.7.4p4:  In a hosted environment, the inline function specifier
3711  //   shall not appear in a declaration of main.
3712  // static main is not an error under C99, but we should warn about it.
3713  bool isInline = FD->isInlineSpecified();
3714  bool isStatic = FD->getStorageClass() == FunctionDecl::Static;
3715  if (isInline || isStatic) {
3716    unsigned diagID = diag::warn_unusual_main_decl;
3717    if (isInline || getLangOptions().CPlusPlus)
3718      diagID = diag::err_unusual_main_decl;
3719
3720    int which = isStatic + (isInline << 1) - 1;
3721    Diag(FD->getLocation(), diagID) << which;
3722  }
3723
3724  QualType T = FD->getType();
3725  assert(T->isFunctionType() && "function decl is not of function type");
3726  const FunctionType* FT = T->getAs<FunctionType>();
3727
3728  if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
3729    // TODO: add a replacement fixit to turn the return type into 'int'.
3730    Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
3731    FD->setInvalidDecl(true);
3732  }
3733
3734  // Treat protoless main() as nullary.
3735  if (isa<FunctionNoProtoType>(FT)) return;
3736
3737  const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
3738  unsigned nparams = FTP->getNumArgs();
3739  assert(FD->getNumParams() == nparams);
3740
3741  bool HasExtraParameters = (nparams > 3);
3742
3743  // Darwin passes an undocumented fourth argument of type char**.  If
3744  // other platforms start sprouting these, the logic below will start
3745  // getting shifty.
3746  if (nparams == 4 &&
3747      Context.Target.getTriple().getOS() == llvm::Triple::Darwin)
3748    HasExtraParameters = false;
3749
3750  if (HasExtraParameters) {
3751    Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
3752    FD->setInvalidDecl(true);
3753    nparams = 3;
3754  }
3755
3756  // FIXME: a lot of the following diagnostics would be improved
3757  // if we had some location information about types.
3758
3759  QualType CharPP =
3760    Context.getPointerType(Context.getPointerType(Context.CharTy));
3761  QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
3762
3763  for (unsigned i = 0; i < nparams; ++i) {
3764    QualType AT = FTP->getArgType(i);
3765
3766    bool mismatch = true;
3767
3768    if (Context.hasSameUnqualifiedType(AT, Expected[i]))
3769      mismatch = false;
3770    else if (Expected[i] == CharPP) {
3771      // As an extension, the following forms are okay:
3772      //   char const **
3773      //   char const * const *
3774      //   char * const *
3775
3776      QualifierCollector qs;
3777      const PointerType* PT;
3778      if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
3779          (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
3780          (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
3781        qs.removeConst();
3782        mismatch = !qs.empty();
3783      }
3784    }
3785
3786    if (mismatch) {
3787      Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
3788      // TODO: suggest replacing given type with expected type
3789      FD->setInvalidDecl(true);
3790    }
3791  }
3792
3793  if (nparams == 1 && !FD->isInvalidDecl()) {
3794    Diag(FD->getLocation(), diag::warn_main_one_arg);
3795  }
3796}
3797
3798bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
3799  // FIXME: Need strict checking.  In C89, we need to check for
3800  // any assignment, increment, decrement, function-calls, or
3801  // commas outside of a sizeof.  In C99, it's the same list,
3802  // except that the aforementioned are allowed in unevaluated
3803  // expressions.  Everything else falls under the
3804  // "may accept other forms of constant expressions" exception.
3805  // (We never end up here for C++, so the constant expression
3806  // rules there don't matter.)
3807  if (Init->isConstantInitializer(Context))
3808    return false;
3809  Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
3810    << Init->getSourceRange();
3811  return true;
3812}
3813
3814void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init) {
3815  AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
3816}
3817
3818/// AddInitializerToDecl - Adds the initializer Init to the
3819/// declaration dcl. If DirectInit is true, this is C++ direct
3820/// initialization rather than copy initialization.
3821void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init, bool DirectInit) {
3822  Decl *RealDecl = dcl.getAs<Decl>();
3823  // If there is no declaration, there was an error parsing it.  Just ignore
3824  // the initializer.
3825  if (RealDecl == 0)
3826    return;
3827
3828  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
3829    // With declarators parsed the way they are, the parser cannot
3830    // distinguish between a normal initializer and a pure-specifier.
3831    // Thus this grotesque test.
3832    IntegerLiteral *IL;
3833    Expr *Init = static_cast<Expr *>(init.get());
3834    if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
3835        Context.getCanonicalType(IL->getType()) == Context.IntTy)
3836      CheckPureMethod(Method, Init->getSourceRange());
3837    else {
3838      Diag(Method->getLocation(), diag::err_member_function_initialization)
3839        << Method->getDeclName() << Init->getSourceRange();
3840      Method->setInvalidDecl();
3841    }
3842    return;
3843  }
3844
3845  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3846  if (!VDecl) {
3847    if (getLangOptions().CPlusPlus &&
3848        RealDecl->getLexicalDeclContext()->isRecord() &&
3849        isa<NamedDecl>(RealDecl))
3850      Diag(RealDecl->getLocation(), diag::err_member_initialization)
3851        << cast<NamedDecl>(RealDecl)->getDeclName();
3852    else
3853      Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3854    RealDecl->setInvalidDecl();
3855    return;
3856  }
3857
3858  // A definition must end up with a complete type, which means it must be
3859  // complete with the restriction that an array type might be completed by the
3860  // initializer; note that later code assumes this restriction.
3861  QualType BaseDeclType = VDecl->getType();
3862  if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
3863    BaseDeclType = Array->getElementType();
3864  if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
3865                          diag::err_typecheck_decl_incomplete_type)) {
3866    RealDecl->setInvalidDecl();
3867    return;
3868  }
3869
3870  // The variable can not have an abstract class type.
3871  if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
3872                             diag::err_abstract_type_in_decl,
3873                             AbstractVariableType))
3874    VDecl->setInvalidDecl();
3875
3876  const VarDecl *Def;
3877  if ((Def = VDecl->getDefinition()) && Def != VDecl) {
3878    Diag(VDecl->getLocation(), diag::err_redefinition)
3879      << VDecl->getDeclName();
3880    Diag(Def->getLocation(), diag::note_previous_definition);
3881    VDecl->setInvalidDecl();
3882    return;
3883  }
3884
3885  // Take ownership of the expression, now that we're sure we have somewhere
3886  // to put it.
3887  Expr *Init = init.takeAs<Expr>();
3888  assert(Init && "missing initializer");
3889
3890  // Capture the variable that is being initialized and the style of
3891  // initialization.
3892  InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
3893
3894  // FIXME: Poor source location information.
3895  InitializationKind Kind
3896    = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(),
3897                                                   Init->getLocStart(),
3898                                                   Init->getLocEnd())
3899                : InitializationKind::CreateCopy(VDecl->getLocation(),
3900                                                 Init->getLocStart());
3901
3902  // Get the decls type and save a reference for later, since
3903  // CheckInitializerTypes may change it.
3904  QualType DclT = VDecl->getType(), SavT = DclT;
3905  if (VDecl->isBlockVarDecl()) {
3906    if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
3907      Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
3908      VDecl->setInvalidDecl();
3909    } else if (!VDecl->isInvalidDecl()) {
3910      InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
3911      OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3912                                          MultiExprArg(*this, (void**)&Init, 1),
3913                                                &DclT);
3914      if (Result.isInvalid()) {
3915        VDecl->setInvalidDecl();
3916        return;
3917      }
3918
3919      Init = Result.takeAs<Expr>();
3920
3921      // C++ 3.6.2p2, allow dynamic initialization of static initializers.
3922      // Don't check invalid declarations to avoid emitting useless diagnostics.
3923      if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
3924        if (VDecl->getStorageClass() == VarDecl::Static) // C99 6.7.8p4.
3925          CheckForConstantInitializer(Init, DclT);
3926      }
3927    }
3928  } else if (VDecl->isStaticDataMember() &&
3929             VDecl->getLexicalDeclContext()->isRecord()) {
3930    // This is an in-class initialization for a static data member, e.g.,
3931    //
3932    // struct S {
3933    //   static const int value = 17;
3934    // };
3935
3936    // Attach the initializer
3937    VDecl->setInit(Init);
3938
3939    // C++ [class.mem]p4:
3940    //   A member-declarator can contain a constant-initializer only
3941    //   if it declares a static member (9.4) of const integral or
3942    //   const enumeration type, see 9.4.2.
3943    QualType T = VDecl->getType();
3944    if (!T->isDependentType() &&
3945        (!Context.getCanonicalType(T).isConstQualified() ||
3946         !T->isIntegralType())) {
3947      Diag(VDecl->getLocation(), diag::err_member_initialization)
3948        << VDecl->getDeclName() << Init->getSourceRange();
3949      VDecl->setInvalidDecl();
3950    } else {
3951      // C++ [class.static.data]p4:
3952      //   If a static data member is of const integral or const
3953      //   enumeration type, its declaration in the class definition
3954      //   can specify a constant-initializer which shall be an
3955      //   integral constant expression (5.19).
3956      if (!Init->isTypeDependent() &&
3957          !Init->getType()->isIntegralType()) {
3958        // We have a non-dependent, non-integral or enumeration type.
3959        Diag(Init->getSourceRange().getBegin(),
3960             diag::err_in_class_initializer_non_integral_type)
3961          << Init->getType() << Init->getSourceRange();
3962        VDecl->setInvalidDecl();
3963      } else if (!Init->isTypeDependent() && !Init->isValueDependent()) {
3964        // Check whether the expression is a constant expression.
3965        llvm::APSInt Value;
3966        SourceLocation Loc;
3967        if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) {
3968          Diag(Loc, diag::err_in_class_initializer_non_constant)
3969            << Init->getSourceRange();
3970          VDecl->setInvalidDecl();
3971        } else if (!VDecl->getType()->isDependentType())
3972          ImpCastExprToType(Init, VDecl->getType(), CastExpr::CK_IntegralCast);
3973      }
3974    }
3975  } else if (VDecl->isFileVarDecl()) {
3976    if (VDecl->getStorageClass() == VarDecl::Extern &&
3977        (!getLangOptions().CPlusPlus ||
3978         !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
3979      Diag(VDecl->getLocation(), diag::warn_extern_init);
3980    if (!VDecl->isInvalidDecl()) {
3981      InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
3982      OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3983                                          MultiExprArg(*this, (void**)&Init, 1),
3984                                                &DclT);
3985      if (Result.isInvalid()) {
3986        VDecl->setInvalidDecl();
3987        return;
3988      }
3989
3990      Init = Result.takeAs<Expr>();
3991    }
3992
3993    // C++ 3.6.2p2, allow dynamic initialization of static initializers.
3994    // Don't check invalid declarations to avoid emitting useless diagnostics.
3995    if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
3996      // C99 6.7.8p4. All file scoped initializers need to be constant.
3997      CheckForConstantInitializer(Init, DclT);
3998    }
3999  }
4000  // If the type changed, it means we had an incomplete type that was
4001  // completed by the initializer. For example:
4002  //   int ary[] = { 1, 3, 5 };
4003  // "ary" transitions from a VariableArrayType to a ConstantArrayType.
4004  if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
4005    VDecl->setType(DclT);
4006    Init->setType(DclT);
4007  }
4008
4009  Init = MaybeCreateCXXExprWithTemporaries(Init);
4010  // Attach the initializer to the decl.
4011  VDecl->setInit(Init);
4012
4013  if (getLangOptions().CPlusPlus) {
4014    // Make sure we mark the destructor as used if necessary.
4015    QualType InitType = VDecl->getType();
4016    while (const ArrayType *Array = Context.getAsArrayType(InitType))
4017      InitType = Context.getBaseElementType(Array);
4018    if (const RecordType *Record = InitType->getAs<RecordType>())
4019      FinalizeVarWithDestructor(VDecl, Record);
4020  }
4021
4022  return;
4023}
4024
4025/// ActOnInitializerError - Given that there was an error parsing an
4026/// initializer for the given declaration, try to return to some form
4027/// of sanity.
4028void Sema::ActOnInitializerError(DeclPtrTy dcl) {
4029  // Our main concern here is re-establishing invariants like "a
4030  // variable's type is either dependent or complete".
4031  Decl *D = dcl.getAs<Decl>();
4032  if (!D || D->isInvalidDecl()) return;
4033
4034  VarDecl *VD = dyn_cast<VarDecl>(D);
4035  if (!VD) return;
4036
4037  QualType Ty = VD->getType();
4038  if (Ty->isDependentType()) return;
4039
4040  // Require a complete type.
4041  if (RequireCompleteType(VD->getLocation(),
4042                          Context.getBaseElementType(Ty),
4043                          diag::err_typecheck_decl_incomplete_type)) {
4044    VD->setInvalidDecl();
4045    return;
4046  }
4047
4048  // Require an abstract type.
4049  if (RequireNonAbstractType(VD->getLocation(), Ty,
4050                             diag::err_abstract_type_in_decl,
4051                             AbstractVariableType)) {
4052    VD->setInvalidDecl();
4053    return;
4054  }
4055
4056  // Don't bother complaining about constructors or destructors,
4057  // though.
4058}
4059
4060void Sema::ActOnUninitializedDecl(DeclPtrTy dcl,
4061                                  bool TypeContainsUndeducedAuto) {
4062  Decl *RealDecl = dcl.getAs<Decl>();
4063
4064  // If there is no declaration, there was an error parsing it. Just ignore it.
4065  if (RealDecl == 0)
4066    return;
4067
4068  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
4069    QualType Type = Var->getType();
4070
4071    // C++0x [dcl.spec.auto]p3
4072    if (TypeContainsUndeducedAuto) {
4073      Diag(Var->getLocation(), diag::err_auto_var_requires_init)
4074        << Var->getDeclName() << Type;
4075      Var->setInvalidDecl();
4076      return;
4077    }
4078
4079    switch (Var->isThisDeclarationADefinition()) {
4080    case VarDecl::Definition:
4081      if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
4082        break;
4083
4084      // We have an out-of-line definition of a static data member
4085      // that has an in-class initializer, so we type-check this like
4086      // a declaration.
4087      //
4088      // Fall through
4089
4090    case VarDecl::DeclarationOnly:
4091      // It's only a declaration.
4092
4093      // Block scope. C99 6.7p7: If an identifier for an object is
4094      // declared with no linkage (C99 6.2.2p6), the type for the
4095      // object shall be complete.
4096      if (!Type->isDependentType() && Var->isBlockVarDecl() &&
4097          !Var->getLinkage() && !Var->isInvalidDecl() &&
4098          RequireCompleteType(Var->getLocation(), Type,
4099                              diag::err_typecheck_decl_incomplete_type))
4100        Var->setInvalidDecl();
4101
4102      // Make sure that the type is not abstract.
4103      if (!Type->isDependentType() && !Var->isInvalidDecl() &&
4104          RequireNonAbstractType(Var->getLocation(), Type,
4105                                 diag::err_abstract_type_in_decl,
4106                                 AbstractVariableType))
4107        Var->setInvalidDecl();
4108      return;
4109
4110    case VarDecl::TentativeDefinition:
4111      // File scope. C99 6.9.2p2: A declaration of an identifier for an
4112      // object that has file scope without an initializer, and without a
4113      // storage-class specifier or with the storage-class specifier "static",
4114      // constitutes a tentative definition. Note: A tentative definition with
4115      // external linkage is valid (C99 6.2.2p5).
4116      if (!Var->isInvalidDecl()) {
4117        if (const IncompleteArrayType *ArrayT
4118                                    = Context.getAsIncompleteArrayType(Type)) {
4119          if (RequireCompleteType(Var->getLocation(),
4120                                  ArrayT->getElementType(),
4121                                  diag::err_illegal_decl_array_incomplete_type))
4122            Var->setInvalidDecl();
4123        } else if (Var->getStorageClass() == VarDecl::Static) {
4124          // C99 6.9.2p3: If the declaration of an identifier for an object is
4125          // a tentative definition and has internal linkage (C99 6.2.2p3), the
4126          // declared type shall not be an incomplete type.
4127          // NOTE: code such as the following
4128          //     static struct s;
4129          //     struct s { int a; };
4130          // is accepted by gcc. Hence here we issue a warning instead of
4131          // an error and we do not invalidate the static declaration.
4132          // NOTE: to avoid multiple warnings, only check the first declaration.
4133          if (Var->getPreviousDeclaration() == 0)
4134            RequireCompleteType(Var->getLocation(), Type,
4135                                diag::ext_typecheck_decl_incomplete_type);
4136        }
4137      }
4138
4139      // Record the tentative definition; we're done.
4140      if (!Var->isInvalidDecl())
4141        TentativeDefinitions.push_back(Var);
4142      return;
4143    }
4144
4145    // Provide a specific diagnostic for uninitialized variable
4146    // definitions with incomplete array type.
4147    if (Type->isIncompleteArrayType()) {
4148      Diag(Var->getLocation(),
4149           diag::err_typecheck_incomplete_array_needs_initializer);
4150      Var->setInvalidDecl();
4151      return;
4152    }
4153
4154   // Provide a specific diagnostic for uninitialized variable
4155   // definitions with reference type.
4156   if (Type->isReferenceType()) {
4157     Diag(Var->getLocation(), diag::err_reference_var_requires_init)
4158       << Var->getDeclName()
4159       << SourceRange(Var->getLocation(), Var->getLocation());
4160     Var->setInvalidDecl();
4161     return;
4162   }
4163
4164    // Do not attempt to type-check the default initializer for a
4165    // variable with dependent type.
4166    if (Type->isDependentType())
4167      return;
4168
4169    if (Var->isInvalidDecl())
4170      return;
4171
4172    if (RequireCompleteType(Var->getLocation(),
4173                            Context.getBaseElementType(Type),
4174                            diag::err_typecheck_decl_incomplete_type)) {
4175      Var->setInvalidDecl();
4176      return;
4177    }
4178
4179    // The variable can not have an abstract class type.
4180    if (RequireNonAbstractType(Var->getLocation(), Type,
4181                               diag::err_abstract_type_in_decl,
4182                               AbstractVariableType)) {
4183      Var->setInvalidDecl();
4184      return;
4185    }
4186
4187    const RecordType *Record
4188      = Context.getBaseElementType(Type)->getAs<RecordType>();
4189    if (Record && getLangOptions().CPlusPlus && !getLangOptions().CPlusPlus0x &&
4190        cast<CXXRecordDecl>(Record->getDecl())->isPOD()) {
4191      // C++03 [dcl.init]p9:
4192      //   If no initializer is specified for an object, and the
4193      //   object is of (possibly cv-qualified) non-POD class type (or
4194      //   array thereof), the object shall be default-initialized; if
4195      //   the object is of const-qualified type, the underlying class
4196      //   type shall have a user-declared default
4197      //   constructor. Otherwise, if no initializer is specified for
4198      //   a non- static object, the object and its subobjects, if
4199      //   any, have an indeterminate initial value); if the object
4200      //   or any of its subobjects are of const-qualified type, the
4201      //   program is ill-formed.
4202      // FIXME: DPG thinks it is very fishy that C++0x disables this.
4203    } else {
4204      InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
4205      InitializationKind Kind
4206        = InitializationKind::CreateDefault(Var->getLocation());
4207
4208      InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
4209      OwningExprResult Init = InitSeq.Perform(*this, Entity, Kind,
4210                                              MultiExprArg(*this, 0, 0));
4211      if (Init.isInvalid())
4212        Var->setInvalidDecl();
4213      else if (Init.get())
4214        Var->setInit(MaybeCreateCXXExprWithTemporaries(Init.takeAs<Expr>()));
4215    }
4216
4217    if (!Var->isInvalidDecl() && getLangOptions().CPlusPlus && Record)
4218      FinalizeVarWithDestructor(Var, Record);
4219  }
4220}
4221
4222Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
4223                                                   DeclPtrTy *Group,
4224                                                   unsigned NumDecls) {
4225  llvm::SmallVector<Decl*, 8> Decls;
4226
4227  if (DS.isTypeSpecOwned())
4228    Decls.push_back((Decl*)DS.getTypeRep());
4229
4230  for (unsigned i = 0; i != NumDecls; ++i)
4231    if (Decl *D = Group[i].getAs<Decl>())
4232      Decls.push_back(D);
4233
4234  return DeclGroupPtrTy::make(DeclGroupRef::Create(Context,
4235                                                   Decls.data(), Decls.size()));
4236}
4237
4238
4239/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
4240/// to introduce parameters into function prototype scope.
4241Sema::DeclPtrTy
4242Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
4243  const DeclSpec &DS = D.getDeclSpec();
4244
4245  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
4246  VarDecl::StorageClass StorageClass = VarDecl::None;
4247  VarDecl::StorageClass StorageClassAsWritten = VarDecl::None;
4248  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
4249    StorageClass = VarDecl::Register;
4250    StorageClassAsWritten = VarDecl::Register;
4251  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
4252    Diag(DS.getStorageClassSpecLoc(),
4253         diag::err_invalid_storage_class_in_func_decl);
4254    D.getMutableDeclSpec().ClearStorageClassSpecs();
4255  }
4256
4257  if (D.getDeclSpec().isThreadSpecified())
4258    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4259
4260  DiagnoseFunctionSpecifiers(D);
4261
4262  // Check that there are no default arguments inside the type of this
4263  // parameter (C++ only).
4264  if (getLangOptions().CPlusPlus)
4265    CheckExtraCXXDefaultArguments(D);
4266
4267  TypeSourceInfo *TInfo = 0;
4268  TagDecl *OwnedDecl = 0;
4269  QualType parmDeclType = GetTypeForDeclarator(D, S, &TInfo, &OwnedDecl);
4270
4271  if (getLangOptions().CPlusPlus && OwnedDecl && OwnedDecl->isDefinition()) {
4272    // C++ [dcl.fct]p6:
4273    //   Types shall not be defined in return or parameter types.
4274    Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type)
4275      << Context.getTypeDeclType(OwnedDecl);
4276  }
4277
4278  // Check for redeclaration of parameters, e.g. int foo(int x, int x);
4279  IdentifierInfo *II = D.getIdentifier();
4280  if (II) {
4281    LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
4282                   ForRedeclaration);
4283    LookupName(R, S);
4284    if (R.isSingleResult()) {
4285      NamedDecl *PrevDecl = R.getFoundDecl();
4286      if (PrevDecl->isTemplateParameter()) {
4287        // Maybe we will complain about the shadowed template parameter.
4288        DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
4289        // Just pretend that we didn't see the previous declaration.
4290        PrevDecl = 0;
4291      } else if (S->isDeclScope(DeclPtrTy::make(PrevDecl))) {
4292        Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
4293        Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4294
4295        // Recover by removing the name
4296        II = 0;
4297        D.SetIdentifier(0, D.getIdentifierLoc());
4298        D.setInvalidType(true);
4299      }
4300    }
4301  }
4302
4303  // Temporarily put parameter variables in the translation unit, not
4304  // the enclosing context.  This prevents them from accidentally
4305  // looking like class members in C++.
4306  ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
4307                                    TInfo, parmDeclType, II,
4308                                    D.getIdentifierLoc(),
4309                                    StorageClass, StorageClassAsWritten);
4310
4311  if (D.isInvalidType())
4312    New->setInvalidDecl();
4313
4314  // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
4315  if (D.getCXXScopeSpec().isSet()) {
4316    Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
4317      << D.getCXXScopeSpec().getRange();
4318    New->setInvalidDecl();
4319  }
4320
4321  // Add the parameter declaration into this scope.
4322  S->AddDecl(DeclPtrTy::make(New));
4323  if (II)
4324    IdResolver.AddDecl(New);
4325
4326  ProcessDeclAttributes(S, New, D);
4327
4328  if (New->hasAttr<BlocksAttr>()) {
4329    Diag(New->getLocation(), diag::err_block_on_nonlocal);
4330  }
4331  return DeclPtrTy::make(New);
4332}
4333
4334ParmVarDecl *Sema::CheckParameter(DeclContext *DC,
4335                                  TypeSourceInfo *TSInfo, QualType T,
4336                                  IdentifierInfo *Name,
4337                                  SourceLocation NameLoc,
4338                                  VarDecl::StorageClass StorageClass,
4339                                  VarDecl::StorageClass StorageClassAsWritten) {
4340  ParmVarDecl *New = ParmVarDecl::Create(Context, DC, NameLoc, Name,
4341                                         adjustParameterType(T), TSInfo,
4342                                         StorageClass, StorageClassAsWritten,
4343                                         0);
4344
4345  // Parameters can not be abstract class types.
4346  // For record types, this is done by the AbstractClassUsageDiagnoser once
4347  // the class has been completely parsed.
4348  if (!CurContext->isRecord() &&
4349      RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
4350                             AbstractParamType))
4351    New->setInvalidDecl();
4352
4353  // Parameter declarators cannot be interface types. All ObjC objects are
4354  // passed by reference.
4355  if (T->isObjCObjectType()) {
4356    Diag(NameLoc,
4357         diag::err_object_cannot_be_passed_returned_by_value) << 1 << T;
4358    New->setInvalidDecl();
4359  }
4360
4361  // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
4362  // duration shall not be qualified by an address-space qualifier."
4363  // Since all parameters have automatic store duration, they can not have
4364  // an address space.
4365  if (T.getAddressSpace() != 0) {
4366    Diag(NameLoc, diag::err_arg_with_address_space);
4367    New->setInvalidDecl();
4368  }
4369
4370  return New;
4371}
4372
4373void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
4374                                           SourceLocation LocAfterDecls) {
4375  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4376         "Not a function declarator!");
4377  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
4378
4379  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
4380  // for a K&R function.
4381  if (!FTI.hasPrototype) {
4382    for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
4383      --i;
4384      if (FTI.ArgInfo[i].Param == 0) {
4385        llvm::SmallString<256> Code;
4386        llvm::raw_svector_ostream(Code) << "  int "
4387                                        << FTI.ArgInfo[i].Ident->getName()
4388                                        << ";\n";
4389        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
4390          << FTI.ArgInfo[i].Ident
4391          << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
4392
4393        // Implicitly declare the argument as type 'int' for lack of a better
4394        // type.
4395        DeclSpec DS;
4396        const char* PrevSpec; // unused
4397        unsigned DiagID; // unused
4398        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
4399                           PrevSpec, DiagID);
4400        Declarator ParamD(DS, Declarator::KNRTypeListContext);
4401        ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
4402        FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
4403      }
4404    }
4405  }
4406}
4407
4408Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
4409                                              Declarator &D) {
4410  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4411  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4412         "Not a function declarator!");
4413  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
4414
4415  if (FTI.hasPrototype) {
4416    // FIXME: Diagnose arguments without names in C.
4417  }
4418
4419  Scope *ParentScope = FnBodyScope->getParent();
4420
4421  DeclPtrTy DP = HandleDeclarator(ParentScope, D,
4422                                  MultiTemplateParamsArg(*this),
4423                                  /*IsFunctionDefinition=*/true);
4424  return ActOnStartOfFunctionDef(FnBodyScope, DP);
4425}
4426
4427static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
4428  // Don't warn about invalid declarations.
4429  if (FD->isInvalidDecl())
4430    return false;
4431
4432  // Or declarations that aren't global.
4433  if (!FD->isGlobal())
4434    return false;
4435
4436  // Don't warn about C++ member functions.
4437  if (isa<CXXMethodDecl>(FD))
4438    return false;
4439
4440  // Don't warn about 'main'.
4441  if (FD->isMain())
4442    return false;
4443
4444  // Don't warn about inline functions.
4445  if (FD->isInlineSpecified())
4446    return false;
4447
4448  // Don't warn about function templates.
4449  if (FD->getDescribedFunctionTemplate())
4450    return false;
4451
4452  // Don't warn about function template specializations.
4453  if (FD->isFunctionTemplateSpecialization())
4454    return false;
4455
4456  bool MissingPrototype = true;
4457  for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
4458       Prev; Prev = Prev->getPreviousDeclaration()) {
4459    // Ignore any declarations that occur in function or method
4460    // scope, because they aren't visible from the header.
4461    if (Prev->getDeclContext()->isFunctionOrMethod())
4462      continue;
4463
4464    MissingPrototype = !Prev->getType()->isFunctionProtoType();
4465    break;
4466  }
4467
4468  return MissingPrototype;
4469}
4470
4471Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclPtrTy D) {
4472  // Clear the last template instantiation error context.
4473  LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
4474
4475  if (!D)
4476    return D;
4477  FunctionDecl *FD = 0;
4478
4479  if (FunctionTemplateDecl *FunTmpl
4480        = dyn_cast<FunctionTemplateDecl>(D.getAs<Decl>()))
4481    FD = FunTmpl->getTemplatedDecl();
4482  else
4483    FD = cast<FunctionDecl>(D.getAs<Decl>());
4484
4485  // Enter a new function scope
4486  PushFunctionScope();
4487
4488  // See if this is a redefinition.
4489  // But don't complain if we're in GNU89 mode and the previous definition
4490  // was an extern inline function.
4491  const FunctionDecl *Definition;
4492  if (FD->getBody(Definition) &&
4493      !canRedefineFunction(Definition, getLangOptions())) {
4494    Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
4495    Diag(Definition->getLocation(), diag::note_previous_definition);
4496  }
4497
4498  // Builtin functions cannot be defined.
4499  if (unsigned BuiltinID = FD->getBuiltinID()) {
4500    if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4501      Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
4502      FD->setInvalidDecl();
4503    }
4504  }
4505
4506  // The return type of a function definition must be complete
4507  // (C99 6.9.1p3, C++ [dcl.fct]p6).
4508  QualType ResultType = FD->getResultType();
4509  if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
4510      !FD->isInvalidDecl() &&
4511      RequireCompleteType(FD->getLocation(), ResultType,
4512                          diag::err_func_def_incomplete_result))
4513    FD->setInvalidDecl();
4514
4515  // GNU warning -Wmissing-prototypes:
4516  //   Warn if a global function is defined without a previous
4517  //   prototype declaration. This warning is issued even if the
4518  //   definition itself provides a prototype. The aim is to detect
4519  //   global functions that fail to be declared in header files.
4520  if (ShouldWarnAboutMissingPrototype(FD))
4521    Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
4522
4523  if (FnBodyScope)
4524    PushDeclContext(FnBodyScope, FD);
4525
4526  // Check the validity of our function parameters
4527  CheckParmsForFunctionDef(FD);
4528
4529  bool ShouldCheckShadow =
4530    Diags.getDiagnosticLevel(diag::warn_decl_shadow) != Diagnostic::Ignored;
4531
4532  // Introduce our parameters into the function scope
4533  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
4534    ParmVarDecl *Param = FD->getParamDecl(p);
4535    Param->setOwningFunction(FD);
4536
4537    // If this has an identifier, add it to the scope stack.
4538    if (Param->getIdentifier() && FnBodyScope) {
4539      if (ShouldCheckShadow)
4540        CheckShadow(FnBodyScope, Param);
4541
4542      PushOnScopeChains(Param, FnBodyScope);
4543    }
4544  }
4545
4546  // Checking attributes of current function definition
4547  // dllimport attribute.
4548  if (FD->getAttr<DLLImportAttr>() &&
4549      (!FD->getAttr<DLLExportAttr>())) {
4550    // dllimport attribute cannot be applied to definition.
4551    if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
4552      Diag(FD->getLocation(),
4553           diag::err_attribute_can_be_applied_only_to_symbol_declaration)
4554        << "dllimport";
4555      FD->setInvalidDecl();
4556      return DeclPtrTy::make(FD);
4557    }
4558
4559    // Visual C++ appears to not think this is an issue, so only issue
4560    // a warning when Microsoft extensions are disabled.
4561    if (!LangOpts.Microsoft) {
4562      // If a symbol previously declared dllimport is later defined, the
4563      // attribute is ignored in subsequent references, and a warning is
4564      // emitted.
4565      Diag(FD->getLocation(),
4566           diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
4567        << FD->getNameAsCString() << "dllimport";
4568    }
4569  }
4570  return DeclPtrTy::make(FD);
4571}
4572
4573/// \brief Given the set of return statements within a function body,
4574/// compute the variables that are subject to the named return value
4575/// optimization.
4576///
4577/// Each of the variables that is subject to the named return value
4578/// optimization will be marked as NRVO variables in the AST, and any
4579/// return statement that has a marked NRVO variable as its NRVO candidate can
4580/// use the named return value optimization.
4581///
4582/// This function applies a very simplistic algorithm for NRVO: if every return
4583/// statement in the function has the same NRVO candidate, that candidate is
4584/// the NRVO variable.
4585///
4586/// FIXME: Employ a smarter algorithm that accounts for multiple return
4587/// statements and the lifetimes of the NRVO candidates. We should be able to
4588/// find a maximal set of NRVO variables.
4589static void ComputeNRVO(Stmt *Body, ReturnStmt **Returns, unsigned NumReturns) {
4590  const VarDecl *NRVOCandidate = 0;
4591  for (unsigned I = 0; I != NumReturns; ++I) {
4592    if (!Returns[I]->getNRVOCandidate())
4593      return;
4594
4595    if (!NRVOCandidate)
4596      NRVOCandidate = Returns[I]->getNRVOCandidate();
4597    else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
4598      return;
4599  }
4600
4601  if (NRVOCandidate)
4602    const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
4603}
4604
4605Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg) {
4606  return ActOnFinishFunctionBody(D, move(BodyArg), false);
4607}
4608
4609Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg,
4610                                              bool IsInstantiation) {
4611  Decl *dcl = D.getAs<Decl>();
4612  Stmt *Body = BodyArg.takeAs<Stmt>();
4613
4614  FunctionDecl *FD = 0;
4615  FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
4616  if (FunTmpl)
4617    FD = FunTmpl->getTemplatedDecl();
4618  else
4619    FD = dyn_cast_or_null<FunctionDecl>(dcl);
4620
4621  sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
4622
4623  if (FD) {
4624    FD->setBody(Body);
4625    if (FD->isMain()) {
4626      // C and C++ allow for main to automagically return 0.
4627      // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
4628      FD->setHasImplicitReturnZero(true);
4629      WP.disableCheckFallThrough();
4630    }
4631
4632    if (!FD->isInvalidDecl()) {
4633      DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
4634
4635      // If this is a constructor, we need a vtable.
4636      if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
4637        MarkVTableUsed(FD->getLocation(), Constructor->getParent());
4638
4639      ComputeNRVO(Body, FunctionScopes.back()->Returns.data(),
4640                  FunctionScopes.back()->Returns.size());
4641    }
4642
4643    assert(FD == getCurFunctionDecl() && "Function parsing confused");
4644  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
4645    assert(MD == getCurMethodDecl() && "Method parsing confused");
4646    MD->setBody(Body);
4647    MD->setEndLoc(Body->getLocEnd());
4648    if (!MD->isInvalidDecl())
4649      DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
4650  } else {
4651    Body->Destroy(Context);
4652    return DeclPtrTy();
4653  }
4654
4655  // Verify and clean out per-function state.
4656
4657  // Check goto/label use.
4658  for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
4659       I = getLabelMap().begin(), E = getLabelMap().end(); I != E; ++I) {
4660    LabelStmt *L = I->second;
4661
4662    // Verify that we have no forward references left.  If so, there was a goto
4663    // or address of a label taken, but no definition of it.  Label fwd
4664    // definitions are indicated with a null substmt.
4665    if (L->getSubStmt() != 0)
4666      continue;
4667
4668    // Emit error.
4669    Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
4670
4671    // At this point, we have gotos that use the bogus label.  Stitch it into
4672    // the function body so that they aren't leaked and that the AST is well
4673    // formed.
4674    if (Body == 0) {
4675      // The whole function wasn't parsed correctly, just delete this.
4676      L->Destroy(Context);
4677      continue;
4678    }
4679
4680    // Otherwise, the body is valid: we want to stitch the label decl into the
4681    // function somewhere so that it is properly owned and so that the goto
4682    // has a valid target.  Do this by creating a new compound stmt with the
4683    // label in it.
4684
4685    // Give the label a sub-statement.
4686    L->setSubStmt(new (Context) NullStmt(L->getIdentLoc()));
4687
4688    CompoundStmt *Compound = isa<CXXTryStmt>(Body) ?
4689                               cast<CXXTryStmt>(Body)->getTryBlock() :
4690                               cast<CompoundStmt>(Body);
4691    llvm::SmallVector<Stmt*, 64> Elements(Compound->body_begin(),
4692                                          Compound->body_end());
4693    Elements.push_back(L);
4694    Compound->setStmts(Context, Elements.data(), Elements.size());
4695  }
4696
4697  if (Body) {
4698    // C++ constructors that have function-try-blocks can't have return
4699    // statements in the handlers of that block. (C++ [except.handle]p14)
4700    // Verify this.
4701    if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
4702      DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
4703
4704    // Verify that that gotos and switch cases don't jump into scopes illegally.
4705    // Verify that that gotos and switch cases don't jump into scopes illegally.
4706    if (FunctionNeedsScopeChecking() &&
4707        !dcl->isInvalidDecl() &&
4708        !hasAnyErrorsInThisFunction())
4709      DiagnoseInvalidJumps(Body);
4710
4711    if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl))
4712      MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4713                                             Destructor->getParent());
4714
4715    // If any errors have occurred, clear out any temporaries that may have
4716    // been leftover. This ensures that these temporaries won't be picked up for
4717    // deletion in some later function.
4718    if (PP.getDiagnostics().hasErrorOccurred())
4719      ExprTemporaries.clear();
4720    else if (!isa<FunctionTemplateDecl>(dcl)) {
4721      // Since the body is valid, issue any analysis-based warnings that are
4722      // enabled.
4723      QualType ResultType;
4724      if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
4725        ResultType = FD->getResultType();
4726      }
4727      else {
4728        ObjCMethodDecl *MD = cast<ObjCMethodDecl>(dcl);
4729        ResultType = MD->getResultType();
4730      }
4731      AnalysisWarnings.IssueWarnings(WP, dcl);
4732    }
4733
4734    assert(ExprTemporaries.empty() && "Leftover temporaries in function");
4735  }
4736
4737  if (!IsInstantiation)
4738    PopDeclContext();
4739
4740  PopFunctionOrBlockScope();
4741
4742  // If any errors have occurred, clear out any temporaries that may have
4743  // been leftover. This ensures that these temporaries won't be picked up for
4744  // deletion in some later function.
4745  if (getDiagnostics().hasErrorOccurred())
4746    ExprTemporaries.clear();
4747
4748  return D;
4749}
4750
4751/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4752/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
4753NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
4754                                          IdentifierInfo &II, Scope *S) {
4755  // Before we produce a declaration for an implicitly defined
4756  // function, see whether there was a locally-scoped declaration of
4757  // this name as a function or variable. If so, use that
4758  // (non-visible) declaration, and complain about it.
4759  llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4760    = LocallyScopedExternalDecls.find(&II);
4761  if (Pos != LocallyScopedExternalDecls.end()) {
4762    Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
4763    Diag(Pos->second->getLocation(), diag::note_previous_declaration);
4764    return Pos->second;
4765  }
4766
4767  // Extension in C99.  Legal in C90, but warn about it.
4768  if (II.getName().startswith("__builtin_"))
4769    Diag(Loc, diag::warn_builtin_unknown) << &II;
4770  else if (getLangOptions().C99)
4771    Diag(Loc, diag::ext_implicit_function_decl) << &II;
4772  else
4773    Diag(Loc, diag::warn_implicit_function_decl) << &II;
4774
4775  // Set a Declarator for the implicit definition: int foo();
4776  const char *Dummy;
4777  DeclSpec DS;
4778  unsigned DiagID;
4779  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
4780  Error = Error; // Silence warning.
4781  assert(!Error && "Error setting up implicit decl!");
4782  Declarator D(DS, Declarator::BlockContext);
4783  D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
4784                                             0, 0, false, SourceLocation(),
4785                                             false, 0,0,0, Loc, Loc, D),
4786                SourceLocation());
4787  D.SetIdentifier(&II, Loc);
4788
4789  // Insert this function into translation-unit scope.
4790
4791  DeclContext *PrevDC = CurContext;
4792  CurContext = Context.getTranslationUnitDecl();
4793
4794  FunctionDecl *FD =
4795 dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D).getAs<Decl>());
4796  FD->setImplicit();
4797
4798  CurContext = PrevDC;
4799
4800  AddKnownFunctionAttributes(FD);
4801
4802  return FD;
4803}
4804
4805/// \brief Adds any function attributes that we know a priori based on
4806/// the declaration of this function.
4807///
4808/// These attributes can apply both to implicitly-declared builtins
4809/// (like __builtin___printf_chk) or to library-declared functions
4810/// like NSLog or printf.
4811void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
4812  if (FD->isInvalidDecl())
4813    return;
4814
4815  // If this is a built-in function, map its builtin attributes to
4816  // actual attributes.
4817  if (unsigned BuiltinID = FD->getBuiltinID()) {
4818    // Handle printf-formatting attributes.
4819    unsigned FormatIdx;
4820    bool HasVAListArg;
4821    if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
4822      if (!FD->getAttr<FormatAttr>())
4823        FD->addAttr(::new (Context) FormatAttr(Context, "printf", FormatIdx+1,
4824                                               HasVAListArg ? 0 : FormatIdx+2));
4825    }
4826
4827    // Mark const if we don't care about errno and that is the only
4828    // thing preventing the function from being const. This allows
4829    // IRgen to use LLVM intrinsics for such functions.
4830    if (!getLangOptions().MathErrno &&
4831        Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
4832      if (!FD->getAttr<ConstAttr>())
4833        FD->addAttr(::new (Context) ConstAttr());
4834    }
4835
4836    if (Context.BuiltinInfo.isNoReturn(BuiltinID))
4837      FD->setType(Context.getNoReturnType(FD->getType()));
4838    if (Context.BuiltinInfo.isNoThrow(BuiltinID))
4839      FD->addAttr(::new (Context) NoThrowAttr());
4840    if (Context.BuiltinInfo.isConst(BuiltinID))
4841      FD->addAttr(::new (Context) ConstAttr());
4842  }
4843
4844  IdentifierInfo *Name = FD->getIdentifier();
4845  if (!Name)
4846    return;
4847  if ((!getLangOptions().CPlusPlus &&
4848       FD->getDeclContext()->isTranslationUnit()) ||
4849      (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
4850       cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
4851       LinkageSpecDecl::lang_c)) {
4852    // Okay: this could be a libc/libm/Objective-C function we know
4853    // about.
4854  } else
4855    return;
4856
4857  if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
4858    // FIXME: NSLog and NSLogv should be target specific
4859    if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
4860      // FIXME: We known better than our headers.
4861      const_cast<FormatAttr *>(Format)->setType(Context, "printf");
4862    } else
4863      FD->addAttr(::new (Context) FormatAttr(Context, "printf", 1,
4864                                             Name->isStr("NSLogv") ? 0 : 2));
4865  } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
4866    // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
4867    // target-specific builtins, perhaps?
4868    if (!FD->getAttr<FormatAttr>())
4869      FD->addAttr(::new (Context) FormatAttr(Context, "printf", 2,
4870                                             Name->isStr("vasprintf") ? 0 : 3));
4871  }
4872}
4873
4874TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
4875                                    TypeSourceInfo *TInfo) {
4876  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
4877  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
4878
4879  if (!TInfo) {
4880    assert(D.isInvalidType() && "no declarator info for valid type");
4881    TInfo = Context.getTrivialTypeSourceInfo(T);
4882  }
4883
4884  // Scope manipulation handled by caller.
4885  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
4886                                           D.getIdentifierLoc(),
4887                                           D.getIdentifier(),
4888                                           TInfo);
4889
4890  if (const TagType *TT = T->getAs<TagType>()) {
4891    TagDecl *TD = TT->getDecl();
4892
4893    // If the TagDecl that the TypedefDecl points to is an anonymous decl
4894    // keep track of the TypedefDecl.
4895    if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
4896      TD->setTypedefForAnonDecl(NewTD);
4897  }
4898
4899  if (D.isInvalidType())
4900    NewTD->setInvalidDecl();
4901  return NewTD;
4902}
4903
4904
4905/// \brief Determine whether a tag with a given kind is acceptable
4906/// as a redeclaration of the given tag declaration.
4907///
4908/// \returns true if the new tag kind is acceptable, false otherwise.
4909bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
4910                                        TagTypeKind NewTag,
4911                                        SourceLocation NewTagLoc,
4912                                        const IdentifierInfo &Name) {
4913  // C++ [dcl.type.elab]p3:
4914  //   The class-key or enum keyword present in the
4915  //   elaborated-type-specifier shall agree in kind with the
4916  //   declaration to which the name in the elaborated-type-specifier
4917  //   refers. This rule also applies to the form of
4918  //   elaborated-type-specifier that declares a class-name or
4919  //   friend class since it can be construed as referring to the
4920  //   definition of the class. Thus, in any
4921  //   elaborated-type-specifier, the enum keyword shall be used to
4922  //   refer to an enumeration (7.2), the union class-key shall be
4923  //   used to refer to a union (clause 9), and either the class or
4924  //   struct class-key shall be used to refer to a class (clause 9)
4925  //   declared using the class or struct class-key.
4926  TagTypeKind OldTag = Previous->getTagKind();
4927  if (OldTag == NewTag)
4928    return true;
4929
4930  if ((OldTag == TTK_Struct || OldTag == TTK_Class) &&
4931      (NewTag == TTK_Struct || NewTag == TTK_Class)) {
4932    // Warn about the struct/class tag mismatch.
4933    bool isTemplate = false;
4934    if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
4935      isTemplate = Record->getDescribedClassTemplate();
4936
4937    Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
4938      << (NewTag == TTK_Class)
4939      << isTemplate << &Name
4940      << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
4941                              OldTag == TTK_Class? "class" : "struct");
4942    Diag(Previous->getLocation(), diag::note_previous_use);
4943    return true;
4944  }
4945  return false;
4946}
4947
4948/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
4949/// former case, Name will be non-null.  In the later case, Name will be null.
4950/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
4951/// reference/declaration/definition of a tag.
4952Sema::DeclPtrTy Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4953                               SourceLocation KWLoc, CXXScopeSpec &SS,
4954                               IdentifierInfo *Name, SourceLocation NameLoc,
4955                               AttributeList *Attr, AccessSpecifier AS,
4956                               MultiTemplateParamsArg TemplateParameterLists,
4957                               bool &OwnedDecl, bool &IsDependent) {
4958  // If this is not a definition, it must have a name.
4959  assert((Name != 0 || TUK == TUK_Definition) &&
4960         "Nameless record must be a definition!");
4961
4962  OwnedDecl = false;
4963  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4964
4965  // FIXME: Check explicit specializations more carefully.
4966  bool isExplicitSpecialization = false;
4967  if (TUK != TUK_Reference) {
4968    if (TemplateParameterList *TemplateParams
4969          = MatchTemplateParametersToScopeSpecifier(KWLoc, SS,
4970                        (TemplateParameterList**)TemplateParameterLists.get(),
4971                                              TemplateParameterLists.size(),
4972                                                    TUK == TUK_Friend,
4973                                                    isExplicitSpecialization)) {
4974      if (TemplateParams->size() > 0) {
4975        // This is a declaration or definition of a class template (which may
4976        // be a member of another template).
4977        OwnedDecl = false;
4978        DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
4979                                               SS, Name, NameLoc, Attr,
4980                                               TemplateParams,
4981                                               AS);
4982        TemplateParameterLists.release();
4983        return Result.get();
4984      } else {
4985        // The "template<>" header is extraneous.
4986        Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
4987          << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
4988        isExplicitSpecialization = true;
4989      }
4990    }
4991
4992    TemplateParameterLists.release();
4993  }
4994
4995  DeclContext *SearchDC = CurContext;
4996  DeclContext *DC = CurContext;
4997  bool isStdBadAlloc = false;
4998  bool Invalid = false;
4999
5000  RedeclarationKind Redecl = ForRedeclaration;
5001  if (TUK == TUK_Friend || TUK == TUK_Reference)
5002    Redecl = NotForRedeclaration;
5003
5004  LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
5005
5006  if (Name && SS.isNotEmpty()) {
5007    // We have a nested-name tag ('struct foo::bar').
5008
5009    // Check for invalid 'foo::'.
5010    if (SS.isInvalid()) {
5011      Name = 0;
5012      goto CreateNewDecl;
5013    }
5014
5015    // If this is a friend or a reference to a class in a dependent
5016    // context, don't try to make a decl for it.
5017    if (TUK == TUK_Friend || TUK == TUK_Reference) {
5018      DC = computeDeclContext(SS, false);
5019      if (!DC) {
5020        IsDependent = true;
5021        return DeclPtrTy();
5022      }
5023    } else {
5024      DC = computeDeclContext(SS, true);
5025      if (!DC) {
5026        Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
5027          << SS.getRange();
5028        return DeclPtrTy();
5029      }
5030    }
5031
5032    if (RequireCompleteDeclContext(SS, DC))
5033      return DeclPtrTy::make((Decl *)0);
5034
5035    SearchDC = DC;
5036    // Look-up name inside 'foo::'.
5037    LookupQualifiedName(Previous, DC);
5038
5039    if (Previous.isAmbiguous())
5040      return DeclPtrTy();
5041
5042    if (Previous.empty()) {
5043      // Name lookup did not find anything. However, if the
5044      // nested-name-specifier refers to the current instantiation,
5045      // and that current instantiation has any dependent base
5046      // classes, we might find something at instantiation time: treat
5047      // this as a dependent elaborated-type-specifier.
5048      if (Previous.wasNotFoundInCurrentInstantiation()) {
5049        IsDependent = true;
5050        return DeclPtrTy();
5051      }
5052
5053      // A tag 'foo::bar' must already exist.
5054      Diag(NameLoc, diag::err_not_tag_in_scope)
5055        << Kind << Name << DC << SS.getRange();
5056      Name = 0;
5057      Invalid = true;
5058      goto CreateNewDecl;
5059    }
5060  } else if (Name) {
5061    // If this is a named struct, check to see if there was a previous forward
5062    // declaration or definition.
5063    // FIXME: We're looking into outer scopes here, even when we
5064    // shouldn't be. Doing so can result in ambiguities that we
5065    // shouldn't be diagnosing.
5066    LookupName(Previous, S);
5067
5068    // Note:  there used to be some attempt at recovery here.
5069    if (Previous.isAmbiguous())
5070      return DeclPtrTy();
5071
5072    if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
5073      // FIXME: This makes sure that we ignore the contexts associated
5074      // with C structs, unions, and enums when looking for a matching
5075      // tag declaration or definition. See the similar lookup tweak
5076      // in Sema::LookupName; is there a better way to deal with this?
5077      while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
5078        SearchDC = SearchDC->getParent();
5079    }
5080  }
5081
5082  if (Previous.isSingleResult() &&
5083      Previous.getFoundDecl()->isTemplateParameter()) {
5084    // Maybe we will complain about the shadowed template parameter.
5085    DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
5086    // Just pretend that we didn't see the previous declaration.
5087    Previous.clear();
5088  }
5089
5090  if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
5091      DC->Equals(StdNamespace) && Name->isStr("bad_alloc")) {
5092    // This is a declaration of or a reference to "std::bad_alloc".
5093    isStdBadAlloc = true;
5094
5095    if (Previous.empty() && StdBadAlloc) {
5096      // std::bad_alloc has been implicitly declared (but made invisible to
5097      // name lookup). Fill in this implicit declaration as the previous
5098      // declaration, so that the declarations get chained appropriately.
5099      Previous.addDecl(StdBadAlloc);
5100    }
5101  }
5102
5103  // If we didn't find a previous declaration, and this is a reference
5104  // (or friend reference), move to the correct scope.  In C++, we
5105  // also need to do a redeclaration lookup there, just in case
5106  // there's a shadow friend decl.
5107  if (Name && Previous.empty() &&
5108      (TUK == TUK_Reference || TUK == TUK_Friend)) {
5109    if (Invalid) goto CreateNewDecl;
5110    assert(SS.isEmpty());
5111
5112    if (TUK == TUK_Reference) {
5113      // C++ [basic.scope.pdecl]p5:
5114      //   -- for an elaborated-type-specifier of the form
5115      //
5116      //          class-key identifier
5117      //
5118      //      if the elaborated-type-specifier is used in the
5119      //      decl-specifier-seq or parameter-declaration-clause of a
5120      //      function defined in namespace scope, the identifier is
5121      //      declared as a class-name in the namespace that contains
5122      //      the declaration; otherwise, except as a friend
5123      //      declaration, the identifier is declared in the smallest
5124      //      non-class, non-function-prototype scope that contains the
5125      //      declaration.
5126      //
5127      // C99 6.7.2.3p8 has a similar (but not identical!) provision for
5128      // C structs and unions.
5129      //
5130      // It is an error in C++ to declare (rather than define) an enum
5131      // type, including via an elaborated type specifier.  We'll
5132      // diagnose that later; for now, declare the enum in the same
5133      // scope as we would have picked for any other tag type.
5134      //
5135      // GNU C also supports this behavior as part of its incomplete
5136      // enum types extension, while GNU C++ does not.
5137      //
5138      // Find the context where we'll be declaring the tag.
5139      // FIXME: We would like to maintain the current DeclContext as the
5140      // lexical context,
5141      while (SearchDC->isRecord())
5142        SearchDC = SearchDC->getParent();
5143
5144      // Find the scope where we'll be declaring the tag.
5145      while (S->isClassScope() ||
5146             (getLangOptions().CPlusPlus &&
5147              S->isFunctionPrototypeScope()) ||
5148             ((S->getFlags() & Scope::DeclScope) == 0) ||
5149             (S->getEntity() &&
5150              ((DeclContext *)S->getEntity())->isTransparentContext()))
5151        S = S->getParent();
5152    } else {
5153      assert(TUK == TUK_Friend);
5154      // C++ [namespace.memdef]p3:
5155      //   If a friend declaration in a non-local class first declares a
5156      //   class or function, the friend class or function is a member of
5157      //   the innermost enclosing namespace.
5158      SearchDC = SearchDC->getEnclosingNamespaceContext();
5159    }
5160
5161    // In C++, we need to do a redeclaration lookup to properly
5162    // diagnose some problems.
5163    if (getLangOptions().CPlusPlus) {
5164      Previous.setRedeclarationKind(ForRedeclaration);
5165      LookupQualifiedName(Previous, SearchDC);
5166    }
5167  }
5168
5169  if (!Previous.empty()) {
5170    NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
5171
5172    // It's okay to have a tag decl in the same scope as a typedef
5173    // which hides a tag decl in the same scope.  Finding this
5174    // insanity with a redeclaration lookup can only actually happen
5175    // in C++.
5176    //
5177    // This is also okay for elaborated-type-specifiers, which is
5178    // technically forbidden by the current standard but which is
5179    // okay according to the likely resolution of an open issue;
5180    // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
5181    if (getLangOptions().CPlusPlus) {
5182      if (TypedefDecl *TD = dyn_cast<TypedefDecl>(PrevDecl)) {
5183        if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
5184          TagDecl *Tag = TT->getDecl();
5185          if (Tag->getDeclName() == Name &&
5186              Tag->getDeclContext()->getLookupContext()
5187                          ->Equals(TD->getDeclContext()->getLookupContext())) {
5188            PrevDecl = Tag;
5189            Previous.clear();
5190            Previous.addDecl(Tag);
5191          }
5192        }
5193      }
5194    }
5195
5196    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
5197      // If this is a use of a previous tag, or if the tag is already declared
5198      // in the same scope (so that the definition/declaration completes or
5199      // rementions the tag), reuse the decl.
5200      if (TUK == TUK_Reference || TUK == TUK_Friend ||
5201          isDeclInScope(PrevDecl, SearchDC, S)) {
5202        // Make sure that this wasn't declared as an enum and now used as a
5203        // struct or something similar.
5204        if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, KWLoc, *Name)) {
5205          bool SafeToContinue
5206            = (PrevTagDecl->getTagKind() != TTK_Enum &&
5207               Kind != TTK_Enum);
5208          if (SafeToContinue)
5209            Diag(KWLoc, diag::err_use_with_wrong_tag)
5210              << Name
5211              << FixItHint::CreateReplacement(SourceRange(KWLoc),
5212                                              PrevTagDecl->getKindName());
5213          else
5214            Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
5215          Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
5216
5217          if (SafeToContinue)
5218            Kind = PrevTagDecl->getTagKind();
5219          else {
5220            // Recover by making this an anonymous redefinition.
5221            Name = 0;
5222            Previous.clear();
5223            Invalid = true;
5224          }
5225        }
5226
5227        if (!Invalid) {
5228          // If this is a use, just return the declaration we found.
5229
5230          // FIXME: In the future, return a variant or some other clue
5231          // for the consumer of this Decl to know it doesn't own it.
5232          // For our current ASTs this shouldn't be a problem, but will
5233          // need to be changed with DeclGroups.
5234          if (TUK == TUK_Reference || TUK == TUK_Friend)
5235            return DeclPtrTy::make(PrevTagDecl);
5236
5237          // Diagnose attempts to redefine a tag.
5238          if (TUK == TUK_Definition) {
5239            if (TagDecl *Def = PrevTagDecl->getDefinition()) {
5240              // If we're defining a specialization and the previous definition
5241              // is from an implicit instantiation, don't emit an error
5242              // here; we'll catch this in the general case below.
5243              if (!isExplicitSpecialization ||
5244                  !isa<CXXRecordDecl>(Def) ||
5245                  cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind()
5246                                               == TSK_ExplicitSpecialization) {
5247                Diag(NameLoc, diag::err_redefinition) << Name;
5248                Diag(Def->getLocation(), diag::note_previous_definition);
5249                // If this is a redefinition, recover by making this
5250                // struct be anonymous, which will make any later
5251                // references get the previous definition.
5252                Name = 0;
5253                Previous.clear();
5254                Invalid = true;
5255              }
5256            } else {
5257              // If the type is currently being defined, complain
5258              // about a nested redefinition.
5259              TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
5260              if (Tag->isBeingDefined()) {
5261                Diag(NameLoc, diag::err_nested_redefinition) << Name;
5262                Diag(PrevTagDecl->getLocation(),
5263                     diag::note_previous_definition);
5264                Name = 0;
5265                Previous.clear();
5266                Invalid = true;
5267              }
5268            }
5269
5270            // Okay, this is definition of a previously declared or referenced
5271            // tag PrevDecl. We're going to create a new Decl for it.
5272          }
5273        }
5274        // If we get here we have (another) forward declaration or we
5275        // have a definition.  Just create a new decl.
5276
5277      } else {
5278        // If we get here, this is a definition of a new tag type in a nested
5279        // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
5280        // new decl/type.  We set PrevDecl to NULL so that the entities
5281        // have distinct types.
5282        Previous.clear();
5283      }
5284      // If we get here, we're going to create a new Decl. If PrevDecl
5285      // is non-NULL, it's a definition of the tag declared by
5286      // PrevDecl. If it's NULL, we have a new definition.
5287
5288
5289    // Otherwise, PrevDecl is not a tag, but was found with tag
5290    // lookup.  This is only actually possible in C++, where a few
5291    // things like templates still live in the tag namespace.
5292    } else {
5293      assert(getLangOptions().CPlusPlus);
5294
5295      // Use a better diagnostic if an elaborated-type-specifier
5296      // found the wrong kind of type on the first
5297      // (non-redeclaration) lookup.
5298      if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
5299          !Previous.isForRedeclaration()) {
5300        unsigned Kind = 0;
5301        if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
5302        else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 2;
5303        Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
5304        Diag(PrevDecl->getLocation(), diag::note_declared_at);
5305        Invalid = true;
5306
5307      // Otherwise, only diagnose if the declaration is in scope.
5308      } else if (!isDeclInScope(PrevDecl, SearchDC, S)) {
5309        // do nothing
5310
5311      // Diagnose implicit declarations introduced by elaborated types.
5312      } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
5313        unsigned Kind = 0;
5314        if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
5315        else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 2;
5316        Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
5317        Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
5318        Invalid = true;
5319
5320      // Otherwise it's a declaration.  Call out a particularly common
5321      // case here.
5322      } else if (isa<TypedefDecl>(PrevDecl)) {
5323        Diag(NameLoc, diag::err_tag_definition_of_typedef)
5324          << Name
5325          << cast<TypedefDecl>(PrevDecl)->getUnderlyingType();
5326        Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
5327        Invalid = true;
5328
5329      // Otherwise, diagnose.
5330      } else {
5331        // The tag name clashes with something else in the target scope,
5332        // issue an error and recover by making this tag be anonymous.
5333        Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
5334        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5335        Name = 0;
5336        Invalid = true;
5337      }
5338
5339      // The existing declaration isn't relevant to us; we're in a
5340      // new scope, so clear out the previous declaration.
5341      Previous.clear();
5342    }
5343  }
5344
5345CreateNewDecl:
5346
5347  TagDecl *PrevDecl = 0;
5348  if (Previous.isSingleResult())
5349    PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
5350
5351  // If there is an identifier, use the location of the identifier as the
5352  // location of the decl, otherwise use the location of the struct/union
5353  // keyword.
5354  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
5355
5356  // Otherwise, create a new declaration. If there is a previous
5357  // declaration of the same entity, the two will be linked via
5358  // PrevDecl.
5359  TagDecl *New;
5360
5361  if (Kind == TTK_Enum) {
5362    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
5363    // enum X { A, B, C } D;    D should chain to X.
5364    New = EnumDecl::Create(Context, SearchDC, Loc, Name, KWLoc,
5365                           cast_or_null<EnumDecl>(PrevDecl));
5366    // If this is an undefined enum, warn.
5367    if (TUK != TUK_Definition && !Invalid)  {
5368      unsigned DK = getLangOptions().CPlusPlus? diag::err_forward_ref_enum
5369                                              : diag::ext_forward_ref_enum;
5370      Diag(Loc, DK);
5371    }
5372  } else {
5373    // struct/union/class
5374
5375    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
5376    // struct X { int A; } D;    D should chain to X.
5377    if (getLangOptions().CPlusPlus) {
5378      // FIXME: Look for a way to use RecordDecl for simple structs.
5379      New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
5380                                  cast_or_null<CXXRecordDecl>(PrevDecl));
5381
5382      if (isStdBadAlloc && (!StdBadAlloc || StdBadAlloc->isImplicit()))
5383        StdBadAlloc = cast<CXXRecordDecl>(New);
5384    } else
5385      New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
5386                               cast_or_null<RecordDecl>(PrevDecl));
5387  }
5388
5389  // Maybe add qualifier info.
5390  if (SS.isNotEmpty()) {
5391    if (SS.isSet()) {
5392      NestedNameSpecifier *NNS
5393        = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5394      New->setQualifierInfo(NNS, SS.getRange());
5395    }
5396    else
5397      Invalid = true;
5398  }
5399
5400  if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
5401    // Add alignment attributes if necessary; these attributes are checked when
5402    // the ASTContext lays out the structure.
5403    //
5404    // It is important for implementing the correct semantics that this
5405    // happen here (in act on tag decl). The #pragma pack stack is
5406    // maintained as a result of parser callbacks which can occur at
5407    // many points during the parsing of a struct declaration (because
5408    // the #pragma tokens are effectively skipped over during the
5409    // parsing of the struct).
5410    AddAlignmentAttributesForRecord(RD);
5411  }
5412
5413  // If this is a specialization of a member class (of a class template),
5414  // check the specialization.
5415  if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
5416    Invalid = true;
5417
5418  if (Invalid)
5419    New->setInvalidDecl();
5420
5421  if (Attr)
5422    ProcessDeclAttributeList(S, New, Attr);
5423
5424  // If we're declaring or defining a tag in function prototype scope
5425  // in C, note that this type can only be used within the function.
5426  if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
5427    Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
5428
5429  // Set the lexical context. If the tag has a C++ scope specifier, the
5430  // lexical context will be different from the semantic context.
5431  New->setLexicalDeclContext(CurContext);
5432
5433  // Mark this as a friend decl if applicable.
5434  if (TUK == TUK_Friend)
5435    New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty());
5436
5437  // Set the access specifier.
5438  if (!Invalid && SearchDC->isRecord())
5439    SetMemberAccessSpecifier(New, PrevDecl, AS);
5440
5441  if (TUK == TUK_Definition)
5442    New->startDefinition();
5443
5444  // If this has an identifier, add it to the scope stack.
5445  if (TUK == TUK_Friend) {
5446    // We might be replacing an existing declaration in the lookup tables;
5447    // if so, borrow its access specifier.
5448    if (PrevDecl)
5449      New->setAccess(PrevDecl->getAccess());
5450
5451    DeclContext *DC = New->getDeclContext()->getLookupContext();
5452    DC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
5453    if (Name) // can be null along some error paths
5454      if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
5455        PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
5456  } else if (Name) {
5457    S = getNonFieldDeclScope(S);
5458    PushOnScopeChains(New, S);
5459  } else {
5460    CurContext->addDecl(New);
5461  }
5462
5463  // If this is the C FILE type, notify the AST context.
5464  if (IdentifierInfo *II = New->getIdentifier())
5465    if (!New->isInvalidDecl() &&
5466        New->getDeclContext()->getLookupContext()->isTranslationUnit() &&
5467        II->isStr("FILE"))
5468      Context.setFILEDecl(New);
5469
5470  OwnedDecl = true;
5471  return DeclPtrTy::make(New);
5472}
5473
5474void Sema::ActOnTagStartDefinition(Scope *S, DeclPtrTy TagD) {
5475  AdjustDeclIfTemplate(TagD);
5476  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
5477
5478  // Enter the tag context.
5479  PushDeclContext(S, Tag);
5480}
5481
5482void Sema::ActOnStartCXXMemberDeclarations(Scope *S, DeclPtrTy TagD,
5483                                           SourceLocation LBraceLoc) {
5484  AdjustDeclIfTemplate(TagD);
5485  CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD.getAs<Decl>());
5486
5487  FieldCollector->StartClass();
5488
5489  if (!Record->getIdentifier())
5490    return;
5491
5492  // C++ [class]p2:
5493  //   [...] The class-name is also inserted into the scope of the
5494  //   class itself; this is known as the injected-class-name. For
5495  //   purposes of access checking, the injected-class-name is treated
5496  //   as if it were a public member name.
5497  CXXRecordDecl *InjectedClassName
5498    = CXXRecordDecl::Create(Context, Record->getTagKind(),
5499                            CurContext, Record->getLocation(),
5500                            Record->getIdentifier(),
5501                            Record->getTagKeywordLoc(),
5502                            Record);
5503  InjectedClassName->setImplicit();
5504  InjectedClassName->setAccess(AS_public);
5505  if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
5506      InjectedClassName->setDescribedClassTemplate(Template);
5507  PushOnScopeChains(InjectedClassName, S);
5508  assert(InjectedClassName->isInjectedClassName() &&
5509         "Broken injected-class-name");
5510}
5511
5512void Sema::ActOnTagFinishDefinition(Scope *S, DeclPtrTy TagD,
5513                                    SourceLocation RBraceLoc) {
5514  AdjustDeclIfTemplate(TagD);
5515  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
5516  Tag->setRBraceLoc(RBraceLoc);
5517
5518  if (isa<CXXRecordDecl>(Tag))
5519    FieldCollector->FinishClass();
5520
5521  // Exit this scope of this tag's definition.
5522  PopDeclContext();
5523
5524  // Notify the consumer that we've defined a tag.
5525  Consumer.HandleTagDeclDefinition(Tag);
5526}
5527
5528void Sema::ActOnTagDefinitionError(Scope *S, DeclPtrTy TagD) {
5529  AdjustDeclIfTemplate(TagD);
5530  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
5531  Tag->setInvalidDecl();
5532
5533  // We're undoing ActOnTagStartDefinition here, not
5534  // ActOnStartCXXMemberDeclarations, so we don't have to mess with
5535  // the FieldCollector.
5536
5537  PopDeclContext();
5538}
5539
5540// Note that FieldName may be null for anonymous bitfields.
5541bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
5542                          QualType FieldTy, const Expr *BitWidth,
5543                          bool *ZeroWidth) {
5544  // Default to true; that shouldn't confuse checks for emptiness
5545  if (ZeroWidth)
5546    *ZeroWidth = true;
5547
5548  // C99 6.7.2.1p4 - verify the field type.
5549  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
5550  if (!FieldTy->isDependentType() && !FieldTy->isIntegralType()) {
5551    // Handle incomplete types with specific error.
5552    if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
5553      return true;
5554    if (FieldName)
5555      return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
5556        << FieldName << FieldTy << BitWidth->getSourceRange();
5557    return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
5558      << FieldTy << BitWidth->getSourceRange();
5559  }
5560
5561  // If the bit-width is type- or value-dependent, don't try to check
5562  // it now.
5563  if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
5564    return false;
5565
5566  llvm::APSInt Value;
5567  if (VerifyIntegerConstantExpression(BitWidth, &Value))
5568    return true;
5569
5570  if (Value != 0 && ZeroWidth)
5571    *ZeroWidth = false;
5572
5573  // Zero-width bitfield is ok for anonymous field.
5574  if (Value == 0 && FieldName)
5575    return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
5576
5577  if (Value.isSigned() && Value.isNegative()) {
5578    if (FieldName)
5579      return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
5580               << FieldName << Value.toString(10);
5581    return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
5582      << Value.toString(10);
5583  }
5584
5585  if (!FieldTy->isDependentType()) {
5586    uint64_t TypeSize = Context.getTypeSize(FieldTy);
5587    if (Value.getZExtValue() > TypeSize) {
5588      if (!getLangOptions().CPlusPlus) {
5589        if (FieldName)
5590          return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
5591            << FieldName << (unsigned)Value.getZExtValue()
5592            << (unsigned)TypeSize;
5593
5594        return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
5595          << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
5596      }
5597
5598      if (FieldName)
5599        Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
5600          << FieldName << (unsigned)Value.getZExtValue()
5601          << (unsigned)TypeSize;
5602      else
5603        Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
5604          << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
5605    }
5606  }
5607
5608  return false;
5609}
5610
5611/// ActOnField - Each field of a struct/union/class is passed into this in order
5612/// to create a FieldDecl object for it.
5613Sema::DeclPtrTy Sema::ActOnField(Scope *S, DeclPtrTy TagD,
5614                                 SourceLocation DeclStart,
5615                                 Declarator &D, ExprTy *BitfieldWidth) {
5616  FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD.getAs<Decl>()),
5617                               DeclStart, D, static_cast<Expr*>(BitfieldWidth),
5618                               AS_public);
5619  return DeclPtrTy::make(Res);
5620}
5621
5622/// HandleField - Analyze a field of a C struct or a C++ data member.
5623///
5624FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
5625                             SourceLocation DeclStart,
5626                             Declarator &D, Expr *BitWidth,
5627                             AccessSpecifier AS) {
5628  IdentifierInfo *II = D.getIdentifier();
5629  SourceLocation Loc = DeclStart;
5630  if (II) Loc = D.getIdentifierLoc();
5631
5632  TypeSourceInfo *TInfo = 0;
5633  QualType T = GetTypeForDeclarator(D, S, &TInfo);
5634  if (getLangOptions().CPlusPlus)
5635    CheckExtraCXXDefaultArguments(D);
5636
5637  DiagnoseFunctionSpecifiers(D);
5638
5639  if (D.getDeclSpec().isThreadSpecified())
5640    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
5641
5642  NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
5643                                         ForRedeclaration);
5644
5645  if (PrevDecl && PrevDecl->isTemplateParameter()) {
5646    // Maybe we will complain about the shadowed template parameter.
5647    DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5648    // Just pretend that we didn't see the previous declaration.
5649    PrevDecl = 0;
5650  }
5651
5652  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
5653    PrevDecl = 0;
5654
5655  bool Mutable
5656    = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
5657  SourceLocation TSSL = D.getSourceRange().getBegin();
5658  FieldDecl *NewFD
5659    = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, TSSL,
5660                     AS, PrevDecl, &D);
5661
5662  if (NewFD->isInvalidDecl())
5663    Record->setInvalidDecl();
5664
5665  if (NewFD->isInvalidDecl() && PrevDecl) {
5666    // Don't introduce NewFD into scope; there's already something
5667    // with the same name in the same scope.
5668  } else if (II) {
5669    PushOnScopeChains(NewFD, S);
5670  } else
5671    Record->addDecl(NewFD);
5672
5673  return NewFD;
5674}
5675
5676/// \brief Build a new FieldDecl and check its well-formedness.
5677///
5678/// This routine builds a new FieldDecl given the fields name, type,
5679/// record, etc. \p PrevDecl should refer to any previous declaration
5680/// with the same name and in the same scope as the field to be
5681/// created.
5682///
5683/// \returns a new FieldDecl.
5684///
5685/// \todo The Declarator argument is a hack. It will be removed once
5686FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
5687                                TypeSourceInfo *TInfo,
5688                                RecordDecl *Record, SourceLocation Loc,
5689                                bool Mutable, Expr *BitWidth,
5690                                SourceLocation TSSL,
5691                                AccessSpecifier AS, NamedDecl *PrevDecl,
5692                                Declarator *D) {
5693  IdentifierInfo *II = Name.getAsIdentifierInfo();
5694  bool InvalidDecl = false;
5695  if (D) InvalidDecl = D->isInvalidType();
5696
5697  // If we receive a broken type, recover by assuming 'int' and
5698  // marking this declaration as invalid.
5699  if (T.isNull()) {
5700    InvalidDecl = true;
5701    T = Context.IntTy;
5702  }
5703
5704  QualType EltTy = Context.getBaseElementType(T);
5705  if (!EltTy->isDependentType() &&
5706      RequireCompleteType(Loc, EltTy, diag::err_field_incomplete))
5707    InvalidDecl = true;
5708
5709  // C99 6.7.2.1p8: A member of a structure or union may have any type other
5710  // than a variably modified type.
5711  if (!InvalidDecl && T->isVariablyModifiedType()) {
5712    bool SizeIsNegative;
5713    QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
5714                                                           SizeIsNegative);
5715    if (!FixedTy.isNull()) {
5716      Diag(Loc, diag::warn_illegal_constant_array_size);
5717      T = FixedTy;
5718    } else {
5719      if (SizeIsNegative)
5720        Diag(Loc, diag::err_typecheck_negative_array_size);
5721      else
5722        Diag(Loc, diag::err_typecheck_field_variable_size);
5723      InvalidDecl = true;
5724    }
5725  }
5726
5727  // Fields can not have abstract class types
5728  if (!InvalidDecl && RequireNonAbstractType(Loc, T,
5729                                             diag::err_abstract_type_in_decl,
5730                                             AbstractFieldType))
5731    InvalidDecl = true;
5732
5733  bool ZeroWidth = false;
5734  // If this is declared as a bit-field, check the bit-field.
5735  if (!InvalidDecl && BitWidth &&
5736      VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) {
5737    InvalidDecl = true;
5738    DeleteExpr(BitWidth);
5739    BitWidth = 0;
5740    ZeroWidth = false;
5741  }
5742
5743  // Check that 'mutable' is consistent with the type of the declaration.
5744  if (!InvalidDecl && Mutable) {
5745    unsigned DiagID = 0;
5746    if (T->isReferenceType())
5747      DiagID = diag::err_mutable_reference;
5748    else if (T.isConstQualified())
5749      DiagID = diag::err_mutable_const;
5750
5751    if (DiagID) {
5752      SourceLocation ErrLoc = Loc;
5753      if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
5754        ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
5755      Diag(ErrLoc, DiagID);
5756      Mutable = false;
5757      InvalidDecl = true;
5758    }
5759  }
5760
5761  FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, TInfo,
5762                                       BitWidth, Mutable);
5763  if (InvalidDecl)
5764    NewFD->setInvalidDecl();
5765
5766  if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
5767    Diag(Loc, diag::err_duplicate_member) << II;
5768    Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5769    NewFD->setInvalidDecl();
5770  }
5771
5772  if (!InvalidDecl && getLangOptions().CPlusPlus) {
5773    CXXRecordDecl* CXXRecord = cast<CXXRecordDecl>(Record);
5774
5775    if (!T->isPODType())
5776      CXXRecord->setPOD(false);
5777    if (!ZeroWidth)
5778      CXXRecord->setEmpty(false);
5779
5780    if (const RecordType *RT = EltTy->getAs<RecordType>()) {
5781      CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
5782
5783      if (!RDecl->hasTrivialConstructor())
5784        CXXRecord->setHasTrivialConstructor(false);
5785      if (!RDecl->hasTrivialCopyConstructor())
5786        CXXRecord->setHasTrivialCopyConstructor(false);
5787      if (!RDecl->hasTrivialCopyAssignment())
5788        CXXRecord->setHasTrivialCopyAssignment(false);
5789      if (!RDecl->hasTrivialDestructor())
5790        CXXRecord->setHasTrivialDestructor(false);
5791
5792      // C++ 9.5p1: An object of a class with a non-trivial
5793      // constructor, a non-trivial copy constructor, a non-trivial
5794      // destructor, or a non-trivial copy assignment operator
5795      // cannot be a member of a union, nor can an array of such
5796      // objects.
5797      // TODO: C++0x alters this restriction significantly.
5798      if (Record->isUnion()) {
5799        // We check for copy constructors before constructors
5800        // because otherwise we'll never get complaints about
5801        // copy constructors.
5802
5803        CXXSpecialMember member = CXXInvalid;
5804        if (!RDecl->hasTrivialCopyConstructor())
5805          member = CXXCopyConstructor;
5806        else if (!RDecl->hasTrivialConstructor())
5807          member = CXXConstructor;
5808        else if (!RDecl->hasTrivialCopyAssignment())
5809          member = CXXCopyAssignment;
5810        else if (!RDecl->hasTrivialDestructor())
5811          member = CXXDestructor;
5812
5813        if (member != CXXInvalid) {
5814          Diag(Loc, diag::err_illegal_union_member) << Name << member;
5815          DiagnoseNontrivial(RT, member);
5816          NewFD->setInvalidDecl();
5817        }
5818      }
5819    }
5820  }
5821
5822  // FIXME: We need to pass in the attributes given an AST
5823  // representation, not a parser representation.
5824  if (D)
5825    // FIXME: What to pass instead of TUScope?
5826    ProcessDeclAttributes(TUScope, NewFD, *D);
5827
5828  if (T.isObjCGCWeak())
5829    Diag(Loc, diag::warn_attribute_weak_on_field);
5830
5831  NewFD->setAccess(AS);
5832
5833  // C++ [dcl.init.aggr]p1:
5834  //   An aggregate is an array or a class (clause 9) with [...] no
5835  //   private or protected non-static data members (clause 11).
5836  // A POD must be an aggregate.
5837  if (getLangOptions().CPlusPlus &&
5838      (AS == AS_private || AS == AS_protected)) {
5839    CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
5840    CXXRecord->setAggregate(false);
5841    CXXRecord->setPOD(false);
5842  }
5843
5844  return NewFD;
5845}
5846
5847/// DiagnoseNontrivial - Given that a class has a non-trivial
5848/// special member, figure out why.
5849void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
5850  QualType QT(T, 0U);
5851  CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
5852
5853  // Check whether the member was user-declared.
5854  switch (member) {
5855  case CXXInvalid:
5856    break;
5857
5858  case CXXConstructor:
5859    if (RD->hasUserDeclaredConstructor()) {
5860      typedef CXXRecordDecl::ctor_iterator ctor_iter;
5861      for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){
5862        const FunctionDecl *body = 0;
5863        ci->getBody(body);
5864        if (!body || !cast<CXXConstructorDecl>(body)->isImplicitlyDefined()) {
5865          SourceLocation CtorLoc = ci->getLocation();
5866          Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5867          return;
5868        }
5869      }
5870
5871      assert(0 && "found no user-declared constructors");
5872      return;
5873    }
5874    break;
5875
5876  case CXXCopyConstructor:
5877    if (RD->hasUserDeclaredCopyConstructor()) {
5878      SourceLocation CtorLoc =
5879        RD->getCopyConstructor(Context, 0)->getLocation();
5880      Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5881      return;
5882    }
5883    break;
5884
5885  case CXXCopyAssignment:
5886    if (RD->hasUserDeclaredCopyAssignment()) {
5887      // FIXME: this should use the location of the copy
5888      // assignment, not the type.
5889      SourceLocation TyLoc = RD->getSourceRange().getBegin();
5890      Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
5891      return;
5892    }
5893    break;
5894
5895  case CXXDestructor:
5896    if (RD->hasUserDeclaredDestructor()) {
5897      SourceLocation DtorLoc = RD->getDestructor(Context)->getLocation();
5898      Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5899      return;
5900    }
5901    break;
5902  }
5903
5904  typedef CXXRecordDecl::base_class_iterator base_iter;
5905
5906  // Virtual bases and members inhibit trivial copying/construction,
5907  // but not trivial destruction.
5908  if (member != CXXDestructor) {
5909    // Check for virtual bases.  vbases includes indirect virtual bases,
5910    // so we just iterate through the direct bases.
5911    for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
5912      if (bi->isVirtual()) {
5913        SourceLocation BaseLoc = bi->getSourceRange().getBegin();
5914        Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
5915        return;
5916      }
5917
5918    // Check for virtual methods.
5919    typedef CXXRecordDecl::method_iterator meth_iter;
5920    for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
5921         ++mi) {
5922      if (mi->isVirtual()) {
5923        SourceLocation MLoc = mi->getSourceRange().getBegin();
5924        Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
5925        return;
5926      }
5927    }
5928  }
5929
5930  bool (CXXRecordDecl::*hasTrivial)() const;
5931  switch (member) {
5932  case CXXConstructor:
5933    hasTrivial = &CXXRecordDecl::hasTrivialConstructor; break;
5934  case CXXCopyConstructor:
5935    hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
5936  case CXXCopyAssignment:
5937    hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
5938  case CXXDestructor:
5939    hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
5940  default:
5941    assert(0 && "unexpected special member"); return;
5942  }
5943
5944  // Check for nontrivial bases (and recurse).
5945  for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
5946    const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
5947    assert(BaseRT && "Don't know how to handle dependent bases");
5948    CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
5949    if (!(BaseRecTy->*hasTrivial)()) {
5950      SourceLocation BaseLoc = bi->getSourceRange().getBegin();
5951      Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
5952      DiagnoseNontrivial(BaseRT, member);
5953      return;
5954    }
5955  }
5956
5957  // Check for nontrivial members (and recurse).
5958  typedef RecordDecl::field_iterator field_iter;
5959  for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
5960       ++fi) {
5961    QualType EltTy = Context.getBaseElementType((*fi)->getType());
5962    if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
5963      CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
5964
5965      if (!(EltRD->*hasTrivial)()) {
5966        SourceLocation FLoc = (*fi)->getLocation();
5967        Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
5968        DiagnoseNontrivial(EltRT, member);
5969        return;
5970      }
5971    }
5972  }
5973
5974  assert(0 && "found no explanation for non-trivial member");
5975}
5976
5977/// TranslateIvarVisibility - Translate visibility from a token ID to an
5978///  AST enum value.
5979static ObjCIvarDecl::AccessControl
5980TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
5981  switch (ivarVisibility) {
5982  default: assert(0 && "Unknown visitibility kind");
5983  case tok::objc_private: return ObjCIvarDecl::Private;
5984  case tok::objc_public: return ObjCIvarDecl::Public;
5985  case tok::objc_protected: return ObjCIvarDecl::Protected;
5986  case tok::objc_package: return ObjCIvarDecl::Package;
5987  }
5988}
5989
5990/// ActOnIvar - Each ivar field of an objective-c class is passed into this
5991/// in order to create an IvarDecl object for it.
5992Sema::DeclPtrTy Sema::ActOnIvar(Scope *S,
5993                                SourceLocation DeclStart,
5994                                DeclPtrTy IntfDecl,
5995                                Declarator &D, ExprTy *BitfieldWidth,
5996                                tok::ObjCKeywordKind Visibility) {
5997
5998  IdentifierInfo *II = D.getIdentifier();
5999  Expr *BitWidth = (Expr*)BitfieldWidth;
6000  SourceLocation Loc = DeclStart;
6001  if (II) Loc = D.getIdentifierLoc();
6002
6003  // FIXME: Unnamed fields can be handled in various different ways, for
6004  // example, unnamed unions inject all members into the struct namespace!
6005
6006  TypeSourceInfo *TInfo = 0;
6007  QualType T = GetTypeForDeclarator(D, S, &TInfo);
6008
6009  if (BitWidth) {
6010    // 6.7.2.1p3, 6.7.2.1p4
6011    if (VerifyBitField(Loc, II, T, BitWidth)) {
6012      D.setInvalidType();
6013      DeleteExpr(BitWidth);
6014      BitWidth = 0;
6015    }
6016  } else {
6017    // Not a bitfield.
6018
6019    // validate II.
6020
6021  }
6022  if (T->isReferenceType()) {
6023    Diag(Loc, diag::err_ivar_reference_type);
6024    D.setInvalidType();
6025  }
6026  // C99 6.7.2.1p8: A member of a structure or union may have any type other
6027  // than a variably modified type.
6028  else if (T->isVariablyModifiedType()) {
6029    Diag(Loc, diag::err_typecheck_ivar_variable_size);
6030    D.setInvalidType();
6031  }
6032
6033  // Get the visibility (access control) for this ivar.
6034  ObjCIvarDecl::AccessControl ac =
6035    Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
6036                                        : ObjCIvarDecl::None;
6037  // Must set ivar's DeclContext to its enclosing interface.
6038  ObjCContainerDecl *EnclosingDecl = IntfDecl.getAs<ObjCContainerDecl>();
6039  ObjCContainerDecl *EnclosingContext;
6040  if (ObjCImplementationDecl *IMPDecl =
6041      dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
6042    // Case of ivar declared in an implementation. Context is that of its class.
6043    EnclosingContext = IMPDecl->getClassInterface();
6044    assert(EnclosingContext && "Implementation has no class interface!");
6045  } else {
6046    if (ObjCCategoryDecl *CDecl =
6047        dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
6048      if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) {
6049        Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
6050        return DeclPtrTy();
6051      }
6052    }
6053    EnclosingContext = EnclosingDecl;
6054  }
6055
6056  // Construct the decl.
6057  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context,
6058                                             EnclosingContext, Loc, II, T,
6059                                             TInfo, ac, (Expr *)BitfieldWidth);
6060
6061  if (II) {
6062    NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
6063                                           ForRedeclaration);
6064    if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
6065        && !isa<TagDecl>(PrevDecl)) {
6066      Diag(Loc, diag::err_duplicate_member) << II;
6067      Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
6068      NewID->setInvalidDecl();
6069    }
6070  }
6071
6072  // Process attributes attached to the ivar.
6073  ProcessDeclAttributes(S, NewID, D);
6074
6075  if (D.isInvalidType())
6076    NewID->setInvalidDecl();
6077
6078  if (II) {
6079    // FIXME: When interfaces are DeclContexts, we'll need to add
6080    // these to the interface.
6081    S->AddDecl(DeclPtrTy::make(NewID));
6082    IdResolver.AddDecl(NewID);
6083  }
6084
6085  return DeclPtrTy::make(NewID);
6086}
6087
6088void Sema::ActOnFields(Scope* S,
6089                       SourceLocation RecLoc, DeclPtrTy RecDecl,
6090                       DeclPtrTy *Fields, unsigned NumFields,
6091                       SourceLocation LBrac, SourceLocation RBrac,
6092                       AttributeList *Attr) {
6093  Decl *EnclosingDecl = RecDecl.getAs<Decl>();
6094  assert(EnclosingDecl && "missing record or interface decl");
6095
6096  // If the decl this is being inserted into is invalid, then it may be a
6097  // redeclaration or some other bogus case.  Don't try to add fields to it.
6098  if (EnclosingDecl->isInvalidDecl()) {
6099    // FIXME: Deallocate fields?
6100    return;
6101  }
6102
6103
6104  // Verify that all the fields are okay.
6105  unsigned NumNamedMembers = 0;
6106  llvm::SmallVector<FieldDecl*, 32> RecFields;
6107
6108  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
6109  for (unsigned i = 0; i != NumFields; ++i) {
6110    FieldDecl *FD = cast<FieldDecl>(Fields[i].getAs<Decl>());
6111
6112    // Get the type for the field.
6113    Type *FDTy = FD->getType().getTypePtr();
6114
6115    if (!FD->isAnonymousStructOrUnion()) {
6116      // Remember all fields written by the user.
6117      RecFields.push_back(FD);
6118    }
6119
6120    // If the field is already invalid for some reason, don't emit more
6121    // diagnostics about it.
6122    if (FD->isInvalidDecl()) {
6123      EnclosingDecl->setInvalidDecl();
6124      continue;
6125    }
6126
6127    // C99 6.7.2.1p2:
6128    //   A structure or union shall not contain a member with
6129    //   incomplete or function type (hence, a structure shall not
6130    //   contain an instance of itself, but may contain a pointer to
6131    //   an instance of itself), except that the last member of a
6132    //   structure with more than one named member may have incomplete
6133    //   array type; such a structure (and any union containing,
6134    //   possibly recursively, a member that is such a structure)
6135    //   shall not be a member of a structure or an element of an
6136    //   array.
6137    if (FDTy->isFunctionType()) {
6138      // Field declared as a function.
6139      Diag(FD->getLocation(), diag::err_field_declared_as_function)
6140        << FD->getDeclName();
6141      FD->setInvalidDecl();
6142      EnclosingDecl->setInvalidDecl();
6143      continue;
6144    } else if (FDTy->isIncompleteArrayType() && i == NumFields - 1 &&
6145               Record && Record->isStruct()) {
6146      // Flexible array member.
6147      if (NumNamedMembers < 1) {
6148        Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
6149          << FD->getDeclName();
6150        FD->setInvalidDecl();
6151        EnclosingDecl->setInvalidDecl();
6152        continue;
6153      }
6154      if (!FD->getType()->isDependentType() &&
6155          !Context.getBaseElementType(FD->getType())->isPODType()) {
6156        Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
6157          << FD->getDeclName() << FD->getType();
6158        FD->setInvalidDecl();
6159        EnclosingDecl->setInvalidDecl();
6160        continue;
6161      }
6162
6163      // Okay, we have a legal flexible array member at the end of the struct.
6164      if (Record)
6165        Record->setHasFlexibleArrayMember(true);
6166    } else if (!FDTy->isDependentType() &&
6167               RequireCompleteType(FD->getLocation(), FD->getType(),
6168                                   diag::err_field_incomplete)) {
6169      // Incomplete type
6170      FD->setInvalidDecl();
6171      EnclosingDecl->setInvalidDecl();
6172      continue;
6173    } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
6174      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
6175        // If this is a member of a union, then entire union becomes "flexible".
6176        if (Record && Record->isUnion()) {
6177          Record->setHasFlexibleArrayMember(true);
6178        } else {
6179          // If this is a struct/class and this is not the last element, reject
6180          // it.  Note that GCC supports variable sized arrays in the middle of
6181          // structures.
6182          if (i != NumFields-1)
6183            Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
6184              << FD->getDeclName() << FD->getType();
6185          else {
6186            // We support flexible arrays at the end of structs in
6187            // other structs as an extension.
6188            Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
6189              << FD->getDeclName();
6190            if (Record)
6191              Record->setHasFlexibleArrayMember(true);
6192          }
6193        }
6194      }
6195      if (Record && FDTTy->getDecl()->hasObjectMember())
6196        Record->setHasObjectMember(true);
6197    } else if (FDTy->isObjCObjectType()) {
6198      /// A field cannot be an Objective-c object
6199      Diag(FD->getLocation(), diag::err_statically_allocated_object);
6200      FD->setInvalidDecl();
6201      EnclosingDecl->setInvalidDecl();
6202      continue;
6203    } else if (getLangOptions().ObjC1 &&
6204               getLangOptions().getGCMode() != LangOptions::NonGC &&
6205               Record &&
6206               (FD->getType()->isObjCObjectPointerType() ||
6207                FD->getType().isObjCGCStrong()))
6208      Record->setHasObjectMember(true);
6209    // Keep track of the number of named members.
6210    if (FD->getIdentifier())
6211      ++NumNamedMembers;
6212  }
6213
6214  // Okay, we successfully defined 'Record'.
6215  if (Record) {
6216    Record->completeDefinition();
6217  } else {
6218    ObjCIvarDecl **ClsFields =
6219      reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
6220    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
6221      ID->setLocEnd(RBrac);
6222      // Add ivar's to class's DeclContext.
6223      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
6224        ClsFields[i]->setLexicalDeclContext(ID);
6225        ID->addDecl(ClsFields[i]);
6226      }
6227      // Must enforce the rule that ivars in the base classes may not be
6228      // duplicates.
6229      if (ID->getSuperClass())
6230        DiagnoseDuplicateIvars(ID, ID->getSuperClass());
6231    } else if (ObjCImplementationDecl *IMPDecl =
6232                  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
6233      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
6234      for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
6235        // Ivar declared in @implementation never belongs to the implementation.
6236        // Only it is in implementation's lexical context.
6237        ClsFields[I]->setLexicalDeclContext(IMPDecl);
6238      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
6239    } else if (ObjCCategoryDecl *CDecl =
6240                dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
6241      // case of ivars in class extension; all other cases have been
6242      // reported as errors elsewhere.
6243      // FIXME. Class extension does not have a LocEnd field.
6244      // CDecl->setLocEnd(RBrac);
6245      // Add ivar's to class extension's DeclContext.
6246      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
6247        ClsFields[i]->setLexicalDeclContext(CDecl);
6248        CDecl->addDecl(ClsFields[i]);
6249      }
6250    }
6251  }
6252
6253  if (Attr)
6254    ProcessDeclAttributeList(S, Record, Attr);
6255}
6256
6257/// \brief Determine whether the given integral value is representable within
6258/// the given type T.
6259static bool isRepresentableIntegerValue(ASTContext &Context,
6260                                        llvm::APSInt &Value,
6261                                        QualType T) {
6262  assert(T->isIntegralType() && "Integral type required!");
6263  unsigned BitWidth = Context.getIntWidth(T);
6264
6265  if (Value.isUnsigned() || Value.isNonNegative())
6266    return Value.getActiveBits() < BitWidth;
6267
6268  return Value.getMinSignedBits() <= BitWidth;
6269}
6270
6271// \brief Given an integral type, return the next larger integral type
6272// (or a NULL type of no such type exists).
6273static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
6274  // FIXME: Int128/UInt128 support, which also needs to be introduced into
6275  // enum checking below.
6276  assert(T->isIntegralType() && "Integral type required!");
6277  const unsigned NumTypes = 4;
6278  QualType SignedIntegralTypes[NumTypes] = {
6279    Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
6280  };
6281  QualType UnsignedIntegralTypes[NumTypes] = {
6282    Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
6283    Context.UnsignedLongLongTy
6284  };
6285
6286  unsigned BitWidth = Context.getTypeSize(T);
6287  QualType *Types = T->isSignedIntegerType()? SignedIntegralTypes
6288                                            : UnsignedIntegralTypes;
6289  for (unsigned I = 0; I != NumTypes; ++I)
6290    if (Context.getTypeSize(Types[I]) > BitWidth)
6291      return Types[I];
6292
6293  return QualType();
6294}
6295
6296EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
6297                                          EnumConstantDecl *LastEnumConst,
6298                                          SourceLocation IdLoc,
6299                                          IdentifierInfo *Id,
6300                                          ExprArg val) {
6301  Expr *Val = (Expr *)val.get();
6302
6303  unsigned IntWidth = Context.Target.getIntWidth();
6304  llvm::APSInt EnumVal(IntWidth);
6305  QualType EltTy;
6306  if (Val) {
6307    if (Enum->isDependentType() || Val->isTypeDependent())
6308      EltTy = Context.DependentTy;
6309    else {
6310      // C99 6.7.2.2p2: Make sure we have an integer constant expression.
6311      SourceLocation ExpLoc;
6312      if (!Val->isValueDependent() &&
6313          VerifyIntegerConstantExpression(Val, &EnumVal)) {
6314        Val = 0;
6315      } else {
6316        if (!getLangOptions().CPlusPlus) {
6317          // C99 6.7.2.2p2:
6318          //   The expression that defines the value of an enumeration constant
6319          //   shall be an integer constant expression that has a value
6320          //   representable as an int.
6321
6322          // Complain if the value is not representable in an int.
6323          if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
6324            Diag(IdLoc, diag::ext_enum_value_not_int)
6325              << EnumVal.toString(10) << Val->getSourceRange()
6326              << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
6327          else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
6328            // Force the type of the expression to 'int'.
6329            ImpCastExprToType(Val, Context.IntTy, CastExpr::CK_IntegralCast);
6330
6331            if (Val != val.get()) {
6332              val.release();
6333              val = Val;
6334            }
6335          }
6336        }
6337
6338        // C++0x [dcl.enum]p5:
6339        //   If the underlying type is not fixed, the type of each enumerator
6340        //   is the type of its initializing value:
6341        //     - If an initializer is specified for an enumerator, the
6342        //       initializing value has the same type as the expression.
6343        EltTy = Val->getType();
6344      }
6345    }
6346  }
6347
6348  if (!Val) {
6349    if (Enum->isDependentType())
6350      EltTy = Context.DependentTy;
6351    else if (!LastEnumConst) {
6352      // C++0x [dcl.enum]p5:
6353      //   If the underlying type is not fixed, the type of each enumerator
6354      //   is the type of its initializing value:
6355      //     - If no initializer is specified for the first enumerator, the
6356      //       initializing value has an unspecified integral type.
6357      //
6358      // GCC uses 'int' for its unspecified integral type, as does
6359      // C99 6.7.2.2p3.
6360      EltTy = Context.IntTy;
6361    } else {
6362      // Assign the last value + 1.
6363      EnumVal = LastEnumConst->getInitVal();
6364      ++EnumVal;
6365      EltTy = LastEnumConst->getType();
6366
6367      // Check for overflow on increment.
6368      if (EnumVal < LastEnumConst->getInitVal()) {
6369        // C++0x [dcl.enum]p5:
6370        //   If the underlying type is not fixed, the type of each enumerator
6371        //   is the type of its initializing value:
6372        //
6373        //     - Otherwise the type of the initializing value is the same as
6374        //       the type of the initializing value of the preceding enumerator
6375        //       unless the incremented value is not representable in that type,
6376        //       in which case the type is an unspecified integral type
6377        //       sufficient to contain the incremented value. If no such type
6378        //       exists, the program is ill-formed.
6379        QualType T = getNextLargerIntegralType(Context, EltTy);
6380        if (T.isNull()) {
6381          // There is no integral type larger enough to represent this
6382          // value. Complain, then allow the value to wrap around.
6383          EnumVal = LastEnumConst->getInitVal();
6384          EnumVal.zext(EnumVal.getBitWidth() * 2);
6385          Diag(IdLoc, diag::warn_enumerator_too_large)
6386            << EnumVal.toString(10);
6387        } else {
6388          EltTy = T;
6389        }
6390
6391        // Retrieve the last enumerator's value, extent that type to the
6392        // type that is supposed to be large enough to represent the incremented
6393        // value, then increment.
6394        EnumVal = LastEnumConst->getInitVal();
6395        EnumVal.setIsSigned(EltTy->isSignedIntegerType());
6396        EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
6397        ++EnumVal;
6398
6399        // If we're not in C++, diagnose the overflow of enumerator values,
6400        // which in C99 means that the enumerator value is not representable in
6401        // an int (C99 6.7.2.2p2). However, we support GCC's extension that
6402        // permits enumerator values that are representable in some larger
6403        // integral type.
6404        if (!getLangOptions().CPlusPlus && !T.isNull())
6405          Diag(IdLoc, diag::warn_enum_value_overflow);
6406      } else if (!getLangOptions().CPlusPlus &&
6407                 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
6408        // Enforce C99 6.7.2.2p2 even when we compute the next value.
6409        Diag(IdLoc, diag::ext_enum_value_not_int)
6410          << EnumVal.toString(10) << 1;
6411      }
6412    }
6413  }
6414
6415  if (!EltTy->isDependentType()) {
6416    // Make the enumerator value match the signedness and size of the
6417    // enumerator's type.
6418    EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
6419    EnumVal.setIsSigned(EltTy->isSignedIntegerType());
6420  }
6421
6422  val.release();
6423  return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
6424                                  Val, EnumVal);
6425}
6426
6427
6428Sema::DeclPtrTy Sema::ActOnEnumConstant(Scope *S, DeclPtrTy theEnumDecl,
6429                                        DeclPtrTy lastEnumConst,
6430                                        SourceLocation IdLoc,
6431                                        IdentifierInfo *Id,
6432                                        SourceLocation EqualLoc, ExprTy *val) {
6433  EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl.getAs<Decl>());
6434  EnumConstantDecl *LastEnumConst =
6435    cast_or_null<EnumConstantDecl>(lastEnumConst.getAs<Decl>());
6436  Expr *Val = static_cast<Expr*>(val);
6437
6438  // The scope passed in may not be a decl scope.  Zip up the scope tree until
6439  // we find one that is.
6440  S = getNonFieldDeclScope(S);
6441
6442  // Verify that there isn't already something declared with this name in this
6443  // scope.
6444  NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
6445                                         ForRedeclaration);
6446  if (PrevDecl && PrevDecl->isTemplateParameter()) {
6447    // Maybe we will complain about the shadowed template parameter.
6448    DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
6449    // Just pretend that we didn't see the previous declaration.
6450    PrevDecl = 0;
6451  }
6452
6453  if (PrevDecl) {
6454    // When in C++, we may get a TagDecl with the same name; in this case the
6455    // enum constant will 'hide' the tag.
6456    assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
6457           "Received TagDecl when not in C++!");
6458    if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
6459      if (isa<EnumConstantDecl>(PrevDecl))
6460        Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
6461      else
6462        Diag(IdLoc, diag::err_redefinition) << Id;
6463      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6464      if (Val) Val->Destroy(Context);
6465      return DeclPtrTy();
6466    }
6467  }
6468
6469  EnumConstantDecl *New = CheckEnumConstant(TheEnumDecl, LastEnumConst,
6470                                            IdLoc, Id, Owned(Val));
6471
6472  // Register this decl in the current scope stack.
6473  if (New) {
6474    New->setAccess(TheEnumDecl->getAccess());
6475    PushOnScopeChains(New, S);
6476  }
6477
6478  return DeclPtrTy::make(New);
6479}
6480
6481void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
6482                         SourceLocation RBraceLoc, DeclPtrTy EnumDeclX,
6483                         DeclPtrTy *Elements, unsigned NumElements,
6484                         Scope *S, AttributeList *Attr) {
6485  EnumDecl *Enum = cast<EnumDecl>(EnumDeclX.getAs<Decl>());
6486  QualType EnumType = Context.getTypeDeclType(Enum);
6487
6488  if (Attr)
6489    ProcessDeclAttributeList(S, Enum, Attr);
6490
6491  if (Enum->isDependentType()) {
6492    for (unsigned i = 0; i != NumElements; ++i) {
6493      EnumConstantDecl *ECD =
6494        cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
6495      if (!ECD) continue;
6496
6497      ECD->setType(EnumType);
6498    }
6499
6500    Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
6501    return;
6502  }
6503
6504  // TODO: If the result value doesn't fit in an int, it must be a long or long
6505  // long value.  ISO C does not support this, but GCC does as an extension,
6506  // emit a warning.
6507  unsigned IntWidth = Context.Target.getIntWidth();
6508  unsigned CharWidth = Context.Target.getCharWidth();
6509  unsigned ShortWidth = Context.Target.getShortWidth();
6510
6511  // Verify that all the values are okay, compute the size of the values, and
6512  // reverse the list.
6513  unsigned NumNegativeBits = 0;
6514  unsigned NumPositiveBits = 0;
6515
6516  // Keep track of whether all elements have type int.
6517  bool AllElementsInt = true;
6518
6519  for (unsigned i = 0; i != NumElements; ++i) {
6520    EnumConstantDecl *ECD =
6521      cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
6522    if (!ECD) continue;  // Already issued a diagnostic.
6523
6524    const llvm::APSInt &InitVal = ECD->getInitVal();
6525
6526    // Keep track of the size of positive and negative values.
6527    if (InitVal.isUnsigned() || InitVal.isNonNegative())
6528      NumPositiveBits = std::max(NumPositiveBits,
6529                                 (unsigned)InitVal.getActiveBits());
6530    else
6531      NumNegativeBits = std::max(NumNegativeBits,
6532                                 (unsigned)InitVal.getMinSignedBits());
6533
6534    // Keep track of whether every enum element has type int (very commmon).
6535    if (AllElementsInt)
6536      AllElementsInt = ECD->getType() == Context.IntTy;
6537  }
6538
6539  // Figure out the type that should be used for this enum.
6540  // FIXME: Support -fshort-enums.
6541  QualType BestType;
6542  unsigned BestWidth;
6543
6544  // C++0x N3000 [conv.prom]p3:
6545  //   An rvalue of an unscoped enumeration type whose underlying
6546  //   type is not fixed can be converted to an rvalue of the first
6547  //   of the following types that can represent all the values of
6548  //   the enumeration: int, unsigned int, long int, unsigned long
6549  //   int, long long int, or unsigned long long int.
6550  // C99 6.4.4.3p2:
6551  //   An identifier declared as an enumeration constant has type int.
6552  // The C99 rule is modified by a gcc extension
6553  QualType BestPromotionType;
6554
6555  bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
6556
6557  if (NumNegativeBits) {
6558    // If there is a negative value, figure out the smallest integer type (of
6559    // int/long/longlong) that fits.
6560    // If it's packed, check also if it fits a char or a short.
6561    if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
6562      BestType = Context.SignedCharTy;
6563      BestWidth = CharWidth;
6564    } else if (Packed && NumNegativeBits <= ShortWidth &&
6565               NumPositiveBits < ShortWidth) {
6566      BestType = Context.ShortTy;
6567      BestWidth = ShortWidth;
6568    } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
6569      BestType = Context.IntTy;
6570      BestWidth = IntWidth;
6571    } else {
6572      BestWidth = Context.Target.getLongWidth();
6573
6574      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
6575        BestType = Context.LongTy;
6576      } else {
6577        BestWidth = Context.Target.getLongLongWidth();
6578
6579        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
6580          Diag(Enum->getLocation(), diag::warn_enum_too_large);
6581        BestType = Context.LongLongTy;
6582      }
6583    }
6584    BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
6585  } else {
6586    // If there is no negative value, figure out the smallest type that fits
6587    // all of the enumerator values.
6588    // If it's packed, check also if it fits a char or a short.
6589    if (Packed && NumPositiveBits <= CharWidth) {
6590      BestType = Context.UnsignedCharTy;
6591      BestPromotionType = Context.IntTy;
6592      BestWidth = CharWidth;
6593    } else if (Packed && NumPositiveBits <= ShortWidth) {
6594      BestType = Context.UnsignedShortTy;
6595      BestPromotionType = Context.IntTy;
6596      BestWidth = ShortWidth;
6597    } else if (NumPositiveBits <= IntWidth) {
6598      BestType = Context.UnsignedIntTy;
6599      BestWidth = IntWidth;
6600      BestPromotionType
6601        = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
6602                           ? Context.UnsignedIntTy : Context.IntTy;
6603    } else if (NumPositiveBits <=
6604               (BestWidth = Context.Target.getLongWidth())) {
6605      BestType = Context.UnsignedLongTy;
6606      BestPromotionType
6607        = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
6608                           ? Context.UnsignedLongTy : Context.LongTy;
6609    } else {
6610      BestWidth = Context.Target.getLongLongWidth();
6611      assert(NumPositiveBits <= BestWidth &&
6612             "How could an initializer get larger than ULL?");
6613      BestType = Context.UnsignedLongLongTy;
6614      BestPromotionType
6615        = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
6616                           ? Context.UnsignedLongLongTy : Context.LongLongTy;
6617    }
6618  }
6619
6620  // Loop over all of the enumerator constants, changing their types to match
6621  // the type of the enum if needed.
6622  for (unsigned i = 0; i != NumElements; ++i) {
6623    EnumConstantDecl *ECD =
6624      cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
6625    if (!ECD) continue;  // Already issued a diagnostic.
6626
6627    // Standard C says the enumerators have int type, but we allow, as an
6628    // extension, the enumerators to be larger than int size.  If each
6629    // enumerator value fits in an int, type it as an int, otherwise type it the
6630    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
6631    // that X has type 'int', not 'unsigned'.
6632
6633    // Determine whether the value fits into an int.
6634    llvm::APSInt InitVal = ECD->getInitVal();
6635
6636    // If it fits into an integer type, force it.  Otherwise force it to match
6637    // the enum decl type.
6638    QualType NewTy;
6639    unsigned NewWidth;
6640    bool NewSign;
6641    if (!getLangOptions().CPlusPlus &&
6642        isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
6643      NewTy = Context.IntTy;
6644      NewWidth = IntWidth;
6645      NewSign = true;
6646    } else if (ECD->getType() == BestType) {
6647      // Already the right type!
6648      if (getLangOptions().CPlusPlus)
6649        // C++ [dcl.enum]p4: Following the closing brace of an
6650        // enum-specifier, each enumerator has the type of its
6651        // enumeration.
6652        ECD->setType(EnumType);
6653      continue;
6654    } else {
6655      NewTy = BestType;
6656      NewWidth = BestWidth;
6657      NewSign = BestType->isSignedIntegerType();
6658    }
6659
6660    // Adjust the APSInt value.
6661    InitVal.extOrTrunc(NewWidth);
6662    InitVal.setIsSigned(NewSign);
6663    ECD->setInitVal(InitVal);
6664
6665    // Adjust the Expr initializer and type.
6666    if (ECD->getInitExpr())
6667      ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy,
6668                                                      CastExpr::CK_IntegralCast,
6669                                                      ECD->getInitExpr(),
6670                                                      CXXBaseSpecifierArray(),
6671                                                      /*isLvalue=*/false));
6672    if (getLangOptions().CPlusPlus)
6673      // C++ [dcl.enum]p4: Following the closing brace of an
6674      // enum-specifier, each enumerator has the type of its
6675      // enumeration.
6676      ECD->setType(EnumType);
6677    else
6678      ECD->setType(NewTy);
6679  }
6680
6681  Enum->completeDefinition(BestType, BestPromotionType,
6682                           NumPositiveBits, NumNegativeBits);
6683}
6684
6685Sema::DeclPtrTy Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
6686                                            ExprArg expr) {
6687  StringLiteral *AsmString = cast<StringLiteral>(expr.takeAs<Expr>());
6688
6689  FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
6690                                                   Loc, AsmString);
6691  CurContext->addDecl(New);
6692  return DeclPtrTy::make(New);
6693}
6694
6695void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
6696                             SourceLocation PragmaLoc,
6697                             SourceLocation NameLoc) {
6698  Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
6699
6700  if (PrevDecl) {
6701    PrevDecl->addAttr(::new (Context) WeakAttr());
6702  } else {
6703    (void)WeakUndeclaredIdentifiers.insert(
6704      std::pair<IdentifierInfo*,WeakInfo>
6705        (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
6706  }
6707}
6708
6709void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
6710                                IdentifierInfo* AliasName,
6711                                SourceLocation PragmaLoc,
6712                                SourceLocation NameLoc,
6713                                SourceLocation AliasNameLoc) {
6714  Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
6715                                    LookupOrdinaryName);
6716  WeakInfo W = WeakInfo(Name, NameLoc);
6717
6718  if (PrevDecl) {
6719    if (!PrevDecl->hasAttr<AliasAttr>())
6720      if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
6721        DeclApplyPragmaWeak(TUScope, ND, W);
6722  } else {
6723    (void)WeakUndeclaredIdentifiers.insert(
6724      std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
6725  }
6726}
6727