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