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