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