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