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