SemaDecl.cpp revision 8d2a701734f6e0aa778f6be4e6b6d561d8ba6fdb
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 "clang/Sema/SemaInternal.h"
15#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/CXXFieldCollector.h"
18#include "clang/Sema/Scope.h"
19#include "clang/Sema/ScopeInfo.h"
20#include "TypeLocBuilder.h"
21#include "clang/AST/ASTConsumer.h"
22#include "clang/AST/ASTContext.h"
23#include "clang/AST/CXXInheritance.h"
24#include "clang/AST/DeclCXX.h"
25#include "clang/AST/DeclObjC.h"
26#include "clang/AST/DeclTemplate.h"
27#include "clang/AST/EvaluatedExprVisitor.h"
28#include "clang/AST/ExprCXX.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/CharUnits.h"
31#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/ParsedTemplate.h"
33#include "clang/Parse/ParseDiagnostic.h"
34#include "clang/Basic/PartialDiagnostic.h"
35#include "clang/Sema/DelayedDiagnostic.h"
36#include "clang/Basic/SourceManager.h"
37#include "clang/Basic/TargetInfo.h"
38// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
39#include "clang/Lex/Preprocessor.h"
40#include "clang/Lex/HeaderSearch.h"
41#include "clang/Lex/ModuleLoader.h"
42#include "llvm/ADT/Triple.h"
43#include <algorithm>
44#include <cstring>
45#include <functional>
46using namespace clang;
47using namespace sema;
48
49Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
50  if (OwnedType) {
51    Decl *Group[2] = { OwnedType, Ptr };
52    return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
53  }
54
55  return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
56}
57
58/// \brief If the identifier refers to a type name within this scope,
59/// return the declaration of that type.
60///
61/// This routine performs ordinary name lookup of the identifier II
62/// within the given scope, with optional C++ scope specifier SS, to
63/// determine whether the name refers to a type. If so, returns an
64/// opaque pointer (actually a QualType) corresponding to that
65/// type. Otherwise, returns NULL.
66///
67/// If name lookup results in an ambiguity, this routine will complain
68/// and then return NULL.
69ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
70                             Scope *S, CXXScopeSpec *SS,
71                             bool isClassName, bool HasTrailingDot,
72                             ParsedType ObjectTypePtr,
73                             bool WantNontrivialTypeSourceInfo,
74                             IdentifierInfo **CorrectedII) {
75  // Determine where we will perform name lookup.
76  DeclContext *LookupCtx = 0;
77  if (ObjectTypePtr) {
78    QualType ObjectType = ObjectTypePtr.get();
79    if (ObjectType->isRecordType())
80      LookupCtx = computeDeclContext(ObjectType);
81  } else if (SS && SS->isNotEmpty()) {
82    LookupCtx = computeDeclContext(*SS, false);
83
84    if (!LookupCtx) {
85      if (isDependentScopeSpecifier(*SS)) {
86        // C++ [temp.res]p3:
87        //   A qualified-id that refers to a type and in which the
88        //   nested-name-specifier depends on a template-parameter (14.6.2)
89        //   shall be prefixed by the keyword typename to indicate that the
90        //   qualified-id denotes a type, forming an
91        //   elaborated-type-specifier (7.1.5.3).
92        //
93        // We therefore do not perform any name lookup if the result would
94        // refer to a member of an unknown specialization.
95        if (!isClassName)
96          return ParsedType();
97
98        // We know from the grammar that this name refers to a type,
99        // so build a dependent node to describe the type.
100        if (WantNontrivialTypeSourceInfo)
101          return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
102
103        NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
104        QualType T =
105          CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
106                            II, NameLoc);
107
108          return ParsedType::make(T);
109      }
110
111      return ParsedType();
112    }
113
114    if (!LookupCtx->isDependentContext() &&
115        RequireCompleteDeclContext(*SS, LookupCtx))
116      return ParsedType();
117  }
118
119  // FIXME: LookupNestedNameSpecifierName isn't the right kind of
120  // lookup for class-names.
121  LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
122                                      LookupOrdinaryName;
123  LookupResult Result(*this, &II, NameLoc, Kind);
124  if (LookupCtx) {
125    // Perform "qualified" name lookup into the declaration context we
126    // computed, which is either the type of the base of a member access
127    // expression or the declaration context associated with a prior
128    // nested-name-specifier.
129    LookupQualifiedName(Result, LookupCtx);
130
131    if (ObjectTypePtr && Result.empty()) {
132      // C++ [basic.lookup.classref]p3:
133      //   If the unqualified-id is ~type-name, the type-name is looked up
134      //   in the context of the entire postfix-expression. If the type T of
135      //   the object expression is of a class type C, the type-name is also
136      //   looked up in the scope of class C. At least one of the lookups shall
137      //   find a name that refers to (possibly cv-qualified) T.
138      LookupName(Result, S);
139    }
140  } else {
141    // Perform unqualified name lookup.
142    LookupName(Result, S);
143  }
144
145  NamedDecl *IIDecl = 0;
146  switch (Result.getResultKind()) {
147  case LookupResult::NotFound:
148  case LookupResult::NotFoundInCurrentInstantiation:
149    if (CorrectedII) {
150      TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
151                                              Kind, S, SS, 0, false,
152                                              Sema::CTC_Type);
153      IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
154      TemplateTy Template;
155      bool MemberOfUnknownSpecialization;
156      UnqualifiedId TemplateName;
157      TemplateName.setIdentifier(NewII, NameLoc);
158      NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
159      CXXScopeSpec NewSS, *NewSSPtr = SS;
160      if (SS && NNS) {
161        NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
162        NewSSPtr = &NewSS;
163      }
164      if (Correction && (NNS || NewII != &II) &&
165          // Ignore a correction to a template type as the to-be-corrected
166          // identifier is not a template (typo correction for template names
167          // is handled elsewhere).
168          !(getLangOptions().CPlusPlus && NewSSPtr &&
169            isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
170                           false, Template, MemberOfUnknownSpecialization))) {
171        ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
172                                    isClassName, HasTrailingDot, ObjectTypePtr,
173                                    WantNontrivialTypeSourceInfo);
174        if (Ty) {
175          std::string CorrectedStr(Correction.getAsString(getLangOptions()));
176          std::string CorrectedQuotedStr(
177              Correction.getQuoted(getLangOptions()));
178          Diag(NameLoc, diag::err_unknown_typename_suggest)
179              << Result.getLookupName() << CorrectedQuotedStr
180              << FixItHint::CreateReplacement(SourceRange(NameLoc),
181                                              CorrectedStr);
182          if (NamedDecl *FirstDecl = Correction.getCorrectionDecl())
183            Diag(FirstDecl->getLocation(), diag::note_previous_decl)
184              << CorrectedQuotedStr;
185
186          if (SS && NNS)
187            SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
188          *CorrectedII = NewII;
189          return Ty;
190        }
191      }
192    }
193    // If typo correction failed or was not performed, fall through
194  case LookupResult::FoundOverloaded:
195  case LookupResult::FoundUnresolvedValue:
196    Result.suppressDiagnostics();
197    return ParsedType();
198
199  case LookupResult::Ambiguous:
200    // Recover from type-hiding ambiguities by hiding the type.  We'll
201    // do the lookup again when looking for an object, and we can
202    // diagnose the error then.  If we don't do this, then the error
203    // about hiding the type will be immediately followed by an error
204    // that only makes sense if the identifier was treated like a type.
205    if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
206      Result.suppressDiagnostics();
207      return ParsedType();
208    }
209
210    // Look to see if we have a type anywhere in the list of results.
211    for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
212         Res != ResEnd; ++Res) {
213      if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
214        if (!IIDecl ||
215            (*Res)->getLocation().getRawEncoding() <
216              IIDecl->getLocation().getRawEncoding())
217          IIDecl = *Res;
218      }
219    }
220
221    if (!IIDecl) {
222      // None of the entities we found is a type, so there is no way
223      // to even assume that the result is a type. In this case, don't
224      // complain about the ambiguity. The parser will either try to
225      // perform this lookup again (e.g., as an object name), which
226      // will produce the ambiguity, or will complain that it expected
227      // a type name.
228      Result.suppressDiagnostics();
229      return ParsedType();
230    }
231
232    // We found a type within the ambiguous lookup; diagnose the
233    // ambiguity and then return that type. This might be the right
234    // answer, or it might not be, but it suppresses any attempt to
235    // perform the name lookup again.
236    break;
237
238  case LookupResult::Found:
239    IIDecl = Result.getFoundDecl();
240    break;
241  }
242
243  assert(IIDecl && "Didn't find decl");
244
245  QualType T;
246  if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
247    DiagnoseUseOfDecl(IIDecl, NameLoc);
248
249    if (T.isNull())
250      T = Context.getTypeDeclType(TD);
251
252    if (SS && SS->isNotEmpty()) {
253      if (WantNontrivialTypeSourceInfo) {
254        // Construct a type with type-source information.
255        TypeLocBuilder Builder;
256        Builder.pushTypeSpec(T).setNameLoc(NameLoc);
257
258        T = getElaboratedType(ETK_None, *SS, T);
259        ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
260        ElabTL.setKeywordLoc(SourceLocation());
261        ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
262        return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
263      } else {
264        T = getElaboratedType(ETK_None, *SS, T);
265      }
266    }
267  } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
268    (void)DiagnoseUseOfDecl(IDecl, NameLoc);
269    if (!HasTrailingDot)
270      T = Context.getObjCInterfaceType(IDecl);
271  }
272
273  if (T.isNull()) {
274    // If it's not plausibly a type, suppress diagnostics.
275    Result.suppressDiagnostics();
276    return ParsedType();
277  }
278  return ParsedType::make(T);
279}
280
281/// isTagName() - This method is called *for error recovery purposes only*
282/// to determine if the specified name is a valid tag name ("struct foo").  If
283/// so, this returns the TST for the tag corresponding to it (TST_enum,
284/// TST_union, TST_struct, TST_class).  This is used to diagnose cases in C
285/// where the user forgot to specify the tag.
286DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
287  // Do a tag name lookup in this scope.
288  LookupResult R(*this, &II, SourceLocation(), LookupTagName);
289  LookupName(R, S, false);
290  R.suppressDiagnostics();
291  if (R.getResultKind() == LookupResult::Found)
292    if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
293      switch (TD->getTagKind()) {
294      default:         return DeclSpec::TST_unspecified;
295      case TTK_Struct: return DeclSpec::TST_struct;
296      case TTK_Union:  return DeclSpec::TST_union;
297      case TTK_Class:  return DeclSpec::TST_class;
298      case TTK_Enum:   return DeclSpec::TST_enum;
299      }
300    }
301
302  return DeclSpec::TST_unspecified;
303}
304
305/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
306/// if a CXXScopeSpec's type is equal to the type of one of the base classes
307/// then downgrade the missing typename error to a warning.
308/// This is needed for MSVC compatibility; Example:
309/// @code
310/// template<class T> class A {
311/// public:
312///   typedef int TYPE;
313/// };
314/// template<class T> class B : public A<T> {
315/// public:
316///   A<T>::TYPE a; // no typename required because A<T> is a base class.
317/// };
318/// @endcode
319bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
320  if (CurContext->isRecord()) {
321    const Type *Ty = SS->getScopeRep()->getAsType();
322
323    CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
324    for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
325          BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
326      if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
327        return true;
328    return S->isFunctionPrototypeScope();
329  }
330  return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
331}
332
333bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II,
334                                   SourceLocation IILoc,
335                                   Scope *S,
336                                   CXXScopeSpec *SS,
337                                   ParsedType &SuggestedType) {
338  // We don't have anything to suggest (yet).
339  SuggestedType = ParsedType();
340
341  // There may have been a typo in the name of the type. Look up typo
342  // results, in case we have something that we can suggest.
343  if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(&II, IILoc),
344                                             LookupOrdinaryName, S, SS, NULL,
345                                             false, CTC_Type)) {
346    std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
347    std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
348
349    if (Corrected.isKeyword()) {
350      // We corrected to a keyword.
351      // FIXME: Actually recover with the keyword we suggest, and emit a fix-it.
352      Diag(IILoc, diag::err_unknown_typename_suggest)
353        << &II << CorrectedQuotedStr;
354      return true;
355    } else {
356      NamedDecl *Result = Corrected.getCorrectionDecl();
357      if ((isa<TypeDecl>(Result) || isa<ObjCInterfaceDecl>(Result)) &&
358          !Result->isInvalidDecl()) {
359        // We found a similarly-named type or interface; suggest that.
360        if (!SS || !SS->isSet())
361          Diag(IILoc, diag::err_unknown_typename_suggest)
362            << &II << CorrectedQuotedStr
363            << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
364        else if (DeclContext *DC = computeDeclContext(*SS, false))
365          Diag(IILoc, diag::err_unknown_nested_typename_suggest)
366            << &II << DC << CorrectedQuotedStr << SS->getRange()
367            << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
368        else
369          llvm_unreachable("could not have corrected a typo here");
370
371        Diag(Result->getLocation(), diag::note_previous_decl)
372          << CorrectedQuotedStr;
373
374        SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS,
375                                    false, false, ParsedType(),
376                                    /*NonTrivialTypeSourceInfo=*/true);
377        return true;
378      }
379    }
380  }
381
382  if (getLangOptions().CPlusPlus) {
383    // See if II is a class template that the user forgot to pass arguments to.
384    UnqualifiedId Name;
385    Name.setIdentifier(&II, IILoc);
386    CXXScopeSpec EmptySS;
387    TemplateTy TemplateResult;
388    bool MemberOfUnknownSpecialization;
389    if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
390                       Name, ParsedType(), true, TemplateResult,
391                       MemberOfUnknownSpecialization) == TNK_Type_template) {
392      TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
393      Diag(IILoc, diag::err_template_missing_args) << TplName;
394      if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
395        Diag(TplDecl->getLocation(), diag::note_template_decl_here)
396          << TplDecl->getTemplateParameters()->getSourceRange();
397      }
398      return true;
399    }
400  }
401
402  // FIXME: Should we move the logic that tries to recover from a missing tag
403  // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
404
405  if (!SS || (!SS->isSet() && !SS->isInvalid()))
406    Diag(IILoc, diag::err_unknown_typename) << &II;
407  else if (DeclContext *DC = computeDeclContext(*SS, false))
408    Diag(IILoc, diag::err_typename_nested_not_found)
409      << &II << DC << SS->getRange();
410  else if (isDependentScopeSpecifier(*SS)) {
411    unsigned DiagID = diag::err_typename_missing;
412    if (getLangOptions().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
413      DiagID = diag::warn_typename_missing;
414
415    Diag(SS->getRange().getBegin(), DiagID)
416      << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
417      << SourceRange(SS->getRange().getBegin(), IILoc)
418      << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
419    SuggestedType = ActOnTypenameType(S, SourceLocation(), *SS, II, IILoc)
420                                                                         .get();
421  } else {
422    assert(SS && SS->isInvalid() &&
423           "Invalid scope specifier has already been diagnosed");
424  }
425
426  return true;
427}
428
429/// \brief Determine whether the given result set contains either a type name
430/// or
431static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
432  bool CheckTemplate = R.getSema().getLangOptions().CPlusPlus &&
433                       NextToken.is(tok::less);
434
435  for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
436    if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
437      return true;
438
439    if (CheckTemplate && isa<TemplateDecl>(*I))
440      return true;
441  }
442
443  return false;
444}
445
446Sema::NameClassification Sema::ClassifyName(Scope *S,
447                                            CXXScopeSpec &SS,
448                                            IdentifierInfo *&Name,
449                                            SourceLocation NameLoc,
450                                            const Token &NextToken) {
451  DeclarationNameInfo NameInfo(Name, NameLoc);
452  ObjCMethodDecl *CurMethod = getCurMethodDecl();
453
454  if (NextToken.is(tok::coloncolon)) {
455    BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
456                                QualType(), false, SS, 0, false);
457
458  }
459
460  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
461  LookupParsedName(Result, S, &SS, !CurMethod);
462
463  // Perform lookup for Objective-C instance variables (including automatically
464  // synthesized instance variables), if we're in an Objective-C method.
465  // FIXME: This lookup really, really needs to be folded in to the normal
466  // unqualified lookup mechanism.
467  if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
468    ExprResult E = LookupInObjCMethod(Result, S, Name, true);
469    if (E.get() || E.isInvalid())
470      return E;
471  }
472
473  bool SecondTry = false;
474  bool IsFilteredTemplateName = false;
475
476Corrected:
477  switch (Result.getResultKind()) {
478  case LookupResult::NotFound:
479    // If an unqualified-id is followed by a '(', then we have a function
480    // call.
481    if (!SS.isSet() && NextToken.is(tok::l_paren)) {
482      // In C++, this is an ADL-only call.
483      // FIXME: Reference?
484      if (getLangOptions().CPlusPlus)
485        return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
486
487      // C90 6.3.2.2:
488      //   If the expression that precedes the parenthesized argument list in a
489      //   function call consists solely of an identifier, and if no
490      //   declaration is visible for this identifier, the identifier is
491      //   implicitly declared exactly as if, in the innermost block containing
492      //   the function call, the declaration
493      //
494      //     extern int identifier ();
495      //
496      //   appeared.
497      //
498      // We also allow this in C99 as an extension.
499      if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
500        Result.addDecl(D);
501        Result.resolveKind();
502        return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
503      }
504    }
505
506    // In C, we first see whether there is a tag type by the same name, in
507    // which case it's likely that the user just forget to write "enum",
508    // "struct", or "union".
509    if (!getLangOptions().CPlusPlus && !SecondTry) {
510      Result.clear(LookupTagName);
511      LookupParsedName(Result, S, &SS);
512      if (TagDecl *Tag = Result.getAsSingle<TagDecl>()) {
513        const char *TagName = 0;
514        const char *FixItTagName = 0;
515        switch (Tag->getTagKind()) {
516          case TTK_Class:
517            TagName = "class";
518            FixItTagName = "class ";
519            break;
520
521          case TTK_Enum:
522            TagName = "enum";
523            FixItTagName = "enum ";
524            break;
525
526          case TTK_Struct:
527            TagName = "struct";
528            FixItTagName = "struct ";
529            break;
530
531          case TTK_Union:
532            TagName = "union";
533            FixItTagName = "union ";
534            break;
535        }
536
537        Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
538          << Name << TagName << getLangOptions().CPlusPlus
539          << FixItHint::CreateInsertion(NameLoc, FixItTagName);
540        break;
541      }
542
543      Result.clear(LookupOrdinaryName);
544    }
545
546    // Perform typo correction to determine if there is another name that is
547    // close to this name.
548    if (!SecondTry) {
549      SecondTry = true;
550      if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
551                                                 Result.getLookupKind(), S,
552                                                 &SS)) {
553        unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
554        unsigned QualifiedDiag = diag::err_no_member_suggest;
555        std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
556        std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
557
558        NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
559        NamedDecl *UnderlyingFirstDecl
560          = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
561        if (getLangOptions().CPlusPlus && NextToken.is(tok::less) &&
562            UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
563          UnqualifiedDiag = diag::err_no_template_suggest;
564          QualifiedDiag = diag::err_no_member_template_suggest;
565        } else if (UnderlyingFirstDecl &&
566                   (isa<TypeDecl>(UnderlyingFirstDecl) ||
567                    isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
568                    isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
569           UnqualifiedDiag = diag::err_unknown_typename_suggest;
570           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
571         }
572
573        if (SS.isEmpty())
574          Diag(NameLoc, UnqualifiedDiag)
575            << Name << CorrectedQuotedStr
576            << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
577        else
578          Diag(NameLoc, QualifiedDiag)
579            << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
580            << SS.getRange()
581            << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
582
583        // Update the name, so that the caller has the new name.
584        Name = Corrected.getCorrectionAsIdentifierInfo();
585
586        // Also update the LookupResult...
587        // FIXME: This should probably go away at some point
588        Result.clear();
589        Result.setLookupName(Corrected.getCorrection());
590        if (FirstDecl) Result.addDecl(FirstDecl);
591
592        // Typo correction corrected to a keyword.
593        if (Corrected.isKeyword())
594          return Corrected.getCorrectionAsIdentifierInfo();
595
596        if (FirstDecl)
597          Diag(FirstDecl->getLocation(), diag::note_previous_decl)
598            << CorrectedQuotedStr;
599
600        // If we found an Objective-C instance variable, let
601        // LookupInObjCMethod build the appropriate expression to
602        // reference the ivar.
603        // FIXME: This is a gross hack.
604        if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
605          Result.clear();
606          ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
607          return move(E);
608        }
609
610        goto Corrected;
611      }
612    }
613
614    // We failed to correct; just fall through and let the parser deal with it.
615    Result.suppressDiagnostics();
616    return NameClassification::Unknown();
617
618  case LookupResult::NotFoundInCurrentInstantiation:
619    // We performed name lookup into the current instantiation, and there were
620    // dependent bases, so we treat this result the same way as any other
621    // dependent nested-name-specifier.
622
623    // C++ [temp.res]p2:
624    //   A name used in a template declaration or definition and that is
625    //   dependent on a template-parameter is assumed not to name a type
626    //   unless the applicable name lookup finds a type name or the name is
627    //   qualified by the keyword typename.
628    //
629    // FIXME: If the next token is '<', we might want to ask the parser to
630    // perform some heroics to see if we actually have a
631    // template-argument-list, which would indicate a missing 'template'
632    // keyword here.
633    return BuildDependentDeclRefExpr(SS, NameInfo, /*TemplateArgs=*/0);
634
635  case LookupResult::Found:
636  case LookupResult::FoundOverloaded:
637  case LookupResult::FoundUnresolvedValue:
638    break;
639
640  case LookupResult::Ambiguous:
641    if (getLangOptions().CPlusPlus && NextToken.is(tok::less) &&
642        hasAnyAcceptableTemplateNames(Result)) {
643      // C++ [temp.local]p3:
644      //   A lookup that finds an injected-class-name (10.2) can result in an
645      //   ambiguity in certain cases (for example, if it is found in more than
646      //   one base class). If all of the injected-class-names that are found
647      //   refer to specializations of the same class template, and if the name
648      //   is followed by a template-argument-list, the reference refers to the
649      //   class template itself and not a specialization thereof, and is not
650      //   ambiguous.
651      //
652      // This filtering can make an ambiguous result into an unambiguous one,
653      // so try again after filtering out template names.
654      FilterAcceptableTemplateNames(Result);
655      if (!Result.isAmbiguous()) {
656        IsFilteredTemplateName = true;
657        break;
658      }
659    }
660
661    // Diagnose the ambiguity and return an error.
662    return NameClassification::Error();
663  }
664
665  if (getLangOptions().CPlusPlus && NextToken.is(tok::less) &&
666      (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
667    // C++ [temp.names]p3:
668    //   After name lookup (3.4) finds that a name is a template-name or that
669    //   an operator-function-id or a literal- operator-id refers to a set of
670    //   overloaded functions any member of which is a function template if
671    //   this is followed by a <, the < is always taken as the delimiter of a
672    //   template-argument-list and never as the less-than operator.
673    if (!IsFilteredTemplateName)
674      FilterAcceptableTemplateNames(Result);
675
676    if (!Result.empty()) {
677      bool IsFunctionTemplate;
678      TemplateName Template;
679      if (Result.end() - Result.begin() > 1) {
680        IsFunctionTemplate = true;
681        Template = Context.getOverloadedTemplateName(Result.begin(),
682                                                     Result.end());
683      } else {
684        TemplateDecl *TD
685          = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
686        IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
687
688        if (SS.isSet() && !SS.isInvalid())
689          Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
690                                                    /*TemplateKeyword=*/false,
691                                                      TD);
692        else
693          Template = TemplateName(TD);
694      }
695
696      if (IsFunctionTemplate) {
697        // Function templates always go through overload resolution, at which
698        // point we'll perform the various checks (e.g., accessibility) we need
699        // to based on which function we selected.
700        Result.suppressDiagnostics();
701
702        return NameClassification::FunctionTemplate(Template);
703      }
704
705      return NameClassification::TypeTemplate(Template);
706    }
707  }
708
709  NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
710  if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
711    DiagnoseUseOfDecl(Type, NameLoc);
712    QualType T = Context.getTypeDeclType(Type);
713    return ParsedType::make(T);
714  }
715
716  ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
717  if (!Class) {
718    // FIXME: It's unfortunate that we don't have a Type node for handling this.
719    if (ObjCCompatibleAliasDecl *Alias
720                                = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
721      Class = Alias->getClassInterface();
722  }
723
724  if (Class) {
725    DiagnoseUseOfDecl(Class, NameLoc);
726
727    if (NextToken.is(tok::period)) {
728      // Interface. <something> is parsed as a property reference expression.
729      // Just return "unknown" as a fall-through for now.
730      Result.suppressDiagnostics();
731      return NameClassification::Unknown();
732    }
733
734    QualType T = Context.getObjCInterfaceType(Class);
735    return ParsedType::make(T);
736  }
737
738  if (!Result.empty() && (*Result.begin())->isCXXClassMember())
739    return BuildPossibleImplicitMemberExpr(SS, Result, 0);
740
741  bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
742  return BuildDeclarationNameExpr(SS, Result, ADL);
743}
744
745// Determines the context to return to after temporarily entering a
746// context.  This depends in an unnecessarily complicated way on the
747// exact ordering of callbacks from the parser.
748DeclContext *Sema::getContainingDC(DeclContext *DC) {
749
750  // Functions defined inline within classes aren't parsed until we've
751  // finished parsing the top-level class, so the top-level class is
752  // the context we'll need to return to.
753  if (isa<FunctionDecl>(DC)) {
754    DC = DC->getLexicalParent();
755
756    // A function not defined within a class will always return to its
757    // lexical context.
758    if (!isa<CXXRecordDecl>(DC))
759      return DC;
760
761    // A C++ inline method/friend is parsed *after* the topmost class
762    // it was declared in is fully parsed ("complete");  the topmost
763    // class is the context we need to return to.
764    while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
765      DC = RD;
766
767    // Return the declaration context of the topmost class the inline method is
768    // declared in.
769    return DC;
770  }
771
772  return DC->getLexicalParent();
773}
774
775void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
776  assert(getContainingDC(DC) == CurContext &&
777      "The next DeclContext should be lexically contained in the current one.");
778  CurContext = DC;
779  S->setEntity(DC);
780}
781
782void Sema::PopDeclContext() {
783  assert(CurContext && "DeclContext imbalance!");
784
785  CurContext = getContainingDC(CurContext);
786  assert(CurContext && "Popped translation unit!");
787}
788
789/// EnterDeclaratorContext - Used when we must lookup names in the context
790/// of a declarator's nested name specifier.
791///
792void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
793  // C++0x [basic.lookup.unqual]p13:
794  //   A name used in the definition of a static data member of class
795  //   X (after the qualified-id of the static member) is looked up as
796  //   if the name was used in a member function of X.
797  // C++0x [basic.lookup.unqual]p14:
798  //   If a variable member of a namespace is defined outside of the
799  //   scope of its namespace then any name used in the definition of
800  //   the variable member (after the declarator-id) is looked up as
801  //   if the definition of the variable member occurred in its
802  //   namespace.
803  // Both of these imply that we should push a scope whose context
804  // is the semantic context of the declaration.  We can't use
805  // PushDeclContext here because that context is not necessarily
806  // lexically contained in the current context.  Fortunately,
807  // the containing scope should have the appropriate information.
808
809  assert(!S->getEntity() && "scope already has entity");
810
811#ifndef NDEBUG
812  Scope *Ancestor = S->getParent();
813  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
814  assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
815#endif
816
817  CurContext = DC;
818  S->setEntity(DC);
819}
820
821void Sema::ExitDeclaratorContext(Scope *S) {
822  assert(S->getEntity() == CurContext && "Context imbalance!");
823
824  // Switch back to the lexical context.  The safety of this is
825  // enforced by an assert in EnterDeclaratorContext.
826  Scope *Ancestor = S->getParent();
827  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
828  CurContext = (DeclContext*) Ancestor->getEntity();
829
830  // We don't need to do anything with the scope, which is going to
831  // disappear.
832}
833
834
835void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
836  FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
837  if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
838    // We assume that the caller has already called
839    // ActOnReenterTemplateScope
840    FD = TFD->getTemplatedDecl();
841  }
842  if (!FD)
843    return;
844
845  PushDeclContext(S, FD);
846  for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
847    ParmVarDecl *Param = FD->getParamDecl(P);
848    // If the parameter has an identifier, then add it to the scope
849    if (Param->getIdentifier()) {
850      S->AddDecl(Param);
851      IdResolver.AddDecl(Param);
852    }
853  }
854}
855
856
857/// \brief Determine whether we allow overloading of the function
858/// PrevDecl with another declaration.
859///
860/// This routine determines whether overloading is possible, not
861/// whether some new function is actually an overload. It will return
862/// true in C++ (where we can always provide overloads) or, as an
863/// extension, in C when the previous function is already an
864/// overloaded function declaration or has the "overloadable"
865/// attribute.
866static bool AllowOverloadingOfFunction(LookupResult &Previous,
867                                       ASTContext &Context) {
868  if (Context.getLangOptions().CPlusPlus)
869    return true;
870
871  if (Previous.getResultKind() == LookupResult::FoundOverloaded)
872    return true;
873
874  return (Previous.getResultKind() == LookupResult::Found
875          && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
876}
877
878/// Add this decl to the scope shadowed decl chains.
879void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
880  // Move up the scope chain until we find the nearest enclosing
881  // non-transparent context. The declaration will be introduced into this
882  // scope.
883  while (S->getEntity() &&
884         ((DeclContext *)S->getEntity())->isTransparentContext())
885    S = S->getParent();
886
887  // Add scoped declarations into their context, so that they can be
888  // found later. Declarations without a context won't be inserted
889  // into any context.
890  if (AddToContext)
891    CurContext->addDecl(D);
892
893  // Out-of-line definitions shouldn't be pushed into scope in C++.
894  // Out-of-line variable and function definitions shouldn't even in C.
895  if ((getLangOptions().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
896      D->isOutOfLine() &&
897      !D->getDeclContext()->getRedeclContext()->Equals(
898        D->getLexicalDeclContext()->getRedeclContext()))
899    return;
900
901  // Template instantiations should also not be pushed into scope.
902  if (isa<FunctionDecl>(D) &&
903      cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
904    return;
905
906  // If this replaces anything in the current scope,
907  IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
908                               IEnd = IdResolver.end();
909  for (; I != IEnd; ++I) {
910    if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
911      S->RemoveDecl(*I);
912      IdResolver.RemoveDecl(*I);
913
914      // Should only need to replace one decl.
915      break;
916    }
917  }
918
919  S->AddDecl(D);
920
921  if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
922    // Implicitly-generated labels may end up getting generated in an order that
923    // isn't strictly lexical, which breaks name lookup. Be careful to insert
924    // the label at the appropriate place in the identifier chain.
925    for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
926      DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
927      if (IDC == CurContext) {
928        if (!S->isDeclScope(*I))
929          continue;
930      } else if (IDC->Encloses(CurContext))
931        break;
932    }
933
934    IdResolver.InsertDeclAfter(I, D);
935  } else {
936    IdResolver.AddDecl(D);
937  }
938}
939
940void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
941  if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
942    TUScope->AddDecl(D);
943}
944
945bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S,
946                         bool ExplicitInstantiationOrSpecialization) {
947  return IdResolver.isDeclInScope(D, Ctx, Context, S,
948                                  ExplicitInstantiationOrSpecialization);
949}
950
951Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
952  DeclContext *TargetDC = DC->getPrimaryContext();
953  do {
954    if (DeclContext *ScopeDC = (DeclContext*) S->getEntity())
955      if (ScopeDC->getPrimaryContext() == TargetDC)
956        return S;
957  } while ((S = S->getParent()));
958
959  return 0;
960}
961
962static bool isOutOfScopePreviousDeclaration(NamedDecl *,
963                                            DeclContext*,
964                                            ASTContext&);
965
966/// Filters out lookup results that don't fall within the given scope
967/// as determined by isDeclInScope.
968void Sema::FilterLookupForScope(LookupResult &R,
969                                DeclContext *Ctx, Scope *S,
970                                bool ConsiderLinkage,
971                                bool ExplicitInstantiationOrSpecialization) {
972  LookupResult::Filter F = R.makeFilter();
973  while (F.hasNext()) {
974    NamedDecl *D = F.next();
975
976    if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
977      continue;
978
979    if (ConsiderLinkage &&
980        isOutOfScopePreviousDeclaration(D, Ctx, Context))
981      continue;
982
983    F.erase();
984  }
985
986  F.done();
987}
988
989static bool isUsingDecl(NamedDecl *D) {
990  return isa<UsingShadowDecl>(D) ||
991         isa<UnresolvedUsingTypenameDecl>(D) ||
992         isa<UnresolvedUsingValueDecl>(D);
993}
994
995/// Removes using shadow declarations from the lookup results.
996static void RemoveUsingDecls(LookupResult &R) {
997  LookupResult::Filter F = R.makeFilter();
998  while (F.hasNext())
999    if (isUsingDecl(F.next()))
1000      F.erase();
1001
1002  F.done();
1003}
1004
1005/// \brief Check for this common pattern:
1006/// @code
1007/// class S {
1008///   S(const S&); // DO NOT IMPLEMENT
1009///   void operator=(const S&); // DO NOT IMPLEMENT
1010/// };
1011/// @endcode
1012static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1013  // FIXME: Should check for private access too but access is set after we get
1014  // the decl here.
1015  if (D->doesThisDeclarationHaveABody())
1016    return false;
1017
1018  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1019    return CD->isCopyConstructor();
1020  if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1021    return Method->isCopyAssignmentOperator();
1022  return false;
1023}
1024
1025bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1026  assert(D);
1027
1028  if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1029    return false;
1030
1031  // Ignore class templates.
1032  if (D->getDeclContext()->isDependentContext() ||
1033      D->getLexicalDeclContext()->isDependentContext())
1034    return false;
1035
1036  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1037    if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1038      return false;
1039
1040    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1041      if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1042        return false;
1043    } else {
1044      // 'static inline' functions are used in headers; don't warn.
1045      if (FD->getStorageClass() == SC_Static &&
1046          FD->isInlineSpecified())
1047        return false;
1048    }
1049
1050    if (FD->doesThisDeclarationHaveABody() &&
1051        Context.DeclMustBeEmitted(FD))
1052      return false;
1053  } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1054    if (!VD->isFileVarDecl() ||
1055        VD->getType().isConstant(Context) ||
1056        Context.DeclMustBeEmitted(VD))
1057      return false;
1058
1059    if (VD->isStaticDataMember() &&
1060        VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1061      return false;
1062
1063  } else {
1064    return false;
1065  }
1066
1067  // Only warn for unused decls internal to the translation unit.
1068  if (D->getLinkage() == ExternalLinkage)
1069    return false;
1070
1071  return true;
1072}
1073
1074void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1075  if (!D)
1076    return;
1077
1078  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1079    const FunctionDecl *First = FD->getFirstDeclaration();
1080    if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1081      return; // First should already be in the vector.
1082  }
1083
1084  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1085    const VarDecl *First = VD->getFirstDeclaration();
1086    if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1087      return; // First should already be in the vector.
1088  }
1089
1090   if (ShouldWarnIfUnusedFileScopedDecl(D))
1091     UnusedFileScopedDecls.push_back(D);
1092 }
1093
1094static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1095  if (D->isInvalidDecl())
1096    return false;
1097
1098  if (D->isUsed() || D->hasAttr<UnusedAttr>())
1099    return false;
1100
1101  if (isa<LabelDecl>(D))
1102    return true;
1103
1104  // White-list anything that isn't a local variable.
1105  if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1106      !D->getDeclContext()->isFunctionOrMethod())
1107    return false;
1108
1109  // Types of valid local variables should be complete, so this should succeed.
1110  if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
1111
1112    // White-list anything with an __attribute__((unused)) type.
1113    QualType Ty = VD->getType();
1114
1115    // Only look at the outermost level of typedef.
1116    if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) {
1117      if (TT->getDecl()->hasAttr<UnusedAttr>())
1118        return false;
1119    }
1120
1121    // If we failed to complete the type for some reason, or if the type is
1122    // dependent, don't diagnose the variable.
1123    if (Ty->isIncompleteType() || Ty->isDependentType())
1124      return false;
1125
1126    if (const TagType *TT = Ty->getAs<TagType>()) {
1127      const TagDecl *Tag = TT->getDecl();
1128      if (Tag->hasAttr<UnusedAttr>())
1129        return false;
1130
1131      if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1132        // FIXME: Checking for the presence of a user-declared constructor
1133        // isn't completely accurate; we'd prefer to check that the initializer
1134        // has no side effects.
1135        if (RD->hasUserDeclaredConstructor() || !RD->hasTrivialDestructor())
1136          return false;
1137      }
1138    }
1139
1140    // TODO: __attribute__((unused)) templates?
1141  }
1142
1143  return true;
1144}
1145
1146static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1147                                     FixItHint &Hint) {
1148  if (isa<LabelDecl>(D)) {
1149    SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1150                tok::colon, Ctx.getSourceManager(), Ctx.getLangOptions(), true);
1151    if (AfterColon.isInvalid())
1152      return;
1153    Hint = FixItHint::CreateRemoval(CharSourceRange::
1154                                    getCharRange(D->getLocStart(), AfterColon));
1155  }
1156  return;
1157}
1158
1159/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1160/// unless they are marked attr(unused).
1161void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1162  FixItHint Hint;
1163  if (!ShouldDiagnoseUnusedDecl(D))
1164    return;
1165
1166  GenerateFixForUnusedDecl(D, Context, Hint);
1167
1168  unsigned DiagID;
1169  if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1170    DiagID = diag::warn_unused_exception_param;
1171  else if (isa<LabelDecl>(D))
1172    DiagID = diag::warn_unused_label;
1173  else
1174    DiagID = diag::warn_unused_variable;
1175
1176  Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1177}
1178
1179static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1180  // Verify that we have no forward references left.  If so, there was a goto
1181  // or address of a label taken, but no definition of it.  Label fwd
1182  // definitions are indicated with a null substmt.
1183  if (L->getStmt() == 0)
1184    S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1185}
1186
1187void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1188  if (S->decl_empty()) return;
1189  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1190         "Scope shouldn't contain decls!");
1191
1192  for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1193       I != E; ++I) {
1194    Decl *TmpD = (*I);
1195    assert(TmpD && "This decl didn't get pushed??");
1196
1197    assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1198    NamedDecl *D = cast<NamedDecl>(TmpD);
1199
1200    if (!D->getDeclName()) continue;
1201
1202    // Diagnose unused variables in this scope.
1203    if (!S->hasErrorOccurred())
1204      DiagnoseUnusedDecl(D);
1205
1206    // If this was a forward reference to a label, verify it was defined.
1207    if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1208      CheckPoppedLabel(LD, *this);
1209
1210    // Remove this name from our lexical scope.
1211    IdResolver.RemoveDecl(D);
1212  }
1213}
1214
1215/// \brief Look for an Objective-C class in the translation unit.
1216///
1217/// \param Id The name of the Objective-C class we're looking for. If
1218/// typo-correction fixes this name, the Id will be updated
1219/// to the fixed name.
1220///
1221/// \param IdLoc The location of the name in the translation unit.
1222///
1223/// \param TypoCorrection If true, this routine will attempt typo correction
1224/// if there is no class with the given name.
1225///
1226/// \returns The declaration of the named Objective-C class, or NULL if the
1227/// class could not be found.
1228ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1229                                              SourceLocation IdLoc,
1230                                              bool DoTypoCorrection) {
1231  // The third "scope" argument is 0 since we aren't enabling lazy built-in
1232  // creation from this context.
1233  NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1234
1235  if (!IDecl && DoTypoCorrection) {
1236    // Perform typo correction at the given location, but only if we
1237    // find an Objective-C class name.
1238    TypoCorrection C;
1239    if ((C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1240                         TUScope, NULL, NULL, false, CTC_NoKeywords)) &&
1241        (IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>())) {
1242      Diag(IdLoc, diag::err_undef_interface_suggest)
1243        << Id << IDecl->getDeclName()
1244        << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
1245      Diag(IDecl->getLocation(), diag::note_previous_decl)
1246        << IDecl->getDeclName();
1247
1248      Id = IDecl->getIdentifier();
1249    }
1250  }
1251
1252  return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1253}
1254
1255/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1256/// from S, where a non-field would be declared. This routine copes
1257/// with the difference between C and C++ scoping rules in structs and
1258/// unions. For example, the following code is well-formed in C but
1259/// ill-formed in C++:
1260/// @code
1261/// struct S6 {
1262///   enum { BAR } e;
1263/// };
1264///
1265/// void test_S6() {
1266///   struct S6 a;
1267///   a.e = BAR;
1268/// }
1269/// @endcode
1270/// For the declaration of BAR, this routine will return a different
1271/// scope. The scope S will be the scope of the unnamed enumeration
1272/// within S6. In C++, this routine will return the scope associated
1273/// with S6, because the enumeration's scope is a transparent
1274/// context but structures can contain non-field names. In C, this
1275/// routine will return the translation unit scope, since the
1276/// enumeration's scope is a transparent context and structures cannot
1277/// contain non-field names.
1278Scope *Sema::getNonFieldDeclScope(Scope *S) {
1279  while (((S->getFlags() & Scope::DeclScope) == 0) ||
1280         (S->getEntity() &&
1281          ((DeclContext *)S->getEntity())->isTransparentContext()) ||
1282         (S->isClassScope() && !getLangOptions().CPlusPlus))
1283    S = S->getParent();
1284  return S;
1285}
1286
1287/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1288/// file scope.  lazily create a decl for it. ForRedeclaration is true
1289/// if we're creating this built-in in anticipation of redeclaring the
1290/// built-in.
1291NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
1292                                     Scope *S, bool ForRedeclaration,
1293                                     SourceLocation Loc) {
1294  Builtin::ID BID = (Builtin::ID)bid;
1295
1296  ASTContext::GetBuiltinTypeError Error;
1297  QualType R = Context.GetBuiltinType(BID, Error);
1298  switch (Error) {
1299  case ASTContext::GE_None:
1300    // Okay
1301    break;
1302
1303  case ASTContext::GE_Missing_stdio:
1304    if (ForRedeclaration)
1305      Diag(Loc, diag::warn_implicit_decl_requires_stdio)
1306        << Context.BuiltinInfo.GetName(BID);
1307    return 0;
1308
1309  case ASTContext::GE_Missing_setjmp:
1310    if (ForRedeclaration)
1311      Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
1312        << Context.BuiltinInfo.GetName(BID);
1313    return 0;
1314
1315  case ASTContext::GE_Missing_ucontext:
1316    if (ForRedeclaration)
1317      Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1318        << Context.BuiltinInfo.GetName(BID);
1319    return 0;
1320  }
1321
1322  if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1323    Diag(Loc, diag::ext_implicit_lib_function_decl)
1324      << Context.BuiltinInfo.GetName(BID)
1325      << R;
1326    if (Context.BuiltinInfo.getHeaderName(BID) &&
1327        Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
1328          != DiagnosticsEngine::Ignored)
1329      Diag(Loc, diag::note_please_include_header)
1330        << Context.BuiltinInfo.getHeaderName(BID)
1331        << Context.BuiltinInfo.GetName(BID);
1332  }
1333
1334  FunctionDecl *New = FunctionDecl::Create(Context,
1335                                           Context.getTranslationUnitDecl(),
1336                                           Loc, Loc, II, R, /*TInfo=*/0,
1337                                           SC_Extern,
1338                                           SC_None, false,
1339                                           /*hasPrototype=*/true);
1340  New->setImplicit();
1341
1342  // Create Decl objects for each parameter, adding them to the
1343  // FunctionDecl.
1344  if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1345    SmallVector<ParmVarDecl*, 16> Params;
1346    for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1347      ParmVarDecl *parm =
1348        ParmVarDecl::Create(Context, New, SourceLocation(),
1349                            SourceLocation(), 0,
1350                            FT->getArgType(i), /*TInfo=*/0,
1351                            SC_None, SC_None, 0);
1352      parm->setScopeInfo(0, i);
1353      Params.push_back(parm);
1354    }
1355    New->setParams(Params);
1356  }
1357
1358  AddKnownFunctionAttributes(New);
1359
1360  // TUScope is the translation-unit scope to insert this function into.
1361  // FIXME: This is hideous. We need to teach PushOnScopeChains to
1362  // relate Scopes to DeclContexts, and probably eliminate CurContext
1363  // entirely, but we're not there yet.
1364  DeclContext *SavedContext = CurContext;
1365  CurContext = Context.getTranslationUnitDecl();
1366  PushOnScopeChains(New, TUScope);
1367  CurContext = SavedContext;
1368  return New;
1369}
1370
1371/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1372/// same name and scope as a previous declaration 'Old'.  Figure out
1373/// how to resolve this situation, merging decls or emitting
1374/// diagnostics as appropriate. If there was an error, set New to be invalid.
1375///
1376void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
1377  // If the new decl is known invalid already, don't bother doing any
1378  // merging checks.
1379  if (New->isInvalidDecl()) return;
1380
1381  // Allow multiple definitions for ObjC built-in typedefs.
1382  // FIXME: Verify the underlying types are equivalent!
1383  if (getLangOptions().ObjC1) {
1384    const IdentifierInfo *TypeID = New->getIdentifier();
1385    switch (TypeID->getLength()) {
1386    default: break;
1387    case 2:
1388      if (!TypeID->isStr("id"))
1389        break;
1390      Context.setObjCIdRedefinitionType(New->getUnderlyingType());
1391      // Install the built-in type for 'id', ignoring the current definition.
1392      New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1393      return;
1394    case 5:
1395      if (!TypeID->isStr("Class"))
1396        break;
1397      Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1398      // Install the built-in type for 'Class', ignoring the current definition.
1399      New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1400      return;
1401    case 3:
1402      if (!TypeID->isStr("SEL"))
1403        break;
1404      Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1405      // Install the built-in type for 'SEL', ignoring the current definition.
1406      New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1407      return;
1408    }
1409    // Fall through - the typedef name was not a builtin type.
1410  }
1411
1412  // Verify the old decl was also a type.
1413  TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1414  if (!Old) {
1415    Diag(New->getLocation(), diag::err_redefinition_different_kind)
1416      << New->getDeclName();
1417
1418    NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1419    if (OldD->getLocation().isValid())
1420      Diag(OldD->getLocation(), diag::note_previous_definition);
1421
1422    return New->setInvalidDecl();
1423  }
1424
1425  // If the old declaration is invalid, just give up here.
1426  if (Old->isInvalidDecl())
1427    return New->setInvalidDecl();
1428
1429  // Determine the "old" type we'll use for checking and diagnostics.
1430  QualType OldType;
1431  if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1432    OldType = OldTypedef->getUnderlyingType();
1433  else
1434    OldType = Context.getTypeDeclType(Old);
1435
1436  // If the typedef types are not identical, reject them in all languages and
1437  // with any extensions enabled.
1438
1439  if (OldType != New->getUnderlyingType() &&
1440      Context.getCanonicalType(OldType) !=
1441      Context.getCanonicalType(New->getUnderlyingType())) {
1442    int Kind = 0;
1443    if (isa<TypeAliasDecl>(Old))
1444      Kind = 1;
1445    Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1446      << Kind << New->getUnderlyingType() << OldType;
1447    if (Old->getLocation().isValid())
1448      Diag(Old->getLocation(), diag::note_previous_definition);
1449    return New->setInvalidDecl();
1450  }
1451
1452  // The types match.  Link up the redeclaration chain if the old
1453  // declaration was a typedef.
1454  // FIXME: this is a potential source of weirdness if the type
1455  // spellings don't match exactly.
1456  if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old))
1457    New->setPreviousDeclaration(Typedef);
1458
1459  if (getLangOptions().MicrosoftExt)
1460    return;
1461
1462  if (getLangOptions().CPlusPlus) {
1463    // C++ [dcl.typedef]p2:
1464    //   In a given non-class scope, a typedef specifier can be used to
1465    //   redefine the name of any type declared in that scope to refer
1466    //   to the type to which it already refers.
1467    if (!isa<CXXRecordDecl>(CurContext))
1468      return;
1469
1470    // C++0x [dcl.typedef]p4:
1471    //   In a given class scope, a typedef specifier can be used to redefine
1472    //   any class-name declared in that scope that is not also a typedef-name
1473    //   to refer to the type to which it already refers.
1474    //
1475    // This wording came in via DR424, which was a correction to the
1476    // wording in DR56, which accidentally banned code like:
1477    //
1478    //   struct S {
1479    //     typedef struct A { } A;
1480    //   };
1481    //
1482    // in the C++03 standard. We implement the C++0x semantics, which
1483    // allow the above but disallow
1484    //
1485    //   struct S {
1486    //     typedef int I;
1487    //     typedef int I;
1488    //   };
1489    //
1490    // since that was the intent of DR56.
1491    if (!isa<TypedefNameDecl>(Old))
1492      return;
1493
1494    Diag(New->getLocation(), diag::err_redefinition)
1495      << New->getDeclName();
1496    Diag(Old->getLocation(), diag::note_previous_definition);
1497    return New->setInvalidDecl();
1498  }
1499
1500  // If we have a redefinition of a typedef in C, emit a warning.  This warning
1501  // is normally mapped to an error, but can be controlled with
1502  // -Wtypedef-redefinition.  If either the original or the redefinition is
1503  // in a system header, don't emit this for compatibility with GCC.
1504  if (getDiagnostics().getSuppressSystemWarnings() &&
1505      (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1506       Context.getSourceManager().isInSystemHeader(New->getLocation())))
1507    return;
1508
1509  Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1510    << New->getDeclName();
1511  Diag(Old->getLocation(), diag::note_previous_definition);
1512  return;
1513}
1514
1515/// DeclhasAttr - returns true if decl Declaration already has the target
1516/// attribute.
1517static bool
1518DeclHasAttr(const Decl *D, const Attr *A) {
1519  const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
1520  const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
1521  for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1522    if ((*i)->getKind() == A->getKind()) {
1523      if (Ann) {
1524        if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1525          return true;
1526        continue;
1527      }
1528      // FIXME: Don't hardcode this check
1529      if (OA && isa<OwnershipAttr>(*i))
1530        return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
1531      return true;
1532    }
1533
1534  return false;
1535}
1536
1537/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
1538static void mergeDeclAttributes(Decl *newDecl, const Decl *oldDecl,
1539                                ASTContext &C, bool mergeDeprecation = true) {
1540  if (!oldDecl->hasAttrs())
1541    return;
1542
1543  bool foundAny = newDecl->hasAttrs();
1544
1545  // Ensure that any moving of objects within the allocated map is done before
1546  // we process them.
1547  if (!foundAny) newDecl->setAttrs(AttrVec());
1548
1549  for (specific_attr_iterator<InheritableAttr>
1550       i = oldDecl->specific_attr_begin<InheritableAttr>(),
1551       e = oldDecl->specific_attr_end<InheritableAttr>(); i != e; ++i) {
1552    // Ignore deprecated/unavailable/availability attributes if requested.
1553    if (!mergeDeprecation &&
1554        (isa<DeprecatedAttr>(*i) ||
1555         isa<UnavailableAttr>(*i) ||
1556         isa<AvailabilityAttr>(*i)))
1557      continue;
1558
1559    if (!DeclHasAttr(newDecl, *i)) {
1560      InheritableAttr *newAttr = cast<InheritableAttr>((*i)->clone(C));
1561      newAttr->setInherited(true);
1562      newDecl->addAttr(newAttr);
1563      foundAny = true;
1564    }
1565  }
1566
1567  if (!foundAny) newDecl->dropAttrs();
1568}
1569
1570/// mergeParamDeclAttributes - Copy attributes from the old parameter
1571/// to the new one.
1572static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
1573                                     const ParmVarDecl *oldDecl,
1574                                     ASTContext &C) {
1575  if (!oldDecl->hasAttrs())
1576    return;
1577
1578  bool foundAny = newDecl->hasAttrs();
1579
1580  // Ensure that any moving of objects within the allocated map is
1581  // done before we process them.
1582  if (!foundAny) newDecl->setAttrs(AttrVec());
1583
1584  for (specific_attr_iterator<InheritableParamAttr>
1585       i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
1586       e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
1587    if (!DeclHasAttr(newDecl, *i)) {
1588      InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C));
1589      newAttr->setInherited(true);
1590      newDecl->addAttr(newAttr);
1591      foundAny = true;
1592    }
1593  }
1594
1595  if (!foundAny) newDecl->dropAttrs();
1596}
1597
1598namespace {
1599
1600/// Used in MergeFunctionDecl to keep track of function parameters in
1601/// C.
1602struct GNUCompatibleParamWarning {
1603  ParmVarDecl *OldParm;
1604  ParmVarDecl *NewParm;
1605  QualType PromotedType;
1606};
1607
1608}
1609
1610/// getSpecialMember - get the special member enum for a method.
1611Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
1612  if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
1613    if (Ctor->isDefaultConstructor())
1614      return Sema::CXXDefaultConstructor;
1615
1616    if (Ctor->isCopyConstructor())
1617      return Sema::CXXCopyConstructor;
1618
1619    if (Ctor->isMoveConstructor())
1620      return Sema::CXXMoveConstructor;
1621  } else if (isa<CXXDestructorDecl>(MD)) {
1622    return Sema::CXXDestructor;
1623  } else if (MD->isCopyAssignmentOperator()) {
1624    return Sema::CXXCopyAssignment;
1625  } else if (MD->isMoveAssignmentOperator()) {
1626    return Sema::CXXMoveAssignment;
1627  }
1628
1629  return Sema::CXXInvalid;
1630}
1631
1632/// canRedefineFunction - checks if a function can be redefined. Currently,
1633/// only extern inline functions can be redefined, and even then only in
1634/// GNU89 mode.
1635static bool canRedefineFunction(const FunctionDecl *FD,
1636                                const LangOptions& LangOpts) {
1637  return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
1638          !LangOpts.CPlusPlus &&
1639          FD->isInlineSpecified() &&
1640          FD->getStorageClass() == SC_Extern);
1641}
1642
1643/// MergeFunctionDecl - We just parsed a function 'New' from
1644/// declarator D which has the same name and scope as a previous
1645/// declaration 'Old'.  Figure out how to resolve this situation,
1646/// merging decls or emitting diagnostics as appropriate.
1647///
1648/// In C++, New and Old must be declarations that are not
1649/// overloaded. Use IsOverload to determine whether New and Old are
1650/// overloaded, and to select the Old declaration that New should be
1651/// merged with.
1652///
1653/// Returns true if there was an error, false otherwise.
1654bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
1655  // Verify the old decl was also a function.
1656  FunctionDecl *Old = 0;
1657  if (FunctionTemplateDecl *OldFunctionTemplate
1658        = dyn_cast<FunctionTemplateDecl>(OldD))
1659    Old = OldFunctionTemplate->getTemplatedDecl();
1660  else
1661    Old = dyn_cast<FunctionDecl>(OldD);
1662  if (!Old) {
1663    if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
1664      Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
1665      Diag(Shadow->getTargetDecl()->getLocation(),
1666           diag::note_using_decl_target);
1667      Diag(Shadow->getUsingDecl()->getLocation(),
1668           diag::note_using_decl) << 0;
1669      return true;
1670    }
1671
1672    Diag(New->getLocation(), diag::err_redefinition_different_kind)
1673      << New->getDeclName();
1674    Diag(OldD->getLocation(), diag::note_previous_definition);
1675    return true;
1676  }
1677
1678  // Determine whether the previous declaration was a definition,
1679  // implicit declaration, or a declaration.
1680  diag::kind PrevDiag;
1681  if (Old->isThisDeclarationADefinition())
1682    PrevDiag = diag::note_previous_definition;
1683  else if (Old->isImplicit())
1684    PrevDiag = diag::note_previous_implicit_declaration;
1685  else
1686    PrevDiag = diag::note_previous_declaration;
1687
1688  QualType OldQType = Context.getCanonicalType(Old->getType());
1689  QualType NewQType = Context.getCanonicalType(New->getType());
1690
1691  // Don't complain about this if we're in GNU89 mode and the old function
1692  // is an extern inline function.
1693  if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
1694      New->getStorageClass() == SC_Static &&
1695      Old->getStorageClass() != SC_Static &&
1696      !canRedefineFunction(Old, getLangOptions())) {
1697    if (getLangOptions().MicrosoftExt) {
1698      Diag(New->getLocation(), diag::warn_static_non_static) << New;
1699      Diag(Old->getLocation(), PrevDiag);
1700    } else {
1701      Diag(New->getLocation(), diag::err_static_non_static) << New;
1702      Diag(Old->getLocation(), PrevDiag);
1703      return true;
1704    }
1705  }
1706
1707  // If a function is first declared with a calling convention, but is
1708  // later declared or defined without one, the second decl assumes the
1709  // calling convention of the first.
1710  //
1711  // For the new decl, we have to look at the NON-canonical type to tell the
1712  // difference between a function that really doesn't have a calling
1713  // convention and one that is declared cdecl. That's because in
1714  // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
1715  // because it is the default calling convention.
1716  //
1717  // Note also that we DO NOT return at this point, because we still have
1718  // other tests to run.
1719  const FunctionType *OldType = cast<FunctionType>(OldQType);
1720  const FunctionType *NewType = New->getType()->getAs<FunctionType>();
1721  FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
1722  FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
1723  bool RequiresAdjustment = false;
1724  if (OldTypeInfo.getCC() != CC_Default &&
1725      NewTypeInfo.getCC() == CC_Default) {
1726    NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
1727    RequiresAdjustment = true;
1728  } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
1729                                     NewTypeInfo.getCC())) {
1730    // Calling conventions really aren't compatible, so complain.
1731    Diag(New->getLocation(), diag::err_cconv_change)
1732      << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
1733      << (OldTypeInfo.getCC() == CC_Default)
1734      << (OldTypeInfo.getCC() == CC_Default ? "" :
1735          FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
1736    Diag(Old->getLocation(), diag::note_previous_declaration);
1737    return true;
1738  }
1739
1740  // FIXME: diagnose the other way around?
1741  if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
1742    NewTypeInfo = NewTypeInfo.withNoReturn(true);
1743    RequiresAdjustment = true;
1744  }
1745
1746  // Merge regparm attribute.
1747  if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
1748      OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
1749    if (NewTypeInfo.getHasRegParm()) {
1750      Diag(New->getLocation(), diag::err_regparm_mismatch)
1751        << NewType->getRegParmType()
1752        << OldType->getRegParmType();
1753      Diag(Old->getLocation(), diag::note_previous_declaration);
1754      return true;
1755    }
1756
1757    NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
1758    RequiresAdjustment = true;
1759  }
1760
1761  // Merge ns_returns_retained attribute.
1762  if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
1763    if (NewTypeInfo.getProducesResult()) {
1764      Diag(New->getLocation(), diag::err_returns_retained_mismatch);
1765      Diag(Old->getLocation(), diag::note_previous_declaration);
1766      return true;
1767    }
1768
1769    NewTypeInfo = NewTypeInfo.withProducesResult(true);
1770    RequiresAdjustment = true;
1771  }
1772
1773  if (RequiresAdjustment) {
1774    NewType = Context.adjustFunctionType(NewType, NewTypeInfo);
1775    New->setType(QualType(NewType, 0));
1776    NewQType = Context.getCanonicalType(New->getType());
1777  }
1778
1779  if (getLangOptions().CPlusPlus) {
1780    // (C++98 13.1p2):
1781    //   Certain function declarations cannot be overloaded:
1782    //     -- Function declarations that differ only in the return type
1783    //        cannot be overloaded.
1784    QualType OldReturnType = OldType->getResultType();
1785    QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
1786    QualType ResQT;
1787    if (OldReturnType != NewReturnType) {
1788      if (NewReturnType->isObjCObjectPointerType()
1789          && OldReturnType->isObjCObjectPointerType())
1790        ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
1791      if (ResQT.isNull()) {
1792        if (New->isCXXClassMember() && New->isOutOfLine())
1793          Diag(New->getLocation(),
1794               diag::err_member_def_does_not_match_ret_type) << New;
1795        else
1796          Diag(New->getLocation(), diag::err_ovl_diff_return_type);
1797        Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1798        return true;
1799      }
1800      else
1801        NewQType = ResQT;
1802    }
1803
1804    const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
1805    CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
1806    if (OldMethod && NewMethod) {
1807      // Preserve triviality.
1808      NewMethod->setTrivial(OldMethod->isTrivial());
1809
1810      // MSVC allows explicit template specialization at class scope:
1811      // 2 CXMethodDecls referring to the same function will be injected.
1812      // We don't want a redeclartion error.
1813      bool IsClassScopeExplicitSpecialization =
1814                              OldMethod->isFunctionTemplateSpecialization() &&
1815                              NewMethod->isFunctionTemplateSpecialization();
1816      bool isFriend = NewMethod->getFriendObjectKind();
1817
1818      if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
1819          !IsClassScopeExplicitSpecialization) {
1820        //    -- Member function declarations with the same name and the
1821        //       same parameter types cannot be overloaded if any of them
1822        //       is a static member function declaration.
1823        if (OldMethod->isStatic() || NewMethod->isStatic()) {
1824          Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
1825          Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1826          return true;
1827        }
1828
1829        // C++ [class.mem]p1:
1830        //   [...] A member shall not be declared twice in the
1831        //   member-specification, except that a nested class or member
1832        //   class template can be declared and then later defined.
1833        unsigned NewDiag;
1834        if (isa<CXXConstructorDecl>(OldMethod))
1835          NewDiag = diag::err_constructor_redeclared;
1836        else if (isa<CXXDestructorDecl>(NewMethod))
1837          NewDiag = diag::err_destructor_redeclared;
1838        else if (isa<CXXConversionDecl>(NewMethod))
1839          NewDiag = diag::err_conv_function_redeclared;
1840        else
1841          NewDiag = diag::err_member_redeclared;
1842
1843        Diag(New->getLocation(), NewDiag);
1844        Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1845
1846      // Complain if this is an explicit declaration of a special
1847      // member that was initially declared implicitly.
1848      //
1849      // As an exception, it's okay to befriend such methods in order
1850      // to permit the implicit constructor/destructor/operator calls.
1851      } else if (OldMethod->isImplicit()) {
1852        if (isFriend) {
1853          NewMethod->setImplicit();
1854        } else {
1855          Diag(NewMethod->getLocation(),
1856               diag::err_definition_of_implicitly_declared_member)
1857            << New << getSpecialMember(OldMethod);
1858          return true;
1859        }
1860      } else if (OldMethod->isExplicitlyDefaulted()) {
1861        Diag(NewMethod->getLocation(),
1862             diag::err_definition_of_explicitly_defaulted_member)
1863          << getSpecialMember(OldMethod);
1864        return true;
1865      }
1866    }
1867
1868    // (C++98 8.3.5p3):
1869    //   All declarations for a function shall agree exactly in both the
1870    //   return type and the parameter-type-list.
1871    // We also want to respect all the extended bits except noreturn.
1872
1873    // noreturn should now match unless the old type info didn't have it.
1874    QualType OldQTypeForComparison = OldQType;
1875    if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
1876      assert(OldQType == QualType(OldType, 0));
1877      const FunctionType *OldTypeForComparison
1878        = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
1879      OldQTypeForComparison = QualType(OldTypeForComparison, 0);
1880      assert(OldQTypeForComparison.isCanonical());
1881    }
1882
1883    if (OldQTypeForComparison == NewQType)
1884      return MergeCompatibleFunctionDecls(New, Old);
1885
1886    // Fall through for conflicting redeclarations and redefinitions.
1887  }
1888
1889  // C: Function types need to be compatible, not identical. This handles
1890  // duplicate function decls like "void f(int); void f(enum X);" properly.
1891  if (!getLangOptions().CPlusPlus &&
1892      Context.typesAreCompatible(OldQType, NewQType)) {
1893    const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
1894    const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
1895    const FunctionProtoType *OldProto = 0;
1896    if (isa<FunctionNoProtoType>(NewFuncType) &&
1897        (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
1898      // The old declaration provided a function prototype, but the
1899      // new declaration does not. Merge in the prototype.
1900      assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
1901      SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
1902                                                 OldProto->arg_type_end());
1903      NewQType = Context.getFunctionType(NewFuncType->getResultType(),
1904                                         ParamTypes.data(), ParamTypes.size(),
1905                                         OldProto->getExtProtoInfo());
1906      New->setType(NewQType);
1907      New->setHasInheritedPrototype();
1908
1909      // Synthesize a parameter for each argument type.
1910      SmallVector<ParmVarDecl*, 16> Params;
1911      for (FunctionProtoType::arg_type_iterator
1912             ParamType = OldProto->arg_type_begin(),
1913             ParamEnd = OldProto->arg_type_end();
1914           ParamType != ParamEnd; ++ParamType) {
1915        ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
1916                                                 SourceLocation(),
1917                                                 SourceLocation(), 0,
1918                                                 *ParamType, /*TInfo=*/0,
1919                                                 SC_None, SC_None,
1920                                                 0);
1921        Param->setScopeInfo(0, Params.size());
1922        Param->setImplicit();
1923        Params.push_back(Param);
1924      }
1925
1926      New->setParams(Params);
1927    }
1928
1929    return MergeCompatibleFunctionDecls(New, Old);
1930  }
1931
1932  // GNU C permits a K&R definition to follow a prototype declaration
1933  // if the declared types of the parameters in the K&R definition
1934  // match the types in the prototype declaration, even when the
1935  // promoted types of the parameters from the K&R definition differ
1936  // from the types in the prototype. GCC then keeps the types from
1937  // the prototype.
1938  //
1939  // If a variadic prototype is followed by a non-variadic K&R definition,
1940  // the K&R definition becomes variadic.  This is sort of an edge case, but
1941  // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
1942  // C99 6.9.1p8.
1943  if (!getLangOptions().CPlusPlus &&
1944      Old->hasPrototype() && !New->hasPrototype() &&
1945      New->getType()->getAs<FunctionProtoType>() &&
1946      Old->getNumParams() == New->getNumParams()) {
1947    SmallVector<QualType, 16> ArgTypes;
1948    SmallVector<GNUCompatibleParamWarning, 16> Warnings;
1949    const FunctionProtoType *OldProto
1950      = Old->getType()->getAs<FunctionProtoType>();
1951    const FunctionProtoType *NewProto
1952      = New->getType()->getAs<FunctionProtoType>();
1953
1954    // Determine whether this is the GNU C extension.
1955    QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
1956                                               NewProto->getResultType());
1957    bool LooseCompatible = !MergedReturn.isNull();
1958    for (unsigned Idx = 0, End = Old->getNumParams();
1959         LooseCompatible && Idx != End; ++Idx) {
1960      ParmVarDecl *OldParm = Old->getParamDecl(Idx);
1961      ParmVarDecl *NewParm = New->getParamDecl(Idx);
1962      if (Context.typesAreCompatible(OldParm->getType(),
1963                                     NewProto->getArgType(Idx))) {
1964        ArgTypes.push_back(NewParm->getType());
1965      } else if (Context.typesAreCompatible(OldParm->getType(),
1966                                            NewParm->getType(),
1967                                            /*CompareUnqualified=*/true)) {
1968        GNUCompatibleParamWarning Warn
1969          = { OldParm, NewParm, NewProto->getArgType(Idx) };
1970        Warnings.push_back(Warn);
1971        ArgTypes.push_back(NewParm->getType());
1972      } else
1973        LooseCompatible = false;
1974    }
1975
1976    if (LooseCompatible) {
1977      for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
1978        Diag(Warnings[Warn].NewParm->getLocation(),
1979             diag::ext_param_promoted_not_compatible_with_prototype)
1980          << Warnings[Warn].PromotedType
1981          << Warnings[Warn].OldParm->getType();
1982        if (Warnings[Warn].OldParm->getLocation().isValid())
1983          Diag(Warnings[Warn].OldParm->getLocation(),
1984               diag::note_previous_declaration);
1985      }
1986
1987      New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
1988                                           ArgTypes.size(),
1989                                           OldProto->getExtProtoInfo()));
1990      return MergeCompatibleFunctionDecls(New, Old);
1991    }
1992
1993    // Fall through to diagnose conflicting types.
1994  }
1995
1996  // A function that has already been declared has been redeclared or defined
1997  // with a different type- show appropriate diagnostic
1998  if (unsigned BuiltinID = Old->getBuiltinID()) {
1999    // The user has declared a builtin function with an incompatible
2000    // signature.
2001    if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2002      // The function the user is redeclaring is a library-defined
2003      // function like 'malloc' or 'printf'. Warn about the
2004      // redeclaration, then pretend that we don't know about this
2005      // library built-in.
2006      Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2007      Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2008        << Old << Old->getType();
2009      New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2010      Old->setInvalidDecl();
2011      return false;
2012    }
2013
2014    PrevDiag = diag::note_previous_builtin_declaration;
2015  }
2016
2017  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
2018  Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2019  return true;
2020}
2021
2022/// \brief Completes the merge of two function declarations that are
2023/// known to be compatible.
2024///
2025/// This routine handles the merging of attributes and other
2026/// properties of function declarations form the old declaration to
2027/// the new declaration, once we know that New is in fact a
2028/// redeclaration of Old.
2029///
2030/// \returns false
2031bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
2032  // Merge the attributes
2033  mergeDeclAttributes(New, Old, Context);
2034
2035  // Merge the storage class.
2036  if (Old->getStorageClass() != SC_Extern &&
2037      Old->getStorageClass() != SC_None)
2038    New->setStorageClass(Old->getStorageClass());
2039
2040  // Merge "pure" flag.
2041  if (Old->isPure())
2042    New->setPure();
2043
2044  // Merge attributes from the parameters.  These can mismatch with K&R
2045  // declarations.
2046  if (New->getNumParams() == Old->getNumParams())
2047    for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2048      mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
2049                               Context);
2050
2051  if (getLangOptions().CPlusPlus)
2052    return MergeCXXFunctionDecl(New, Old);
2053
2054  return false;
2055}
2056
2057
2058void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
2059                                const ObjCMethodDecl *oldMethod) {
2060  // We don't want to merge unavailable and deprecated attributes
2061  // except from interface to implementation.
2062  bool mergeDeprecation = isa<ObjCImplDecl>(newMethod->getDeclContext());
2063
2064  // Merge the attributes.
2065  mergeDeclAttributes(newMethod, oldMethod, Context, mergeDeprecation);
2066
2067  // Merge attributes from the parameters.
2068  ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin();
2069  for (ObjCMethodDecl::param_iterator
2070         ni = newMethod->param_begin(), ne = newMethod->param_end();
2071       ni != ne; ++ni, ++oi)
2072    mergeParamDeclAttributes(*ni, *oi, Context);
2073
2074  CheckObjCMethodOverride(newMethod, oldMethod, true);
2075}
2076
2077/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2078/// scope as a previous declaration 'Old'.  Figure out how to merge their types,
2079/// emitting diagnostics as appropriate.
2080///
2081/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
2082/// to here in AddInitializerToDecl and AddCXXDirectInitializerToDecl. We can't
2083/// check them before the initializer is attached.
2084///
2085void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) {
2086  if (New->isInvalidDecl() || Old->isInvalidDecl())
2087    return;
2088
2089  QualType MergedT;
2090  if (getLangOptions().CPlusPlus) {
2091    AutoType *AT = New->getType()->getContainedAutoType();
2092    if (AT && !AT->isDeduced()) {
2093      // We don't know what the new type is until the initializer is attached.
2094      return;
2095    } else if (Context.hasSameType(New->getType(), Old->getType())) {
2096      // These could still be something that needs exception specs checked.
2097      return MergeVarDeclExceptionSpecs(New, Old);
2098    }
2099    // C++ [basic.link]p10:
2100    //   [...] the types specified by all declarations referring to a given
2101    //   object or function shall be identical, except that declarations for an
2102    //   array object can specify array types that differ by the presence or
2103    //   absence of a major array bound (8.3.4).
2104    else if (Old->getType()->isIncompleteArrayType() &&
2105             New->getType()->isArrayType()) {
2106      CanQual<ArrayType> OldArray
2107        = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
2108      CanQual<ArrayType> NewArray
2109        = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
2110      if (OldArray->getElementType() == NewArray->getElementType())
2111        MergedT = New->getType();
2112    } else if (Old->getType()->isArrayType() &&
2113             New->getType()->isIncompleteArrayType()) {
2114      CanQual<ArrayType> OldArray
2115        = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
2116      CanQual<ArrayType> NewArray
2117        = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
2118      if (OldArray->getElementType() == NewArray->getElementType())
2119        MergedT = Old->getType();
2120    } else if (New->getType()->isObjCObjectPointerType()
2121               && Old->getType()->isObjCObjectPointerType()) {
2122        MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2123                                                        Old->getType());
2124    }
2125  } else {
2126    MergedT = Context.mergeTypes(New->getType(), Old->getType());
2127  }
2128  if (MergedT.isNull()) {
2129    Diag(New->getLocation(), diag::err_redefinition_different_type)
2130      << New->getDeclName();
2131    Diag(Old->getLocation(), diag::note_previous_definition);
2132    return New->setInvalidDecl();
2133  }
2134  New->setType(MergedT);
2135}
2136
2137/// MergeVarDecl - We just parsed a variable 'New' which has the same name
2138/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
2139/// situation, merging decls or emitting diagnostics as appropriate.
2140///
2141/// Tentative definition rules (C99 6.9.2p2) are checked by
2142/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
2143/// definitions here, since the initializer hasn't been attached.
2144///
2145void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
2146  // If the new decl is already invalid, don't do any other checking.
2147  if (New->isInvalidDecl())
2148    return;
2149
2150  // Verify the old decl was also a variable.
2151  VarDecl *Old = 0;
2152  if (!Previous.isSingleResult() ||
2153      !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
2154    Diag(New->getLocation(), diag::err_redefinition_different_kind)
2155      << New->getDeclName();
2156    Diag(Previous.getRepresentativeDecl()->getLocation(),
2157         diag::note_previous_definition);
2158    return New->setInvalidDecl();
2159  }
2160
2161  // C++ [class.mem]p1:
2162  //   A member shall not be declared twice in the member-specification [...]
2163  //
2164  // Here, we need only consider static data members.
2165  if (Old->isStaticDataMember() && !New->isOutOfLine()) {
2166    Diag(New->getLocation(), diag::err_duplicate_member)
2167      << New->getIdentifier();
2168    Diag(Old->getLocation(), diag::note_previous_declaration);
2169    New->setInvalidDecl();
2170  }
2171
2172  mergeDeclAttributes(New, Old, Context);
2173  // Warn if an already-declared variable is made a weak_import in a subsequent
2174  // declaration
2175  if (New->getAttr<WeakImportAttr>() &&
2176      Old->getStorageClass() == SC_None &&
2177      !Old->getAttr<WeakImportAttr>()) {
2178    Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
2179    Diag(Old->getLocation(), diag::note_previous_definition);
2180    // Remove weak_import attribute on new declaration.
2181    New->dropAttr<WeakImportAttr>();
2182  }
2183
2184  // Merge the types.
2185  MergeVarDeclTypes(New, Old);
2186  if (New->isInvalidDecl())
2187    return;
2188
2189  // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
2190  if (New->getStorageClass() == SC_Static &&
2191      (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) {
2192    Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
2193    Diag(Old->getLocation(), diag::note_previous_definition);
2194    return New->setInvalidDecl();
2195  }
2196  // C99 6.2.2p4:
2197  //   For an identifier declared with the storage-class specifier
2198  //   extern in a scope in which a prior declaration of that
2199  //   identifier is visible,23) if the prior declaration specifies
2200  //   internal or external linkage, the linkage of the identifier at
2201  //   the later declaration is the same as the linkage specified at
2202  //   the prior declaration. If no prior declaration is visible, or
2203  //   if the prior declaration specifies no linkage, then the
2204  //   identifier has external linkage.
2205  if (New->hasExternalStorage() && Old->hasLinkage())
2206    /* Okay */;
2207  else if (New->getStorageClass() != SC_Static &&
2208           Old->getStorageClass() == SC_Static) {
2209    Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
2210    Diag(Old->getLocation(), diag::note_previous_definition);
2211    return New->setInvalidDecl();
2212  }
2213
2214  // Check if extern is followed by non-extern and vice-versa.
2215  if (New->hasExternalStorage() &&
2216      !Old->hasLinkage() && Old->isLocalVarDecl()) {
2217    Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
2218    Diag(Old->getLocation(), diag::note_previous_definition);
2219    return New->setInvalidDecl();
2220  }
2221  if (Old->hasExternalStorage() &&
2222      !New->hasLinkage() && New->isLocalVarDecl()) {
2223    Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
2224    Diag(Old->getLocation(), diag::note_previous_definition);
2225    return New->setInvalidDecl();
2226  }
2227
2228  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
2229
2230  // FIXME: The test for external storage here seems wrong? We still
2231  // need to check for mismatches.
2232  if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
2233      // Don't complain about out-of-line definitions of static members.
2234      !(Old->getLexicalDeclContext()->isRecord() &&
2235        !New->getLexicalDeclContext()->isRecord())) {
2236    Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
2237    Diag(Old->getLocation(), diag::note_previous_definition);
2238    return New->setInvalidDecl();
2239  }
2240
2241  if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
2242    Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
2243    Diag(Old->getLocation(), diag::note_previous_definition);
2244  } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
2245    Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
2246    Diag(Old->getLocation(), diag::note_previous_definition);
2247  }
2248
2249  // C++ doesn't have tentative definitions, so go right ahead and check here.
2250  const VarDecl *Def;
2251  if (getLangOptions().CPlusPlus &&
2252      New->isThisDeclarationADefinition() == VarDecl::Definition &&
2253      (Def = Old->getDefinition())) {
2254    Diag(New->getLocation(), diag::err_redefinition)
2255      << New->getDeclName();
2256    Diag(Def->getLocation(), diag::note_previous_definition);
2257    New->setInvalidDecl();
2258    return;
2259  }
2260  // c99 6.2.2 P4.
2261  // For an identifier declared with the storage-class specifier extern in a
2262  // scope in which a prior declaration of that identifier is visible, if
2263  // the prior declaration specifies internal or external linkage, the linkage
2264  // of the identifier at the later declaration is the same as the linkage
2265  // specified at the prior declaration.
2266  // FIXME. revisit this code.
2267  if (New->hasExternalStorage() &&
2268      Old->getLinkage() == InternalLinkage &&
2269      New->getDeclContext() == Old->getDeclContext())
2270    New->setStorageClass(Old->getStorageClass());
2271
2272  // Keep a chain of previous declarations.
2273  New->setPreviousDeclaration(Old);
2274
2275  // Inherit access appropriately.
2276  New->setAccess(Old->getAccess());
2277}
2278
2279/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2280/// no declarator (e.g. "struct foo;") is parsed.
2281Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
2282                                       DeclSpec &DS) {
2283  return ParsedFreeStandingDeclSpec(S, AS, DS,
2284                                    MultiTemplateParamsArg(*this, 0, 0));
2285}
2286
2287/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2288/// no declarator (e.g. "struct foo;") is parsed. It also accopts template
2289/// parameters to cope with template friend declarations.
2290Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
2291                                       DeclSpec &DS,
2292                                       MultiTemplateParamsArg TemplateParams) {
2293  Decl *TagD = 0;
2294  TagDecl *Tag = 0;
2295  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
2296      DS.getTypeSpecType() == DeclSpec::TST_struct ||
2297      DS.getTypeSpecType() == DeclSpec::TST_union ||
2298      DS.getTypeSpecType() == DeclSpec::TST_enum) {
2299    TagD = DS.getRepAsDecl();
2300
2301    if (!TagD) // We probably had an error
2302      return 0;
2303
2304    // Note that the above type specs guarantee that the
2305    // type rep is a Decl, whereas in many of the others
2306    // it's a Type.
2307    if (isa<TagDecl>(TagD))
2308      Tag = cast<TagDecl>(TagD);
2309    else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
2310      Tag = CTD->getTemplatedDecl();
2311  }
2312
2313  if (Tag)
2314    Tag->setFreeStanding();
2315
2316  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
2317    // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
2318    // or incomplete types shall not be restrict-qualified."
2319    if (TypeQuals & DeclSpec::TQ_restrict)
2320      Diag(DS.getRestrictSpecLoc(),
2321           diag::err_typecheck_invalid_restrict_not_pointer_noarg)
2322           << DS.getSourceRange();
2323  }
2324
2325  if (DS.isConstexprSpecified()) {
2326    // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
2327    // and definitions of functions and variables.
2328    if (Tag)
2329      Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
2330        << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
2331            DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
2332            DS.getTypeSpecType() == DeclSpec::TST_union ? 2 : 3);
2333    else
2334      Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
2335    // Don't emit warnings after this error.
2336    return TagD;
2337  }
2338
2339  if (DS.isFriendSpecified()) {
2340    // If we're dealing with a decl but not a TagDecl, assume that
2341    // whatever routines created it handled the friendship aspect.
2342    if (TagD && !Tag)
2343      return 0;
2344    return ActOnFriendTypeDecl(S, DS, TemplateParams);
2345  }
2346
2347  // Track whether we warned about the fact that there aren't any
2348  // declarators.
2349  bool emittedWarning = false;
2350
2351  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
2352    if (!Record->getDeclName() && Record->isCompleteDefinition() &&
2353        DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
2354      if (getLangOptions().CPlusPlus ||
2355          Record->getDeclContext()->isRecord())
2356        return BuildAnonymousStructOrUnion(S, DS, AS, Record);
2357
2358      Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
2359        << DS.getSourceRange();
2360      emittedWarning = true;
2361    }
2362  }
2363
2364  // Check for Microsoft C extension: anonymous struct.
2365  if (getLangOptions().MicrosoftExt && !getLangOptions().CPlusPlus &&
2366      CurContext->isRecord() &&
2367      DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
2368    // Handle 2 kinds of anonymous struct:
2369    //   struct STRUCT;
2370    // and
2371    //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
2372    RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
2373    if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
2374        (DS.getTypeSpecType() == DeclSpec::TST_typename &&
2375         DS.getRepAsType().get()->isStructureType())) {
2376      Diag(DS.getSourceRange().getBegin(), diag::ext_ms_anonymous_struct)
2377        << DS.getSourceRange();
2378      return BuildMicrosoftCAnonymousStruct(S, DS, Record);
2379    }
2380  }
2381
2382  if (getLangOptions().CPlusPlus &&
2383      DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
2384    if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
2385      if (Enum->enumerator_begin() == Enum->enumerator_end() &&
2386          !Enum->getIdentifier() && !Enum->isInvalidDecl()) {
2387        Diag(Enum->getLocation(), diag::ext_no_declarators)
2388          << DS.getSourceRange();
2389        emittedWarning = true;
2390      }
2391
2392  // Skip all the checks below if we have a type error.
2393  if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD;
2394
2395  if (!DS.isMissingDeclaratorOk()) {
2396    // Warn about typedefs of enums without names, since this is an
2397    // extension in both Microsoft and GNU.
2398    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
2399        Tag && isa<EnumDecl>(Tag)) {
2400      Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
2401        << DS.getSourceRange();
2402      return Tag;
2403    }
2404
2405    Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
2406      << DS.getSourceRange();
2407    emittedWarning = true;
2408  }
2409
2410  // We're going to complain about a bunch of spurious specifiers;
2411  // only do this if we're declaring a tag, because otherwise we
2412  // should be getting diag::ext_no_declarators.
2413  if (emittedWarning || (TagD && TagD->isInvalidDecl()))
2414    return TagD;
2415
2416  // Note that a linkage-specification sets a storage class, but
2417  // 'extern "C" struct foo;' is actually valid and not theoretically
2418  // useless.
2419  if (DeclSpec::SCS scs = DS.getStorageClassSpec())
2420    if (!DS.isExternInLinkageSpec())
2421      Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier)
2422        << DeclSpec::getSpecifierName(scs);
2423
2424  if (DS.isThreadSpecified())
2425    Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread";
2426  if (DS.getTypeQualifiers()) {
2427    if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2428      Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const";
2429    if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2430      Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile";
2431    // Restrict is covered above.
2432  }
2433  if (DS.isInlineSpecified())
2434    Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline";
2435  if (DS.isVirtualSpecified())
2436    Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual";
2437  if (DS.isExplicitSpecified())
2438    Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit";
2439
2440  if (DS.isModulePrivateSpecified() &&
2441      Tag && Tag->getDeclContext()->isFunctionOrMethod())
2442    Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
2443      << Tag->getTagKind()
2444      << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
2445
2446  // Warn about ignored type attributes, for example:
2447  // __attribute__((aligned)) struct A;
2448  // Attributes should be placed after tag to apply to type declaration.
2449  if (!DS.getAttributes().empty()) {
2450    DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
2451    if (TypeSpecType == DeclSpec::TST_class ||
2452        TypeSpecType == DeclSpec::TST_struct ||
2453        TypeSpecType == DeclSpec::TST_union ||
2454        TypeSpecType == DeclSpec::TST_enum) {
2455      AttributeList* attrs = DS.getAttributes().getList();
2456      while (attrs) {
2457        Diag(attrs->getScopeLoc(),
2458             diag::warn_declspec_attribute_ignored)
2459        << attrs->getName()
2460        << (TypeSpecType == DeclSpec::TST_class ? 0 :
2461            TypeSpecType == DeclSpec::TST_struct ? 1 :
2462            TypeSpecType == DeclSpec::TST_union ? 2 : 3);
2463        attrs = attrs->getNext();
2464      }
2465    }
2466  }
2467
2468  return TagD;
2469}
2470
2471/// ActOnVlaStmt - This rouine if finds a vla expression in a decl spec.
2472/// builds a statement for it and returns it so it is evaluated.
2473StmtResult Sema::ActOnVlaStmt(const DeclSpec &DS) {
2474  StmtResult R;
2475  if (DS.getTypeSpecType() == DeclSpec::TST_typeofExpr) {
2476    Expr *Exp = DS.getRepAsExpr();
2477    QualType Ty = Exp->getType();
2478    if (Ty->isPointerType()) {
2479      do
2480        Ty = Ty->getAs<PointerType>()->getPointeeType();
2481      while (Ty->isPointerType());
2482    }
2483    if (Ty->isVariableArrayType()) {
2484      R = ActOnExprStmt(MakeFullExpr(Exp));
2485    }
2486  }
2487  return R;
2488}
2489
2490/// We are trying to inject an anonymous member into the given scope;
2491/// check if there's an existing declaration that can't be overloaded.
2492///
2493/// \return true if this is a forbidden redeclaration
2494static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
2495                                         Scope *S,
2496                                         DeclContext *Owner,
2497                                         DeclarationName Name,
2498                                         SourceLocation NameLoc,
2499                                         unsigned diagnostic) {
2500  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
2501                 Sema::ForRedeclaration);
2502  if (!SemaRef.LookupName(R, S)) return false;
2503
2504  if (R.getAsSingle<TagDecl>())
2505    return false;
2506
2507  // Pick a representative declaration.
2508  NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
2509  assert(PrevDecl && "Expected a non-null Decl");
2510
2511  if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
2512    return false;
2513
2514  SemaRef.Diag(NameLoc, diagnostic) << Name;
2515  SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
2516
2517  return true;
2518}
2519
2520/// InjectAnonymousStructOrUnionMembers - Inject the members of the
2521/// anonymous struct or union AnonRecord into the owning context Owner
2522/// and scope S. This routine will be invoked just after we realize
2523/// that an unnamed union or struct is actually an anonymous union or
2524/// struct, e.g.,
2525///
2526/// @code
2527/// union {
2528///   int i;
2529///   float f;
2530/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
2531///    // f into the surrounding scope.x
2532/// @endcode
2533///
2534/// This routine is recursive, injecting the names of nested anonymous
2535/// structs/unions into the owning context and scope as well.
2536static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
2537                                                DeclContext *Owner,
2538                                                RecordDecl *AnonRecord,
2539                                                AccessSpecifier AS,
2540                              SmallVector<NamedDecl*, 2> &Chaining,
2541                                                      bool MSAnonStruct) {
2542  unsigned diagKind
2543    = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
2544                            : diag::err_anonymous_struct_member_redecl;
2545
2546  bool Invalid = false;
2547
2548  // Look every FieldDecl and IndirectFieldDecl with a name.
2549  for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
2550                               DEnd = AnonRecord->decls_end();
2551       D != DEnd; ++D) {
2552    if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
2553        cast<NamedDecl>(*D)->getDeclName()) {
2554      ValueDecl *VD = cast<ValueDecl>(*D);
2555      if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
2556                                       VD->getLocation(), diagKind)) {
2557        // C++ [class.union]p2:
2558        //   The names of the members of an anonymous union shall be
2559        //   distinct from the names of any other entity in the
2560        //   scope in which the anonymous union is declared.
2561        Invalid = true;
2562      } else {
2563        // C++ [class.union]p2:
2564        //   For the purpose of name lookup, after the anonymous union
2565        //   definition, the members of the anonymous union are
2566        //   considered to have been defined in the scope in which the
2567        //   anonymous union is declared.
2568        unsigned OldChainingSize = Chaining.size();
2569        if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
2570          for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
2571               PE = IF->chain_end(); PI != PE; ++PI)
2572            Chaining.push_back(*PI);
2573        else
2574          Chaining.push_back(VD);
2575
2576        assert(Chaining.size() >= 2);
2577        NamedDecl **NamedChain =
2578          new (SemaRef.Context)NamedDecl*[Chaining.size()];
2579        for (unsigned i = 0; i < Chaining.size(); i++)
2580          NamedChain[i] = Chaining[i];
2581
2582        IndirectFieldDecl* IndirectField =
2583          IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
2584                                    VD->getIdentifier(), VD->getType(),
2585                                    NamedChain, Chaining.size());
2586
2587        IndirectField->setAccess(AS);
2588        IndirectField->setImplicit();
2589        SemaRef.PushOnScopeChains(IndirectField, S);
2590
2591        // That includes picking up the appropriate access specifier.
2592        if (AS != AS_none) IndirectField->setAccess(AS);
2593
2594        Chaining.resize(OldChainingSize);
2595      }
2596    }
2597  }
2598
2599  return Invalid;
2600}
2601
2602/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
2603/// a VarDecl::StorageClass. Any error reporting is up to the caller:
2604/// illegal input values are mapped to SC_None.
2605static StorageClass
2606StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
2607  switch (StorageClassSpec) {
2608  case DeclSpec::SCS_unspecified:    return SC_None;
2609  case DeclSpec::SCS_extern:         return SC_Extern;
2610  case DeclSpec::SCS_static:         return SC_Static;
2611  case DeclSpec::SCS_auto:           return SC_Auto;
2612  case DeclSpec::SCS_register:       return SC_Register;
2613  case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
2614    // Illegal SCSs map to None: error reporting is up to the caller.
2615  case DeclSpec::SCS_mutable:        // Fall through.
2616  case DeclSpec::SCS_typedef:        return SC_None;
2617  }
2618  llvm_unreachable("unknown storage class specifier");
2619}
2620
2621/// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
2622/// a StorageClass. Any error reporting is up to the caller:
2623/// illegal input values are mapped to SC_None.
2624static StorageClass
2625StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
2626  switch (StorageClassSpec) {
2627  case DeclSpec::SCS_unspecified:    return SC_None;
2628  case DeclSpec::SCS_extern:         return SC_Extern;
2629  case DeclSpec::SCS_static:         return SC_Static;
2630  case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
2631    // Illegal SCSs map to None: error reporting is up to the caller.
2632  case DeclSpec::SCS_auto:           // Fall through.
2633  case DeclSpec::SCS_mutable:        // Fall through.
2634  case DeclSpec::SCS_register:       // Fall through.
2635  case DeclSpec::SCS_typedef:        return SC_None;
2636  }
2637  llvm_unreachable("unknown storage class specifier");
2638}
2639
2640/// BuildAnonymousStructOrUnion - Handle the declaration of an
2641/// anonymous structure or union. Anonymous unions are a C++ feature
2642/// (C++ [class.union]) and a GNU C extension; anonymous structures
2643/// are a GNU C and GNU C++ extension.
2644Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2645                                             AccessSpecifier AS,
2646                                             RecordDecl *Record) {
2647  DeclContext *Owner = Record->getDeclContext();
2648
2649  // Diagnose whether this anonymous struct/union is an extension.
2650  if (Record->isUnion() && !getLangOptions().CPlusPlus)
2651    Diag(Record->getLocation(), diag::ext_anonymous_union);
2652  else if (!Record->isUnion())
2653    Diag(Record->getLocation(), diag::ext_anonymous_struct);
2654
2655  // C and C++ require different kinds of checks for anonymous
2656  // structs/unions.
2657  bool Invalid = false;
2658  if (getLangOptions().CPlusPlus) {
2659    const char* PrevSpec = 0;
2660    unsigned DiagID;
2661    if (Record->isUnion()) {
2662      // C++ [class.union]p6:
2663      //   Anonymous unions declared in a named namespace or in the
2664      //   global namespace shall be declared static.
2665      if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
2666          (isa<TranslationUnitDecl>(Owner) ||
2667           (isa<NamespaceDecl>(Owner) &&
2668            cast<NamespaceDecl>(Owner)->getDeclName()))) {
2669        Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
2670          << FixItHint::CreateInsertion(Record->getLocation(), "static ");
2671
2672        // Recover by adding 'static'.
2673        DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
2674                               PrevSpec, DiagID);
2675      }
2676      // C++ [class.union]p6:
2677      //   A storage class is not allowed in a declaration of an
2678      //   anonymous union in a class scope.
2679      else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
2680               isa<RecordDecl>(Owner)) {
2681        Diag(DS.getStorageClassSpecLoc(),
2682             diag::err_anonymous_union_with_storage_spec)
2683          << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
2684
2685        // Recover by removing the storage specifier.
2686        DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
2687                               SourceLocation(),
2688                               PrevSpec, DiagID);
2689      }
2690    }
2691
2692    // Ignore const/volatile/restrict qualifiers.
2693    if (DS.getTypeQualifiers()) {
2694      if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2695        Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
2696          << Record->isUnion() << 0
2697          << FixItHint::CreateRemoval(DS.getConstSpecLoc());
2698      if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2699        Diag(DS.getVolatileSpecLoc(),
2700             diag::ext_anonymous_struct_union_qualified)
2701          << Record->isUnion() << 1
2702          << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
2703      if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
2704        Diag(DS.getRestrictSpecLoc(),
2705             diag::ext_anonymous_struct_union_qualified)
2706          << Record->isUnion() << 2
2707          << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
2708
2709      DS.ClearTypeQualifiers();
2710    }
2711
2712    // C++ [class.union]p2:
2713    //   The member-specification of an anonymous union shall only
2714    //   define non-static data members. [Note: nested types and
2715    //   functions cannot be declared within an anonymous union. ]
2716    for (DeclContext::decl_iterator Mem = Record->decls_begin(),
2717                                 MemEnd = Record->decls_end();
2718         Mem != MemEnd; ++Mem) {
2719      if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
2720        // C++ [class.union]p3:
2721        //   An anonymous union shall not have private or protected
2722        //   members (clause 11).
2723        assert(FD->getAccess() != AS_none);
2724        if (FD->getAccess() != AS_public) {
2725          Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
2726            << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
2727          Invalid = true;
2728        }
2729
2730        // C++ [class.union]p1
2731        //   An object of a class with a non-trivial constructor, a non-trivial
2732        //   copy constructor, a non-trivial destructor, or a non-trivial copy
2733        //   assignment operator cannot be a member of a union, nor can an
2734        //   array of such objects.
2735        if (CheckNontrivialField(FD))
2736          Invalid = true;
2737      } else if ((*Mem)->isImplicit()) {
2738        // Any implicit members are fine.
2739      } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
2740        // This is a type that showed up in an
2741        // elaborated-type-specifier inside the anonymous struct or
2742        // union, but which actually declares a type outside of the
2743        // anonymous struct or union. It's okay.
2744      } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
2745        if (!MemRecord->isAnonymousStructOrUnion() &&
2746            MemRecord->getDeclName()) {
2747          // Visual C++ allows type definition in anonymous struct or union.
2748          if (getLangOptions().MicrosoftExt)
2749            Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
2750              << (int)Record->isUnion();
2751          else {
2752            // This is a nested type declaration.
2753            Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
2754              << (int)Record->isUnion();
2755            Invalid = true;
2756          }
2757        }
2758      } else if (isa<AccessSpecDecl>(*Mem)) {
2759        // Any access specifier is fine.
2760      } else {
2761        // We have something that isn't a non-static data
2762        // member. Complain about it.
2763        unsigned DK = diag::err_anonymous_record_bad_member;
2764        if (isa<TypeDecl>(*Mem))
2765          DK = diag::err_anonymous_record_with_type;
2766        else if (isa<FunctionDecl>(*Mem))
2767          DK = diag::err_anonymous_record_with_function;
2768        else if (isa<VarDecl>(*Mem))
2769          DK = diag::err_anonymous_record_with_static;
2770
2771        // Visual C++ allows type definition in anonymous struct or union.
2772        if (getLangOptions().MicrosoftExt &&
2773            DK == diag::err_anonymous_record_with_type)
2774          Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
2775            << (int)Record->isUnion();
2776        else {
2777          Diag((*Mem)->getLocation(), DK)
2778              << (int)Record->isUnion();
2779          Invalid = true;
2780        }
2781      }
2782    }
2783  }
2784
2785  if (!Record->isUnion() && !Owner->isRecord()) {
2786    Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
2787      << (int)getLangOptions().CPlusPlus;
2788    Invalid = true;
2789  }
2790
2791  // Mock up a declarator.
2792  Declarator Dc(DS, Declarator::MemberContext);
2793  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
2794  assert(TInfo && "couldn't build declarator info for anonymous struct/union");
2795
2796  // Create a declaration for this anonymous struct/union.
2797  NamedDecl *Anon = 0;
2798  if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
2799    Anon = FieldDecl::Create(Context, OwningClass,
2800                             DS.getSourceRange().getBegin(),
2801                             Record->getLocation(),
2802                             /*IdentifierInfo=*/0,
2803                             Context.getTypeDeclType(Record),
2804                             TInfo,
2805                             /*BitWidth=*/0, /*Mutable=*/false,
2806                             /*HasInit=*/false);
2807    Anon->setAccess(AS);
2808    if (getLangOptions().CPlusPlus)
2809      FieldCollector->Add(cast<FieldDecl>(Anon));
2810  } else {
2811    DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
2812    assert(SCSpec != DeclSpec::SCS_typedef &&
2813           "Parser allowed 'typedef' as storage class VarDecl.");
2814    VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
2815    if (SCSpec == DeclSpec::SCS_mutable) {
2816      // mutable can only appear on non-static class members, so it's always
2817      // an error here
2818      Diag(Record->getLocation(), diag::err_mutable_nonmember);
2819      Invalid = true;
2820      SC = SC_None;
2821    }
2822    SCSpec = DS.getStorageClassSpecAsWritten();
2823    VarDecl::StorageClass SCAsWritten
2824      = StorageClassSpecToVarDeclStorageClass(SCSpec);
2825
2826    Anon = VarDecl::Create(Context, Owner,
2827                           DS.getSourceRange().getBegin(),
2828                           Record->getLocation(), /*IdentifierInfo=*/0,
2829                           Context.getTypeDeclType(Record),
2830                           TInfo, SC, SCAsWritten);
2831
2832    // Default-initialize the implicit variable. This initialization will be
2833    // trivial in almost all cases, except if a union member has an in-class
2834    // initializer:
2835    //   union { int n = 0; };
2836    ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
2837  }
2838  Anon->setImplicit();
2839
2840  // Add the anonymous struct/union object to the current
2841  // context. We'll be referencing this object when we refer to one of
2842  // its members.
2843  Owner->addDecl(Anon);
2844
2845  // Inject the members of the anonymous struct/union into the owning
2846  // context and into the identifier resolver chain for name lookup
2847  // purposes.
2848  SmallVector<NamedDecl*, 2> Chain;
2849  Chain.push_back(Anon);
2850
2851  if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
2852                                          Chain, false))
2853    Invalid = true;
2854
2855  // Mark this as an anonymous struct/union type. Note that we do not
2856  // do this until after we have already checked and injected the
2857  // members of this anonymous struct/union type, because otherwise
2858  // the members could be injected twice: once by DeclContext when it
2859  // builds its lookup table, and once by
2860  // InjectAnonymousStructOrUnionMembers.
2861  Record->setAnonymousStructOrUnion(true);
2862
2863  if (Invalid)
2864    Anon->setInvalidDecl();
2865
2866  return Anon;
2867}
2868
2869/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
2870/// Microsoft C anonymous structure.
2871/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
2872/// Example:
2873///
2874/// struct A { int a; };
2875/// struct B { struct A; int b; };
2876///
2877/// void foo() {
2878///   B var;
2879///   var.a = 3;
2880/// }
2881///
2882Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2883                                           RecordDecl *Record) {
2884
2885  // If there is no Record, get the record via the typedef.
2886  if (!Record)
2887    Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
2888
2889  // Mock up a declarator.
2890  Declarator Dc(DS, Declarator::TypeNameContext);
2891  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
2892  assert(TInfo && "couldn't build declarator info for anonymous struct");
2893
2894  // Create a declaration for this anonymous struct.
2895  NamedDecl* Anon = FieldDecl::Create(Context,
2896                             cast<RecordDecl>(CurContext),
2897                             DS.getSourceRange().getBegin(),
2898                             DS.getSourceRange().getBegin(),
2899                             /*IdentifierInfo=*/0,
2900                             Context.getTypeDeclType(Record),
2901                             TInfo,
2902                             /*BitWidth=*/0, /*Mutable=*/false,
2903                             /*HasInit=*/false);
2904  Anon->setImplicit();
2905
2906  // Add the anonymous struct object to the current context.
2907  CurContext->addDecl(Anon);
2908
2909  // Inject the members of the anonymous struct into the current
2910  // context and into the identifier resolver chain for name lookup
2911  // purposes.
2912  SmallVector<NamedDecl*, 2> Chain;
2913  Chain.push_back(Anon);
2914
2915  if (InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
2916                                          Record->getDefinition(),
2917                                          AS_none, Chain, true))
2918    Anon->setInvalidDecl();
2919
2920  return Anon;
2921}
2922
2923/// GetNameForDeclarator - Determine the full declaration name for the
2924/// given Declarator.
2925DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
2926  return GetNameFromUnqualifiedId(D.getName());
2927}
2928
2929/// \brief Retrieves the declaration name from a parsed unqualified-id.
2930DeclarationNameInfo
2931Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
2932  DeclarationNameInfo NameInfo;
2933  NameInfo.setLoc(Name.StartLocation);
2934
2935  switch (Name.getKind()) {
2936
2937  case UnqualifiedId::IK_ImplicitSelfParam:
2938  case UnqualifiedId::IK_Identifier:
2939    NameInfo.setName(Name.Identifier);
2940    NameInfo.setLoc(Name.StartLocation);
2941    return NameInfo;
2942
2943  case UnqualifiedId::IK_OperatorFunctionId:
2944    NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
2945                                           Name.OperatorFunctionId.Operator));
2946    NameInfo.setLoc(Name.StartLocation);
2947    NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
2948      = Name.OperatorFunctionId.SymbolLocations[0];
2949    NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
2950      = Name.EndLocation.getRawEncoding();
2951    return NameInfo;
2952
2953  case UnqualifiedId::IK_LiteralOperatorId:
2954    NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
2955                                                           Name.Identifier));
2956    NameInfo.setLoc(Name.StartLocation);
2957    NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
2958    return NameInfo;
2959
2960  case UnqualifiedId::IK_ConversionFunctionId: {
2961    TypeSourceInfo *TInfo;
2962    QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
2963    if (Ty.isNull())
2964      return DeclarationNameInfo();
2965    NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
2966                                               Context.getCanonicalType(Ty)));
2967    NameInfo.setLoc(Name.StartLocation);
2968    NameInfo.setNamedTypeInfo(TInfo);
2969    return NameInfo;
2970  }
2971
2972  case UnqualifiedId::IK_ConstructorName: {
2973    TypeSourceInfo *TInfo;
2974    QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
2975    if (Ty.isNull())
2976      return DeclarationNameInfo();
2977    NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
2978                                              Context.getCanonicalType(Ty)));
2979    NameInfo.setLoc(Name.StartLocation);
2980    NameInfo.setNamedTypeInfo(TInfo);
2981    return NameInfo;
2982  }
2983
2984  case UnqualifiedId::IK_ConstructorTemplateId: {
2985    // In well-formed code, we can only have a constructor
2986    // template-id that refers to the current context, so go there
2987    // to find the actual type being constructed.
2988    CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
2989    if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
2990      return DeclarationNameInfo();
2991
2992    // Determine the type of the class being constructed.
2993    QualType CurClassType = Context.getTypeDeclType(CurClass);
2994
2995    // FIXME: Check two things: that the template-id names the same type as
2996    // CurClassType, and that the template-id does not occur when the name
2997    // was qualified.
2998
2999    NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3000                                    Context.getCanonicalType(CurClassType)));
3001    NameInfo.setLoc(Name.StartLocation);
3002    // FIXME: should we retrieve TypeSourceInfo?
3003    NameInfo.setNamedTypeInfo(0);
3004    return NameInfo;
3005  }
3006
3007  case UnqualifiedId::IK_DestructorName: {
3008    TypeSourceInfo *TInfo;
3009    QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3010    if (Ty.isNull())
3011      return DeclarationNameInfo();
3012    NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3013                                              Context.getCanonicalType(Ty)));
3014    NameInfo.setLoc(Name.StartLocation);
3015    NameInfo.setNamedTypeInfo(TInfo);
3016    return NameInfo;
3017  }
3018
3019  case UnqualifiedId::IK_TemplateId: {
3020    TemplateName TName = Name.TemplateId->Template.get();
3021    SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3022    return Context.getNameForTemplate(TName, TNameLoc);
3023  }
3024
3025  } // switch (Name.getKind())
3026
3027  llvm_unreachable("Unknown name kind");
3028}
3029
3030static QualType getCoreType(QualType Ty) {
3031  do {
3032    if (Ty->isPointerType() || Ty->isReferenceType())
3033      Ty = Ty->getPointeeType();
3034    else if (Ty->isArrayType())
3035      Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3036    else
3037      return Ty.withoutLocalFastQualifiers();
3038  } while (true);
3039}
3040
3041/// hasSimilarParameters - Determine whether the C++ functions Declaration
3042/// and Definition have "nearly" matching parameters. This heuristic is
3043/// used to improve diagnostics in the case where an out-of-line function
3044/// definition doesn't match any declaration within the class or namespace.
3045/// Also sets Params to the list of indices to the parameters that differ
3046/// between the declaration and the definition. If hasSimilarParameters
3047/// returns true and Params is empty, then all of the parameters match.
3048static bool hasSimilarParameters(ASTContext &Context,
3049                                     FunctionDecl *Declaration,
3050                                     FunctionDecl *Definition,
3051                                     llvm::SmallVectorImpl<unsigned> &Params) {
3052  Params.clear();
3053  if (Declaration->param_size() != Definition->param_size())
3054    return false;
3055  for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3056    QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3057    QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3058
3059    // The parameter types are identical
3060    if (Context.hasSameType(DefParamTy, DeclParamTy))
3061      continue;
3062
3063    QualType DeclParamBaseTy = getCoreType(DeclParamTy);
3064    QualType DefParamBaseTy = getCoreType(DefParamTy);
3065    const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
3066    const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
3067
3068    if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
3069        (DeclTyName && DeclTyName == DefTyName))
3070      Params.push_back(Idx);
3071    else  // The two parameters aren't even close
3072      return false;
3073  }
3074
3075  return true;
3076}
3077
3078/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
3079/// declarator needs to be rebuilt in the current instantiation.
3080/// Any bits of declarator which appear before the name are valid for
3081/// consideration here.  That's specifically the type in the decl spec
3082/// and the base type in any member-pointer chunks.
3083static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
3084                                                    DeclarationName Name) {
3085  // The types we specifically need to rebuild are:
3086  //   - typenames, typeofs, and decltypes
3087  //   - types which will become injected class names
3088  // Of course, we also need to rebuild any type referencing such a
3089  // type.  It's safest to just say "dependent", but we call out a
3090  // few cases here.
3091
3092  DeclSpec &DS = D.getMutableDeclSpec();
3093  switch (DS.getTypeSpecType()) {
3094  case DeclSpec::TST_typename:
3095  case DeclSpec::TST_typeofType:
3096  case DeclSpec::TST_decltype:
3097  case DeclSpec::TST_underlyingType:
3098  case DeclSpec::TST_atomic: {
3099    // Grab the type from the parser.
3100    TypeSourceInfo *TSI = 0;
3101    QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
3102    if (T.isNull() || !T->isDependentType()) break;
3103
3104    // Make sure there's a type source info.  This isn't really much
3105    // of a waste; most dependent types should have type source info
3106    // attached already.
3107    if (!TSI)
3108      TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
3109
3110    // Rebuild the type in the current instantiation.
3111    TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
3112    if (!TSI) return true;
3113
3114    // Store the new type back in the decl spec.
3115    ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
3116    DS.UpdateTypeRep(LocType);
3117    break;
3118  }
3119
3120  case DeclSpec::TST_typeofExpr: {
3121    Expr *E = DS.getRepAsExpr();
3122    ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
3123    if (Result.isInvalid()) return true;
3124    DS.UpdateExprRep(Result.get());
3125    break;
3126  }
3127
3128  default:
3129    // Nothing to do for these decl specs.
3130    break;
3131  }
3132
3133  // It doesn't matter what order we do this in.
3134  for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3135    DeclaratorChunk &Chunk = D.getTypeObject(I);
3136
3137    // The only type information in the declarator which can come
3138    // before the declaration name is the base type of a member
3139    // pointer.
3140    if (Chunk.Kind != DeclaratorChunk::MemberPointer)
3141      continue;
3142
3143    // Rebuild the scope specifier in-place.
3144    CXXScopeSpec &SS = Chunk.Mem.Scope();
3145    if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
3146      return true;
3147  }
3148
3149  return false;
3150}
3151
3152Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
3153  D.setFunctionDefinitionKind(FDK_Declaration);
3154  Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg(*this));
3155
3156  if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
3157      Dcl->getDeclContext()->isFileContext())
3158    Dcl->setTopLevelDeclInObjCContainer();
3159
3160  return Dcl;
3161}
3162
3163/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
3164///   If T is the name of a class, then each of the following shall have a
3165///   name different from T:
3166///     - every static data member of class T;
3167///     - every member function of class T
3168///     - every member of class T that is itself a type;
3169/// \returns true if the declaration name violates these rules.
3170bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
3171                                   DeclarationNameInfo NameInfo) {
3172  DeclarationName Name = NameInfo.getName();
3173
3174  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
3175    if (Record->getIdentifier() && Record->getDeclName() == Name) {
3176      Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
3177      return true;
3178    }
3179
3180  return false;
3181}
3182
3183Decl *Sema::HandleDeclarator(Scope *S, Declarator &D,
3184                             MultiTemplateParamsArg TemplateParamLists) {
3185  // TODO: consider using NameInfo for diagnostic.
3186  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3187  DeclarationName Name = NameInfo.getName();
3188
3189  // All of these full declarators require an identifier.  If it doesn't have
3190  // one, the ParsedFreeStandingDeclSpec action should be used.
3191  if (!Name) {
3192    if (!D.isInvalidType())  // Reject this if we think it is valid.
3193      Diag(D.getDeclSpec().getSourceRange().getBegin(),
3194           diag::err_declarator_need_ident)
3195        << D.getDeclSpec().getSourceRange() << D.getSourceRange();
3196    return 0;
3197  } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
3198    return 0;
3199
3200  // The scope passed in may not be a decl scope.  Zip up the scope tree until
3201  // we find one that is.
3202  while ((S->getFlags() & Scope::DeclScope) == 0 ||
3203         (S->getFlags() & Scope::TemplateParamScope) != 0)
3204    S = S->getParent();
3205
3206  DeclContext *DC = CurContext;
3207  if (D.getCXXScopeSpec().isInvalid())
3208    D.setInvalidType();
3209  else if (D.getCXXScopeSpec().isSet()) {
3210    if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
3211                                        UPPC_DeclarationQualifier))
3212      return 0;
3213
3214    bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
3215    DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
3216    if (!DC) {
3217      // If we could not compute the declaration context, it's because the
3218      // declaration context is dependent but does not refer to a class,
3219      // class template, or class template partial specialization. Complain
3220      // and return early, to avoid the coming semantic disaster.
3221      Diag(D.getIdentifierLoc(),
3222           diag::err_template_qualified_declarator_no_match)
3223        << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
3224        << D.getCXXScopeSpec().getRange();
3225      return 0;
3226    }
3227    bool IsDependentContext = DC->isDependentContext();
3228
3229    if (!IsDependentContext &&
3230        RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
3231      return 0;
3232
3233    if (isa<CXXRecordDecl>(DC)) {
3234      if (!cast<CXXRecordDecl>(DC)->hasDefinition()) {
3235        Diag(D.getIdentifierLoc(),
3236             diag::err_member_def_undefined_record)
3237          << Name << DC << D.getCXXScopeSpec().getRange();
3238        D.setInvalidType();
3239      } else if (isa<CXXRecordDecl>(CurContext) &&
3240                 !D.getDeclSpec().isFriendSpecified()) {
3241        // The user provided a superfluous scope specifier inside a class
3242        // definition:
3243        //
3244        // class X {
3245        //   void X::f();
3246        // };
3247        if (CurContext->Equals(DC)) {
3248          Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
3249            << Name << FixItHint::CreateRemoval(D.getCXXScopeSpec().getRange());
3250        } else {
3251          Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3252            << Name << D.getCXXScopeSpec().getRange();
3253
3254          // C++ constructors and destructors with incorrect scopes can break
3255          // our AST invariants by having the wrong underlying types. If
3256          // that's the case, then drop this declaration entirely.
3257          if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
3258               Name.getNameKind() == DeclarationName::CXXDestructorName) &&
3259              !Context.hasSameType(Name.getCXXNameType(),
3260                 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))))
3261            return 0;
3262        }
3263
3264        // Pretend that this qualifier was not here.
3265        D.getCXXScopeSpec().clear();
3266      }
3267    }
3268
3269    // Check whether we need to rebuild the type of the given
3270    // declaration in the current instantiation.
3271    if (EnteringContext && IsDependentContext &&
3272        TemplateParamLists.size() != 0) {
3273      ContextRAII SavedContext(*this, DC);
3274      if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
3275        D.setInvalidType();
3276    }
3277  }
3278
3279  if (DiagnoseClassNameShadow(DC, NameInfo))
3280    // If this is a typedef, we'll end up spewing multiple diagnostics.
3281    // Just return early; it's safer.
3282    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3283      return 0;
3284
3285  NamedDecl *New;
3286
3287  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3288  QualType R = TInfo->getType();
3289
3290  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
3291                                      UPPC_DeclarationType))
3292    D.setInvalidType();
3293
3294  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
3295                        ForRedeclaration);
3296
3297  // See if this is a redefinition of a variable in the same scope.
3298  if (!D.getCXXScopeSpec().isSet()) {
3299    bool IsLinkageLookup = false;
3300
3301    // If the declaration we're planning to build will be a function
3302    // or object with linkage, then look for another declaration with
3303    // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
3304    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3305      /* Do nothing*/;
3306    else if (R->isFunctionType()) {
3307      if (CurContext->isFunctionOrMethod() ||
3308          D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
3309        IsLinkageLookup = true;
3310    } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
3311      IsLinkageLookup = true;
3312    else if (CurContext->getRedeclContext()->isTranslationUnit() &&
3313             D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
3314      IsLinkageLookup = true;
3315
3316    if (IsLinkageLookup)
3317      Previous.clear(LookupRedeclarationWithLinkage);
3318
3319    LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
3320  } else { // Something like "int foo::x;"
3321    LookupQualifiedName(Previous, DC);
3322
3323    // Don't consider using declarations as previous declarations for
3324    // out-of-line members.
3325    RemoveUsingDecls(Previous);
3326
3327    // C++ 7.3.1.2p2:
3328    // Members (including explicit specializations of templates) of a named
3329    // namespace can also be defined outside that namespace by explicit
3330    // qualification of the name being defined, provided that the entity being
3331    // defined was already declared in the namespace and the definition appears
3332    // after the point of declaration in a namespace that encloses the
3333    // declarations namespace.
3334    //
3335    // Note that we only check the context at this point. We don't yet
3336    // have enough information to make sure that PrevDecl is actually
3337    // the declaration we want to match. For example, given:
3338    //
3339    //   class X {
3340    //     void f();
3341    //     void f(float);
3342    //   };
3343    //
3344    //   void X::f(int) { } // ill-formed
3345    //
3346    // In this case, PrevDecl will point to the overload set
3347    // containing the two f's declared in X, but neither of them
3348    // matches.
3349
3350    // First check whether we named the global scope.
3351    if (isa<TranslationUnitDecl>(DC)) {
3352      Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
3353        << Name << D.getCXXScopeSpec().getRange();
3354    } else {
3355      DeclContext *Cur = CurContext;
3356      while (isa<LinkageSpecDecl>(Cur))
3357        Cur = Cur->getParent();
3358      if (!Cur->Encloses(DC)) {
3359        // The qualifying scope doesn't enclose the original declaration.
3360        // Emit diagnostic based on current scope.
3361        SourceLocation L = D.getIdentifierLoc();
3362        SourceRange R = D.getCXXScopeSpec().getRange();
3363        if (isa<FunctionDecl>(Cur))
3364          Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
3365        else
3366          Diag(L, diag::err_invalid_declarator_scope)
3367            << Name << cast<NamedDecl>(DC) << R;
3368        D.setInvalidType();
3369      }
3370
3371      // C++11 8.3p1:
3372      // ... "The nested-name-specifier of the qualified declarator-id shall
3373      // not begin with a decltype-specifer"
3374      NestedNameSpecifierLoc SpecLoc =
3375            D.getCXXScopeSpec().getWithLocInContext(Context);
3376      assert(SpecLoc && "A non-empty CXXScopeSpec should have a non-empty "
3377                        "NestedNameSpecifierLoc");
3378      while (SpecLoc.getPrefix())
3379        SpecLoc = SpecLoc.getPrefix();
3380      if (dyn_cast_or_null<DecltypeType>(
3381            SpecLoc.getNestedNameSpecifier()->getAsType()))
3382        Diag(SpecLoc.getBeginLoc(), diag::err_decltype_in_declarator)
3383          << SpecLoc.getTypeLoc().getSourceRange();
3384    }
3385  }
3386
3387  if (Previous.isSingleResult() &&
3388      Previous.getFoundDecl()->isTemplateParameter()) {
3389    // Maybe we will complain about the shadowed template parameter.
3390    if (!D.isInvalidType())
3391      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
3392                                      Previous.getFoundDecl());
3393
3394    // Just pretend that we didn't see the previous declaration.
3395    Previous.clear();
3396  }
3397
3398  // In C++, the previous declaration we find might be a tag type
3399  // (class or enum). In this case, the new declaration will hide the
3400  // tag type. Note that this does does not apply if we're declaring a
3401  // typedef (C++ [dcl.typedef]p4).
3402  if (Previous.isSingleTagDecl() &&
3403      D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
3404    Previous.clear();
3405
3406  bool AddToScope = true;
3407  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
3408    if (TemplateParamLists.size()) {
3409      Diag(D.getIdentifierLoc(), diag::err_template_typedef);
3410      return 0;
3411    }
3412
3413    New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
3414  } else if (R->isFunctionType()) {
3415    New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
3416                                  move(TemplateParamLists),
3417                                  AddToScope);
3418  } else {
3419    New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
3420                                  move(TemplateParamLists));
3421  }
3422
3423  if (New == 0)
3424    return 0;
3425
3426  // If this has an identifier and is not an invalid redeclaration or
3427  // function template specialization, add it to the scope stack.
3428  if (New->getDeclName() && AddToScope &&
3429       !(D.isRedeclaration() && New->isInvalidDecl()))
3430    PushOnScopeChains(New, S);
3431
3432  return New;
3433}
3434
3435/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3436/// types into constant array types in certain situations which would otherwise
3437/// be errors (for GCC compatibility).
3438static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3439                                                    ASTContext &Context,
3440                                                    bool &SizeIsNegative,
3441                                                    llvm::APSInt &Oversized) {
3442  // This method tries to turn a variable array into a constant
3443  // array even when the size isn't an ICE.  This is necessary
3444  // for compatibility with code that depends on gcc's buggy
3445  // constant expression folding, like struct {char x[(int)(char*)2];}
3446  SizeIsNegative = false;
3447  Oversized = 0;
3448
3449  if (T->isDependentType())
3450    return QualType();
3451
3452  QualifierCollector Qs;
3453  const Type *Ty = Qs.strip(T);
3454
3455  if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
3456    QualType Pointee = PTy->getPointeeType();
3457    QualType FixedType =
3458        TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
3459                                            Oversized);
3460    if (FixedType.isNull()) return FixedType;
3461    FixedType = Context.getPointerType(FixedType);
3462    return Qs.apply(Context, FixedType);
3463  }
3464  if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
3465    QualType Inner = PTy->getInnerType();
3466    QualType FixedType =
3467        TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
3468                                            Oversized);
3469    if (FixedType.isNull()) return FixedType;
3470    FixedType = Context.getParenType(FixedType);
3471    return Qs.apply(Context, FixedType);
3472  }
3473
3474  const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3475  if (!VLATy)
3476    return QualType();
3477  // FIXME: We should probably handle this case
3478  if (VLATy->getElementType()->isVariablyModifiedType())
3479    return QualType();
3480
3481  llvm::APSInt Res;
3482  if (!VLATy->getSizeExpr() ||
3483      !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
3484    return QualType();
3485
3486  // Check whether the array size is negative.
3487  if (Res.isSigned() && Res.isNegative()) {
3488    SizeIsNegative = true;
3489    return QualType();
3490  }
3491
3492  // Check whether the array is too large to be addressed.
3493  unsigned ActiveSizeBits
3494    = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
3495                                              Res);
3496  if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
3497    Oversized = Res;
3498    return QualType();
3499  }
3500
3501  return Context.getConstantArrayType(VLATy->getElementType(),
3502                                      Res, ArrayType::Normal, 0);
3503}
3504
3505/// \brief Register the given locally-scoped external C declaration so
3506/// that it can be found later for redeclarations
3507void
3508Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
3509                                       const LookupResult &Previous,
3510                                       Scope *S) {
3511  assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
3512         "Decl is not a locally-scoped decl!");
3513  // Note that we have a locally-scoped external with this name.
3514  LocallyScopedExternalDecls[ND->getDeclName()] = ND;
3515
3516  if (!Previous.isSingleResult())
3517    return;
3518
3519  NamedDecl *PrevDecl = Previous.getFoundDecl();
3520
3521  // If there was a previous declaration of this variable, it may be
3522  // in our identifier chain. Update the identifier chain with the new
3523  // declaration.
3524  if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
3525    // The previous declaration was found on the identifer resolver
3526    // chain, so remove it from its scope.
3527
3528    if (S->isDeclScope(PrevDecl)) {
3529      // Special case for redeclarations in the SAME scope.
3530      // Because this declaration is going to be added to the identifier chain
3531      // later, we should temporarily take it OFF the chain.
3532      IdResolver.RemoveDecl(ND);
3533
3534    } else {
3535      // Find the scope for the original declaration.
3536      while (S && !S->isDeclScope(PrevDecl))
3537        S = S->getParent();
3538    }
3539
3540    if (S)
3541      S->RemoveDecl(PrevDecl);
3542  }
3543}
3544
3545llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
3546Sema::findLocallyScopedExternalDecl(DeclarationName Name) {
3547  if (ExternalSource) {
3548    // Load locally-scoped external decls from the external source.
3549    SmallVector<NamedDecl *, 4> Decls;
3550    ExternalSource->ReadLocallyScopedExternalDecls(Decls);
3551    for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
3552      llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
3553        = LocallyScopedExternalDecls.find(Decls[I]->getDeclName());
3554      if (Pos == LocallyScopedExternalDecls.end())
3555        LocallyScopedExternalDecls[Decls[I]->getDeclName()] = Decls[I];
3556    }
3557  }
3558
3559  return LocallyScopedExternalDecls.find(Name);
3560}
3561
3562/// \brief Diagnose function specifiers on a declaration of an identifier that
3563/// does not identify a function.
3564void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
3565  // FIXME: We should probably indicate the identifier in question to avoid
3566  // confusion for constructs like "inline int a(), b;"
3567  if (D.getDeclSpec().isInlineSpecified())
3568    Diag(D.getDeclSpec().getInlineSpecLoc(),
3569         diag::err_inline_non_function);
3570
3571  if (D.getDeclSpec().isVirtualSpecified())
3572    Diag(D.getDeclSpec().getVirtualSpecLoc(),
3573         diag::err_virtual_non_function);
3574
3575  if (D.getDeclSpec().isExplicitSpecified())
3576    Diag(D.getDeclSpec().getExplicitSpecLoc(),
3577         diag::err_explicit_non_function);
3578}
3579
3580NamedDecl*
3581Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
3582                             TypeSourceInfo *TInfo, LookupResult &Previous) {
3583  // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
3584  if (D.getCXXScopeSpec().isSet()) {
3585    Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
3586      << D.getCXXScopeSpec().getRange();
3587    D.setInvalidType();
3588    // Pretend we didn't see the scope specifier.
3589    DC = CurContext;
3590    Previous.clear();
3591  }
3592
3593  if (getLangOptions().CPlusPlus) {
3594    // Check that there are no default arguments (C++ only).
3595    CheckExtraCXXDefaultArguments(D);
3596  }
3597
3598  DiagnoseFunctionSpecifiers(D);
3599
3600  if (D.getDeclSpec().isThreadSpecified())
3601    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
3602  if (D.getDeclSpec().isConstexprSpecified())
3603    Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
3604      << 1;
3605
3606  if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
3607    Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
3608      << D.getName().getSourceRange();
3609    return 0;
3610  }
3611
3612  TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
3613  if (!NewTD) return 0;
3614
3615  // Handle attributes prior to checking for duplicates in MergeVarDecl
3616  ProcessDeclAttributes(S, NewTD, D);
3617
3618  CheckTypedefForVariablyModifiedType(S, NewTD);
3619
3620  bool Redeclaration = D.isRedeclaration();
3621  NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
3622  D.setRedeclaration(Redeclaration);
3623  return ND;
3624}
3625
3626void
3627Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
3628  // C99 6.7.7p2: If a typedef name specifies a variably modified type
3629  // then it shall have block scope.
3630  // Note that variably modified types must be fixed before merging the decl so
3631  // that redeclarations will match.
3632  QualType T = NewTD->getUnderlyingType();
3633  if (T->isVariablyModifiedType()) {
3634    getCurFunction()->setHasBranchProtectedScope();
3635
3636    if (S->getFnParent() == 0) {
3637      bool SizeIsNegative;
3638      llvm::APSInt Oversized;
3639      QualType FixedTy =
3640          TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
3641                                              Oversized);
3642      if (!FixedTy.isNull()) {
3643        Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
3644        NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
3645      } else {
3646        if (SizeIsNegative)
3647          Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
3648        else if (T->isVariableArrayType())
3649          Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
3650        else if (Oversized.getBoolValue())
3651          Diag(NewTD->getLocation(), diag::err_array_too_large)
3652            << Oversized.toString(10);
3653        else
3654          Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
3655        NewTD->setInvalidDecl();
3656      }
3657    }
3658  }
3659}
3660
3661
3662/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
3663/// declares a typedef-name, either using the 'typedef' type specifier or via
3664/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
3665NamedDecl*
3666Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
3667                           LookupResult &Previous, bool &Redeclaration) {
3668  // Merge the decl with the existing one if appropriate. If the decl is
3669  // in an outer scope, it isn't the same thing.
3670  FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
3671                       /*ExplicitInstantiationOrSpecialization=*/false);
3672  if (!Previous.empty()) {
3673    Redeclaration = true;
3674    MergeTypedefNameDecl(NewTD, Previous);
3675  }
3676
3677  // If this is the C FILE type, notify the AST context.
3678  if (IdentifierInfo *II = NewTD->getIdentifier())
3679    if (!NewTD->isInvalidDecl() &&
3680        NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
3681      if (II->isStr("FILE"))
3682        Context.setFILEDecl(NewTD);
3683      else if (II->isStr("jmp_buf"))
3684        Context.setjmp_bufDecl(NewTD);
3685      else if (II->isStr("sigjmp_buf"))
3686        Context.setsigjmp_bufDecl(NewTD);
3687      else if (II->isStr("ucontext_t"))
3688        Context.setucontext_tDecl(NewTD);
3689      else if (II->isStr("__builtin_va_list"))
3690        Context.setBuiltinVaListType(Context.getTypedefType(NewTD));
3691    }
3692
3693  return NewTD;
3694}
3695
3696/// \brief Determines whether the given declaration is an out-of-scope
3697/// previous declaration.
3698///
3699/// This routine should be invoked when name lookup has found a
3700/// previous declaration (PrevDecl) that is not in the scope where a
3701/// new declaration by the same name is being introduced. If the new
3702/// declaration occurs in a local scope, previous declarations with
3703/// linkage may still be considered previous declarations (C99
3704/// 6.2.2p4-5, C++ [basic.link]p6).
3705///
3706/// \param PrevDecl the previous declaration found by name
3707/// lookup
3708///
3709/// \param DC the context in which the new declaration is being
3710/// declared.
3711///
3712/// \returns true if PrevDecl is an out-of-scope previous declaration
3713/// for a new delcaration with the same name.
3714static bool
3715isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
3716                                ASTContext &Context) {
3717  if (!PrevDecl)
3718    return false;
3719
3720  if (!PrevDecl->hasLinkage())
3721    return false;
3722
3723  if (Context.getLangOptions().CPlusPlus) {
3724    // C++ [basic.link]p6:
3725    //   If there is a visible declaration of an entity with linkage
3726    //   having the same name and type, ignoring entities declared
3727    //   outside the innermost enclosing namespace scope, the block
3728    //   scope declaration declares that same entity and receives the
3729    //   linkage of the previous declaration.
3730    DeclContext *OuterContext = DC->getRedeclContext();
3731    if (!OuterContext->isFunctionOrMethod())
3732      // This rule only applies to block-scope declarations.
3733      return false;
3734
3735    DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
3736    if (PrevOuterContext->isRecord())
3737      // We found a member function: ignore it.
3738      return false;
3739
3740    // Find the innermost enclosing namespace for the new and
3741    // previous declarations.
3742    OuterContext = OuterContext->getEnclosingNamespaceContext();
3743    PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
3744
3745    // The previous declaration is in a different namespace, so it
3746    // isn't the same function.
3747    if (!OuterContext->Equals(PrevOuterContext))
3748      return false;
3749  }
3750
3751  return true;
3752}
3753
3754static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
3755  CXXScopeSpec &SS = D.getCXXScopeSpec();
3756  if (!SS.isSet()) return;
3757  DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
3758}
3759
3760bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
3761  QualType type = decl->getType();
3762  Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
3763  if (lifetime == Qualifiers::OCL_Autoreleasing) {
3764    // Various kinds of declaration aren't allowed to be __autoreleasing.
3765    unsigned kind = -1U;
3766    if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
3767      if (var->hasAttr<BlocksAttr>())
3768        kind = 0; // __block
3769      else if (!var->hasLocalStorage())
3770        kind = 1; // global
3771    } else if (isa<ObjCIvarDecl>(decl)) {
3772      kind = 3; // ivar
3773    } else if (isa<FieldDecl>(decl)) {
3774      kind = 2; // field
3775    }
3776
3777    if (kind != -1U) {
3778      Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
3779        << kind;
3780    }
3781  } else if (lifetime == Qualifiers::OCL_None) {
3782    // Try to infer lifetime.
3783    if (!type->isObjCLifetimeType())
3784      return false;
3785
3786    lifetime = type->getObjCARCImplicitLifetime();
3787    type = Context.getLifetimeQualifiedType(type, lifetime);
3788    decl->setType(type);
3789  }
3790
3791  if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
3792    // Thread-local variables cannot have lifetime.
3793    if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
3794        var->isThreadSpecified()) {
3795      Diag(var->getLocation(), diag::err_arc_thread_ownership)
3796        << var->getType();
3797      return true;
3798    }
3799  }
3800
3801  return false;
3802}
3803
3804NamedDecl*
3805Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
3806                              TypeSourceInfo *TInfo, LookupResult &Previous,
3807                              MultiTemplateParamsArg TemplateParamLists) {
3808  QualType R = TInfo->getType();
3809  DeclarationName Name = GetNameForDeclarator(D).getName();
3810
3811  // Check that there are no default arguments (C++ only).
3812  if (getLangOptions().CPlusPlus)
3813    CheckExtraCXXDefaultArguments(D);
3814
3815  DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
3816  assert(SCSpec != DeclSpec::SCS_typedef &&
3817         "Parser allowed 'typedef' as storage class VarDecl.");
3818  VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
3819  if (SCSpec == DeclSpec::SCS_mutable) {
3820    // mutable can only appear on non-static class members, so it's always
3821    // an error here
3822    Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
3823    D.setInvalidType();
3824    SC = SC_None;
3825  }
3826  SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
3827  VarDecl::StorageClass SCAsWritten
3828    = StorageClassSpecToVarDeclStorageClass(SCSpec);
3829
3830  IdentifierInfo *II = Name.getAsIdentifierInfo();
3831  if (!II) {
3832    Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
3833      << Name;
3834    return 0;
3835  }
3836
3837  DiagnoseFunctionSpecifiers(D);
3838
3839  if (!DC->isRecord() && S->getFnParent() == 0) {
3840    // C99 6.9p2: The storage-class specifiers auto and register shall not
3841    // appear in the declaration specifiers in an external declaration.
3842    if (SC == SC_Auto || SC == SC_Register) {
3843
3844      // If this is a register variable with an asm label specified, then this
3845      // is a GNU extension.
3846      if (SC == SC_Register && D.getAsmLabel())
3847        Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
3848      else
3849        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
3850      D.setInvalidType();
3851    }
3852  }
3853
3854  if (getLangOptions().OpenCL) {
3855    // Set up the special work-group-local storage class for variables in the
3856    // OpenCL __local address space.
3857    if (R.getAddressSpace() == LangAS::opencl_local)
3858      SC = SC_OpenCLWorkGroupLocal;
3859  }
3860
3861  bool isExplicitSpecialization = false;
3862  VarDecl *NewVD;
3863  if (!getLangOptions().CPlusPlus) {
3864    NewVD = VarDecl::Create(Context, DC, D.getSourceRange().getBegin(),
3865                            D.getIdentifierLoc(), II,
3866                            R, TInfo, SC, SCAsWritten);
3867
3868    if (D.isInvalidType())
3869      NewVD->setInvalidDecl();
3870  } else {
3871    if (DC->isRecord() && !CurContext->isRecord()) {
3872      // This is an out-of-line definition of a static data member.
3873      if (SC == SC_Static) {
3874        Diag(D.getDeclSpec().getStorageClassSpecLoc(),
3875             diag::err_static_out_of_line)
3876          << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3877      } else if (SC == SC_None)
3878        SC = SC_Static;
3879    }
3880    if (SC == SC_Static) {
3881      if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
3882        if (RD->isLocalClass())
3883          Diag(D.getIdentifierLoc(),
3884               diag::err_static_data_member_not_allowed_in_local_class)
3885            << Name << RD->getDeclName();
3886
3887        // C++ [class.union]p1: If a union contains a static data member,
3888        // the program is ill-formed.
3889        //
3890        // We also disallow static data members in anonymous structs.
3891        if (CurContext->isRecord() && (RD->isUnion() || !RD->getDeclName()))
3892          Diag(D.getIdentifierLoc(),
3893               diag::err_static_data_member_not_allowed_in_union_or_anon_struct)
3894            << Name << RD->isUnion();
3895      }
3896    }
3897
3898    // Match up the template parameter lists with the scope specifier, then
3899    // determine whether we have a template or a template specialization.
3900    isExplicitSpecialization = false;
3901    bool Invalid = false;
3902    if (TemplateParameterList *TemplateParams
3903        = MatchTemplateParametersToScopeSpecifier(
3904                                  D.getDeclSpec().getSourceRange().getBegin(),
3905                                                  D.getIdentifierLoc(),
3906                                                  D.getCXXScopeSpec(),
3907                                                  TemplateParamLists.get(),
3908                                                  TemplateParamLists.size(),
3909                                                  /*never a friend*/ false,
3910                                                  isExplicitSpecialization,
3911                                                  Invalid)) {
3912      if (TemplateParams->size() > 0) {
3913        // There is no such thing as a variable template.
3914        Diag(D.getIdentifierLoc(), diag::err_template_variable)
3915          << II
3916          << SourceRange(TemplateParams->getTemplateLoc(),
3917                         TemplateParams->getRAngleLoc());
3918        return 0;
3919      } else {
3920        // There is an extraneous 'template<>' for this variable. Complain
3921        // about it, but allow the declaration of the variable.
3922        Diag(TemplateParams->getTemplateLoc(),
3923             diag::err_template_variable_noparams)
3924          << II
3925          << SourceRange(TemplateParams->getTemplateLoc(),
3926                         TemplateParams->getRAngleLoc());
3927      }
3928    }
3929
3930    NewVD = VarDecl::Create(Context, DC, D.getSourceRange().getBegin(),
3931                            D.getIdentifierLoc(), II,
3932                            R, TInfo, SC, SCAsWritten);
3933
3934    // If this decl has an auto type in need of deduction, make a note of the
3935    // Decl so we can diagnose uses of it in its own initializer.
3936    if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
3937        R->getContainedAutoType())
3938      ParsingInitForAutoVars.insert(NewVD);
3939
3940    if (D.isInvalidType() || Invalid)
3941      NewVD->setInvalidDecl();
3942
3943    SetNestedNameSpecifier(NewVD, D);
3944
3945    if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) {
3946      NewVD->setTemplateParameterListsInfo(Context,
3947                                           TemplateParamLists.size(),
3948                                           TemplateParamLists.release());
3949    }
3950
3951    if (D.getDeclSpec().isConstexprSpecified()) {
3952      // FIXME: once we know whether there's an initializer, apply this to
3953      // static data members too.
3954      if (!NewVD->isStaticDataMember() &&
3955          !NewVD->isThisDeclarationADefinition()) {
3956        // 'constexpr' is redundant and ill-formed on a non-defining declaration
3957        // of a variable. Suggest replacing it with 'const' if appropriate.
3958        SourceLocation ConstexprLoc = D.getDeclSpec().getConstexprSpecLoc();
3959        SourceRange ConstexprRange(ConstexprLoc, ConstexprLoc);
3960        // If the declarator is complex, we need to move the keyword to the
3961        // innermost chunk as we switch it from 'constexpr' to 'const'.
3962        int Kind = DeclaratorChunk::Paren;
3963        for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3964          Kind = D.getTypeObject(I).Kind;
3965          if (Kind != DeclaratorChunk::Paren)
3966            break;
3967        }
3968        if ((D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) ||
3969            Kind == DeclaratorChunk::Reference)
3970          Diag(ConstexprLoc, diag::err_invalid_constexpr_var_decl)
3971            << FixItHint::CreateRemoval(ConstexprRange);
3972        else if (Kind == DeclaratorChunk::Paren)
3973          Diag(ConstexprLoc, diag::err_invalid_constexpr_var_decl)
3974            << FixItHint::CreateReplacement(ConstexprRange, "const");
3975        else
3976          Diag(ConstexprLoc, diag::err_invalid_constexpr_var_decl)
3977            << FixItHint::CreateRemoval(ConstexprRange)
3978            << FixItHint::CreateInsertion(D.getIdentifierLoc(), "const ");
3979      } else {
3980        NewVD->setConstexpr(true);
3981      }
3982    }
3983  }
3984
3985  // Set the lexical context. If the declarator has a C++ scope specifier, the
3986  // lexical context will be different from the semantic context.
3987  NewVD->setLexicalDeclContext(CurContext);
3988
3989  if (D.getDeclSpec().isThreadSpecified()) {
3990    if (NewVD->hasLocalStorage())
3991      Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
3992    else if (!Context.getTargetInfo().isTLSSupported())
3993      Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
3994    else
3995      NewVD->setThreadSpecified(true);
3996  }
3997
3998  if (D.getDeclSpec().isModulePrivateSpecified()) {
3999    if (isExplicitSpecialization)
4000      Diag(NewVD->getLocation(), diag::err_module_private_specialization)
4001        << 2
4002        << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
4003    else if (NewVD->hasLocalStorage())
4004      Diag(NewVD->getLocation(), diag::err_module_private_local)
4005        << 0 << NewVD->getDeclName()
4006        << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
4007        << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
4008    else
4009      NewVD->setModulePrivate();
4010  }
4011
4012  // Handle attributes prior to checking for duplicates in MergeVarDecl
4013  ProcessDeclAttributes(S, NewVD, D);
4014
4015  // In auto-retain/release, infer strong retension for variables of
4016  // retainable type.
4017  if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
4018    NewVD->setInvalidDecl();
4019
4020  // Handle GNU asm-label extension (encoded as an attribute).
4021  if (Expr *E = (Expr*)D.getAsmLabel()) {
4022    // The parser guarantees this is a string.
4023    StringLiteral *SE = cast<StringLiteral>(E);
4024    StringRef Label = SE->getString();
4025    if (S->getFnParent() != 0) {
4026      switch (SC) {
4027      case SC_None:
4028      case SC_Auto:
4029        Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
4030        break;
4031      case SC_Register:
4032        if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
4033          Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
4034        break;
4035      case SC_Static:
4036      case SC_Extern:
4037      case SC_PrivateExtern:
4038      case SC_OpenCLWorkGroupLocal:
4039        break;
4040      }
4041    }
4042
4043    NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
4044                                                Context, Label));
4045  }
4046
4047  // Diagnose shadowed variables before filtering for scope.
4048  if (!D.getCXXScopeSpec().isSet())
4049    CheckShadow(S, NewVD, Previous);
4050
4051  // Don't consider existing declarations that are in a different
4052  // scope and are out-of-semantic-context declarations (if the new
4053  // declaration has linkage).
4054  FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(),
4055                       isExplicitSpecialization);
4056
4057  if (!getLangOptions().CPlusPlus) {
4058    D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
4059  } else {
4060    // Merge the decl with the existing one if appropriate.
4061    if (!Previous.empty()) {
4062      if (Previous.isSingleResult() &&
4063          isa<FieldDecl>(Previous.getFoundDecl()) &&
4064          D.getCXXScopeSpec().isSet()) {
4065        // The user tried to define a non-static data member
4066        // out-of-line (C++ [dcl.meaning]p1).
4067        Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
4068          << D.getCXXScopeSpec().getRange();
4069        Previous.clear();
4070        NewVD->setInvalidDecl();
4071      }
4072    } else if (D.getCXXScopeSpec().isSet()) {
4073      // No previous declaration in the qualifying scope.
4074      Diag(D.getIdentifierLoc(), diag::err_no_member)
4075        << Name << computeDeclContext(D.getCXXScopeSpec(), true)
4076        << D.getCXXScopeSpec().getRange();
4077      NewVD->setInvalidDecl();
4078    }
4079
4080    D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
4081
4082    // This is an explicit specialization of a static data member. Check it.
4083    if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
4084        CheckMemberSpecialization(NewVD, Previous))
4085      NewVD->setInvalidDecl();
4086  }
4087
4088  // attributes declared post-definition are currently ignored
4089  // FIXME: This should be handled in attribute merging, not
4090  // here.
4091  if (Previous.isSingleResult()) {
4092    VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl());
4093    if (Def && (Def = Def->getDefinition()) &&
4094        Def != NewVD && D.hasAttributes()) {
4095      Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
4096      Diag(Def->getLocation(), diag::note_previous_definition);
4097    }
4098  }
4099
4100  // If this is a locally-scoped extern C variable, update the map of
4101  // such variables.
4102  if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
4103      !NewVD->isInvalidDecl())
4104    RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
4105
4106  // If there's a #pragma GCC visibility in scope, and this isn't a class
4107  // member, set the visibility of this variable.
4108  if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord())
4109    AddPushedVisibilityAttribute(NewVD);
4110
4111  MarkUnusedFileScopedDecl(NewVD);
4112
4113  return NewVD;
4114}
4115
4116/// \brief Diagnose variable or built-in function shadowing.  Implements
4117/// -Wshadow.
4118///
4119/// This method is called whenever a VarDecl is added to a "useful"
4120/// scope.
4121///
4122/// \param S the scope in which the shadowing name is being declared
4123/// \param R the lookup of the name
4124///
4125void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
4126  // Return if warning is ignored.
4127  if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
4128        DiagnosticsEngine::Ignored)
4129    return;
4130
4131  // Don't diagnose declarations at file scope.
4132  if (D->hasGlobalStorage())
4133    return;
4134
4135  DeclContext *NewDC = D->getDeclContext();
4136
4137  // Only diagnose if we're shadowing an unambiguous field or variable.
4138  if (R.getResultKind() != LookupResult::Found)
4139    return;
4140
4141  NamedDecl* ShadowedDecl = R.getFoundDecl();
4142  if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
4143    return;
4144
4145  // Fields are not shadowed by variables in C++ static methods.
4146  if (isa<FieldDecl>(ShadowedDecl))
4147    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
4148      if (MD->isStatic())
4149        return;
4150
4151  if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
4152    if (shadowedVar->isExternC()) {
4153      // For shadowing external vars, make sure that we point to the global
4154      // declaration, not a locally scoped extern declaration.
4155      for (VarDecl::redecl_iterator
4156             I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
4157           I != E; ++I)
4158        if (I->isFileVarDecl()) {
4159          ShadowedDecl = *I;
4160          break;
4161        }
4162    }
4163
4164  DeclContext *OldDC = ShadowedDecl->getDeclContext();
4165
4166  // Only warn about certain kinds of shadowing for class members.
4167  if (NewDC && NewDC->isRecord()) {
4168    // In particular, don't warn about shadowing non-class members.
4169    if (!OldDC->isRecord())
4170      return;
4171
4172    // TODO: should we warn about static data members shadowing
4173    // static data members from base classes?
4174
4175    // TODO: don't diagnose for inaccessible shadowed members.
4176    // This is hard to do perfectly because we might friend the
4177    // shadowing context, but that's just a false negative.
4178  }
4179
4180  // Determine what kind of declaration we're shadowing.
4181  unsigned Kind;
4182  if (isa<RecordDecl>(OldDC)) {
4183    if (isa<FieldDecl>(ShadowedDecl))
4184      Kind = 3; // field
4185    else
4186      Kind = 2; // static data member
4187  } else if (OldDC->isFileContext())
4188    Kind = 1; // global
4189  else
4190    Kind = 0; // local
4191
4192  DeclarationName Name = R.getLookupName();
4193
4194  // Emit warning and note.
4195  Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
4196  Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
4197}
4198
4199/// \brief Check -Wshadow without the advantage of a previous lookup.
4200void Sema::CheckShadow(Scope *S, VarDecl *D) {
4201  if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
4202        DiagnosticsEngine::Ignored)
4203    return;
4204
4205  LookupResult R(*this, D->getDeclName(), D->getLocation(),
4206                 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
4207  LookupName(R, S);
4208  CheckShadow(S, D, R);
4209}
4210
4211/// \brief Perform semantic checking on a newly-created variable
4212/// declaration.
4213///
4214/// This routine performs all of the type-checking required for a
4215/// variable declaration once it has been built. It is used both to
4216/// check variables after they have been parsed and their declarators
4217/// have been translated into a declaration, and to check variables
4218/// that have been instantiated from a template.
4219///
4220/// Sets NewVD->isInvalidDecl() if an error was encountered.
4221///
4222/// Returns true if the variable declaration is a redeclaration.
4223bool Sema::CheckVariableDeclaration(VarDecl *NewVD,
4224                                    LookupResult &Previous) {
4225  // If the decl is already known invalid, don't check it.
4226  if (NewVD->isInvalidDecl())
4227    return false;
4228
4229  QualType T = NewVD->getType();
4230
4231  if (T->isObjCObjectType()) {
4232    Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
4233      << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
4234    T = Context.getObjCObjectPointerType(T);
4235    NewVD->setType(T);
4236  }
4237
4238  // Emit an error if an address space was applied to decl with local storage.
4239  // This includes arrays of objects with address space qualifiers, but not
4240  // automatic variables that point to other address spaces.
4241  // ISO/IEC TR 18037 S5.1.2
4242  if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
4243    Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
4244    NewVD->setInvalidDecl();
4245    return false;
4246  }
4247
4248  if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
4249      && !NewVD->hasAttr<BlocksAttr>()) {
4250    if (getLangOptions().getGC() != LangOptions::NonGC)
4251      Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
4252    else
4253      Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
4254  }
4255
4256  bool isVM = T->isVariablyModifiedType();
4257  if (isVM || NewVD->hasAttr<CleanupAttr>() ||
4258      NewVD->hasAttr<BlocksAttr>())
4259    getCurFunction()->setHasBranchProtectedScope();
4260
4261  if ((isVM && NewVD->hasLinkage()) ||
4262      (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
4263    bool SizeIsNegative;
4264    llvm::APSInt Oversized;
4265    QualType FixedTy =
4266        TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
4267                                            Oversized);
4268
4269    if (FixedTy.isNull() && T->isVariableArrayType()) {
4270      const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
4271      // FIXME: This won't give the correct result for
4272      // int a[10][n];
4273      SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
4274
4275      if (NewVD->isFileVarDecl())
4276        Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
4277        << SizeRange;
4278      else if (NewVD->getStorageClass() == SC_Static)
4279        Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
4280        << SizeRange;
4281      else
4282        Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
4283        << SizeRange;
4284      NewVD->setInvalidDecl();
4285      return false;
4286    }
4287
4288    if (FixedTy.isNull()) {
4289      if (NewVD->isFileVarDecl())
4290        Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
4291      else
4292        Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
4293      NewVD->setInvalidDecl();
4294      return false;
4295    }
4296
4297    Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
4298    NewVD->setType(FixedTy);
4299  }
4300
4301  if (Previous.empty() && NewVD->isExternC()) {
4302    // Since we did not find anything by this name and we're declaring
4303    // an extern "C" variable, look for a non-visible extern "C"
4304    // declaration with the same name.
4305    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4306      = findLocallyScopedExternalDecl(NewVD->getDeclName());
4307    if (Pos != LocallyScopedExternalDecls.end())
4308      Previous.addDecl(Pos->second);
4309  }
4310
4311  if (T->isVoidType() && !NewVD->hasExternalStorage()) {
4312    Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
4313      << T;
4314    NewVD->setInvalidDecl();
4315    return false;
4316  }
4317
4318  if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
4319    Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
4320    NewVD->setInvalidDecl();
4321    return false;
4322  }
4323
4324  if (isVM && NewVD->hasAttr<BlocksAttr>()) {
4325    Diag(NewVD->getLocation(), diag::err_block_on_vm);
4326    NewVD->setInvalidDecl();
4327    return false;
4328  }
4329
4330  // Function pointers and references cannot have qualified function type, only
4331  // function pointer-to-members can do that.
4332  QualType Pointee;
4333  unsigned PtrOrRef = 0;
4334  if (const PointerType *Ptr = T->getAs<PointerType>())
4335    Pointee = Ptr->getPointeeType();
4336  else if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
4337    Pointee = Ref->getPointeeType();
4338    PtrOrRef = 1;
4339  }
4340  if (!Pointee.isNull() && Pointee->isFunctionProtoType() &&
4341      Pointee->getAs<FunctionProtoType>()->getTypeQuals() != 0) {
4342    Diag(NewVD->getLocation(), diag::err_invalid_qualified_function_pointer)
4343        << PtrOrRef;
4344    NewVD->setInvalidDecl();
4345    return false;
4346  }
4347
4348  if (!Previous.empty()) {
4349    MergeVarDecl(NewVD, Previous);
4350    return true;
4351  }
4352  return false;
4353}
4354
4355/// \brief Data used with FindOverriddenMethod
4356struct FindOverriddenMethodData {
4357  Sema *S;
4358  CXXMethodDecl *Method;
4359};
4360
4361/// \brief Member lookup function that determines whether a given C++
4362/// method overrides a method in a base class, to be used with
4363/// CXXRecordDecl::lookupInBases().
4364static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
4365                                 CXXBasePath &Path,
4366                                 void *UserData) {
4367  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4368
4369  FindOverriddenMethodData *Data
4370    = reinterpret_cast<FindOverriddenMethodData*>(UserData);
4371
4372  DeclarationName Name = Data->Method->getDeclName();
4373
4374  // FIXME: Do we care about other names here too?
4375  if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4376    // We really want to find the base class destructor here.
4377    QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
4378    CanQualType CT = Data->S->Context.getCanonicalType(T);
4379
4380    Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
4381  }
4382
4383  for (Path.Decls = BaseRecord->lookup(Name);
4384       Path.Decls.first != Path.Decls.second;
4385       ++Path.Decls.first) {
4386    NamedDecl *D = *Path.Decls.first;
4387    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4388      if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
4389        return true;
4390    }
4391  }
4392
4393  return false;
4394}
4395
4396/// AddOverriddenMethods - See if a method overrides any in the base classes,
4397/// and if so, check that it's a valid override and remember it.
4398bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4399  // Look for virtual methods in base classes that this method might override.
4400  CXXBasePaths Paths;
4401  FindOverriddenMethodData Data;
4402  Data.Method = MD;
4403  Data.S = this;
4404  bool AddedAny = false;
4405  if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
4406    for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
4407         E = Paths.found_decls_end(); I != E; ++I) {
4408      if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
4409        MD->addOverriddenMethod(OldMD->getCanonicalDecl());
4410        if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
4411            !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
4412            !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
4413          AddedAny = true;
4414        }
4415      }
4416    }
4417  }
4418
4419  return AddedAny;
4420}
4421
4422namespace {
4423  // Struct for holding all of the extra arguments needed by
4424  // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
4425  struct ActOnFDArgs {
4426    Scope *S;
4427    Declarator &D;
4428    MultiTemplateParamsArg TemplateParamLists;
4429    bool AddToScope;
4430  };
4431}
4432
4433/// \brief Generate diagnostics for an invalid function redeclaration.
4434///
4435/// This routine handles generating the diagnostic messages for an invalid
4436/// function redeclaration, including finding possible similar declarations
4437/// or performing typo correction if there are no previous declarations with
4438/// the same name.
4439///
4440/// Returns a NamedDecl iff typo correction was performed and substituting in
4441/// the new declaration name does not cause new errors.
4442static NamedDecl* DiagnoseInvalidRedeclaration(
4443    Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
4444    ActOnFDArgs &ExtraArgs) {
4445  NamedDecl *Result = NULL;
4446  DeclarationName Name = NewFD->getDeclName();
4447  DeclContext *NewDC = NewFD->getDeclContext();
4448  LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
4449                    Sema::LookupOrdinaryName, Sema::ForRedeclaration);
4450  llvm::SmallVector<unsigned, 1> MismatchedParams;
4451  llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1> NearMatches;
4452  TypoCorrection Correction;
4453  bool isFriendDecl = (SemaRef.getLangOptions().CPlusPlus &&
4454                       ExtraArgs.D.getDeclSpec().isFriendSpecified());
4455  unsigned DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend
4456                                  : diag::err_member_def_does_not_match;
4457
4458  NewFD->setInvalidDecl();
4459  SemaRef.LookupQualifiedName(Prev, NewDC);
4460  assert(!Prev.isAmbiguous() &&
4461         "Cannot have an ambiguity in previous-declaration lookup");
4462  if (!Prev.empty()) {
4463    for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
4464         Func != FuncEnd; ++Func) {
4465      FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
4466      if (FD &&
4467          hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
4468        // Add 1 to the index so that 0 can mean the mismatch didn't
4469        // involve a parameter
4470        unsigned ParamNum =
4471            MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
4472        NearMatches.push_back(std::make_pair(FD, ParamNum));
4473      }
4474    }
4475  // If the qualified name lookup yielded nothing, try typo correction
4476  } else if ((Correction = SemaRef.CorrectTypo(Prev.getLookupNameInfo(),
4477                                         Prev.getLookupKind(), 0, 0, NewDC)) &&
4478             Correction.getCorrection() != Name) {
4479    // Trap errors.
4480    Sema::SFINAETrap Trap(SemaRef);
4481
4482    // Set up everything for the call to ActOnFunctionDeclarator
4483    ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
4484                              ExtraArgs.D.getIdentifierLoc());
4485    Previous.clear();
4486    Previous.setLookupName(Correction.getCorrection());
4487    for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
4488                                    CDeclEnd = Correction.end();
4489         CDecl != CDeclEnd; ++CDecl) {
4490      FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
4491      if (FD && hasSimilarParameters(SemaRef.Context, FD, NewFD,
4492                                     MismatchedParams)) {
4493        Previous.addDecl(FD);
4494      }
4495    }
4496    bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
4497    // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
4498    // pieces need to verify the typo-corrected C++ declaraction and hopefully
4499    // eliminate the need for the parameter pack ExtraArgs.
4500    Result = SemaRef.ActOnFunctionDeclarator(ExtraArgs.S, ExtraArgs.D,
4501                                             NewFD->getDeclContext(),
4502                                             NewFD->getTypeSourceInfo(),
4503                                             Previous,
4504                                             ExtraArgs.TemplateParamLists,
4505                                             ExtraArgs.AddToScope);
4506    if (Trap.hasErrorOccurred()) {
4507      // Pretend the typo correction never occurred
4508      ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
4509                                ExtraArgs.D.getIdentifierLoc());
4510      ExtraArgs.D.setRedeclaration(wasRedeclaration);
4511      Previous.clear();
4512      Previous.setLookupName(Name);
4513      Result = NULL;
4514    } else {
4515      for (LookupResult::iterator Func = Previous.begin(),
4516                               FuncEnd = Previous.end();
4517           Func != FuncEnd; ++Func) {
4518        if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
4519          NearMatches.push_back(std::make_pair(FD, 0));
4520      }
4521    }
4522    if (NearMatches.empty()) {
4523      // Ignore the correction if it didn't yield any close FunctionDecl matches
4524      Correction = TypoCorrection();
4525    } else {
4526      DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend_suggest
4527                             : diag::err_member_def_does_not_match_suggest;
4528    }
4529  }
4530
4531  if (Correction)
4532    SemaRef.Diag(NewFD->getLocation(), DiagMsg)
4533        << Name << NewDC << Correction.getQuoted(SemaRef.getLangOptions())
4534        << FixItHint::CreateReplacement(
4535            NewFD->getLocation(),
4536            Correction.getAsString(SemaRef.getLangOptions()));
4537  else
4538    SemaRef.Diag(NewFD->getLocation(), DiagMsg)
4539        << Name << NewDC << NewFD->getLocation();
4540
4541  bool NewFDisConst = false;
4542  if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
4543    NewFDisConst = NewMD->getTypeQualifiers() & Qualifiers::Const;
4544
4545  for (llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1>::iterator
4546       NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
4547       NearMatch != NearMatchEnd; ++NearMatch) {
4548    FunctionDecl *FD = NearMatch->first;
4549    bool FDisConst = false;
4550    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
4551      FDisConst = MD->getTypeQualifiers() & Qualifiers::Const;
4552
4553    if (unsigned Idx = NearMatch->second) {
4554      ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
4555      SemaRef.Diag(FDParam->getTypeSpecStartLoc(),
4556             diag::note_member_def_close_param_match)
4557          << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getType();
4558    } else if (Correction) {
4559      SemaRef.Diag(FD->getLocation(), diag::note_previous_decl)
4560          << Correction.getQuoted(SemaRef.getLangOptions());
4561    } else if (FDisConst != NewFDisConst) {
4562      SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
4563          << NewFDisConst << FD->getSourceRange().getEnd();
4564    } else
4565      SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_match);
4566  }
4567  return Result;
4568}
4569
4570static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
4571                                                          Declarator &D) {
4572  switch (D.getDeclSpec().getStorageClassSpec()) {
4573  default: llvm_unreachable("Unknown storage class!");
4574  case DeclSpec::SCS_auto:
4575  case DeclSpec::SCS_register:
4576  case DeclSpec::SCS_mutable:
4577    SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4578                 diag::err_typecheck_sclass_func);
4579    D.setInvalidType();
4580    break;
4581  case DeclSpec::SCS_unspecified: break;
4582  case DeclSpec::SCS_extern: return SC_Extern;
4583  case DeclSpec::SCS_static: {
4584    if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
4585      // C99 6.7.1p5:
4586      //   The declaration of an identifier for a function that has
4587      //   block scope shall have no explicit storage-class specifier
4588      //   other than extern
4589      // See also (C++ [dcl.stc]p4).
4590      SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4591                   diag::err_static_block_func);
4592      break;
4593    } else
4594      return SC_Static;
4595  }
4596  case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4597  }
4598
4599  // No explicit storage class has already been returned
4600  return SC_None;
4601}
4602
4603static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
4604                                           DeclContext *DC, QualType &R,
4605                                           TypeSourceInfo *TInfo,
4606                                           FunctionDecl::StorageClass SC,
4607                                           bool &IsVirtualOkay) {
4608  DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
4609  DeclarationName Name = NameInfo.getName();
4610
4611  FunctionDecl *NewFD = 0;
4612  bool isInline = D.getDeclSpec().isInlineSpecified();
4613  DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
4614  FunctionDecl::StorageClass SCAsWritten
4615    = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
4616
4617  if (!SemaRef.getLangOptions().CPlusPlus) {
4618    // Determine whether the function was written with a
4619    // prototype. This true when:
4620    //   - there is a prototype in the declarator, or
4621    //   - the type R of the function is some kind of typedef or other reference
4622    //     to a type name (which eventually refers to a function type).
4623    bool HasPrototype =
4624      (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
4625      (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
4626
4627    NewFD = FunctionDecl::Create(SemaRef.Context, DC,
4628                                 D.getSourceRange().getBegin(), NameInfo, R,
4629                                 TInfo, SC, SCAsWritten, isInline,
4630                                 HasPrototype);
4631    if (D.isInvalidType())
4632      NewFD->setInvalidDecl();
4633
4634    // Set the lexical context.
4635    NewFD->setLexicalDeclContext(SemaRef.CurContext);
4636
4637    return NewFD;
4638  }
4639
4640  bool isExplicit = D.getDeclSpec().isExplicitSpecified();
4641  bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
4642
4643  // Check that the return type is not an abstract class type.
4644  // For record types, this is done by the AbstractClassUsageDiagnoser once
4645  // the class has been completely parsed.
4646  if (!DC->isRecord() &&
4647      SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
4648                                     R->getAs<FunctionType>()->getResultType(),
4649                                     diag::err_abstract_type_in_decl,
4650                                     SemaRef.AbstractReturnType))
4651    D.setInvalidType();
4652
4653  if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
4654    // This is a C++ constructor declaration.
4655    assert(DC->isRecord() &&
4656           "Constructors can only be declared in a member context");
4657
4658    R = SemaRef.CheckConstructorDeclarator(D, R, SC);
4659    return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
4660                                      D.getSourceRange().getBegin(), NameInfo,
4661                                      R, TInfo, isExplicit, isInline,
4662                                      /*isImplicitlyDeclared=*/false,
4663                                      isConstexpr);
4664
4665  } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4666    // This is a C++ destructor declaration.
4667    if (DC->isRecord()) {
4668      R = SemaRef.CheckDestructorDeclarator(D, R, SC);
4669      CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
4670      CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
4671                                        SemaRef.Context, Record,
4672                                        D.getSourceRange().getBegin(),
4673                                        NameInfo, R, TInfo, isInline,
4674                                        /*isImplicitlyDeclared=*/false);
4675
4676      // If the class is complete, then we now create the implicit exception
4677      // specification. If the class is incomplete or dependent, we can't do
4678      // it yet.
4679      if (SemaRef.getLangOptions().CPlusPlus0x && !Record->isDependentType() &&
4680          Record->getDefinition() && !Record->isBeingDefined() &&
4681          R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
4682        SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
4683      }
4684
4685      IsVirtualOkay = true;
4686      return NewDD;
4687
4688    } else {
4689      SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
4690      D.setInvalidType();
4691
4692      // Create a FunctionDecl to satisfy the function definition parsing
4693      // code path.
4694      return FunctionDecl::Create(SemaRef.Context, DC,
4695                                  D.getSourceRange().getBegin(),
4696                                  D.getIdentifierLoc(), Name, R, TInfo,
4697                                  SC, SCAsWritten, isInline,
4698                                  /*hasPrototype=*/true, isConstexpr);
4699    }
4700
4701  } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
4702    if (!DC->isRecord()) {
4703      SemaRef.Diag(D.getIdentifierLoc(),
4704           diag::err_conv_function_not_member);
4705      return 0;
4706    }
4707
4708    SemaRef.CheckConversionDeclarator(D, R, SC);
4709    IsVirtualOkay = true;
4710    return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
4711                                     D.getSourceRange().getBegin(), NameInfo,
4712                                     R, TInfo, isInline, isExplicit,
4713                                     isConstexpr, SourceLocation());
4714
4715  } else if (DC->isRecord()) {
4716    // If the name of the function is the same as the name of the record,
4717    // then this must be an invalid constructor that has a return type.
4718    // (The parser checks for a return type and makes the declarator a
4719    // constructor if it has no return type).
4720    if (Name.getAsIdentifierInfo() &&
4721        Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
4722      SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
4723        << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4724        << SourceRange(D.getIdentifierLoc());
4725      return 0;
4726    }
4727
4728    bool isStatic = SC == SC_Static;
4729
4730    // [class.free]p1:
4731    // Any allocation function for a class T is a static member
4732    // (even if not explicitly declared static).
4733    if (Name.getCXXOverloadedOperator() == OO_New ||
4734        Name.getCXXOverloadedOperator() == OO_Array_New)
4735      isStatic = true;
4736
4737    // [class.free]p6 Any deallocation function for a class X is a static member
4738    // (even if not explicitly declared static).
4739    if (Name.getCXXOverloadedOperator() == OO_Delete ||
4740        Name.getCXXOverloadedOperator() == OO_Array_Delete)
4741      isStatic = true;
4742
4743    IsVirtualOkay = !isStatic;
4744
4745    // This is a C++ method declaration.
4746    return CXXMethodDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
4747                                 D.getSourceRange().getBegin(), NameInfo, R,
4748                                 TInfo, isStatic, SCAsWritten, isInline,
4749                                 isConstexpr, SourceLocation());
4750
4751  } else {
4752    // Determine whether the function was written with a
4753    // prototype. This true when:
4754    //   - we're in C++ (where every function has a prototype),
4755    return FunctionDecl::Create(SemaRef.Context, DC,
4756                                D.getSourceRange().getBegin(),
4757                                NameInfo, R, TInfo, SC, SCAsWritten, isInline,
4758                                true/*HasPrototype*/, isConstexpr);
4759  }
4760}
4761
4762NamedDecl*
4763Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4764                              TypeSourceInfo *TInfo, LookupResult &Previous,
4765                              MultiTemplateParamsArg TemplateParamLists,
4766                              bool &AddToScope) {
4767  QualType R = TInfo->getType();
4768
4769  assert(R.getTypePtr()->isFunctionType());
4770
4771  // TODO: consider using NameInfo for diagnostic.
4772  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4773  DeclarationName Name = NameInfo.getName();
4774  FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
4775
4776  if (D.getDeclSpec().isThreadSpecified())
4777    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4778
4779  // Do not allow returning a objc interface by-value.
4780  if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) {
4781    Diag(D.getIdentifierLoc(),
4782         diag::err_object_cannot_be_passed_returned_by_value) << 0
4783    << R->getAs<FunctionType>()->getResultType()
4784    << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
4785
4786    QualType T = R->getAs<FunctionType>()->getResultType();
4787    T = Context.getObjCObjectPointerType(T);
4788    if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(R)) {
4789      FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4790      R = Context.getFunctionType(T, FPT->arg_type_begin(),
4791                                  FPT->getNumArgs(), EPI);
4792    }
4793    else if (isa<FunctionNoProtoType>(R))
4794      R = Context.getFunctionNoProtoType(T);
4795  }
4796
4797  bool isFriend = false;
4798  FunctionTemplateDecl *FunctionTemplate = 0;
4799  bool isExplicitSpecialization = false;
4800  bool isFunctionTemplateSpecialization = false;
4801  bool isDependentClassScopeExplicitSpecialization = false;
4802  bool isVirtualOkay = false;
4803
4804  FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
4805                                              isVirtualOkay);
4806  if (!NewFD) return 0;
4807
4808  if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
4809    NewFD->setTopLevelDeclInObjCContainer();
4810
4811  if (getLangOptions().CPlusPlus) {
4812    bool isInline = D.getDeclSpec().isInlineSpecified();
4813    bool isVirtual = D.getDeclSpec().isVirtualSpecified();
4814    bool isExplicit = D.getDeclSpec().isExplicitSpecified();
4815    bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
4816    isFriend = D.getDeclSpec().isFriendSpecified();
4817    if (isFriend && !isInline && D.isFunctionDefinition()) {
4818      // C++ [class.friend]p5
4819      //   A function can be defined in a friend declaration of a
4820      //   class . . . . Such a function is implicitly inline.
4821      NewFD->setImplicitlyInline();
4822    }
4823
4824    SetNestedNameSpecifier(NewFD, D);
4825    isExplicitSpecialization = false;
4826    isFunctionTemplateSpecialization = false;
4827    if (D.isInvalidType())
4828      NewFD->setInvalidDecl();
4829
4830    // Set the lexical context. If the declarator has a C++
4831    // scope specifier, or is the object of a friend declaration, the
4832    // lexical context will be different from the semantic context.
4833    NewFD->setLexicalDeclContext(CurContext);
4834
4835    // Match up the template parameter lists with the scope specifier, then
4836    // determine whether we have a template or a template specialization.
4837    bool Invalid = false;
4838    if (TemplateParameterList *TemplateParams
4839          = MatchTemplateParametersToScopeSpecifier(
4840                                  D.getDeclSpec().getSourceRange().getBegin(),
4841                                  D.getIdentifierLoc(),
4842                                  D.getCXXScopeSpec(),
4843                                  TemplateParamLists.get(),
4844                                  TemplateParamLists.size(),
4845                                  isFriend,
4846                                  isExplicitSpecialization,
4847                                  Invalid)) {
4848      if (TemplateParams->size() > 0) {
4849        // This is a function template
4850
4851        // Check that we can declare a template here.
4852        if (CheckTemplateDeclScope(S, TemplateParams))
4853          return 0;
4854
4855        // A destructor cannot be a template.
4856        if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4857          Diag(NewFD->getLocation(), diag::err_destructor_template);
4858          return 0;
4859        }
4860
4861        // If we're adding a template to a dependent context, we may need to
4862        // rebuilding some of the types used within the template parameter list,
4863        // now that we know what the current instantiation is.
4864        if (DC->isDependentContext()) {
4865          ContextRAII SavedContext(*this, DC);
4866          if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
4867            Invalid = true;
4868        }
4869
4870
4871        FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
4872                                                        NewFD->getLocation(),
4873                                                        Name, TemplateParams,
4874                                                        NewFD);
4875        FunctionTemplate->setLexicalDeclContext(CurContext);
4876        NewFD->setDescribedFunctionTemplate(FunctionTemplate);
4877
4878        // For source fidelity, store the other template param lists.
4879        if (TemplateParamLists.size() > 1) {
4880          NewFD->setTemplateParameterListsInfo(Context,
4881                                               TemplateParamLists.size() - 1,
4882                                               TemplateParamLists.release());
4883        }
4884      } else {
4885        // This is a function template specialization.
4886        isFunctionTemplateSpecialization = true;
4887        // For source fidelity, store all the template param lists.
4888        NewFD->setTemplateParameterListsInfo(Context,
4889                                             TemplateParamLists.size(),
4890                                             TemplateParamLists.release());
4891
4892        // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
4893        if (isFriend) {
4894          // We want to remove the "template<>", found here.
4895          SourceRange RemoveRange = TemplateParams->getSourceRange();
4896
4897          // If we remove the template<> and the name is not a
4898          // template-id, we're actually silently creating a problem:
4899          // the friend declaration will refer to an untemplated decl,
4900          // and clearly the user wants a template specialization.  So
4901          // we need to insert '<>' after the name.
4902          SourceLocation InsertLoc;
4903          if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
4904            InsertLoc = D.getName().getSourceRange().getEnd();
4905            InsertLoc = PP.getLocForEndOfToken(InsertLoc);
4906          }
4907
4908          Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
4909            << Name << RemoveRange
4910            << FixItHint::CreateRemoval(RemoveRange)
4911            << FixItHint::CreateInsertion(InsertLoc, "<>");
4912        }
4913      }
4914    }
4915    else {
4916      // All template param lists were matched against the scope specifier:
4917      // this is NOT (an explicit specialization of) a template.
4918      if (TemplateParamLists.size() > 0)
4919        // For source fidelity, store all the template param lists.
4920        NewFD->setTemplateParameterListsInfo(Context,
4921                                             TemplateParamLists.size(),
4922                                             TemplateParamLists.release());
4923    }
4924
4925    if (Invalid) {
4926      NewFD->setInvalidDecl();
4927      if (FunctionTemplate)
4928        FunctionTemplate->setInvalidDecl();
4929    }
4930
4931    // C++ [dcl.fct.spec]p5:
4932    //   The virtual specifier shall only be used in declarations of
4933    //   nonstatic class member functions that appear within a
4934    //   member-specification of a class declaration; see 10.3.
4935    //
4936    if (isVirtual && !NewFD->isInvalidDecl()) {
4937      if (!isVirtualOkay) {
4938        Diag(D.getDeclSpec().getVirtualSpecLoc(),
4939             diag::err_virtual_non_function);
4940      } else if (!CurContext->isRecord()) {
4941        // 'virtual' was specified outside of the class.
4942        Diag(D.getDeclSpec().getVirtualSpecLoc(),
4943             diag::err_virtual_out_of_class)
4944          << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
4945      } else if (NewFD->getDescribedFunctionTemplate()) {
4946        // C++ [temp.mem]p3:
4947        //  A member function template shall not be virtual.
4948        Diag(D.getDeclSpec().getVirtualSpecLoc(),
4949             diag::err_virtual_member_function_template)
4950          << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
4951      } else {
4952        // Okay: Add virtual to the method.
4953        NewFD->setVirtualAsWritten(true);
4954      }
4955    }
4956
4957    // C++ [dcl.fct.spec]p3:
4958    //  The inline specifier shall not appear on a block scope function
4959    //  declaration.
4960    if (isInline && !NewFD->isInvalidDecl()) {
4961      if (CurContext->isFunctionOrMethod()) {
4962        // 'inline' is not allowed on block scope function declaration.
4963        Diag(D.getDeclSpec().getInlineSpecLoc(),
4964             diag::err_inline_declaration_block_scope) << Name
4965          << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
4966      }
4967    }
4968
4969    // C++ [dcl.fct.spec]p6:
4970    //  The explicit specifier shall be used only in the declaration of a
4971    //  constructor or conversion function within its class definition;
4972    //  see 12.3.1 and 12.3.2.
4973    if (isExplicit && !NewFD->isInvalidDecl()) {
4974      if (!CurContext->isRecord()) {
4975        // 'explicit' was specified outside of the class.
4976        Diag(D.getDeclSpec().getExplicitSpecLoc(),
4977             diag::err_explicit_out_of_class)
4978          << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
4979      } else if (!isa<CXXConstructorDecl>(NewFD) &&
4980                 !isa<CXXConversionDecl>(NewFD)) {
4981        // 'explicit' was specified on a function that wasn't a constructor
4982        // or conversion function.
4983        Diag(D.getDeclSpec().getExplicitSpecLoc(),
4984             diag::err_explicit_non_ctor_or_conv_function)
4985          << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
4986      }
4987    }
4988
4989    if (isConstexpr) {
4990      // C++0x [dcl.constexpr]p2: constexpr functions and constexpr constructors
4991      // are implicitly inline.
4992      NewFD->setImplicitlyInline();
4993
4994      // C++0x [dcl.constexpr]p3: functions declared constexpr are required to
4995      // be either constructors or to return a literal type. Therefore,
4996      // destructors cannot be declared constexpr.
4997      if (isa<CXXDestructorDecl>(NewFD))
4998        Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
4999    }
5000
5001    // If __module_private__ was specified, mark the function accordingly.
5002    if (D.getDeclSpec().isModulePrivateSpecified()) {
5003      if (isFunctionTemplateSpecialization) {
5004        SourceLocation ModulePrivateLoc
5005          = D.getDeclSpec().getModulePrivateSpecLoc();
5006        Diag(ModulePrivateLoc, diag::err_module_private_specialization)
5007          << 0
5008          << FixItHint::CreateRemoval(ModulePrivateLoc);
5009      } else {
5010        NewFD->setModulePrivate();
5011        if (FunctionTemplate)
5012          FunctionTemplate->setModulePrivate();
5013      }
5014    }
5015
5016    if (isFriend) {
5017      // For now, claim that the objects have no previous declaration.
5018      if (FunctionTemplate) {
5019        FunctionTemplate->setObjectOfFriendDecl(false);
5020        FunctionTemplate->setAccess(AS_public);
5021      }
5022      NewFD->setObjectOfFriendDecl(false);
5023      NewFD->setAccess(AS_public);
5024    }
5025
5026    // If a function is defined as defaulted or deleted, mark it as such now.
5027    switch (D.getFunctionDefinitionKind()) {
5028      case FDK_Declaration:
5029      case FDK_Definition:
5030        break;
5031
5032      case FDK_Defaulted:
5033        NewFD->setDefaulted();
5034        break;
5035
5036      case FDK_Deleted:
5037        NewFD->setDeletedAsWritten();
5038        break;
5039    }
5040
5041    if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
5042        D.isFunctionDefinition()) {
5043      // C++ [class.mfct]p2:
5044      //   A member function may be defined (8.4) in its class definition, in
5045      //   which case it is an inline member function (7.1.2)
5046      NewFD->setImplicitlyInline();
5047    }
5048
5049    if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
5050        !CurContext->isRecord()) {
5051      // C++ [class.static]p1:
5052      //   A data or function member of a class may be declared static
5053      //   in a class definition, in which case it is a static member of
5054      //   the class.
5055
5056      // Complain about the 'static' specifier if it's on an out-of-line
5057      // member function definition.
5058      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5059           diag::err_static_out_of_line)
5060        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5061    }
5062  }
5063
5064  // Filter out previous declarations that don't match the scope.
5065  FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(),
5066                       isExplicitSpecialization ||
5067                       isFunctionTemplateSpecialization);
5068
5069  // Handle GNU asm-label extension (encoded as an attribute).
5070  if (Expr *E = (Expr*) D.getAsmLabel()) {
5071    // The parser guarantees this is a string.
5072    StringLiteral *SE = cast<StringLiteral>(E);
5073    NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
5074                                                SE->getString()));
5075  }
5076
5077  // Copy the parameter declarations from the declarator D to the function
5078  // declaration NewFD, if they are available.  First scavenge them into Params.
5079  SmallVector<ParmVarDecl*, 16> Params;
5080  if (D.isFunctionDeclarator()) {
5081    DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5082
5083    // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
5084    // function that takes no arguments, not a function that takes a
5085    // single void argument.
5086    // We let through "const void" here because Sema::GetTypeForDeclarator
5087    // already checks for that case.
5088    if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5089        FTI.ArgInfo[0].Param &&
5090        cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
5091      // Empty arg list, don't push any params.
5092      ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[0].Param);
5093
5094      // In C++, the empty parameter-type-list must be spelled "void"; a
5095      // typedef of void is not permitted.
5096      if (getLangOptions().CPlusPlus &&
5097          Param->getType().getUnqualifiedType() != Context.VoidTy) {
5098        bool IsTypeAlias = false;
5099        if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
5100          IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
5101        else if (const TemplateSpecializationType *TST =
5102                   Param->getType()->getAs<TemplateSpecializationType>())
5103          IsTypeAlias = TST->isTypeAlias();
5104        Diag(Param->getLocation(), diag::err_param_typedef_of_void)
5105          << IsTypeAlias;
5106      }
5107    } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
5108      for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
5109        ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
5110        assert(Param->getDeclContext() != NewFD && "Was set before ?");
5111        Param->setDeclContext(NewFD);
5112        Params.push_back(Param);
5113
5114        if (Param->isInvalidDecl())
5115          NewFD->setInvalidDecl();
5116      }
5117    }
5118
5119  } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
5120    // When we're declaring a function with a typedef, typeof, etc as in the
5121    // following example, we'll need to synthesize (unnamed)
5122    // parameters for use in the declaration.
5123    //
5124    // @code
5125    // typedef void fn(int);
5126    // fn f;
5127    // @endcode
5128
5129    // Synthesize a parameter for each argument type.
5130    for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
5131         AE = FT->arg_type_end(); AI != AE; ++AI) {
5132      ParmVarDecl *Param =
5133        BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
5134      Param->setScopeInfo(0, Params.size());
5135      Params.push_back(Param);
5136    }
5137  } else {
5138    assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
5139           "Should not need args for typedef of non-prototype fn");
5140  }
5141
5142  // Finally, we know we have the right number of parameters, install them.
5143  NewFD->setParams(Params);
5144
5145  // Process the non-inheritable attributes on this declaration.
5146  ProcessDeclAttributes(S, NewFD, D,
5147                        /*NonInheritable=*/true, /*Inheritable=*/false);
5148
5149  if (!getLangOptions().CPlusPlus) {
5150    // Perform semantic checking on the function declaration.
5151    bool isExplicitSpecialization=false;
5152    if (!NewFD->isInvalidDecl()) {
5153      if (NewFD->getResultType()->isVariablyModifiedType()) {
5154        // Functions returning a variably modified type violate C99 6.7.5.2p2
5155        // because all functions have linkage.
5156        Diag(NewFD->getLocation(), diag::err_vm_func_decl);
5157        NewFD->setInvalidDecl();
5158      } else {
5159        if (NewFD->isMain())
5160          CheckMain(NewFD, D.getDeclSpec());
5161        D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
5162                                                    isExplicitSpecialization));
5163      }
5164    }
5165    assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
5166            Previous.getResultKind() != LookupResult::FoundOverloaded) &&
5167           "previous declaration set still overloaded");
5168  } else {
5169    // If the declarator is a template-id, translate the parser's template
5170    // argument list into our AST format.
5171    bool HasExplicitTemplateArgs = false;
5172    TemplateArgumentListInfo TemplateArgs;
5173    if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5174      TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5175      TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5176      TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
5177      ASTTemplateArgsPtr TemplateArgsPtr(*this,
5178                                         TemplateId->getTemplateArgs(),
5179                                         TemplateId->NumArgs);
5180      translateTemplateArguments(TemplateArgsPtr,
5181                                 TemplateArgs);
5182      TemplateArgsPtr.release();
5183
5184      HasExplicitTemplateArgs = true;
5185
5186      if (NewFD->isInvalidDecl()) {
5187        HasExplicitTemplateArgs = false;
5188      } else if (FunctionTemplate) {
5189        // Function template with explicit template arguments.
5190        Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
5191          << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
5192
5193        HasExplicitTemplateArgs = false;
5194      } else if (!isFunctionTemplateSpecialization &&
5195                 !D.getDeclSpec().isFriendSpecified()) {
5196        // We have encountered something that the user meant to be a
5197        // specialization (because it has explicitly-specified template
5198        // arguments) but that was not introduced with a "template<>" (or had
5199        // too few of them).
5200        Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5201          << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5202          << FixItHint::CreateInsertion(
5203                                    D.getDeclSpec().getSourceRange().getBegin(),
5204                                        "template<> ");
5205        isFunctionTemplateSpecialization = true;
5206      } else {
5207        // "friend void foo<>(int);" is an implicit specialization decl.
5208        isFunctionTemplateSpecialization = true;
5209      }
5210    } else if (isFriend && isFunctionTemplateSpecialization) {
5211      // This combination is only possible in a recovery case;  the user
5212      // wrote something like:
5213      //   template <> friend void foo(int);
5214      // which we're recovering from as if the user had written:
5215      //   friend void foo<>(int);
5216      // Go ahead and fake up a template id.
5217      HasExplicitTemplateArgs = true;
5218        TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
5219      TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
5220    }
5221
5222    // If it's a friend (and only if it's a friend), it's possible
5223    // that either the specialized function type or the specialized
5224    // template is dependent, and therefore matching will fail.  In
5225    // this case, don't check the specialization yet.
5226    bool InstantiationDependent = false;
5227    if (isFunctionTemplateSpecialization && isFriend &&
5228        (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
5229         TemplateSpecializationType::anyDependentTemplateArguments(
5230            TemplateArgs.getArgumentArray(), TemplateArgs.size(),
5231            InstantiationDependent))) {
5232      assert(HasExplicitTemplateArgs &&
5233             "friend function specialization without template args");
5234      if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
5235                                                       Previous))
5236        NewFD->setInvalidDecl();
5237    } else if (isFunctionTemplateSpecialization) {
5238      if (CurContext->isDependentContext() && CurContext->isRecord()
5239          && !isFriend) {
5240        isDependentClassScopeExplicitSpecialization = true;
5241        Diag(NewFD->getLocation(), getLangOptions().MicrosoftExt ?
5242          diag::ext_function_specialization_in_class :
5243          diag::err_function_specialization_in_class)
5244          << NewFD->getDeclName();
5245      } else if (CheckFunctionTemplateSpecialization(NewFD,
5246                                  (HasExplicitTemplateArgs ? &TemplateArgs : 0),
5247                                                     Previous))
5248        NewFD->setInvalidDecl();
5249
5250      // C++ [dcl.stc]p1:
5251      //   A storage-class-specifier shall not be specified in an explicit
5252      //   specialization (14.7.3)
5253      if (SC != SC_None) {
5254        if (SC != NewFD->getStorageClass())
5255          Diag(NewFD->getLocation(),
5256               diag::err_explicit_specialization_inconsistent_storage_class)
5257            << SC
5258            << FixItHint::CreateRemoval(
5259                                      D.getDeclSpec().getStorageClassSpecLoc());
5260
5261        else
5262          Diag(NewFD->getLocation(),
5263               diag::ext_explicit_specialization_storage_class)
5264            << FixItHint::CreateRemoval(
5265                                      D.getDeclSpec().getStorageClassSpecLoc());
5266      }
5267
5268    } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
5269      if (CheckMemberSpecialization(NewFD, Previous))
5270          NewFD->setInvalidDecl();
5271    }
5272
5273    // Perform semantic checking on the function declaration.
5274    if (!isDependentClassScopeExplicitSpecialization) {
5275      if (NewFD->isInvalidDecl()) {
5276        // If this is a class member, mark the class invalid immediately.
5277        // This avoids some consistency errors later.
5278        if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
5279          methodDecl->getParent()->setInvalidDecl();
5280      } else {
5281        if (NewFD->isMain())
5282          CheckMain(NewFD, D.getDeclSpec());
5283        D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
5284                                                    isExplicitSpecialization));
5285      }
5286    }
5287
5288    assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
5289            Previous.getResultKind() != LookupResult::FoundOverloaded) &&
5290           "previous declaration set still overloaded");
5291
5292    if (NewFD->isConstexpr() && !NewFD->isInvalidDecl() &&
5293        !CheckConstexprFunctionDecl(NewFD, CCK_Declaration))
5294      NewFD->setInvalidDecl();
5295
5296    NamedDecl *PrincipalDecl = (FunctionTemplate
5297                                ? cast<NamedDecl>(FunctionTemplate)
5298                                : NewFD);
5299
5300    if (isFriend && D.isRedeclaration()) {
5301      AccessSpecifier Access = AS_public;
5302      if (!NewFD->isInvalidDecl())
5303        Access = NewFD->getPreviousDeclaration()->getAccess();
5304
5305      NewFD->setAccess(Access);
5306      if (FunctionTemplate) FunctionTemplate->setAccess(Access);
5307
5308      PrincipalDecl->setObjectOfFriendDecl(true);
5309    }
5310
5311    if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
5312        PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
5313      PrincipalDecl->setNonMemberOperator();
5314
5315    // If we have a function template, check the template parameter
5316    // list. This will check and merge default template arguments.
5317    if (FunctionTemplate) {
5318      FunctionTemplateDecl *PrevTemplate =
5319                                     FunctionTemplate->getPreviousDeclaration();
5320      CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
5321                       PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
5322                            D.getDeclSpec().isFriendSpecified()
5323                              ? (D.isFunctionDefinition()
5324                                   ? TPC_FriendFunctionTemplateDefinition
5325                                   : TPC_FriendFunctionTemplate)
5326                              : (D.getCXXScopeSpec().isSet() &&
5327                                 DC && DC->isRecord() &&
5328                                 DC->isDependentContext())
5329                                  ? TPC_ClassTemplateMember
5330                                  : TPC_FunctionTemplate);
5331    }
5332
5333    if (NewFD->isInvalidDecl()) {
5334      // Ignore all the rest of this.
5335    } else if (!D.isRedeclaration()) {
5336      struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
5337                                       AddToScope };
5338      // Fake up an access specifier if it's supposed to be a class member.
5339      if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
5340        NewFD->setAccess(AS_public);
5341
5342      // Qualified decls generally require a previous declaration.
5343      if (D.getCXXScopeSpec().isSet()) {
5344        // ...with the major exception of templated-scope or
5345        // dependent-scope friend declarations.
5346
5347        // TODO: we currently also suppress this check in dependent
5348        // contexts because (1) the parameter depth will be off when
5349        // matching friend templates and (2) we might actually be
5350        // selecting a friend based on a dependent factor.  But there
5351        // are situations where these conditions don't apply and we
5352        // can actually do this check immediately.
5353        if (isFriend &&
5354            (TemplateParamLists.size() ||
5355             D.getCXXScopeSpec().getScopeRep()->isDependent() ||
5356             CurContext->isDependentContext())) {
5357          // ignore these
5358        } else {
5359          // The user tried to provide an out-of-line definition for a
5360          // function that is a member of a class or namespace, but there
5361          // was no such member function declared (C++ [class.mfct]p2,
5362          // C++ [namespace.memdef]p2). For example:
5363          //
5364          // class X {
5365          //   void f() const;
5366          // };
5367          //
5368          // void X::f() { } // ill-formed
5369          //
5370          // Complain about this problem, and attempt to suggest close
5371          // matches (e.g., those that differ only in cv-qualifiers and
5372          // whether the parameter types are references).
5373
5374          if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
5375                                                               NewFD,
5376                                                               ExtraArgs)) {
5377            AddToScope = ExtraArgs.AddToScope;
5378            return Result;
5379          }
5380        }
5381
5382        // Unqualified local friend declarations are required to resolve
5383        // to something.
5384      } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
5385        if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
5386                                                             NewFD,
5387                                                             ExtraArgs)) {
5388          AddToScope = ExtraArgs.AddToScope;
5389          return Result;
5390        }
5391      }
5392
5393    } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
5394               !isFriend && !isFunctionTemplateSpecialization &&
5395               !isExplicitSpecialization) {
5396      // An out-of-line member function declaration must also be a
5397      // definition (C++ [dcl.meaning]p1).
5398      // Note that this is not the case for explicit specializations of
5399      // function templates or member functions of class templates, per
5400      // C++ [temp.expl.spec]p2. We also allow these declarations as an
5401      // extension for compatibility with old SWIG code which likes to
5402      // generate them.
5403      Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
5404        << D.getCXXScopeSpec().getRange();
5405    }
5406  }
5407
5408
5409  // Handle attributes. We need to have merged decls when handling attributes
5410  // (for example to check for conflicts, etc).
5411  // FIXME: This needs to happen before we merge declarations. Then,
5412  // let attribute merging cope with attribute conflicts.
5413  ProcessDeclAttributes(S, NewFD, D,
5414                        /*NonInheritable=*/false, /*Inheritable=*/true);
5415
5416  // attributes declared post-definition are currently ignored
5417  // FIXME: This should happen during attribute merging
5418  if (D.isRedeclaration() && Previous.isSingleResult()) {
5419    const FunctionDecl *Def;
5420    FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
5421    if (PrevFD && PrevFD->isDefined(Def) && D.hasAttributes()) {
5422      Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
5423      Diag(Def->getLocation(), diag::note_previous_definition);
5424    }
5425  }
5426
5427  AddKnownFunctionAttributes(NewFD);
5428
5429  if (NewFD->hasAttr<OverloadableAttr>() &&
5430      !NewFD->getType()->getAs<FunctionProtoType>()) {
5431    Diag(NewFD->getLocation(),
5432         diag::err_attribute_overloadable_no_prototype)
5433      << NewFD;
5434
5435    // Turn this into a variadic function with no parameters.
5436    const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
5437    FunctionProtoType::ExtProtoInfo EPI;
5438    EPI.Variadic = true;
5439    EPI.ExtInfo = FT->getExtInfo();
5440
5441    QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI);
5442    NewFD->setType(R);
5443  }
5444
5445  // If there's a #pragma GCC visibility in scope, and this isn't a class
5446  // member, set the visibility of this function.
5447  if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord())
5448    AddPushedVisibilityAttribute(NewFD);
5449
5450  // If there's a #pragma clang arc_cf_code_audited in scope, consider
5451  // marking the function.
5452  AddCFAuditedAttribute(NewFD);
5453
5454  // If this is a locally-scoped extern C function, update the
5455  // map of such names.
5456  if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
5457      && !NewFD->isInvalidDecl())
5458    RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
5459
5460  // Set this FunctionDecl's range up to the right paren.
5461  NewFD->setRangeEnd(D.getSourceRange().getEnd());
5462
5463  if (getLangOptions().CPlusPlus) {
5464    if (FunctionTemplate) {
5465      if (NewFD->isInvalidDecl())
5466        FunctionTemplate->setInvalidDecl();
5467      return FunctionTemplate;
5468    }
5469  }
5470
5471  MarkUnusedFileScopedDecl(NewFD);
5472
5473  if (getLangOptions().CUDA)
5474    if (IdentifierInfo *II = NewFD->getIdentifier())
5475      if (!NewFD->isInvalidDecl() &&
5476          NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5477        if (II->isStr("cudaConfigureCall")) {
5478          if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
5479            Diag(NewFD->getLocation(), diag::err_config_scalar_return);
5480
5481          Context.setcudaConfigureCallDecl(NewFD);
5482        }
5483      }
5484
5485  // Here we have an function template explicit specialization at class scope.
5486  // The actually specialization will be postponed to template instatiation
5487  // time via the ClassScopeFunctionSpecializationDecl node.
5488  if (isDependentClassScopeExplicitSpecialization) {
5489    ClassScopeFunctionSpecializationDecl *NewSpec =
5490                         ClassScopeFunctionSpecializationDecl::Create(
5491                                Context, CurContext,  SourceLocation(),
5492                                cast<CXXMethodDecl>(NewFD));
5493    CurContext->addDecl(NewSpec);
5494    AddToScope = false;
5495  }
5496
5497  return NewFD;
5498}
5499
5500/// \brief Perform semantic checking of a new function declaration.
5501///
5502/// Performs semantic analysis of the new function declaration
5503/// NewFD. This routine performs all semantic checking that does not
5504/// require the actual declarator involved in the declaration, and is
5505/// used both for the declaration of functions as they are parsed
5506/// (called via ActOnDeclarator) and for the declaration of functions
5507/// that have been instantiated via C++ template instantiation (called
5508/// via InstantiateDecl).
5509///
5510/// \param IsExplicitSpecialiation whether this new function declaration is
5511/// an explicit specialization of the previous declaration.
5512///
5513/// This sets NewFD->isInvalidDecl() to true if there was an error.
5514///
5515/// Returns true if the function declaration is a redeclaration.
5516bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
5517                                    LookupResult &Previous,
5518                                    bool IsExplicitSpecialization) {
5519  assert(!NewFD->getResultType()->isVariablyModifiedType()
5520         && "Variably modified return types are not handled here");
5521
5522  // Check for a previous declaration of this name.
5523  if (Previous.empty() && NewFD->isExternC()) {
5524    // Since we did not find anything by this name and we're declaring
5525    // an extern "C" function, look for a non-visible extern "C"
5526    // declaration with the same name.
5527    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
5528      = findLocallyScopedExternalDecl(NewFD->getDeclName());
5529    if (Pos != LocallyScopedExternalDecls.end())
5530      Previous.addDecl(Pos->second);
5531  }
5532
5533  bool Redeclaration = false;
5534
5535  // Merge or overload the declaration with an existing declaration of
5536  // the same name, if appropriate.
5537  if (!Previous.empty()) {
5538    // Determine whether NewFD is an overload of PrevDecl or
5539    // a declaration that requires merging. If it's an overload,
5540    // there's no more work to do here; we'll just add the new
5541    // function to the scope.
5542
5543    NamedDecl *OldDecl = 0;
5544    if (!AllowOverloadingOfFunction(Previous, Context)) {
5545      Redeclaration = true;
5546      OldDecl = Previous.getFoundDecl();
5547    } else {
5548      switch (CheckOverload(S, NewFD, Previous, OldDecl,
5549                            /*NewIsUsingDecl*/ false)) {
5550      case Ovl_Match:
5551        Redeclaration = true;
5552        break;
5553
5554      case Ovl_NonFunction:
5555        Redeclaration = true;
5556        break;
5557
5558      case Ovl_Overload:
5559        Redeclaration = false;
5560        break;
5561      }
5562
5563      if (!getLangOptions().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
5564        // If a function name is overloadable in C, then every function
5565        // with that name must be marked "overloadable".
5566        Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
5567          << Redeclaration << NewFD;
5568        NamedDecl *OverloadedDecl = 0;
5569        if (Redeclaration)
5570          OverloadedDecl = OldDecl;
5571        else if (!Previous.empty())
5572          OverloadedDecl = Previous.getRepresentativeDecl();
5573        if (OverloadedDecl)
5574          Diag(OverloadedDecl->getLocation(),
5575               diag::note_attribute_overloadable_prev_overload);
5576        NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
5577                                                        Context));
5578      }
5579    }
5580
5581    if (Redeclaration) {
5582      // NewFD and OldDecl represent declarations that need to be
5583      // merged.
5584      if (MergeFunctionDecl(NewFD, OldDecl)) {
5585        NewFD->setInvalidDecl();
5586        return Redeclaration;
5587      }
5588
5589      Previous.clear();
5590      Previous.addDecl(OldDecl);
5591
5592      if (FunctionTemplateDecl *OldTemplateDecl
5593                                    = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
5594        NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
5595        FunctionTemplateDecl *NewTemplateDecl
5596          = NewFD->getDescribedFunctionTemplate();
5597        assert(NewTemplateDecl && "Template/non-template mismatch");
5598        if (CXXMethodDecl *Method
5599              = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
5600          Method->setAccess(OldTemplateDecl->getAccess());
5601          NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
5602        }
5603
5604        // If this is an explicit specialization of a member that is a function
5605        // template, mark it as a member specialization.
5606        if (IsExplicitSpecialization &&
5607            NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
5608          NewTemplateDecl->setMemberSpecialization();
5609          assert(OldTemplateDecl->isMemberSpecialization());
5610        }
5611
5612      } else {
5613        if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
5614          NewFD->setAccess(OldDecl->getAccess());
5615        NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
5616      }
5617    }
5618  }
5619
5620  // Semantic checking for this function declaration (in isolation).
5621  if (getLangOptions().CPlusPlus) {
5622    // C++-specific checks.
5623    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
5624      CheckConstructor(Constructor);
5625    } else if (CXXDestructorDecl *Destructor =
5626                dyn_cast<CXXDestructorDecl>(NewFD)) {
5627      CXXRecordDecl *Record = Destructor->getParent();
5628      QualType ClassType = Context.getTypeDeclType(Record);
5629
5630      // FIXME: Shouldn't we be able to perform this check even when the class
5631      // type is dependent? Both gcc and edg can handle that.
5632      if (!ClassType->isDependentType()) {
5633        DeclarationName Name
5634          = Context.DeclarationNames.getCXXDestructorName(
5635                                        Context.getCanonicalType(ClassType));
5636        if (NewFD->getDeclName() != Name) {
5637          Diag(NewFD->getLocation(), diag::err_destructor_name);
5638          NewFD->setInvalidDecl();
5639          return Redeclaration;
5640        }
5641      }
5642    } else if (CXXConversionDecl *Conversion
5643               = dyn_cast<CXXConversionDecl>(NewFD)) {
5644      ActOnConversionDeclarator(Conversion);
5645    }
5646
5647    // Find any virtual functions that this function overrides.
5648    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
5649      if (!Method->isFunctionTemplateSpecialization() &&
5650          !Method->getDescribedFunctionTemplate()) {
5651        if (AddOverriddenMethods(Method->getParent(), Method)) {
5652          // If the function was marked as "static", we have a problem.
5653          if (NewFD->getStorageClass() == SC_Static) {
5654            Diag(NewFD->getLocation(), diag::err_static_overrides_virtual)
5655              << NewFD->getDeclName();
5656            for (CXXMethodDecl::method_iterator
5657                      Overridden = Method->begin_overridden_methods(),
5658                   OverriddenEnd = Method->end_overridden_methods();
5659                 Overridden != OverriddenEnd;
5660                 ++Overridden) {
5661              Diag((*Overridden)->getLocation(),
5662                   diag::note_overridden_virtual_function);
5663            }
5664          }
5665        }
5666      }
5667    }
5668
5669    // Extra checking for C++ overloaded operators (C++ [over.oper]).
5670    if (NewFD->isOverloadedOperator() &&
5671        CheckOverloadedOperatorDeclaration(NewFD)) {
5672      NewFD->setInvalidDecl();
5673      return Redeclaration;
5674    }
5675
5676    // Extra checking for C++0x literal operators (C++0x [over.literal]).
5677    if (NewFD->getLiteralIdentifier() &&
5678        CheckLiteralOperatorDeclaration(NewFD)) {
5679      NewFD->setInvalidDecl();
5680      return Redeclaration;
5681    }
5682
5683    // In C++, check default arguments now that we have merged decls. Unless
5684    // the lexical context is the class, because in this case this is done
5685    // during delayed parsing anyway.
5686    if (!CurContext->isRecord())
5687      CheckCXXDefaultArguments(NewFD);
5688
5689    // If this function declares a builtin function, check the type of this
5690    // declaration against the expected type for the builtin.
5691    if (unsigned BuiltinID = NewFD->getBuiltinID()) {
5692      ASTContext::GetBuiltinTypeError Error;
5693      QualType T = Context.GetBuiltinType(BuiltinID, Error);
5694      if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
5695        // The type of this function differs from the type of the builtin,
5696        // so forget about the builtin entirely.
5697        Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
5698      }
5699    }
5700  }
5701  return Redeclaration;
5702}
5703
5704void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
5705  // C++ [basic.start.main]p3:  A program that declares main to be inline
5706  //   or static is ill-formed.
5707  // C99 6.7.4p4:  In a hosted environment, the inline function specifier
5708  //   shall not appear in a declaration of main.
5709  // static main is not an error under C99, but we should warn about it.
5710  if (FD->getStorageClass() == SC_Static)
5711    Diag(DS.getStorageClassSpecLoc(), getLangOptions().CPlusPlus
5712         ? diag::err_static_main : diag::warn_static_main)
5713      << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5714  if (FD->isInlineSpecified())
5715    Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
5716      << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
5717
5718  QualType T = FD->getType();
5719  assert(T->isFunctionType() && "function decl is not of function type");
5720  const FunctionType* FT = T->getAs<FunctionType>();
5721
5722  if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
5723    Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
5724    FD->setInvalidDecl(true);
5725  }
5726
5727  // Treat protoless main() as nullary.
5728  if (isa<FunctionNoProtoType>(FT)) return;
5729
5730  const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
5731  unsigned nparams = FTP->getNumArgs();
5732  assert(FD->getNumParams() == nparams);
5733
5734  bool HasExtraParameters = (nparams > 3);
5735
5736  // Darwin passes an undocumented fourth argument of type char**.  If
5737  // other platforms start sprouting these, the logic below will start
5738  // getting shifty.
5739  if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
5740    HasExtraParameters = false;
5741
5742  if (HasExtraParameters) {
5743    Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
5744    FD->setInvalidDecl(true);
5745    nparams = 3;
5746  }
5747
5748  // FIXME: a lot of the following diagnostics would be improved
5749  // if we had some location information about types.
5750
5751  QualType CharPP =
5752    Context.getPointerType(Context.getPointerType(Context.CharTy));
5753  QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
5754
5755  for (unsigned i = 0; i < nparams; ++i) {
5756    QualType AT = FTP->getArgType(i);
5757
5758    bool mismatch = true;
5759
5760    if (Context.hasSameUnqualifiedType(AT, Expected[i]))
5761      mismatch = false;
5762    else if (Expected[i] == CharPP) {
5763      // As an extension, the following forms are okay:
5764      //   char const **
5765      //   char const * const *
5766      //   char * const *
5767
5768      QualifierCollector qs;
5769      const PointerType* PT;
5770      if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
5771          (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
5772          (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
5773        qs.removeConst();
5774        mismatch = !qs.empty();
5775      }
5776    }
5777
5778    if (mismatch) {
5779      Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
5780      // TODO: suggest replacing given type with expected type
5781      FD->setInvalidDecl(true);
5782    }
5783  }
5784
5785  if (nparams == 1 && !FD->isInvalidDecl()) {
5786    Diag(FD->getLocation(), diag::warn_main_one_arg);
5787  }
5788
5789  if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
5790    Diag(FD->getLocation(), diag::err_main_template_decl);
5791    FD->setInvalidDecl();
5792  }
5793}
5794
5795bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
5796  // FIXME: Need strict checking.  In C89, we need to check for
5797  // any assignment, increment, decrement, function-calls, or
5798  // commas outside of a sizeof.  In C99, it's the same list,
5799  // except that the aforementioned are allowed in unevaluated
5800  // expressions.  Everything else falls under the
5801  // "may accept other forms of constant expressions" exception.
5802  // (We never end up here for C++, so the constant expression
5803  // rules there don't matter.)
5804  if (Init->isConstantInitializer(Context, false))
5805    return false;
5806  Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
5807    << Init->getSourceRange();
5808  return true;
5809}
5810
5811namespace {
5812  // Visits an initialization expression to see if OrigDecl is evaluated in
5813  // its own initialization and throws a warning if it does.
5814  class SelfReferenceChecker
5815      : public EvaluatedExprVisitor<SelfReferenceChecker> {
5816    Sema &S;
5817    Decl *OrigDecl;
5818    bool isRecordType;
5819    bool isPODType;
5820
5821  public:
5822    typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
5823
5824    SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
5825                                                    S(S), OrigDecl(OrigDecl) {
5826      isPODType = false;
5827      isRecordType = false;
5828      if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
5829        isPODType = VD->getType().isPODType(S.Context);
5830        isRecordType = VD->getType()->isRecordType();
5831      }
5832    }
5833
5834    void VisitExpr(Expr *E) {
5835      if (isa<ObjCMessageExpr>(*E)) return;
5836      if (isRecordType) {
5837        Expr *expr = E;
5838        if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5839          ValueDecl *VD = ME->getMemberDecl();
5840          if (isa<EnumConstantDecl>(VD) || isa<VarDecl>(VD)) return;
5841          expr = ME->getBase();
5842        }
5843        if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(expr)) {
5844          HandleDeclRefExpr(DRE);
5845          return;
5846        }
5847      }
5848      Inherited::VisitExpr(E);
5849    }
5850
5851    void VisitMemberExpr(MemberExpr *E) {
5852      if (E->getType()->canDecayToPointerType()) return;
5853      if (isa<FieldDecl>(E->getMemberDecl()))
5854        if (DeclRefExpr *DRE
5855              = dyn_cast<DeclRefExpr>(E->getBase()->IgnoreParenImpCasts())) {
5856          HandleDeclRefExpr(DRE);
5857          return;
5858        }
5859      Inherited::VisitMemberExpr(E);
5860    }
5861
5862    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
5863      if ((!isRecordType &&E->getCastKind() == CK_LValueToRValue) ||
5864          (isRecordType && E->getCastKind() == CK_NoOp)) {
5865        Expr* SubExpr = E->getSubExpr()->IgnoreParenImpCasts();
5866        if (MemberExpr *ME = dyn_cast<MemberExpr>(SubExpr))
5867          SubExpr = ME->getBase()->IgnoreParenImpCasts();
5868        if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
5869          HandleDeclRefExpr(DRE);
5870          return;
5871        }
5872      }
5873      Inherited::VisitImplicitCastExpr(E);
5874    }
5875
5876    void VisitUnaryOperator(UnaryOperator *E) {
5877      // For POD record types, addresses of its own members are well-defined.
5878      if (isRecordType && isPODType) return;
5879      Inherited::VisitUnaryOperator(E);
5880    }
5881
5882    void HandleDeclRefExpr(DeclRefExpr *DRE) {
5883      Decl* ReferenceDecl = DRE->getDecl();
5884      if (OrigDecl != ReferenceDecl) return;
5885      LookupResult Result(S, DRE->getNameInfo(), Sema::LookupOrdinaryName,
5886                          Sema::NotForRedeclaration);
5887      S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
5888                            S.PDiag(diag::warn_uninit_self_reference_in_init)
5889                              << Result.getLookupName()
5890                              << OrigDecl->getLocation()
5891                              << DRE->getSourceRange());
5892    }
5893  };
5894}
5895
5896/// CheckSelfReference - Warns if OrigDecl is used in expression E.
5897void Sema::CheckSelfReference(Decl* OrigDecl, Expr *E) {
5898  SelfReferenceChecker(*this, OrigDecl).VisitExpr(E);
5899}
5900
5901/// AddInitializerToDecl - Adds the initializer Init to the
5902/// declaration dcl. If DirectInit is true, this is C++ direct
5903/// initialization rather than copy initialization.
5904void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
5905                                bool DirectInit, bool TypeMayContainAuto) {
5906  // If there is no declaration, there was an error parsing it.  Just ignore
5907  // the initializer.
5908  if (RealDecl == 0 || RealDecl->isInvalidDecl())
5909    return;
5910
5911  // Check for self-references within variable initializers.
5912  if (VarDecl *vd = dyn_cast<VarDecl>(RealDecl)) {
5913    // Variables declared within a function/method body are handled
5914    // by a dataflow analysis.
5915    if (!vd->hasLocalStorage() && !vd->isStaticLocal())
5916      CheckSelfReference(RealDecl, Init);
5917  }
5918  else {
5919    CheckSelfReference(RealDecl, Init);
5920  }
5921
5922  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
5923    // With declarators parsed the way they are, the parser cannot
5924    // distinguish between a normal initializer and a pure-specifier.
5925    // Thus this grotesque test.
5926    IntegerLiteral *IL;
5927    if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
5928        Context.getCanonicalType(IL->getType()) == Context.IntTy)
5929      CheckPureMethod(Method, Init->getSourceRange());
5930    else {
5931      Diag(Method->getLocation(), diag::err_member_function_initialization)
5932        << Method->getDeclName() << Init->getSourceRange();
5933      Method->setInvalidDecl();
5934    }
5935    return;
5936  }
5937
5938  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5939  if (!VDecl) {
5940    assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
5941    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5942    RealDecl->setInvalidDecl();
5943    return;
5944  }
5945
5946  // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
5947  if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
5948    TypeSourceInfo *DeducedType = 0;
5949    if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
5950      Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
5951        << VDecl->getDeclName() << VDecl->getType() << Init->getType()
5952        << Init->getSourceRange();
5953    if (!DeducedType) {
5954      RealDecl->setInvalidDecl();
5955      return;
5956    }
5957    VDecl->setTypeSourceInfo(DeducedType);
5958    VDecl->setType(DeducedType->getType());
5959
5960    // In ARC, infer lifetime.
5961    if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
5962      VDecl->setInvalidDecl();
5963
5964    // If this is a redeclaration, check that the type we just deduced matches
5965    // the previously declared type.
5966    if (VarDecl *Old = VDecl->getPreviousDeclaration())
5967      MergeVarDeclTypes(VDecl, Old);
5968  }
5969
5970  if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
5971    // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
5972    Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
5973    VDecl->setInvalidDecl();
5974    return;
5975  }
5976
5977
5978  // A definition must end up with a complete type, which means it must be
5979  // complete with the restriction that an array type might be completed by the
5980  // initializer; note that later code assumes this restriction.
5981  QualType BaseDeclType = VDecl->getType();
5982  if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
5983    BaseDeclType = Array->getElementType();
5984  if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
5985                          diag::err_typecheck_decl_incomplete_type)) {
5986    RealDecl->setInvalidDecl();
5987    return;
5988  }
5989
5990  // The variable can not have an abstract class type.
5991  if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5992                             diag::err_abstract_type_in_decl,
5993                             AbstractVariableType))
5994    VDecl->setInvalidDecl();
5995
5996  const VarDecl *Def;
5997  if ((Def = VDecl->getDefinition()) && Def != VDecl) {
5998    Diag(VDecl->getLocation(), diag::err_redefinition)
5999      << VDecl->getDeclName();
6000    Diag(Def->getLocation(), diag::note_previous_definition);
6001    VDecl->setInvalidDecl();
6002    return;
6003  }
6004
6005  const VarDecl* PrevInit = 0;
6006  if (getLangOptions().CPlusPlus) {
6007    // C++ [class.static.data]p4
6008    //   If a static data member is of const integral or const
6009    //   enumeration type, its declaration in the class definition can
6010    //   specify a constant-initializer which shall be an integral
6011    //   constant expression (5.19). In that case, the member can appear
6012    //   in integral constant expressions. The member shall still be
6013    //   defined in a namespace scope if it is used in the program and the
6014    //   namespace scope definition shall not contain an initializer.
6015    //
6016    // We already performed a redefinition check above, but for static
6017    // data members we also need to check whether there was an in-class
6018    // declaration with an initializer.
6019    if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
6020      Diag(VDecl->getLocation(), diag::err_redefinition)
6021        << VDecl->getDeclName();
6022      Diag(PrevInit->getLocation(), diag::note_previous_definition);
6023      return;
6024    }
6025
6026    if (VDecl->hasLocalStorage())
6027      getCurFunction()->setHasBranchProtectedScope();
6028
6029    if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
6030      VDecl->setInvalidDecl();
6031      return;
6032    }
6033  }
6034
6035  // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
6036  // a kernel function cannot be initialized."
6037  if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
6038    Diag(VDecl->getLocation(), diag::err_local_cant_init);
6039    VDecl->setInvalidDecl();
6040    return;
6041  }
6042
6043  // Get the decls type and save a reference for later, since
6044  // CheckInitializerTypes may change it.
6045  QualType DclT = VDecl->getType(), SavT = DclT;
6046
6047  // Perform the initialization.
6048  if (!VDecl->isInvalidDecl()) {
6049    InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6050    InitializationKind Kind
6051      = DirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
6052                                                      Init->getLocStart(),
6053                                                      Init->getLocEnd())
6054                   : InitializationKind::CreateCopy(VDecl->getLocation(),
6055                                                    Init->getLocStart());
6056
6057    InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
6058    ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
6059                                              MultiExprArg(*this, &Init, 1),
6060                                              &DclT);
6061    if (Result.isInvalid()) {
6062      VDecl->setInvalidDecl();
6063      return;
6064    }
6065
6066    Init = Result.takeAs<Expr>();
6067  }
6068
6069  // If the type changed, it means we had an incomplete type that was
6070  // completed by the initializer. For example:
6071  //   int ary[] = { 1, 3, 5 };
6072  // "ary" transitions from a VariableArrayType to a ConstantArrayType.
6073  if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
6074    VDecl->setType(DclT);
6075    Init->setType(DclT.getNonReferenceType());
6076  }
6077
6078  // Check any implicit conversions within the expression.
6079  CheckImplicitConversions(Init, VDecl->getLocation());
6080
6081  if (!VDecl->isInvalidDecl())
6082    checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
6083
6084  Init = MaybeCreateExprWithCleanups(Init);
6085  // Attach the initializer to the decl.
6086  VDecl->setInit(Init);
6087
6088  if (VDecl->isLocalVarDecl()) {
6089    // C99 6.7.8p4: All the expressions in an initializer for an object that has
6090    // static storage duration shall be constant expressions or string literals.
6091    // C++ does not have this restriction.
6092    if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl() &&
6093        VDecl->getStorageClass() == SC_Static)
6094      CheckForConstantInitializer(Init, DclT);
6095  } else if (VDecl->isStaticDataMember() &&
6096             VDecl->getLexicalDeclContext()->isRecord()) {
6097    // This is an in-class initialization for a static data member, e.g.,
6098    //
6099    // struct S {
6100    //   static const int value = 17;
6101    // };
6102
6103    // C++ [class.mem]p4:
6104    //   A member-declarator can contain a constant-initializer only
6105    //   if it declares a static member (9.4) of const integral or
6106    //   const enumeration type, see 9.4.2.
6107    //
6108    // C++11 [class.static.data]p3:
6109    //   If a non-volatile const static data member is of integral or
6110    //   enumeration type, its declaration in the class definition can
6111    //   specify a brace-or-equal-initializer in which every initalizer-clause
6112    //   that is an assignment-expression is a constant expression. A static
6113    //   data member of literal type can be declared in the class definition
6114    //   with the constexpr specifier; if so, its declaration shall specify a
6115    //   brace-or-equal-initializer in which every initializer-clause that is
6116    //   an assignment-expression is a constant expression.
6117
6118    // Do nothing on dependent types.
6119    if (DclT->isDependentType()) {
6120
6121    // Allow any 'static constexpr' members, whether or not they are of literal
6122    // type. We separately check that the initializer is a constant expression,
6123    // which implicitly requires the member to be of literal type.
6124    } else if (VDecl->isConstexpr()) {
6125
6126    // Require constness.
6127    } else if (!DclT.isConstQualified()) {
6128      Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
6129        << Init->getSourceRange();
6130      VDecl->setInvalidDecl();
6131
6132    // We allow integer constant expressions in all cases.
6133    } else if (DclT->isIntegralOrEnumerationType()) {
6134      // Check whether the expression is a constant expression.
6135      SourceLocation Loc;
6136      if (getLangOptions().CPlusPlus0x && DclT.isVolatileQualified())
6137        // In C++11, a non-constexpr const static data member with an
6138        // in-class initializer cannot be volatile.
6139        Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
6140      else if (Init->isValueDependent())
6141        ; // Nothing to check.
6142      else if (Init->isIntegerConstantExpr(Context, &Loc))
6143        ; // Ok, it's an ICE!
6144      else if (Init->isEvaluatable(Context)) {
6145        // If we can constant fold the initializer through heroics, accept it,
6146        // but report this as a use of an extension for -pedantic.
6147        Diag(Loc, diag::ext_in_class_initializer_non_constant)
6148          << Init->getSourceRange();
6149      } else {
6150        // Otherwise, this is some crazy unknown case.  Report the issue at the
6151        // location provided by the isIntegerConstantExpr failed check.
6152        Diag(Loc, diag::err_in_class_initializer_non_constant)
6153          << Init->getSourceRange();
6154        VDecl->setInvalidDecl();
6155      }
6156
6157    // We allow foldable floating-point constants as an extension.
6158    } else if (DclT->isFloatingType()) { // also permits complex, which is ok
6159      Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
6160        << DclT << Init->getSourceRange();
6161      if (getLangOptions().CPlusPlus0x)
6162        Diag(VDecl->getLocation(),
6163             diag::note_in_class_initializer_float_type_constexpr)
6164          << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
6165
6166      if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
6167        Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
6168          << Init->getSourceRange();
6169        VDecl->setInvalidDecl();
6170      }
6171
6172    // Suggest adding 'constexpr' in C++11 for literal types.
6173    } else if (getLangOptions().CPlusPlus0x && DclT->isLiteralType()) {
6174      Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
6175        << DclT << Init->getSourceRange()
6176        << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
6177      VDecl->setConstexpr(true);
6178
6179    } else {
6180      Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
6181        << DclT << Init->getSourceRange();
6182      VDecl->setInvalidDecl();
6183    }
6184  } else if (VDecl->isFileVarDecl()) {
6185    if (VDecl->getStorageClassAsWritten() == SC_Extern &&
6186        (!getLangOptions().CPlusPlus ||
6187         !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
6188      Diag(VDecl->getLocation(), diag::warn_extern_init);
6189
6190    // C99 6.7.8p4. All file scoped initializers need to be constant.
6191    if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl())
6192      CheckForConstantInitializer(Init, DclT);
6193  }
6194
6195  CheckCompleteVariableDeclaration(VDecl);
6196}
6197
6198/// ActOnInitializerError - Given that there was an error parsing an
6199/// initializer for the given declaration, try to return to some form
6200/// of sanity.
6201void Sema::ActOnInitializerError(Decl *D) {
6202  // Our main concern here is re-establishing invariants like "a
6203  // variable's type is either dependent or complete".
6204  if (!D || D->isInvalidDecl()) return;
6205
6206  VarDecl *VD = dyn_cast<VarDecl>(D);
6207  if (!VD) return;
6208
6209  // Auto types are meaningless if we can't make sense of the initializer.
6210  if (ParsingInitForAutoVars.count(D)) {
6211    D->setInvalidDecl();
6212    return;
6213  }
6214
6215  QualType Ty = VD->getType();
6216  if (Ty->isDependentType()) return;
6217
6218  // Require a complete type.
6219  if (RequireCompleteType(VD->getLocation(),
6220                          Context.getBaseElementType(Ty),
6221                          diag::err_typecheck_decl_incomplete_type)) {
6222    VD->setInvalidDecl();
6223    return;
6224  }
6225
6226  // Require an abstract type.
6227  if (RequireNonAbstractType(VD->getLocation(), Ty,
6228                             diag::err_abstract_type_in_decl,
6229                             AbstractVariableType)) {
6230    VD->setInvalidDecl();
6231    return;
6232  }
6233
6234  // Don't bother complaining about constructors or destructors,
6235  // though.
6236}
6237
6238void Sema::ActOnUninitializedDecl(Decl *RealDecl,
6239                                  bool TypeMayContainAuto) {
6240  // If there is no declaration, there was an error parsing it. Just ignore it.
6241  if (RealDecl == 0)
6242    return;
6243
6244  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
6245    QualType Type = Var->getType();
6246
6247    // C++0x [dcl.spec.auto]p3
6248    if (TypeMayContainAuto && Type->getContainedAutoType()) {
6249      Diag(Var->getLocation(), diag::err_auto_var_requires_init)
6250        << Var->getDeclName() << Type;
6251      Var->setInvalidDecl();
6252      return;
6253    }
6254
6255    // C++0x [class.static.data]p3: A static data member can be declared with
6256    // the constexpr specifier; if so, its declaration shall specify
6257    // a brace-or-equal-initializer.
6258    if (Var->isConstexpr() && Var->isStaticDataMember() &&
6259        !Var->isThisDeclarationADefinition()) {
6260      Diag(Var->getLocation(), diag::err_constexpr_static_mem_var_requires_init)
6261        << Var->getDeclName();
6262      Var->setInvalidDecl();
6263      return;
6264    }
6265
6266    switch (Var->isThisDeclarationADefinition()) {
6267    case VarDecl::Definition:
6268      if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
6269        break;
6270
6271      // We have an out-of-line definition of a static data member
6272      // that has an in-class initializer, so we type-check this like
6273      // a declaration.
6274      //
6275      // Fall through
6276
6277    case VarDecl::DeclarationOnly:
6278      // It's only a declaration.
6279
6280      // Block scope. C99 6.7p7: If an identifier for an object is
6281      // declared with no linkage (C99 6.2.2p6), the type for the
6282      // object shall be complete.
6283      if (!Type->isDependentType() && Var->isLocalVarDecl() &&
6284          !Var->getLinkage() && !Var->isInvalidDecl() &&
6285          RequireCompleteType(Var->getLocation(), Type,
6286                              diag::err_typecheck_decl_incomplete_type))
6287        Var->setInvalidDecl();
6288
6289      // Make sure that the type is not abstract.
6290      if (!Type->isDependentType() && !Var->isInvalidDecl() &&
6291          RequireNonAbstractType(Var->getLocation(), Type,
6292                                 diag::err_abstract_type_in_decl,
6293                                 AbstractVariableType))
6294        Var->setInvalidDecl();
6295      return;
6296
6297    case VarDecl::TentativeDefinition:
6298      // File scope. C99 6.9.2p2: A declaration of an identifier for an
6299      // object that has file scope without an initializer, and without a
6300      // storage-class specifier or with the storage-class specifier "static",
6301      // constitutes a tentative definition. Note: A tentative definition with
6302      // external linkage is valid (C99 6.2.2p5).
6303      if (!Var->isInvalidDecl()) {
6304        if (const IncompleteArrayType *ArrayT
6305                                    = Context.getAsIncompleteArrayType(Type)) {
6306          if (RequireCompleteType(Var->getLocation(),
6307                                  ArrayT->getElementType(),
6308                                  diag::err_illegal_decl_array_incomplete_type))
6309            Var->setInvalidDecl();
6310        } else if (Var->getStorageClass() == SC_Static) {
6311          // C99 6.9.2p3: If the declaration of an identifier for an object is
6312          // a tentative definition and has internal linkage (C99 6.2.2p3), the
6313          // declared type shall not be an incomplete type.
6314          // NOTE: code such as the following
6315          //     static struct s;
6316          //     struct s { int a; };
6317          // is accepted by gcc. Hence here we issue a warning instead of
6318          // an error and we do not invalidate the static declaration.
6319          // NOTE: to avoid multiple warnings, only check the first declaration.
6320          if (Var->getPreviousDeclaration() == 0)
6321            RequireCompleteType(Var->getLocation(), Type,
6322                                diag::ext_typecheck_decl_incomplete_type);
6323        }
6324      }
6325
6326      // Record the tentative definition; we're done.
6327      if (!Var->isInvalidDecl())
6328        TentativeDefinitions.push_back(Var);
6329      return;
6330    }
6331
6332    // Provide a specific diagnostic for uninitialized variable
6333    // definitions with incomplete array type.
6334    if (Type->isIncompleteArrayType()) {
6335      Diag(Var->getLocation(),
6336           diag::err_typecheck_incomplete_array_needs_initializer);
6337      Var->setInvalidDecl();
6338      return;
6339    }
6340
6341    // Provide a specific diagnostic for uninitialized variable
6342    // definitions with reference type.
6343    if (Type->isReferenceType()) {
6344      Diag(Var->getLocation(), diag::err_reference_var_requires_init)
6345        << Var->getDeclName()
6346        << SourceRange(Var->getLocation(), Var->getLocation());
6347      Var->setInvalidDecl();
6348      return;
6349    }
6350
6351    // Do not attempt to type-check the default initializer for a
6352    // variable with dependent type.
6353    if (Type->isDependentType())
6354      return;
6355
6356    if (Var->isInvalidDecl())
6357      return;
6358
6359    if (RequireCompleteType(Var->getLocation(),
6360                            Context.getBaseElementType(Type),
6361                            diag::err_typecheck_decl_incomplete_type)) {
6362      Var->setInvalidDecl();
6363      return;
6364    }
6365
6366    // The variable can not have an abstract class type.
6367    if (RequireNonAbstractType(Var->getLocation(), Type,
6368                               diag::err_abstract_type_in_decl,
6369                               AbstractVariableType)) {
6370      Var->setInvalidDecl();
6371      return;
6372    }
6373
6374    // Check for jumps past the implicit initializer.  C++0x
6375    // clarifies that this applies to a "variable with automatic
6376    // storage duration", not a "local variable".
6377    // C++11 [stmt.dcl]p3
6378    //   A program that jumps from a point where a variable with automatic
6379    //   storage duration is not in scope to a point where it is in scope is
6380    //   ill-formed unless the variable has scalar type, class type with a
6381    //   trivial default constructor and a trivial destructor, a cv-qualified
6382    //   version of one of these types, or an array of one of the preceding
6383    //   types and is declared without an initializer.
6384    if (getLangOptions().CPlusPlus && Var->hasLocalStorage()) {
6385      if (const RecordType *Record
6386            = Context.getBaseElementType(Type)->getAs<RecordType>()) {
6387        CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
6388        // Mark the function for further checking even if the looser rules of
6389        // C++11 do not require such checks, so that we can diagnose
6390        // incompatibilities with C++98.
6391        if (!CXXRecord->isPOD())
6392          getCurFunction()->setHasBranchProtectedScope();
6393      }
6394    }
6395
6396    // C++03 [dcl.init]p9:
6397    //   If no initializer is specified for an object, and the
6398    //   object is of (possibly cv-qualified) non-POD class type (or
6399    //   array thereof), the object shall be default-initialized; if
6400    //   the object is of const-qualified type, the underlying class
6401    //   type shall have a user-declared default
6402    //   constructor. Otherwise, if no initializer is specified for
6403    //   a non- static object, the object and its subobjects, if
6404    //   any, have an indeterminate initial value); if the object
6405    //   or any of its subobjects are of const-qualified type, the
6406    //   program is ill-formed.
6407    // C++0x [dcl.init]p11:
6408    //   If no initializer is specified for an object, the object is
6409    //   default-initialized; [...].
6410    InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
6411    InitializationKind Kind
6412      = InitializationKind::CreateDefault(Var->getLocation());
6413
6414    InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
6415    ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
6416                                      MultiExprArg(*this, 0, 0));
6417    if (Init.isInvalid())
6418      Var->setInvalidDecl();
6419    else if (Init.get())
6420      Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
6421
6422    CheckCompleteVariableDeclaration(Var);
6423  }
6424}
6425
6426void Sema::ActOnCXXForRangeDecl(Decl *D) {
6427  VarDecl *VD = dyn_cast<VarDecl>(D);
6428  if (!VD) {
6429    Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
6430    D->setInvalidDecl();
6431    return;
6432  }
6433
6434  VD->setCXXForRangeDecl(true);
6435
6436  // for-range-declaration cannot be given a storage class specifier.
6437  int Error = -1;
6438  switch (VD->getStorageClassAsWritten()) {
6439  case SC_None:
6440    break;
6441  case SC_Extern:
6442    Error = 0;
6443    break;
6444  case SC_Static:
6445    Error = 1;
6446    break;
6447  case SC_PrivateExtern:
6448    Error = 2;
6449    break;
6450  case SC_Auto:
6451    Error = 3;
6452    break;
6453  case SC_Register:
6454    Error = 4;
6455    break;
6456  case SC_OpenCLWorkGroupLocal:
6457    llvm_unreachable("Unexpected storage class");
6458  }
6459  if (VD->isConstexpr())
6460    Error = 5;
6461  if (Error != -1) {
6462    Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
6463      << VD->getDeclName() << Error;
6464    D->setInvalidDecl();
6465  }
6466}
6467
6468void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
6469  if (var->isInvalidDecl()) return;
6470
6471  // In ARC, don't allow jumps past the implicit initialization of a
6472  // local retaining variable.
6473  if (getLangOptions().ObjCAutoRefCount &&
6474      var->hasLocalStorage()) {
6475    switch (var->getType().getObjCLifetime()) {
6476    case Qualifiers::OCL_None:
6477    case Qualifiers::OCL_ExplicitNone:
6478    case Qualifiers::OCL_Autoreleasing:
6479      break;
6480
6481    case Qualifiers::OCL_Weak:
6482    case Qualifiers::OCL_Strong:
6483      getCurFunction()->setHasBranchProtectedScope();
6484      break;
6485    }
6486  }
6487
6488  // All the following checks are C++ only.
6489  if (!getLangOptions().CPlusPlus) return;
6490
6491  QualType baseType = Context.getBaseElementType(var->getType());
6492  if (baseType->isDependentType()) return;
6493
6494  // __block variables might require us to capture a copy-initializer.
6495  if (var->hasAttr<BlocksAttr>()) {
6496    // It's currently invalid to ever have a __block variable with an
6497    // array type; should we diagnose that here?
6498
6499    // Regardless, we don't want to ignore array nesting when
6500    // constructing this copy.
6501    QualType type = var->getType();
6502
6503    if (type->isStructureOrClassType()) {
6504      SourceLocation poi = var->getLocation();
6505      Expr *varRef = new (Context) DeclRefExpr(var, type, VK_LValue, poi);
6506      ExprResult result =
6507        PerformCopyInitialization(
6508                        InitializedEntity::InitializeBlock(poi, type, false),
6509                                  poi, Owned(varRef));
6510      if (!result.isInvalid()) {
6511        result = MaybeCreateExprWithCleanups(result);
6512        Expr *init = result.takeAs<Expr>();
6513        Context.setBlockVarCopyInits(var, init);
6514      }
6515    }
6516  }
6517
6518  Expr *Init = var->getInit();
6519  bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
6520
6521  if (!var->getDeclContext()->isDependentContext() && Init) {
6522    if (IsGlobal && !var->isConstexpr() &&
6523        getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
6524                                            var->getLocation())
6525          != DiagnosticsEngine::Ignored &&
6526        !Init->isConstantInitializer(Context, baseType->isReferenceType()))
6527      Diag(var->getLocation(), diag::warn_global_constructor)
6528        << Init->getSourceRange();
6529
6530    if (var->isConstexpr()) {
6531      llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
6532      if (!var->evaluateValue(Notes) || !var->isInitICE()) {
6533        SourceLocation DiagLoc = var->getLocation();
6534        // If the note doesn't add any useful information other than a source
6535        // location, fold it into the primary diagnostic.
6536        if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6537              diag::note_invalid_subexpr_in_const_expr) {
6538          DiagLoc = Notes[0].first;
6539          Notes.clear();
6540        }
6541        Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
6542          << var << Init->getSourceRange();
6543        for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6544          Diag(Notes[I].first, Notes[I].second);
6545      }
6546    } else if (var->isUsableInConstantExpressions()) {
6547      // Check whether the initializer of a const variable of integral or
6548      // enumeration type is an ICE now, since we can't tell whether it was
6549      // initialized by a constant expression if we check later.
6550      var->checkInitIsICE();
6551    }
6552  }
6553
6554  // Require the destructor.
6555  if (const RecordType *recordType = baseType->getAs<RecordType>())
6556    FinalizeVarWithDestructor(var, recordType);
6557}
6558
6559/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
6560/// any semantic actions necessary after any initializer has been attached.
6561void
6562Sema::FinalizeDeclaration(Decl *ThisDecl) {
6563  // Note that we are no longer parsing the initializer for this declaration.
6564  ParsingInitForAutoVars.erase(ThisDecl);
6565}
6566
6567Sema::DeclGroupPtrTy
6568Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
6569                              Decl **Group, unsigned NumDecls) {
6570  SmallVector<Decl*, 8> Decls;
6571
6572  if (DS.isTypeSpecOwned())
6573    Decls.push_back(DS.getRepAsDecl());
6574
6575  for (unsigned i = 0; i != NumDecls; ++i)
6576    if (Decl *D = Group[i])
6577      Decls.push_back(D);
6578
6579  return BuildDeclaratorGroup(Decls.data(), Decls.size(),
6580                              DS.getTypeSpecType() == DeclSpec::TST_auto);
6581}
6582
6583/// BuildDeclaratorGroup - convert a list of declarations into a declaration
6584/// group, performing any necessary semantic checking.
6585Sema::DeclGroupPtrTy
6586Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
6587                           bool TypeMayContainAuto) {
6588  // C++0x [dcl.spec.auto]p7:
6589  //   If the type deduced for the template parameter U is not the same in each
6590  //   deduction, the program is ill-formed.
6591  // FIXME: When initializer-list support is added, a distinction is needed
6592  // between the deduced type U and the deduced type which 'auto' stands for.
6593  //   auto a = 0, b = { 1, 2, 3 };
6594  // is legal because the deduced type U is 'int' in both cases.
6595  if (TypeMayContainAuto && NumDecls > 1) {
6596    QualType Deduced;
6597    CanQualType DeducedCanon;
6598    VarDecl *DeducedDecl = 0;
6599    for (unsigned i = 0; i != NumDecls; ++i) {
6600      if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
6601        AutoType *AT = D->getType()->getContainedAutoType();
6602        // Don't reissue diagnostics when instantiating a template.
6603        if (AT && D->isInvalidDecl())
6604          break;
6605        if (AT && AT->isDeduced()) {
6606          QualType U = AT->getDeducedType();
6607          CanQualType UCanon = Context.getCanonicalType(U);
6608          if (Deduced.isNull()) {
6609            Deduced = U;
6610            DeducedCanon = UCanon;
6611            DeducedDecl = D;
6612          } else if (DeducedCanon != UCanon) {
6613            Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
6614                 diag::err_auto_different_deductions)
6615              << Deduced << DeducedDecl->getDeclName()
6616              << U << D->getDeclName()
6617              << DeducedDecl->getInit()->getSourceRange()
6618              << D->getInit()->getSourceRange();
6619            D->setInvalidDecl();
6620            break;
6621          }
6622        }
6623      }
6624    }
6625  }
6626
6627  return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls));
6628}
6629
6630
6631/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
6632/// to introduce parameters into function prototype scope.
6633Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
6634  const DeclSpec &DS = D.getDeclSpec();
6635
6636  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
6637  // C++03 [dcl.stc]p2 also permits 'auto'.
6638  VarDecl::StorageClass StorageClass = SC_None;
6639  VarDecl::StorageClass StorageClassAsWritten = SC_None;
6640  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
6641    StorageClass = SC_Register;
6642    StorageClassAsWritten = SC_Register;
6643  } else if (getLangOptions().CPlusPlus &&
6644             DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
6645    StorageClass = SC_Auto;
6646    StorageClassAsWritten = SC_Auto;
6647  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
6648    Diag(DS.getStorageClassSpecLoc(),
6649         diag::err_invalid_storage_class_in_func_decl);
6650    D.getMutableDeclSpec().ClearStorageClassSpecs();
6651  }
6652
6653  if (D.getDeclSpec().isThreadSpecified())
6654    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
6655  if (D.getDeclSpec().isConstexprSpecified())
6656    Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6657      << 0;
6658
6659  DiagnoseFunctionSpecifiers(D);
6660
6661  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6662  QualType parmDeclType = TInfo->getType();
6663
6664  if (getLangOptions().CPlusPlus) {
6665    // Check that there are no default arguments inside the type of this
6666    // parameter.
6667    CheckExtraCXXDefaultArguments(D);
6668
6669    // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
6670    if (D.getCXXScopeSpec().isSet()) {
6671      Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
6672        << D.getCXXScopeSpec().getRange();
6673      D.getCXXScopeSpec().clear();
6674    }
6675  }
6676
6677  // Ensure we have a valid name
6678  IdentifierInfo *II = 0;
6679  if (D.hasName()) {
6680    II = D.getIdentifier();
6681    if (!II) {
6682      Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
6683        << GetNameForDeclarator(D).getName().getAsString();
6684      D.setInvalidType(true);
6685    }
6686  }
6687
6688  // Check for redeclaration of parameters, e.g. int foo(int x, int x);
6689  if (II) {
6690    LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
6691                   ForRedeclaration);
6692    LookupName(R, S);
6693    if (R.isSingleResult()) {
6694      NamedDecl *PrevDecl = R.getFoundDecl();
6695      if (PrevDecl->isTemplateParameter()) {
6696        // Maybe we will complain about the shadowed template parameter.
6697        DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
6698        // Just pretend that we didn't see the previous declaration.
6699        PrevDecl = 0;
6700      } else if (S->isDeclScope(PrevDecl)) {
6701        Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
6702        Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
6703
6704        // Recover by removing the name
6705        II = 0;
6706        D.SetIdentifier(0, D.getIdentifierLoc());
6707        D.setInvalidType(true);
6708      }
6709    }
6710  }
6711
6712  // Temporarily put parameter variables in the translation unit, not
6713  // the enclosing context.  This prevents them from accidentally
6714  // looking like class members in C++.
6715  ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
6716                                    D.getSourceRange().getBegin(),
6717                                    D.getIdentifierLoc(), II,
6718                                    parmDeclType, TInfo,
6719                                    StorageClass, StorageClassAsWritten);
6720
6721  if (D.isInvalidType())
6722    New->setInvalidDecl();
6723
6724  assert(S->isFunctionPrototypeScope());
6725  assert(S->getFunctionPrototypeDepth() >= 1);
6726  New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
6727                    S->getNextFunctionPrototypeIndex());
6728
6729  // Add the parameter declaration into this scope.
6730  S->AddDecl(New);
6731  if (II)
6732    IdResolver.AddDecl(New);
6733
6734  ProcessDeclAttributes(S, New, D);
6735
6736  if (D.getDeclSpec().isModulePrivateSpecified())
6737    Diag(New->getLocation(), diag::err_module_private_local)
6738      << 1 << New->getDeclName()
6739      << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6740      << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6741
6742  if (New->hasAttr<BlocksAttr>()) {
6743    Diag(New->getLocation(), diag::err_block_on_nonlocal);
6744  }
6745  return New;
6746}
6747
6748/// \brief Synthesizes a variable for a parameter arising from a
6749/// typedef.
6750ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
6751                                              SourceLocation Loc,
6752                                              QualType T) {
6753  /* FIXME: setting StartLoc == Loc.
6754     Would it be worth to modify callers so as to provide proper source
6755     location for the unnamed parameters, embedding the parameter's type? */
6756  ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
6757                                T, Context.getTrivialTypeSourceInfo(T, Loc),
6758                                           SC_None, SC_None, 0);
6759  Param->setImplicit();
6760  return Param;
6761}
6762
6763void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
6764                                    ParmVarDecl * const *ParamEnd) {
6765  // Don't diagnose unused-parameter errors in template instantiations; we
6766  // will already have done so in the template itself.
6767  if (!ActiveTemplateInstantiations.empty())
6768    return;
6769
6770  for (; Param != ParamEnd; ++Param) {
6771    if (!(*Param)->isUsed() && (*Param)->getDeclName() &&
6772        !(*Param)->hasAttr<UnusedAttr>()) {
6773      Diag((*Param)->getLocation(), diag::warn_unused_parameter)
6774        << (*Param)->getDeclName();
6775    }
6776  }
6777}
6778
6779void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
6780                                                  ParmVarDecl * const *ParamEnd,
6781                                                  QualType ReturnTy,
6782                                                  NamedDecl *D) {
6783  if (LangOpts.NumLargeByValueCopy == 0) // No check.
6784    return;
6785
6786  // Warn if the return value is pass-by-value and larger than the specified
6787  // threshold.
6788  if (ReturnTy.isPODType(Context)) {
6789    unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
6790    if (Size > LangOpts.NumLargeByValueCopy)
6791      Diag(D->getLocation(), diag::warn_return_value_size)
6792          << D->getDeclName() << Size;
6793  }
6794
6795  // Warn if any parameter is pass-by-value and larger than the specified
6796  // threshold.
6797  for (; Param != ParamEnd; ++Param) {
6798    QualType T = (*Param)->getType();
6799    if (!T.isPODType(Context))
6800      continue;
6801    unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
6802    if (Size > LangOpts.NumLargeByValueCopy)
6803      Diag((*Param)->getLocation(), diag::warn_parameter_size)
6804          << (*Param)->getDeclName() << Size;
6805  }
6806}
6807
6808ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
6809                                  SourceLocation NameLoc, IdentifierInfo *Name,
6810                                  QualType T, TypeSourceInfo *TSInfo,
6811                                  VarDecl::StorageClass StorageClass,
6812                                  VarDecl::StorageClass StorageClassAsWritten) {
6813  // In ARC, infer a lifetime qualifier for appropriate parameter types.
6814  if (getLangOptions().ObjCAutoRefCount &&
6815      T.getObjCLifetime() == Qualifiers::OCL_None &&
6816      T->isObjCLifetimeType()) {
6817
6818    Qualifiers::ObjCLifetime lifetime;
6819
6820    // Special cases for arrays:
6821    //   - if it's const, use __unsafe_unretained
6822    //   - otherwise, it's an error
6823    if (T->isArrayType()) {
6824      if (!T.isConstQualified()) {
6825        DelayedDiagnostics.add(
6826            sema::DelayedDiagnostic::makeForbiddenType(
6827            NameLoc, diag::err_arc_array_param_no_ownership, T, false));
6828      }
6829      lifetime = Qualifiers::OCL_ExplicitNone;
6830    } else {
6831      lifetime = T->getObjCARCImplicitLifetime();
6832    }
6833    T = Context.getLifetimeQualifiedType(T, lifetime);
6834  }
6835
6836  ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
6837                                         Context.getAdjustedParameterType(T),
6838                                         TSInfo,
6839                                         StorageClass, StorageClassAsWritten,
6840                                         0);
6841
6842  // Parameters can not be abstract class types.
6843  // For record types, this is done by the AbstractClassUsageDiagnoser once
6844  // the class has been completely parsed.
6845  if (!CurContext->isRecord() &&
6846      RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
6847                             AbstractParamType))
6848    New->setInvalidDecl();
6849
6850  // Parameter declarators cannot be interface types. All ObjC objects are
6851  // passed by reference.
6852  if (T->isObjCObjectType()) {
6853    Diag(NameLoc,
6854         diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
6855      << FixItHint::CreateInsertion(NameLoc, "*");
6856    T = Context.getObjCObjectPointerType(T);
6857    New->setType(T);
6858  }
6859
6860  // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
6861  // duration shall not be qualified by an address-space qualifier."
6862  // Since all parameters have automatic store duration, they can not have
6863  // an address space.
6864  if (T.getAddressSpace() != 0) {
6865    Diag(NameLoc, diag::err_arg_with_address_space);
6866    New->setInvalidDecl();
6867  }
6868
6869  return New;
6870}
6871
6872void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
6873                                           SourceLocation LocAfterDecls) {
6874  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6875
6876  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
6877  // for a K&R function.
6878  if (!FTI.hasPrototype) {
6879    for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
6880      --i;
6881      if (FTI.ArgInfo[i].Param == 0) {
6882        llvm::SmallString<256> Code;
6883        llvm::raw_svector_ostream(Code) << "  int "
6884                                        << FTI.ArgInfo[i].Ident->getName()
6885                                        << ";\n";
6886        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
6887          << FTI.ArgInfo[i].Ident
6888          << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
6889
6890        // Implicitly declare the argument as type 'int' for lack of a better
6891        // type.
6892        AttributeFactory attrs;
6893        DeclSpec DS(attrs);
6894        const char* PrevSpec; // unused
6895        unsigned DiagID; // unused
6896        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
6897                           PrevSpec, DiagID);
6898        Declarator ParamD(DS, Declarator::KNRTypeListContext);
6899        ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
6900        FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
6901      }
6902    }
6903  }
6904}
6905
6906Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
6907                                         Declarator &D) {
6908  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
6909  assert(D.isFunctionDeclarator() && "Not a function declarator!");
6910  Scope *ParentScope = FnBodyScope->getParent();
6911
6912  D.setFunctionDefinitionKind(FDK_Definition);
6913  Decl *DP = HandleDeclarator(ParentScope, D,
6914                              MultiTemplateParamsArg(*this));
6915  return ActOnStartOfFunctionDef(FnBodyScope, DP);
6916}
6917
6918static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
6919  // Don't warn about invalid declarations.
6920  if (FD->isInvalidDecl())
6921    return false;
6922
6923  // Or declarations that aren't global.
6924  if (!FD->isGlobal())
6925    return false;
6926
6927  // Don't warn about C++ member functions.
6928  if (isa<CXXMethodDecl>(FD))
6929    return false;
6930
6931  // Don't warn about 'main'.
6932  if (FD->isMain())
6933    return false;
6934
6935  // Don't warn about inline functions.
6936  if (FD->isInlined())
6937    return false;
6938
6939  // Don't warn about function templates.
6940  if (FD->getDescribedFunctionTemplate())
6941    return false;
6942
6943  // Don't warn about function template specializations.
6944  if (FD->isFunctionTemplateSpecialization())
6945    return false;
6946
6947  bool MissingPrototype = true;
6948  for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
6949       Prev; Prev = Prev->getPreviousDeclaration()) {
6950    // Ignore any declarations that occur in function or method
6951    // scope, because they aren't visible from the header.
6952    if (Prev->getDeclContext()->isFunctionOrMethod())
6953      continue;
6954
6955    MissingPrototype = !Prev->getType()->isFunctionProtoType();
6956    break;
6957  }
6958
6959  return MissingPrototype;
6960}
6961
6962void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) {
6963  // Don't complain if we're in GNU89 mode and the previous definition
6964  // was an extern inline function.
6965  const FunctionDecl *Definition;
6966  if (FD->isDefined(Definition) &&
6967      !canRedefineFunction(Definition, getLangOptions())) {
6968    if (getLangOptions().GNUMode && Definition->isInlineSpecified() &&
6969        Definition->getStorageClass() == SC_Extern)
6970      Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
6971        << FD->getDeclName() << getLangOptions().CPlusPlus;
6972    else
6973      Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
6974    Diag(Definition->getLocation(), diag::note_previous_definition);
6975  }
6976}
6977
6978Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
6979  // Clear the last template instantiation error context.
6980  LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
6981
6982  if (!D)
6983    return D;
6984  FunctionDecl *FD = 0;
6985
6986  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
6987    FD = FunTmpl->getTemplatedDecl();
6988  else
6989    FD = cast<FunctionDecl>(D);
6990
6991  // Enter a new function scope
6992  PushFunctionScope();
6993
6994  // See if this is a redefinition.
6995  if (!FD->isLateTemplateParsed())
6996    CheckForFunctionRedefinition(FD);
6997
6998  // Builtin functions cannot be defined.
6999  if (unsigned BuiltinID = FD->getBuiltinID()) {
7000    if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
7001      Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
7002      FD->setInvalidDecl();
7003    }
7004  }
7005
7006  // The return type of a function definition must be complete
7007  // (C99 6.9.1p3, C++ [dcl.fct]p6).
7008  QualType ResultType = FD->getResultType();
7009  if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
7010      !FD->isInvalidDecl() &&
7011      RequireCompleteType(FD->getLocation(), ResultType,
7012                          diag::err_func_def_incomplete_result))
7013    FD->setInvalidDecl();
7014
7015  // GNU warning -Wmissing-prototypes:
7016  //   Warn if a global function is defined without a previous
7017  //   prototype declaration. This warning is issued even if the
7018  //   definition itself provides a prototype. The aim is to detect
7019  //   global functions that fail to be declared in header files.
7020  if (ShouldWarnAboutMissingPrototype(FD))
7021    Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
7022
7023  if (FnBodyScope)
7024    PushDeclContext(FnBodyScope, FD);
7025
7026  // Check the validity of our function parameters
7027  CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
7028                           /*CheckParameterNames=*/true);
7029
7030  // Introduce our parameters into the function scope
7031  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
7032    ParmVarDecl *Param = FD->getParamDecl(p);
7033    Param->setOwningFunction(FD);
7034
7035    // If this has an identifier, add it to the scope stack.
7036    if (Param->getIdentifier() && FnBodyScope) {
7037      CheckShadow(FnBodyScope, Param);
7038
7039      PushOnScopeChains(Param, FnBodyScope);
7040    }
7041  }
7042
7043  // Checking attributes of current function definition
7044  // dllimport attribute.
7045  DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
7046  if (DA && (!FD->getAttr<DLLExportAttr>())) {
7047    // dllimport attribute cannot be directly applied to definition.
7048    // Microsoft accepts dllimport for functions defined within class scope.
7049    if (!DA->isInherited() &&
7050        !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
7051      Diag(FD->getLocation(),
7052           diag::err_attribute_can_be_applied_only_to_symbol_declaration)
7053        << "dllimport";
7054      FD->setInvalidDecl();
7055      return FD;
7056    }
7057
7058    // Visual C++ appears to not think this is an issue, so only issue
7059    // a warning when Microsoft extensions are disabled.
7060    if (!LangOpts.MicrosoftExt) {
7061      // If a symbol previously declared dllimport is later defined, the
7062      // attribute is ignored in subsequent references, and a warning is
7063      // emitted.
7064      Diag(FD->getLocation(),
7065           diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7066        << FD->getName() << "dllimport";
7067    }
7068  }
7069  return FD;
7070}
7071
7072/// \brief Given the set of return statements within a function body,
7073/// compute the variables that are subject to the named return value
7074/// optimization.
7075///
7076/// Each of the variables that is subject to the named return value
7077/// optimization will be marked as NRVO variables in the AST, and any
7078/// return statement that has a marked NRVO variable as its NRVO candidate can
7079/// use the named return value optimization.
7080///
7081/// This function applies a very simplistic algorithm for NRVO: if every return
7082/// statement in the function has the same NRVO candidate, that candidate is
7083/// the NRVO variable.
7084///
7085/// FIXME: Employ a smarter algorithm that accounts for multiple return
7086/// statements and the lifetimes of the NRVO candidates. We should be able to
7087/// find a maximal set of NRVO variables.
7088void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
7089  ReturnStmt **Returns = Scope->Returns.data();
7090
7091  const VarDecl *NRVOCandidate = 0;
7092  for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
7093    if (!Returns[I]->getNRVOCandidate())
7094      return;
7095
7096    if (!NRVOCandidate)
7097      NRVOCandidate = Returns[I]->getNRVOCandidate();
7098    else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
7099      return;
7100  }
7101
7102  if (NRVOCandidate)
7103    const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
7104}
7105
7106Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
7107  return ActOnFinishFunctionBody(D, move(BodyArg), false);
7108}
7109
7110Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
7111                                    bool IsInstantiation) {
7112  FunctionDecl *FD = 0;
7113  FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
7114  if (FunTmpl)
7115    FD = FunTmpl->getTemplatedDecl();
7116  else
7117    FD = dyn_cast_or_null<FunctionDecl>(dcl);
7118
7119  sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
7120  sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
7121
7122  if (FD) {
7123    FD->setBody(Body);
7124    if (FD->isMain()) {
7125      // C and C++ allow for main to automagically return 0.
7126      // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7127      FD->setHasImplicitReturnZero(true);
7128      WP.disableCheckFallThrough();
7129    } else if (FD->hasAttr<NakedAttr>()) {
7130      // If the function is marked 'naked', don't complain about missing return
7131      // statements.
7132      WP.disableCheckFallThrough();
7133    }
7134
7135    // MSVC permits the use of pure specifier (=0) on function definition,
7136    // defined at class scope, warn about this non standard construct.
7137    if (getLangOptions().MicrosoftExt && FD->isPure())
7138      Diag(FD->getLocation(), diag::warn_pure_function_definition);
7139
7140    if (!FD->isInvalidDecl()) {
7141      DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
7142      DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
7143                                             FD->getResultType(), FD);
7144
7145      // If this is a constructor, we need a vtable.
7146      if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
7147        MarkVTableUsed(FD->getLocation(), Constructor->getParent());
7148
7149      computeNRVO(Body, getCurFunction());
7150    }
7151
7152    assert(FD == getCurFunctionDecl() && "Function parsing confused");
7153  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
7154    assert(MD == getCurMethodDecl() && "Method parsing confused");
7155    MD->setBody(Body);
7156    if (Body)
7157      MD->setEndLoc(Body->getLocEnd());
7158    if (!MD->isInvalidDecl()) {
7159      DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
7160      DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
7161                                             MD->getResultType(), MD);
7162
7163      if (Body)
7164        computeNRVO(Body, getCurFunction());
7165    }
7166    if (ObjCShouldCallSuperDealloc) {
7167      Diag(MD->getLocEnd(), diag::warn_objc_missing_super_dealloc);
7168      ObjCShouldCallSuperDealloc = false;
7169    }
7170    if (ObjCShouldCallSuperFinalize) {
7171      Diag(MD->getLocEnd(), diag::warn_objc_missing_super_finalize);
7172      ObjCShouldCallSuperFinalize = false;
7173    }
7174  } else {
7175    return 0;
7176  }
7177
7178  assert(!ObjCShouldCallSuperDealloc && "This should only be set for "
7179         "ObjC methods, which should have been handled in the block above.");
7180  assert(!ObjCShouldCallSuperFinalize && "This should only be set for "
7181         "ObjC methods, which should have been handled in the block above.");
7182
7183  // Verify and clean out per-function state.
7184  if (Body) {
7185    // C++ constructors that have function-try-blocks can't have return
7186    // statements in the handlers of that block. (C++ [except.handle]p14)
7187    // Verify this.
7188    if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
7189      DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
7190
7191    // Verify that gotos and switch cases don't jump into scopes illegally.
7192    if (getCurFunction()->NeedsScopeChecking() &&
7193        !dcl->isInvalidDecl() &&
7194        !hasAnyUnrecoverableErrorsInThisFunction())
7195      DiagnoseInvalidJumps(Body);
7196
7197    if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
7198      if (!Destructor->getParent()->isDependentType())
7199        CheckDestructor(Destructor);
7200
7201      MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7202                                             Destructor->getParent());
7203    }
7204
7205    // If any errors have occurred, clear out any temporaries that may have
7206    // been leftover. This ensures that these temporaries won't be picked up for
7207    // deletion in some later function.
7208    if (PP.getDiagnostics().hasErrorOccurred() ||
7209        PP.getDiagnostics().getSuppressAllDiagnostics()) {
7210      DiscardCleanupsInEvaluationContext();
7211    } else if (!isa<FunctionTemplateDecl>(dcl)) {
7212      // Since the body is valid, issue any analysis-based warnings that are
7213      // enabled.
7214      ActivePolicy = &WP;
7215    }
7216
7217    if (FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
7218        !CheckConstexprFunctionBody(FD, Body))
7219      FD->setInvalidDecl();
7220
7221    assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
7222    assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
7223  }
7224
7225  if (!IsInstantiation)
7226    PopDeclContext();
7227
7228  PopFunctionOrBlockScope(ActivePolicy, dcl);
7229
7230  // If any errors have occurred, clear out any temporaries that may have
7231  // been leftover. This ensures that these temporaries won't be picked up for
7232  // deletion in some later function.
7233  if (getDiagnostics().hasErrorOccurred()) {
7234    DiscardCleanupsInEvaluationContext();
7235  }
7236
7237  return dcl;
7238}
7239
7240
7241/// When we finish delayed parsing of an attribute, we must attach it to the
7242/// relevant Decl.
7243void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
7244                                       ParsedAttributes &Attrs) {
7245  ProcessDeclAttributeList(S, D, Attrs.getList());
7246}
7247
7248
7249/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
7250/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
7251NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
7252                                          IdentifierInfo &II, Scope *S) {
7253  // Before we produce a declaration for an implicitly defined
7254  // function, see whether there was a locally-scoped declaration of
7255  // this name as a function or variable. If so, use that
7256  // (non-visible) declaration, and complain about it.
7257  llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
7258    = findLocallyScopedExternalDecl(&II);
7259  if (Pos != LocallyScopedExternalDecls.end()) {
7260    Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
7261    Diag(Pos->second->getLocation(), diag::note_previous_declaration);
7262    return Pos->second;
7263  }
7264
7265  // Extension in C99.  Legal in C90, but warn about it.
7266  unsigned diag_id;
7267  if (II.getName().startswith("__builtin_"))
7268    diag_id = diag::err_builtin_unknown;
7269  else if (getLangOptions().C99)
7270    diag_id = diag::ext_implicit_function_decl;
7271  else
7272    diag_id = diag::warn_implicit_function_decl;
7273  Diag(Loc, diag_id) << &II;
7274
7275  // Because typo correction is expensive, only do it if the implicit
7276  // function declaration is going to be treated as an error.
7277  if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
7278    TypoCorrection Corrected;
7279    if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
7280                                      LookupOrdinaryName, S, 0))) {
7281      NamedDecl *Decl = Corrected.getCorrectionDecl();
7282      if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Decl)) {
7283        std::string CorrectedStr = Corrected.getAsString(getLangOptions());
7284        std::string CorrectedQuotedStr = Corrected.getQuoted(getLangOptions());
7285
7286        Diag(Loc, diag::note_function_suggestion) << CorrectedQuotedStr
7287            << FixItHint::CreateReplacement(Loc, CorrectedStr);
7288
7289        if (Func->getLocation().isValid()
7290            && !II.getName().startswith("__builtin_"))
7291          Diag(Func->getLocation(), diag::note_previous_decl)
7292              << CorrectedQuotedStr;
7293      }
7294    }
7295  }
7296
7297  // Set a Declarator for the implicit definition: int foo();
7298  const char *Dummy;
7299  AttributeFactory attrFactory;
7300  DeclSpec DS(attrFactory);
7301  unsigned DiagID;
7302  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
7303  (void)Error; // Silence warning.
7304  assert(!Error && "Error setting up implicit decl!");
7305  Declarator D(DS, Declarator::BlockContext);
7306  D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
7307                                             0, 0, true, SourceLocation(),
7308                                             SourceLocation(), SourceLocation(),
7309                                             SourceLocation(),
7310                                             EST_None, SourceLocation(),
7311                                             0, 0, 0, 0, Loc, Loc, D),
7312                DS.getAttributes(),
7313                SourceLocation());
7314  D.SetIdentifier(&II, Loc);
7315
7316  // Insert this function into translation-unit scope.
7317
7318  DeclContext *PrevDC = CurContext;
7319  CurContext = Context.getTranslationUnitDecl();
7320
7321  FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
7322  FD->setImplicit();
7323
7324  CurContext = PrevDC;
7325
7326  AddKnownFunctionAttributes(FD);
7327
7328  return FD;
7329}
7330
7331/// \brief Adds any function attributes that we know a priori based on
7332/// the declaration of this function.
7333///
7334/// These attributes can apply both to implicitly-declared builtins
7335/// (like __builtin___printf_chk) or to library-declared functions
7336/// like NSLog or printf.
7337///
7338/// We need to check for duplicate attributes both here and where user-written
7339/// attributes are applied to declarations.
7340void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
7341  if (FD->isInvalidDecl())
7342    return;
7343
7344  // If this is a built-in function, map its builtin attributes to
7345  // actual attributes.
7346  if (unsigned BuiltinID = FD->getBuiltinID()) {
7347    // Handle printf-formatting attributes.
7348    unsigned FormatIdx;
7349    bool HasVAListArg;
7350    if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
7351      if (!FD->getAttr<FormatAttr>())
7352        FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
7353                                                "printf", FormatIdx+1,
7354                                               HasVAListArg ? 0 : FormatIdx+2));
7355    }
7356    if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
7357                                             HasVAListArg)) {
7358     if (!FD->getAttr<FormatAttr>())
7359       FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
7360                                              "scanf", FormatIdx+1,
7361                                              HasVAListArg ? 0 : FormatIdx+2));
7362    }
7363
7364    // Mark const if we don't care about errno and that is the only
7365    // thing preventing the function from being const. This allows
7366    // IRgen to use LLVM intrinsics for such functions.
7367    if (!getLangOptions().MathErrno &&
7368        Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
7369      if (!FD->getAttr<ConstAttr>())
7370        FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
7371    }
7372
7373    if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
7374        !FD->getAttr<ReturnsTwiceAttr>())
7375      FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
7376    if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
7377      FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
7378    if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
7379      FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
7380  }
7381
7382  IdentifierInfo *Name = FD->getIdentifier();
7383  if (!Name)
7384    return;
7385  if ((!getLangOptions().CPlusPlus &&
7386       FD->getDeclContext()->isTranslationUnit()) ||
7387      (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
7388       cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
7389       LinkageSpecDecl::lang_c)) {
7390    // Okay: this could be a libc/libm/Objective-C function we know
7391    // about.
7392  } else
7393    return;
7394
7395  if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
7396    // FIXME: NSLog and NSLogv should be target specific
7397    if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
7398      // FIXME: We known better than our headers.
7399      const_cast<FormatAttr *>(Format)->setType(Context, "printf");
7400    } else
7401      FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
7402                                             "printf", 1,
7403                                             Name->isStr("NSLogv") ? 0 : 2));
7404  } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
7405    // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
7406    // target-specific builtins, perhaps?
7407    if (!FD->getAttr<FormatAttr>())
7408      FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
7409                                             "printf", 2,
7410                                             Name->isStr("vasprintf") ? 0 : 3));
7411  }
7412}
7413
7414TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
7415                                    TypeSourceInfo *TInfo) {
7416  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
7417  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
7418
7419  if (!TInfo) {
7420    assert(D.isInvalidType() && "no declarator info for valid type");
7421    TInfo = Context.getTrivialTypeSourceInfo(T);
7422  }
7423
7424  // Scope manipulation handled by caller.
7425  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
7426                                           D.getSourceRange().getBegin(),
7427                                           D.getIdentifierLoc(),
7428                                           D.getIdentifier(),
7429                                           TInfo);
7430
7431  // Bail out immediately if we have an invalid declaration.
7432  if (D.isInvalidType()) {
7433    NewTD->setInvalidDecl();
7434    return NewTD;
7435  }
7436
7437  if (D.getDeclSpec().isModulePrivateSpecified()) {
7438    if (CurContext->isFunctionOrMethod())
7439      Diag(NewTD->getLocation(), diag::err_module_private_local)
7440        << 2 << NewTD->getDeclName()
7441        << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7442        << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7443    else
7444      NewTD->setModulePrivate();
7445  }
7446
7447  // C++ [dcl.typedef]p8:
7448  //   If the typedef declaration defines an unnamed class (or
7449  //   enum), the first typedef-name declared by the declaration
7450  //   to be that class type (or enum type) is used to denote the
7451  //   class type (or enum type) for linkage purposes only.
7452  // We need to check whether the type was declared in the declaration.
7453  switch (D.getDeclSpec().getTypeSpecType()) {
7454  case TST_enum:
7455  case TST_struct:
7456  case TST_union:
7457  case TST_class: {
7458    TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
7459
7460    // Do nothing if the tag is not anonymous or already has an
7461    // associated typedef (from an earlier typedef in this decl group).
7462    if (tagFromDeclSpec->getIdentifier()) break;
7463    if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
7464
7465    // A well-formed anonymous tag must always be a TUK_Definition.
7466    assert(tagFromDeclSpec->isThisDeclarationADefinition());
7467
7468    // The type must match the tag exactly;  no qualifiers allowed.
7469    if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
7470      break;
7471
7472    // Otherwise, set this is the anon-decl typedef for the tag.
7473    tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
7474    break;
7475  }
7476
7477  default:
7478    break;
7479  }
7480
7481  return NewTD;
7482}
7483
7484
7485/// \brief Determine whether a tag with a given kind is acceptable
7486/// as a redeclaration of the given tag declaration.
7487///
7488/// \returns true if the new tag kind is acceptable, false otherwise.
7489bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
7490                                        TagTypeKind NewTag, bool isDefinition,
7491                                        SourceLocation NewTagLoc,
7492                                        const IdentifierInfo &Name) {
7493  // C++ [dcl.type.elab]p3:
7494  //   The class-key or enum keyword present in the
7495  //   elaborated-type-specifier shall agree in kind with the
7496  //   declaration to which the name in the elaborated-type-specifier
7497  //   refers. This rule also applies to the form of
7498  //   elaborated-type-specifier that declares a class-name or
7499  //   friend class since it can be construed as referring to the
7500  //   definition of the class. Thus, in any
7501  //   elaborated-type-specifier, the enum keyword shall be used to
7502  //   refer to an enumeration (7.2), the union class-key shall be
7503  //   used to refer to a union (clause 9), and either the class or
7504  //   struct class-key shall be used to refer to a class (clause 9)
7505  //   declared using the class or struct class-key.
7506  TagTypeKind OldTag = Previous->getTagKind();
7507  if (!isDefinition || (NewTag != TTK_Class && NewTag != TTK_Struct))
7508    if (OldTag == NewTag)
7509      return true;
7510
7511  if ((OldTag == TTK_Struct || OldTag == TTK_Class) &&
7512      (NewTag == TTK_Struct || NewTag == TTK_Class)) {
7513    // Warn about the struct/class tag mismatch.
7514    bool isTemplate = false;
7515    if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
7516      isTemplate = Record->getDescribedClassTemplate();
7517
7518    if (!ActiveTemplateInstantiations.empty()) {
7519      // In a template instantiation, do not offer fix-its for tag mismatches
7520      // since they usually mess up the template instead of fixing the problem.
7521      Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
7522        << (NewTag == TTK_Class) << isTemplate << &Name;
7523      return true;
7524    }
7525
7526    if (isDefinition) {
7527      // On definitions, check previous tags and issue a fix-it for each
7528      // one that doesn't match the current tag.
7529      if (Previous->getDefinition()) {
7530        // Don't suggest fix-its for redefinitions.
7531        return true;
7532      }
7533
7534      bool previousMismatch = false;
7535      for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
7536           E(Previous->redecls_end()); I != E; ++I) {
7537        if (I->getTagKind() != NewTag) {
7538          if (!previousMismatch) {
7539            previousMismatch = true;
7540            Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
7541              << (NewTag == TTK_Class) << isTemplate << &Name;
7542          }
7543          Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
7544            << (NewTag == TTK_Class)
7545            << FixItHint::CreateReplacement(I->getInnerLocStart(),
7546                                            NewTag == TTK_Class?
7547                                            "class" : "struct");
7548        }
7549      }
7550      return true;
7551    }
7552
7553    // Check for a previous definition.  If current tag and definition
7554    // are same type, do nothing.  If no definition, but disagree with
7555    // with previous tag type, give a warning, but no fix-it.
7556    const TagDecl *Redecl = Previous->getDefinition() ?
7557                            Previous->getDefinition() : Previous;
7558    if (Redecl->getTagKind() == NewTag) {
7559      return true;
7560    }
7561
7562    Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
7563      << (NewTag == TTK_Class)
7564      << isTemplate << &Name;
7565    Diag(Redecl->getLocation(), diag::note_previous_use);
7566
7567    // If there is a previous defintion, suggest a fix-it.
7568    if (Previous->getDefinition()) {
7569        Diag(NewTagLoc, diag::note_struct_class_suggestion)
7570          << (Redecl->getTagKind() == TTK_Class)
7571          << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
7572                        Redecl->getTagKind() == TTK_Class? "class" : "struct");
7573    }
7574
7575    return true;
7576  }
7577  return false;
7578}
7579
7580/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
7581/// former case, Name will be non-null.  In the later case, Name will be null.
7582/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
7583/// reference/declaration/definition of a tag.
7584Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
7585                     SourceLocation KWLoc, CXXScopeSpec &SS,
7586                     IdentifierInfo *Name, SourceLocation NameLoc,
7587                     AttributeList *Attr, AccessSpecifier AS,
7588                     SourceLocation ModulePrivateLoc,
7589                     MultiTemplateParamsArg TemplateParameterLists,
7590                     bool &OwnedDecl, bool &IsDependent,
7591                     bool ScopedEnum, bool ScopedEnumUsesClassTag,
7592                     TypeResult UnderlyingType) {
7593  // If this is not a definition, it must have a name.
7594  assert((Name != 0 || TUK == TUK_Definition) &&
7595         "Nameless record must be a definition!");
7596  assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
7597
7598  OwnedDecl = false;
7599  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7600
7601  // FIXME: Check explicit specializations more carefully.
7602  bool isExplicitSpecialization = false;
7603  bool Invalid = false;
7604
7605  // We only need to do this matching if we have template parameters
7606  // or a scope specifier, which also conveniently avoids this work
7607  // for non-C++ cases.
7608  if (TemplateParameterLists.size() > 0 ||
7609      (SS.isNotEmpty() && TUK != TUK_Reference)) {
7610    if (TemplateParameterList *TemplateParams
7611          = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS,
7612                                                TemplateParameterLists.get(),
7613                                                TemplateParameterLists.size(),
7614                                                    TUK == TUK_Friend,
7615                                                    isExplicitSpecialization,
7616                                                    Invalid)) {
7617      if (TemplateParams->size() > 0) {
7618        // This is a declaration or definition of a class template (which may
7619        // be a member of another template).
7620
7621        if (Invalid)
7622          return 0;
7623
7624        OwnedDecl = false;
7625        DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
7626                                               SS, Name, NameLoc, Attr,
7627                                               TemplateParams, AS,
7628                                               ModulePrivateLoc,
7629                                           TemplateParameterLists.size() - 1,
7630                 (TemplateParameterList**) TemplateParameterLists.release());
7631        return Result.get();
7632      } else {
7633        // The "template<>" header is extraneous.
7634        Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
7635          << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
7636        isExplicitSpecialization = true;
7637      }
7638    }
7639  }
7640
7641  // Figure out the underlying type if this a enum declaration. We need to do
7642  // this early, because it's needed to detect if this is an incompatible
7643  // redeclaration.
7644  llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
7645
7646  if (Kind == TTK_Enum) {
7647    if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
7648      // No underlying type explicitly specified, or we failed to parse the
7649      // type, default to int.
7650      EnumUnderlying = Context.IntTy.getTypePtr();
7651    else if (UnderlyingType.get()) {
7652      // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
7653      // integral type; any cv-qualification is ignored.
7654      TypeSourceInfo *TI = 0;
7655      QualType T = GetTypeFromParser(UnderlyingType.get(), &TI);
7656      EnumUnderlying = TI;
7657
7658      SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
7659
7660      if (!T->isDependentType() && !T->isIntegralType(Context)) {
7661        Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
7662          << T;
7663        // Recover by falling back to int.
7664        EnumUnderlying = Context.IntTy.getTypePtr();
7665      }
7666
7667      if (DiagnoseUnexpandedParameterPack(UnderlyingLoc, TI,
7668                                          UPPC_FixedUnderlyingType))
7669        EnumUnderlying = Context.IntTy.getTypePtr();
7670
7671    } else if (getLangOptions().MicrosoftExt)
7672      // Microsoft enums are always of int type.
7673      EnumUnderlying = Context.IntTy.getTypePtr();
7674  }
7675
7676  DeclContext *SearchDC = CurContext;
7677  DeclContext *DC = CurContext;
7678  bool isStdBadAlloc = false;
7679
7680  RedeclarationKind Redecl = ForRedeclaration;
7681  if (TUK == TUK_Friend || TUK == TUK_Reference)
7682    Redecl = NotForRedeclaration;
7683
7684  LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
7685
7686  if (Name && SS.isNotEmpty()) {
7687    // We have a nested-name tag ('struct foo::bar').
7688
7689    // Check for invalid 'foo::'.
7690    if (SS.isInvalid()) {
7691      Name = 0;
7692      goto CreateNewDecl;
7693    }
7694
7695    // If this is a friend or a reference to a class in a dependent
7696    // context, don't try to make a decl for it.
7697    if (TUK == TUK_Friend || TUK == TUK_Reference) {
7698      DC = computeDeclContext(SS, false);
7699      if (!DC) {
7700        IsDependent = true;
7701        return 0;
7702      }
7703    } else {
7704      DC = computeDeclContext(SS, true);
7705      if (!DC) {
7706        Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
7707          << SS.getRange();
7708        return 0;
7709      }
7710    }
7711
7712    if (RequireCompleteDeclContext(SS, DC))
7713      return 0;
7714
7715    SearchDC = DC;
7716    // Look-up name inside 'foo::'.
7717    LookupQualifiedName(Previous, DC);
7718
7719    if (Previous.isAmbiguous())
7720      return 0;
7721
7722    if (Previous.empty()) {
7723      // Name lookup did not find anything. However, if the
7724      // nested-name-specifier refers to the current instantiation,
7725      // and that current instantiation has any dependent base
7726      // classes, we might find something at instantiation time: treat
7727      // this as a dependent elaborated-type-specifier.
7728      // But this only makes any sense for reference-like lookups.
7729      if (Previous.wasNotFoundInCurrentInstantiation() &&
7730          (TUK == TUK_Reference || TUK == TUK_Friend)) {
7731        IsDependent = true;
7732        return 0;
7733      }
7734
7735      // A tag 'foo::bar' must already exist.
7736      Diag(NameLoc, diag::err_not_tag_in_scope)
7737        << Kind << Name << DC << SS.getRange();
7738      Name = 0;
7739      Invalid = true;
7740      goto CreateNewDecl;
7741    }
7742  } else if (Name) {
7743    // If this is a named struct, check to see if there was a previous forward
7744    // declaration or definition.
7745    // FIXME: We're looking into outer scopes here, even when we
7746    // shouldn't be. Doing so can result in ambiguities that we
7747    // shouldn't be diagnosing.
7748    LookupName(Previous, S);
7749
7750    if (Previous.isAmbiguous() &&
7751        (TUK == TUK_Definition || TUK == TUK_Declaration)) {
7752      LookupResult::Filter F = Previous.makeFilter();
7753      while (F.hasNext()) {
7754        NamedDecl *ND = F.next();
7755        if (ND->getDeclContext()->getRedeclContext() != SearchDC)
7756          F.erase();
7757      }
7758      F.done();
7759    }
7760
7761    // Note:  there used to be some attempt at recovery here.
7762    if (Previous.isAmbiguous())
7763      return 0;
7764
7765    if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
7766      // FIXME: This makes sure that we ignore the contexts associated
7767      // with C structs, unions, and enums when looking for a matching
7768      // tag declaration or definition. See the similar lookup tweak
7769      // in Sema::LookupName; is there a better way to deal with this?
7770      while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
7771        SearchDC = SearchDC->getParent();
7772    }
7773  } else if (S->isFunctionPrototypeScope()) {
7774    // If this is an enum declaration in function prototype scope, set its
7775    // initial context to the translation unit.
7776    SearchDC = Context.getTranslationUnitDecl();
7777  }
7778
7779  if (Previous.isSingleResult() &&
7780      Previous.getFoundDecl()->isTemplateParameter()) {
7781    // Maybe we will complain about the shadowed template parameter.
7782    DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
7783    // Just pretend that we didn't see the previous declaration.
7784    Previous.clear();
7785  }
7786
7787  if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
7788      DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
7789    // This is a declaration of or a reference to "std::bad_alloc".
7790    isStdBadAlloc = true;
7791
7792    if (Previous.empty() && StdBadAlloc) {
7793      // std::bad_alloc has been implicitly declared (but made invisible to
7794      // name lookup). Fill in this implicit declaration as the previous
7795      // declaration, so that the declarations get chained appropriately.
7796      Previous.addDecl(getStdBadAlloc());
7797    }
7798  }
7799
7800  // If we didn't find a previous declaration, and this is a reference
7801  // (or friend reference), move to the correct scope.  In C++, we
7802  // also need to do a redeclaration lookup there, just in case
7803  // there's a shadow friend decl.
7804  if (Name && Previous.empty() &&
7805      (TUK == TUK_Reference || TUK == TUK_Friend)) {
7806    if (Invalid) goto CreateNewDecl;
7807    assert(SS.isEmpty());
7808
7809    if (TUK == TUK_Reference) {
7810      // C++ [basic.scope.pdecl]p5:
7811      //   -- for an elaborated-type-specifier of the form
7812      //
7813      //          class-key identifier
7814      //
7815      //      if the elaborated-type-specifier is used in the
7816      //      decl-specifier-seq or parameter-declaration-clause of a
7817      //      function defined in namespace scope, the identifier is
7818      //      declared as a class-name in the namespace that contains
7819      //      the declaration; otherwise, except as a friend
7820      //      declaration, the identifier is declared in the smallest
7821      //      non-class, non-function-prototype scope that contains the
7822      //      declaration.
7823      //
7824      // C99 6.7.2.3p8 has a similar (but not identical!) provision for
7825      // C structs and unions.
7826      //
7827      // It is an error in C++ to declare (rather than define) an enum
7828      // type, including via an elaborated type specifier.  We'll
7829      // diagnose that later; for now, declare the enum in the same
7830      // scope as we would have picked for any other tag type.
7831      //
7832      // GNU C also supports this behavior as part of its incomplete
7833      // enum types extension, while GNU C++ does not.
7834      //
7835      // Find the context where we'll be declaring the tag.
7836      // FIXME: We would like to maintain the current DeclContext as the
7837      // lexical context,
7838      while (SearchDC->isRecord() || SearchDC->isTransparentContext())
7839        SearchDC = SearchDC->getParent();
7840
7841      // Find the scope where we'll be declaring the tag.
7842      while (S->isClassScope() ||
7843             (getLangOptions().CPlusPlus &&
7844              S->isFunctionPrototypeScope()) ||
7845             ((S->getFlags() & Scope::DeclScope) == 0) ||
7846             (S->getEntity() &&
7847              ((DeclContext *)S->getEntity())->isTransparentContext()))
7848        S = S->getParent();
7849    } else {
7850      assert(TUK == TUK_Friend);
7851      // C++ [namespace.memdef]p3:
7852      //   If a friend declaration in a non-local class first declares a
7853      //   class or function, the friend class or function is a member of
7854      //   the innermost enclosing namespace.
7855      SearchDC = SearchDC->getEnclosingNamespaceContext();
7856    }
7857
7858    // In C++, we need to do a redeclaration lookup to properly
7859    // diagnose some problems.
7860    if (getLangOptions().CPlusPlus) {
7861      Previous.setRedeclarationKind(ForRedeclaration);
7862      LookupQualifiedName(Previous, SearchDC);
7863    }
7864  }
7865
7866  if (!Previous.empty()) {
7867    NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
7868
7869    // It's okay to have a tag decl in the same scope as a typedef
7870    // which hides a tag decl in the same scope.  Finding this
7871    // insanity with a redeclaration lookup can only actually happen
7872    // in C++.
7873    //
7874    // This is also okay for elaborated-type-specifiers, which is
7875    // technically forbidden by the current standard but which is
7876    // okay according to the likely resolution of an open issue;
7877    // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
7878    if (getLangOptions().CPlusPlus) {
7879      if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
7880        if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
7881          TagDecl *Tag = TT->getDecl();
7882          if (Tag->getDeclName() == Name &&
7883              Tag->getDeclContext()->getRedeclContext()
7884                          ->Equals(TD->getDeclContext()->getRedeclContext())) {
7885            PrevDecl = Tag;
7886            Previous.clear();
7887            Previous.addDecl(Tag);
7888            Previous.resolveKind();
7889          }
7890        }
7891      }
7892    }
7893
7894    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
7895      // If this is a use of a previous tag, or if the tag is already declared
7896      // in the same scope (so that the definition/declaration completes or
7897      // rementions the tag), reuse the decl.
7898      if (TUK == TUK_Reference || TUK == TUK_Friend ||
7899          isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
7900        // Make sure that this wasn't declared as an enum and now used as a
7901        // struct or something similar.
7902        if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
7903                                          TUK == TUK_Definition, KWLoc,
7904                                          *Name)) {
7905          bool SafeToContinue
7906            = (PrevTagDecl->getTagKind() != TTK_Enum &&
7907               Kind != TTK_Enum);
7908          if (SafeToContinue)
7909            Diag(KWLoc, diag::err_use_with_wrong_tag)
7910              << Name
7911              << FixItHint::CreateReplacement(SourceRange(KWLoc),
7912                                              PrevTagDecl->getKindName());
7913          else
7914            Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
7915          Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
7916
7917          if (SafeToContinue)
7918            Kind = PrevTagDecl->getTagKind();
7919          else {
7920            // Recover by making this an anonymous redefinition.
7921            Name = 0;
7922            Previous.clear();
7923            Invalid = true;
7924          }
7925        }
7926
7927        if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
7928          const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
7929
7930          // All conflicts with previous declarations are recovered by
7931          // returning the previous declaration.
7932          if (ScopedEnum != PrevEnum->isScoped()) {
7933            Diag(KWLoc, diag::err_enum_redeclare_scoped_mismatch)
7934              << PrevEnum->isScoped();
7935            Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
7936            return PrevTagDecl;
7937          }
7938          else if (EnumUnderlying && PrevEnum->isFixed()) {
7939            QualType T;
7940            if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
7941                T = TI->getType();
7942            else
7943                T = QualType(EnumUnderlying.get<const Type*>(), 0);
7944
7945            if (!Context.hasSameUnqualifiedType(T,
7946                                                PrevEnum->getIntegerType())) {
7947              Diag(NameLoc.isValid() ? NameLoc : KWLoc,
7948                   diag::err_enum_redeclare_type_mismatch)
7949                << T
7950                << PrevEnum->getIntegerType();
7951              Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
7952              return PrevTagDecl;
7953            }
7954          }
7955          else if (!EnumUnderlying.isNull() != PrevEnum->isFixed()) {
7956            Diag(KWLoc, diag::err_enum_redeclare_fixed_mismatch)
7957              << PrevEnum->isFixed();
7958            Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
7959            return PrevTagDecl;
7960          }
7961        }
7962
7963        if (!Invalid) {
7964          // If this is a use, just return the declaration we found.
7965
7966          // FIXME: In the future, return a variant or some other clue
7967          // for the consumer of this Decl to know it doesn't own it.
7968          // For our current ASTs this shouldn't be a problem, but will
7969          // need to be changed with DeclGroups.
7970          if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
7971               getLangOptions().MicrosoftExt)) || TUK == TUK_Friend)
7972            return PrevTagDecl;
7973
7974          // Diagnose attempts to redefine a tag.
7975          if (TUK == TUK_Definition) {
7976            if (TagDecl *Def = PrevTagDecl->getDefinition()) {
7977              // If we're defining a specialization and the previous definition
7978              // is from an implicit instantiation, don't emit an error
7979              // here; we'll catch this in the general case below.
7980              if (!isExplicitSpecialization ||
7981                  !isa<CXXRecordDecl>(Def) ||
7982                  cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind()
7983                                               == TSK_ExplicitSpecialization) {
7984                Diag(NameLoc, diag::err_redefinition) << Name;
7985                Diag(Def->getLocation(), diag::note_previous_definition);
7986                // If this is a redefinition, recover by making this
7987                // struct be anonymous, which will make any later
7988                // references get the previous definition.
7989                Name = 0;
7990                Previous.clear();
7991                Invalid = true;
7992              }
7993            } else {
7994              // If the type is currently being defined, complain
7995              // about a nested redefinition.
7996              const TagType *Tag
7997                = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
7998              if (Tag->isBeingDefined()) {
7999                Diag(NameLoc, diag::err_nested_redefinition) << Name;
8000                Diag(PrevTagDecl->getLocation(),
8001                     diag::note_previous_definition);
8002                Name = 0;
8003                Previous.clear();
8004                Invalid = true;
8005              }
8006            }
8007
8008            // Okay, this is definition of a previously declared or referenced
8009            // tag PrevDecl. We're going to create a new Decl for it.
8010          }
8011        }
8012        // If we get here we have (another) forward declaration or we
8013        // have a definition.  Just create a new decl.
8014
8015      } else {
8016        // If we get here, this is a definition of a new tag type in a nested
8017        // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
8018        // new decl/type.  We set PrevDecl to NULL so that the entities
8019        // have distinct types.
8020        Previous.clear();
8021      }
8022      // If we get here, we're going to create a new Decl. If PrevDecl
8023      // is non-NULL, it's a definition of the tag declared by
8024      // PrevDecl. If it's NULL, we have a new definition.
8025
8026
8027    // Otherwise, PrevDecl is not a tag, but was found with tag
8028    // lookup.  This is only actually possible in C++, where a few
8029    // things like templates still live in the tag namespace.
8030    } else {
8031      assert(getLangOptions().CPlusPlus);
8032
8033      // Use a better diagnostic if an elaborated-type-specifier
8034      // found the wrong kind of type on the first
8035      // (non-redeclaration) lookup.
8036      if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
8037          !Previous.isForRedeclaration()) {
8038        unsigned Kind = 0;
8039        if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
8040        else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
8041        else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
8042        Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
8043        Diag(PrevDecl->getLocation(), diag::note_declared_at);
8044        Invalid = true;
8045
8046      // Otherwise, only diagnose if the declaration is in scope.
8047      } else if (!isDeclInScope(PrevDecl, SearchDC, S,
8048                                isExplicitSpecialization)) {
8049        // do nothing
8050
8051      // Diagnose implicit declarations introduced by elaborated types.
8052      } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
8053        unsigned Kind = 0;
8054        if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
8055        else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
8056        else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
8057        Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
8058        Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
8059        Invalid = true;
8060
8061      // Otherwise it's a declaration.  Call out a particularly common
8062      // case here.
8063      } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
8064        unsigned Kind = 0;
8065        if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
8066        Diag(NameLoc, diag::err_tag_definition_of_typedef)
8067          << Name << Kind << TND->getUnderlyingType();
8068        Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
8069        Invalid = true;
8070
8071      // Otherwise, diagnose.
8072      } else {
8073        // The tag name clashes with something else in the target scope,
8074        // issue an error and recover by making this tag be anonymous.
8075        Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
8076        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8077        Name = 0;
8078        Invalid = true;
8079      }
8080
8081      // The existing declaration isn't relevant to us; we're in a
8082      // new scope, so clear out the previous declaration.
8083      Previous.clear();
8084    }
8085  }
8086
8087CreateNewDecl:
8088
8089  TagDecl *PrevDecl = 0;
8090  if (Previous.isSingleResult())
8091    PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
8092
8093  // If there is an identifier, use the location of the identifier as the
8094  // location of the decl, otherwise use the location of the struct/union
8095  // keyword.
8096  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
8097
8098  // Otherwise, create a new declaration. If there is a previous
8099  // declaration of the same entity, the two will be linked via
8100  // PrevDecl.
8101  TagDecl *New;
8102
8103  bool IsForwardReference = false;
8104  if (Kind == TTK_Enum) {
8105    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
8106    // enum X { A, B, C } D;    D should chain to X.
8107    New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
8108                           cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
8109                           ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
8110    // If this is an undefined enum, warn.
8111    if (TUK != TUK_Definition && !Invalid) {
8112      TagDecl *Def;
8113      if (getLangOptions().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) {
8114        // C++0x: 7.2p2: opaque-enum-declaration.
8115        // Conflicts are diagnosed above. Do nothing.
8116      }
8117      else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
8118        Diag(Loc, diag::ext_forward_ref_enum_def)
8119          << New;
8120        Diag(Def->getLocation(), diag::note_previous_definition);
8121      } else {
8122        unsigned DiagID = diag::ext_forward_ref_enum;
8123        if (getLangOptions().MicrosoftExt)
8124          DiagID = diag::ext_ms_forward_ref_enum;
8125        else if (getLangOptions().CPlusPlus)
8126          DiagID = diag::err_forward_ref_enum;
8127        Diag(Loc, DiagID);
8128
8129        // If this is a forward-declared reference to an enumeration, make a
8130        // note of it; we won't actually be introducing the declaration into
8131        // the declaration context.
8132        if (TUK == TUK_Reference)
8133          IsForwardReference = true;
8134      }
8135    }
8136
8137    if (EnumUnderlying) {
8138      EnumDecl *ED = cast<EnumDecl>(New);
8139      if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
8140        ED->setIntegerTypeSourceInfo(TI);
8141      else
8142        ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
8143      ED->setPromotionType(ED->getIntegerType());
8144    }
8145
8146  } else {
8147    // struct/union/class
8148
8149    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
8150    // struct X { int A; } D;    D should chain to X.
8151    if (getLangOptions().CPlusPlus) {
8152      // FIXME: Look for a way to use RecordDecl for simple structs.
8153      New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
8154                                  cast_or_null<CXXRecordDecl>(PrevDecl));
8155
8156      if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
8157        StdBadAlloc = cast<CXXRecordDecl>(New);
8158    } else
8159      New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
8160                               cast_or_null<RecordDecl>(PrevDecl));
8161  }
8162
8163  // Maybe add qualifier info.
8164  if (SS.isNotEmpty()) {
8165    if (SS.isSet()) {
8166      New->setQualifierInfo(SS.getWithLocInContext(Context));
8167      if (TemplateParameterLists.size() > 0) {
8168        New->setTemplateParameterListsInfo(Context,
8169                                           TemplateParameterLists.size(),
8170                    (TemplateParameterList**) TemplateParameterLists.release());
8171      }
8172    }
8173    else
8174      Invalid = true;
8175  }
8176
8177  if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
8178    // Add alignment attributes if necessary; these attributes are checked when
8179    // the ASTContext lays out the structure.
8180    //
8181    // It is important for implementing the correct semantics that this
8182    // happen here (in act on tag decl). The #pragma pack stack is
8183    // maintained as a result of parser callbacks which can occur at
8184    // many points during the parsing of a struct declaration (because
8185    // the #pragma tokens are effectively skipped over during the
8186    // parsing of the struct).
8187    AddAlignmentAttributesForRecord(RD);
8188
8189    AddMsStructLayoutForRecord(RD);
8190  }
8191
8192  if (ModulePrivateLoc.isValid()) {
8193    if (isExplicitSpecialization)
8194      Diag(New->getLocation(), diag::err_module_private_specialization)
8195        << 2
8196        << FixItHint::CreateRemoval(ModulePrivateLoc);
8197    // __module_private__ does not apply to local classes. However, we only
8198    // diagnose this as an error when the declaration specifiers are
8199    // freestanding. Here, we just ignore the __module_private__.
8200    else if (!SearchDC->isFunctionOrMethod())
8201      New->setModulePrivate();
8202  }
8203
8204  // If this is a specialization of a member class (of a class template),
8205  // check the specialization.
8206  if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
8207    Invalid = true;
8208
8209  if (Invalid)
8210    New->setInvalidDecl();
8211
8212  if (Attr)
8213    ProcessDeclAttributeList(S, New, Attr);
8214
8215  // If we're declaring or defining a tag in function prototype scope
8216  // in C, note that this type can only be used within the function.
8217  if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
8218    Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
8219
8220  // Set the lexical context. If the tag has a C++ scope specifier, the
8221  // lexical context will be different from the semantic context.
8222  New->setLexicalDeclContext(CurContext);
8223
8224  // Mark this as a friend decl if applicable.
8225  // In Microsoft mode, a friend declaration also acts as a forward
8226  // declaration so we always pass true to setObjectOfFriendDecl to make
8227  // the tag name visible.
8228  if (TUK == TUK_Friend)
8229    New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() ||
8230                               getLangOptions().MicrosoftExt);
8231
8232  // Set the access specifier.
8233  if (!Invalid && SearchDC->isRecord())
8234    SetMemberAccessSpecifier(New, PrevDecl, AS);
8235
8236  if (TUK == TUK_Definition)
8237    New->startDefinition();
8238
8239  // If this has an identifier, add it to the scope stack.
8240  if (TUK == TUK_Friend) {
8241    // We might be replacing an existing declaration in the lookup tables;
8242    // if so, borrow its access specifier.
8243    if (PrevDecl)
8244      New->setAccess(PrevDecl->getAccess());
8245
8246    DeclContext *DC = New->getDeclContext()->getRedeclContext();
8247    DC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
8248    if (Name) // can be null along some error paths
8249      if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
8250        PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
8251  } else if (Name) {
8252    S = getNonFieldDeclScope(S);
8253    PushOnScopeChains(New, S, !IsForwardReference);
8254    if (IsForwardReference)
8255      SearchDC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
8256
8257  } else {
8258    CurContext->addDecl(New);
8259  }
8260
8261  // If this is the C FILE type, notify the AST context.
8262  if (IdentifierInfo *II = New->getIdentifier())
8263    if (!New->isInvalidDecl() &&
8264        New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
8265        II->isStr("FILE"))
8266      Context.setFILEDecl(New);
8267
8268  OwnedDecl = true;
8269  return New;
8270}
8271
8272void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
8273  AdjustDeclIfTemplate(TagD);
8274  TagDecl *Tag = cast<TagDecl>(TagD);
8275
8276  // Enter the tag context.
8277  PushDeclContext(S, Tag);
8278}
8279
8280Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
8281  assert(isa<ObjCContainerDecl>(IDecl) &&
8282         "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
8283  DeclContext *OCD = cast<DeclContext>(IDecl);
8284  assert(getContainingDC(OCD) == CurContext &&
8285      "The next DeclContext should be lexically contained in the current one.");
8286  CurContext = OCD;
8287  return IDecl;
8288}
8289
8290void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
8291                                           SourceLocation FinalLoc,
8292                                           SourceLocation LBraceLoc) {
8293  AdjustDeclIfTemplate(TagD);
8294  CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
8295
8296  FieldCollector->StartClass();
8297
8298  if (!Record->getIdentifier())
8299    return;
8300
8301  if (FinalLoc.isValid())
8302    Record->addAttr(new (Context) FinalAttr(FinalLoc, Context));
8303
8304  // C++ [class]p2:
8305  //   [...] The class-name is also inserted into the scope of the
8306  //   class itself; this is known as the injected-class-name. For
8307  //   purposes of access checking, the injected-class-name is treated
8308  //   as if it were a public member name.
8309  CXXRecordDecl *InjectedClassName
8310    = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
8311                            Record->getLocStart(), Record->getLocation(),
8312                            Record->getIdentifier(),
8313                            /*PrevDecl=*/0,
8314                            /*DelayTypeCreation=*/true);
8315  Context.getTypeDeclType(InjectedClassName, Record);
8316  InjectedClassName->setImplicit();
8317  InjectedClassName->setAccess(AS_public);
8318  if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
8319      InjectedClassName->setDescribedClassTemplate(Template);
8320  PushOnScopeChains(InjectedClassName, S);
8321  assert(InjectedClassName->isInjectedClassName() &&
8322         "Broken injected-class-name");
8323}
8324
8325void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
8326                                    SourceLocation RBraceLoc) {
8327  AdjustDeclIfTemplate(TagD);
8328  TagDecl *Tag = cast<TagDecl>(TagD);
8329  Tag->setRBraceLoc(RBraceLoc);
8330
8331  if (isa<CXXRecordDecl>(Tag))
8332    FieldCollector->FinishClass();
8333
8334  // Exit this scope of this tag's definition.
8335  PopDeclContext();
8336
8337  // Notify the consumer that we've defined a tag.
8338  Consumer.HandleTagDeclDefinition(Tag);
8339}
8340
8341void Sema::ActOnObjCContainerFinishDefinition() {
8342  // Exit this scope of this interface definition.
8343  PopDeclContext();
8344}
8345
8346void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
8347  assert(DC == CurContext && "Mismatch of container contexts");
8348  OriginalLexicalContext = DC;
8349  ActOnObjCContainerFinishDefinition();
8350}
8351
8352void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
8353  ActOnObjCContainerStartDefinition(cast<Decl>(DC));
8354  OriginalLexicalContext = 0;
8355}
8356
8357void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
8358  AdjustDeclIfTemplate(TagD);
8359  TagDecl *Tag = cast<TagDecl>(TagD);
8360  Tag->setInvalidDecl();
8361
8362  // We're undoing ActOnTagStartDefinition here, not
8363  // ActOnStartCXXMemberDeclarations, so we don't have to mess with
8364  // the FieldCollector.
8365
8366  PopDeclContext();
8367}
8368
8369// Note that FieldName may be null for anonymous bitfields.
8370bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
8371                          QualType FieldTy, const Expr *BitWidth,
8372                          bool *ZeroWidth) {
8373  // Default to true; that shouldn't confuse checks for emptiness
8374  if (ZeroWidth)
8375    *ZeroWidth = true;
8376
8377  // C99 6.7.2.1p4 - verify the field type.
8378  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
8379  if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
8380    // Handle incomplete types with specific error.
8381    if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
8382      return true;
8383    if (FieldName)
8384      return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
8385        << FieldName << FieldTy << BitWidth->getSourceRange();
8386    return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
8387      << FieldTy << BitWidth->getSourceRange();
8388  } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
8389                                             UPPC_BitFieldWidth))
8390    return true;
8391
8392  // If the bit-width is type- or value-dependent, don't try to check
8393  // it now.
8394  if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
8395    return false;
8396
8397  llvm::APSInt Value;
8398  if (VerifyIntegerConstantExpression(BitWidth, &Value))
8399    return true;
8400
8401  if (Value != 0 && ZeroWidth)
8402    *ZeroWidth = false;
8403
8404  // Zero-width bitfield is ok for anonymous field.
8405  if (Value == 0 && FieldName)
8406    return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
8407
8408  if (Value.isSigned() && Value.isNegative()) {
8409    if (FieldName)
8410      return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
8411               << FieldName << Value.toString(10);
8412    return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
8413      << Value.toString(10);
8414  }
8415
8416  if (!FieldTy->isDependentType()) {
8417    uint64_t TypeSize = Context.getTypeSize(FieldTy);
8418    if (Value.getZExtValue() > TypeSize) {
8419      if (!getLangOptions().CPlusPlus) {
8420        if (FieldName)
8421          return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
8422            << FieldName << (unsigned)Value.getZExtValue()
8423            << (unsigned)TypeSize;
8424
8425        return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
8426          << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
8427      }
8428
8429      if (FieldName)
8430        Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
8431          << FieldName << (unsigned)Value.getZExtValue()
8432          << (unsigned)TypeSize;
8433      else
8434        Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
8435          << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
8436    }
8437  }
8438
8439  return false;
8440}
8441
8442/// ActOnField - Each field of a C struct/union is passed into this in order
8443/// to create a FieldDecl object for it.
8444Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
8445                       Declarator &D, Expr *BitfieldWidth) {
8446  FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
8447                               DeclStart, D, static_cast<Expr*>(BitfieldWidth),
8448                               /*HasInit=*/false, AS_public);
8449  return Res;
8450}
8451
8452/// HandleField - Analyze a field of a C struct or a C++ data member.
8453///
8454FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
8455                             SourceLocation DeclStart,
8456                             Declarator &D, Expr *BitWidth, bool HasInit,
8457                             AccessSpecifier AS) {
8458  IdentifierInfo *II = D.getIdentifier();
8459  SourceLocation Loc = DeclStart;
8460  if (II) Loc = D.getIdentifierLoc();
8461
8462  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8463  QualType T = TInfo->getType();
8464  if (getLangOptions().CPlusPlus) {
8465    CheckExtraCXXDefaultArguments(D);
8466
8467    if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
8468                                        UPPC_DataMemberType)) {
8469      D.setInvalidType();
8470      T = Context.IntTy;
8471      TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
8472    }
8473  }
8474
8475  DiagnoseFunctionSpecifiers(D);
8476
8477  if (D.getDeclSpec().isThreadSpecified())
8478    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
8479  if (D.getDeclSpec().isConstexprSpecified())
8480    Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
8481      << 2;
8482
8483  // Check to see if this name was declared as a member previously
8484  NamedDecl *PrevDecl = 0;
8485  LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
8486  LookupName(Previous, S);
8487  switch (Previous.getResultKind()) {
8488    case LookupResult::Found:
8489    case LookupResult::FoundUnresolvedValue:
8490      PrevDecl = Previous.getAsSingle<NamedDecl>();
8491      break;
8492
8493    case LookupResult::FoundOverloaded:
8494      PrevDecl = Previous.getRepresentativeDecl();
8495      break;
8496
8497    case LookupResult::NotFound:
8498    case LookupResult::NotFoundInCurrentInstantiation:
8499    case LookupResult::Ambiguous:
8500      break;
8501  }
8502  Previous.suppressDiagnostics();
8503
8504  if (PrevDecl && PrevDecl->isTemplateParameter()) {
8505    // Maybe we will complain about the shadowed template parameter.
8506    DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
8507    // Just pretend that we didn't see the previous declaration.
8508    PrevDecl = 0;
8509  }
8510
8511  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
8512    PrevDecl = 0;
8513
8514  bool Mutable
8515    = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
8516  SourceLocation TSSL = D.getSourceRange().getBegin();
8517  FieldDecl *NewFD
8518    = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, HasInit,
8519                     TSSL, AS, PrevDecl, &D);
8520
8521  if (NewFD->isInvalidDecl())
8522    Record->setInvalidDecl();
8523
8524  if (D.getDeclSpec().isModulePrivateSpecified())
8525    NewFD->setModulePrivate();
8526
8527  if (NewFD->isInvalidDecl() && PrevDecl) {
8528    // Don't introduce NewFD into scope; there's already something
8529    // with the same name in the same scope.
8530  } else if (II) {
8531    PushOnScopeChains(NewFD, S);
8532  } else
8533    Record->addDecl(NewFD);
8534
8535  return NewFD;
8536}
8537
8538/// \brief Build a new FieldDecl and check its well-formedness.
8539///
8540/// This routine builds a new FieldDecl given the fields name, type,
8541/// record, etc. \p PrevDecl should refer to any previous declaration
8542/// with the same name and in the same scope as the field to be
8543/// created.
8544///
8545/// \returns a new FieldDecl.
8546///
8547/// \todo The Declarator argument is a hack. It will be removed once
8548FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
8549                                TypeSourceInfo *TInfo,
8550                                RecordDecl *Record, SourceLocation Loc,
8551                                bool Mutable, Expr *BitWidth, bool HasInit,
8552                                SourceLocation TSSL,
8553                                AccessSpecifier AS, NamedDecl *PrevDecl,
8554                                Declarator *D) {
8555  IdentifierInfo *II = Name.getAsIdentifierInfo();
8556  bool InvalidDecl = false;
8557  if (D) InvalidDecl = D->isInvalidType();
8558
8559  // If we receive a broken type, recover by assuming 'int' and
8560  // marking this declaration as invalid.
8561  if (T.isNull()) {
8562    InvalidDecl = true;
8563    T = Context.IntTy;
8564  }
8565
8566  QualType EltTy = Context.getBaseElementType(T);
8567  if (!EltTy->isDependentType() &&
8568      RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
8569    // Fields of incomplete type force their record to be invalid.
8570    Record->setInvalidDecl();
8571    InvalidDecl = true;
8572  }
8573
8574  // C99 6.7.2.1p8: A member of a structure or union may have any type other
8575  // than a variably modified type.
8576  if (!InvalidDecl && T->isVariablyModifiedType()) {
8577    bool SizeIsNegative;
8578    llvm::APSInt Oversized;
8579    QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
8580                                                           SizeIsNegative,
8581                                                           Oversized);
8582    if (!FixedTy.isNull()) {
8583      Diag(Loc, diag::warn_illegal_constant_array_size);
8584      T = FixedTy;
8585    } else {
8586      if (SizeIsNegative)
8587        Diag(Loc, diag::err_typecheck_negative_array_size);
8588      else if (Oversized.getBoolValue())
8589        Diag(Loc, diag::err_array_too_large)
8590          << Oversized.toString(10);
8591      else
8592        Diag(Loc, diag::err_typecheck_field_variable_size);
8593      InvalidDecl = true;
8594    }
8595  }
8596
8597  // Fields can not have abstract class types
8598  if (!InvalidDecl && RequireNonAbstractType(Loc, T,
8599                                             diag::err_abstract_type_in_decl,
8600                                             AbstractFieldType))
8601    InvalidDecl = true;
8602
8603  bool ZeroWidth = false;
8604  // If this is declared as a bit-field, check the bit-field.
8605  if (!InvalidDecl && BitWidth &&
8606      VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) {
8607    InvalidDecl = true;
8608    BitWidth = 0;
8609    ZeroWidth = false;
8610  }
8611
8612  // Check that 'mutable' is consistent with the type of the declaration.
8613  if (!InvalidDecl && Mutable) {
8614    unsigned DiagID = 0;
8615    if (T->isReferenceType())
8616      DiagID = diag::err_mutable_reference;
8617    else if (T.isConstQualified())
8618      DiagID = diag::err_mutable_const;
8619
8620    if (DiagID) {
8621      SourceLocation ErrLoc = Loc;
8622      if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
8623        ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
8624      Diag(ErrLoc, DiagID);
8625      Mutable = false;
8626      InvalidDecl = true;
8627    }
8628  }
8629
8630  FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
8631                                       BitWidth, Mutable, HasInit);
8632  if (InvalidDecl)
8633    NewFD->setInvalidDecl();
8634
8635  if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
8636    Diag(Loc, diag::err_duplicate_member) << II;
8637    Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
8638    NewFD->setInvalidDecl();
8639  }
8640
8641  if (!InvalidDecl && getLangOptions().CPlusPlus) {
8642    if (Record->isUnion()) {
8643      if (const RecordType *RT = EltTy->getAs<RecordType>()) {
8644        CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
8645        if (RDecl->getDefinition()) {
8646          // C++ [class.union]p1: An object of a class with a non-trivial
8647          // constructor, a non-trivial copy constructor, a non-trivial
8648          // destructor, or a non-trivial copy assignment operator
8649          // cannot be a member of a union, nor can an array of such
8650          // objects.
8651          if (CheckNontrivialField(NewFD))
8652            NewFD->setInvalidDecl();
8653        }
8654      }
8655
8656      // C++ [class.union]p1: If a union contains a member of reference type,
8657      // the program is ill-formed.
8658      if (EltTy->isReferenceType()) {
8659        Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type)
8660          << NewFD->getDeclName() << EltTy;
8661        NewFD->setInvalidDecl();
8662      }
8663    }
8664  }
8665
8666  // FIXME: We need to pass in the attributes given an AST
8667  // representation, not a parser representation.
8668  if (D)
8669    // FIXME: What to pass instead of TUScope?
8670    ProcessDeclAttributes(TUScope, NewFD, *D);
8671
8672  // In auto-retain/release, infer strong retension for fields of
8673  // retainable type.
8674  if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
8675    NewFD->setInvalidDecl();
8676
8677  if (T.isObjCGCWeak())
8678    Diag(Loc, diag::warn_attribute_weak_on_field);
8679
8680  NewFD->setAccess(AS);
8681  return NewFD;
8682}
8683
8684bool Sema::CheckNontrivialField(FieldDecl *FD) {
8685  assert(FD);
8686  assert(getLangOptions().CPlusPlus && "valid check only for C++");
8687
8688  if (FD->isInvalidDecl())
8689    return true;
8690
8691  QualType EltTy = Context.getBaseElementType(FD->getType());
8692  if (const RecordType *RT = EltTy->getAs<RecordType>()) {
8693    CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
8694    if (RDecl->getDefinition()) {
8695      // We check for copy constructors before constructors
8696      // because otherwise we'll never get complaints about
8697      // copy constructors.
8698
8699      CXXSpecialMember member = CXXInvalid;
8700      if (!RDecl->hasTrivialCopyConstructor())
8701        member = CXXCopyConstructor;
8702      else if (!RDecl->hasTrivialDefaultConstructor())
8703        member = CXXDefaultConstructor;
8704      else if (!RDecl->hasTrivialCopyAssignment())
8705        member = CXXCopyAssignment;
8706      else if (!RDecl->hasTrivialDestructor())
8707        member = CXXDestructor;
8708
8709      if (member != CXXInvalid) {
8710        if (!getLangOptions().CPlusPlus0x &&
8711            getLangOptions().ObjCAutoRefCount && RDecl->hasObjectMember()) {
8712          // Objective-C++ ARC: it is an error to have a non-trivial field of
8713          // a union. However, system headers in Objective-C programs
8714          // occasionally have Objective-C lifetime objects within unions,
8715          // and rather than cause the program to fail, we make those
8716          // members unavailable.
8717          SourceLocation Loc = FD->getLocation();
8718          if (getSourceManager().isInSystemHeader(Loc)) {
8719            if (!FD->hasAttr<UnavailableAttr>())
8720              FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
8721                                  "this system field has retaining ownership"));
8722            return false;
8723          }
8724        }
8725
8726        Diag(FD->getLocation(), getLangOptions().CPlusPlus0x ?
8727               diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
8728               diag::err_illegal_union_or_anon_struct_member)
8729          << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
8730        DiagnoseNontrivial(RT, member);
8731        return !getLangOptions().CPlusPlus0x;
8732      }
8733    }
8734  }
8735
8736  return false;
8737}
8738
8739/// DiagnoseNontrivial - Given that a class has a non-trivial
8740/// special member, figure out why.
8741void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
8742  QualType QT(T, 0U);
8743  CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
8744
8745  // Check whether the member was user-declared.
8746  switch (member) {
8747  case CXXInvalid:
8748    break;
8749
8750  case CXXDefaultConstructor:
8751    if (RD->hasUserDeclaredConstructor()) {
8752      typedef CXXRecordDecl::ctor_iterator ctor_iter;
8753      for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){
8754        const FunctionDecl *body = 0;
8755        ci->hasBody(body);
8756        if (!body || !cast<CXXConstructorDecl>(body)->isImplicitlyDefined()) {
8757          SourceLocation CtorLoc = ci->getLocation();
8758          Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
8759          return;
8760        }
8761      }
8762
8763      llvm_unreachable("found no user-declared constructors");
8764    }
8765    break;
8766
8767  case CXXCopyConstructor:
8768    if (RD->hasUserDeclaredCopyConstructor()) {
8769      SourceLocation CtorLoc =
8770        RD->getCopyConstructor(0)->getLocation();
8771      Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
8772      return;
8773    }
8774    break;
8775
8776  case CXXMoveConstructor:
8777    if (RD->hasUserDeclaredMoveConstructor()) {
8778      SourceLocation CtorLoc = RD->getMoveConstructor()->getLocation();
8779      Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
8780      return;
8781    }
8782    break;
8783
8784  case CXXCopyAssignment:
8785    if (RD->hasUserDeclaredCopyAssignment()) {
8786      // FIXME: this should use the location of the copy
8787      // assignment, not the type.
8788      SourceLocation TyLoc = RD->getSourceRange().getBegin();
8789      Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
8790      return;
8791    }
8792    break;
8793
8794  case CXXMoveAssignment:
8795    if (RD->hasUserDeclaredMoveAssignment()) {
8796      SourceLocation AssignLoc = RD->getMoveAssignmentOperator()->getLocation();
8797      Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member;
8798      return;
8799    }
8800    break;
8801
8802  case CXXDestructor:
8803    if (RD->hasUserDeclaredDestructor()) {
8804      SourceLocation DtorLoc = LookupDestructor(RD)->getLocation();
8805      Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
8806      return;
8807    }
8808    break;
8809  }
8810
8811  typedef CXXRecordDecl::base_class_iterator base_iter;
8812
8813  // Virtual bases and members inhibit trivial copying/construction,
8814  // but not trivial destruction.
8815  if (member != CXXDestructor) {
8816    // Check for virtual bases.  vbases includes indirect virtual bases,
8817    // so we just iterate through the direct bases.
8818    for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
8819      if (bi->isVirtual()) {
8820        SourceLocation BaseLoc = bi->getSourceRange().getBegin();
8821        Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
8822        return;
8823      }
8824
8825    // Check for virtual methods.
8826    typedef CXXRecordDecl::method_iterator meth_iter;
8827    for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
8828         ++mi) {
8829      if (mi->isVirtual()) {
8830        SourceLocation MLoc = mi->getSourceRange().getBegin();
8831        Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
8832        return;
8833      }
8834    }
8835  }
8836
8837  bool (CXXRecordDecl::*hasTrivial)() const;
8838  switch (member) {
8839  case CXXDefaultConstructor:
8840    hasTrivial = &CXXRecordDecl::hasTrivialDefaultConstructor; break;
8841  case CXXCopyConstructor:
8842    hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
8843  case CXXCopyAssignment:
8844    hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
8845  case CXXDestructor:
8846    hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
8847  default:
8848    llvm_unreachable("unexpected special member");
8849  }
8850
8851  // Check for nontrivial bases (and recurse).
8852  for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
8853    const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
8854    assert(BaseRT && "Don't know how to handle dependent bases");
8855    CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
8856    if (!(BaseRecTy->*hasTrivial)()) {
8857      SourceLocation BaseLoc = bi->getSourceRange().getBegin();
8858      Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
8859      DiagnoseNontrivial(BaseRT, member);
8860      return;
8861    }
8862  }
8863
8864  // Check for nontrivial members (and recurse).
8865  typedef RecordDecl::field_iterator field_iter;
8866  for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
8867       ++fi) {
8868    QualType EltTy = Context.getBaseElementType((*fi)->getType());
8869    if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
8870      CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
8871
8872      if (!(EltRD->*hasTrivial)()) {
8873        SourceLocation FLoc = (*fi)->getLocation();
8874        Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
8875        DiagnoseNontrivial(EltRT, member);
8876        return;
8877      }
8878    }
8879
8880    if (EltTy->isObjCLifetimeType()) {
8881      switch (EltTy.getObjCLifetime()) {
8882      case Qualifiers::OCL_None:
8883      case Qualifiers::OCL_ExplicitNone:
8884        break;
8885
8886      case Qualifiers::OCL_Autoreleasing:
8887      case Qualifiers::OCL_Weak:
8888      case Qualifiers::OCL_Strong:
8889        Diag((*fi)->getLocation(), diag::note_nontrivial_objc_ownership)
8890          << QT << EltTy.getObjCLifetime();
8891        return;
8892      }
8893    }
8894  }
8895
8896  llvm_unreachable("found no explanation for non-trivial member");
8897}
8898
8899/// TranslateIvarVisibility - Translate visibility from a token ID to an
8900///  AST enum value.
8901static ObjCIvarDecl::AccessControl
8902TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
8903  switch (ivarVisibility) {
8904  default: llvm_unreachable("Unknown visitibility kind");
8905  case tok::objc_private: return ObjCIvarDecl::Private;
8906  case tok::objc_public: return ObjCIvarDecl::Public;
8907  case tok::objc_protected: return ObjCIvarDecl::Protected;
8908  case tok::objc_package: return ObjCIvarDecl::Package;
8909  }
8910}
8911
8912/// ActOnIvar - Each ivar field of an objective-c class is passed into this
8913/// in order to create an IvarDecl object for it.
8914Decl *Sema::ActOnIvar(Scope *S,
8915                                SourceLocation DeclStart,
8916                                Declarator &D, Expr *BitfieldWidth,
8917                                tok::ObjCKeywordKind Visibility) {
8918
8919  IdentifierInfo *II = D.getIdentifier();
8920  Expr *BitWidth = (Expr*)BitfieldWidth;
8921  SourceLocation Loc = DeclStart;
8922  if (II) Loc = D.getIdentifierLoc();
8923
8924  // FIXME: Unnamed fields can be handled in various different ways, for
8925  // example, unnamed unions inject all members into the struct namespace!
8926
8927  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8928  QualType T = TInfo->getType();
8929
8930  if (BitWidth) {
8931    // 6.7.2.1p3, 6.7.2.1p4
8932    if (VerifyBitField(Loc, II, T, BitWidth)) {
8933      D.setInvalidType();
8934      BitWidth = 0;
8935    }
8936  } else {
8937    // Not a bitfield.
8938
8939    // validate II.
8940
8941  }
8942  if (T->isReferenceType()) {
8943    Diag(Loc, diag::err_ivar_reference_type);
8944    D.setInvalidType();
8945  }
8946  // C99 6.7.2.1p8: A member of a structure or union may have any type other
8947  // than a variably modified type.
8948  else if (T->isVariablyModifiedType()) {
8949    Diag(Loc, diag::err_typecheck_ivar_variable_size);
8950    D.setInvalidType();
8951  }
8952
8953  // Get the visibility (access control) for this ivar.
8954  ObjCIvarDecl::AccessControl ac =
8955    Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
8956                                        : ObjCIvarDecl::None;
8957  // Must set ivar's DeclContext to its enclosing interface.
8958  ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
8959  ObjCContainerDecl *EnclosingContext;
8960  if (ObjCImplementationDecl *IMPDecl =
8961      dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
8962    if (!LangOpts.ObjCNonFragileABI2) {
8963    // Case of ivar declared in an implementation. Context is that of its class.
8964      EnclosingContext = IMPDecl->getClassInterface();
8965      assert(EnclosingContext && "Implementation has no class interface!");
8966    }
8967    else
8968      EnclosingContext = EnclosingDecl;
8969  } else {
8970    if (ObjCCategoryDecl *CDecl =
8971        dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
8972      if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) {
8973        Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
8974        return 0;
8975      }
8976    }
8977    EnclosingContext = EnclosingDecl;
8978  }
8979
8980  // Construct the decl.
8981  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
8982                                             DeclStart, Loc, II, T,
8983                                             TInfo, ac, (Expr *)BitfieldWidth);
8984
8985  if (II) {
8986    NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
8987                                           ForRedeclaration);
8988    if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
8989        && !isa<TagDecl>(PrevDecl)) {
8990      Diag(Loc, diag::err_duplicate_member) << II;
8991      Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
8992      NewID->setInvalidDecl();
8993    }
8994  }
8995
8996  // Process attributes attached to the ivar.
8997  ProcessDeclAttributes(S, NewID, D);
8998
8999  if (D.isInvalidType())
9000    NewID->setInvalidDecl();
9001
9002  // In ARC, infer 'retaining' for ivars of retainable type.
9003  if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
9004    NewID->setInvalidDecl();
9005
9006  if (D.getDeclSpec().isModulePrivateSpecified())
9007    NewID->setModulePrivate();
9008
9009  if (II) {
9010    // FIXME: When interfaces are DeclContexts, we'll need to add
9011    // these to the interface.
9012    S->AddDecl(NewID);
9013    IdResolver.AddDecl(NewID);
9014  }
9015
9016  return NewID;
9017}
9018
9019/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
9020/// class and class extensions. For every class @interface and class
9021/// extension @interface, if the last ivar is a bitfield of any type,
9022/// then add an implicit `char :0` ivar to the end of that interface.
9023void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
9024                             SmallVectorImpl<Decl *> &AllIvarDecls) {
9025  if (!LangOpts.ObjCNonFragileABI2 || AllIvarDecls.empty())
9026    return;
9027
9028  Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
9029  ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
9030
9031  if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
9032    return;
9033  ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
9034  if (!ID) {
9035    if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
9036      if (!CD->IsClassExtension())
9037        return;
9038    }
9039    // No need to add this to end of @implementation.
9040    else
9041      return;
9042  }
9043  // All conditions are met. Add a new bitfield to the tail end of ivars.
9044  llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
9045  Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
9046
9047  Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
9048                              DeclLoc, DeclLoc, 0,
9049                              Context.CharTy,
9050                              Context.getTrivialTypeSourceInfo(Context.CharTy,
9051                                                               DeclLoc),
9052                              ObjCIvarDecl::Private, BW,
9053                              true);
9054  AllIvarDecls.push_back(Ivar);
9055}
9056
9057void Sema::ActOnFields(Scope* S,
9058                       SourceLocation RecLoc, Decl *EnclosingDecl,
9059                       llvm::ArrayRef<Decl *> Fields,
9060                       SourceLocation LBrac, SourceLocation RBrac,
9061                       AttributeList *Attr) {
9062  assert(EnclosingDecl && "missing record or interface decl");
9063
9064  // If the decl this is being inserted into is invalid, then it may be a
9065  // redeclaration or some other bogus case.  Don't try to add fields to it.
9066  if (EnclosingDecl->isInvalidDecl())
9067    return;
9068
9069  // Verify that all the fields are okay.
9070  unsigned NumNamedMembers = 0;
9071  SmallVector<FieldDecl*, 32> RecFields;
9072
9073  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
9074  bool ARCErrReported = false;
9075  for (llvm::ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
9076       i != end; ++i) {
9077    FieldDecl *FD = cast<FieldDecl>(*i);
9078
9079    // Get the type for the field.
9080    const Type *FDTy = FD->getType().getTypePtr();
9081
9082    if (!FD->isAnonymousStructOrUnion()) {
9083      // Remember all fields written by the user.
9084      RecFields.push_back(FD);
9085    }
9086
9087    // If the field is already invalid for some reason, don't emit more
9088    // diagnostics about it.
9089    if (FD->isInvalidDecl()) {
9090      EnclosingDecl->setInvalidDecl();
9091      continue;
9092    }
9093
9094    // C99 6.7.2.1p2:
9095    //   A structure or union shall not contain a member with
9096    //   incomplete or function type (hence, a structure shall not
9097    //   contain an instance of itself, but may contain a pointer to
9098    //   an instance of itself), except that the last member of a
9099    //   structure with more than one named member may have incomplete
9100    //   array type; such a structure (and any union containing,
9101    //   possibly recursively, a member that is such a structure)
9102    //   shall not be a member of a structure or an element of an
9103    //   array.
9104    if (FDTy->isFunctionType()) {
9105      // Field declared as a function.
9106      Diag(FD->getLocation(), diag::err_field_declared_as_function)
9107        << FD->getDeclName();
9108      FD->setInvalidDecl();
9109      EnclosingDecl->setInvalidDecl();
9110      continue;
9111    } else if (FDTy->isIncompleteArrayType() && Record &&
9112               ((i + 1 == Fields.end() && !Record->isUnion()) ||
9113                ((getLangOptions().MicrosoftExt ||
9114                  getLangOptions().CPlusPlus) &&
9115                 (i + 1 == Fields.end() || Record->isUnion())))) {
9116      // Flexible array member.
9117      // Microsoft and g++ is more permissive regarding flexible array.
9118      // It will accept flexible array in union and also
9119      // as the sole element of a struct/class.
9120      if (getLangOptions().MicrosoftExt) {
9121        if (Record->isUnion())
9122          Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
9123            << FD->getDeclName();
9124        else if (Fields.size() == 1)
9125          Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
9126            << FD->getDeclName() << Record->getTagKind();
9127      } else if (getLangOptions().CPlusPlus) {
9128        if (Record->isUnion())
9129          Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
9130            << FD->getDeclName();
9131        else if (Fields.size() == 1)
9132          Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
9133            << FD->getDeclName() << Record->getTagKind();
9134      } else if (NumNamedMembers < 1) {
9135        Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
9136          << FD->getDeclName();
9137        FD->setInvalidDecl();
9138        EnclosingDecl->setInvalidDecl();
9139        continue;
9140      }
9141      if (!FD->getType()->isDependentType() &&
9142          !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
9143        Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
9144          << FD->getDeclName() << FD->getType();
9145        FD->setInvalidDecl();
9146        EnclosingDecl->setInvalidDecl();
9147        continue;
9148      }
9149      // Okay, we have a legal flexible array member at the end of the struct.
9150      if (Record)
9151        Record->setHasFlexibleArrayMember(true);
9152    } else if (!FDTy->isDependentType() &&
9153               RequireCompleteType(FD->getLocation(), FD->getType(),
9154                                   diag::err_field_incomplete)) {
9155      // Incomplete type
9156      FD->setInvalidDecl();
9157      EnclosingDecl->setInvalidDecl();
9158      continue;
9159    } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
9160      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
9161        // If this is a member of a union, then entire union becomes "flexible".
9162        if (Record && Record->isUnion()) {
9163          Record->setHasFlexibleArrayMember(true);
9164        } else {
9165          // If this is a struct/class and this is not the last element, reject
9166          // it.  Note that GCC supports variable sized arrays in the middle of
9167          // structures.
9168          if (i + 1 != Fields.end())
9169            Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
9170              << FD->getDeclName() << FD->getType();
9171          else {
9172            // We support flexible arrays at the end of structs in
9173            // other structs as an extension.
9174            Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
9175              << FD->getDeclName();
9176            if (Record)
9177              Record->setHasFlexibleArrayMember(true);
9178          }
9179        }
9180      }
9181      if (Record && FDTTy->getDecl()->hasObjectMember())
9182        Record->setHasObjectMember(true);
9183    } else if (FDTy->isObjCObjectType()) {
9184      /// A field cannot be an Objective-c object
9185      Diag(FD->getLocation(), diag::err_statically_allocated_object)
9186        << FixItHint::CreateInsertion(FD->getLocation(), "*");
9187      QualType T = Context.getObjCObjectPointerType(FD->getType());
9188      FD->setType(T);
9189    }
9190    else if (!getLangOptions().CPlusPlus) {
9191      if (getLangOptions().ObjCAutoRefCount && Record && !ARCErrReported) {
9192        // It's an error in ARC if a field has lifetime.
9193        // We don't want to report this in a system header, though,
9194        // so we just make the field unavailable.
9195        // FIXME: that's really not sufficient; we need to make the type
9196        // itself invalid to, say, initialize or copy.
9197        QualType T = FD->getType();
9198        Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
9199        if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
9200          SourceLocation loc = FD->getLocation();
9201          if (getSourceManager().isInSystemHeader(loc)) {
9202            if (!FD->hasAttr<UnavailableAttr>()) {
9203              FD->addAttr(new (Context) UnavailableAttr(loc, Context,
9204                                "this system field has retaining ownership"));
9205            }
9206          } else {
9207            Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct)
9208              << T->isBlockPointerType();
9209          }
9210          ARCErrReported = true;
9211        }
9212      }
9213      else if (getLangOptions().ObjC1 &&
9214               getLangOptions().getGC() != LangOptions::NonGC &&
9215               Record && !Record->hasObjectMember()) {
9216        if (FD->getType()->isObjCObjectPointerType() ||
9217            FD->getType().isObjCGCStrong())
9218          Record->setHasObjectMember(true);
9219        else if (Context.getAsArrayType(FD->getType())) {
9220          QualType BaseType = Context.getBaseElementType(FD->getType());
9221          if (BaseType->isRecordType() &&
9222              BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
9223            Record->setHasObjectMember(true);
9224          else if (BaseType->isObjCObjectPointerType() ||
9225                   BaseType.isObjCGCStrong())
9226                 Record->setHasObjectMember(true);
9227        }
9228      }
9229    }
9230    // Keep track of the number of named members.
9231    if (FD->getIdentifier())
9232      ++NumNamedMembers;
9233  }
9234
9235  // Okay, we successfully defined 'Record'.
9236  if (Record) {
9237    bool Completed = false;
9238    if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
9239      if (!CXXRecord->isInvalidDecl()) {
9240        // Set access bits correctly on the directly-declared conversions.
9241        UnresolvedSetImpl *Convs = CXXRecord->getConversionFunctions();
9242        for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end();
9243             I != E; ++I)
9244          Convs->setAccess(I, (*I)->getAccess());
9245
9246        if (!CXXRecord->isDependentType()) {
9247          // Objective-C Automatic Reference Counting:
9248          //   If a class has a non-static data member of Objective-C pointer
9249          //   type (or array thereof), it is a non-POD type and its
9250          //   default constructor (if any), copy constructor, copy assignment
9251          //   operator, and destructor are non-trivial.
9252          //
9253          // This rule is also handled by CXXRecordDecl::completeDefinition().
9254          // However, here we check whether this particular class is only
9255          // non-POD because of the presence of an Objective-C pointer member.
9256          // If so, objects of this type cannot be shared between code compiled
9257          // with instant objects and code compiled with manual retain/release.
9258          if (getLangOptions().ObjCAutoRefCount &&
9259              CXXRecord->hasObjectMember() &&
9260              CXXRecord->getLinkage() == ExternalLinkage) {
9261            if (CXXRecord->isPOD()) {
9262              Diag(CXXRecord->getLocation(),
9263                   diag::warn_arc_non_pod_class_with_object_member)
9264               << CXXRecord;
9265            } else {
9266              // FIXME: Fix-Its would be nice here, but finding a good location
9267              // for them is going to be tricky.
9268              if (CXXRecord->hasTrivialCopyConstructor())
9269                Diag(CXXRecord->getLocation(),
9270                     diag::warn_arc_trivial_member_function_with_object_member)
9271                  << CXXRecord << 0;
9272              if (CXXRecord->hasTrivialCopyAssignment())
9273                Diag(CXXRecord->getLocation(),
9274                     diag::warn_arc_trivial_member_function_with_object_member)
9275                << CXXRecord << 1;
9276              if (CXXRecord->hasTrivialDestructor())
9277                Diag(CXXRecord->getLocation(),
9278                     diag::warn_arc_trivial_member_function_with_object_member)
9279                << CXXRecord << 2;
9280            }
9281          }
9282
9283          // Adjust user-defined destructor exception spec.
9284          if (getLangOptions().CPlusPlus0x &&
9285              CXXRecord->hasUserDeclaredDestructor())
9286            AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor());
9287
9288          // Add any implicitly-declared members to this class.
9289          AddImplicitlyDeclaredMembersToClass(CXXRecord);
9290
9291          // If we have virtual base classes, we may end up finding multiple
9292          // final overriders for a given virtual function. Check for this
9293          // problem now.
9294          if (CXXRecord->getNumVBases()) {
9295            CXXFinalOverriderMap FinalOverriders;
9296            CXXRecord->getFinalOverriders(FinalOverriders);
9297
9298            for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
9299                                             MEnd = FinalOverriders.end();
9300                 M != MEnd; ++M) {
9301              for (OverridingMethods::iterator SO = M->second.begin(),
9302                                            SOEnd = M->second.end();
9303                   SO != SOEnd; ++SO) {
9304                assert(SO->second.size() > 0 &&
9305                       "Virtual function without overridding functions?");
9306                if (SO->second.size() == 1)
9307                  continue;
9308
9309                // C++ [class.virtual]p2:
9310                //   In a derived class, if a virtual member function of a base
9311                //   class subobject has more than one final overrider the
9312                //   program is ill-formed.
9313                Diag(Record->getLocation(), diag::err_multiple_final_overriders)
9314                  << (NamedDecl *)M->first << Record;
9315                Diag(M->first->getLocation(),
9316                     diag::note_overridden_virtual_function);
9317                for (OverridingMethods::overriding_iterator
9318                          OM = SO->second.begin(),
9319                       OMEnd = SO->second.end();
9320                     OM != OMEnd; ++OM)
9321                  Diag(OM->Method->getLocation(), diag::note_final_overrider)
9322                    << (NamedDecl *)M->first << OM->Method->getParent();
9323
9324                Record->setInvalidDecl();
9325              }
9326            }
9327            CXXRecord->completeDefinition(&FinalOverriders);
9328            Completed = true;
9329          }
9330        }
9331      }
9332    }
9333
9334    if (!Completed)
9335      Record->completeDefinition();
9336
9337    // Now that the record is complete, do any delayed exception spec checks
9338    // we were missing.
9339    while (!DelayedDestructorExceptionSpecChecks.empty()) {
9340      const CXXDestructorDecl *Dtor =
9341              DelayedDestructorExceptionSpecChecks.back().first;
9342      if (Dtor->getParent() != Record)
9343        break;
9344
9345      assert(!Dtor->getParent()->isDependentType() &&
9346          "Should not ever add destructors of templates into the list.");
9347      CheckOverridingFunctionExceptionSpec(Dtor,
9348          DelayedDestructorExceptionSpecChecks.back().second);
9349      DelayedDestructorExceptionSpecChecks.pop_back();
9350    }
9351
9352  } else {
9353    ObjCIvarDecl **ClsFields =
9354      reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
9355    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
9356      ID->setEndOfDefinitionLoc(RBrac);
9357      // Add ivar's to class's DeclContext.
9358      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
9359        ClsFields[i]->setLexicalDeclContext(ID);
9360        ID->addDecl(ClsFields[i]);
9361      }
9362      // Must enforce the rule that ivars in the base classes may not be
9363      // duplicates.
9364      if (ID->getSuperClass())
9365        DiagnoseDuplicateIvars(ID, ID->getSuperClass());
9366    } else if (ObjCImplementationDecl *IMPDecl =
9367                  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
9368      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
9369      for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
9370        // Ivar declared in @implementation never belongs to the implementation.
9371        // Only it is in implementation's lexical context.
9372        ClsFields[I]->setLexicalDeclContext(IMPDecl);
9373      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
9374    } else if (ObjCCategoryDecl *CDecl =
9375                dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
9376      // case of ivars in class extension; all other cases have been
9377      // reported as errors elsewhere.
9378      // FIXME. Class extension does not have a LocEnd field.
9379      // CDecl->setLocEnd(RBrac);
9380      // Add ivar's to class extension's DeclContext.
9381      // Diagnose redeclaration of private ivars.
9382      ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
9383      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
9384        if (IDecl) {
9385          if (const ObjCIvarDecl *ClsIvar =
9386              IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
9387            Diag(ClsFields[i]->getLocation(),
9388                 diag::err_duplicate_ivar_declaration);
9389            Diag(ClsIvar->getLocation(), diag::note_previous_definition);
9390            continue;
9391          }
9392          for (const ObjCCategoryDecl *ClsExtDecl =
9393                IDecl->getFirstClassExtension();
9394               ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
9395            if (const ObjCIvarDecl *ClsExtIvar =
9396                ClsExtDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
9397              Diag(ClsFields[i]->getLocation(),
9398                   diag::err_duplicate_ivar_declaration);
9399              Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
9400              continue;
9401            }
9402          }
9403        }
9404        ClsFields[i]->setLexicalDeclContext(CDecl);
9405        CDecl->addDecl(ClsFields[i]);
9406      }
9407    }
9408  }
9409
9410  if (Attr)
9411    ProcessDeclAttributeList(S, Record, Attr);
9412
9413  // If there's a #pragma GCC visibility in scope, and this isn't a subclass,
9414  // set the visibility of this record.
9415  if (Record && !Record->getDeclContext()->isRecord())
9416    AddPushedVisibilityAttribute(Record);
9417}
9418
9419/// \brief Determine whether the given integral value is representable within
9420/// the given type T.
9421static bool isRepresentableIntegerValue(ASTContext &Context,
9422                                        llvm::APSInt &Value,
9423                                        QualType T) {
9424  assert(T->isIntegralType(Context) && "Integral type required!");
9425  unsigned BitWidth = Context.getIntWidth(T);
9426
9427  if (Value.isUnsigned() || Value.isNonNegative()) {
9428    if (T->isSignedIntegerOrEnumerationType())
9429      --BitWidth;
9430    return Value.getActiveBits() <= BitWidth;
9431  }
9432  return Value.getMinSignedBits() <= BitWidth;
9433}
9434
9435// \brief Given an integral type, return the next larger integral type
9436// (or a NULL type of no such type exists).
9437static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
9438  // FIXME: Int128/UInt128 support, which also needs to be introduced into
9439  // enum checking below.
9440  assert(T->isIntegralType(Context) && "Integral type required!");
9441  const unsigned NumTypes = 4;
9442  QualType SignedIntegralTypes[NumTypes] = {
9443    Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
9444  };
9445  QualType UnsignedIntegralTypes[NumTypes] = {
9446    Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
9447    Context.UnsignedLongLongTy
9448  };
9449
9450  unsigned BitWidth = Context.getTypeSize(T);
9451  QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
9452                                                        : UnsignedIntegralTypes;
9453  for (unsigned I = 0; I != NumTypes; ++I)
9454    if (Context.getTypeSize(Types[I]) > BitWidth)
9455      return Types[I];
9456
9457  return QualType();
9458}
9459
9460EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
9461                                          EnumConstantDecl *LastEnumConst,
9462                                          SourceLocation IdLoc,
9463                                          IdentifierInfo *Id,
9464                                          Expr *Val) {
9465  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
9466  llvm::APSInt EnumVal(IntWidth);
9467  QualType EltTy;
9468
9469  if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
9470    Val = 0;
9471
9472  if (Val)
9473    Val = DefaultLvalueConversion(Val).take();
9474
9475  if (Val) {
9476    if (Enum->isDependentType() || Val->isTypeDependent())
9477      EltTy = Context.DependentTy;
9478    else {
9479      // C99 6.7.2.2p2: Make sure we have an integer constant expression.
9480      SourceLocation ExpLoc;
9481      if (!Val->isValueDependent() &&
9482          VerifyIntegerConstantExpression(Val, &EnumVal)) {
9483        Val = 0;
9484      } else {
9485        if (!getLangOptions().CPlusPlus) {
9486          // C99 6.7.2.2p2:
9487          //   The expression that defines the value of an enumeration constant
9488          //   shall be an integer constant expression that has a value
9489          //   representable as an int.
9490
9491          // Complain if the value is not representable in an int.
9492          if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
9493            Diag(IdLoc, diag::ext_enum_value_not_int)
9494              << EnumVal.toString(10) << Val->getSourceRange()
9495              << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
9496          else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
9497            // Force the type of the expression to 'int'.
9498            Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
9499          }
9500        }
9501
9502        if (Enum->isFixed()) {
9503          EltTy = Enum->getIntegerType();
9504
9505          // C++0x [dcl.enum]p5:
9506          //   ... if the initializing value of an enumerator cannot be
9507          //   represented by the underlying type, the program is ill-formed.
9508          if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
9509            if (getLangOptions().MicrosoftExt) {
9510              Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
9511              Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
9512            } else
9513              Diag(IdLoc, diag::err_enumerator_too_large)
9514                << EltTy;
9515          } else
9516            Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
9517        }
9518        else {
9519          // C++0x [dcl.enum]p5:
9520          //   If the underlying type is not fixed, the type of each enumerator
9521          //   is the type of its initializing value:
9522          //     - If an initializer is specified for an enumerator, the
9523          //       initializing value has the same type as the expression.
9524          EltTy = Val->getType();
9525        }
9526      }
9527    }
9528  }
9529
9530  if (!Val) {
9531    if (Enum->isDependentType())
9532      EltTy = Context.DependentTy;
9533    else if (!LastEnumConst) {
9534      // C++0x [dcl.enum]p5:
9535      //   If the underlying type is not fixed, the type of each enumerator
9536      //   is the type of its initializing value:
9537      //     - If no initializer is specified for the first enumerator, the
9538      //       initializing value has an unspecified integral type.
9539      //
9540      // GCC uses 'int' for its unspecified integral type, as does
9541      // C99 6.7.2.2p3.
9542      if (Enum->isFixed()) {
9543        EltTy = Enum->getIntegerType();
9544      }
9545      else {
9546        EltTy = Context.IntTy;
9547      }
9548    } else {
9549      // Assign the last value + 1.
9550      EnumVal = LastEnumConst->getInitVal();
9551      ++EnumVal;
9552      EltTy = LastEnumConst->getType();
9553
9554      // Check for overflow on increment.
9555      if (EnumVal < LastEnumConst->getInitVal()) {
9556        // C++0x [dcl.enum]p5:
9557        //   If the underlying type is not fixed, the type of each enumerator
9558        //   is the type of its initializing value:
9559        //
9560        //     - Otherwise the type of the initializing value is the same as
9561        //       the type of the initializing value of the preceding enumerator
9562        //       unless the incremented value is not representable in that type,
9563        //       in which case the type is an unspecified integral type
9564        //       sufficient to contain the incremented value. If no such type
9565        //       exists, the program is ill-formed.
9566        QualType T = getNextLargerIntegralType(Context, EltTy);
9567        if (T.isNull() || Enum->isFixed()) {
9568          // There is no integral type larger enough to represent this
9569          // value. Complain, then allow the value to wrap around.
9570          EnumVal = LastEnumConst->getInitVal();
9571          EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
9572          ++EnumVal;
9573          if (Enum->isFixed())
9574            // When the underlying type is fixed, this is ill-formed.
9575            Diag(IdLoc, diag::err_enumerator_wrapped)
9576              << EnumVal.toString(10)
9577              << EltTy;
9578          else
9579            Diag(IdLoc, diag::warn_enumerator_too_large)
9580              << EnumVal.toString(10);
9581        } else {
9582          EltTy = T;
9583        }
9584
9585        // Retrieve the last enumerator's value, extent that type to the
9586        // type that is supposed to be large enough to represent the incremented
9587        // value, then increment.
9588        EnumVal = LastEnumConst->getInitVal();
9589        EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
9590        EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
9591        ++EnumVal;
9592
9593        // If we're not in C++, diagnose the overflow of enumerator values,
9594        // which in C99 means that the enumerator value is not representable in
9595        // an int (C99 6.7.2.2p2). However, we support GCC's extension that
9596        // permits enumerator values that are representable in some larger
9597        // integral type.
9598        if (!getLangOptions().CPlusPlus && !T.isNull())
9599          Diag(IdLoc, diag::warn_enum_value_overflow);
9600      } else if (!getLangOptions().CPlusPlus &&
9601                 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
9602        // Enforce C99 6.7.2.2p2 even when we compute the next value.
9603        Diag(IdLoc, diag::ext_enum_value_not_int)
9604          << EnumVal.toString(10) << 1;
9605      }
9606    }
9607  }
9608
9609  if (!EltTy->isDependentType()) {
9610    // Make the enumerator value match the signedness and size of the
9611    // enumerator's type.
9612    EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
9613    EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
9614  }
9615
9616  return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
9617                                  Val, EnumVal);
9618}
9619
9620
9621Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
9622                              SourceLocation IdLoc, IdentifierInfo *Id,
9623                              AttributeList *Attr,
9624                              SourceLocation EqualLoc, Expr *val) {
9625  EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
9626  EnumConstantDecl *LastEnumConst =
9627    cast_or_null<EnumConstantDecl>(lastEnumConst);
9628  Expr *Val = static_cast<Expr*>(val);
9629
9630  // The scope passed in may not be a decl scope.  Zip up the scope tree until
9631  // we find one that is.
9632  S = getNonFieldDeclScope(S);
9633
9634  // Verify that there isn't already something declared with this name in this
9635  // scope.
9636  NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
9637                                         ForRedeclaration);
9638  if (PrevDecl && PrevDecl->isTemplateParameter()) {
9639    // Maybe we will complain about the shadowed template parameter.
9640    DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
9641    // Just pretend that we didn't see the previous declaration.
9642    PrevDecl = 0;
9643  }
9644
9645  if (PrevDecl) {
9646    // When in C++, we may get a TagDecl with the same name; in this case the
9647    // enum constant will 'hide' the tag.
9648    assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
9649           "Received TagDecl when not in C++!");
9650    if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
9651      if (isa<EnumConstantDecl>(PrevDecl))
9652        Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
9653      else
9654        Diag(IdLoc, diag::err_redefinition) << Id;
9655      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
9656      return 0;
9657    }
9658  }
9659
9660  // C++ [class.mem]p13:
9661  //   If T is the name of a class, then each of the following shall have a
9662  //   name different from T:
9663  //     - every enumerator of every member of class T that is an enumerated
9664  //       type
9665  if (CXXRecordDecl *Record
9666                      = dyn_cast<CXXRecordDecl>(
9667                             TheEnumDecl->getDeclContext()->getRedeclContext()))
9668    if (Record->getIdentifier() && Record->getIdentifier() == Id)
9669      Diag(IdLoc, diag::err_member_name_of_class) << Id;
9670
9671  EnumConstantDecl *New =
9672    CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
9673
9674  if (New) {
9675    // Process attributes.
9676    if (Attr) ProcessDeclAttributeList(S, New, Attr);
9677
9678    // Register this decl in the current scope stack.
9679    New->setAccess(TheEnumDecl->getAccess());
9680    PushOnScopeChains(New, S);
9681  }
9682
9683  return New;
9684}
9685
9686void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
9687                         SourceLocation RBraceLoc, Decl *EnumDeclX,
9688                         Decl **Elements, unsigned NumElements,
9689                         Scope *S, AttributeList *Attr) {
9690  EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
9691  QualType EnumType = Context.getTypeDeclType(Enum);
9692
9693  if (Attr)
9694    ProcessDeclAttributeList(S, Enum, Attr);
9695
9696  if (Enum->isDependentType()) {
9697    for (unsigned i = 0; i != NumElements; ++i) {
9698      EnumConstantDecl *ECD =
9699        cast_or_null<EnumConstantDecl>(Elements[i]);
9700      if (!ECD) continue;
9701
9702      ECD->setType(EnumType);
9703    }
9704
9705    Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
9706    return;
9707  }
9708
9709  // TODO: If the result value doesn't fit in an int, it must be a long or long
9710  // long value.  ISO C does not support this, but GCC does as an extension,
9711  // emit a warning.
9712  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
9713  unsigned CharWidth = Context.getTargetInfo().getCharWidth();
9714  unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
9715
9716  // Verify that all the values are okay, compute the size of the values, and
9717  // reverse the list.
9718  unsigned NumNegativeBits = 0;
9719  unsigned NumPositiveBits = 0;
9720
9721  // Keep track of whether all elements have type int.
9722  bool AllElementsInt = true;
9723
9724  for (unsigned i = 0; i != NumElements; ++i) {
9725    EnumConstantDecl *ECD =
9726      cast_or_null<EnumConstantDecl>(Elements[i]);
9727    if (!ECD) continue;  // Already issued a diagnostic.
9728
9729    const llvm::APSInt &InitVal = ECD->getInitVal();
9730
9731    // Keep track of the size of positive and negative values.
9732    if (InitVal.isUnsigned() || InitVal.isNonNegative())
9733      NumPositiveBits = std::max(NumPositiveBits,
9734                                 (unsigned)InitVal.getActiveBits());
9735    else
9736      NumNegativeBits = std::max(NumNegativeBits,
9737                                 (unsigned)InitVal.getMinSignedBits());
9738
9739    // Keep track of whether every enum element has type int (very commmon).
9740    if (AllElementsInt)
9741      AllElementsInt = ECD->getType() == Context.IntTy;
9742  }
9743
9744  // Figure out the type that should be used for this enum.
9745  QualType BestType;
9746  unsigned BestWidth;
9747
9748  // C++0x N3000 [conv.prom]p3:
9749  //   An rvalue of an unscoped enumeration type whose underlying
9750  //   type is not fixed can be converted to an rvalue of the first
9751  //   of the following types that can represent all the values of
9752  //   the enumeration: int, unsigned int, long int, unsigned long
9753  //   int, long long int, or unsigned long long int.
9754  // C99 6.4.4.3p2:
9755  //   An identifier declared as an enumeration constant has type int.
9756  // The C99 rule is modified by a gcc extension
9757  QualType BestPromotionType;
9758
9759  bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
9760  // -fshort-enums is the equivalent to specifying the packed attribute on all
9761  // enum definitions.
9762  if (LangOpts.ShortEnums)
9763    Packed = true;
9764
9765  if (Enum->isFixed()) {
9766    BestType = Enum->getIntegerType();
9767    if (BestType->isPromotableIntegerType())
9768      BestPromotionType = Context.getPromotedIntegerType(BestType);
9769    else
9770      BestPromotionType = BestType;
9771    // We don't need to set BestWidth, because BestType is going to be the type
9772    // of the enumerators, but we do anyway because otherwise some compilers
9773    // warn that it might be used uninitialized.
9774    BestWidth = CharWidth;
9775  }
9776  else if (NumNegativeBits) {
9777    // If there is a negative value, figure out the smallest integer type (of
9778    // int/long/longlong) that fits.
9779    // If it's packed, check also if it fits a char or a short.
9780    if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
9781      BestType = Context.SignedCharTy;
9782      BestWidth = CharWidth;
9783    } else if (Packed && NumNegativeBits <= ShortWidth &&
9784               NumPositiveBits < ShortWidth) {
9785      BestType = Context.ShortTy;
9786      BestWidth = ShortWidth;
9787    } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
9788      BestType = Context.IntTy;
9789      BestWidth = IntWidth;
9790    } else {
9791      BestWidth = Context.getTargetInfo().getLongWidth();
9792
9793      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
9794        BestType = Context.LongTy;
9795      } else {
9796        BestWidth = Context.getTargetInfo().getLongLongWidth();
9797
9798        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
9799          Diag(Enum->getLocation(), diag::warn_enum_too_large);
9800        BestType = Context.LongLongTy;
9801      }
9802    }
9803    BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
9804  } else {
9805    // If there is no negative value, figure out the smallest type that fits
9806    // all of the enumerator values.
9807    // If it's packed, check also if it fits a char or a short.
9808    if (Packed && NumPositiveBits <= CharWidth) {
9809      BestType = Context.UnsignedCharTy;
9810      BestPromotionType = Context.IntTy;
9811      BestWidth = CharWidth;
9812    } else if (Packed && NumPositiveBits <= ShortWidth) {
9813      BestType = Context.UnsignedShortTy;
9814      BestPromotionType = Context.IntTy;
9815      BestWidth = ShortWidth;
9816    } else if (NumPositiveBits <= IntWidth) {
9817      BestType = Context.UnsignedIntTy;
9818      BestWidth = IntWidth;
9819      BestPromotionType
9820        = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
9821                           ? Context.UnsignedIntTy : Context.IntTy;
9822    } else if (NumPositiveBits <=
9823               (BestWidth = Context.getTargetInfo().getLongWidth())) {
9824      BestType = Context.UnsignedLongTy;
9825      BestPromotionType
9826        = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
9827                           ? Context.UnsignedLongTy : Context.LongTy;
9828    } else {
9829      BestWidth = Context.getTargetInfo().getLongLongWidth();
9830      assert(NumPositiveBits <= BestWidth &&
9831             "How could an initializer get larger than ULL?");
9832      BestType = Context.UnsignedLongLongTy;
9833      BestPromotionType
9834        = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
9835                           ? Context.UnsignedLongLongTy : Context.LongLongTy;
9836    }
9837  }
9838
9839  // Loop over all of the enumerator constants, changing their types to match
9840  // the type of the enum if needed.
9841  for (unsigned i = 0; i != NumElements; ++i) {
9842    EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
9843    if (!ECD) continue;  // Already issued a diagnostic.
9844
9845    // Standard C says the enumerators have int type, but we allow, as an
9846    // extension, the enumerators to be larger than int size.  If each
9847    // enumerator value fits in an int, type it as an int, otherwise type it the
9848    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
9849    // that X has type 'int', not 'unsigned'.
9850
9851    // Determine whether the value fits into an int.
9852    llvm::APSInt InitVal = ECD->getInitVal();
9853
9854    // If it fits into an integer type, force it.  Otherwise force it to match
9855    // the enum decl type.
9856    QualType NewTy;
9857    unsigned NewWidth;
9858    bool NewSign;
9859    if (!getLangOptions().CPlusPlus &&
9860        !Enum->isFixed() &&
9861        isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
9862      NewTy = Context.IntTy;
9863      NewWidth = IntWidth;
9864      NewSign = true;
9865    } else if (ECD->getType() == BestType) {
9866      // Already the right type!
9867      if (getLangOptions().CPlusPlus)
9868        // C++ [dcl.enum]p4: Following the closing brace of an
9869        // enum-specifier, each enumerator has the type of its
9870        // enumeration.
9871        ECD->setType(EnumType);
9872      continue;
9873    } else {
9874      NewTy = BestType;
9875      NewWidth = BestWidth;
9876      NewSign = BestType->isSignedIntegerOrEnumerationType();
9877    }
9878
9879    // Adjust the APSInt value.
9880    InitVal = InitVal.extOrTrunc(NewWidth);
9881    InitVal.setIsSigned(NewSign);
9882    ECD->setInitVal(InitVal);
9883
9884    // Adjust the Expr initializer and type.
9885    if (ECD->getInitExpr() &&
9886        !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
9887      ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
9888                                                CK_IntegralCast,
9889                                                ECD->getInitExpr(),
9890                                                /*base paths*/ 0,
9891                                                VK_RValue));
9892    if (getLangOptions().CPlusPlus)
9893      // C++ [dcl.enum]p4: Following the closing brace of an
9894      // enum-specifier, each enumerator has the type of its
9895      // enumeration.
9896      ECD->setType(EnumType);
9897    else
9898      ECD->setType(NewTy);
9899  }
9900
9901  Enum->completeDefinition(BestType, BestPromotionType,
9902                           NumPositiveBits, NumNegativeBits);
9903}
9904
9905Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
9906                                  SourceLocation StartLoc,
9907                                  SourceLocation EndLoc) {
9908  StringLiteral *AsmString = cast<StringLiteral>(expr);
9909
9910  FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
9911                                                   AsmString, StartLoc,
9912                                                   EndLoc);
9913  CurContext->addDecl(New);
9914  return New;
9915}
9916
9917DeclResult Sema::ActOnModuleImport(SourceLocation ImportLoc, ModuleIdPath Path) {
9918  Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
9919                                                Module::AllVisible,
9920                                                /*IsIncludeDirective=*/false);
9921  if (!Mod)
9922    return true;
9923
9924  llvm::SmallVector<SourceLocation, 2> IdentifierLocs;
9925  Module *ModCheck = Mod;
9926  for (unsigned I = 0, N = Path.size(); I != N; ++I) {
9927    // If we've run out of module parents, just drop the remaining identifiers.
9928    // We need the length to be consistent.
9929    if (!ModCheck)
9930      break;
9931    ModCheck = ModCheck->Parent;
9932
9933    IdentifierLocs.push_back(Path[I].second);
9934  }
9935
9936  ImportDecl *Import = ImportDecl::Create(Context,
9937                                          Context.getTranslationUnitDecl(),
9938                                          ImportLoc, Mod,
9939                                          IdentifierLocs);
9940  Context.getTranslationUnitDecl()->addDecl(Import);
9941  return Import;
9942}
9943
9944void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
9945                             SourceLocation PragmaLoc,
9946                             SourceLocation NameLoc) {
9947  Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
9948
9949  if (PrevDecl) {
9950    PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
9951  } else {
9952    (void)WeakUndeclaredIdentifiers.insert(
9953      std::pair<IdentifierInfo*,WeakInfo>
9954        (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
9955  }
9956}
9957
9958void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
9959                                IdentifierInfo* AliasName,
9960                                SourceLocation PragmaLoc,
9961                                SourceLocation NameLoc,
9962                                SourceLocation AliasNameLoc) {
9963  Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
9964                                    LookupOrdinaryName);
9965  WeakInfo W = WeakInfo(Name, NameLoc);
9966
9967  if (PrevDecl) {
9968    if (!PrevDecl->hasAttr<AliasAttr>())
9969      if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
9970        DeclApplyPragmaWeak(TUScope, ND, W);
9971  } else {
9972    (void)WeakUndeclaredIdentifiers.insert(
9973      std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
9974  }
9975}
9976
9977Decl *Sema::getObjCDeclContext() const {
9978  return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
9979}
9980
9981AvailabilityResult Sema::getCurContextAvailability() const {
9982  const Decl *D = cast<Decl>(getCurLexicalContext());
9983  // A category implicitly has the availability of the interface.
9984  if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
9985    D = CatD->getClassInterface();
9986
9987  return D->getAvailability();
9988}
9989