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