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