SemaDecl.cpp revision fff3248e69c478cfb4d1a1ffdefb808d5885535b
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 "TypeLocBuilder.h"
16#include "clang/AST/ASTConsumer.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/CXXInheritance.h"
19#include "clang/AST/CharUnits.h"
20#include "clang/AST/CommentDiagnostic.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/EvaluatedExprVisitor.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/StmtCXX.h"
27#include "clang/Basic/PartialDiagnostic.h"
28#include "clang/Basic/SourceManager.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Lex/HeaderSearch.h" // FIXME: Sema shouldn't depend on Lex
31#include "clang/Lex/ModuleLoader.h" // FIXME: Sema shouldn't depend on Lex
32#include "clang/Lex/Preprocessor.h" // FIXME: Sema shouldn't depend on Lex
33#include "clang/Parse/ParseDiagnostic.h"
34#include "clang/Sema/CXXFieldCollector.h"
35#include "clang/Sema/DeclSpec.h"
36#include "clang/Sema/DelayedDiagnostic.h"
37#include "clang/Sema/Initialization.h"
38#include "clang/Sema/Lookup.h"
39#include "clang/Sema/ParsedTemplate.h"
40#include "clang/Sema/Scope.h"
41#include "clang/Sema/ScopeInfo.h"
42#include "llvm/ADT/SmallString.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
59namespace {
60
61class TypeNameValidatorCCC : public CorrectionCandidateCallback {
62 public:
63  TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false)
64      : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass) {
65    WantExpressionKeywords = false;
66    WantCXXNamedCasts = false;
67    WantRemainingKeywords = false;
68  }
69
70  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
71    if (NamedDecl *ND = candidate.getCorrectionDecl())
72      return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
73          (AllowInvalidDecl || !ND->isInvalidDecl());
74    else
75      return !WantClassName && candidate.isKeyword();
76  }
77
78 private:
79  bool AllowInvalidDecl;
80  bool WantClassName;
81};
82
83}
84
85/// \brief Determine whether the token kind starts a simple-type-specifier.
86bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
87  switch (Kind) {
88  // FIXME: Take into account the current language when deciding whether a
89  // token kind is a valid type specifier
90  case tok::kw_short:
91  case tok::kw_long:
92  case tok::kw___int64:
93  case tok::kw___int128:
94  case tok::kw_signed:
95  case tok::kw_unsigned:
96  case tok::kw_void:
97  case tok::kw_char:
98  case tok::kw_int:
99  case tok::kw_half:
100  case tok::kw_float:
101  case tok::kw_double:
102  case tok::kw_wchar_t:
103  case tok::kw_bool:
104  case tok::kw___underlying_type:
105    return true;
106
107  case tok::annot_typename:
108  case tok::kw_char16_t:
109  case tok::kw_char32_t:
110  case tok::kw_typeof:
111  case tok::kw_decltype:
112    return getLangOpts().CPlusPlus;
113
114  default:
115    break;
116  }
117
118  return false;
119}
120
121/// \brief If the identifier refers to a type name within this scope,
122/// return the declaration of that type.
123///
124/// This routine performs ordinary name lookup of the identifier II
125/// within the given scope, with optional C++ scope specifier SS, to
126/// determine whether the name refers to a type. If so, returns an
127/// opaque pointer (actually a QualType) corresponding to that
128/// type. Otherwise, returns NULL.
129///
130/// If name lookup results in an ambiguity, this routine will complain
131/// and then return NULL.
132ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
133                             Scope *S, CXXScopeSpec *SS,
134                             bool isClassName, bool HasTrailingDot,
135                             ParsedType ObjectTypePtr,
136                             bool IsCtorOrDtorName,
137                             bool WantNontrivialTypeSourceInfo,
138                             IdentifierInfo **CorrectedII) {
139  // Determine where we will perform name lookup.
140  DeclContext *LookupCtx = 0;
141  if (ObjectTypePtr) {
142    QualType ObjectType = ObjectTypePtr.get();
143    if (ObjectType->isRecordType())
144      LookupCtx = computeDeclContext(ObjectType);
145  } else if (SS && SS->isNotEmpty()) {
146    LookupCtx = computeDeclContext(*SS, false);
147
148    if (!LookupCtx) {
149      if (isDependentScopeSpecifier(*SS)) {
150        // C++ [temp.res]p3:
151        //   A qualified-id that refers to a type and in which the
152        //   nested-name-specifier depends on a template-parameter (14.6.2)
153        //   shall be prefixed by the keyword typename to indicate that the
154        //   qualified-id denotes a type, forming an
155        //   elaborated-type-specifier (7.1.5.3).
156        //
157        // We therefore do not perform any name lookup if the result would
158        // refer to a member of an unknown specialization.
159        if (!isClassName && !IsCtorOrDtorName)
160          return ParsedType();
161
162        // We know from the grammar that this name refers to a type,
163        // so build a dependent node to describe the type.
164        if (WantNontrivialTypeSourceInfo)
165          return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
166
167        NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
168        QualType T =
169          CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
170                            II, NameLoc);
171
172          return ParsedType::make(T);
173      }
174
175      return ParsedType();
176    }
177
178    if (!LookupCtx->isDependentContext() &&
179        RequireCompleteDeclContext(*SS, LookupCtx))
180      return ParsedType();
181  }
182
183  // FIXME: LookupNestedNameSpecifierName isn't the right kind of
184  // lookup for class-names.
185  LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
186                                      LookupOrdinaryName;
187  LookupResult Result(*this, &II, NameLoc, Kind);
188  if (LookupCtx) {
189    // Perform "qualified" name lookup into the declaration context we
190    // computed, which is either the type of the base of a member access
191    // expression or the declaration context associated with a prior
192    // nested-name-specifier.
193    LookupQualifiedName(Result, LookupCtx);
194
195    if (ObjectTypePtr && Result.empty()) {
196      // C++ [basic.lookup.classref]p3:
197      //   If the unqualified-id is ~type-name, the type-name is looked up
198      //   in the context of the entire postfix-expression. If the type T of
199      //   the object expression is of a class type C, the type-name is also
200      //   looked up in the scope of class C. At least one of the lookups shall
201      //   find a name that refers to (possibly cv-qualified) T.
202      LookupName(Result, S);
203    }
204  } else {
205    // Perform unqualified name lookup.
206    LookupName(Result, S);
207  }
208
209  NamedDecl *IIDecl = 0;
210  switch (Result.getResultKind()) {
211  case LookupResult::NotFound:
212  case LookupResult::NotFoundInCurrentInstantiation:
213    if (CorrectedII) {
214      TypeNameValidatorCCC Validator(true, isClassName);
215      TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
216                                              Kind, S, SS, Validator);
217      IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
218      TemplateTy Template;
219      bool MemberOfUnknownSpecialization;
220      UnqualifiedId TemplateName;
221      TemplateName.setIdentifier(NewII, NameLoc);
222      NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
223      CXXScopeSpec NewSS, *NewSSPtr = SS;
224      if (SS && NNS) {
225        NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
226        NewSSPtr = &NewSS;
227      }
228      if (Correction && (NNS || NewII != &II) &&
229          // Ignore a correction to a template type as the to-be-corrected
230          // identifier is not a template (typo correction for template names
231          // is handled elsewhere).
232          !(getLangOpts().CPlusPlus && NewSSPtr &&
233            isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
234                           false, Template, MemberOfUnknownSpecialization))) {
235        ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
236                                    isClassName, HasTrailingDot, ObjectTypePtr,
237                                    IsCtorOrDtorName,
238                                    WantNontrivialTypeSourceInfo);
239        if (Ty) {
240          std::string CorrectedStr(Correction.getAsString(getLangOpts()));
241          std::string CorrectedQuotedStr(
242              Correction.getQuoted(getLangOpts()));
243          Diag(NameLoc, diag::err_unknown_type_or_class_name_suggest)
244              << Result.getLookupName() << CorrectedQuotedStr << isClassName
245              << FixItHint::CreateReplacement(SourceRange(NameLoc),
246                                              CorrectedStr);
247          if (NamedDecl *FirstDecl = Correction.getCorrectionDecl())
248            Diag(FirstDecl->getLocation(), diag::note_previous_decl)
249              << CorrectedQuotedStr;
250
251          if (SS && NNS)
252            SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
253          *CorrectedII = NewII;
254          return Ty;
255        }
256      }
257    }
258    // If typo correction failed or was not performed, fall through
259  case LookupResult::FoundOverloaded:
260  case LookupResult::FoundUnresolvedValue:
261    Result.suppressDiagnostics();
262    return ParsedType();
263
264  case LookupResult::Ambiguous:
265    // Recover from type-hiding ambiguities by hiding the type.  We'll
266    // do the lookup again when looking for an object, and we can
267    // diagnose the error then.  If we don't do this, then the error
268    // about hiding the type will be immediately followed by an error
269    // that only makes sense if the identifier was treated like a type.
270    if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
271      Result.suppressDiagnostics();
272      return ParsedType();
273    }
274
275    // Look to see if we have a type anywhere in the list of results.
276    for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
277         Res != ResEnd; ++Res) {
278      if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
279        if (!IIDecl ||
280            (*Res)->getLocation().getRawEncoding() <
281              IIDecl->getLocation().getRawEncoding())
282          IIDecl = *Res;
283      }
284    }
285
286    if (!IIDecl) {
287      // None of the entities we found is a type, so there is no way
288      // to even assume that the result is a type. In this case, don't
289      // complain about the ambiguity. The parser will either try to
290      // perform this lookup again (e.g., as an object name), which
291      // will produce the ambiguity, or will complain that it expected
292      // a type name.
293      Result.suppressDiagnostics();
294      return ParsedType();
295    }
296
297    // We found a type within the ambiguous lookup; diagnose the
298    // ambiguity and then return that type. This might be the right
299    // answer, or it might not be, but it suppresses any attempt to
300    // perform the name lookup again.
301    break;
302
303  case LookupResult::Found:
304    IIDecl = Result.getFoundDecl();
305    break;
306  }
307
308  assert(IIDecl && "Didn't find decl");
309
310  QualType T;
311  if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
312    DiagnoseUseOfDecl(IIDecl, NameLoc);
313
314    if (T.isNull())
315      T = Context.getTypeDeclType(TD);
316
317    // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
318    // constructor or destructor name (in such a case, the scope specifier
319    // will be attached to the enclosing Expr or Decl node).
320    if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
321      if (WantNontrivialTypeSourceInfo) {
322        // Construct a type with type-source information.
323        TypeLocBuilder Builder;
324        Builder.pushTypeSpec(T).setNameLoc(NameLoc);
325
326        T = getElaboratedType(ETK_None, *SS, T);
327        ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
328        ElabTL.setElaboratedKeywordLoc(SourceLocation());
329        ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
330        return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
331      } else {
332        T = getElaboratedType(ETK_None, *SS, T);
333      }
334    }
335  } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
336    (void)DiagnoseUseOfDecl(IDecl, NameLoc);
337    if (!HasTrailingDot)
338      T = Context.getObjCInterfaceType(IDecl);
339  }
340
341  if (T.isNull()) {
342    // If it's not plausibly a type, suppress diagnostics.
343    Result.suppressDiagnostics();
344    return ParsedType();
345  }
346  return ParsedType::make(T);
347}
348
349/// isTagName() - This method is called *for error recovery purposes only*
350/// to determine if the specified name is a valid tag name ("struct foo").  If
351/// so, this returns the TST for the tag corresponding to it (TST_enum,
352/// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
353/// cases in C where the user forgot to specify the tag.
354DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
355  // Do a tag name lookup in this scope.
356  LookupResult R(*this, &II, SourceLocation(), LookupTagName);
357  LookupName(R, S, false);
358  R.suppressDiagnostics();
359  if (R.getResultKind() == LookupResult::Found)
360    if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
361      switch (TD->getTagKind()) {
362      case TTK_Struct: return DeclSpec::TST_struct;
363      case TTK_Interface: return DeclSpec::TST_interface;
364      case TTK_Union:  return DeclSpec::TST_union;
365      case TTK_Class:  return DeclSpec::TST_class;
366      case TTK_Enum:   return DeclSpec::TST_enum;
367      }
368    }
369
370  return DeclSpec::TST_unspecified;
371}
372
373/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
374/// if a CXXScopeSpec's type is equal to the type of one of the base classes
375/// then downgrade the missing typename error to a warning.
376/// This is needed for MSVC compatibility; Example:
377/// @code
378/// template<class T> class A {
379/// public:
380///   typedef int TYPE;
381/// };
382/// template<class T> class B : public A<T> {
383/// public:
384///   A<T>::TYPE a; // no typename required because A<T> is a base class.
385/// };
386/// @endcode
387bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
388  if (CurContext->isRecord()) {
389    const Type *Ty = SS->getScopeRep()->getAsType();
390
391    CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
392    for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
393          BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
394      if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
395        return true;
396    return S->isFunctionPrototypeScope();
397  }
398  return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
399}
400
401bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
402                                   SourceLocation IILoc,
403                                   Scope *S,
404                                   CXXScopeSpec *SS,
405                                   ParsedType &SuggestedType) {
406  // We don't have anything to suggest (yet).
407  SuggestedType = ParsedType();
408
409  // There may have been a typo in the name of the type. Look up typo
410  // results, in case we have something that we can suggest.
411  TypeNameValidatorCCC Validator(false);
412  if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
413                                             LookupOrdinaryName, S, SS,
414                                             Validator)) {
415    std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
416    std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
417
418    if (Corrected.isKeyword()) {
419      // We corrected to a keyword.
420      IdentifierInfo *NewII = Corrected.getCorrectionAsIdentifierInfo();
421      if (!isSimpleTypeSpecifier(NewII->getTokenID()))
422        CorrectedQuotedStr = "the keyword " + CorrectedQuotedStr;
423      Diag(IILoc, diag::err_unknown_typename_suggest)
424        << II << CorrectedQuotedStr
425        << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
426      II = NewII;
427    } else {
428      NamedDecl *Result = Corrected.getCorrectionDecl();
429      // We found a similarly-named type or interface; suggest that.
430      if (!SS || !SS->isSet())
431        Diag(IILoc, diag::err_unknown_typename_suggest)
432          << II << CorrectedQuotedStr
433          << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
434      else if (DeclContext *DC = computeDeclContext(*SS, false))
435        Diag(IILoc, diag::err_unknown_nested_typename_suggest)
436          << II << DC << CorrectedQuotedStr << SS->getRange()
437          << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
438                                          CorrectedStr);
439      else
440        llvm_unreachable("could not have corrected a typo here");
441
442      Diag(Result->getLocation(), diag::note_previous_decl)
443        << CorrectedQuotedStr;
444
445      SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS,
446                                  false, false, ParsedType(),
447                                  /*IsCtorOrDtorName=*/false,
448                                  /*NonTrivialTypeSourceInfo=*/true);
449    }
450    return true;
451  }
452
453  if (getLangOpts().CPlusPlus) {
454    // See if II is a class template that the user forgot to pass arguments to.
455    UnqualifiedId Name;
456    Name.setIdentifier(II, IILoc);
457    CXXScopeSpec EmptySS;
458    TemplateTy TemplateResult;
459    bool MemberOfUnknownSpecialization;
460    if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
461                       Name, ParsedType(), true, TemplateResult,
462                       MemberOfUnknownSpecialization) == TNK_Type_template) {
463      TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
464      Diag(IILoc, diag::err_template_missing_args) << TplName;
465      if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
466        Diag(TplDecl->getLocation(), diag::note_template_decl_here)
467          << TplDecl->getTemplateParameters()->getSourceRange();
468      }
469      return true;
470    }
471  }
472
473  // FIXME: Should we move the logic that tries to recover from a missing tag
474  // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
475
476  if (!SS || (!SS->isSet() && !SS->isInvalid()))
477    Diag(IILoc, diag::err_unknown_typename) << II;
478  else if (DeclContext *DC = computeDeclContext(*SS, false))
479    Diag(IILoc, diag::err_typename_nested_not_found)
480      << II << DC << SS->getRange();
481  else if (isDependentScopeSpecifier(*SS)) {
482    unsigned DiagID = diag::err_typename_missing;
483    if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
484      DiagID = diag::warn_typename_missing;
485
486    Diag(SS->getRange().getBegin(), DiagID)
487      << (NestedNameSpecifier *)SS->getScopeRep() << II->getName()
488      << SourceRange(SS->getRange().getBegin(), IILoc)
489      << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
490    SuggestedType = ActOnTypenameType(S, SourceLocation(),
491                                      *SS, *II, IILoc).get();
492  } else {
493    assert(SS && SS->isInvalid() &&
494           "Invalid scope specifier has already been diagnosed");
495  }
496
497  return true;
498}
499
500/// \brief Determine whether the given result set contains either a type name
501/// or
502static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
503  bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
504                       NextToken.is(tok::less);
505
506  for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
507    if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
508      return true;
509
510    if (CheckTemplate && isa<TemplateDecl>(*I))
511      return true;
512  }
513
514  return false;
515}
516
517static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
518                                    Scope *S, CXXScopeSpec &SS,
519                                    IdentifierInfo *&Name,
520                                    SourceLocation NameLoc) {
521  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
522  SemaRef.LookupParsedName(R, S, &SS);
523  if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
524    const char *TagName = 0;
525    const char *FixItTagName = 0;
526    switch (Tag->getTagKind()) {
527      case TTK_Class:
528        TagName = "class";
529        FixItTagName = "class ";
530        break;
531
532      case TTK_Enum:
533        TagName = "enum";
534        FixItTagName = "enum ";
535        break;
536
537      case TTK_Struct:
538        TagName = "struct";
539        FixItTagName = "struct ";
540        break;
541
542      case TTK_Interface:
543        TagName = "__interface";
544        FixItTagName = "__interface ";
545        break;
546
547      case TTK_Union:
548        TagName = "union";
549        FixItTagName = "union ";
550        break;
551    }
552
553    SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
554      << Name << TagName << SemaRef.getLangOpts().CPlusPlus
555      << FixItHint::CreateInsertion(NameLoc, FixItTagName);
556
557    for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
558         I != IEnd; ++I)
559      SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
560        << Name << TagName;
561
562    // Replace lookup results with just the tag decl.
563    Result.clear(Sema::LookupTagName);
564    SemaRef.LookupParsedName(Result, S, &SS);
565    return true;
566  }
567
568  return false;
569}
570
571/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
572static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
573                                  QualType T, SourceLocation NameLoc) {
574  ASTContext &Context = S.Context;
575
576  TypeLocBuilder Builder;
577  Builder.pushTypeSpec(T).setNameLoc(NameLoc);
578
579  T = S.getElaboratedType(ETK_None, SS, T);
580  ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
581  ElabTL.setElaboratedKeywordLoc(SourceLocation());
582  ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
583  return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
584}
585
586Sema::NameClassification Sema::ClassifyName(Scope *S,
587                                            CXXScopeSpec &SS,
588                                            IdentifierInfo *&Name,
589                                            SourceLocation NameLoc,
590                                            const Token &NextToken,
591                                            bool IsAddressOfOperand,
592                                            CorrectionCandidateCallback *CCC) {
593  DeclarationNameInfo NameInfo(Name, NameLoc);
594  ObjCMethodDecl *CurMethod = getCurMethodDecl();
595
596  if (NextToken.is(tok::coloncolon)) {
597    BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
598                                QualType(), false, SS, 0, false);
599
600  }
601
602  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
603  LookupParsedName(Result, S, &SS, !CurMethod);
604
605  // Perform lookup for Objective-C instance variables (including automatically
606  // synthesized instance variables), if we're in an Objective-C method.
607  // FIXME: This lookup really, really needs to be folded in to the normal
608  // unqualified lookup mechanism.
609  if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
610    ExprResult E = LookupInObjCMethod(Result, S, Name, true);
611    if (E.get() || E.isInvalid())
612      return E;
613  }
614
615  bool SecondTry = false;
616  bool IsFilteredTemplateName = false;
617
618Corrected:
619  switch (Result.getResultKind()) {
620  case LookupResult::NotFound:
621    // If an unqualified-id is followed by a '(', then we have a function
622    // call.
623    if (!SS.isSet() && NextToken.is(tok::l_paren)) {
624      // In C++, this is an ADL-only call.
625      // FIXME: Reference?
626      if (getLangOpts().CPlusPlus)
627        return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
628
629      // C90 6.3.2.2:
630      //   If the expression that precedes the parenthesized argument list in a
631      //   function call consists solely of an identifier, and if no
632      //   declaration is visible for this identifier, the identifier is
633      //   implicitly declared exactly as if, in the innermost block containing
634      //   the function call, the declaration
635      //
636      //     extern int identifier ();
637      //
638      //   appeared.
639      //
640      // We also allow this in C99 as an extension.
641      if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
642        Result.addDecl(D);
643        Result.resolveKind();
644        return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
645      }
646    }
647
648    // In C, we first see whether there is a tag type by the same name, in
649    // which case it's likely that the user just forget to write "enum",
650    // "struct", or "union".
651    if (!getLangOpts().CPlusPlus && !SecondTry &&
652        isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
653      break;
654    }
655
656    // Perform typo correction to determine if there is another name that is
657    // close to this name.
658    if (!SecondTry && CCC) {
659      SecondTry = true;
660      if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
661                                                 Result.getLookupKind(), S,
662                                                 &SS, *CCC)) {
663        unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
664        unsigned QualifiedDiag = diag::err_no_member_suggest;
665        std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
666        std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
667
668        NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
669        NamedDecl *UnderlyingFirstDecl
670          = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
671        if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
672            UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
673          UnqualifiedDiag = diag::err_no_template_suggest;
674          QualifiedDiag = diag::err_no_member_template_suggest;
675        } else if (UnderlyingFirstDecl &&
676                   (isa<TypeDecl>(UnderlyingFirstDecl) ||
677                    isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
678                    isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
679           UnqualifiedDiag = diag::err_unknown_typename_suggest;
680           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
681         }
682
683        if (SS.isEmpty())
684          Diag(NameLoc, UnqualifiedDiag)
685            << Name << CorrectedQuotedStr
686            << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
687        else // FIXME: is this even reachable? Test it.
688          Diag(NameLoc, QualifiedDiag)
689            << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
690            << SS.getRange()
691            << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
692                                            CorrectedStr);
693
694        // Update the name, so that the caller has the new name.
695        Name = Corrected.getCorrectionAsIdentifierInfo();
696
697        // Typo correction corrected to a keyword.
698        if (Corrected.isKeyword())
699          return Corrected.getCorrectionAsIdentifierInfo();
700
701        // Also update the LookupResult...
702        // FIXME: This should probably go away at some point
703        Result.clear();
704        Result.setLookupName(Corrected.getCorrection());
705        if (FirstDecl) {
706          Result.addDecl(FirstDecl);
707          Diag(FirstDecl->getLocation(), diag::note_previous_decl)
708            << CorrectedQuotedStr;
709        }
710
711        // If we found an Objective-C instance variable, let
712        // LookupInObjCMethod build the appropriate expression to
713        // reference the ivar.
714        // FIXME: This is a gross hack.
715        if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
716          Result.clear();
717          ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
718          return E;
719        }
720
721        goto Corrected;
722      }
723    }
724
725    // We failed to correct; just fall through and let the parser deal with it.
726    Result.suppressDiagnostics();
727    return NameClassification::Unknown();
728
729  case LookupResult::NotFoundInCurrentInstantiation: {
730    // We performed name lookup into the current instantiation, and there were
731    // dependent bases, so we treat this result the same way as any other
732    // dependent nested-name-specifier.
733
734    // C++ [temp.res]p2:
735    //   A name used in a template declaration or definition and that is
736    //   dependent on a template-parameter is assumed not to name a type
737    //   unless the applicable name lookup finds a type name or the name is
738    //   qualified by the keyword typename.
739    //
740    // FIXME: If the next token is '<', we might want to ask the parser to
741    // perform some heroics to see if we actually have a
742    // template-argument-list, which would indicate a missing 'template'
743    // keyword here.
744    return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
745                                      NameInfo, IsAddressOfOperand,
746                                      /*TemplateArgs=*/0);
747  }
748
749  case LookupResult::Found:
750  case LookupResult::FoundOverloaded:
751  case LookupResult::FoundUnresolvedValue:
752    break;
753
754  case LookupResult::Ambiguous:
755    if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
756        hasAnyAcceptableTemplateNames(Result)) {
757      // C++ [temp.local]p3:
758      //   A lookup that finds an injected-class-name (10.2) can result in an
759      //   ambiguity in certain cases (for example, if it is found in more than
760      //   one base class). If all of the injected-class-names that are found
761      //   refer to specializations of the same class template, and if the name
762      //   is followed by a template-argument-list, the reference refers to the
763      //   class template itself and not a specialization thereof, and is not
764      //   ambiguous.
765      //
766      // This filtering can make an ambiguous result into an unambiguous one,
767      // so try again after filtering out template names.
768      FilterAcceptableTemplateNames(Result);
769      if (!Result.isAmbiguous()) {
770        IsFilteredTemplateName = true;
771        break;
772      }
773    }
774
775    // Diagnose the ambiguity and return an error.
776    return NameClassification::Error();
777  }
778
779  if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
780      (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
781    // C++ [temp.names]p3:
782    //   After name lookup (3.4) finds that a name is a template-name or that
783    //   an operator-function-id or a literal- operator-id refers to a set of
784    //   overloaded functions any member of which is a function template if
785    //   this is followed by a <, the < is always taken as the delimiter of a
786    //   template-argument-list and never as the less-than operator.
787    if (!IsFilteredTemplateName)
788      FilterAcceptableTemplateNames(Result);
789
790    if (!Result.empty()) {
791      bool IsFunctionTemplate;
792      TemplateName Template;
793      if (Result.end() - Result.begin() > 1) {
794        IsFunctionTemplate = true;
795        Template = Context.getOverloadedTemplateName(Result.begin(),
796                                                     Result.end());
797      } else {
798        TemplateDecl *TD
799          = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
800        IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
801
802        if (SS.isSet() && !SS.isInvalid())
803          Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
804                                                    /*TemplateKeyword=*/false,
805                                                      TD);
806        else
807          Template = TemplateName(TD);
808      }
809
810      if (IsFunctionTemplate) {
811        // Function templates always go through overload resolution, at which
812        // point we'll perform the various checks (e.g., accessibility) we need
813        // to based on which function we selected.
814        Result.suppressDiagnostics();
815
816        return NameClassification::FunctionTemplate(Template);
817      }
818
819      return NameClassification::TypeTemplate(Template);
820    }
821  }
822
823  NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
824  if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
825    DiagnoseUseOfDecl(Type, NameLoc);
826    QualType T = Context.getTypeDeclType(Type);
827    if (SS.isNotEmpty())
828      return buildNestedType(*this, SS, T, NameLoc);
829    return ParsedType::make(T);
830  }
831
832  ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
833  if (!Class) {
834    // FIXME: It's unfortunate that we don't have a Type node for handling this.
835    if (ObjCCompatibleAliasDecl *Alias
836                                = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
837      Class = Alias->getClassInterface();
838  }
839
840  if (Class) {
841    DiagnoseUseOfDecl(Class, NameLoc);
842
843    if (NextToken.is(tok::period)) {
844      // Interface. <something> is parsed as a property reference expression.
845      // Just return "unknown" as a fall-through for now.
846      Result.suppressDiagnostics();
847      return NameClassification::Unknown();
848    }
849
850    QualType T = Context.getObjCInterfaceType(Class);
851    return ParsedType::make(T);
852  }
853
854  // We can have a type template here if we're classifying a template argument.
855  if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
856    return NameClassification::TypeTemplate(
857        TemplateName(cast<TemplateDecl>(FirstDecl)));
858
859  // Check for a tag type hidden by a non-type decl in a few cases where it
860  // seems likely a type is wanted instead of the non-type that was found.
861  if (!getLangOpts().ObjC1) {
862    bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
863    if ((NextToken.is(tok::identifier) ||
864         (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) &&
865        isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
866      TypeDecl *Type = Result.getAsSingle<TypeDecl>();
867      DiagnoseUseOfDecl(Type, NameLoc);
868      QualType T = Context.getTypeDeclType(Type);
869      if (SS.isNotEmpty())
870        return buildNestedType(*this, SS, T, NameLoc);
871      return ParsedType::make(T);
872    }
873  }
874
875  if (FirstDecl->isCXXClassMember())
876    return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
877
878  bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
879  return BuildDeclarationNameExpr(SS, Result, ADL);
880}
881
882// Determines the context to return to after temporarily entering a
883// context.  This depends in an unnecessarily complicated way on the
884// exact ordering of callbacks from the parser.
885DeclContext *Sema::getContainingDC(DeclContext *DC) {
886
887  // Functions defined inline within classes aren't parsed until we've
888  // finished parsing the top-level class, so the top-level class is
889  // the context we'll need to return to.
890  if (isa<FunctionDecl>(DC)) {
891    DC = DC->getLexicalParent();
892
893    // A function not defined within a class will always return to its
894    // lexical context.
895    if (!isa<CXXRecordDecl>(DC))
896      return DC;
897
898    // A C++ inline method/friend is parsed *after* the topmost class
899    // it was declared in is fully parsed ("complete");  the topmost
900    // class is the context we need to return to.
901    while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
902      DC = RD;
903
904    // Return the declaration context of the topmost class the inline method is
905    // declared in.
906    return DC;
907  }
908
909  return DC->getLexicalParent();
910}
911
912void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
913  assert(getContainingDC(DC) == CurContext &&
914      "The next DeclContext should be lexically contained in the current one.");
915  CurContext = DC;
916  S->setEntity(DC);
917}
918
919void Sema::PopDeclContext() {
920  assert(CurContext && "DeclContext imbalance!");
921
922  CurContext = getContainingDC(CurContext);
923  assert(CurContext && "Popped translation unit!");
924}
925
926/// EnterDeclaratorContext - Used when we must lookup names in the context
927/// of a declarator's nested name specifier.
928///
929void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
930  // C++0x [basic.lookup.unqual]p13:
931  //   A name used in the definition of a static data member of class
932  //   X (after the qualified-id of the static member) is looked up as
933  //   if the name was used in a member function of X.
934  // C++0x [basic.lookup.unqual]p14:
935  //   If a variable member of a namespace is defined outside of the
936  //   scope of its namespace then any name used in the definition of
937  //   the variable member (after the declarator-id) is looked up as
938  //   if the definition of the variable member occurred in its
939  //   namespace.
940  // Both of these imply that we should push a scope whose context
941  // is the semantic context of the declaration.  We can't use
942  // PushDeclContext here because that context is not necessarily
943  // lexically contained in the current context.  Fortunately,
944  // the containing scope should have the appropriate information.
945
946  assert(!S->getEntity() && "scope already has entity");
947
948#ifndef NDEBUG
949  Scope *Ancestor = S->getParent();
950  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
951  assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
952#endif
953
954  CurContext = DC;
955  S->setEntity(DC);
956}
957
958void Sema::ExitDeclaratorContext(Scope *S) {
959  assert(S->getEntity() == CurContext && "Context imbalance!");
960
961  // Switch back to the lexical context.  The safety of this is
962  // enforced by an assert in EnterDeclaratorContext.
963  Scope *Ancestor = S->getParent();
964  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
965  CurContext = (DeclContext*) Ancestor->getEntity();
966
967  // We don't need to do anything with the scope, which is going to
968  // disappear.
969}
970
971
972void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
973  FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
974  if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
975    // We assume that the caller has already called
976    // ActOnReenterTemplateScope
977    FD = TFD->getTemplatedDecl();
978  }
979  if (!FD)
980    return;
981
982  // Same implementation as PushDeclContext, but enters the context
983  // from the lexical parent, rather than the top-level class.
984  assert(CurContext == FD->getLexicalParent() &&
985    "The next DeclContext should be lexically contained in the current one.");
986  CurContext = FD;
987  S->setEntity(CurContext);
988
989  for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
990    ParmVarDecl *Param = FD->getParamDecl(P);
991    // If the parameter has an identifier, then add it to the scope
992    if (Param->getIdentifier()) {
993      S->AddDecl(Param);
994      IdResolver.AddDecl(Param);
995    }
996  }
997}
998
999
1000void Sema::ActOnExitFunctionContext() {
1001  // Same implementation as PopDeclContext, but returns to the lexical parent,
1002  // rather than the top-level class.
1003  assert(CurContext && "DeclContext imbalance!");
1004  CurContext = CurContext->getLexicalParent();
1005  assert(CurContext && "Popped translation unit!");
1006}
1007
1008
1009/// \brief Determine whether we allow overloading of the function
1010/// PrevDecl with another declaration.
1011///
1012/// This routine determines whether overloading is possible, not
1013/// whether some new function is actually an overload. It will return
1014/// true in C++ (where we can always provide overloads) or, as an
1015/// extension, in C when the previous function is already an
1016/// overloaded function declaration or has the "overloadable"
1017/// attribute.
1018static bool AllowOverloadingOfFunction(LookupResult &Previous,
1019                                       ASTContext &Context) {
1020  if (Context.getLangOpts().CPlusPlus)
1021    return true;
1022
1023  if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1024    return true;
1025
1026  return (Previous.getResultKind() == LookupResult::Found
1027          && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1028}
1029
1030/// Add this decl to the scope shadowed decl chains.
1031void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1032  // Move up the scope chain until we find the nearest enclosing
1033  // non-transparent context. The declaration will be introduced into this
1034  // scope.
1035  while (S->getEntity() &&
1036         ((DeclContext *)S->getEntity())->isTransparentContext())
1037    S = S->getParent();
1038
1039  // Add scoped declarations into their context, so that they can be
1040  // found later. Declarations without a context won't be inserted
1041  // into any context.
1042  if (AddToContext)
1043    CurContext->addDecl(D);
1044
1045  // Out-of-line definitions shouldn't be pushed into scope in C++.
1046  // Out-of-line variable and function definitions shouldn't even in C.
1047  if ((getLangOpts().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
1048      D->isOutOfLine() &&
1049      !D->getDeclContext()->getRedeclContext()->Equals(
1050        D->getLexicalDeclContext()->getRedeclContext()))
1051    return;
1052
1053  // Template instantiations should also not be pushed into scope.
1054  if (isa<FunctionDecl>(D) &&
1055      cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1056    return;
1057
1058  // If this replaces anything in the current scope,
1059  IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1060                               IEnd = IdResolver.end();
1061  for (; I != IEnd; ++I) {
1062    if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1063      S->RemoveDecl(*I);
1064      IdResolver.RemoveDecl(*I);
1065
1066      // Should only need to replace one decl.
1067      break;
1068    }
1069  }
1070
1071  S->AddDecl(D);
1072
1073  if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1074    // Implicitly-generated labels may end up getting generated in an order that
1075    // isn't strictly lexical, which breaks name lookup. Be careful to insert
1076    // the label at the appropriate place in the identifier chain.
1077    for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1078      DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1079      if (IDC == CurContext) {
1080        if (!S->isDeclScope(*I))
1081          continue;
1082      } else if (IDC->Encloses(CurContext))
1083        break;
1084    }
1085
1086    IdResolver.InsertDeclAfter(I, D);
1087  } else {
1088    IdResolver.AddDecl(D);
1089  }
1090}
1091
1092void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1093  if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1094    TUScope->AddDecl(D);
1095}
1096
1097bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S,
1098                         bool ExplicitInstantiationOrSpecialization) {
1099  return IdResolver.isDeclInScope(D, Ctx, Context, S,
1100                                  ExplicitInstantiationOrSpecialization);
1101}
1102
1103Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1104  DeclContext *TargetDC = DC->getPrimaryContext();
1105  do {
1106    if (DeclContext *ScopeDC = (DeclContext*) S->getEntity())
1107      if (ScopeDC->getPrimaryContext() == TargetDC)
1108        return S;
1109  } while ((S = S->getParent()));
1110
1111  return 0;
1112}
1113
1114static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1115                                            DeclContext*,
1116                                            ASTContext&);
1117
1118/// Filters out lookup results that don't fall within the given scope
1119/// as determined by isDeclInScope.
1120void Sema::FilterLookupForScope(LookupResult &R,
1121                                DeclContext *Ctx, Scope *S,
1122                                bool ConsiderLinkage,
1123                                bool ExplicitInstantiationOrSpecialization) {
1124  LookupResult::Filter F = R.makeFilter();
1125  while (F.hasNext()) {
1126    NamedDecl *D = F.next();
1127
1128    if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
1129      continue;
1130
1131    if (ConsiderLinkage &&
1132        isOutOfScopePreviousDeclaration(D, Ctx, Context))
1133      continue;
1134
1135    F.erase();
1136  }
1137
1138  F.done();
1139}
1140
1141static bool isUsingDecl(NamedDecl *D) {
1142  return isa<UsingShadowDecl>(D) ||
1143         isa<UnresolvedUsingTypenameDecl>(D) ||
1144         isa<UnresolvedUsingValueDecl>(D);
1145}
1146
1147/// Removes using shadow declarations from the lookup results.
1148static void RemoveUsingDecls(LookupResult &R) {
1149  LookupResult::Filter F = R.makeFilter();
1150  while (F.hasNext())
1151    if (isUsingDecl(F.next()))
1152      F.erase();
1153
1154  F.done();
1155}
1156
1157/// \brief Check for this common pattern:
1158/// @code
1159/// class S {
1160///   S(const S&); // DO NOT IMPLEMENT
1161///   void operator=(const S&); // DO NOT IMPLEMENT
1162/// };
1163/// @endcode
1164static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1165  // FIXME: Should check for private access too but access is set after we get
1166  // the decl here.
1167  if (D->doesThisDeclarationHaveABody())
1168    return false;
1169
1170  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1171    return CD->isCopyConstructor();
1172  if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1173    return Method->isCopyAssignmentOperator();
1174  return false;
1175}
1176
1177bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1178  assert(D);
1179
1180  if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1181    return false;
1182
1183  // Ignore class templates.
1184  if (D->getDeclContext()->isDependentContext() ||
1185      D->getLexicalDeclContext()->isDependentContext())
1186    return false;
1187
1188  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1189    if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1190      return false;
1191
1192    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1193      if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1194        return false;
1195    } else {
1196      // 'static inline' functions are used in headers; don't warn.
1197      if (FD->getStorageClass() == SC_Static &&
1198          FD->isInlineSpecified())
1199        return false;
1200    }
1201
1202    if (FD->doesThisDeclarationHaveABody() &&
1203        Context.DeclMustBeEmitted(FD))
1204      return false;
1205  } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1206    // Don't warn on variables of const-qualified or reference type, since their
1207    // values can be used even if though they're not odr-used, and because const
1208    // qualified variables can appear in headers in contexts where they're not
1209    // intended to be used.
1210    // FIXME: Use more principled rules for these exemptions.
1211    if (!VD->isFileVarDecl() ||
1212        VD->getType().isConstQualified() ||
1213        VD->getType()->isReferenceType() ||
1214        Context.DeclMustBeEmitted(VD))
1215      return false;
1216
1217    if (VD->isStaticDataMember() &&
1218        VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1219      return false;
1220
1221  } else {
1222    return false;
1223  }
1224
1225  // Only warn for unused decls internal to the translation unit.
1226  if (D->getLinkage() == ExternalLinkage)
1227    return false;
1228
1229  return true;
1230}
1231
1232void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1233  if (!D)
1234    return;
1235
1236  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1237    const FunctionDecl *First = FD->getFirstDeclaration();
1238    if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1239      return; // First should already be in the vector.
1240  }
1241
1242  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1243    const VarDecl *First = VD->getFirstDeclaration();
1244    if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1245      return; // First should already be in the vector.
1246  }
1247
1248  if (ShouldWarnIfUnusedFileScopedDecl(D))
1249    UnusedFileScopedDecls.push_back(D);
1250}
1251
1252static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1253  if (D->isInvalidDecl())
1254    return false;
1255
1256  if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
1257    return false;
1258
1259  if (isa<LabelDecl>(D))
1260    return true;
1261
1262  // White-list anything that isn't a local variable.
1263  if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1264      !D->getDeclContext()->isFunctionOrMethod())
1265    return false;
1266
1267  // Types of valid local variables should be complete, so this should succeed.
1268  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1269
1270    // White-list anything with an __attribute__((unused)) type.
1271    QualType Ty = VD->getType();
1272
1273    // Only look at the outermost level of typedef.
1274    if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1275      if (TT->getDecl()->hasAttr<UnusedAttr>())
1276        return false;
1277    }
1278
1279    // If we failed to complete the type for some reason, or if the type is
1280    // dependent, don't diagnose the variable.
1281    if (Ty->isIncompleteType() || Ty->isDependentType())
1282      return false;
1283
1284    if (const TagType *TT = Ty->getAs<TagType>()) {
1285      const TagDecl *Tag = TT->getDecl();
1286      if (Tag->hasAttr<UnusedAttr>())
1287        return false;
1288
1289      if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1290        if (!RD->hasTrivialDestructor())
1291          return false;
1292
1293        if (const Expr *Init = VD->getInit()) {
1294          if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init))
1295            Init = Cleanups->getSubExpr();
1296          const CXXConstructExpr *Construct =
1297            dyn_cast<CXXConstructExpr>(Init);
1298          if (Construct && !Construct->isElidable()) {
1299            CXXConstructorDecl *CD = Construct->getConstructor();
1300            if (!CD->isTrivial())
1301              return false;
1302          }
1303        }
1304      }
1305    }
1306
1307    // TODO: __attribute__((unused)) templates?
1308  }
1309
1310  return true;
1311}
1312
1313static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1314                                     FixItHint &Hint) {
1315  if (isa<LabelDecl>(D)) {
1316    SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1317                tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1318    if (AfterColon.isInvalid())
1319      return;
1320    Hint = FixItHint::CreateRemoval(CharSourceRange::
1321                                    getCharRange(D->getLocStart(), AfterColon));
1322  }
1323  return;
1324}
1325
1326/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1327/// unless they are marked attr(unused).
1328void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1329  FixItHint Hint;
1330  if (!ShouldDiagnoseUnusedDecl(D))
1331    return;
1332
1333  GenerateFixForUnusedDecl(D, Context, Hint);
1334
1335  unsigned DiagID;
1336  if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1337    DiagID = diag::warn_unused_exception_param;
1338  else if (isa<LabelDecl>(D))
1339    DiagID = diag::warn_unused_label;
1340  else
1341    DiagID = diag::warn_unused_variable;
1342
1343  Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1344}
1345
1346static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1347  // Verify that we have no forward references left.  If so, there was a goto
1348  // or address of a label taken, but no definition of it.  Label fwd
1349  // definitions are indicated with a null substmt.
1350  if (L->getStmt() == 0)
1351    S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1352}
1353
1354void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1355  if (S->decl_empty()) return;
1356  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1357         "Scope shouldn't contain decls!");
1358
1359  for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1360       I != E; ++I) {
1361    Decl *TmpD = (*I);
1362    assert(TmpD && "This decl didn't get pushed??");
1363
1364    assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1365    NamedDecl *D = cast<NamedDecl>(TmpD);
1366
1367    if (!D->getDeclName()) continue;
1368
1369    // Diagnose unused variables in this scope.
1370    if (!S->hasErrorOccurred())
1371      DiagnoseUnusedDecl(D);
1372
1373    // If this was a forward reference to a label, verify it was defined.
1374    if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1375      CheckPoppedLabel(LD, *this);
1376
1377    // Remove this name from our lexical scope.
1378    IdResolver.RemoveDecl(D);
1379  }
1380}
1381
1382void Sema::ActOnStartFunctionDeclarator() {
1383  ++InFunctionDeclarator;
1384}
1385
1386void Sema::ActOnEndFunctionDeclarator() {
1387  assert(InFunctionDeclarator);
1388  --InFunctionDeclarator;
1389}
1390
1391/// \brief Look for an Objective-C class in the translation unit.
1392///
1393/// \param Id The name of the Objective-C class we're looking for. If
1394/// typo-correction fixes this name, the Id will be updated
1395/// to the fixed name.
1396///
1397/// \param IdLoc The location of the name in the translation unit.
1398///
1399/// \param DoTypoCorrection If true, this routine will attempt typo correction
1400/// if there is no class with the given name.
1401///
1402/// \returns The declaration of the named Objective-C class, or NULL if the
1403/// class could not be found.
1404ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1405                                              SourceLocation IdLoc,
1406                                              bool DoTypoCorrection) {
1407  // The third "scope" argument is 0 since we aren't enabling lazy built-in
1408  // creation from this context.
1409  NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1410
1411  if (!IDecl && DoTypoCorrection) {
1412    // Perform typo correction at the given location, but only if we
1413    // find an Objective-C class name.
1414    DeclFilterCCC<ObjCInterfaceDecl> Validator;
1415    if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1416                                       LookupOrdinaryName, TUScope, NULL,
1417                                       Validator)) {
1418      IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1419      Diag(IdLoc, diag::err_undef_interface_suggest)
1420        << Id << IDecl->getDeclName()
1421        << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
1422      Diag(IDecl->getLocation(), diag::note_previous_decl)
1423        << IDecl->getDeclName();
1424
1425      Id = IDecl->getIdentifier();
1426    }
1427  }
1428  ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1429  // This routine must always return a class definition, if any.
1430  if (Def && Def->getDefinition())
1431      Def = Def->getDefinition();
1432  return Def;
1433}
1434
1435/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1436/// from S, where a non-field would be declared. This routine copes
1437/// with the difference between C and C++ scoping rules in structs and
1438/// unions. For example, the following code is well-formed in C but
1439/// ill-formed in C++:
1440/// @code
1441/// struct S6 {
1442///   enum { BAR } e;
1443/// };
1444///
1445/// void test_S6() {
1446///   struct S6 a;
1447///   a.e = BAR;
1448/// }
1449/// @endcode
1450/// For the declaration of BAR, this routine will return a different
1451/// scope. The scope S will be the scope of the unnamed enumeration
1452/// within S6. In C++, this routine will return the scope associated
1453/// with S6, because the enumeration's scope is a transparent
1454/// context but structures can contain non-field names. In C, this
1455/// routine will return the translation unit scope, since the
1456/// enumeration's scope is a transparent context and structures cannot
1457/// contain non-field names.
1458Scope *Sema::getNonFieldDeclScope(Scope *S) {
1459  while (((S->getFlags() & Scope::DeclScope) == 0) ||
1460         (S->getEntity() &&
1461          ((DeclContext *)S->getEntity())->isTransparentContext()) ||
1462         (S->isClassScope() && !getLangOpts().CPlusPlus))
1463    S = S->getParent();
1464  return S;
1465}
1466
1467/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1468/// file scope.  lazily create a decl for it. ForRedeclaration is true
1469/// if we're creating this built-in in anticipation of redeclaring the
1470/// built-in.
1471NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
1472                                     Scope *S, bool ForRedeclaration,
1473                                     SourceLocation Loc) {
1474  Builtin::ID BID = (Builtin::ID)bid;
1475
1476  ASTContext::GetBuiltinTypeError Error;
1477  QualType R = Context.GetBuiltinType(BID, Error);
1478  switch (Error) {
1479  case ASTContext::GE_None:
1480    // Okay
1481    break;
1482
1483  case ASTContext::GE_Missing_stdio:
1484    if (ForRedeclaration)
1485      Diag(Loc, diag::warn_implicit_decl_requires_stdio)
1486        << Context.BuiltinInfo.GetName(BID);
1487    return 0;
1488
1489  case ASTContext::GE_Missing_setjmp:
1490    if (ForRedeclaration)
1491      Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
1492        << Context.BuiltinInfo.GetName(BID);
1493    return 0;
1494
1495  case ASTContext::GE_Missing_ucontext:
1496    if (ForRedeclaration)
1497      Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1498        << Context.BuiltinInfo.GetName(BID);
1499    return 0;
1500  }
1501
1502  if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1503    Diag(Loc, diag::ext_implicit_lib_function_decl)
1504      << Context.BuiltinInfo.GetName(BID)
1505      << R;
1506    if (Context.BuiltinInfo.getHeaderName(BID) &&
1507        Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
1508          != DiagnosticsEngine::Ignored)
1509      Diag(Loc, diag::note_please_include_header)
1510        << Context.BuiltinInfo.getHeaderName(BID)
1511        << Context.BuiltinInfo.GetName(BID);
1512  }
1513
1514  FunctionDecl *New = FunctionDecl::Create(Context,
1515                                           Context.getTranslationUnitDecl(),
1516                                           Loc, Loc, II, R, /*TInfo=*/0,
1517                                           SC_Extern,
1518                                           SC_None, false,
1519                                           /*hasPrototype=*/true);
1520  New->setImplicit();
1521
1522  // Create Decl objects for each parameter, adding them to the
1523  // FunctionDecl.
1524  if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1525    SmallVector<ParmVarDecl*, 16> Params;
1526    for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1527      ParmVarDecl *parm =
1528        ParmVarDecl::Create(Context, New, SourceLocation(),
1529                            SourceLocation(), 0,
1530                            FT->getArgType(i), /*TInfo=*/0,
1531                            SC_None, SC_None, 0);
1532      parm->setScopeInfo(0, i);
1533      Params.push_back(parm);
1534    }
1535    New->setParams(Params);
1536  }
1537
1538  AddKnownFunctionAttributes(New);
1539
1540  // TUScope is the translation-unit scope to insert this function into.
1541  // FIXME: This is hideous. We need to teach PushOnScopeChains to
1542  // relate Scopes to DeclContexts, and probably eliminate CurContext
1543  // entirely, but we're not there yet.
1544  DeclContext *SavedContext = CurContext;
1545  CurContext = Context.getTranslationUnitDecl();
1546  PushOnScopeChains(New, TUScope);
1547  CurContext = SavedContext;
1548  return New;
1549}
1550
1551bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1552  QualType OldType;
1553  if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1554    OldType = OldTypedef->getUnderlyingType();
1555  else
1556    OldType = Context.getTypeDeclType(Old);
1557  QualType NewType = New->getUnderlyingType();
1558
1559  if (NewType->isVariablyModifiedType()) {
1560    // Must not redefine a typedef with a variably-modified type.
1561    int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1562    Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1563      << Kind << NewType;
1564    if (Old->getLocation().isValid())
1565      Diag(Old->getLocation(), diag::note_previous_definition);
1566    New->setInvalidDecl();
1567    return true;
1568  }
1569
1570  if (OldType != NewType &&
1571      !OldType->isDependentType() &&
1572      !NewType->isDependentType() &&
1573      !Context.hasSameType(OldType, NewType)) {
1574    int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1575    Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1576      << Kind << NewType << OldType;
1577    if (Old->getLocation().isValid())
1578      Diag(Old->getLocation(), diag::note_previous_definition);
1579    New->setInvalidDecl();
1580    return true;
1581  }
1582  return false;
1583}
1584
1585/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1586/// same name and scope as a previous declaration 'Old'.  Figure out
1587/// how to resolve this situation, merging decls or emitting
1588/// diagnostics as appropriate. If there was an error, set New to be invalid.
1589///
1590void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
1591  // If the new decl is known invalid already, don't bother doing any
1592  // merging checks.
1593  if (New->isInvalidDecl()) return;
1594
1595  // Allow multiple definitions for ObjC built-in typedefs.
1596  // FIXME: Verify the underlying types are equivalent!
1597  if (getLangOpts().ObjC1) {
1598    const IdentifierInfo *TypeID = New->getIdentifier();
1599    switch (TypeID->getLength()) {
1600    default: break;
1601    case 2:
1602      {
1603        if (!TypeID->isStr("id"))
1604          break;
1605        QualType T = New->getUnderlyingType();
1606        if (!T->isPointerType())
1607          break;
1608        if (!T->isVoidPointerType()) {
1609          QualType PT = T->getAs<PointerType>()->getPointeeType();
1610          if (!PT->isStructureType())
1611            break;
1612        }
1613        Context.setObjCIdRedefinitionType(T);
1614        // Install the built-in type for 'id', ignoring the current definition.
1615        New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1616        return;
1617      }
1618    case 5:
1619      if (!TypeID->isStr("Class"))
1620        break;
1621      Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1622      // Install the built-in type for 'Class', ignoring the current definition.
1623      New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1624      return;
1625    case 3:
1626      if (!TypeID->isStr("SEL"))
1627        break;
1628      Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1629      // Install the built-in type for 'SEL', ignoring the current definition.
1630      New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1631      return;
1632    }
1633    // Fall through - the typedef name was not a builtin type.
1634  }
1635
1636  // Verify the old decl was also a type.
1637  TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1638  if (!Old) {
1639    Diag(New->getLocation(), diag::err_redefinition_different_kind)
1640      << New->getDeclName();
1641
1642    NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1643    if (OldD->getLocation().isValid())
1644      Diag(OldD->getLocation(), diag::note_previous_definition);
1645
1646    return New->setInvalidDecl();
1647  }
1648
1649  // If the old declaration is invalid, just give up here.
1650  if (Old->isInvalidDecl())
1651    return New->setInvalidDecl();
1652
1653  // If the typedef types are not identical, reject them in all languages and
1654  // with any extensions enabled.
1655  if (isIncompatibleTypedef(Old, New))
1656    return;
1657
1658  // The types match.  Link up the redeclaration chain if the old
1659  // declaration was a typedef.
1660  if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old))
1661    New->setPreviousDeclaration(Typedef);
1662
1663  if (getLangOpts().MicrosoftExt)
1664    return;
1665
1666  if (getLangOpts().CPlusPlus) {
1667    // C++ [dcl.typedef]p2:
1668    //   In a given non-class scope, a typedef specifier can be used to
1669    //   redefine the name of any type declared in that scope to refer
1670    //   to the type to which it already refers.
1671    if (!isa<CXXRecordDecl>(CurContext))
1672      return;
1673
1674    // C++0x [dcl.typedef]p4:
1675    //   In a given class scope, a typedef specifier can be used to redefine
1676    //   any class-name declared in that scope that is not also a typedef-name
1677    //   to refer to the type to which it already refers.
1678    //
1679    // This wording came in via DR424, which was a correction to the
1680    // wording in DR56, which accidentally banned code like:
1681    //
1682    //   struct S {
1683    //     typedef struct A { } A;
1684    //   };
1685    //
1686    // in the C++03 standard. We implement the C++0x semantics, which
1687    // allow the above but disallow
1688    //
1689    //   struct S {
1690    //     typedef int I;
1691    //     typedef int I;
1692    //   };
1693    //
1694    // since that was the intent of DR56.
1695    if (!isa<TypedefNameDecl>(Old))
1696      return;
1697
1698    Diag(New->getLocation(), diag::err_redefinition)
1699      << New->getDeclName();
1700    Diag(Old->getLocation(), diag::note_previous_definition);
1701    return New->setInvalidDecl();
1702  }
1703
1704  // Modules always permit redefinition of typedefs, as does C11.
1705  if (getLangOpts().Modules || getLangOpts().C11)
1706    return;
1707
1708  // If we have a redefinition of a typedef in C, emit a warning.  This warning
1709  // is normally mapped to an error, but can be controlled with
1710  // -Wtypedef-redefinition.  If either the original or the redefinition is
1711  // in a system header, don't emit this for compatibility with GCC.
1712  if (getDiagnostics().getSuppressSystemWarnings() &&
1713      (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1714       Context.getSourceManager().isInSystemHeader(New->getLocation())))
1715    return;
1716
1717  Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1718    << New->getDeclName();
1719  Diag(Old->getLocation(), diag::note_previous_definition);
1720  return;
1721}
1722
1723/// DeclhasAttr - returns true if decl Declaration already has the target
1724/// attribute.
1725static bool
1726DeclHasAttr(const Decl *D, const Attr *A) {
1727  // There can be multiple AvailabilityAttr in a Decl. Make sure we copy
1728  // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is
1729  // responsible for making sure they are consistent.
1730  const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A);
1731  if (AA)
1732    return false;
1733
1734  // The following thread safety attributes can also be duplicated.
1735  switch (A->getKind()) {
1736    case attr::ExclusiveLocksRequired:
1737    case attr::SharedLocksRequired:
1738    case attr::LocksExcluded:
1739    case attr::ExclusiveLockFunction:
1740    case attr::SharedLockFunction:
1741    case attr::UnlockFunction:
1742    case attr::ExclusiveTrylockFunction:
1743    case attr::SharedTrylockFunction:
1744    case attr::GuardedBy:
1745    case attr::PtGuardedBy:
1746    case attr::AcquiredBefore:
1747    case attr::AcquiredAfter:
1748      return false;
1749    default:
1750      ;
1751  }
1752
1753  const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
1754  const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
1755  for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1756    if ((*i)->getKind() == A->getKind()) {
1757      if (Ann) {
1758        if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1759          return true;
1760        continue;
1761      }
1762      // FIXME: Don't hardcode this check
1763      if (OA && isa<OwnershipAttr>(*i))
1764        return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
1765      return true;
1766    }
1767
1768  return false;
1769}
1770
1771bool Sema::mergeDeclAttribute(Decl *D, InheritableAttr *Attr) {
1772  InheritableAttr *NewAttr = NULL;
1773  if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
1774    NewAttr = mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1775                                    AA->getIntroduced(), AA->getDeprecated(),
1776                                    AA->getObsoleted(), AA->getUnavailable(),
1777                                    AA->getMessage());
1778  else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
1779    NewAttr = mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility());
1780  else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
1781    NewAttr = mergeDLLImportAttr(D, ImportA->getRange());
1782  else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
1783    NewAttr = mergeDLLExportAttr(D, ExportA->getRange());
1784  else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
1785    NewAttr = mergeFormatAttr(D, FA->getRange(), FA->getType(),
1786                              FA->getFormatIdx(), FA->getFirstArg());
1787  else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
1788    NewAttr = mergeSectionAttr(D, SA->getRange(), SA->getName());
1789  else if (!DeclHasAttr(D, Attr))
1790    NewAttr = cast<InheritableAttr>(Attr->clone(Context));
1791
1792  if (NewAttr) {
1793    NewAttr->setInherited(true);
1794    D->addAttr(NewAttr);
1795    return true;
1796  }
1797
1798  return false;
1799}
1800
1801static const Decl *getDefinition(const Decl *D) {
1802  if (const TagDecl *TD = dyn_cast<TagDecl>(D))
1803    return TD->getDefinition();
1804  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1805    return VD->getDefinition();
1806  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1807    const FunctionDecl* Def;
1808    if (FD->hasBody(Def))
1809      return Def;
1810  }
1811  return NULL;
1812}
1813
1814static bool hasAttribute(const Decl *D, attr::Kind Kind) {
1815  for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
1816       I != E; ++I) {
1817    Attr *Attribute = *I;
1818    if (Attribute->getKind() == Kind)
1819      return true;
1820  }
1821  return false;
1822}
1823
1824/// checkNewAttributesAfterDef - If we already have a definition, check that
1825/// there are no new attributes in this declaration.
1826static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
1827  if (!New->hasAttrs())
1828    return;
1829
1830  const Decl *Def = getDefinition(Old);
1831  if (!Def || Def == New)
1832    return;
1833
1834  AttrVec &NewAttributes = New->getAttrs();
1835  for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
1836    const Attr *NewAttribute = NewAttributes[I];
1837    if (hasAttribute(Def, NewAttribute->getKind())) {
1838      ++I;
1839      continue; // regular attr merging will take care of validating this.
1840    }
1841    S.Diag(NewAttribute->getLocation(),
1842           diag::warn_attribute_precede_definition);
1843    S.Diag(Def->getLocation(), diag::note_previous_definition);
1844    NewAttributes.erase(NewAttributes.begin() + I);
1845    --E;
1846  }
1847}
1848
1849/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
1850void Sema::mergeDeclAttributes(Decl *New, Decl *Old,
1851                               bool MergeDeprecation) {
1852  // attributes declared post-definition are currently ignored
1853  checkNewAttributesAfterDef(*this, New, Old);
1854
1855  if (!Old->hasAttrs())
1856    return;
1857
1858  bool foundAny = New->hasAttrs();
1859
1860  // Ensure that any moving of objects within the allocated map is done before
1861  // we process them.
1862  if (!foundAny) New->setAttrs(AttrVec());
1863
1864  for (specific_attr_iterator<InheritableAttr>
1865         i = Old->specific_attr_begin<InheritableAttr>(),
1866         e = Old->specific_attr_end<InheritableAttr>();
1867       i != e; ++i) {
1868    // Ignore deprecated/unavailable/availability attributes if requested.
1869    if (!MergeDeprecation &&
1870        (isa<DeprecatedAttr>(*i) ||
1871         isa<UnavailableAttr>(*i) ||
1872         isa<AvailabilityAttr>(*i)))
1873      continue;
1874
1875    if (mergeDeclAttribute(New, *i))
1876      foundAny = true;
1877  }
1878
1879  if (!foundAny) New->dropAttrs();
1880}
1881
1882/// mergeParamDeclAttributes - Copy attributes from the old parameter
1883/// to the new one.
1884static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
1885                                     const ParmVarDecl *oldDecl,
1886                                     ASTContext &C) {
1887  if (!oldDecl->hasAttrs())
1888    return;
1889
1890  bool foundAny = newDecl->hasAttrs();
1891
1892  // Ensure that any moving of objects within the allocated map is
1893  // done before we process them.
1894  if (!foundAny) newDecl->setAttrs(AttrVec());
1895
1896  for (specific_attr_iterator<InheritableParamAttr>
1897       i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
1898       e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
1899    if (!DeclHasAttr(newDecl, *i)) {
1900      InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C));
1901      newAttr->setInherited(true);
1902      newDecl->addAttr(newAttr);
1903      foundAny = true;
1904    }
1905  }
1906
1907  if (!foundAny) newDecl->dropAttrs();
1908}
1909
1910namespace {
1911
1912/// Used in MergeFunctionDecl to keep track of function parameters in
1913/// C.
1914struct GNUCompatibleParamWarning {
1915  ParmVarDecl *OldParm;
1916  ParmVarDecl *NewParm;
1917  QualType PromotedType;
1918};
1919
1920}
1921
1922/// getSpecialMember - get the special member enum for a method.
1923Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
1924  if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
1925    if (Ctor->isDefaultConstructor())
1926      return Sema::CXXDefaultConstructor;
1927
1928    if (Ctor->isCopyConstructor())
1929      return Sema::CXXCopyConstructor;
1930
1931    if (Ctor->isMoveConstructor())
1932      return Sema::CXXMoveConstructor;
1933  } else if (isa<CXXDestructorDecl>(MD)) {
1934    return Sema::CXXDestructor;
1935  } else if (MD->isCopyAssignmentOperator()) {
1936    return Sema::CXXCopyAssignment;
1937  } else if (MD->isMoveAssignmentOperator()) {
1938    return Sema::CXXMoveAssignment;
1939  }
1940
1941  return Sema::CXXInvalid;
1942}
1943
1944/// canRedefineFunction - checks if a function can be redefined. Currently,
1945/// only extern inline functions can be redefined, and even then only in
1946/// GNU89 mode.
1947static bool canRedefineFunction(const FunctionDecl *FD,
1948                                const LangOptions& LangOpts) {
1949  return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
1950          !LangOpts.CPlusPlus &&
1951          FD->isInlineSpecified() &&
1952          FD->getStorageClass() == SC_Extern);
1953}
1954
1955/// Is the given calling convention the ABI default for the given
1956/// declaration?
1957static bool isABIDefaultCC(Sema &S, CallingConv CC, FunctionDecl *D) {
1958  CallingConv ABIDefaultCC;
1959  if (isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
1960    ABIDefaultCC = S.Context.getDefaultCXXMethodCallConv(D->isVariadic());
1961  } else {
1962    // Free C function or a static method.
1963    ABIDefaultCC = (S.Context.getLangOpts().MRTD ? CC_X86StdCall : CC_C);
1964  }
1965  return ABIDefaultCC == CC;
1966}
1967
1968/// MergeFunctionDecl - We just parsed a function 'New' from
1969/// declarator D which has the same name and scope as a previous
1970/// declaration 'Old'.  Figure out how to resolve this situation,
1971/// merging decls or emitting diagnostics as appropriate.
1972///
1973/// In C++, New and Old must be declarations that are not
1974/// overloaded. Use IsOverload to determine whether New and Old are
1975/// overloaded, and to select the Old declaration that New should be
1976/// merged with.
1977///
1978/// Returns true if there was an error, false otherwise.
1979bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S) {
1980  // Verify the old decl was also a function.
1981  FunctionDecl *Old = 0;
1982  if (FunctionTemplateDecl *OldFunctionTemplate
1983        = dyn_cast<FunctionTemplateDecl>(OldD))
1984    Old = OldFunctionTemplate->getTemplatedDecl();
1985  else
1986    Old = dyn_cast<FunctionDecl>(OldD);
1987  if (!Old) {
1988    if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
1989      Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
1990      Diag(Shadow->getTargetDecl()->getLocation(),
1991           diag::note_using_decl_target);
1992      Diag(Shadow->getUsingDecl()->getLocation(),
1993           diag::note_using_decl) << 0;
1994      return true;
1995    }
1996
1997    Diag(New->getLocation(), diag::err_redefinition_different_kind)
1998      << New->getDeclName();
1999    Diag(OldD->getLocation(), diag::note_previous_definition);
2000    return true;
2001  }
2002
2003  // Determine whether the previous declaration was a definition,
2004  // implicit declaration, or a declaration.
2005  diag::kind PrevDiag;
2006  if (Old->isThisDeclarationADefinition())
2007    PrevDiag = diag::note_previous_definition;
2008  else if (Old->isImplicit())
2009    PrevDiag = diag::note_previous_implicit_declaration;
2010  else
2011    PrevDiag = diag::note_previous_declaration;
2012
2013  QualType OldQType = Context.getCanonicalType(Old->getType());
2014  QualType NewQType = Context.getCanonicalType(New->getType());
2015
2016  // Don't complain about this if we're in GNU89 mode and the old function
2017  // is an extern inline function.
2018  if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2019      New->getStorageClass() == SC_Static &&
2020      Old->getStorageClass() != SC_Static &&
2021      !canRedefineFunction(Old, getLangOpts())) {
2022    if (getLangOpts().MicrosoftExt) {
2023      Diag(New->getLocation(), diag::warn_static_non_static) << New;
2024      Diag(Old->getLocation(), PrevDiag);
2025    } else {
2026      Diag(New->getLocation(), diag::err_static_non_static) << New;
2027      Diag(Old->getLocation(), PrevDiag);
2028      return true;
2029    }
2030  }
2031
2032  // If a function is first declared with a calling convention, but is
2033  // later declared or defined without one, the second decl assumes the
2034  // calling convention of the first.
2035  //
2036  // It's OK if a function is first declared without a calling convention,
2037  // but is later declared or defined with the default calling convention.
2038  //
2039  // For the new decl, we have to look at the NON-canonical type to tell the
2040  // difference between a function that really doesn't have a calling
2041  // convention and one that is declared cdecl. That's because in
2042  // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
2043  // because it is the default calling convention.
2044  //
2045  // Note also that we DO NOT return at this point, because we still have
2046  // other tests to run.
2047  const FunctionType *OldType = cast<FunctionType>(OldQType);
2048  const FunctionType *NewType = New->getType()->getAs<FunctionType>();
2049  FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2050  FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2051  bool RequiresAdjustment = false;
2052  if (OldTypeInfo.getCC() == NewTypeInfo.getCC()) {
2053    // Fast path: nothing to do.
2054
2055  // Inherit the CC from the previous declaration if it was specified
2056  // there but not here.
2057  } else if (NewTypeInfo.getCC() == CC_Default) {
2058    NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2059    RequiresAdjustment = true;
2060
2061  // Don't complain about mismatches when the default CC is
2062  // effectively the same as the explict one.
2063  } else if (OldTypeInfo.getCC() == CC_Default &&
2064             isABIDefaultCC(*this, NewTypeInfo.getCC(), New)) {
2065    NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2066    RequiresAdjustment = true;
2067
2068  } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
2069                                     NewTypeInfo.getCC())) {
2070    // Calling conventions really aren't compatible, so complain.
2071    Diag(New->getLocation(), diag::err_cconv_change)
2072      << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2073      << (OldTypeInfo.getCC() == CC_Default)
2074      << (OldTypeInfo.getCC() == CC_Default ? "" :
2075          FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
2076    Diag(Old->getLocation(), diag::note_previous_declaration);
2077    return true;
2078  }
2079
2080  // FIXME: diagnose the other way around?
2081  if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2082    NewTypeInfo = NewTypeInfo.withNoReturn(true);
2083    RequiresAdjustment = true;
2084  }
2085
2086  // Merge regparm attribute.
2087  if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2088      OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2089    if (NewTypeInfo.getHasRegParm()) {
2090      Diag(New->getLocation(), diag::err_regparm_mismatch)
2091        << NewType->getRegParmType()
2092        << OldType->getRegParmType();
2093      Diag(Old->getLocation(), diag::note_previous_declaration);
2094      return true;
2095    }
2096
2097    NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2098    RequiresAdjustment = true;
2099  }
2100
2101  // Merge ns_returns_retained attribute.
2102  if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2103    if (NewTypeInfo.getProducesResult()) {
2104      Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2105      Diag(Old->getLocation(), diag::note_previous_declaration);
2106      return true;
2107    }
2108
2109    NewTypeInfo = NewTypeInfo.withProducesResult(true);
2110    RequiresAdjustment = true;
2111  }
2112
2113  if (RequiresAdjustment) {
2114    NewType = Context.adjustFunctionType(NewType, NewTypeInfo);
2115    New->setType(QualType(NewType, 0));
2116    NewQType = Context.getCanonicalType(New->getType());
2117  }
2118
2119  if (getLangOpts().CPlusPlus) {
2120    // (C++98 13.1p2):
2121    //   Certain function declarations cannot be overloaded:
2122    //     -- Function declarations that differ only in the return type
2123    //        cannot be overloaded.
2124    QualType OldReturnType = OldType->getResultType();
2125    QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
2126    QualType ResQT;
2127    if (OldReturnType != NewReturnType) {
2128      if (NewReturnType->isObjCObjectPointerType()
2129          && OldReturnType->isObjCObjectPointerType())
2130        ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2131      if (ResQT.isNull()) {
2132        if (New->isCXXClassMember() && New->isOutOfLine())
2133          Diag(New->getLocation(),
2134               diag::err_member_def_does_not_match_ret_type) << New;
2135        else
2136          Diag(New->getLocation(), diag::err_ovl_diff_return_type);
2137        Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2138        return true;
2139      }
2140      else
2141        NewQType = ResQT;
2142    }
2143
2144    const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
2145    CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
2146    if (OldMethod && NewMethod) {
2147      // Preserve triviality.
2148      NewMethod->setTrivial(OldMethod->isTrivial());
2149
2150      // MSVC allows explicit template specialization at class scope:
2151      // 2 CXMethodDecls referring to the same function will be injected.
2152      // We don't want a redeclartion error.
2153      bool IsClassScopeExplicitSpecialization =
2154                              OldMethod->isFunctionTemplateSpecialization() &&
2155                              NewMethod->isFunctionTemplateSpecialization();
2156      bool isFriend = NewMethod->getFriendObjectKind();
2157
2158      if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2159          !IsClassScopeExplicitSpecialization) {
2160        //    -- Member function declarations with the same name and the
2161        //       same parameter types cannot be overloaded if any of them
2162        //       is a static member function declaration.
2163        if (OldMethod->isStatic() || NewMethod->isStatic()) {
2164          Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2165          Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2166          return true;
2167        }
2168
2169        // C++ [class.mem]p1:
2170        //   [...] A member shall not be declared twice in the
2171        //   member-specification, except that a nested class or member
2172        //   class template can be declared and then later defined.
2173        if (ActiveTemplateInstantiations.empty()) {
2174          unsigned NewDiag;
2175          if (isa<CXXConstructorDecl>(OldMethod))
2176            NewDiag = diag::err_constructor_redeclared;
2177          else if (isa<CXXDestructorDecl>(NewMethod))
2178            NewDiag = diag::err_destructor_redeclared;
2179          else if (isa<CXXConversionDecl>(NewMethod))
2180            NewDiag = diag::err_conv_function_redeclared;
2181          else
2182            NewDiag = diag::err_member_redeclared;
2183
2184          Diag(New->getLocation(), NewDiag);
2185        } else {
2186          Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2187            << New << New->getType();
2188        }
2189        Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2190
2191      // Complain if this is an explicit declaration of a special
2192      // member that was initially declared implicitly.
2193      //
2194      // As an exception, it's okay to befriend such methods in order
2195      // to permit the implicit constructor/destructor/operator calls.
2196      } else if (OldMethod->isImplicit()) {
2197        if (isFriend) {
2198          NewMethod->setImplicit();
2199        } else {
2200          Diag(NewMethod->getLocation(),
2201               diag::err_definition_of_implicitly_declared_member)
2202            << New << getSpecialMember(OldMethod);
2203          return true;
2204        }
2205      } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2206        Diag(NewMethod->getLocation(),
2207             diag::err_definition_of_explicitly_defaulted_member)
2208          << getSpecialMember(OldMethod);
2209        return true;
2210      }
2211    }
2212
2213    // (C++98 8.3.5p3):
2214    //   All declarations for a function shall agree exactly in both the
2215    //   return type and the parameter-type-list.
2216    // We also want to respect all the extended bits except noreturn.
2217
2218    // noreturn should now match unless the old type info didn't have it.
2219    QualType OldQTypeForComparison = OldQType;
2220    if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2221      assert(OldQType == QualType(OldType, 0));
2222      const FunctionType *OldTypeForComparison
2223        = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2224      OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2225      assert(OldQTypeForComparison.isCanonical());
2226    }
2227
2228    if (OldQTypeForComparison == NewQType)
2229      return MergeCompatibleFunctionDecls(New, Old, S);
2230
2231    // Fall through for conflicting redeclarations and redefinitions.
2232  }
2233
2234  // C: Function types need to be compatible, not identical. This handles
2235  // duplicate function decls like "void f(int); void f(enum X);" properly.
2236  if (!getLangOpts().CPlusPlus &&
2237      Context.typesAreCompatible(OldQType, NewQType)) {
2238    const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2239    const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
2240    const FunctionProtoType *OldProto = 0;
2241    if (isa<FunctionNoProtoType>(NewFuncType) &&
2242        (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
2243      // The old declaration provided a function prototype, but the
2244      // new declaration does not. Merge in the prototype.
2245      assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
2246      SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
2247                                                 OldProto->arg_type_end());
2248      NewQType = Context.getFunctionType(NewFuncType->getResultType(),
2249                                         ParamTypes.data(), ParamTypes.size(),
2250                                         OldProto->getExtProtoInfo());
2251      New->setType(NewQType);
2252      New->setHasInheritedPrototype();
2253
2254      // Synthesize a parameter for each argument type.
2255      SmallVector<ParmVarDecl*, 16> Params;
2256      for (FunctionProtoType::arg_type_iterator
2257             ParamType = OldProto->arg_type_begin(),
2258             ParamEnd = OldProto->arg_type_end();
2259           ParamType != ParamEnd; ++ParamType) {
2260        ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
2261                                                 SourceLocation(),
2262                                                 SourceLocation(), 0,
2263                                                 *ParamType, /*TInfo=*/0,
2264                                                 SC_None, SC_None,
2265                                                 0);
2266        Param->setScopeInfo(0, Params.size());
2267        Param->setImplicit();
2268        Params.push_back(Param);
2269      }
2270
2271      New->setParams(Params);
2272    }
2273
2274    return MergeCompatibleFunctionDecls(New, Old, S);
2275  }
2276
2277  // GNU C permits a K&R definition to follow a prototype declaration
2278  // if the declared types of the parameters in the K&R definition
2279  // match the types in the prototype declaration, even when the
2280  // promoted types of the parameters from the K&R definition differ
2281  // from the types in the prototype. GCC then keeps the types from
2282  // the prototype.
2283  //
2284  // If a variadic prototype is followed by a non-variadic K&R definition,
2285  // the K&R definition becomes variadic.  This is sort of an edge case, but
2286  // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2287  // C99 6.9.1p8.
2288  if (!getLangOpts().CPlusPlus &&
2289      Old->hasPrototype() && !New->hasPrototype() &&
2290      New->getType()->getAs<FunctionProtoType>() &&
2291      Old->getNumParams() == New->getNumParams()) {
2292    SmallVector<QualType, 16> ArgTypes;
2293    SmallVector<GNUCompatibleParamWarning, 16> Warnings;
2294    const FunctionProtoType *OldProto
2295      = Old->getType()->getAs<FunctionProtoType>();
2296    const FunctionProtoType *NewProto
2297      = New->getType()->getAs<FunctionProtoType>();
2298
2299    // Determine whether this is the GNU C extension.
2300    QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
2301                                               NewProto->getResultType());
2302    bool LooseCompatible = !MergedReturn.isNull();
2303    for (unsigned Idx = 0, End = Old->getNumParams();
2304         LooseCompatible && Idx != End; ++Idx) {
2305      ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2306      ParmVarDecl *NewParm = New->getParamDecl(Idx);
2307      if (Context.typesAreCompatible(OldParm->getType(),
2308                                     NewProto->getArgType(Idx))) {
2309        ArgTypes.push_back(NewParm->getType());
2310      } else if (Context.typesAreCompatible(OldParm->getType(),
2311                                            NewParm->getType(),
2312                                            /*CompareUnqualified=*/true)) {
2313        GNUCompatibleParamWarning Warn
2314          = { OldParm, NewParm, NewProto->getArgType(Idx) };
2315        Warnings.push_back(Warn);
2316        ArgTypes.push_back(NewParm->getType());
2317      } else
2318        LooseCompatible = false;
2319    }
2320
2321    if (LooseCompatible) {
2322      for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2323        Diag(Warnings[Warn].NewParm->getLocation(),
2324             diag::ext_param_promoted_not_compatible_with_prototype)
2325          << Warnings[Warn].PromotedType
2326          << Warnings[Warn].OldParm->getType();
2327        if (Warnings[Warn].OldParm->getLocation().isValid())
2328          Diag(Warnings[Warn].OldParm->getLocation(),
2329               diag::note_previous_declaration);
2330      }
2331
2332      New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
2333                                           ArgTypes.size(),
2334                                           OldProto->getExtProtoInfo()));
2335      return MergeCompatibleFunctionDecls(New, Old, S);
2336    }
2337
2338    // Fall through to diagnose conflicting types.
2339  }
2340
2341  // A function that has already been declared has been redeclared or defined
2342  // with a different type- show appropriate diagnostic
2343  if (unsigned BuiltinID = Old->getBuiltinID()) {
2344    // The user has declared a builtin function with an incompatible
2345    // signature.
2346    if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2347      // The function the user is redeclaring is a library-defined
2348      // function like 'malloc' or 'printf'. Warn about the
2349      // redeclaration, then pretend that we don't know about this
2350      // library built-in.
2351      Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2352      Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2353        << Old << Old->getType();
2354      New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2355      Old->setInvalidDecl();
2356      return false;
2357    }
2358
2359    PrevDiag = diag::note_previous_builtin_declaration;
2360  }
2361
2362  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
2363  Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2364  return true;
2365}
2366
2367/// \brief Completes the merge of two function declarations that are
2368/// known to be compatible.
2369///
2370/// This routine handles the merging of attributes and other
2371/// properties of function declarations form the old declaration to
2372/// the new declaration, once we know that New is in fact a
2373/// redeclaration of Old.
2374///
2375/// \returns false
2376bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2377                                        Scope *S) {
2378  // Merge the attributes
2379  mergeDeclAttributes(New, Old);
2380
2381  // Merge the storage class.
2382  if (Old->getStorageClass() != SC_Extern &&
2383      Old->getStorageClass() != SC_None)
2384    New->setStorageClass(Old->getStorageClass());
2385
2386  // Merge "pure" flag.
2387  if (Old->isPure())
2388    New->setPure();
2389
2390  // Merge "used" flag.
2391  if (Old->isUsed(false))
2392    New->setUsed();
2393
2394  // Merge attributes from the parameters.  These can mismatch with K&R
2395  // declarations.
2396  if (New->getNumParams() == Old->getNumParams())
2397    for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2398      mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
2399                               Context);
2400
2401  if (getLangOpts().CPlusPlus)
2402    return MergeCXXFunctionDecl(New, Old, S);
2403
2404  // Merge the function types so the we get the composite types for the return
2405  // and argument types.
2406  QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
2407  if (!Merged.isNull())
2408    New->setType(Merged);
2409
2410  return false;
2411}
2412
2413
2414void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
2415                                ObjCMethodDecl *oldMethod) {
2416
2417  // Merge the attributes, including deprecated/unavailable
2418  mergeDeclAttributes(newMethod, oldMethod, /* mergeDeprecation */true);
2419
2420  // Merge attributes from the parameters.
2421  ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2422                                       oe = oldMethod->param_end();
2423  for (ObjCMethodDecl::param_iterator
2424         ni = newMethod->param_begin(), ne = newMethod->param_end();
2425       ni != ne && oi != oe; ++ni, ++oi)
2426    mergeParamDeclAttributes(*ni, *oi, Context);
2427
2428  CheckObjCMethodOverride(newMethod, oldMethod, true);
2429}
2430
2431/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2432/// scope as a previous declaration 'Old'.  Figure out how to merge their types,
2433/// emitting diagnostics as appropriate.
2434///
2435/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
2436/// to here in AddInitializerToDecl. We can't check them before the initializer
2437/// is attached.
2438void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) {
2439  if (New->isInvalidDecl() || Old->isInvalidDecl())
2440    return;
2441
2442  QualType MergedT;
2443  if (getLangOpts().CPlusPlus) {
2444    AutoType *AT = New->getType()->getContainedAutoType();
2445    if (AT && !AT->isDeduced()) {
2446      // We don't know what the new type is until the initializer is attached.
2447      return;
2448    } else if (Context.hasSameType(New->getType(), Old->getType())) {
2449      // These could still be something that needs exception specs checked.
2450      return MergeVarDeclExceptionSpecs(New, Old);
2451    }
2452    // C++ [basic.link]p10:
2453    //   [...] the types specified by all declarations referring to a given
2454    //   object or function shall be identical, except that declarations for an
2455    //   array object can specify array types that differ by the presence or
2456    //   absence of a major array bound (8.3.4).
2457    else if (Old->getType()->isIncompleteArrayType() &&
2458             New->getType()->isArrayType()) {
2459      CanQual<ArrayType> OldArray
2460        = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
2461      CanQual<ArrayType> NewArray
2462        = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
2463      if (OldArray->getElementType() == NewArray->getElementType())
2464        MergedT = New->getType();
2465    } else if (Old->getType()->isArrayType() &&
2466             New->getType()->isIncompleteArrayType()) {
2467      CanQual<ArrayType> OldArray
2468        = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
2469      CanQual<ArrayType> NewArray
2470        = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
2471      if (OldArray->getElementType() == NewArray->getElementType())
2472        MergedT = Old->getType();
2473    } else if (New->getType()->isObjCObjectPointerType()
2474               && Old->getType()->isObjCObjectPointerType()) {
2475        MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2476                                                        Old->getType());
2477    }
2478  } else {
2479    MergedT = Context.mergeTypes(New->getType(), Old->getType());
2480  }
2481  if (MergedT.isNull()) {
2482    Diag(New->getLocation(), diag::err_redefinition_different_type)
2483      << New->getDeclName() << New->getType() << Old->getType();
2484    Diag(Old->getLocation(), diag::note_previous_definition);
2485    return New->setInvalidDecl();
2486  }
2487  New->setType(MergedT);
2488}
2489
2490/// MergeVarDecl - We just parsed a variable 'New' which has the same name
2491/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
2492/// situation, merging decls or emitting diagnostics as appropriate.
2493///
2494/// Tentative definition rules (C99 6.9.2p2) are checked by
2495/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
2496/// definitions here, since the initializer hasn't been attached.
2497///
2498void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
2499  // If the new decl is already invalid, don't do any other checking.
2500  if (New->isInvalidDecl())
2501    return;
2502
2503  // Verify the old decl was also a variable.
2504  VarDecl *Old = 0;
2505  if (!Previous.isSingleResult() ||
2506      !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
2507    Diag(New->getLocation(), diag::err_redefinition_different_kind)
2508      << New->getDeclName();
2509    Diag(Previous.getRepresentativeDecl()->getLocation(),
2510         diag::note_previous_definition);
2511    return New->setInvalidDecl();
2512  }
2513
2514  // C++ [class.mem]p1:
2515  //   A member shall not be declared twice in the member-specification [...]
2516  //
2517  // Here, we need only consider static data members.
2518  if (Old->isStaticDataMember() && !New->isOutOfLine()) {
2519    Diag(New->getLocation(), diag::err_duplicate_member)
2520      << New->getIdentifier();
2521    Diag(Old->getLocation(), diag::note_previous_declaration);
2522    New->setInvalidDecl();
2523  }
2524
2525  mergeDeclAttributes(New, Old);
2526  // Warn if an already-declared variable is made a weak_import in a subsequent
2527  // declaration
2528  if (New->getAttr<WeakImportAttr>() &&
2529      Old->getStorageClass() == SC_None &&
2530      !Old->getAttr<WeakImportAttr>()) {
2531    Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
2532    Diag(Old->getLocation(), diag::note_previous_definition);
2533    // Remove weak_import attribute on new declaration.
2534    New->dropAttr<WeakImportAttr>();
2535  }
2536
2537  // Merge the types.
2538  MergeVarDeclTypes(New, Old);
2539  if (New->isInvalidDecl())
2540    return;
2541
2542  // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
2543  if (New->getStorageClass() == SC_Static &&
2544      (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) {
2545    Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
2546    Diag(Old->getLocation(), diag::note_previous_definition);
2547    return New->setInvalidDecl();
2548  }
2549  // C99 6.2.2p4:
2550  //   For an identifier declared with the storage-class specifier
2551  //   extern in a scope in which a prior declaration of that
2552  //   identifier is visible,23) if the prior declaration specifies
2553  //   internal or external linkage, the linkage of the identifier at
2554  //   the later declaration is the same as the linkage specified at
2555  //   the prior declaration. If no prior declaration is visible, or
2556  //   if the prior declaration specifies no linkage, then the
2557  //   identifier has external linkage.
2558  if (New->hasExternalStorage() && Old->hasLinkage())
2559    /* Okay */;
2560  else if (New->getStorageClass() != SC_Static &&
2561           Old->getStorageClass() == SC_Static) {
2562    Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
2563    Diag(Old->getLocation(), diag::note_previous_definition);
2564    return New->setInvalidDecl();
2565  }
2566
2567  // Check if extern is followed by non-extern and vice-versa.
2568  if (New->hasExternalStorage() &&
2569      !Old->hasLinkage() && Old->isLocalVarDecl()) {
2570    Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
2571    Diag(Old->getLocation(), diag::note_previous_definition);
2572    return New->setInvalidDecl();
2573  }
2574  if (Old->hasExternalStorage() &&
2575      !New->hasLinkage() && New->isLocalVarDecl()) {
2576    Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
2577    Diag(Old->getLocation(), diag::note_previous_definition);
2578    return New->setInvalidDecl();
2579  }
2580
2581  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
2582
2583  // FIXME: The test for external storage here seems wrong? We still
2584  // need to check for mismatches.
2585  if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
2586      // Don't complain about out-of-line definitions of static members.
2587      !(Old->getLexicalDeclContext()->isRecord() &&
2588        !New->getLexicalDeclContext()->isRecord())) {
2589    Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
2590    Diag(Old->getLocation(), diag::note_previous_definition);
2591    return New->setInvalidDecl();
2592  }
2593
2594  if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
2595    Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
2596    Diag(Old->getLocation(), diag::note_previous_definition);
2597  } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
2598    Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
2599    Diag(Old->getLocation(), diag::note_previous_definition);
2600  }
2601
2602  // C++ doesn't have tentative definitions, so go right ahead and check here.
2603  const VarDecl *Def;
2604  if (getLangOpts().CPlusPlus &&
2605      New->isThisDeclarationADefinition() == VarDecl::Definition &&
2606      (Def = Old->getDefinition())) {
2607    Diag(New->getLocation(), diag::err_redefinition)
2608      << New->getDeclName();
2609    Diag(Def->getLocation(), diag::note_previous_definition);
2610    New->setInvalidDecl();
2611    return;
2612  }
2613  // c99 6.2.2 P4.
2614  // For an identifier declared with the storage-class specifier extern in a
2615  // scope in which a prior declaration of that identifier is visible, if
2616  // the prior declaration specifies internal or external linkage, the linkage
2617  // of the identifier at the later declaration is the same as the linkage
2618  // specified at the prior declaration.
2619  // FIXME. revisit this code.
2620  if (New->hasExternalStorage() &&
2621      Old->getLinkage() == InternalLinkage &&
2622      New->getDeclContext() == Old->getDeclContext())
2623    New->setStorageClass(Old->getStorageClass());
2624
2625  // Merge "used" flag.
2626  if (Old->isUsed(false))
2627    New->setUsed();
2628
2629  // Keep a chain of previous declarations.
2630  New->setPreviousDeclaration(Old);
2631
2632  // Inherit access appropriately.
2633  New->setAccess(Old->getAccess());
2634}
2635
2636/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2637/// no declarator (e.g. "struct foo;") is parsed.
2638Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
2639                                       DeclSpec &DS) {
2640  return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
2641}
2642
2643/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2644/// no declarator (e.g. "struct foo;") is parsed. It also accopts template
2645/// parameters to cope with template friend declarations.
2646Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
2647                                       DeclSpec &DS,
2648                                       MultiTemplateParamsArg TemplateParams) {
2649  Decl *TagD = 0;
2650  TagDecl *Tag = 0;
2651  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
2652      DS.getTypeSpecType() == DeclSpec::TST_struct ||
2653      DS.getTypeSpecType() == DeclSpec::TST_interface ||
2654      DS.getTypeSpecType() == DeclSpec::TST_union ||
2655      DS.getTypeSpecType() == DeclSpec::TST_enum) {
2656    TagD = DS.getRepAsDecl();
2657
2658    if (!TagD) // We probably had an error
2659      return 0;
2660
2661    // Note that the above type specs guarantee that the
2662    // type rep is a Decl, whereas in many of the others
2663    // it's a Type.
2664    if (isa<TagDecl>(TagD))
2665      Tag = cast<TagDecl>(TagD);
2666    else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
2667      Tag = CTD->getTemplatedDecl();
2668  }
2669
2670  if (Tag) {
2671    getASTContext().addUnnamedTag(Tag);
2672    Tag->setFreeStanding();
2673    if (Tag->isInvalidDecl())
2674      return Tag;
2675  }
2676
2677  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
2678    // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
2679    // or incomplete types shall not be restrict-qualified."
2680    if (TypeQuals & DeclSpec::TQ_restrict)
2681      Diag(DS.getRestrictSpecLoc(),
2682           diag::err_typecheck_invalid_restrict_not_pointer_noarg)
2683           << DS.getSourceRange();
2684  }
2685
2686  if (DS.isConstexprSpecified()) {
2687    // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
2688    // and definitions of functions and variables.
2689    if (Tag)
2690      Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
2691        << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
2692            DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
2693            DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
2694            DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
2695    else
2696      Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
2697    // Don't emit warnings after this error.
2698    return TagD;
2699  }
2700
2701  if (DS.isFriendSpecified()) {
2702    // If we're dealing with a decl but not a TagDecl, assume that
2703    // whatever routines created it handled the friendship aspect.
2704    if (TagD && !Tag)
2705      return 0;
2706    return ActOnFriendTypeDecl(S, DS, TemplateParams);
2707  }
2708
2709  // Track whether we warned about the fact that there aren't any
2710  // declarators.
2711  bool emittedWarning = false;
2712
2713  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
2714    if (!Record->getDeclName() && Record->isCompleteDefinition() &&
2715        DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
2716      if (getLangOpts().CPlusPlus ||
2717          Record->getDeclContext()->isRecord())
2718        return BuildAnonymousStructOrUnion(S, DS, AS, Record);
2719
2720      Diag(DS.getLocStart(), diag::ext_no_declarators)
2721        << DS.getSourceRange();
2722      emittedWarning = true;
2723    }
2724  }
2725
2726  // Check for Microsoft C extension: anonymous struct.
2727  if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
2728      CurContext->isRecord() &&
2729      DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
2730    // Handle 2 kinds of anonymous struct:
2731    //   struct STRUCT;
2732    // and
2733    //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
2734    RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
2735    if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
2736        (DS.getTypeSpecType() == DeclSpec::TST_typename &&
2737         DS.getRepAsType().get()->isStructureType())) {
2738      Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
2739        << DS.getSourceRange();
2740      return BuildMicrosoftCAnonymousStruct(S, DS, Record);
2741    }
2742  }
2743
2744  if (getLangOpts().CPlusPlus &&
2745      DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
2746    if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
2747      if (Enum->enumerator_begin() == Enum->enumerator_end() &&
2748          !Enum->getIdentifier() && !Enum->isInvalidDecl()) {
2749        Diag(Enum->getLocation(), diag::ext_no_declarators)
2750          << DS.getSourceRange();
2751        emittedWarning = true;
2752      }
2753
2754  // Skip all the checks below if we have a type error.
2755  if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD;
2756
2757  if (!DS.isMissingDeclaratorOk()) {
2758    // Warn about typedefs of enums without names, since this is an
2759    // extension in both Microsoft and GNU.
2760    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
2761        Tag && isa<EnumDecl>(Tag)) {
2762      Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
2763        << DS.getSourceRange();
2764      return Tag;
2765    }
2766
2767    Diag(DS.getLocStart(), diag::ext_no_declarators)
2768      << DS.getSourceRange();
2769    emittedWarning = true;
2770  }
2771
2772  // We're going to complain about a bunch of spurious specifiers;
2773  // only do this if we're declaring a tag, because otherwise we
2774  // should be getting diag::ext_no_declarators.
2775  if (emittedWarning || (TagD && TagD->isInvalidDecl()))
2776    return TagD;
2777
2778  // Note that a linkage-specification sets a storage class, but
2779  // 'extern "C" struct foo;' is actually valid and not theoretically
2780  // useless.
2781  if (DeclSpec::SCS scs = DS.getStorageClassSpec())
2782    if (!DS.isExternInLinkageSpec())
2783      Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier)
2784        << DeclSpec::getSpecifierName(scs);
2785
2786  if (DS.isThreadSpecified())
2787    Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread";
2788  if (DS.getTypeQualifiers()) {
2789    if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2790      Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const";
2791    if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2792      Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile";
2793    // Restrict is covered above.
2794  }
2795  if (DS.isInlineSpecified())
2796    Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline";
2797  if (DS.isVirtualSpecified())
2798    Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual";
2799  if (DS.isExplicitSpecified())
2800    Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit";
2801
2802  if (DS.isModulePrivateSpecified() &&
2803      Tag && Tag->getDeclContext()->isFunctionOrMethod())
2804    Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
2805      << Tag->getTagKind()
2806      << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
2807
2808  // Warn about ignored type attributes, for example:
2809  // __attribute__((aligned)) struct A;
2810  // Attributes should be placed after tag to apply to type declaration.
2811  if (!DS.getAttributes().empty()) {
2812    DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
2813    if (TypeSpecType == DeclSpec::TST_class ||
2814        TypeSpecType == DeclSpec::TST_struct ||
2815        TypeSpecType == DeclSpec::TST_interface ||
2816        TypeSpecType == DeclSpec::TST_union ||
2817        TypeSpecType == DeclSpec::TST_enum) {
2818      AttributeList* attrs = DS.getAttributes().getList();
2819      while (attrs) {
2820        Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
2821        << attrs->getName()
2822        << (TypeSpecType == DeclSpec::TST_class ? 0 :
2823            TypeSpecType == DeclSpec::TST_struct ? 1 :
2824            TypeSpecType == DeclSpec::TST_union ? 2 :
2825            TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
2826        attrs = attrs->getNext();
2827      }
2828    }
2829  }
2830
2831  ActOnDocumentableDecl(TagD);
2832
2833  return TagD;
2834}
2835
2836/// We are trying to inject an anonymous member into the given scope;
2837/// check if there's an existing declaration that can't be overloaded.
2838///
2839/// \return true if this is a forbidden redeclaration
2840static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
2841                                         Scope *S,
2842                                         DeclContext *Owner,
2843                                         DeclarationName Name,
2844                                         SourceLocation NameLoc,
2845                                         unsigned diagnostic) {
2846  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
2847                 Sema::ForRedeclaration);
2848  if (!SemaRef.LookupName(R, S)) return false;
2849
2850  if (R.getAsSingle<TagDecl>())
2851    return false;
2852
2853  // Pick a representative declaration.
2854  NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
2855  assert(PrevDecl && "Expected a non-null Decl");
2856
2857  if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
2858    return false;
2859
2860  SemaRef.Diag(NameLoc, diagnostic) << Name;
2861  SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
2862
2863  return true;
2864}
2865
2866/// InjectAnonymousStructOrUnionMembers - Inject the members of the
2867/// anonymous struct or union AnonRecord into the owning context Owner
2868/// and scope S. This routine will be invoked just after we realize
2869/// that an unnamed union or struct is actually an anonymous union or
2870/// struct, e.g.,
2871///
2872/// @code
2873/// union {
2874///   int i;
2875///   float f;
2876/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
2877///    // f into the surrounding scope.x
2878/// @endcode
2879///
2880/// This routine is recursive, injecting the names of nested anonymous
2881/// structs/unions into the owning context and scope as well.
2882static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
2883                                                DeclContext *Owner,
2884                                                RecordDecl *AnonRecord,
2885                                                AccessSpecifier AS,
2886                              SmallVector<NamedDecl*, 2> &Chaining,
2887                                                      bool MSAnonStruct) {
2888  unsigned diagKind
2889    = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
2890                            : diag::err_anonymous_struct_member_redecl;
2891
2892  bool Invalid = false;
2893
2894  // Look every FieldDecl and IndirectFieldDecl with a name.
2895  for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
2896                               DEnd = AnonRecord->decls_end();
2897       D != DEnd; ++D) {
2898    if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
2899        cast<NamedDecl>(*D)->getDeclName()) {
2900      ValueDecl *VD = cast<ValueDecl>(*D);
2901      if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
2902                                       VD->getLocation(), diagKind)) {
2903        // C++ [class.union]p2:
2904        //   The names of the members of an anonymous union shall be
2905        //   distinct from the names of any other entity in the
2906        //   scope in which the anonymous union is declared.
2907        Invalid = true;
2908      } else {
2909        // C++ [class.union]p2:
2910        //   For the purpose of name lookup, after the anonymous union
2911        //   definition, the members of the anonymous union are
2912        //   considered to have been defined in the scope in which the
2913        //   anonymous union is declared.
2914        unsigned OldChainingSize = Chaining.size();
2915        if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
2916          for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
2917               PE = IF->chain_end(); PI != PE; ++PI)
2918            Chaining.push_back(*PI);
2919        else
2920          Chaining.push_back(VD);
2921
2922        assert(Chaining.size() >= 2);
2923        NamedDecl **NamedChain =
2924          new (SemaRef.Context)NamedDecl*[Chaining.size()];
2925        for (unsigned i = 0; i < Chaining.size(); i++)
2926          NamedChain[i] = Chaining[i];
2927
2928        IndirectFieldDecl* IndirectField =
2929          IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
2930                                    VD->getIdentifier(), VD->getType(),
2931                                    NamedChain, Chaining.size());
2932
2933        IndirectField->setAccess(AS);
2934        IndirectField->setImplicit();
2935        SemaRef.PushOnScopeChains(IndirectField, S);
2936
2937        // That includes picking up the appropriate access specifier.
2938        if (AS != AS_none) IndirectField->setAccess(AS);
2939
2940        Chaining.resize(OldChainingSize);
2941      }
2942    }
2943  }
2944
2945  return Invalid;
2946}
2947
2948/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
2949/// a VarDecl::StorageClass. Any error reporting is up to the caller:
2950/// illegal input values are mapped to SC_None.
2951static StorageClass
2952StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
2953  switch (StorageClassSpec) {
2954  case DeclSpec::SCS_unspecified:    return SC_None;
2955  case DeclSpec::SCS_extern:         return SC_Extern;
2956  case DeclSpec::SCS_static:         return SC_Static;
2957  case DeclSpec::SCS_auto:           return SC_Auto;
2958  case DeclSpec::SCS_register:       return SC_Register;
2959  case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
2960    // Illegal SCSs map to None: error reporting is up to the caller.
2961  case DeclSpec::SCS_mutable:        // Fall through.
2962  case DeclSpec::SCS_typedef:        return SC_None;
2963  }
2964  llvm_unreachable("unknown storage class specifier");
2965}
2966
2967/// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
2968/// a StorageClass. Any error reporting is up to the caller:
2969/// illegal input values are mapped to SC_None.
2970static StorageClass
2971StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
2972  switch (StorageClassSpec) {
2973  case DeclSpec::SCS_unspecified:    return SC_None;
2974  case DeclSpec::SCS_extern:         return SC_Extern;
2975  case DeclSpec::SCS_static:         return SC_Static;
2976  case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
2977    // Illegal SCSs map to None: error reporting is up to the caller.
2978  case DeclSpec::SCS_auto:           // Fall through.
2979  case DeclSpec::SCS_mutable:        // Fall through.
2980  case DeclSpec::SCS_register:       // Fall through.
2981  case DeclSpec::SCS_typedef:        return SC_None;
2982  }
2983  llvm_unreachable("unknown storage class specifier");
2984}
2985
2986/// BuildAnonymousStructOrUnion - Handle the declaration of an
2987/// anonymous structure or union. Anonymous unions are a C++ feature
2988/// (C++ [class.union]) and a C11 feature; anonymous structures
2989/// are a C11 feature and GNU C++ extension.
2990Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2991                                             AccessSpecifier AS,
2992                                             RecordDecl *Record) {
2993  DeclContext *Owner = Record->getDeclContext();
2994
2995  // Diagnose whether this anonymous struct/union is an extension.
2996  if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
2997    Diag(Record->getLocation(), diag::ext_anonymous_union);
2998  else if (!Record->isUnion() && getLangOpts().CPlusPlus)
2999    Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
3000  else if (!Record->isUnion() && !getLangOpts().C11)
3001    Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
3002
3003  // C and C++ require different kinds of checks for anonymous
3004  // structs/unions.
3005  bool Invalid = false;
3006  if (getLangOpts().CPlusPlus) {
3007    const char* PrevSpec = 0;
3008    unsigned DiagID;
3009    if (Record->isUnion()) {
3010      // C++ [class.union]p6:
3011      //   Anonymous unions declared in a named namespace or in the
3012      //   global namespace shall be declared static.
3013      if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3014          (isa<TranslationUnitDecl>(Owner) ||
3015           (isa<NamespaceDecl>(Owner) &&
3016            cast<NamespaceDecl>(Owner)->getDeclName()))) {
3017        Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3018          << FixItHint::CreateInsertion(Record->getLocation(), "static ");
3019
3020        // Recover by adding 'static'.
3021        DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
3022                               PrevSpec, DiagID);
3023      }
3024      // C++ [class.union]p6:
3025      //   A storage class is not allowed in a declaration of an
3026      //   anonymous union in a class scope.
3027      else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3028               isa<RecordDecl>(Owner)) {
3029        Diag(DS.getStorageClassSpecLoc(),
3030             diag::err_anonymous_union_with_storage_spec)
3031          << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3032
3033        // Recover by removing the storage specifier.
3034        DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3035                               SourceLocation(),
3036                               PrevSpec, DiagID);
3037      }
3038    }
3039
3040    // Ignore const/volatile/restrict qualifiers.
3041    if (DS.getTypeQualifiers()) {
3042      if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3043        Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
3044          << Record->isUnion() << 0
3045          << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3046      if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3047        Diag(DS.getVolatileSpecLoc(),
3048             diag::ext_anonymous_struct_union_qualified)
3049          << Record->isUnion() << 1
3050          << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3051      if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
3052        Diag(DS.getRestrictSpecLoc(),
3053             diag::ext_anonymous_struct_union_qualified)
3054          << Record->isUnion() << 2
3055          << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
3056
3057      DS.ClearTypeQualifiers();
3058    }
3059
3060    // C++ [class.union]p2:
3061    //   The member-specification of an anonymous union shall only
3062    //   define non-static data members. [Note: nested types and
3063    //   functions cannot be declared within an anonymous union. ]
3064    for (DeclContext::decl_iterator Mem = Record->decls_begin(),
3065                                 MemEnd = Record->decls_end();
3066         Mem != MemEnd; ++Mem) {
3067      if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
3068        // C++ [class.union]p3:
3069        //   An anonymous union shall not have private or protected
3070        //   members (clause 11).
3071        assert(FD->getAccess() != AS_none);
3072        if (FD->getAccess() != AS_public) {
3073          Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3074            << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3075          Invalid = true;
3076        }
3077
3078        // C++ [class.union]p1
3079        //   An object of a class with a non-trivial constructor, a non-trivial
3080        //   copy constructor, a non-trivial destructor, or a non-trivial copy
3081        //   assignment operator cannot be a member of a union, nor can an
3082        //   array of such objects.
3083        if (CheckNontrivialField(FD))
3084          Invalid = true;
3085      } else if ((*Mem)->isImplicit()) {
3086        // Any implicit members are fine.
3087      } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
3088        // This is a type that showed up in an
3089        // elaborated-type-specifier inside the anonymous struct or
3090        // union, but which actually declares a type outside of the
3091        // anonymous struct or union. It's okay.
3092      } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
3093        if (!MemRecord->isAnonymousStructOrUnion() &&
3094            MemRecord->getDeclName()) {
3095          // Visual C++ allows type definition in anonymous struct or union.
3096          if (getLangOpts().MicrosoftExt)
3097            Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3098              << (int)Record->isUnion();
3099          else {
3100            // This is a nested type declaration.
3101            Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3102              << (int)Record->isUnion();
3103            Invalid = true;
3104          }
3105        }
3106      } else if (isa<AccessSpecDecl>(*Mem)) {
3107        // Any access specifier is fine.
3108      } else {
3109        // We have something that isn't a non-static data
3110        // member. Complain about it.
3111        unsigned DK = diag::err_anonymous_record_bad_member;
3112        if (isa<TypeDecl>(*Mem))
3113          DK = diag::err_anonymous_record_with_type;
3114        else if (isa<FunctionDecl>(*Mem))
3115          DK = diag::err_anonymous_record_with_function;
3116        else if (isa<VarDecl>(*Mem))
3117          DK = diag::err_anonymous_record_with_static;
3118
3119        // Visual C++ allows type definition in anonymous struct or union.
3120        if (getLangOpts().MicrosoftExt &&
3121            DK == diag::err_anonymous_record_with_type)
3122          Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
3123            << (int)Record->isUnion();
3124        else {
3125          Diag((*Mem)->getLocation(), DK)
3126              << (int)Record->isUnion();
3127          Invalid = true;
3128        }
3129      }
3130    }
3131  }
3132
3133  if (!Record->isUnion() && !Owner->isRecord()) {
3134    Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
3135      << (int)getLangOpts().CPlusPlus;
3136    Invalid = true;
3137  }
3138
3139  // Mock up a declarator.
3140  Declarator Dc(DS, Declarator::MemberContext);
3141  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3142  assert(TInfo && "couldn't build declarator info for anonymous struct/union");
3143
3144  // Create a declaration for this anonymous struct/union.
3145  NamedDecl *Anon = 0;
3146  if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
3147    Anon = FieldDecl::Create(Context, OwningClass,
3148                             DS.getLocStart(),
3149                             Record->getLocation(),
3150                             /*IdentifierInfo=*/0,
3151                             Context.getTypeDeclType(Record),
3152                             TInfo,
3153                             /*BitWidth=*/0, /*Mutable=*/false,
3154                             /*InitStyle=*/ICIS_NoInit);
3155    Anon->setAccess(AS);
3156    if (getLangOpts().CPlusPlus)
3157      FieldCollector->Add(cast<FieldDecl>(Anon));
3158  } else {
3159    DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
3160    assert(SCSpec != DeclSpec::SCS_typedef &&
3161           "Parser allowed 'typedef' as storage class VarDecl.");
3162    VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
3163    if (SCSpec == DeclSpec::SCS_mutable) {
3164      // mutable can only appear on non-static class members, so it's always
3165      // an error here
3166      Diag(Record->getLocation(), diag::err_mutable_nonmember);
3167      Invalid = true;
3168      SC = SC_None;
3169    }
3170    SCSpec = DS.getStorageClassSpecAsWritten();
3171    VarDecl::StorageClass SCAsWritten
3172      = StorageClassSpecToVarDeclStorageClass(SCSpec);
3173
3174    Anon = VarDecl::Create(Context, Owner,
3175                           DS.getLocStart(),
3176                           Record->getLocation(), /*IdentifierInfo=*/0,
3177                           Context.getTypeDeclType(Record),
3178                           TInfo, SC, SCAsWritten);
3179
3180    // Default-initialize the implicit variable. This initialization will be
3181    // trivial in almost all cases, except if a union member has an in-class
3182    // initializer:
3183    //   union { int n = 0; };
3184    ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
3185  }
3186  Anon->setImplicit();
3187
3188  // Add the anonymous struct/union object to the current
3189  // context. We'll be referencing this object when we refer to one of
3190  // its members.
3191  Owner->addDecl(Anon);
3192
3193  // Inject the members of the anonymous struct/union into the owning
3194  // context and into the identifier resolver chain for name lookup
3195  // purposes.
3196  SmallVector<NamedDecl*, 2> Chain;
3197  Chain.push_back(Anon);
3198
3199  if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3200                                          Chain, false))
3201    Invalid = true;
3202
3203  // Mark this as an anonymous struct/union type. Note that we do not
3204  // do this until after we have already checked and injected the
3205  // members of this anonymous struct/union type, because otherwise
3206  // the members could be injected twice: once by DeclContext when it
3207  // builds its lookup table, and once by
3208  // InjectAnonymousStructOrUnionMembers.
3209  Record->setAnonymousStructOrUnion(true);
3210
3211  if (Invalid)
3212    Anon->setInvalidDecl();
3213
3214  return Anon;
3215}
3216
3217/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3218/// Microsoft C anonymous structure.
3219/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3220/// Example:
3221///
3222/// struct A { int a; };
3223/// struct B { struct A; int b; };
3224///
3225/// void foo() {
3226///   B var;
3227///   var.a = 3;
3228/// }
3229///
3230Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3231                                           RecordDecl *Record) {
3232
3233  // If there is no Record, get the record via the typedef.
3234  if (!Record)
3235    Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3236
3237  // Mock up a declarator.
3238  Declarator Dc(DS, Declarator::TypeNameContext);
3239  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3240  assert(TInfo && "couldn't build declarator info for anonymous struct");
3241
3242  // Create a declaration for this anonymous struct.
3243  NamedDecl* Anon = FieldDecl::Create(Context,
3244                             cast<RecordDecl>(CurContext),
3245                             DS.getLocStart(),
3246                             DS.getLocStart(),
3247                             /*IdentifierInfo=*/0,
3248                             Context.getTypeDeclType(Record),
3249                             TInfo,
3250                             /*BitWidth=*/0, /*Mutable=*/false,
3251                             /*InitStyle=*/ICIS_NoInit);
3252  Anon->setImplicit();
3253
3254  // Add the anonymous struct object to the current context.
3255  CurContext->addDecl(Anon);
3256
3257  // Inject the members of the anonymous struct into the current
3258  // context and into the identifier resolver chain for name lookup
3259  // purposes.
3260  SmallVector<NamedDecl*, 2> Chain;
3261  Chain.push_back(Anon);
3262
3263  RecordDecl *RecordDef = Record->getDefinition();
3264  if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3265                                                        RecordDef, AS_none,
3266                                                        Chain, true))
3267    Anon->setInvalidDecl();
3268
3269  return Anon;
3270}
3271
3272/// GetNameForDeclarator - Determine the full declaration name for the
3273/// given Declarator.
3274DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
3275  return GetNameFromUnqualifiedId(D.getName());
3276}
3277
3278/// \brief Retrieves the declaration name from a parsed unqualified-id.
3279DeclarationNameInfo
3280Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3281  DeclarationNameInfo NameInfo;
3282  NameInfo.setLoc(Name.StartLocation);
3283
3284  switch (Name.getKind()) {
3285
3286  case UnqualifiedId::IK_ImplicitSelfParam:
3287  case UnqualifiedId::IK_Identifier:
3288    NameInfo.setName(Name.Identifier);
3289    NameInfo.setLoc(Name.StartLocation);
3290    return NameInfo;
3291
3292  case UnqualifiedId::IK_OperatorFunctionId:
3293    NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3294                                           Name.OperatorFunctionId.Operator));
3295    NameInfo.setLoc(Name.StartLocation);
3296    NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3297      = Name.OperatorFunctionId.SymbolLocations[0];
3298    NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3299      = Name.EndLocation.getRawEncoding();
3300    return NameInfo;
3301
3302  case UnqualifiedId::IK_LiteralOperatorId:
3303    NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3304                                                           Name.Identifier));
3305    NameInfo.setLoc(Name.StartLocation);
3306    NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3307    return NameInfo;
3308
3309  case UnqualifiedId::IK_ConversionFunctionId: {
3310    TypeSourceInfo *TInfo;
3311    QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3312    if (Ty.isNull())
3313      return DeclarationNameInfo();
3314    NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3315                                               Context.getCanonicalType(Ty)));
3316    NameInfo.setLoc(Name.StartLocation);
3317    NameInfo.setNamedTypeInfo(TInfo);
3318    return NameInfo;
3319  }
3320
3321  case UnqualifiedId::IK_ConstructorName: {
3322    TypeSourceInfo *TInfo;
3323    QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3324    if (Ty.isNull())
3325      return DeclarationNameInfo();
3326    NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3327                                              Context.getCanonicalType(Ty)));
3328    NameInfo.setLoc(Name.StartLocation);
3329    NameInfo.setNamedTypeInfo(TInfo);
3330    return NameInfo;
3331  }
3332
3333  case UnqualifiedId::IK_ConstructorTemplateId: {
3334    // In well-formed code, we can only have a constructor
3335    // template-id that refers to the current context, so go there
3336    // to find the actual type being constructed.
3337    CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3338    if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3339      return DeclarationNameInfo();
3340
3341    // Determine the type of the class being constructed.
3342    QualType CurClassType = Context.getTypeDeclType(CurClass);
3343
3344    // FIXME: Check two things: that the template-id names the same type as
3345    // CurClassType, and that the template-id does not occur when the name
3346    // was qualified.
3347
3348    NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3349                                    Context.getCanonicalType(CurClassType)));
3350    NameInfo.setLoc(Name.StartLocation);
3351    // FIXME: should we retrieve TypeSourceInfo?
3352    NameInfo.setNamedTypeInfo(0);
3353    return NameInfo;
3354  }
3355
3356  case UnqualifiedId::IK_DestructorName: {
3357    TypeSourceInfo *TInfo;
3358    QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3359    if (Ty.isNull())
3360      return DeclarationNameInfo();
3361    NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3362                                              Context.getCanonicalType(Ty)));
3363    NameInfo.setLoc(Name.StartLocation);
3364    NameInfo.setNamedTypeInfo(TInfo);
3365    return NameInfo;
3366  }
3367
3368  case UnqualifiedId::IK_TemplateId: {
3369    TemplateName TName = Name.TemplateId->Template.get();
3370    SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3371    return Context.getNameForTemplate(TName, TNameLoc);
3372  }
3373
3374  } // switch (Name.getKind())
3375
3376  llvm_unreachable("Unknown name kind");
3377}
3378
3379static QualType getCoreType(QualType Ty) {
3380  do {
3381    if (Ty->isPointerType() || Ty->isReferenceType())
3382      Ty = Ty->getPointeeType();
3383    else if (Ty->isArrayType())
3384      Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3385    else
3386      return Ty.withoutLocalFastQualifiers();
3387  } while (true);
3388}
3389
3390/// hasSimilarParameters - Determine whether the C++ functions Declaration
3391/// and Definition have "nearly" matching parameters. This heuristic is
3392/// used to improve diagnostics in the case where an out-of-line function
3393/// definition doesn't match any declaration within the class or namespace.
3394/// Also sets Params to the list of indices to the parameters that differ
3395/// between the declaration and the definition. If hasSimilarParameters
3396/// returns true and Params is empty, then all of the parameters match.
3397static bool hasSimilarParameters(ASTContext &Context,
3398                                     FunctionDecl *Declaration,
3399                                     FunctionDecl *Definition,
3400                                     llvm::SmallVectorImpl<unsigned> &Params) {
3401  Params.clear();
3402  if (Declaration->param_size() != Definition->param_size())
3403    return false;
3404  for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3405    QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3406    QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3407
3408    // The parameter types are identical
3409    if (Context.hasSameType(DefParamTy, DeclParamTy))
3410      continue;
3411
3412    QualType DeclParamBaseTy = getCoreType(DeclParamTy);
3413    QualType DefParamBaseTy = getCoreType(DefParamTy);
3414    const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
3415    const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
3416
3417    if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
3418        (DeclTyName && DeclTyName == DefTyName))
3419      Params.push_back(Idx);
3420    else  // The two parameters aren't even close
3421      return false;
3422  }
3423
3424  return true;
3425}
3426
3427/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
3428/// declarator needs to be rebuilt in the current instantiation.
3429/// Any bits of declarator which appear before the name are valid for
3430/// consideration here.  That's specifically the type in the decl spec
3431/// and the base type in any member-pointer chunks.
3432static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
3433                                                    DeclarationName Name) {
3434  // The types we specifically need to rebuild are:
3435  //   - typenames, typeofs, and decltypes
3436  //   - types which will become injected class names
3437  // Of course, we also need to rebuild any type referencing such a
3438  // type.  It's safest to just say "dependent", but we call out a
3439  // few cases here.
3440
3441  DeclSpec &DS = D.getMutableDeclSpec();
3442  switch (DS.getTypeSpecType()) {
3443  case DeclSpec::TST_typename:
3444  case DeclSpec::TST_typeofType:
3445  case DeclSpec::TST_underlyingType:
3446  case DeclSpec::TST_atomic: {
3447    // Grab the type from the parser.
3448    TypeSourceInfo *TSI = 0;
3449    QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
3450    if (T.isNull() || !T->isDependentType()) break;
3451
3452    // Make sure there's a type source info.  This isn't really much
3453    // of a waste; most dependent types should have type source info
3454    // attached already.
3455    if (!TSI)
3456      TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
3457
3458    // Rebuild the type in the current instantiation.
3459    TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
3460    if (!TSI) return true;
3461
3462    // Store the new type back in the decl spec.
3463    ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
3464    DS.UpdateTypeRep(LocType);
3465    break;
3466  }
3467
3468  case DeclSpec::TST_decltype:
3469  case DeclSpec::TST_typeofExpr: {
3470    Expr *E = DS.getRepAsExpr();
3471    ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
3472    if (Result.isInvalid()) return true;
3473    DS.UpdateExprRep(Result.get());
3474    break;
3475  }
3476
3477  default:
3478    // Nothing to do for these decl specs.
3479    break;
3480  }
3481
3482  // It doesn't matter what order we do this in.
3483  for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3484    DeclaratorChunk &Chunk = D.getTypeObject(I);
3485
3486    // The only type information in the declarator which can come
3487    // before the declaration name is the base type of a member
3488    // pointer.
3489    if (Chunk.Kind != DeclaratorChunk::MemberPointer)
3490      continue;
3491
3492    // Rebuild the scope specifier in-place.
3493    CXXScopeSpec &SS = Chunk.Mem.Scope();
3494    if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
3495      return true;
3496  }
3497
3498  return false;
3499}
3500
3501Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
3502  D.setFunctionDefinitionKind(FDK_Declaration);
3503  Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
3504
3505  if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
3506      Dcl && Dcl->getDeclContext()->isFileContext())
3507    Dcl->setTopLevelDeclInObjCContainer();
3508
3509  return Dcl;
3510}
3511
3512/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
3513///   If T is the name of a class, then each of the following shall have a
3514///   name different from T:
3515///     - every static data member of class T;
3516///     - every member function of class T
3517///     - every member of class T that is itself a type;
3518/// \returns true if the declaration name violates these rules.
3519bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
3520                                   DeclarationNameInfo NameInfo) {
3521  DeclarationName Name = NameInfo.getName();
3522
3523  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
3524    if (Record->getIdentifier() && Record->getDeclName() == Name) {
3525      Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
3526      return true;
3527    }
3528
3529  return false;
3530}
3531
3532/// \brief Diagnose a declaration whose declarator-id has the given
3533/// nested-name-specifier.
3534///
3535/// \param SS The nested-name-specifier of the declarator-id.
3536///
3537/// \param DC The declaration context to which the nested-name-specifier
3538/// resolves.
3539///
3540/// \param Name The name of the entity being declared.
3541///
3542/// \param Loc The location of the name of the entity being declared.
3543///
3544/// \returns true if we cannot safely recover from this error, false otherwise.
3545bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
3546                                        DeclarationName Name,
3547                                      SourceLocation Loc) {
3548  DeclContext *Cur = CurContext;
3549  while (isa<LinkageSpecDecl>(Cur))
3550    Cur = Cur->getParent();
3551
3552  // C++ [dcl.meaning]p1:
3553  //   A declarator-id shall not be qualified except for the definition
3554  //   of a member function (9.3) or static data member (9.4) outside of
3555  //   its class, the definition or explicit instantiation of a function
3556  //   or variable member of a namespace outside of its namespace, or the
3557  //   definition of an explicit specialization outside of its namespace,
3558  //   or the declaration of a friend function that is a member of
3559  //   another class or namespace (11.3). [...]
3560
3561  // The user provided a superfluous scope specifier that refers back to the
3562  // class or namespaces in which the entity is already declared.
3563  //
3564  // class X {
3565  //   void X::f();
3566  // };
3567  if (Cur->Equals(DC)) {
3568    Diag(Loc, LangOpts.MicrosoftExt? diag::warn_member_extra_qualification
3569                                   : diag::err_member_extra_qualification)
3570      << Name << FixItHint::CreateRemoval(SS.getRange());
3571    SS.clear();
3572    return false;
3573  }
3574
3575  // Check whether the qualifying scope encloses the scope of the original
3576  // declaration.
3577  if (!Cur->Encloses(DC)) {
3578    if (Cur->isRecord())
3579      Diag(Loc, diag::err_member_qualification)
3580        << Name << SS.getRange();
3581    else if (isa<TranslationUnitDecl>(DC))
3582      Diag(Loc, diag::err_invalid_declarator_global_scope)
3583        << Name << SS.getRange();
3584    else if (isa<FunctionDecl>(Cur))
3585      Diag(Loc, diag::err_invalid_declarator_in_function)
3586        << Name << SS.getRange();
3587    else
3588      Diag(Loc, diag::err_invalid_declarator_scope)
3589      << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
3590
3591    return true;
3592  }
3593
3594  if (Cur->isRecord()) {
3595    // Cannot qualify members within a class.
3596    Diag(Loc, diag::err_member_qualification)
3597      << Name << SS.getRange();
3598    SS.clear();
3599
3600    // C++ constructors and destructors with incorrect scopes can break
3601    // our AST invariants by having the wrong underlying types. If
3602    // that's the case, then drop this declaration entirely.
3603    if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
3604         Name.getNameKind() == DeclarationName::CXXDestructorName) &&
3605        !Context.hasSameType(Name.getCXXNameType(),
3606                             Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
3607      return true;
3608
3609    return false;
3610  }
3611
3612  // C++11 [dcl.meaning]p1:
3613  //   [...] "The nested-name-specifier of the qualified declarator-id shall
3614  //   not begin with a decltype-specifer"
3615  NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
3616  while (SpecLoc.getPrefix())
3617    SpecLoc = SpecLoc.getPrefix();
3618  if (dyn_cast_or_null<DecltypeType>(
3619        SpecLoc.getNestedNameSpecifier()->getAsType()))
3620    Diag(Loc, diag::err_decltype_in_declarator)
3621      << SpecLoc.getTypeLoc().getSourceRange();
3622
3623  return false;
3624}
3625
3626Decl *Sema::HandleDeclarator(Scope *S, Declarator &D,
3627                             MultiTemplateParamsArg TemplateParamLists) {
3628  // TODO: consider using NameInfo for diagnostic.
3629  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3630  DeclarationName Name = NameInfo.getName();
3631
3632  // All of these full declarators require an identifier.  If it doesn't have
3633  // one, the ParsedFreeStandingDeclSpec action should be used.
3634  if (!Name) {
3635    if (!D.isInvalidType())  // Reject this if we think it is valid.
3636      Diag(D.getDeclSpec().getLocStart(),
3637           diag::err_declarator_need_ident)
3638        << D.getDeclSpec().getSourceRange() << D.getSourceRange();
3639    return 0;
3640  } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
3641    return 0;
3642
3643  // The scope passed in may not be a decl scope.  Zip up the scope tree until
3644  // we find one that is.
3645  while ((S->getFlags() & Scope::DeclScope) == 0 ||
3646         (S->getFlags() & Scope::TemplateParamScope) != 0)
3647    S = S->getParent();
3648
3649  DeclContext *DC = CurContext;
3650  if (D.getCXXScopeSpec().isInvalid())
3651    D.setInvalidType();
3652  else if (D.getCXXScopeSpec().isSet()) {
3653    if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
3654                                        UPPC_DeclarationQualifier))
3655      return 0;
3656
3657    bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
3658    DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
3659    if (!DC) {
3660      // If we could not compute the declaration context, it's because the
3661      // declaration context is dependent but does not refer to a class,
3662      // class template, or class template partial specialization. Complain
3663      // and return early, to avoid the coming semantic disaster.
3664      Diag(D.getIdentifierLoc(),
3665           diag::err_template_qualified_declarator_no_match)
3666        << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
3667        << D.getCXXScopeSpec().getRange();
3668      return 0;
3669    }
3670    bool IsDependentContext = DC->isDependentContext();
3671
3672    if (!IsDependentContext &&
3673        RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
3674      return 0;
3675
3676    if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
3677      Diag(D.getIdentifierLoc(),
3678           diag::err_member_def_undefined_record)
3679        << Name << DC << D.getCXXScopeSpec().getRange();
3680      D.setInvalidType();
3681    } else if (!D.getDeclSpec().isFriendSpecified()) {
3682      if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
3683                                      Name, D.getIdentifierLoc())) {
3684        if (DC->isRecord())
3685          return 0;
3686
3687        D.setInvalidType();
3688      }
3689    }
3690
3691    // Check whether we need to rebuild the type of the given
3692    // declaration in the current instantiation.
3693    if (EnteringContext && IsDependentContext &&
3694        TemplateParamLists.size() != 0) {
3695      ContextRAII SavedContext(*this, DC);
3696      if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
3697        D.setInvalidType();
3698    }
3699  }
3700
3701  if (DiagnoseClassNameShadow(DC, NameInfo))
3702    // If this is a typedef, we'll end up spewing multiple diagnostics.
3703    // Just return early; it's safer.
3704    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3705      return 0;
3706
3707  NamedDecl *New;
3708
3709  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3710  QualType R = TInfo->getType();
3711
3712  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
3713                                      UPPC_DeclarationType))
3714    D.setInvalidType();
3715
3716  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
3717                        ForRedeclaration);
3718
3719  // See if this is a redefinition of a variable in the same scope.
3720  if (!D.getCXXScopeSpec().isSet()) {
3721    bool IsLinkageLookup = false;
3722
3723    // If the declaration we're planning to build will be a function
3724    // or object with linkage, then look for another declaration with
3725    // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
3726    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3727      /* Do nothing*/;
3728    else if (R->isFunctionType()) {
3729      if (CurContext->isFunctionOrMethod() ||
3730          D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
3731        IsLinkageLookup = true;
3732    } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
3733      IsLinkageLookup = true;
3734    else if (CurContext->getRedeclContext()->isTranslationUnit() &&
3735             D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
3736      IsLinkageLookup = true;
3737
3738    if (IsLinkageLookup)
3739      Previous.clear(LookupRedeclarationWithLinkage);
3740
3741    LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
3742  } else { // Something like "int foo::x;"
3743    LookupQualifiedName(Previous, DC);
3744
3745    // C++ [dcl.meaning]p1:
3746    //   When the declarator-id is qualified, the declaration shall refer to a
3747    //  previously declared member of the class or namespace to which the
3748    //  qualifier refers (or, in the case of a namespace, of an element of the
3749    //  inline namespace set of that namespace (7.3.1)) or to a specialization
3750    //  thereof; [...]
3751    //
3752    // Note that we already checked the context above, and that we do not have
3753    // enough information to make sure that Previous contains the declaration
3754    // we want to match. For example, given:
3755    //
3756    //   class X {
3757    //     void f();
3758    //     void f(float);
3759    //   };
3760    //
3761    //   void X::f(int) { } // ill-formed
3762    //
3763    // In this case, Previous will point to the overload set
3764    // containing the two f's declared in X, but neither of them
3765    // matches.
3766
3767    // C++ [dcl.meaning]p1:
3768    //   [...] the member shall not merely have been introduced by a
3769    //   using-declaration in the scope of the class or namespace nominated by
3770    //   the nested-name-specifier of the declarator-id.
3771    RemoveUsingDecls(Previous);
3772  }
3773
3774  if (Previous.isSingleResult() &&
3775      Previous.getFoundDecl()->isTemplateParameter()) {
3776    // Maybe we will complain about the shadowed template parameter.
3777    if (!D.isInvalidType())
3778      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
3779                                      Previous.getFoundDecl());
3780
3781    // Just pretend that we didn't see the previous declaration.
3782    Previous.clear();
3783  }
3784
3785  // In C++, the previous declaration we find might be a tag type
3786  // (class or enum). In this case, the new declaration will hide the
3787  // tag type. Note that this does does not apply if we're declaring a
3788  // typedef (C++ [dcl.typedef]p4).
3789  if (Previous.isSingleTagDecl() &&
3790      D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
3791    Previous.clear();
3792
3793  bool AddToScope = true;
3794  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
3795    if (TemplateParamLists.size()) {
3796      Diag(D.getIdentifierLoc(), diag::err_template_typedef);
3797      return 0;
3798    }
3799
3800    New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
3801  } else if (R->isFunctionType()) {
3802    New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
3803                                  TemplateParamLists,
3804                                  AddToScope);
3805  } else {
3806    New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
3807                                  TemplateParamLists);
3808  }
3809
3810  if (New == 0)
3811    return 0;
3812
3813  // If this has an identifier and is not an invalid redeclaration or
3814  // function template specialization, add it to the scope stack.
3815  if (New->getDeclName() && AddToScope &&
3816       !(D.isRedeclaration() && New->isInvalidDecl()))
3817    PushOnScopeChains(New, S);
3818
3819  return New;
3820}
3821
3822/// Helper method to turn variable array types into constant array
3823/// types in certain situations which would otherwise be errors (for
3824/// GCC compatibility).
3825static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3826                                                    ASTContext &Context,
3827                                                    bool &SizeIsNegative,
3828                                                    llvm::APSInt &Oversized) {
3829  // This method tries to turn a variable array into a constant
3830  // array even when the size isn't an ICE.  This is necessary
3831  // for compatibility with code that depends on gcc's buggy
3832  // constant expression folding, like struct {char x[(int)(char*)2];}
3833  SizeIsNegative = false;
3834  Oversized = 0;
3835
3836  if (T->isDependentType())
3837    return QualType();
3838
3839  QualifierCollector Qs;
3840  const Type *Ty = Qs.strip(T);
3841
3842  if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
3843    QualType Pointee = PTy->getPointeeType();
3844    QualType FixedType =
3845        TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
3846                                            Oversized);
3847    if (FixedType.isNull()) return FixedType;
3848    FixedType = Context.getPointerType(FixedType);
3849    return Qs.apply(Context, FixedType);
3850  }
3851  if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
3852    QualType Inner = PTy->getInnerType();
3853    QualType FixedType =
3854        TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
3855                                            Oversized);
3856    if (FixedType.isNull()) return FixedType;
3857    FixedType = Context.getParenType(FixedType);
3858    return Qs.apply(Context, FixedType);
3859  }
3860
3861  const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3862  if (!VLATy)
3863    return QualType();
3864  // FIXME: We should probably handle this case
3865  if (VLATy->getElementType()->isVariablyModifiedType())
3866    return QualType();
3867
3868  llvm::APSInt Res;
3869  if (!VLATy->getSizeExpr() ||
3870      !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
3871    return QualType();
3872
3873  // Check whether the array size is negative.
3874  if (Res.isSigned() && Res.isNegative()) {
3875    SizeIsNegative = true;
3876    return QualType();
3877  }
3878
3879  // Check whether the array is too large to be addressed.
3880  unsigned ActiveSizeBits
3881    = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
3882                                              Res);
3883  if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
3884    Oversized = Res;
3885    return QualType();
3886  }
3887
3888  return Context.getConstantArrayType(VLATy->getElementType(),
3889                                      Res, ArrayType::Normal, 0);
3890}
3891
3892static void
3893FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
3894  if (PointerTypeLoc* SrcPTL = dyn_cast<PointerTypeLoc>(&SrcTL)) {
3895    PointerTypeLoc* DstPTL = cast<PointerTypeLoc>(&DstTL);
3896    FixInvalidVariablyModifiedTypeLoc(SrcPTL->getPointeeLoc(),
3897                                      DstPTL->getPointeeLoc());
3898    DstPTL->setStarLoc(SrcPTL->getStarLoc());
3899    return;
3900  }
3901  if (ParenTypeLoc* SrcPTL = dyn_cast<ParenTypeLoc>(&SrcTL)) {
3902    ParenTypeLoc* DstPTL = cast<ParenTypeLoc>(&DstTL);
3903    FixInvalidVariablyModifiedTypeLoc(SrcPTL->getInnerLoc(),
3904                                      DstPTL->getInnerLoc());
3905    DstPTL->setLParenLoc(SrcPTL->getLParenLoc());
3906    DstPTL->setRParenLoc(SrcPTL->getRParenLoc());
3907    return;
3908  }
3909  ArrayTypeLoc* SrcATL = cast<ArrayTypeLoc>(&SrcTL);
3910  ArrayTypeLoc* DstATL = cast<ArrayTypeLoc>(&DstTL);
3911  TypeLoc SrcElemTL = SrcATL->getElementLoc();
3912  TypeLoc DstElemTL = DstATL->getElementLoc();
3913  DstElemTL.initializeFullCopy(SrcElemTL);
3914  DstATL->setLBracketLoc(SrcATL->getLBracketLoc());
3915  DstATL->setSizeExpr(SrcATL->getSizeExpr());
3916  DstATL->setRBracketLoc(SrcATL->getRBracketLoc());
3917}
3918
3919/// Helper method to turn variable array types into constant array
3920/// types in certain situations which would otherwise be errors (for
3921/// GCC compatibility).
3922static TypeSourceInfo*
3923TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
3924                                              ASTContext &Context,
3925                                              bool &SizeIsNegative,
3926                                              llvm::APSInt &Oversized) {
3927  QualType FixedTy
3928    = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
3929                                          SizeIsNegative, Oversized);
3930  if (FixedTy.isNull())
3931    return 0;
3932  TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
3933  FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
3934                                    FixedTInfo->getTypeLoc());
3935  return FixedTInfo;
3936}
3937
3938/// \brief Register the given locally-scoped external C declaration so
3939/// that it can be found later for redeclarations
3940void
3941Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
3942                                       const LookupResult &Previous,
3943                                       Scope *S) {
3944  assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
3945         "Decl is not a locally-scoped decl!");
3946  // Note that we have a locally-scoped external with this name.
3947  LocallyScopedExternalDecls[ND->getDeclName()] = ND;
3948
3949  if (!Previous.isSingleResult())
3950    return;
3951
3952  NamedDecl *PrevDecl = Previous.getFoundDecl();
3953
3954  // If there was a previous declaration of this variable, it may be
3955  // in our identifier chain. Update the identifier chain with the new
3956  // declaration.
3957  if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
3958    // The previous declaration was found on the identifer resolver
3959    // chain, so remove it from its scope.
3960
3961    if (S->isDeclScope(PrevDecl)) {
3962      // Special case for redeclarations in the SAME scope.
3963      // Because this declaration is going to be added to the identifier chain
3964      // later, we should temporarily take it OFF the chain.
3965      IdResolver.RemoveDecl(ND);
3966
3967    } else {
3968      // Find the scope for the original declaration.
3969      while (S && !S->isDeclScope(PrevDecl))
3970        S = S->getParent();
3971    }
3972
3973    if (S)
3974      S->RemoveDecl(PrevDecl);
3975  }
3976}
3977
3978llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
3979Sema::findLocallyScopedExternalDecl(DeclarationName Name) {
3980  if (ExternalSource) {
3981    // Load locally-scoped external decls from the external source.
3982    SmallVector<NamedDecl *, 4> Decls;
3983    ExternalSource->ReadLocallyScopedExternalDecls(Decls);
3984    for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
3985      llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
3986        = LocallyScopedExternalDecls.find(Decls[I]->getDeclName());
3987      if (Pos == LocallyScopedExternalDecls.end())
3988        LocallyScopedExternalDecls[Decls[I]->getDeclName()] = Decls[I];
3989    }
3990  }
3991
3992  return LocallyScopedExternalDecls.find(Name);
3993}
3994
3995/// \brief Diagnose function specifiers on a declaration of an identifier that
3996/// does not identify a function.
3997void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
3998  // FIXME: We should probably indicate the identifier in question to avoid
3999  // confusion for constructs like "inline int a(), b;"
4000  if (D.getDeclSpec().isInlineSpecified())
4001    Diag(D.getDeclSpec().getInlineSpecLoc(),
4002         diag::err_inline_non_function);
4003
4004  if (D.getDeclSpec().isVirtualSpecified())
4005    Diag(D.getDeclSpec().getVirtualSpecLoc(),
4006         diag::err_virtual_non_function);
4007
4008  if (D.getDeclSpec().isExplicitSpecified())
4009    Diag(D.getDeclSpec().getExplicitSpecLoc(),
4010         diag::err_explicit_non_function);
4011}
4012
4013NamedDecl*
4014Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
4015                             TypeSourceInfo *TInfo, LookupResult &Previous) {
4016  // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4017  if (D.getCXXScopeSpec().isSet()) {
4018    Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4019      << D.getCXXScopeSpec().getRange();
4020    D.setInvalidType();
4021    // Pretend we didn't see the scope specifier.
4022    DC = CurContext;
4023    Previous.clear();
4024  }
4025
4026  if (getLangOpts().CPlusPlus) {
4027    // Check that there are no default arguments (C++ only).
4028    CheckExtraCXXDefaultArguments(D);
4029  }
4030
4031  DiagnoseFunctionSpecifiers(D);
4032
4033  if (D.getDeclSpec().isThreadSpecified())
4034    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4035  if (D.getDeclSpec().isConstexprSpecified())
4036    Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4037      << 1;
4038
4039  if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4040    Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4041      << D.getName().getSourceRange();
4042    return 0;
4043  }
4044
4045  TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
4046  if (!NewTD) return 0;
4047
4048  // Handle attributes prior to checking for duplicates in MergeVarDecl
4049  ProcessDeclAttributes(S, NewTD, D);
4050
4051  CheckTypedefForVariablyModifiedType(S, NewTD);
4052
4053  bool Redeclaration = D.isRedeclaration();
4054  NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4055  D.setRedeclaration(Redeclaration);
4056  return ND;
4057}
4058
4059void
4060Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
4061  // C99 6.7.7p2: If a typedef name specifies a variably modified type
4062  // then it shall have block scope.
4063  // Note that variably modified types must be fixed before merging the decl so
4064  // that redeclarations will match.
4065  TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4066  QualType T = TInfo->getType();
4067  if (T->isVariablyModifiedType()) {
4068    getCurFunction()->setHasBranchProtectedScope();
4069
4070    if (S->getFnParent() == 0) {
4071      bool SizeIsNegative;
4072      llvm::APSInt Oversized;
4073      TypeSourceInfo *FixedTInfo =
4074        TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4075                                                      SizeIsNegative,
4076                                                      Oversized);
4077      if (FixedTInfo) {
4078        Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
4079        NewTD->setTypeSourceInfo(FixedTInfo);
4080      } else {
4081        if (SizeIsNegative)
4082          Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
4083        else if (T->isVariableArrayType())
4084          Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
4085        else if (Oversized.getBoolValue())
4086          Diag(NewTD->getLocation(), diag::err_array_too_large)
4087            << Oversized.toString(10);
4088        else
4089          Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
4090        NewTD->setInvalidDecl();
4091      }
4092    }
4093  }
4094}
4095
4096
4097/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4098/// declares a typedef-name, either using the 'typedef' type specifier or via
4099/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4100NamedDecl*
4101Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4102                           LookupResult &Previous, bool &Redeclaration) {
4103  // Merge the decl with the existing one if appropriate. If the decl is
4104  // in an outer scope, it isn't the same thing.
4105  FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
4106                       /*ExplicitInstantiationOrSpecialization=*/false);
4107  if (!Previous.empty()) {
4108    Redeclaration = true;
4109    MergeTypedefNameDecl(NewTD, Previous);
4110  }
4111
4112  // If this is the C FILE type, notify the AST context.
4113  if (IdentifierInfo *II = NewTD->getIdentifier())
4114    if (!NewTD->isInvalidDecl() &&
4115        NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
4116      if (II->isStr("FILE"))
4117        Context.setFILEDecl(NewTD);
4118      else if (II->isStr("jmp_buf"))
4119        Context.setjmp_bufDecl(NewTD);
4120      else if (II->isStr("sigjmp_buf"))
4121        Context.setsigjmp_bufDecl(NewTD);
4122      else if (II->isStr("ucontext_t"))
4123        Context.setucontext_tDecl(NewTD);
4124    }
4125
4126  return NewTD;
4127}
4128
4129/// \brief Determines whether the given declaration is an out-of-scope
4130/// previous declaration.
4131///
4132/// This routine should be invoked when name lookup has found a
4133/// previous declaration (PrevDecl) that is not in the scope where a
4134/// new declaration by the same name is being introduced. If the new
4135/// declaration occurs in a local scope, previous declarations with
4136/// linkage may still be considered previous declarations (C99
4137/// 6.2.2p4-5, C++ [basic.link]p6).
4138///
4139/// \param PrevDecl the previous declaration found by name
4140/// lookup
4141///
4142/// \param DC the context in which the new declaration is being
4143/// declared.
4144///
4145/// \returns true if PrevDecl is an out-of-scope previous declaration
4146/// for a new delcaration with the same name.
4147static bool
4148isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4149                                ASTContext &Context) {
4150  if (!PrevDecl)
4151    return false;
4152
4153  if (!PrevDecl->hasLinkage())
4154    return false;
4155
4156  if (Context.getLangOpts().CPlusPlus) {
4157    // C++ [basic.link]p6:
4158    //   If there is a visible declaration of an entity with linkage
4159    //   having the same name and type, ignoring entities declared
4160    //   outside the innermost enclosing namespace scope, the block
4161    //   scope declaration declares that same entity and receives the
4162    //   linkage of the previous declaration.
4163    DeclContext *OuterContext = DC->getRedeclContext();
4164    if (!OuterContext->isFunctionOrMethod())
4165      // This rule only applies to block-scope declarations.
4166      return false;
4167
4168    DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4169    if (PrevOuterContext->isRecord())
4170      // We found a member function: ignore it.
4171      return false;
4172
4173    // Find the innermost enclosing namespace for the new and
4174    // previous declarations.
4175    OuterContext = OuterContext->getEnclosingNamespaceContext();
4176    PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
4177
4178    // The previous declaration is in a different namespace, so it
4179    // isn't the same function.
4180    if (!OuterContext->Equals(PrevOuterContext))
4181      return false;
4182  }
4183
4184  return true;
4185}
4186
4187static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4188  CXXScopeSpec &SS = D.getCXXScopeSpec();
4189  if (!SS.isSet()) return;
4190  DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
4191}
4192
4193bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4194  QualType type = decl->getType();
4195  Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4196  if (lifetime == Qualifiers::OCL_Autoreleasing) {
4197    // Various kinds of declaration aren't allowed to be __autoreleasing.
4198    unsigned kind = -1U;
4199    if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4200      if (var->hasAttr<BlocksAttr>())
4201        kind = 0; // __block
4202      else if (!var->hasLocalStorage())
4203        kind = 1; // global
4204    } else if (isa<ObjCIvarDecl>(decl)) {
4205      kind = 3; // ivar
4206    } else if (isa<FieldDecl>(decl)) {
4207      kind = 2; // field
4208    }
4209
4210    if (kind != -1U) {
4211      Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4212        << kind;
4213    }
4214  } else if (lifetime == Qualifiers::OCL_None) {
4215    // Try to infer lifetime.
4216    if (!type->isObjCLifetimeType())
4217      return false;
4218
4219    lifetime = type->getObjCARCImplicitLifetime();
4220    type = Context.getLifetimeQualifiedType(type, lifetime);
4221    decl->setType(type);
4222  }
4223
4224  if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4225    // Thread-local variables cannot have lifetime.
4226    if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
4227        var->isThreadSpecified()) {
4228      Diag(var->getLocation(), diag::err_arc_thread_ownership)
4229        << var->getType();
4230      return true;
4231    }
4232  }
4233
4234  return false;
4235}
4236
4237NamedDecl*
4238Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4239                              TypeSourceInfo *TInfo, LookupResult &Previous,
4240                              MultiTemplateParamsArg TemplateParamLists) {
4241  QualType R = TInfo->getType();
4242  DeclarationName Name = GetNameForDeclarator(D).getName();
4243
4244  // Check that there are no default arguments (C++ only).
4245  if (getLangOpts().CPlusPlus)
4246    CheckExtraCXXDefaultArguments(D);
4247
4248  DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
4249  assert(SCSpec != DeclSpec::SCS_typedef &&
4250         "Parser allowed 'typedef' as storage class VarDecl.");
4251  VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
4252  if (SCSpec == DeclSpec::SCS_mutable) {
4253    // mutable can only appear on non-static class members, so it's always
4254    // an error here
4255    Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
4256    D.setInvalidType();
4257    SC = SC_None;
4258  }
4259  SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
4260  VarDecl::StorageClass SCAsWritten
4261    = StorageClassSpecToVarDeclStorageClass(SCSpec);
4262
4263  IdentifierInfo *II = Name.getAsIdentifierInfo();
4264  if (!II) {
4265    Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
4266      << Name;
4267    return 0;
4268  }
4269
4270  DiagnoseFunctionSpecifiers(D);
4271
4272  if (!DC->isRecord() && S->getFnParent() == 0) {
4273    // C99 6.9p2: The storage-class specifiers auto and register shall not
4274    // appear in the declaration specifiers in an external declaration.
4275    if (SC == SC_Auto || SC == SC_Register) {
4276
4277      // If this is a register variable with an asm label specified, then this
4278      // is a GNU extension.
4279      if (SC == SC_Register && D.getAsmLabel())
4280        Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
4281      else
4282        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
4283      D.setInvalidType();
4284    }
4285  }
4286
4287  if (getLangOpts().OpenCL) {
4288    // Set up the special work-group-local storage class for variables in the
4289    // OpenCL __local address space.
4290    if (R.getAddressSpace() == LangAS::opencl_local)
4291      SC = SC_OpenCLWorkGroupLocal;
4292  }
4293
4294  bool isExplicitSpecialization = false;
4295  VarDecl *NewVD;
4296  if (!getLangOpts().CPlusPlus) {
4297    NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
4298                            D.getIdentifierLoc(), II,
4299                            R, TInfo, SC, SCAsWritten);
4300
4301    if (D.isInvalidType())
4302      NewVD->setInvalidDecl();
4303  } else {
4304    if (DC->isRecord() && !CurContext->isRecord()) {
4305      // This is an out-of-line definition of a static data member.
4306      if (SC == SC_Static) {
4307        Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4308             diag::err_static_out_of_line)
4309          << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4310      } else if (SC == SC_None)
4311        SC = SC_Static;
4312    }
4313    if (SC == SC_Static && CurContext->isRecord()) {
4314      if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
4315        if (RD->isLocalClass())
4316          Diag(D.getIdentifierLoc(),
4317               diag::err_static_data_member_not_allowed_in_local_class)
4318            << Name << RD->getDeclName();
4319
4320        // C++98 [class.union]p1: If a union contains a static data member,
4321        // the program is ill-formed. C++11 drops this restriction.
4322        if (RD->isUnion())
4323          Diag(D.getIdentifierLoc(),
4324               getLangOpts().CPlusPlus0x
4325                 ? diag::warn_cxx98_compat_static_data_member_in_union
4326                 : diag::ext_static_data_member_in_union) << Name;
4327        // We conservatively disallow static data members in anonymous structs.
4328        else if (!RD->getDeclName())
4329          Diag(D.getIdentifierLoc(),
4330               diag::err_static_data_member_not_allowed_in_anon_struct)
4331            << Name << RD->isUnion();
4332      }
4333    }
4334
4335    // Match up the template parameter lists with the scope specifier, then
4336    // determine whether we have a template or a template specialization.
4337    isExplicitSpecialization = false;
4338    bool Invalid = false;
4339    if (TemplateParameterList *TemplateParams
4340        = MatchTemplateParametersToScopeSpecifier(
4341                                  D.getDeclSpec().getLocStart(),
4342                                                  D.getIdentifierLoc(),
4343                                                  D.getCXXScopeSpec(),
4344                                                  TemplateParamLists.data(),
4345                                                  TemplateParamLists.size(),
4346                                                  /*never a friend*/ false,
4347                                                  isExplicitSpecialization,
4348                                                  Invalid)) {
4349      if (TemplateParams->size() > 0) {
4350        // There is no such thing as a variable template.
4351        Diag(D.getIdentifierLoc(), diag::err_template_variable)
4352          << II
4353          << SourceRange(TemplateParams->getTemplateLoc(),
4354                         TemplateParams->getRAngleLoc());
4355        return 0;
4356      } else {
4357        // There is an extraneous 'template<>' for this variable. Complain
4358        // about it, but allow the declaration of the variable.
4359        Diag(TemplateParams->getTemplateLoc(),
4360             diag::err_template_variable_noparams)
4361          << II
4362          << SourceRange(TemplateParams->getTemplateLoc(),
4363                         TemplateParams->getRAngleLoc());
4364      }
4365    }
4366
4367    NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
4368                            D.getIdentifierLoc(), II,
4369                            R, TInfo, SC, SCAsWritten);
4370
4371    // If this decl has an auto type in need of deduction, make a note of the
4372    // Decl so we can diagnose uses of it in its own initializer.
4373    if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
4374        R->getContainedAutoType())
4375      ParsingInitForAutoVars.insert(NewVD);
4376
4377    if (D.isInvalidType() || Invalid)
4378      NewVD->setInvalidDecl();
4379
4380    SetNestedNameSpecifier(NewVD, D);
4381
4382    if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) {
4383      NewVD->setTemplateParameterListsInfo(Context,
4384                                           TemplateParamLists.size(),
4385                                           TemplateParamLists.data());
4386    }
4387
4388    if (D.getDeclSpec().isConstexprSpecified())
4389      NewVD->setConstexpr(true);
4390  }
4391
4392  // Set the lexical context. If the declarator has a C++ scope specifier, the
4393  // lexical context will be different from the semantic context.
4394  NewVD->setLexicalDeclContext(CurContext);
4395
4396  if (D.getDeclSpec().isThreadSpecified()) {
4397    if (NewVD->hasLocalStorage())
4398      Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
4399    else if (!Context.getTargetInfo().isTLSSupported())
4400      Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
4401    else
4402      NewVD->setThreadSpecified(true);
4403  }
4404
4405  if (D.getDeclSpec().isModulePrivateSpecified()) {
4406    if (isExplicitSpecialization)
4407      Diag(NewVD->getLocation(), diag::err_module_private_specialization)
4408        << 2
4409        << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
4410    else if (NewVD->hasLocalStorage())
4411      Diag(NewVD->getLocation(), diag::err_module_private_local)
4412        << 0 << NewVD->getDeclName()
4413        << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
4414        << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
4415    else
4416      NewVD->setModulePrivate();
4417  }
4418
4419  // Handle attributes prior to checking for duplicates in MergeVarDecl
4420  ProcessDeclAttributes(S, NewVD, D);
4421
4422  if (getLangOpts().CUDA) {
4423    // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
4424    // storage [duration]."
4425    if (SC == SC_None && S->getFnParent() != 0 &&
4426       (NewVD->hasAttr<CUDASharedAttr>() || NewVD->hasAttr<CUDAConstantAttr>()))
4427      NewVD->setStorageClass(SC_Static);
4428  }
4429
4430  // In auto-retain/release, infer strong retension for variables of
4431  // retainable type.
4432  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
4433    NewVD->setInvalidDecl();
4434
4435  // Handle GNU asm-label extension (encoded as an attribute).
4436  if (Expr *E = (Expr*)D.getAsmLabel()) {
4437    // The parser guarantees this is a string.
4438    StringLiteral *SE = cast<StringLiteral>(E);
4439    StringRef Label = SE->getString();
4440    if (S->getFnParent() != 0) {
4441      switch (SC) {
4442      case SC_None:
4443      case SC_Auto:
4444        Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
4445        break;
4446      case SC_Register:
4447        if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
4448          Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
4449        break;
4450      case SC_Static:
4451      case SC_Extern:
4452      case SC_PrivateExtern:
4453      case SC_OpenCLWorkGroupLocal:
4454        break;
4455      }
4456    }
4457
4458    NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
4459                                                Context, Label));
4460  } else if (!ExtnameUndeclaredIdentifiers.empty()) {
4461    llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
4462      ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
4463    if (I != ExtnameUndeclaredIdentifiers.end()) {
4464      NewVD->addAttr(I->second);
4465      ExtnameUndeclaredIdentifiers.erase(I);
4466    }
4467  }
4468
4469  // Diagnose shadowed variables before filtering for scope.
4470  if (!D.getCXXScopeSpec().isSet())
4471    CheckShadow(S, NewVD, Previous);
4472
4473  // Don't consider existing declarations that are in a different
4474  // scope and are out-of-semantic-context declarations (if the new
4475  // declaration has linkage).
4476  FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(),
4477                       isExplicitSpecialization);
4478
4479  if (!getLangOpts().CPlusPlus) {
4480    D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
4481  } else {
4482    // Merge the decl with the existing one if appropriate.
4483    if (!Previous.empty()) {
4484      if (Previous.isSingleResult() &&
4485          isa<FieldDecl>(Previous.getFoundDecl()) &&
4486          D.getCXXScopeSpec().isSet()) {
4487        // The user tried to define a non-static data member
4488        // out-of-line (C++ [dcl.meaning]p1).
4489        Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
4490          << D.getCXXScopeSpec().getRange();
4491        Previous.clear();
4492        NewVD->setInvalidDecl();
4493      }
4494    } else if (D.getCXXScopeSpec().isSet()) {
4495      // No previous declaration in the qualifying scope.
4496      Diag(D.getIdentifierLoc(), diag::err_no_member)
4497        << Name << computeDeclContext(D.getCXXScopeSpec(), true)
4498        << D.getCXXScopeSpec().getRange();
4499      NewVD->setInvalidDecl();
4500    }
4501
4502    D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
4503
4504    // This is an explicit specialization of a static data member. Check it.
4505    if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
4506        CheckMemberSpecialization(NewVD, Previous))
4507      NewVD->setInvalidDecl();
4508  }
4509
4510  // If this is a locally-scoped extern C variable, update the map of
4511  // such variables.
4512  if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
4513      !NewVD->isInvalidDecl())
4514    RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
4515
4516  // If there's a #pragma GCC visibility in scope, and this isn't a class
4517  // member, set the visibility of this variable.
4518  if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord())
4519    AddPushedVisibilityAttribute(NewVD);
4520
4521  MarkUnusedFileScopedDecl(NewVD);
4522
4523  return NewVD;
4524}
4525
4526/// \brief Diagnose variable or built-in function shadowing.  Implements
4527/// -Wshadow.
4528///
4529/// This method is called whenever a VarDecl is added to a "useful"
4530/// scope.
4531///
4532/// \param S the scope in which the shadowing name is being declared
4533/// \param R the lookup of the name
4534///
4535void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
4536  // Return if warning is ignored.
4537  if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
4538        DiagnosticsEngine::Ignored)
4539    return;
4540
4541  // Don't diagnose declarations at file scope.
4542  if (D->hasGlobalStorage())
4543    return;
4544
4545  DeclContext *NewDC = D->getDeclContext();
4546
4547  // Only diagnose if we're shadowing an unambiguous field or variable.
4548  if (R.getResultKind() != LookupResult::Found)
4549    return;
4550
4551  NamedDecl* ShadowedDecl = R.getFoundDecl();
4552  if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
4553    return;
4554
4555  // Fields are not shadowed by variables in C++ static methods.
4556  if (isa<FieldDecl>(ShadowedDecl))
4557    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
4558      if (MD->isStatic())
4559        return;
4560
4561  if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
4562    if (shadowedVar->isExternC()) {
4563      // For shadowing external vars, make sure that we point to the global
4564      // declaration, not a locally scoped extern declaration.
4565      for (VarDecl::redecl_iterator
4566             I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
4567           I != E; ++I)
4568        if (I->isFileVarDecl()) {
4569          ShadowedDecl = *I;
4570          break;
4571        }
4572    }
4573
4574  DeclContext *OldDC = ShadowedDecl->getDeclContext();
4575
4576  // Only warn about certain kinds of shadowing for class members.
4577  if (NewDC && NewDC->isRecord()) {
4578    // In particular, don't warn about shadowing non-class members.
4579    if (!OldDC->isRecord())
4580      return;
4581
4582    // TODO: should we warn about static data members shadowing
4583    // static data members from base classes?
4584
4585    // TODO: don't diagnose for inaccessible shadowed members.
4586    // This is hard to do perfectly because we might friend the
4587    // shadowing context, but that's just a false negative.
4588  }
4589
4590  // Determine what kind of declaration we're shadowing.
4591  unsigned Kind;
4592  if (isa<RecordDecl>(OldDC)) {
4593    if (isa<FieldDecl>(ShadowedDecl))
4594      Kind = 3; // field
4595    else
4596      Kind = 2; // static data member
4597  } else if (OldDC->isFileContext())
4598    Kind = 1; // global
4599  else
4600    Kind = 0; // local
4601
4602  DeclarationName Name = R.getLookupName();
4603
4604  // Emit warning and note.
4605  Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
4606  Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
4607}
4608
4609/// \brief Check -Wshadow without the advantage of a previous lookup.
4610void Sema::CheckShadow(Scope *S, VarDecl *D) {
4611  if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
4612        DiagnosticsEngine::Ignored)
4613    return;
4614
4615  LookupResult R(*this, D->getDeclName(), D->getLocation(),
4616                 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
4617  LookupName(R, S);
4618  CheckShadow(S, D, R);
4619}
4620
4621/// \brief Perform semantic checking on a newly-created variable
4622/// declaration.
4623///
4624/// This routine performs all of the type-checking required for a
4625/// variable declaration once it has been built. It is used both to
4626/// check variables after they have been parsed and their declarators
4627/// have been translated into a declaration, and to check variables
4628/// that have been instantiated from a template.
4629///
4630/// Sets NewVD->isInvalidDecl() if an error was encountered.
4631///
4632/// Returns true if the variable declaration is a redeclaration.
4633bool Sema::CheckVariableDeclaration(VarDecl *NewVD,
4634                                    LookupResult &Previous) {
4635  // If the decl is already known invalid, don't check it.
4636  if (NewVD->isInvalidDecl())
4637    return false;
4638
4639  TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
4640  QualType T = TInfo->getType();
4641
4642  if (T->isObjCObjectType()) {
4643    Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
4644      << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
4645    T = Context.getObjCObjectPointerType(T);
4646    NewVD->setType(T);
4647  }
4648
4649  // Emit an error if an address space was applied to decl with local storage.
4650  // This includes arrays of objects with address space qualifiers, but not
4651  // automatic variables that point to other address spaces.
4652  // ISO/IEC TR 18037 S5.1.2
4653  if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
4654    Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
4655    NewVD->setInvalidDecl();
4656    return false;
4657  }
4658
4659  // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
4660  // scope.
4661  if ((getLangOpts().OpenCLVersion >= 120)
4662      && NewVD->isStaticLocal()) {
4663    Diag(NewVD->getLocation(), diag::err_static_function_scope);
4664    NewVD->setInvalidDecl();
4665    return false;
4666  }
4667
4668  if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
4669      && !NewVD->hasAttr<BlocksAttr>()) {
4670    if (getLangOpts().getGC() != LangOptions::NonGC)
4671      Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
4672    else {
4673      assert(!getLangOpts().ObjCAutoRefCount);
4674      Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
4675    }
4676  }
4677
4678  bool isVM = T->isVariablyModifiedType();
4679  if (isVM || NewVD->hasAttr<CleanupAttr>() ||
4680      NewVD->hasAttr<BlocksAttr>())
4681    getCurFunction()->setHasBranchProtectedScope();
4682
4683  if ((isVM && NewVD->hasLinkage()) ||
4684      (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
4685    bool SizeIsNegative;
4686    llvm::APSInt Oversized;
4687    TypeSourceInfo *FixedTInfo =
4688      TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4689                                                    SizeIsNegative, Oversized);
4690    if (FixedTInfo == 0 && T->isVariableArrayType()) {
4691      const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
4692      // FIXME: This won't give the correct result for
4693      // int a[10][n];
4694      SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
4695
4696      if (NewVD->isFileVarDecl())
4697        Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
4698        << SizeRange;
4699      else if (NewVD->getStorageClass() == SC_Static)
4700        Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
4701        << SizeRange;
4702      else
4703        Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
4704        << SizeRange;
4705      NewVD->setInvalidDecl();
4706      return false;
4707    }
4708
4709    if (FixedTInfo == 0) {
4710      if (NewVD->isFileVarDecl())
4711        Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
4712      else
4713        Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
4714      NewVD->setInvalidDecl();
4715      return false;
4716    }
4717
4718    Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
4719    NewVD->setType(FixedTInfo->getType());
4720    NewVD->setTypeSourceInfo(FixedTInfo);
4721  }
4722
4723  if (Previous.empty() && NewVD->isExternC()) {
4724    // Since we did not find anything by this name and we're declaring
4725    // an extern "C" variable, look for a non-visible extern "C"
4726    // declaration with the same name.
4727    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4728      = findLocallyScopedExternalDecl(NewVD->getDeclName());
4729    if (Pos != LocallyScopedExternalDecls.end())
4730      Previous.addDecl(Pos->second);
4731  }
4732
4733  if (T->isVoidType() && !NewVD->hasExternalStorage()) {
4734    Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
4735      << T;
4736    NewVD->setInvalidDecl();
4737    return false;
4738  }
4739
4740  if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
4741    Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
4742    NewVD->setInvalidDecl();
4743    return false;
4744  }
4745
4746  if (isVM && NewVD->hasAttr<BlocksAttr>()) {
4747    Diag(NewVD->getLocation(), diag::err_block_on_vm);
4748    NewVD->setInvalidDecl();
4749    return false;
4750  }
4751
4752  if (NewVD->isConstexpr() && !T->isDependentType() &&
4753      RequireLiteralType(NewVD->getLocation(), T,
4754                         diag::err_constexpr_var_non_literal)) {
4755    NewVD->setInvalidDecl();
4756    return false;
4757  }
4758
4759  if (!Previous.empty()) {
4760    MergeVarDecl(NewVD, Previous);
4761    return true;
4762  }
4763  return false;
4764}
4765
4766/// \brief Data used with FindOverriddenMethod
4767struct FindOverriddenMethodData {
4768  Sema *S;
4769  CXXMethodDecl *Method;
4770};
4771
4772/// \brief Member lookup function that determines whether a given C++
4773/// method overrides a method in a base class, to be used with
4774/// CXXRecordDecl::lookupInBases().
4775static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
4776                                 CXXBasePath &Path,
4777                                 void *UserData) {
4778  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4779
4780  FindOverriddenMethodData *Data
4781    = reinterpret_cast<FindOverriddenMethodData*>(UserData);
4782
4783  DeclarationName Name = Data->Method->getDeclName();
4784
4785  // FIXME: Do we care about other names here too?
4786  if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4787    // We really want to find the base class destructor here.
4788    QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
4789    CanQualType CT = Data->S->Context.getCanonicalType(T);
4790
4791    Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
4792  }
4793
4794  for (Path.Decls = BaseRecord->lookup(Name);
4795       Path.Decls.first != Path.Decls.second;
4796       ++Path.Decls.first) {
4797    NamedDecl *D = *Path.Decls.first;
4798    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4799      if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
4800        return true;
4801    }
4802  }
4803
4804  return false;
4805}
4806
4807namespace {
4808  enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
4809}
4810/// \brief Report an error regarding overriding, along with any relevant
4811/// overriden methods.
4812///
4813/// \param DiagID the primary error to report.
4814/// \param MD the overriding method.
4815/// \param OEK which overrides to include as notes.
4816static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
4817                            OverrideErrorKind OEK = OEK_All) {
4818  S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
4819  for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4820                                      E = MD->end_overridden_methods();
4821       I != E; ++I) {
4822    // This check (& the OEK parameter) could be replaced by a predicate, but
4823    // without lambdas that would be overkill. This is still nicer than writing
4824    // out the diag loop 3 times.
4825    if ((OEK == OEK_All) ||
4826        (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
4827        (OEK == OEK_Deleted && (*I)->isDeleted()))
4828      S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
4829  }
4830}
4831
4832/// AddOverriddenMethods - See if a method overrides any in the base classes,
4833/// and if so, check that it's a valid override and remember it.
4834bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4835  // Look for virtual methods in base classes that this method might override.
4836  CXXBasePaths Paths;
4837  FindOverriddenMethodData Data;
4838  Data.Method = MD;
4839  Data.S = this;
4840  bool hasDeletedOverridenMethods = false;
4841  bool hasNonDeletedOverridenMethods = false;
4842  bool AddedAny = false;
4843  if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
4844    for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
4845         E = Paths.found_decls_end(); I != E; ++I) {
4846      if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
4847        MD->addOverriddenMethod(OldMD->getCanonicalDecl());
4848        if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
4849            !CheckOverridingFunctionAttributes(MD, OldMD) &&
4850            !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
4851            !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
4852          hasDeletedOverridenMethods |= OldMD->isDeleted();
4853          hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
4854          AddedAny = true;
4855        }
4856      }
4857    }
4858  }
4859
4860  if (hasDeletedOverridenMethods && !MD->isDeleted()) {
4861    ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
4862  }
4863  if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
4864    ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
4865  }
4866
4867  return AddedAny;
4868}
4869
4870namespace {
4871  // Struct for holding all of the extra arguments needed by
4872  // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
4873  struct ActOnFDArgs {
4874    Scope *S;
4875    Declarator &D;
4876    MultiTemplateParamsArg TemplateParamLists;
4877    bool AddToScope;
4878  };
4879}
4880
4881namespace {
4882
4883// Callback to only accept typo corrections that have a non-zero edit distance.
4884// Also only accept corrections that have the same parent decl.
4885class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
4886 public:
4887  DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
4888                            CXXRecordDecl *Parent)
4889      : Context(Context), OriginalFD(TypoFD),
4890        ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
4891
4892  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
4893    if (candidate.getEditDistance() == 0)
4894      return false;
4895
4896    llvm::SmallVector<unsigned, 1> MismatchedParams;
4897    for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
4898                                          CDeclEnd = candidate.end();
4899         CDecl != CDeclEnd; ++CDecl) {
4900      FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
4901
4902      if (FD && !FD->hasBody() &&
4903          hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
4904        if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
4905          CXXRecordDecl *Parent = MD->getParent();
4906          if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
4907            return true;
4908        } else if (!ExpectedParent) {
4909          return true;
4910        }
4911      }
4912    }
4913
4914    return false;
4915  }
4916
4917 private:
4918  ASTContext &Context;
4919  FunctionDecl *OriginalFD;
4920  CXXRecordDecl *ExpectedParent;
4921};
4922
4923}
4924
4925/// \brief Generate diagnostics for an invalid function redeclaration.
4926///
4927/// This routine handles generating the diagnostic messages for an invalid
4928/// function redeclaration, including finding possible similar declarations
4929/// or performing typo correction if there are no previous declarations with
4930/// the same name.
4931///
4932/// Returns a NamedDecl iff typo correction was performed and substituting in
4933/// the new declaration name does not cause new errors.
4934static NamedDecl* DiagnoseInvalidRedeclaration(
4935    Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
4936    ActOnFDArgs &ExtraArgs) {
4937  NamedDecl *Result = NULL;
4938  DeclarationName Name = NewFD->getDeclName();
4939  DeclContext *NewDC = NewFD->getDeclContext();
4940  LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
4941                    Sema::LookupOrdinaryName, Sema::ForRedeclaration);
4942  llvm::SmallVector<unsigned, 1> MismatchedParams;
4943  llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1> NearMatches;
4944  TypoCorrection Correction;
4945  bool isFriendDecl = (SemaRef.getLangOpts().CPlusPlus &&
4946                       ExtraArgs.D.getDeclSpec().isFriendSpecified());
4947  unsigned DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend
4948                                  : diag::err_member_def_does_not_match;
4949
4950  NewFD->setInvalidDecl();
4951  SemaRef.LookupQualifiedName(Prev, NewDC);
4952  assert(!Prev.isAmbiguous() &&
4953         "Cannot have an ambiguity in previous-declaration lookup");
4954  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
4955  DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
4956                                      MD ? MD->getParent() : 0);
4957  if (!Prev.empty()) {
4958    for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
4959         Func != FuncEnd; ++Func) {
4960      FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
4961      if (FD &&
4962          hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
4963        // Add 1 to the index so that 0 can mean the mismatch didn't
4964        // involve a parameter
4965        unsigned ParamNum =
4966            MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
4967        NearMatches.push_back(std::make_pair(FD, ParamNum));
4968      }
4969    }
4970  // If the qualified name lookup yielded nothing, try typo correction
4971  } else if ((Correction = SemaRef.CorrectTypo(Prev.getLookupNameInfo(),
4972                                         Prev.getLookupKind(), 0, 0,
4973                                         Validator, NewDC))) {
4974    // Trap errors.
4975    Sema::SFINAETrap Trap(SemaRef);
4976
4977    // Set up everything for the call to ActOnFunctionDeclarator
4978    ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
4979                              ExtraArgs.D.getIdentifierLoc());
4980    Previous.clear();
4981    Previous.setLookupName(Correction.getCorrection());
4982    for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
4983                                    CDeclEnd = Correction.end();
4984         CDecl != CDeclEnd; ++CDecl) {
4985      FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
4986      if (FD && !FD->hasBody() &&
4987          hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
4988        Previous.addDecl(FD);
4989      }
4990    }
4991    bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
4992    // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
4993    // pieces need to verify the typo-corrected C++ declaraction and hopefully
4994    // eliminate the need for the parameter pack ExtraArgs.
4995    Result = SemaRef.ActOnFunctionDeclarator(
4996        ExtraArgs.S, ExtraArgs.D,
4997        Correction.getCorrectionDecl()->getDeclContext(),
4998        NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
4999        ExtraArgs.AddToScope);
5000    if (Trap.hasErrorOccurred()) {
5001      // Pretend the typo correction never occurred
5002      ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
5003                                ExtraArgs.D.getIdentifierLoc());
5004      ExtraArgs.D.setRedeclaration(wasRedeclaration);
5005      Previous.clear();
5006      Previous.setLookupName(Name);
5007      Result = NULL;
5008    } else {
5009      for (LookupResult::iterator Func = Previous.begin(),
5010                               FuncEnd = Previous.end();
5011           Func != FuncEnd; ++Func) {
5012        if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
5013          NearMatches.push_back(std::make_pair(FD, 0));
5014      }
5015    }
5016    if (NearMatches.empty()) {
5017      // Ignore the correction if it didn't yield any close FunctionDecl matches
5018      Correction = TypoCorrection();
5019    } else {
5020      DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend_suggest
5021                             : diag::err_member_def_does_not_match_suggest;
5022    }
5023  }
5024
5025  if (Correction) {
5026    // FIXME: use Correction.getCorrectionRange() instead of computing the range
5027    // here. This requires passing in the CXXScopeSpec to CorrectTypo which in
5028    // turn causes the correction to fully qualify the name. If we fix
5029    // CorrectTypo to minimally qualify then this change should be good.
5030    SourceRange FixItLoc(NewFD->getLocation());
5031    CXXScopeSpec &SS = ExtraArgs.D.getCXXScopeSpec();
5032    if (Correction.getCorrectionSpecifier() && SS.isValid())
5033      FixItLoc.setBegin(SS.getBeginLoc());
5034    SemaRef.Diag(NewFD->getLocStart(), DiagMsg)
5035        << Name << NewDC << Correction.getQuoted(SemaRef.getLangOpts())
5036        << FixItHint::CreateReplacement(
5037            FixItLoc, Correction.getAsString(SemaRef.getLangOpts()));
5038  } else {
5039    SemaRef.Diag(NewFD->getLocation(), DiagMsg)
5040        << Name << NewDC << NewFD->getLocation();
5041  }
5042
5043  bool NewFDisConst = false;
5044  if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
5045    NewFDisConst = NewMD->isConst();
5046
5047  for (llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1>::iterator
5048       NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
5049       NearMatch != NearMatchEnd; ++NearMatch) {
5050    FunctionDecl *FD = NearMatch->first;
5051    bool FDisConst = false;
5052    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
5053      FDisConst = MD->isConst();
5054
5055    if (unsigned Idx = NearMatch->second) {
5056      ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
5057      SourceLocation Loc = FDParam->getTypeSpecStartLoc();
5058      if (Loc.isInvalid()) Loc = FD->getLocation();
5059      SemaRef.Diag(Loc, diag::note_member_def_close_param_match)
5060          << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getType();
5061    } else if (Correction) {
5062      SemaRef.Diag(FD->getLocation(), diag::note_previous_decl)
5063          << Correction.getQuoted(SemaRef.getLangOpts());
5064    } else if (FDisConst != NewFDisConst) {
5065      SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
5066          << NewFDisConst << FD->getSourceRange().getEnd();
5067    } else
5068      SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_match);
5069  }
5070  return Result;
5071}
5072
5073static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
5074                                                          Declarator &D) {
5075  switch (D.getDeclSpec().getStorageClassSpec()) {
5076  default: llvm_unreachable("Unknown storage class!");
5077  case DeclSpec::SCS_auto:
5078  case DeclSpec::SCS_register:
5079  case DeclSpec::SCS_mutable:
5080    SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5081                 diag::err_typecheck_sclass_func);
5082    D.setInvalidType();
5083    break;
5084  case DeclSpec::SCS_unspecified: break;
5085  case DeclSpec::SCS_extern: return SC_Extern;
5086  case DeclSpec::SCS_static: {
5087    if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
5088      // C99 6.7.1p5:
5089      //   The declaration of an identifier for a function that has
5090      //   block scope shall have no explicit storage-class specifier
5091      //   other than extern
5092      // See also (C++ [dcl.stc]p4).
5093      SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5094                   diag::err_static_block_func);
5095      break;
5096    } else
5097      return SC_Static;
5098  }
5099  case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5100  }
5101
5102  // No explicit storage class has already been returned
5103  return SC_None;
5104}
5105
5106static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
5107                                           DeclContext *DC, QualType &R,
5108                                           TypeSourceInfo *TInfo,
5109                                           FunctionDecl::StorageClass SC,
5110                                           bool &IsVirtualOkay) {
5111  DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
5112  DeclarationName Name = NameInfo.getName();
5113
5114  FunctionDecl *NewFD = 0;
5115  bool isInline = D.getDeclSpec().isInlineSpecified();
5116  DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
5117  FunctionDecl::StorageClass SCAsWritten
5118    = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
5119
5120  if (!SemaRef.getLangOpts().CPlusPlus) {
5121    // Determine whether the function was written with a
5122    // prototype. This true when:
5123    //   - there is a prototype in the declarator, or
5124    //   - the type R of the function is some kind of typedef or other reference
5125    //     to a type name (which eventually refers to a function type).
5126    bool HasPrototype =
5127      (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
5128      (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
5129
5130    NewFD = FunctionDecl::Create(SemaRef.Context, DC,
5131                                 D.getLocStart(), NameInfo, R,
5132                                 TInfo, SC, SCAsWritten, isInline,
5133                                 HasPrototype);
5134    if (D.isInvalidType())
5135      NewFD->setInvalidDecl();
5136
5137    // Set the lexical context.
5138    NewFD->setLexicalDeclContext(SemaRef.CurContext);
5139
5140    return NewFD;
5141  }
5142
5143  bool isExplicit = D.getDeclSpec().isExplicitSpecified();
5144  bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
5145
5146  // Check that the return type is not an abstract class type.
5147  // For record types, this is done by the AbstractClassUsageDiagnoser once
5148  // the class has been completely parsed.
5149  if (!DC->isRecord() &&
5150      SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
5151                                     R->getAs<FunctionType>()->getResultType(),
5152                                     diag::err_abstract_type_in_decl,
5153                                     SemaRef.AbstractReturnType))
5154    D.setInvalidType();
5155
5156  if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
5157    // This is a C++ constructor declaration.
5158    assert(DC->isRecord() &&
5159           "Constructors can only be declared in a member context");
5160
5161    R = SemaRef.CheckConstructorDeclarator(D, R, SC);
5162    return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
5163                                      D.getLocStart(), NameInfo,
5164                                      R, TInfo, isExplicit, isInline,
5165                                      /*isImplicitlyDeclared=*/false,
5166                                      isConstexpr);
5167
5168  } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
5169    // This is a C++ destructor declaration.
5170    if (DC->isRecord()) {
5171      R = SemaRef.CheckDestructorDeclarator(D, R, SC);
5172      CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
5173      CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
5174                                        SemaRef.Context, Record,
5175                                        D.getLocStart(),
5176                                        NameInfo, R, TInfo, isInline,
5177                                        /*isImplicitlyDeclared=*/false);
5178
5179      // If the class is complete, then we now create the implicit exception
5180      // specification. If the class is incomplete or dependent, we can't do
5181      // it yet.
5182      if (SemaRef.getLangOpts().CPlusPlus0x && !Record->isDependentType() &&
5183          Record->getDefinition() && !Record->isBeingDefined() &&
5184          R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
5185        SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
5186      }
5187
5188      IsVirtualOkay = true;
5189      return NewDD;
5190
5191    } else {
5192      SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
5193      D.setInvalidType();
5194
5195      // Create a FunctionDecl to satisfy the function definition parsing
5196      // code path.
5197      return FunctionDecl::Create(SemaRef.Context, DC,
5198                                  D.getLocStart(),
5199                                  D.getIdentifierLoc(), Name, R, TInfo,
5200                                  SC, SCAsWritten, isInline,
5201                                  /*hasPrototype=*/true, isConstexpr);
5202    }
5203
5204  } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
5205    if (!DC->isRecord()) {
5206      SemaRef.Diag(D.getIdentifierLoc(),
5207           diag::err_conv_function_not_member);
5208      return 0;
5209    }
5210
5211    SemaRef.CheckConversionDeclarator(D, R, SC);
5212    IsVirtualOkay = true;
5213    return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
5214                                     D.getLocStart(), NameInfo,
5215                                     R, TInfo, isInline, isExplicit,
5216                                     isConstexpr, SourceLocation());
5217
5218  } else if (DC->isRecord()) {
5219    // If the name of the function is the same as the name of the record,
5220    // then this must be an invalid constructor that has a return type.
5221    // (The parser checks for a return type and makes the declarator a
5222    // constructor if it has no return type).
5223    if (Name.getAsIdentifierInfo() &&
5224        Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
5225      SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
5226        << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5227        << SourceRange(D.getIdentifierLoc());
5228      return 0;
5229    }
5230
5231    bool isStatic = SC == SC_Static;
5232
5233    // [class.free]p1:
5234    // Any allocation function for a class T is a static member
5235    // (even if not explicitly declared static).
5236    if (Name.getCXXOverloadedOperator() == OO_New ||
5237        Name.getCXXOverloadedOperator() == OO_Array_New)
5238      isStatic = true;
5239
5240    // [class.free]p6 Any deallocation function for a class X is a static member
5241    // (even if not explicitly declared static).
5242    if (Name.getCXXOverloadedOperator() == OO_Delete ||
5243        Name.getCXXOverloadedOperator() == OO_Array_Delete)
5244      isStatic = true;
5245
5246    IsVirtualOkay = !isStatic;
5247
5248    // This is a C++ method declaration.
5249    return CXXMethodDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
5250                                 D.getLocStart(), NameInfo, R,
5251                                 TInfo, isStatic, SCAsWritten, isInline,
5252                                 isConstexpr, SourceLocation());
5253
5254  } else {
5255    // Determine whether the function was written with a
5256    // prototype. This true when:
5257    //   - we're in C++ (where every function has a prototype),
5258    return FunctionDecl::Create(SemaRef.Context, DC,
5259                                D.getLocStart(),
5260                                NameInfo, R, TInfo, SC, SCAsWritten, isInline,
5261                                true/*HasPrototype*/, isConstexpr);
5262  }
5263}
5264
5265void Sema::checkVoidParamDecl(ParmVarDecl *Param) {
5266  // In C++, the empty parameter-type-list must be spelled "void"; a
5267  // typedef of void is not permitted.
5268  if (getLangOpts().CPlusPlus &&
5269      Param->getType().getUnqualifiedType() != Context.VoidTy) {
5270    bool IsTypeAlias = false;
5271    if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
5272      IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
5273    else if (const TemplateSpecializationType *TST =
5274               Param->getType()->getAs<TemplateSpecializationType>())
5275      IsTypeAlias = TST->isTypeAlias();
5276    Diag(Param->getLocation(), diag::err_param_typedef_of_void)
5277      << IsTypeAlias;
5278  }
5279}
5280
5281NamedDecl*
5282Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5283                              TypeSourceInfo *TInfo, LookupResult &Previous,
5284                              MultiTemplateParamsArg TemplateParamLists,
5285                              bool &AddToScope) {
5286  QualType R = TInfo->getType();
5287
5288  assert(R.getTypePtr()->isFunctionType());
5289
5290  // TODO: consider using NameInfo for diagnostic.
5291  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5292  DeclarationName Name = NameInfo.getName();
5293  FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
5294
5295  if (D.getDeclSpec().isThreadSpecified())
5296    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
5297
5298  // Do not allow returning a objc interface by-value.
5299  if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) {
5300    Diag(D.getIdentifierLoc(),
5301         diag::err_object_cannot_be_passed_returned_by_value) << 0
5302    << R->getAs<FunctionType>()->getResultType()
5303    << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
5304
5305    QualType T = R->getAs<FunctionType>()->getResultType();
5306    T = Context.getObjCObjectPointerType(T);
5307    if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(R)) {
5308      FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5309      R = Context.getFunctionType(T, FPT->arg_type_begin(),
5310                                  FPT->getNumArgs(), EPI);
5311    }
5312    else if (isa<FunctionNoProtoType>(R))
5313      R = Context.getFunctionNoProtoType(T);
5314  }
5315
5316  bool isFriend = false;
5317  FunctionTemplateDecl *FunctionTemplate = 0;
5318  bool isExplicitSpecialization = false;
5319  bool isFunctionTemplateSpecialization = false;
5320
5321  bool isDependentClassScopeExplicitSpecialization = false;
5322  bool HasExplicitTemplateArgs = false;
5323  TemplateArgumentListInfo TemplateArgs;
5324
5325  bool isVirtualOkay = false;
5326
5327  FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
5328                                              isVirtualOkay);
5329  if (!NewFD) return 0;
5330
5331  if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
5332    NewFD->setTopLevelDeclInObjCContainer();
5333
5334  if (getLangOpts().CPlusPlus) {
5335    bool isInline = D.getDeclSpec().isInlineSpecified();
5336    bool isVirtual = D.getDeclSpec().isVirtualSpecified();
5337    bool isExplicit = D.getDeclSpec().isExplicitSpecified();
5338    bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
5339    isFriend = D.getDeclSpec().isFriendSpecified();
5340    if (isFriend && !isInline && D.isFunctionDefinition()) {
5341      // C++ [class.friend]p5
5342      //   A function can be defined in a friend declaration of a
5343      //   class . . . . Such a function is implicitly inline.
5344      NewFD->setImplicitlyInline();
5345    }
5346
5347    // If this is a method defined in an __interface, and is not a constructor
5348    // or an overloaded operator, then set the pure flag (isVirtual will already
5349    // return true).
5350    if (const CXXRecordDecl *Parent =
5351          dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
5352      if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
5353        NewFD->setPure(true);
5354    }
5355
5356    SetNestedNameSpecifier(NewFD, D);
5357    isExplicitSpecialization = false;
5358    isFunctionTemplateSpecialization = false;
5359    if (D.isInvalidType())
5360      NewFD->setInvalidDecl();
5361
5362    // Set the lexical context. If the declarator has a C++
5363    // scope specifier, or is the object of a friend declaration, the
5364    // lexical context will be different from the semantic context.
5365    NewFD->setLexicalDeclContext(CurContext);
5366
5367    // Match up the template parameter lists with the scope specifier, then
5368    // determine whether we have a template or a template specialization.
5369    bool Invalid = false;
5370    if (TemplateParameterList *TemplateParams
5371          = MatchTemplateParametersToScopeSpecifier(
5372                                  D.getDeclSpec().getLocStart(),
5373                                  D.getIdentifierLoc(),
5374                                  D.getCXXScopeSpec(),
5375                                  TemplateParamLists.data(),
5376                                  TemplateParamLists.size(),
5377                                  isFriend,
5378                                  isExplicitSpecialization,
5379                                  Invalid)) {
5380      if (TemplateParams->size() > 0) {
5381        // This is a function template
5382
5383        // Check that we can declare a template here.
5384        if (CheckTemplateDeclScope(S, TemplateParams))
5385          return 0;
5386
5387        // A destructor cannot be a template.
5388        if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
5389          Diag(NewFD->getLocation(), diag::err_destructor_template);
5390          return 0;
5391        }
5392
5393        // If we're adding a template to a dependent context, we may need to
5394        // rebuilding some of the types used within the template parameter list,
5395        // now that we know what the current instantiation is.
5396        if (DC->isDependentContext()) {
5397          ContextRAII SavedContext(*this, DC);
5398          if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
5399            Invalid = true;
5400        }
5401
5402
5403        FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
5404                                                        NewFD->getLocation(),
5405                                                        Name, TemplateParams,
5406                                                        NewFD);
5407        FunctionTemplate->setLexicalDeclContext(CurContext);
5408        NewFD->setDescribedFunctionTemplate(FunctionTemplate);
5409
5410        // For source fidelity, store the other template param lists.
5411        if (TemplateParamLists.size() > 1) {
5412          NewFD->setTemplateParameterListsInfo(Context,
5413                                               TemplateParamLists.size() - 1,
5414                                               TemplateParamLists.data());
5415        }
5416      } else {
5417        // This is a function template specialization.
5418        isFunctionTemplateSpecialization = true;
5419        // For source fidelity, store all the template param lists.
5420        NewFD->setTemplateParameterListsInfo(Context,
5421                                             TemplateParamLists.size(),
5422                                             TemplateParamLists.data());
5423
5424        // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
5425        if (isFriend) {
5426          // We want to remove the "template<>", found here.
5427          SourceRange RemoveRange = TemplateParams->getSourceRange();
5428
5429          // If we remove the template<> and the name is not a
5430          // template-id, we're actually silently creating a problem:
5431          // the friend declaration will refer to an untemplated decl,
5432          // and clearly the user wants a template specialization.  So
5433          // we need to insert '<>' after the name.
5434          SourceLocation InsertLoc;
5435          if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5436            InsertLoc = D.getName().getSourceRange().getEnd();
5437            InsertLoc = PP.getLocForEndOfToken(InsertLoc);
5438          }
5439
5440          Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
5441            << Name << RemoveRange
5442            << FixItHint::CreateRemoval(RemoveRange)
5443            << FixItHint::CreateInsertion(InsertLoc, "<>");
5444        }
5445      }
5446    }
5447    else {
5448      // All template param lists were matched against the scope specifier:
5449      // this is NOT (an explicit specialization of) a template.
5450      if (TemplateParamLists.size() > 0)
5451        // For source fidelity, store all the template param lists.
5452        NewFD->setTemplateParameterListsInfo(Context,
5453                                             TemplateParamLists.size(),
5454                                             TemplateParamLists.data());
5455    }
5456
5457    if (Invalid) {
5458      NewFD->setInvalidDecl();
5459      if (FunctionTemplate)
5460        FunctionTemplate->setInvalidDecl();
5461    }
5462
5463    // C++ [dcl.fct.spec]p5:
5464    //   The virtual specifier shall only be used in declarations of
5465    //   nonstatic class member functions that appear within a
5466    //   member-specification of a class declaration; see 10.3.
5467    //
5468    if (isVirtual && !NewFD->isInvalidDecl()) {
5469      if (!isVirtualOkay) {
5470        Diag(D.getDeclSpec().getVirtualSpecLoc(),
5471             diag::err_virtual_non_function);
5472      } else if (!CurContext->isRecord()) {
5473        // 'virtual' was specified outside of the class.
5474        Diag(D.getDeclSpec().getVirtualSpecLoc(),
5475             diag::err_virtual_out_of_class)
5476          << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
5477      } else if (NewFD->getDescribedFunctionTemplate()) {
5478        // C++ [temp.mem]p3:
5479        //  A member function template shall not be virtual.
5480        Diag(D.getDeclSpec().getVirtualSpecLoc(),
5481             diag::err_virtual_member_function_template)
5482          << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
5483      } else {
5484        // Okay: Add virtual to the method.
5485        NewFD->setVirtualAsWritten(true);
5486      }
5487    }
5488
5489    // C++ [dcl.fct.spec]p3:
5490    //  The inline specifier shall not appear on a block scope function
5491    //  declaration.
5492    if (isInline && !NewFD->isInvalidDecl()) {
5493      if (CurContext->isFunctionOrMethod()) {
5494        // 'inline' is not allowed on block scope function declaration.
5495        Diag(D.getDeclSpec().getInlineSpecLoc(),
5496             diag::err_inline_declaration_block_scope) << Name
5497          << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
5498      }
5499    }
5500
5501    // C++ [dcl.fct.spec]p6:
5502    //  The explicit specifier shall be used only in the declaration of a
5503    //  constructor or conversion function within its class definition;
5504    //  see 12.3.1 and 12.3.2.
5505    if (isExplicit && !NewFD->isInvalidDecl()) {
5506      if (!CurContext->isRecord()) {
5507        // 'explicit' was specified outside of the class.
5508        Diag(D.getDeclSpec().getExplicitSpecLoc(),
5509             diag::err_explicit_out_of_class)
5510          << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
5511      } else if (!isa<CXXConstructorDecl>(NewFD) &&
5512                 !isa<CXXConversionDecl>(NewFD)) {
5513        // 'explicit' was specified on a function that wasn't a constructor
5514        // or conversion function.
5515        Diag(D.getDeclSpec().getExplicitSpecLoc(),
5516             diag::err_explicit_non_ctor_or_conv_function)
5517          << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
5518      }
5519    }
5520
5521    if (isConstexpr) {
5522      // C++0x [dcl.constexpr]p2: constexpr functions and constexpr constructors
5523      // are implicitly inline.
5524      NewFD->setImplicitlyInline();
5525
5526      // C++0x [dcl.constexpr]p3: functions declared constexpr are required to
5527      // be either constructors or to return a literal type. Therefore,
5528      // destructors cannot be declared constexpr.
5529      if (isa<CXXDestructorDecl>(NewFD))
5530        Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
5531    }
5532
5533    // If __module_private__ was specified, mark the function accordingly.
5534    if (D.getDeclSpec().isModulePrivateSpecified()) {
5535      if (isFunctionTemplateSpecialization) {
5536        SourceLocation ModulePrivateLoc
5537          = D.getDeclSpec().getModulePrivateSpecLoc();
5538        Diag(ModulePrivateLoc, diag::err_module_private_specialization)
5539          << 0
5540          << FixItHint::CreateRemoval(ModulePrivateLoc);
5541      } else {
5542        NewFD->setModulePrivate();
5543        if (FunctionTemplate)
5544          FunctionTemplate->setModulePrivate();
5545      }
5546    }
5547
5548    if (isFriend) {
5549      // For now, claim that the objects have no previous declaration.
5550      if (FunctionTemplate) {
5551        FunctionTemplate->setObjectOfFriendDecl(false);
5552        FunctionTemplate->setAccess(AS_public);
5553      }
5554      NewFD->setObjectOfFriendDecl(false);
5555      NewFD->setAccess(AS_public);
5556    }
5557
5558    // If a function is defined as defaulted or deleted, mark it as such now.
5559    switch (D.getFunctionDefinitionKind()) {
5560      case FDK_Declaration:
5561      case FDK_Definition:
5562        break;
5563
5564      case FDK_Defaulted:
5565        NewFD->setDefaulted();
5566        break;
5567
5568      case FDK_Deleted:
5569        NewFD->setDeletedAsWritten();
5570        break;
5571    }
5572
5573    if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
5574        D.isFunctionDefinition()) {
5575      // C++ [class.mfct]p2:
5576      //   A member function may be defined (8.4) in its class definition, in
5577      //   which case it is an inline member function (7.1.2)
5578      NewFD->setImplicitlyInline();
5579    }
5580
5581    if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
5582        !CurContext->isRecord()) {
5583      // C++ [class.static]p1:
5584      //   A data or function member of a class may be declared static
5585      //   in a class definition, in which case it is a static member of
5586      //   the class.
5587
5588      // Complain about the 'static' specifier if it's on an out-of-line
5589      // member function definition.
5590      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5591           diag::err_static_out_of_line)
5592        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5593    }
5594
5595    // C++11 [except.spec]p15:
5596    //   A deallocation function with no exception-specification is treated
5597    //   as if it were specified with noexcept(true).
5598    const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
5599    if ((Name.getCXXOverloadedOperator() == OO_Delete ||
5600         Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
5601        getLangOpts().CPlusPlus0x && FPT && !FPT->hasExceptionSpec()) {
5602      FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5603      EPI.ExceptionSpecType = EST_BasicNoexcept;
5604      NewFD->setType(Context.getFunctionType(FPT->getResultType(),
5605                                             FPT->arg_type_begin(),
5606                                             FPT->getNumArgs(), EPI));
5607    }
5608  }
5609
5610  // Filter out previous declarations that don't match the scope.
5611  FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(),
5612                       isExplicitSpecialization ||
5613                       isFunctionTemplateSpecialization);
5614
5615  // Handle GNU asm-label extension (encoded as an attribute).
5616  if (Expr *E = (Expr*) D.getAsmLabel()) {
5617    // The parser guarantees this is a string.
5618    StringLiteral *SE = cast<StringLiteral>(E);
5619    NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
5620                                                SE->getString()));
5621  } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5622    llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5623      ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
5624    if (I != ExtnameUndeclaredIdentifiers.end()) {
5625      NewFD->addAttr(I->second);
5626      ExtnameUndeclaredIdentifiers.erase(I);
5627    }
5628  }
5629
5630  // Copy the parameter declarations from the declarator D to the function
5631  // declaration NewFD, if they are available.  First scavenge them into Params.
5632  SmallVector<ParmVarDecl*, 16> Params;
5633  if (D.isFunctionDeclarator()) {
5634    DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5635
5636    // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
5637    // function that takes no arguments, not a function that takes a
5638    // single void argument.
5639    // We let through "const void" here because Sema::GetTypeForDeclarator
5640    // already checks for that case.
5641    if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5642        FTI.ArgInfo[0].Param &&
5643        cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
5644      // Empty arg list, don't push any params.
5645      checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
5646    } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
5647      for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
5648        ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
5649        assert(Param->getDeclContext() != NewFD && "Was set before ?");
5650        Param->setDeclContext(NewFD);
5651        Params.push_back(Param);
5652
5653        if (Param->isInvalidDecl())
5654          NewFD->setInvalidDecl();
5655      }
5656    }
5657
5658  } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
5659    // When we're declaring a function with a typedef, typeof, etc as in the
5660    // following example, we'll need to synthesize (unnamed)
5661    // parameters for use in the declaration.
5662    //
5663    // @code
5664    // typedef void fn(int);
5665    // fn f;
5666    // @endcode
5667
5668    // Synthesize a parameter for each argument type.
5669    for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
5670         AE = FT->arg_type_end(); AI != AE; ++AI) {
5671      ParmVarDecl *Param =
5672        BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
5673      Param->setScopeInfo(0, Params.size());
5674      Params.push_back(Param);
5675    }
5676  } else {
5677    assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
5678           "Should not need args for typedef of non-prototype fn");
5679  }
5680
5681  // Finally, we know we have the right number of parameters, install them.
5682  NewFD->setParams(Params);
5683
5684  // Find all anonymous symbols defined during the declaration of this function
5685  // and add to NewFD. This lets us track decls such 'enum Y' in:
5686  //
5687  //   void f(enum Y {AA} x) {}
5688  //
5689  // which would otherwise incorrectly end up in the translation unit scope.
5690  NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
5691  DeclsInPrototypeScope.clear();
5692
5693  // Process the non-inheritable attributes on this declaration.
5694  ProcessDeclAttributes(S, NewFD, D,
5695                        /*NonInheritable=*/true, /*Inheritable=*/false);
5696
5697  // Functions returning a variably modified type violate C99 6.7.5.2p2
5698  // because all functions have linkage.
5699  if (!NewFD->isInvalidDecl() &&
5700      NewFD->getResultType()->isVariablyModifiedType()) {
5701    Diag(NewFD->getLocation(), diag::err_vm_func_decl);
5702    NewFD->setInvalidDecl();
5703  }
5704
5705  // Handle attributes.
5706  ProcessDeclAttributes(S, NewFD, D,
5707                        /*NonInheritable=*/false, /*Inheritable=*/true);
5708
5709  QualType RetType = NewFD->getResultType();
5710  const CXXRecordDecl *Ret = RetType->isRecordType() ?
5711      RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
5712  if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
5713      Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
5714    const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
5715    if (!(MD && MD->getCorrespondingMethodInClass(Ret, true))) {
5716      NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(),
5717                                                        Context));
5718    }
5719  }
5720
5721  if (!getLangOpts().CPlusPlus) {
5722    // Perform semantic checking on the function declaration.
5723    bool isExplicitSpecialization=false;
5724    if (!NewFD->isInvalidDecl()) {
5725      if (NewFD->isMain())
5726        CheckMain(NewFD, D.getDeclSpec());
5727      D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
5728                                                  isExplicitSpecialization));
5729    }
5730    // Make graceful recovery from an invalid redeclaration.
5731    else if (!Previous.empty())
5732           D.setRedeclaration(true);
5733    assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
5734            Previous.getResultKind() != LookupResult::FoundOverloaded) &&
5735           "previous declaration set still overloaded");
5736  } else {
5737    // If the declarator is a template-id, translate the parser's template
5738    // argument list into our AST format.
5739    if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5740      TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5741      TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5742      TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
5743      ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
5744                                         TemplateId->NumArgs);
5745      translateTemplateArguments(TemplateArgsPtr,
5746                                 TemplateArgs);
5747
5748      HasExplicitTemplateArgs = true;
5749
5750      if (NewFD->isInvalidDecl()) {
5751        HasExplicitTemplateArgs = false;
5752      } else if (FunctionTemplate) {
5753        // Function template with explicit template arguments.
5754        Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
5755          << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
5756
5757        HasExplicitTemplateArgs = false;
5758      } else if (!isFunctionTemplateSpecialization &&
5759                 !D.getDeclSpec().isFriendSpecified()) {
5760        // We have encountered something that the user meant to be a
5761        // specialization (because it has explicitly-specified template
5762        // arguments) but that was not introduced with a "template<>" (or had
5763        // too few of them).
5764        Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5765          << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5766          << FixItHint::CreateInsertion(
5767                                    D.getDeclSpec().getLocStart(),
5768                                        "template<> ");
5769        isFunctionTemplateSpecialization = true;
5770      } else {
5771        // "friend void foo<>(int);" is an implicit specialization decl.
5772        isFunctionTemplateSpecialization = true;
5773      }
5774    } else if (isFriend && isFunctionTemplateSpecialization) {
5775      // This combination is only possible in a recovery case;  the user
5776      // wrote something like:
5777      //   template <> friend void foo(int);
5778      // which we're recovering from as if the user had written:
5779      //   friend void foo<>(int);
5780      // Go ahead and fake up a template id.
5781      HasExplicitTemplateArgs = true;
5782        TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
5783      TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
5784    }
5785
5786    // If it's a friend (and only if it's a friend), it's possible
5787    // that either the specialized function type or the specialized
5788    // template is dependent, and therefore matching will fail.  In
5789    // this case, don't check the specialization yet.
5790    bool InstantiationDependent = false;
5791    if (isFunctionTemplateSpecialization && isFriend &&
5792        (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
5793         TemplateSpecializationType::anyDependentTemplateArguments(
5794            TemplateArgs.getArgumentArray(), TemplateArgs.size(),
5795            InstantiationDependent))) {
5796      assert(HasExplicitTemplateArgs &&
5797             "friend function specialization without template args");
5798      if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
5799                                                       Previous))
5800        NewFD->setInvalidDecl();
5801    } else if (isFunctionTemplateSpecialization) {
5802      if (CurContext->isDependentContext() && CurContext->isRecord()
5803          && !isFriend) {
5804        isDependentClassScopeExplicitSpecialization = true;
5805        Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
5806          diag::ext_function_specialization_in_class :
5807          diag::err_function_specialization_in_class)
5808          << NewFD->getDeclName();
5809      } else if (CheckFunctionTemplateSpecialization(NewFD,
5810                                  (HasExplicitTemplateArgs ? &TemplateArgs : 0),
5811                                                     Previous))
5812        NewFD->setInvalidDecl();
5813
5814      // C++ [dcl.stc]p1:
5815      //   A storage-class-specifier shall not be specified in an explicit
5816      //   specialization (14.7.3)
5817      if (SC != SC_None) {
5818        if (SC != NewFD->getStorageClass())
5819          Diag(NewFD->getLocation(),
5820               diag::err_explicit_specialization_inconsistent_storage_class)
5821            << SC
5822            << FixItHint::CreateRemoval(
5823                                      D.getDeclSpec().getStorageClassSpecLoc());
5824
5825        else
5826          Diag(NewFD->getLocation(),
5827               diag::ext_explicit_specialization_storage_class)
5828            << FixItHint::CreateRemoval(
5829                                      D.getDeclSpec().getStorageClassSpecLoc());
5830      }
5831
5832    } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
5833      if (CheckMemberSpecialization(NewFD, Previous))
5834          NewFD->setInvalidDecl();
5835    }
5836
5837    // Perform semantic checking on the function declaration.
5838    if (!isDependentClassScopeExplicitSpecialization) {
5839      if (NewFD->isInvalidDecl()) {
5840        // If this is a class member, mark the class invalid immediately.
5841        // This avoids some consistency errors later.
5842        if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
5843          methodDecl->getParent()->setInvalidDecl();
5844      } else {
5845        if (NewFD->isMain())
5846          CheckMain(NewFD, D.getDeclSpec());
5847        D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
5848                                                    isExplicitSpecialization));
5849      }
5850    }
5851
5852    assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
5853            Previous.getResultKind() != LookupResult::FoundOverloaded) &&
5854           "previous declaration set still overloaded");
5855
5856    NamedDecl *PrincipalDecl = (FunctionTemplate
5857                                ? cast<NamedDecl>(FunctionTemplate)
5858                                : NewFD);
5859
5860    if (isFriend && D.isRedeclaration()) {
5861      AccessSpecifier Access = AS_public;
5862      if (!NewFD->isInvalidDecl())
5863        Access = NewFD->getPreviousDecl()->getAccess();
5864
5865      NewFD->setAccess(Access);
5866      if (FunctionTemplate) FunctionTemplate->setAccess(Access);
5867
5868      PrincipalDecl->setObjectOfFriendDecl(true);
5869    }
5870
5871    if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
5872        PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
5873      PrincipalDecl->setNonMemberOperator();
5874
5875    // If we have a function template, check the template parameter
5876    // list. This will check and merge default template arguments.
5877    if (FunctionTemplate) {
5878      FunctionTemplateDecl *PrevTemplate =
5879                                     FunctionTemplate->getPreviousDecl();
5880      CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
5881                       PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
5882                            D.getDeclSpec().isFriendSpecified()
5883                              ? (D.isFunctionDefinition()
5884                                   ? TPC_FriendFunctionTemplateDefinition
5885                                   : TPC_FriendFunctionTemplate)
5886                              : (D.getCXXScopeSpec().isSet() &&
5887                                 DC && DC->isRecord() &&
5888                                 DC->isDependentContext())
5889                                  ? TPC_ClassTemplateMember
5890                                  : TPC_FunctionTemplate);
5891    }
5892
5893    if (NewFD->isInvalidDecl()) {
5894      // Ignore all the rest of this.
5895    } else if (!D.isRedeclaration()) {
5896      struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
5897                                       AddToScope };
5898      // Fake up an access specifier if it's supposed to be a class member.
5899      if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
5900        NewFD->setAccess(AS_public);
5901
5902      // Qualified decls generally require a previous declaration.
5903      if (D.getCXXScopeSpec().isSet()) {
5904        // ...with the major exception of templated-scope or
5905        // dependent-scope friend declarations.
5906
5907        // TODO: we currently also suppress this check in dependent
5908        // contexts because (1) the parameter depth will be off when
5909        // matching friend templates and (2) we might actually be
5910        // selecting a friend based on a dependent factor.  But there
5911        // are situations where these conditions don't apply and we
5912        // can actually do this check immediately.
5913        if (isFriend &&
5914            (TemplateParamLists.size() ||
5915             D.getCXXScopeSpec().getScopeRep()->isDependent() ||
5916             CurContext->isDependentContext())) {
5917          // ignore these
5918        } else {
5919          // The user tried to provide an out-of-line definition for a
5920          // function that is a member of a class or namespace, but there
5921          // was no such member function declared (C++ [class.mfct]p2,
5922          // C++ [namespace.memdef]p2). For example:
5923          //
5924          // class X {
5925          //   void f() const;
5926          // };
5927          //
5928          // void X::f() { } // ill-formed
5929          //
5930          // Complain about this problem, and attempt to suggest close
5931          // matches (e.g., those that differ only in cv-qualifiers and
5932          // whether the parameter types are references).
5933
5934          if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
5935                                                               NewFD,
5936                                                               ExtraArgs)) {
5937            AddToScope = ExtraArgs.AddToScope;
5938            return Result;
5939          }
5940        }
5941
5942        // Unqualified local friend declarations are required to resolve
5943        // to something.
5944      } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
5945        if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
5946                                                             NewFD,
5947                                                             ExtraArgs)) {
5948          AddToScope = ExtraArgs.AddToScope;
5949          return Result;
5950        }
5951      }
5952
5953    } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
5954               !isFriend && !isFunctionTemplateSpecialization &&
5955               !isExplicitSpecialization) {
5956      // An out-of-line member function declaration must also be a
5957      // definition (C++ [dcl.meaning]p1).
5958      // Note that this is not the case for explicit specializations of
5959      // function templates or member functions of class templates, per
5960      // C++ [temp.expl.spec]p2. We also allow these declarations as an
5961      // extension for compatibility with old SWIG code which likes to
5962      // generate them.
5963      Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
5964        << D.getCXXScopeSpec().getRange();
5965    }
5966  }
5967
5968  AddKnownFunctionAttributes(NewFD);
5969
5970  if (NewFD->hasAttr<OverloadableAttr>() &&
5971      !NewFD->getType()->getAs<FunctionProtoType>()) {
5972    Diag(NewFD->getLocation(),
5973         diag::err_attribute_overloadable_no_prototype)
5974      << NewFD;
5975
5976    // Turn this into a variadic function with no parameters.
5977    const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
5978    FunctionProtoType::ExtProtoInfo EPI;
5979    EPI.Variadic = true;
5980    EPI.ExtInfo = FT->getExtInfo();
5981
5982    QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI);
5983    NewFD->setType(R);
5984  }
5985
5986  // If there's a #pragma GCC visibility in scope, and this isn't a class
5987  // member, set the visibility of this function.
5988  if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord())
5989    AddPushedVisibilityAttribute(NewFD);
5990
5991  // If there's a #pragma clang arc_cf_code_audited in scope, consider
5992  // marking the function.
5993  AddCFAuditedAttribute(NewFD);
5994
5995  // If this is a locally-scoped extern C function, update the
5996  // map of such names.
5997  if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
5998      && !NewFD->isInvalidDecl())
5999    RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
6000
6001  // Set this FunctionDecl's range up to the right paren.
6002  NewFD->setRangeEnd(D.getSourceRange().getEnd());
6003
6004  if (getLangOpts().CPlusPlus) {
6005    if (FunctionTemplate) {
6006      if (NewFD->isInvalidDecl())
6007        FunctionTemplate->setInvalidDecl();
6008      return FunctionTemplate;
6009    }
6010  }
6011
6012  // OpenCL v1.2 s6.8 static is invalid for kernel functions.
6013  if ((getLangOpts().OpenCLVersion >= 120)
6014      && NewFD->hasAttr<OpenCLKernelAttr>()
6015      && (SC == SC_Static)) {
6016    Diag(D.getIdentifierLoc(), diag::err_static_kernel);
6017    D.setInvalidType();
6018  }
6019
6020  MarkUnusedFileScopedDecl(NewFD);
6021
6022  if (getLangOpts().CUDA)
6023    if (IdentifierInfo *II = NewFD->getIdentifier())
6024      if (!NewFD->isInvalidDecl() &&
6025          NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6026        if (II->isStr("cudaConfigureCall")) {
6027          if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
6028            Diag(NewFD->getLocation(), diag::err_config_scalar_return);
6029
6030          Context.setcudaConfigureCallDecl(NewFD);
6031        }
6032      }
6033
6034  // Here we have an function template explicit specialization at class scope.
6035  // The actually specialization will be postponed to template instatiation
6036  // time via the ClassScopeFunctionSpecializationDecl node.
6037  if (isDependentClassScopeExplicitSpecialization) {
6038    ClassScopeFunctionSpecializationDecl *NewSpec =
6039                         ClassScopeFunctionSpecializationDecl::Create(
6040                                Context, CurContext, SourceLocation(),
6041                                cast<CXXMethodDecl>(NewFD),
6042                                HasExplicitTemplateArgs, TemplateArgs);
6043    CurContext->addDecl(NewSpec);
6044    AddToScope = false;
6045  }
6046
6047  return NewFD;
6048}
6049
6050/// \brief Perform semantic checking of a new function declaration.
6051///
6052/// Performs semantic analysis of the new function declaration
6053/// NewFD. This routine performs all semantic checking that does not
6054/// require the actual declarator involved in the declaration, and is
6055/// used both for the declaration of functions as they are parsed
6056/// (called via ActOnDeclarator) and for the declaration of functions
6057/// that have been instantiated via C++ template instantiation (called
6058/// via InstantiateDecl).
6059///
6060/// \param IsExplicitSpecialization whether this new function declaration is
6061/// an explicit specialization of the previous declaration.
6062///
6063/// This sets NewFD->isInvalidDecl() to true if there was an error.
6064///
6065/// \returns true if the function declaration is a redeclaration.
6066bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
6067                                    LookupResult &Previous,
6068                                    bool IsExplicitSpecialization) {
6069  assert(!NewFD->getResultType()->isVariablyModifiedType()
6070         && "Variably modified return types are not handled here");
6071
6072  // Check for a previous declaration of this name.
6073  if (Previous.empty() && NewFD->isExternC()) {
6074    // Since we did not find anything by this name and we're declaring
6075    // an extern "C" function, look for a non-visible extern "C"
6076    // declaration with the same name.
6077    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
6078      = findLocallyScopedExternalDecl(NewFD->getDeclName());
6079    if (Pos != LocallyScopedExternalDecls.end())
6080      Previous.addDecl(Pos->second);
6081  }
6082
6083  bool Redeclaration = false;
6084
6085  // Merge or overload the declaration with an existing declaration of
6086  // the same name, if appropriate.
6087  if (!Previous.empty()) {
6088    // Determine whether NewFD is an overload of PrevDecl or
6089    // a declaration that requires merging. If it's an overload,
6090    // there's no more work to do here; we'll just add the new
6091    // function to the scope.
6092
6093    NamedDecl *OldDecl = 0;
6094    if (!AllowOverloadingOfFunction(Previous, Context)) {
6095      Redeclaration = true;
6096      OldDecl = Previous.getFoundDecl();
6097    } else {
6098      switch (CheckOverload(S, NewFD, Previous, OldDecl,
6099                            /*NewIsUsingDecl*/ false)) {
6100      case Ovl_Match:
6101        Redeclaration = true;
6102        break;
6103
6104      case Ovl_NonFunction:
6105        Redeclaration = true;
6106        break;
6107
6108      case Ovl_Overload:
6109        Redeclaration = false;
6110        break;
6111      }
6112
6113      if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
6114        // If a function name is overloadable in C, then every function
6115        // with that name must be marked "overloadable".
6116        Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
6117          << Redeclaration << NewFD;
6118        NamedDecl *OverloadedDecl = 0;
6119        if (Redeclaration)
6120          OverloadedDecl = OldDecl;
6121        else if (!Previous.empty())
6122          OverloadedDecl = Previous.getRepresentativeDecl();
6123        if (OverloadedDecl)
6124          Diag(OverloadedDecl->getLocation(),
6125               diag::note_attribute_overloadable_prev_overload);
6126        NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
6127                                                        Context));
6128      }
6129    }
6130
6131    if (Redeclaration) {
6132      // NewFD and OldDecl represent declarations that need to be
6133      // merged.
6134      if (MergeFunctionDecl(NewFD, OldDecl, S)) {
6135        NewFD->setInvalidDecl();
6136        return Redeclaration;
6137      }
6138
6139      Previous.clear();
6140      Previous.addDecl(OldDecl);
6141
6142      if (FunctionTemplateDecl *OldTemplateDecl
6143                                    = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
6144        NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
6145        FunctionTemplateDecl *NewTemplateDecl
6146          = NewFD->getDescribedFunctionTemplate();
6147        assert(NewTemplateDecl && "Template/non-template mismatch");
6148        if (CXXMethodDecl *Method
6149              = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
6150          Method->setAccess(OldTemplateDecl->getAccess());
6151          NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
6152        }
6153
6154        // If this is an explicit specialization of a member that is a function
6155        // template, mark it as a member specialization.
6156        if (IsExplicitSpecialization &&
6157            NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
6158          NewTemplateDecl->setMemberSpecialization();
6159          assert(OldTemplateDecl->isMemberSpecialization());
6160        }
6161
6162      } else {
6163        if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
6164          NewFD->setAccess(OldDecl->getAccess());
6165        NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
6166      }
6167    }
6168  }
6169
6170  // Semantic checking for this function declaration (in isolation).
6171  if (getLangOpts().CPlusPlus) {
6172    // C++-specific checks.
6173    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
6174      CheckConstructor(Constructor);
6175    } else if (CXXDestructorDecl *Destructor =
6176                dyn_cast<CXXDestructorDecl>(NewFD)) {
6177      CXXRecordDecl *Record = Destructor->getParent();
6178      QualType ClassType = Context.getTypeDeclType(Record);
6179
6180      // FIXME: Shouldn't we be able to perform this check even when the class
6181      // type is dependent? Both gcc and edg can handle that.
6182      if (!ClassType->isDependentType()) {
6183        DeclarationName Name
6184          = Context.DeclarationNames.getCXXDestructorName(
6185                                        Context.getCanonicalType(ClassType));
6186        if (NewFD->getDeclName() != Name) {
6187          Diag(NewFD->getLocation(), diag::err_destructor_name);
6188          NewFD->setInvalidDecl();
6189          return Redeclaration;
6190        }
6191      }
6192    } else if (CXXConversionDecl *Conversion
6193               = dyn_cast<CXXConversionDecl>(NewFD)) {
6194      ActOnConversionDeclarator(Conversion);
6195    }
6196
6197    // Find any virtual functions that this function overrides.
6198    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
6199      if (!Method->isFunctionTemplateSpecialization() &&
6200          !Method->getDescribedFunctionTemplate() &&
6201          Method->isCanonicalDecl()) {
6202        if (AddOverriddenMethods(Method->getParent(), Method)) {
6203          // If the function was marked as "static", we have a problem.
6204          if (NewFD->getStorageClass() == SC_Static) {
6205            ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
6206          }
6207        }
6208      }
6209
6210      if (Method->isStatic())
6211        checkThisInStaticMemberFunctionType(Method);
6212    }
6213
6214    // Extra checking for C++ overloaded operators (C++ [over.oper]).
6215    if (NewFD->isOverloadedOperator() &&
6216        CheckOverloadedOperatorDeclaration(NewFD)) {
6217      NewFD->setInvalidDecl();
6218      return Redeclaration;
6219    }
6220
6221    // Extra checking for C++0x literal operators (C++0x [over.literal]).
6222    if (NewFD->getLiteralIdentifier() &&
6223        CheckLiteralOperatorDeclaration(NewFD)) {
6224      NewFD->setInvalidDecl();
6225      return Redeclaration;
6226    }
6227
6228    // In C++, check default arguments now that we have merged decls. Unless
6229    // the lexical context is the class, because in this case this is done
6230    // during delayed parsing anyway.
6231    if (!CurContext->isRecord())
6232      CheckCXXDefaultArguments(NewFD);
6233
6234    // If this function declares a builtin function, check the type of this
6235    // declaration against the expected type for the builtin.
6236    if (unsigned BuiltinID = NewFD->getBuiltinID()) {
6237      ASTContext::GetBuiltinTypeError Error;
6238      QualType T = Context.GetBuiltinType(BuiltinID, Error);
6239      if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
6240        // The type of this function differs from the type of the builtin,
6241        // so forget about the builtin entirely.
6242        Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
6243      }
6244    }
6245
6246    // If this function is declared as being extern "C", then check to see if
6247    // the function returns a UDT (class, struct, or union type) that is not C
6248    // compatible, and if it does, warn the user.
6249    if (NewFD->isExternC()) {
6250      QualType R = NewFD->getResultType();
6251      if (R->isIncompleteType() && !R->isVoidType())
6252        Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
6253            << NewFD << R;
6254      else if (!R.isPODType(Context) && !R->isVoidType() &&
6255               !R->isObjCObjectPointerType())
6256        Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
6257    }
6258  }
6259  return Redeclaration;
6260}
6261
6262void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
6263  // C++11 [basic.start.main]p3:  A program that declares main to be inline,
6264  //   static or constexpr is ill-formed.
6265  // C99 6.7.4p4:  In a hosted environment, the inline function specifier
6266  //   shall not appear in a declaration of main.
6267  // static main is not an error under C99, but we should warn about it.
6268  if (FD->getStorageClass() == SC_Static)
6269    Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
6270         ? diag::err_static_main : diag::warn_static_main)
6271      << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
6272  if (FD->isInlineSpecified())
6273    Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
6274      << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
6275  if (FD->isConstexpr()) {
6276    Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
6277      << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
6278    FD->setConstexpr(false);
6279  }
6280
6281  QualType T = FD->getType();
6282  assert(T->isFunctionType() && "function decl is not of function type");
6283  const FunctionType* FT = T->castAs<FunctionType>();
6284
6285  // All the standards say that main() should should return 'int'.
6286  if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
6287    // In C and C++, main magically returns 0 if you fall off the end;
6288    // set the flag which tells us that.
6289    // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
6290    FD->setHasImplicitReturnZero(true);
6291
6292  // In C with GNU extensions we allow main() to have non-integer return
6293  // type, but we should warn about the extension, and we disable the
6294  // implicit-return-zero rule.
6295  } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
6296    Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
6297
6298  // Otherwise, this is just a flat-out error.
6299  } else {
6300    Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
6301    FD->setInvalidDecl(true);
6302  }
6303
6304  // Treat protoless main() as nullary.
6305  if (isa<FunctionNoProtoType>(FT)) return;
6306
6307  const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
6308  unsigned nparams = FTP->getNumArgs();
6309  assert(FD->getNumParams() == nparams);
6310
6311  bool HasExtraParameters = (nparams > 3);
6312
6313  // Darwin passes an undocumented fourth argument of type char**.  If
6314  // other platforms start sprouting these, the logic below will start
6315  // getting shifty.
6316  if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
6317    HasExtraParameters = false;
6318
6319  if (HasExtraParameters) {
6320    Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
6321    FD->setInvalidDecl(true);
6322    nparams = 3;
6323  }
6324
6325  // FIXME: a lot of the following diagnostics would be improved
6326  // if we had some location information about types.
6327
6328  QualType CharPP =
6329    Context.getPointerType(Context.getPointerType(Context.CharTy));
6330  QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
6331
6332  for (unsigned i = 0; i < nparams; ++i) {
6333    QualType AT = FTP->getArgType(i);
6334
6335    bool mismatch = true;
6336
6337    if (Context.hasSameUnqualifiedType(AT, Expected[i]))
6338      mismatch = false;
6339    else if (Expected[i] == CharPP) {
6340      // As an extension, the following forms are okay:
6341      //   char const **
6342      //   char const * const *
6343      //   char * const *
6344
6345      QualifierCollector qs;
6346      const PointerType* PT;
6347      if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
6348          (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
6349          (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
6350        qs.removeConst();
6351        mismatch = !qs.empty();
6352      }
6353    }
6354
6355    if (mismatch) {
6356      Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
6357      // TODO: suggest replacing given type with expected type
6358      FD->setInvalidDecl(true);
6359    }
6360  }
6361
6362  if (nparams == 1 && !FD->isInvalidDecl()) {
6363    Diag(FD->getLocation(), diag::warn_main_one_arg);
6364  }
6365
6366  if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
6367    Diag(FD->getLocation(), diag::err_main_template_decl);
6368    FD->setInvalidDecl();
6369  }
6370}
6371
6372bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
6373  // FIXME: Need strict checking.  In C89, we need to check for
6374  // any assignment, increment, decrement, function-calls, or
6375  // commas outside of a sizeof.  In C99, it's the same list,
6376  // except that the aforementioned are allowed in unevaluated
6377  // expressions.  Everything else falls under the
6378  // "may accept other forms of constant expressions" exception.
6379  // (We never end up here for C++, so the constant expression
6380  // rules there don't matter.)
6381  if (Init->isConstantInitializer(Context, false))
6382    return false;
6383  Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
6384    << Init->getSourceRange();
6385  return true;
6386}
6387
6388namespace {
6389  // Visits an initialization expression to see if OrigDecl is evaluated in
6390  // its own initialization and throws a warning if it does.
6391  class SelfReferenceChecker
6392      : public EvaluatedExprVisitor<SelfReferenceChecker> {
6393    Sema &S;
6394    Decl *OrigDecl;
6395    bool isRecordType;
6396    bool isPODType;
6397    bool isReferenceType;
6398
6399  public:
6400    typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
6401
6402    SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
6403                                                    S(S), OrigDecl(OrigDecl) {
6404      isPODType = false;
6405      isRecordType = false;
6406      isReferenceType = false;
6407      if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
6408        isPODType = VD->getType().isPODType(S.Context);
6409        isRecordType = VD->getType()->isRecordType();
6410        isReferenceType = VD->getType()->isReferenceType();
6411      }
6412    }
6413
6414    // For most expressions, the cast is directly above the DeclRefExpr.
6415    // For conditional operators, the cast can be outside the conditional
6416    // operator if both expressions are DeclRefExpr's.
6417    void HandleValue(Expr *E) {
6418      if (isReferenceType)
6419        return;
6420      E = E->IgnoreParenImpCasts();
6421      if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
6422        HandleDeclRefExpr(DRE);
6423        return;
6424      }
6425
6426      if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6427        HandleValue(CO->getTrueExpr());
6428        HandleValue(CO->getFalseExpr());
6429        return;
6430      }
6431
6432      if (isa<MemberExpr>(E)) {
6433        Expr *Base = E->IgnoreParenImpCasts();
6434        while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
6435          // Check for static member variables and don't warn on them.
6436          if (!isa<FieldDecl>(ME->getMemberDecl()))
6437            return;
6438          Base = ME->getBase()->IgnoreParenImpCasts();
6439        }
6440        if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
6441          HandleDeclRefExpr(DRE);
6442        return;
6443      }
6444    }
6445
6446    // Reference types are handled here since all uses of references are
6447    // bad, not just r-value uses.
6448    void VisitDeclRefExpr(DeclRefExpr *E) {
6449      if (isReferenceType)
6450        HandleDeclRefExpr(E);
6451    }
6452
6453    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
6454      if (E->getCastKind() == CK_LValueToRValue ||
6455          (isRecordType && E->getCastKind() == CK_NoOp))
6456        HandleValue(E->getSubExpr());
6457
6458      Inherited::VisitImplicitCastExpr(E);
6459    }
6460
6461    void VisitMemberExpr(MemberExpr *E) {
6462      // Don't warn on arrays since they can be treated as pointers.
6463      if (E->getType()->canDecayToPointerType()) return;
6464
6465      // Warn when a non-static method call is followed by non-static member
6466      // field accesses, which is followed by a DeclRefExpr.
6467      CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
6468      bool Warn = (MD && !MD->isStatic());
6469      Expr *Base = E->getBase()->IgnoreParenImpCasts();
6470      while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
6471        if (!isa<FieldDecl>(ME->getMemberDecl()))
6472          Warn = false;
6473        Base = ME->getBase()->IgnoreParenImpCasts();
6474      }
6475
6476      if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
6477        if (Warn)
6478          HandleDeclRefExpr(DRE);
6479        return;
6480      }
6481
6482      // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
6483      // Visit that expression.
6484      Visit(Base);
6485    }
6486
6487    void VisitUnaryOperator(UnaryOperator *E) {
6488      // For POD record types, addresses of its own members are well-defined.
6489      if (E->getOpcode() == UO_AddrOf && isRecordType &&
6490          isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
6491        if (!isPODType)
6492          HandleValue(E->getSubExpr());
6493        return;
6494      }
6495      Inherited::VisitUnaryOperator(E);
6496    }
6497
6498    void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
6499
6500    void HandleDeclRefExpr(DeclRefExpr *DRE) {
6501      Decl* ReferenceDecl = DRE->getDecl();
6502      if (OrigDecl != ReferenceDecl) return;
6503      unsigned diag = isReferenceType
6504          ? diag::warn_uninit_self_reference_in_reference_init
6505          : diag::warn_uninit_self_reference_in_init;
6506      S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
6507                            S.PDiag(diag)
6508                              << DRE->getNameInfo().getName()
6509                              << OrigDecl->getLocation()
6510                              << DRE->getSourceRange());
6511    }
6512  };
6513
6514  /// CheckSelfReference - Warns if OrigDecl is used in expression E.
6515  static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
6516                                 bool DirectInit) {
6517    // Parameters arguments are occassionially constructed with itself,
6518    // for instance, in recursive functions.  Skip them.
6519    if (isa<ParmVarDecl>(OrigDecl))
6520      return;
6521
6522    E = E->IgnoreParens();
6523
6524    // Skip checking T a = a where T is not a record or reference type.
6525    // Doing so is a way to silence uninitialized warnings.
6526    if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
6527      if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
6528        if (ICE->getCastKind() == CK_LValueToRValue)
6529          if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
6530            if (DRE->getDecl() == OrigDecl)
6531              return;
6532
6533    SelfReferenceChecker(S, OrigDecl).Visit(E);
6534  }
6535}
6536
6537/// AddInitializerToDecl - Adds the initializer Init to the
6538/// declaration dcl. If DirectInit is true, this is C++ direct
6539/// initialization rather than copy initialization.
6540void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
6541                                bool DirectInit, bool TypeMayContainAuto) {
6542  // If there is no declaration, there was an error parsing it.  Just ignore
6543  // the initializer.
6544  if (RealDecl == 0 || RealDecl->isInvalidDecl())
6545    return;
6546
6547  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
6548    // With declarators parsed the way they are, the parser cannot
6549    // distinguish between a normal initializer and a pure-specifier.
6550    // Thus this grotesque test.
6551    IntegerLiteral *IL;
6552    if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
6553        Context.getCanonicalType(IL->getType()) == Context.IntTy)
6554      CheckPureMethod(Method, Init->getSourceRange());
6555    else {
6556      Diag(Method->getLocation(), diag::err_member_function_initialization)
6557        << Method->getDeclName() << Init->getSourceRange();
6558      Method->setInvalidDecl();
6559    }
6560    return;
6561  }
6562
6563  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
6564  if (!VDecl) {
6565    assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
6566    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
6567    RealDecl->setInvalidDecl();
6568    return;
6569  }
6570
6571  ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
6572
6573  // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
6574  AutoType *Auto = 0;
6575  if (TypeMayContainAuto &&
6576      (Auto = VDecl->getType()->getContainedAutoType()) &&
6577      !Auto->isDeduced()) {
6578    Expr *DeduceInit = Init;
6579    // Initializer could be a C++ direct-initializer. Deduction only works if it
6580    // contains exactly one expression.
6581    if (CXXDirectInit) {
6582      if (CXXDirectInit->getNumExprs() == 0) {
6583        // It isn't possible to write this directly, but it is possible to
6584        // end up in this situation with "auto x(some_pack...);"
6585        Diag(CXXDirectInit->getLocStart(),
6586             diag::err_auto_var_init_no_expression)
6587          << VDecl->getDeclName() << VDecl->getType()
6588          << VDecl->getSourceRange();
6589        RealDecl->setInvalidDecl();
6590        return;
6591      } else if (CXXDirectInit->getNumExprs() > 1) {
6592        Diag(CXXDirectInit->getExpr(1)->getLocStart(),
6593             diag::err_auto_var_init_multiple_expressions)
6594          << VDecl->getDeclName() << VDecl->getType()
6595          << VDecl->getSourceRange();
6596        RealDecl->setInvalidDecl();
6597        return;
6598      } else {
6599        DeduceInit = CXXDirectInit->getExpr(0);
6600      }
6601    }
6602    TypeSourceInfo *DeducedType = 0;
6603    if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
6604            DAR_Failed)
6605      DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
6606    if (!DeducedType) {
6607      RealDecl->setInvalidDecl();
6608      return;
6609    }
6610    VDecl->setTypeSourceInfo(DeducedType);
6611    VDecl->setType(DeducedType->getType());
6612    VDecl->ClearLinkageCache();
6613
6614    // In ARC, infer lifetime.
6615    if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
6616      VDecl->setInvalidDecl();
6617
6618    // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
6619    // 'id' instead of a specific object type prevents most of our usual checks.
6620    // We only want to warn outside of template instantiations, though:
6621    // inside a template, the 'id' could have come from a parameter.
6622    if (ActiveTemplateInstantiations.empty() &&
6623        DeducedType->getType()->isObjCIdType()) {
6624      SourceLocation Loc = DeducedType->getTypeLoc().getBeginLoc();
6625      Diag(Loc, diag::warn_auto_var_is_id)
6626        << VDecl->getDeclName() << DeduceInit->getSourceRange();
6627    }
6628
6629    // If this is a redeclaration, check that the type we just deduced matches
6630    // the previously declared type.
6631    if (VarDecl *Old = VDecl->getPreviousDecl())
6632      MergeVarDeclTypes(VDecl, Old);
6633  }
6634
6635  if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
6636    // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
6637    Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
6638    VDecl->setInvalidDecl();
6639    return;
6640  }
6641
6642  if (!VDecl->getType()->isDependentType()) {
6643    // A definition must end up with a complete type, which means it must be
6644    // complete with the restriction that an array type might be completed by
6645    // the initializer; note that later code assumes this restriction.
6646    QualType BaseDeclType = VDecl->getType();
6647    if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
6648      BaseDeclType = Array->getElementType();
6649    if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
6650                            diag::err_typecheck_decl_incomplete_type)) {
6651      RealDecl->setInvalidDecl();
6652      return;
6653    }
6654
6655    // The variable can not have an abstract class type.
6656    if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
6657                               diag::err_abstract_type_in_decl,
6658                               AbstractVariableType))
6659      VDecl->setInvalidDecl();
6660  }
6661
6662  const VarDecl *Def;
6663  if ((Def = VDecl->getDefinition()) && Def != VDecl) {
6664    Diag(VDecl->getLocation(), diag::err_redefinition)
6665      << VDecl->getDeclName();
6666    Diag(Def->getLocation(), diag::note_previous_definition);
6667    VDecl->setInvalidDecl();
6668    return;
6669  }
6670
6671  const VarDecl* PrevInit = 0;
6672  if (getLangOpts().CPlusPlus) {
6673    // C++ [class.static.data]p4
6674    //   If a static data member is of const integral or const
6675    //   enumeration type, its declaration in the class definition can
6676    //   specify a constant-initializer which shall be an integral
6677    //   constant expression (5.19). In that case, the member can appear
6678    //   in integral constant expressions. The member shall still be
6679    //   defined in a namespace scope if it is used in the program and the
6680    //   namespace scope definition shall not contain an initializer.
6681    //
6682    // We already performed a redefinition check above, but for static
6683    // data members we also need to check whether there was an in-class
6684    // declaration with an initializer.
6685    if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
6686      Diag(VDecl->getLocation(), diag::err_redefinition)
6687        << VDecl->getDeclName();
6688      Diag(PrevInit->getLocation(), diag::note_previous_definition);
6689      return;
6690    }
6691
6692    if (VDecl->hasLocalStorage())
6693      getCurFunction()->setHasBranchProtectedScope();
6694
6695    if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
6696      VDecl->setInvalidDecl();
6697      return;
6698    }
6699  }
6700
6701  // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
6702  // a kernel function cannot be initialized."
6703  if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
6704    Diag(VDecl->getLocation(), diag::err_local_cant_init);
6705    VDecl->setInvalidDecl();
6706    return;
6707  }
6708
6709  // Get the decls type and save a reference for later, since
6710  // CheckInitializerTypes may change it.
6711  QualType DclT = VDecl->getType(), SavT = DclT;
6712
6713  // Top-level message sends default to 'id' when we're in a debugger
6714  // and we are assigning it to a variable of 'id' type.
6715  if (getLangOpts().DebuggerCastResultToId && DclT->isObjCIdType())
6716    if (Init->getType() == Context.UnknownAnyTy && isa<ObjCMessageExpr>(Init)) {
6717      ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
6718      if (Result.isInvalid()) {
6719        VDecl->setInvalidDecl();
6720        return;
6721      }
6722      Init = Result.take();
6723    }
6724
6725  // Perform the initialization.
6726  if (!VDecl->isInvalidDecl()) {
6727    InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6728    InitializationKind Kind
6729      = DirectInit ?
6730          CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
6731                                                           Init->getLocStart(),
6732                                                           Init->getLocEnd())
6733                        : InitializationKind::CreateDirectList(
6734                                                          VDecl->getLocation())
6735                   : InitializationKind::CreateCopy(VDecl->getLocation(),
6736                                                    Init->getLocStart());
6737
6738    Expr **Args = &Init;
6739    unsigned NumArgs = 1;
6740    if (CXXDirectInit) {
6741      Args = CXXDirectInit->getExprs();
6742      NumArgs = CXXDirectInit->getNumExprs();
6743    }
6744    InitializationSequence InitSeq(*this, Entity, Kind, Args, NumArgs);
6745    ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
6746                                        MultiExprArg(Args, NumArgs), &DclT);
6747    if (Result.isInvalid()) {
6748      VDecl->setInvalidDecl();
6749      return;
6750    }
6751
6752    Init = Result.takeAs<Expr>();
6753  }
6754
6755  // Check for self-references within variable initializers.
6756  // Variables declared within a function/method body (except for references)
6757  // are handled by a dataflow analysis.
6758  if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
6759      VDecl->getType()->isReferenceType()) {
6760    CheckSelfReference(*this, RealDecl, Init, DirectInit);
6761  }
6762
6763  // If the type changed, it means we had an incomplete type that was
6764  // completed by the initializer. For example:
6765  //   int ary[] = { 1, 3, 5 };
6766  // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
6767  if (!VDecl->isInvalidDecl() && (DclT != SavT))
6768    VDecl->setType(DclT);
6769
6770  // Check any implicit conversions within the expression.
6771  CheckImplicitConversions(Init, VDecl->getLocation());
6772
6773  if (!VDecl->isInvalidDecl()) {
6774    checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
6775
6776    if (VDecl->hasAttr<BlocksAttr>())
6777      checkRetainCycles(VDecl, Init);
6778
6779    // It is safe to assign a weak reference into a strong variable.
6780    // Although this code can still have problems:
6781    //   id x = self.weakProp;
6782    //   id y = self.weakProp;
6783    // we do not warn to warn spuriously when 'x' and 'y' are on separate
6784    // paths through the function. This should be revisited if
6785    // -Wrepeated-use-of-weak is made flow-sensitive.
6786    if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
6787      DiagnosticsEngine::Level Level =
6788        Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
6789                                 Init->getLocStart());
6790      if (Level != DiagnosticsEngine::Ignored)
6791        getCurFunction()->markSafeWeakUse(Init);
6792    }
6793  }
6794
6795  Init = MaybeCreateExprWithCleanups(Init);
6796  // Attach the initializer to the decl.
6797  VDecl->setInit(Init);
6798
6799  if (VDecl->isLocalVarDecl()) {
6800    // C99 6.7.8p4: All the expressions in an initializer for an object that has
6801    // static storage duration shall be constant expressions or string literals.
6802    // C++ does not have this restriction.
6803    if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
6804        VDecl->getStorageClass() == SC_Static)
6805      CheckForConstantInitializer(Init, DclT);
6806  } else if (VDecl->isStaticDataMember() &&
6807             VDecl->getLexicalDeclContext()->isRecord()) {
6808    // This is an in-class initialization for a static data member, e.g.,
6809    //
6810    // struct S {
6811    //   static const int value = 17;
6812    // };
6813
6814    // C++ [class.mem]p4:
6815    //   A member-declarator can contain a constant-initializer only
6816    //   if it declares a static member (9.4) of const integral or
6817    //   const enumeration type, see 9.4.2.
6818    //
6819    // C++11 [class.static.data]p3:
6820    //   If a non-volatile const static data member is of integral or
6821    //   enumeration type, its declaration in the class definition can
6822    //   specify a brace-or-equal-initializer in which every initalizer-clause
6823    //   that is an assignment-expression is a constant expression. A static
6824    //   data member of literal type can be declared in the class definition
6825    //   with the constexpr specifier; if so, its declaration shall specify a
6826    //   brace-or-equal-initializer in which every initializer-clause that is
6827    //   an assignment-expression is a constant expression.
6828
6829    // Do nothing on dependent types.
6830    if (DclT->isDependentType()) {
6831
6832    // Allow any 'static constexpr' members, whether or not they are of literal
6833    // type. We separately check that every constexpr variable is of literal
6834    // type.
6835    } else if (VDecl->isConstexpr()) {
6836
6837    // Require constness.
6838    } else if (!DclT.isConstQualified()) {
6839      Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
6840        << Init->getSourceRange();
6841      VDecl->setInvalidDecl();
6842
6843    // We allow integer constant expressions in all cases.
6844    } else if (DclT->isIntegralOrEnumerationType()) {
6845      // Check whether the expression is a constant expression.
6846      SourceLocation Loc;
6847      if (getLangOpts().CPlusPlus0x && DclT.isVolatileQualified())
6848        // In C++11, a non-constexpr const static data member with an
6849        // in-class initializer cannot be volatile.
6850        Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
6851      else if (Init->isValueDependent())
6852        ; // Nothing to check.
6853      else if (Init->isIntegerConstantExpr(Context, &Loc))
6854        ; // Ok, it's an ICE!
6855      else if (Init->isEvaluatable(Context)) {
6856        // If we can constant fold the initializer through heroics, accept it,
6857        // but report this as a use of an extension for -pedantic.
6858        Diag(Loc, diag::ext_in_class_initializer_non_constant)
6859          << Init->getSourceRange();
6860      } else {
6861        // Otherwise, this is some crazy unknown case.  Report the issue at the
6862        // location provided by the isIntegerConstantExpr failed check.
6863        Diag(Loc, diag::err_in_class_initializer_non_constant)
6864          << Init->getSourceRange();
6865        VDecl->setInvalidDecl();
6866      }
6867
6868    // We allow foldable floating-point constants as an extension.
6869    } else if (DclT->isFloatingType()) { // also permits complex, which is ok
6870      Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
6871        << DclT << Init->getSourceRange();
6872      if (getLangOpts().CPlusPlus0x)
6873        Diag(VDecl->getLocation(),
6874             diag::note_in_class_initializer_float_type_constexpr)
6875          << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
6876
6877      if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
6878        Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
6879          << Init->getSourceRange();
6880        VDecl->setInvalidDecl();
6881      }
6882
6883    // Suggest adding 'constexpr' in C++11 for literal types.
6884    } else if (getLangOpts().CPlusPlus0x && DclT->isLiteralType()) {
6885      Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
6886        << DclT << Init->getSourceRange()
6887        << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
6888      VDecl->setConstexpr(true);
6889
6890    } else {
6891      Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
6892        << DclT << Init->getSourceRange();
6893      VDecl->setInvalidDecl();
6894    }
6895  } else if (VDecl->isFileVarDecl()) {
6896    if (VDecl->getStorageClassAsWritten() == SC_Extern &&
6897        (!getLangOpts().CPlusPlus ||
6898         !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
6899      Diag(VDecl->getLocation(), diag::warn_extern_init);
6900
6901    // C99 6.7.8p4. All file scoped initializers need to be constant.
6902    if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
6903      CheckForConstantInitializer(Init, DclT);
6904  }
6905
6906  // We will represent direct-initialization similarly to copy-initialization:
6907  //    int x(1);  -as-> int x = 1;
6908  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
6909  //
6910  // Clients that want to distinguish between the two forms, can check for
6911  // direct initializer using VarDecl::getInitStyle().
6912  // A major benefit is that clients that don't particularly care about which
6913  // exactly form was it (like the CodeGen) can handle both cases without
6914  // special case code.
6915
6916  // C++ 8.5p11:
6917  // The form of initialization (using parentheses or '=') is generally
6918  // insignificant, but does matter when the entity being initialized has a
6919  // class type.
6920  if (CXXDirectInit) {
6921    assert(DirectInit && "Call-style initializer must be direct init.");
6922    VDecl->setInitStyle(VarDecl::CallInit);
6923  } else if (DirectInit) {
6924    // This must be list-initialization. No other way is direct-initialization.
6925    VDecl->setInitStyle(VarDecl::ListInit);
6926  }
6927
6928  CheckCompleteVariableDeclaration(VDecl);
6929}
6930
6931/// ActOnInitializerError - Given that there was an error parsing an
6932/// initializer for the given declaration, try to return to some form
6933/// of sanity.
6934void Sema::ActOnInitializerError(Decl *D) {
6935  // Our main concern here is re-establishing invariants like "a
6936  // variable's type is either dependent or complete".
6937  if (!D || D->isInvalidDecl()) return;
6938
6939  VarDecl *VD = dyn_cast<VarDecl>(D);
6940  if (!VD) return;
6941
6942  // Auto types are meaningless if we can't make sense of the initializer.
6943  if (ParsingInitForAutoVars.count(D)) {
6944    D->setInvalidDecl();
6945    return;
6946  }
6947
6948  QualType Ty = VD->getType();
6949  if (Ty->isDependentType()) return;
6950
6951  // Require a complete type.
6952  if (RequireCompleteType(VD->getLocation(),
6953                          Context.getBaseElementType(Ty),
6954                          diag::err_typecheck_decl_incomplete_type)) {
6955    VD->setInvalidDecl();
6956    return;
6957  }
6958
6959  // Require an abstract type.
6960  if (RequireNonAbstractType(VD->getLocation(), Ty,
6961                             diag::err_abstract_type_in_decl,
6962                             AbstractVariableType)) {
6963    VD->setInvalidDecl();
6964    return;
6965  }
6966
6967  // Don't bother complaining about constructors or destructors,
6968  // though.
6969}
6970
6971void Sema::ActOnUninitializedDecl(Decl *RealDecl,
6972                                  bool TypeMayContainAuto) {
6973  // If there is no declaration, there was an error parsing it. Just ignore it.
6974  if (RealDecl == 0)
6975    return;
6976
6977  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
6978    QualType Type = Var->getType();
6979
6980    // C++11 [dcl.spec.auto]p3
6981    if (TypeMayContainAuto && Type->getContainedAutoType()) {
6982      Diag(Var->getLocation(), diag::err_auto_var_requires_init)
6983        << Var->getDeclName() << Type;
6984      Var->setInvalidDecl();
6985      return;
6986    }
6987
6988    // C++11 [class.static.data]p3: A static data member can be declared with
6989    // the constexpr specifier; if so, its declaration shall specify
6990    // a brace-or-equal-initializer.
6991    // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
6992    // the definition of a variable [...] or the declaration of a static data
6993    // member.
6994    if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
6995      if (Var->isStaticDataMember())
6996        Diag(Var->getLocation(),
6997             diag::err_constexpr_static_mem_var_requires_init)
6998          << Var->getDeclName();
6999      else
7000        Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
7001      Var->setInvalidDecl();
7002      return;
7003    }
7004
7005    switch (Var->isThisDeclarationADefinition()) {
7006    case VarDecl::Definition:
7007      if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
7008        break;
7009
7010      // We have an out-of-line definition of a static data member
7011      // that has an in-class initializer, so we type-check this like
7012      // a declaration.
7013      //
7014      // Fall through
7015
7016    case VarDecl::DeclarationOnly:
7017      // It's only a declaration.
7018
7019      // Block scope. C99 6.7p7: If an identifier for an object is
7020      // declared with no linkage (C99 6.2.2p6), the type for the
7021      // object shall be complete.
7022      if (!Type->isDependentType() && Var->isLocalVarDecl() &&
7023          !Var->getLinkage() && !Var->isInvalidDecl() &&
7024          RequireCompleteType(Var->getLocation(), Type,
7025                              diag::err_typecheck_decl_incomplete_type))
7026        Var->setInvalidDecl();
7027
7028      // Make sure that the type is not abstract.
7029      if (!Type->isDependentType() && !Var->isInvalidDecl() &&
7030          RequireNonAbstractType(Var->getLocation(), Type,
7031                                 diag::err_abstract_type_in_decl,
7032                                 AbstractVariableType))
7033        Var->setInvalidDecl();
7034      if (!Type->isDependentType() && !Var->isInvalidDecl() &&
7035          Var->getStorageClass() == SC_PrivateExtern) {
7036        Diag(Var->getLocation(), diag::warn_private_extern);
7037        Diag(Var->getLocation(), diag::note_private_extern);
7038      }
7039
7040      return;
7041
7042    case VarDecl::TentativeDefinition:
7043      // File scope. C99 6.9.2p2: A declaration of an identifier for an
7044      // object that has file scope without an initializer, and without a
7045      // storage-class specifier or with the storage-class specifier "static",
7046      // constitutes a tentative definition. Note: A tentative definition with
7047      // external linkage is valid (C99 6.2.2p5).
7048      if (!Var->isInvalidDecl()) {
7049        if (const IncompleteArrayType *ArrayT
7050                                    = Context.getAsIncompleteArrayType(Type)) {
7051          if (RequireCompleteType(Var->getLocation(),
7052                                  ArrayT->getElementType(),
7053                                  diag::err_illegal_decl_array_incomplete_type))
7054            Var->setInvalidDecl();
7055        } else if (Var->getStorageClass() == SC_Static) {
7056          // C99 6.9.2p3: If the declaration of an identifier for an object is
7057          // a tentative definition and has internal linkage (C99 6.2.2p3), the
7058          // declared type shall not be an incomplete type.
7059          // NOTE: code such as the following
7060          //     static struct s;
7061          //     struct s { int a; };
7062          // is accepted by gcc. Hence here we issue a warning instead of
7063          // an error and we do not invalidate the static declaration.
7064          // NOTE: to avoid multiple warnings, only check the first declaration.
7065          if (Var->getPreviousDecl() == 0)
7066            RequireCompleteType(Var->getLocation(), Type,
7067                                diag::ext_typecheck_decl_incomplete_type);
7068        }
7069      }
7070
7071      // Record the tentative definition; we're done.
7072      if (!Var->isInvalidDecl())
7073        TentativeDefinitions.push_back(Var);
7074      return;
7075    }
7076
7077    // Provide a specific diagnostic for uninitialized variable
7078    // definitions with incomplete array type.
7079    if (Type->isIncompleteArrayType()) {
7080      Diag(Var->getLocation(),
7081           diag::err_typecheck_incomplete_array_needs_initializer);
7082      Var->setInvalidDecl();
7083      return;
7084    }
7085
7086    // Provide a specific diagnostic for uninitialized variable
7087    // definitions with reference type.
7088    if (Type->isReferenceType()) {
7089      Diag(Var->getLocation(), diag::err_reference_var_requires_init)
7090        << Var->getDeclName()
7091        << SourceRange(Var->getLocation(), Var->getLocation());
7092      Var->setInvalidDecl();
7093      return;
7094    }
7095
7096    // Do not attempt to type-check the default initializer for a
7097    // variable with dependent type.
7098    if (Type->isDependentType())
7099      return;
7100
7101    if (Var->isInvalidDecl())
7102      return;
7103
7104    if (RequireCompleteType(Var->getLocation(),
7105                            Context.getBaseElementType(Type),
7106                            diag::err_typecheck_decl_incomplete_type)) {
7107      Var->setInvalidDecl();
7108      return;
7109    }
7110
7111    // The variable can not have an abstract class type.
7112    if (RequireNonAbstractType(Var->getLocation(), Type,
7113                               diag::err_abstract_type_in_decl,
7114                               AbstractVariableType)) {
7115      Var->setInvalidDecl();
7116      return;
7117    }
7118
7119    // Check for jumps past the implicit initializer.  C++0x
7120    // clarifies that this applies to a "variable with automatic
7121    // storage duration", not a "local variable".
7122    // C++11 [stmt.dcl]p3
7123    //   A program that jumps from a point where a variable with automatic
7124    //   storage duration is not in scope to a point where it is in scope is
7125    //   ill-formed unless the variable has scalar type, class type with a
7126    //   trivial default constructor and a trivial destructor, a cv-qualified
7127    //   version of one of these types, or an array of one of the preceding
7128    //   types and is declared without an initializer.
7129    if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
7130      if (const RecordType *Record
7131            = Context.getBaseElementType(Type)->getAs<RecordType>()) {
7132        CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
7133        // Mark the function for further checking even if the looser rules of
7134        // C++11 do not require such checks, so that we can diagnose
7135        // incompatibilities with C++98.
7136        if (!CXXRecord->isPOD())
7137          getCurFunction()->setHasBranchProtectedScope();
7138      }
7139    }
7140
7141    // C++03 [dcl.init]p9:
7142    //   If no initializer is specified for an object, and the
7143    //   object is of (possibly cv-qualified) non-POD class type (or
7144    //   array thereof), the object shall be default-initialized; if
7145    //   the object is of const-qualified type, the underlying class
7146    //   type shall have a user-declared default
7147    //   constructor. Otherwise, if no initializer is specified for
7148    //   a non- static object, the object and its subobjects, if
7149    //   any, have an indeterminate initial value); if the object
7150    //   or any of its subobjects are of const-qualified type, the
7151    //   program is ill-formed.
7152    // C++0x [dcl.init]p11:
7153    //   If no initializer is specified for an object, the object is
7154    //   default-initialized; [...].
7155    InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
7156    InitializationKind Kind
7157      = InitializationKind::CreateDefault(Var->getLocation());
7158
7159    InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
7160    ExprResult Init = InitSeq.Perform(*this, Entity, Kind, MultiExprArg());
7161    if (Init.isInvalid())
7162      Var->setInvalidDecl();
7163    else if (Init.get()) {
7164      Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
7165      // This is important for template substitution.
7166      Var->setInitStyle(VarDecl::CallInit);
7167    }
7168
7169    CheckCompleteVariableDeclaration(Var);
7170  }
7171}
7172
7173void Sema::ActOnCXXForRangeDecl(Decl *D) {
7174  VarDecl *VD = dyn_cast<VarDecl>(D);
7175  if (!VD) {
7176    Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
7177    D->setInvalidDecl();
7178    return;
7179  }
7180
7181  VD->setCXXForRangeDecl(true);
7182
7183  // for-range-declaration cannot be given a storage class specifier.
7184  int Error = -1;
7185  switch (VD->getStorageClassAsWritten()) {
7186  case SC_None:
7187    break;
7188  case SC_Extern:
7189    Error = 0;
7190    break;
7191  case SC_Static:
7192    Error = 1;
7193    break;
7194  case SC_PrivateExtern:
7195    Error = 2;
7196    break;
7197  case SC_Auto:
7198    Error = 3;
7199    break;
7200  case SC_Register:
7201    Error = 4;
7202    break;
7203  case SC_OpenCLWorkGroupLocal:
7204    llvm_unreachable("Unexpected storage class");
7205  }
7206  if (VD->isConstexpr())
7207    Error = 5;
7208  if (Error != -1) {
7209    Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
7210      << VD->getDeclName() << Error;
7211    D->setInvalidDecl();
7212  }
7213}
7214
7215void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
7216  if (var->isInvalidDecl()) return;
7217
7218  // In ARC, don't allow jumps past the implicit initialization of a
7219  // local retaining variable.
7220  if (getLangOpts().ObjCAutoRefCount &&
7221      var->hasLocalStorage()) {
7222    switch (var->getType().getObjCLifetime()) {
7223    case Qualifiers::OCL_None:
7224    case Qualifiers::OCL_ExplicitNone:
7225    case Qualifiers::OCL_Autoreleasing:
7226      break;
7227
7228    case Qualifiers::OCL_Weak:
7229    case Qualifiers::OCL_Strong:
7230      getCurFunction()->setHasBranchProtectedScope();
7231      break;
7232    }
7233  }
7234
7235  if (var->isThisDeclarationADefinition() &&
7236      var->getLinkage() == ExternalLinkage) {
7237    // Find a previous declaration that's not a definition.
7238    VarDecl *prev = var->getPreviousDecl();
7239    while (prev && prev->isThisDeclarationADefinition())
7240      prev = prev->getPreviousDecl();
7241
7242    if (!prev)
7243      Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
7244  }
7245
7246  // All the following checks are C++ only.
7247  if (!getLangOpts().CPlusPlus) return;
7248
7249  QualType type = var->getType();
7250  if (type->isDependentType()) return;
7251
7252  // __block variables might require us to capture a copy-initializer.
7253  if (var->hasAttr<BlocksAttr>()) {
7254    // It's currently invalid to ever have a __block variable with an
7255    // array type; should we diagnose that here?
7256
7257    // Regardless, we don't want to ignore array nesting when
7258    // constructing this copy.
7259    if (type->isStructureOrClassType()) {
7260      SourceLocation poi = var->getLocation();
7261      Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
7262      ExprResult result =
7263        PerformCopyInitialization(
7264                        InitializedEntity::InitializeBlock(poi, type, false),
7265                                  poi, Owned(varRef));
7266      if (!result.isInvalid()) {
7267        result = MaybeCreateExprWithCleanups(result);
7268        Expr *init = result.takeAs<Expr>();
7269        Context.setBlockVarCopyInits(var, init);
7270      }
7271    }
7272  }
7273
7274  Expr *Init = var->getInit();
7275  bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
7276  QualType baseType = Context.getBaseElementType(type);
7277
7278  if (!var->getDeclContext()->isDependentContext() &&
7279      Init && !Init->isValueDependent()) {
7280    if (IsGlobal && !var->isConstexpr() &&
7281        getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
7282                                            var->getLocation())
7283          != DiagnosticsEngine::Ignored &&
7284        !Init->isConstantInitializer(Context, baseType->isReferenceType()))
7285      Diag(var->getLocation(), diag::warn_global_constructor)
7286        << Init->getSourceRange();
7287
7288    if (var->isConstexpr()) {
7289      llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
7290      if (!var->evaluateValue(Notes) || !var->isInitICE()) {
7291        SourceLocation DiagLoc = var->getLocation();
7292        // If the note doesn't add any useful information other than a source
7293        // location, fold it into the primary diagnostic.
7294        if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
7295              diag::note_invalid_subexpr_in_const_expr) {
7296          DiagLoc = Notes[0].first;
7297          Notes.clear();
7298        }
7299        Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
7300          << var << Init->getSourceRange();
7301        for (unsigned I = 0, N = Notes.size(); I != N; ++I)
7302          Diag(Notes[I].first, Notes[I].second);
7303      }
7304    } else if (var->isUsableInConstantExpressions(Context)) {
7305      // Check whether the initializer of a const variable of integral or
7306      // enumeration type is an ICE now, since we can't tell whether it was
7307      // initialized by a constant expression if we check later.
7308      var->checkInitIsICE();
7309    }
7310  }
7311
7312  // Require the destructor.
7313  if (const RecordType *recordType = baseType->getAs<RecordType>())
7314    FinalizeVarWithDestructor(var, recordType);
7315}
7316
7317/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
7318/// any semantic actions necessary after any initializer has been attached.
7319void
7320Sema::FinalizeDeclaration(Decl *ThisDecl) {
7321  // Note that we are no longer parsing the initializer for this declaration.
7322  ParsingInitForAutoVars.erase(ThisDecl);
7323
7324  // Now we have parsed the initializer and can update the table of magic
7325  // tag values.
7326  if (ThisDecl && ThisDecl->hasAttr<TypeTagForDatatypeAttr>()) {
7327    const VarDecl *VD = dyn_cast<VarDecl>(ThisDecl);
7328    if (VD && VD->getType()->isIntegralOrEnumerationType()) {
7329      for (specific_attr_iterator<TypeTagForDatatypeAttr>
7330               I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(),
7331               E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>();
7332           I != E; ++I) {
7333        const Expr *MagicValueExpr = VD->getInit();
7334        if (!MagicValueExpr) {
7335          continue;
7336        }
7337        llvm::APSInt MagicValueInt;
7338        if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
7339          Diag(I->getRange().getBegin(),
7340               diag::err_type_tag_for_datatype_not_ice)
7341            << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
7342          continue;
7343        }
7344        if (MagicValueInt.getActiveBits() > 64) {
7345          Diag(I->getRange().getBegin(),
7346               diag::err_type_tag_for_datatype_too_large)
7347            << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
7348          continue;
7349        }
7350        uint64_t MagicValue = MagicValueInt.getZExtValue();
7351        RegisterTypeTagForDatatype(I->getArgumentKind(),
7352                                   MagicValue,
7353                                   I->getMatchingCType(),
7354                                   I->getLayoutCompatible(),
7355                                   I->getMustBeNull());
7356      }
7357    }
7358  }
7359}
7360
7361Sema::DeclGroupPtrTy
7362Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
7363                              Decl **Group, unsigned NumDecls) {
7364  SmallVector<Decl*, 8> Decls;
7365
7366  if (DS.isTypeSpecOwned())
7367    Decls.push_back(DS.getRepAsDecl());
7368
7369  for (unsigned i = 0; i != NumDecls; ++i)
7370    if (Decl *D = Group[i])
7371      Decls.push_back(D);
7372
7373  if (DeclSpec::isDeclRep(DS.getTypeSpecType()))
7374    if (const TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl()))
7375      getASTContext().addUnnamedTag(Tag);
7376
7377  return BuildDeclaratorGroup(Decls.data(), Decls.size(),
7378                              DS.getTypeSpecType() == DeclSpec::TST_auto);
7379}
7380
7381/// BuildDeclaratorGroup - convert a list of declarations into a declaration
7382/// group, performing any necessary semantic checking.
7383Sema::DeclGroupPtrTy
7384Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
7385                           bool TypeMayContainAuto) {
7386  // C++0x [dcl.spec.auto]p7:
7387  //   If the type deduced for the template parameter U is not the same in each
7388  //   deduction, the program is ill-formed.
7389  // FIXME: When initializer-list support is added, a distinction is needed
7390  // between the deduced type U and the deduced type which 'auto' stands for.
7391  //   auto a = 0, b = { 1, 2, 3 };
7392  // is legal because the deduced type U is 'int' in both cases.
7393  if (TypeMayContainAuto && NumDecls > 1) {
7394    QualType Deduced;
7395    CanQualType DeducedCanon;
7396    VarDecl *DeducedDecl = 0;
7397    for (unsigned i = 0; i != NumDecls; ++i) {
7398      if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
7399        AutoType *AT = D->getType()->getContainedAutoType();
7400        // Don't reissue diagnostics when instantiating a template.
7401        if (AT && D->isInvalidDecl())
7402          break;
7403        if (AT && AT->isDeduced()) {
7404          QualType U = AT->getDeducedType();
7405          CanQualType UCanon = Context.getCanonicalType(U);
7406          if (Deduced.isNull()) {
7407            Deduced = U;
7408            DeducedCanon = UCanon;
7409            DeducedDecl = D;
7410          } else if (DeducedCanon != UCanon) {
7411            Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
7412                 diag::err_auto_different_deductions)
7413              << Deduced << DeducedDecl->getDeclName()
7414              << U << D->getDeclName()
7415              << DeducedDecl->getInit()->getSourceRange()
7416              << D->getInit()->getSourceRange();
7417            D->setInvalidDecl();
7418            break;
7419          }
7420        }
7421      }
7422    }
7423  }
7424
7425  ActOnDocumentableDecls(Group, NumDecls);
7426
7427  return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls));
7428}
7429
7430void Sema::ActOnDocumentableDecl(Decl *D) {
7431  ActOnDocumentableDecls(&D, 1);
7432}
7433
7434void Sema::ActOnDocumentableDecls(Decl **Group, unsigned NumDecls) {
7435  // Don't parse the comment if Doxygen diagnostics are ignored.
7436  if (NumDecls == 0 || !Group[0])
7437   return;
7438
7439  if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
7440                               Group[0]->getLocation())
7441        == DiagnosticsEngine::Ignored)
7442    return;
7443
7444  if (NumDecls >= 2) {
7445    // This is a decl group.  Normally it will contain only declarations
7446    // procuded from declarator list.  But in case we have any definitions or
7447    // additional declaration references:
7448    //   'typedef struct S {} S;'
7449    //   'typedef struct S *S;'
7450    //   'struct S *pS;'
7451    // FinalizeDeclaratorGroup adds these as separate declarations.
7452    Decl *MaybeTagDecl = Group[0];
7453    if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
7454      Group++;
7455      NumDecls--;
7456    }
7457  }
7458
7459  // See if there are any new comments that are not attached to a decl.
7460  ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
7461  if (!Comments.empty() &&
7462      !Comments.back()->isAttached()) {
7463    // There is at least one comment that not attached to a decl.
7464    // Maybe it should be attached to one of these decls?
7465    //
7466    // Note that this way we pick up not only comments that precede the
7467    // declaration, but also comments that *follow* the declaration -- thanks to
7468    // the lookahead in the lexer: we've consumed the semicolon and looked
7469    // ahead through comments.
7470    for (unsigned i = 0; i != NumDecls; ++i)
7471      Context.getCommentForDecl(Group[i], &PP);
7472  }
7473}
7474
7475/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
7476/// to introduce parameters into function prototype scope.
7477Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
7478  const DeclSpec &DS = D.getDeclSpec();
7479
7480  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
7481  // C++03 [dcl.stc]p2 also permits 'auto'.
7482  VarDecl::StorageClass StorageClass = SC_None;
7483  VarDecl::StorageClass StorageClassAsWritten = SC_None;
7484  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
7485    StorageClass = SC_Register;
7486    StorageClassAsWritten = SC_Register;
7487  } else if (getLangOpts().CPlusPlus &&
7488             DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
7489    StorageClass = SC_Auto;
7490    StorageClassAsWritten = SC_Auto;
7491  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
7492    Diag(DS.getStorageClassSpecLoc(),
7493         diag::err_invalid_storage_class_in_func_decl);
7494    D.getMutableDeclSpec().ClearStorageClassSpecs();
7495  }
7496
7497  if (D.getDeclSpec().isThreadSpecified())
7498    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
7499  if (D.getDeclSpec().isConstexprSpecified())
7500    Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
7501      << 0;
7502
7503  DiagnoseFunctionSpecifiers(D);
7504
7505  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
7506  QualType parmDeclType = TInfo->getType();
7507
7508  if (getLangOpts().CPlusPlus) {
7509    // Check that there are no default arguments inside the type of this
7510    // parameter.
7511    CheckExtraCXXDefaultArguments(D);
7512
7513    // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
7514    if (D.getCXXScopeSpec().isSet()) {
7515      Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
7516        << D.getCXXScopeSpec().getRange();
7517      D.getCXXScopeSpec().clear();
7518    }
7519  }
7520
7521  // Ensure we have a valid name
7522  IdentifierInfo *II = 0;
7523  if (D.hasName()) {
7524    II = D.getIdentifier();
7525    if (!II) {
7526      Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
7527        << GetNameForDeclarator(D).getName().getAsString();
7528      D.setInvalidType(true);
7529    }
7530  }
7531
7532  // Check for redeclaration of parameters, e.g. int foo(int x, int x);
7533  if (II) {
7534    LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
7535                   ForRedeclaration);
7536    LookupName(R, S);
7537    if (R.isSingleResult()) {
7538      NamedDecl *PrevDecl = R.getFoundDecl();
7539      if (PrevDecl->isTemplateParameter()) {
7540        // Maybe we will complain about the shadowed template parameter.
7541        DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
7542        // Just pretend that we didn't see the previous declaration.
7543        PrevDecl = 0;
7544      } else if (S->isDeclScope(PrevDecl)) {
7545        Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
7546        Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
7547
7548        // Recover by removing the name
7549        II = 0;
7550        D.SetIdentifier(0, D.getIdentifierLoc());
7551        D.setInvalidType(true);
7552      }
7553    }
7554  }
7555
7556  // Temporarily put parameter variables in the translation unit, not
7557  // the enclosing context.  This prevents them from accidentally
7558  // looking like class members in C++.
7559  ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
7560                                    D.getLocStart(),
7561                                    D.getIdentifierLoc(), II,
7562                                    parmDeclType, TInfo,
7563                                    StorageClass, StorageClassAsWritten);
7564
7565  if (D.isInvalidType())
7566    New->setInvalidDecl();
7567
7568  assert(S->isFunctionPrototypeScope());
7569  assert(S->getFunctionPrototypeDepth() >= 1);
7570  New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
7571                    S->getNextFunctionPrototypeIndex());
7572
7573  // Add the parameter declaration into this scope.
7574  S->AddDecl(New);
7575  if (II)
7576    IdResolver.AddDecl(New);
7577
7578  ProcessDeclAttributes(S, New, D);
7579
7580  if (D.getDeclSpec().isModulePrivateSpecified())
7581    Diag(New->getLocation(), diag::err_module_private_local)
7582      << 1 << New->getDeclName()
7583      << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7584      << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7585
7586  if (New->hasAttr<BlocksAttr>()) {
7587    Diag(New->getLocation(), diag::err_block_on_nonlocal);
7588  }
7589  return New;
7590}
7591
7592/// \brief Synthesizes a variable for a parameter arising from a
7593/// typedef.
7594ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
7595                                              SourceLocation Loc,
7596                                              QualType T) {
7597  /* FIXME: setting StartLoc == Loc.
7598     Would it be worth to modify callers so as to provide proper source
7599     location for the unnamed parameters, embedding the parameter's type? */
7600  ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
7601                                T, Context.getTrivialTypeSourceInfo(T, Loc),
7602                                           SC_None, SC_None, 0);
7603  Param->setImplicit();
7604  return Param;
7605}
7606
7607void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
7608                                    ParmVarDecl * const *ParamEnd) {
7609  // Don't diagnose unused-parameter errors in template instantiations; we
7610  // will already have done so in the template itself.
7611  if (!ActiveTemplateInstantiations.empty())
7612    return;
7613
7614  for (; Param != ParamEnd; ++Param) {
7615    if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
7616        !(*Param)->hasAttr<UnusedAttr>()) {
7617      Diag((*Param)->getLocation(), diag::warn_unused_parameter)
7618        << (*Param)->getDeclName();
7619    }
7620  }
7621}
7622
7623void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
7624                                                  ParmVarDecl * const *ParamEnd,
7625                                                  QualType ReturnTy,
7626                                                  NamedDecl *D) {
7627  if (LangOpts.NumLargeByValueCopy == 0) // No check.
7628    return;
7629
7630  // Warn if the return value is pass-by-value and larger than the specified
7631  // threshold.
7632  if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
7633    unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
7634    if (Size > LangOpts.NumLargeByValueCopy)
7635      Diag(D->getLocation(), diag::warn_return_value_size)
7636          << D->getDeclName() << Size;
7637  }
7638
7639  // Warn if any parameter is pass-by-value and larger than the specified
7640  // threshold.
7641  for (; Param != ParamEnd; ++Param) {
7642    QualType T = (*Param)->getType();
7643    if (T->isDependentType() || !T.isPODType(Context))
7644      continue;
7645    unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
7646    if (Size > LangOpts.NumLargeByValueCopy)
7647      Diag((*Param)->getLocation(), diag::warn_parameter_size)
7648          << (*Param)->getDeclName() << Size;
7649  }
7650}
7651
7652ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
7653                                  SourceLocation NameLoc, IdentifierInfo *Name,
7654                                  QualType T, TypeSourceInfo *TSInfo,
7655                                  VarDecl::StorageClass StorageClass,
7656                                  VarDecl::StorageClass StorageClassAsWritten) {
7657  // In ARC, infer a lifetime qualifier for appropriate parameter types.
7658  if (getLangOpts().ObjCAutoRefCount &&
7659      T.getObjCLifetime() == Qualifiers::OCL_None &&
7660      T->isObjCLifetimeType()) {
7661
7662    Qualifiers::ObjCLifetime lifetime;
7663
7664    // Special cases for arrays:
7665    //   - if it's const, use __unsafe_unretained
7666    //   - otherwise, it's an error
7667    if (T->isArrayType()) {
7668      if (!T.isConstQualified()) {
7669        DelayedDiagnostics.add(
7670            sema::DelayedDiagnostic::makeForbiddenType(
7671            NameLoc, diag::err_arc_array_param_no_ownership, T, false));
7672      }
7673      lifetime = Qualifiers::OCL_ExplicitNone;
7674    } else {
7675      lifetime = T->getObjCARCImplicitLifetime();
7676    }
7677    T = Context.getLifetimeQualifiedType(T, lifetime);
7678  }
7679
7680  ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
7681                                         Context.getAdjustedParameterType(T),
7682                                         TSInfo,
7683                                         StorageClass, StorageClassAsWritten,
7684                                         0);
7685
7686  // Parameters can not be abstract class types.
7687  // For record types, this is done by the AbstractClassUsageDiagnoser once
7688  // the class has been completely parsed.
7689  if (!CurContext->isRecord() &&
7690      RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
7691                             AbstractParamType))
7692    New->setInvalidDecl();
7693
7694  // Parameter declarators cannot be interface types. All ObjC objects are
7695  // passed by reference.
7696  if (T->isObjCObjectType()) {
7697    SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
7698    Diag(NameLoc,
7699         diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
7700      << FixItHint::CreateInsertion(TypeEndLoc, "*");
7701    T = Context.getObjCObjectPointerType(T);
7702    New->setType(T);
7703  }
7704
7705  // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
7706  // duration shall not be qualified by an address-space qualifier."
7707  // Since all parameters have automatic store duration, they can not have
7708  // an address space.
7709  if (T.getAddressSpace() != 0) {
7710    Diag(NameLoc, diag::err_arg_with_address_space);
7711    New->setInvalidDecl();
7712  }
7713
7714  return New;
7715}
7716
7717void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
7718                                           SourceLocation LocAfterDecls) {
7719  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7720
7721  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
7722  // for a K&R function.
7723  if (!FTI.hasPrototype) {
7724    for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
7725      --i;
7726      if (FTI.ArgInfo[i].Param == 0) {
7727        SmallString<256> Code;
7728        llvm::raw_svector_ostream(Code) << "  int "
7729                                        << FTI.ArgInfo[i].Ident->getName()
7730                                        << ";\n";
7731        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
7732          << FTI.ArgInfo[i].Ident
7733          << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
7734
7735        // Implicitly declare the argument as type 'int' for lack of a better
7736        // type.
7737        AttributeFactory attrs;
7738        DeclSpec DS(attrs);
7739        const char* PrevSpec; // unused
7740        unsigned DiagID; // unused
7741        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
7742                           PrevSpec, DiagID);
7743        // Use the identifier location for the type source range.
7744        DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc);
7745        DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc);
7746        Declarator ParamD(DS, Declarator::KNRTypeListContext);
7747        ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
7748        FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
7749      }
7750    }
7751  }
7752}
7753
7754Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
7755  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
7756  assert(D.isFunctionDeclarator() && "Not a function declarator!");
7757  Scope *ParentScope = FnBodyScope->getParent();
7758
7759  D.setFunctionDefinitionKind(FDK_Definition);
7760  Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
7761  return ActOnStartOfFunctionDef(FnBodyScope, DP);
7762}
7763
7764static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
7765  // Don't warn about invalid declarations.
7766  if (FD->isInvalidDecl())
7767    return false;
7768
7769  // Or declarations that aren't global.
7770  if (!FD->isGlobal())
7771    return false;
7772
7773  // Don't warn about C++ member functions.
7774  if (isa<CXXMethodDecl>(FD))
7775    return false;
7776
7777  // Don't warn about 'main'.
7778  if (FD->isMain())
7779    return false;
7780
7781  // Don't warn about inline functions.
7782  if (FD->isInlined())
7783    return false;
7784
7785  // Don't warn about function templates.
7786  if (FD->getDescribedFunctionTemplate())
7787    return false;
7788
7789  // Don't warn about function template specializations.
7790  if (FD->isFunctionTemplateSpecialization())
7791    return false;
7792
7793  // Don't warn for OpenCL kernels.
7794  if (FD->hasAttr<OpenCLKernelAttr>())
7795    return false;
7796
7797  bool MissingPrototype = true;
7798  for (const FunctionDecl *Prev = FD->getPreviousDecl();
7799       Prev; Prev = Prev->getPreviousDecl()) {
7800    // Ignore any declarations that occur in function or method
7801    // scope, because they aren't visible from the header.
7802    if (Prev->getDeclContext()->isFunctionOrMethod())
7803      continue;
7804
7805    MissingPrototype = !Prev->getType()->isFunctionProtoType();
7806    break;
7807  }
7808
7809  return MissingPrototype;
7810}
7811
7812void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) {
7813  // Don't complain if we're in GNU89 mode and the previous definition
7814  // was an extern inline function.
7815  const FunctionDecl *Definition;
7816  if (FD->isDefined(Definition) &&
7817      !canRedefineFunction(Definition, getLangOpts())) {
7818    if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
7819        Definition->getStorageClass() == SC_Extern)
7820      Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
7821        << FD->getDeclName() << getLangOpts().CPlusPlus;
7822    else
7823      Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
7824    Diag(Definition->getLocation(), diag::note_previous_definition);
7825    FD->setInvalidDecl();
7826  }
7827}
7828
7829Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
7830  // Clear the last template instantiation error context.
7831  LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
7832
7833  if (!D)
7834    return D;
7835  FunctionDecl *FD = 0;
7836
7837  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
7838    FD = FunTmpl->getTemplatedDecl();
7839  else
7840    FD = cast<FunctionDecl>(D);
7841
7842  // Enter a new function scope
7843  PushFunctionScope();
7844
7845  // See if this is a redefinition.
7846  if (!FD->isLateTemplateParsed())
7847    CheckForFunctionRedefinition(FD);
7848
7849  // Builtin functions cannot be defined.
7850  if (unsigned BuiltinID = FD->getBuiltinID()) {
7851    if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
7852      Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
7853      FD->setInvalidDecl();
7854    }
7855  }
7856
7857  // The return type of a function definition must be complete
7858  // (C99 6.9.1p3, C++ [dcl.fct]p6).
7859  QualType ResultType = FD->getResultType();
7860  if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
7861      !FD->isInvalidDecl() &&
7862      RequireCompleteType(FD->getLocation(), ResultType,
7863                          diag::err_func_def_incomplete_result))
7864    FD->setInvalidDecl();
7865
7866  // GNU warning -Wmissing-prototypes:
7867  //   Warn if a global function is defined without a previous
7868  //   prototype declaration. This warning is issued even if the
7869  //   definition itself provides a prototype. The aim is to detect
7870  //   global functions that fail to be declared in header files.
7871  if (ShouldWarnAboutMissingPrototype(FD))
7872    Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
7873
7874  if (FnBodyScope)
7875    PushDeclContext(FnBodyScope, FD);
7876
7877  // Check the validity of our function parameters
7878  CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
7879                           /*CheckParameterNames=*/true);
7880
7881  // Introduce our parameters into the function scope
7882  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
7883    ParmVarDecl *Param = FD->getParamDecl(p);
7884    Param->setOwningFunction(FD);
7885
7886    // If this has an identifier, add it to the scope stack.
7887    if (Param->getIdentifier() && FnBodyScope) {
7888      CheckShadow(FnBodyScope, Param);
7889
7890      PushOnScopeChains(Param, FnBodyScope);
7891    }
7892  }
7893
7894  // If we had any tags defined in the function prototype,
7895  // introduce them into the function scope.
7896  if (FnBodyScope) {
7897    for (llvm::ArrayRef<NamedDecl*>::iterator I = FD->getDeclsInPrototypeScope().begin(),
7898           E = FD->getDeclsInPrototypeScope().end(); I != E; ++I) {
7899      NamedDecl *D = *I;
7900
7901      // Some of these decls (like enums) may have been pinned to the translation unit
7902      // for lack of a real context earlier. If so, remove from the translation unit
7903      // and reattach to the current context.
7904      if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
7905        // Is the decl actually in the context?
7906        for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
7907               DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
7908          if (*DI == D) {
7909            Context.getTranslationUnitDecl()->removeDecl(D);
7910            break;
7911          }
7912        }
7913        // Either way, reassign the lexical decl context to our FunctionDecl.
7914        D->setLexicalDeclContext(CurContext);
7915      }
7916
7917      // If the decl has a non-null name, make accessible in the current scope.
7918      if (!D->getName().empty())
7919        PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
7920
7921      // Similarly, dive into enums and fish their constants out, making them
7922      // accessible in this scope.
7923      if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
7924        for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
7925               EE = ED->enumerator_end(); EI != EE; ++EI)
7926          PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
7927      }
7928    }
7929  }
7930
7931  // Ensure that the function's exception specification is instantiated.
7932  if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
7933    ResolveExceptionSpec(D->getLocation(), FPT);
7934
7935  // Checking attributes of current function definition
7936  // dllimport attribute.
7937  DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
7938  if (DA && (!FD->getAttr<DLLExportAttr>())) {
7939    // dllimport attribute cannot be directly applied to definition.
7940    // Microsoft accepts dllimport for functions defined within class scope.
7941    if (!DA->isInherited() &&
7942        !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
7943      Diag(FD->getLocation(),
7944           diag::err_attribute_can_be_applied_only_to_symbol_declaration)
7945        << "dllimport";
7946      FD->setInvalidDecl();
7947      return FD;
7948    }
7949
7950    // Visual C++ appears to not think this is an issue, so only issue
7951    // a warning when Microsoft extensions are disabled.
7952    if (!LangOpts.MicrosoftExt) {
7953      // If a symbol previously declared dllimport is later defined, the
7954      // attribute is ignored in subsequent references, and a warning is
7955      // emitted.
7956      Diag(FD->getLocation(),
7957           diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7958        << FD->getName() << "dllimport";
7959    }
7960  }
7961  // We want to attach documentation to original Decl (which might be
7962  // a function template).
7963  ActOnDocumentableDecl(D);
7964  return FD;
7965}
7966
7967/// \brief Given the set of return statements within a function body,
7968/// compute the variables that are subject to the named return value
7969/// optimization.
7970///
7971/// Each of the variables that is subject to the named return value
7972/// optimization will be marked as NRVO variables in the AST, and any
7973/// return statement that has a marked NRVO variable as its NRVO candidate can
7974/// use the named return value optimization.
7975///
7976/// This function applies a very simplistic algorithm for NRVO: if every return
7977/// statement in the function has the same NRVO candidate, that candidate is
7978/// the NRVO variable.
7979///
7980/// FIXME: Employ a smarter algorithm that accounts for multiple return
7981/// statements and the lifetimes of the NRVO candidates. We should be able to
7982/// find a maximal set of NRVO variables.
7983void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
7984  ReturnStmt **Returns = Scope->Returns.data();
7985
7986  const VarDecl *NRVOCandidate = 0;
7987  for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
7988    if (!Returns[I]->getNRVOCandidate())
7989      return;
7990
7991    if (!NRVOCandidate)
7992      NRVOCandidate = Returns[I]->getNRVOCandidate();
7993    else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
7994      return;
7995  }
7996
7997  if (NRVOCandidate)
7998    const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
7999}
8000
8001bool Sema::canSkipFunctionBody(Decl *D) {
8002  if (!Consumer.shouldSkipFunctionBody(D))
8003    return false;
8004
8005  if (isa<ObjCMethodDecl>(D))
8006    return true;
8007
8008  FunctionDecl *FD = 0;
8009  if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
8010    FD = FTD->getTemplatedDecl();
8011  else
8012    FD = cast<FunctionDecl>(D);
8013
8014  // We cannot skip the body of a function (or function template) which is
8015  // constexpr, since we may need to evaluate its body in order to parse the
8016  // rest of the file.
8017  return !FD->isConstexpr();
8018}
8019
8020Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
8021  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl))
8022    FD->setHasSkippedBody();
8023  else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
8024    MD->setHasSkippedBody();
8025  return ActOnFinishFunctionBody(Decl, 0);
8026}
8027
8028Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
8029  return ActOnFinishFunctionBody(D, BodyArg, false);
8030}
8031
8032Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
8033                                    bool IsInstantiation) {
8034  FunctionDecl *FD = 0;
8035  FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
8036  if (FunTmpl)
8037    FD = FunTmpl->getTemplatedDecl();
8038  else
8039    FD = dyn_cast_or_null<FunctionDecl>(dcl);
8040
8041  sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
8042  sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
8043
8044  if (FD) {
8045    FD->setBody(Body);
8046
8047    // If the function implicitly returns zero (like 'main') or is naked,
8048    // don't complain about missing return statements.
8049    if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
8050      WP.disableCheckFallThrough();
8051
8052    // MSVC permits the use of pure specifier (=0) on function definition,
8053    // defined at class scope, warn about this non standard construct.
8054    if (getLangOpts().MicrosoftExt && FD->isPure())
8055      Diag(FD->getLocation(), diag::warn_pure_function_definition);
8056
8057    if (!FD->isInvalidDecl()) {
8058      DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
8059      DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
8060                                             FD->getResultType(), FD);
8061
8062      // If this is a constructor, we need a vtable.
8063      if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
8064        MarkVTableUsed(FD->getLocation(), Constructor->getParent());
8065
8066      // Try to apply the named return value optimization. We have to check
8067      // if we can do this here because lambdas keep return statements around
8068      // to deduce an implicit return type.
8069      if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() &&
8070          !FD->isDependentContext())
8071        computeNRVO(Body, getCurFunction());
8072    }
8073
8074    assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
8075           "Function parsing confused");
8076  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
8077    assert(MD == getCurMethodDecl() && "Method parsing confused");
8078    MD->setBody(Body);
8079    if (!MD->isInvalidDecl()) {
8080      DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
8081      DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
8082                                             MD->getResultType(), MD);
8083
8084      if (Body)
8085        computeNRVO(Body, getCurFunction());
8086    }
8087    if (getCurFunction()->ObjCShouldCallSuper) {
8088      Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
8089        << MD->getSelector().getAsString();
8090      getCurFunction()->ObjCShouldCallSuper = false;
8091    }
8092  } else {
8093    return 0;
8094  }
8095
8096  assert(!getCurFunction()->ObjCShouldCallSuper &&
8097         "This should only be set for ObjC methods, which should have been "
8098         "handled in the block above.");
8099
8100  // Verify and clean out per-function state.
8101  if (Body) {
8102    // C++ constructors that have function-try-blocks can't have return
8103    // statements in the handlers of that block. (C++ [except.handle]p14)
8104    // Verify this.
8105    if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
8106      DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
8107
8108    // Verify that gotos and switch cases don't jump into scopes illegally.
8109    if (getCurFunction()->NeedsScopeChecking() &&
8110        !dcl->isInvalidDecl() &&
8111        !hasAnyUnrecoverableErrorsInThisFunction() &&
8112        !PP.isCodeCompletionEnabled())
8113      DiagnoseInvalidJumps(Body);
8114
8115    if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
8116      if (!Destructor->getParent()->isDependentType())
8117        CheckDestructor(Destructor);
8118
8119      MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8120                                             Destructor->getParent());
8121    }
8122
8123    // If any errors have occurred, clear out any temporaries that may have
8124    // been leftover. This ensures that these temporaries won't be picked up for
8125    // deletion in some later function.
8126    if (PP.getDiagnostics().hasErrorOccurred() ||
8127        PP.getDiagnostics().getSuppressAllDiagnostics()) {
8128      DiscardCleanupsInEvaluationContext();
8129    }
8130    if (!PP.getDiagnostics().hasUncompilableErrorOccurred() &&
8131        !isa<FunctionTemplateDecl>(dcl)) {
8132      // Since the body is valid, issue any analysis-based warnings that are
8133      // enabled.
8134      ActivePolicy = &WP;
8135    }
8136
8137    if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
8138        (!CheckConstexprFunctionDecl(FD) ||
8139         !CheckConstexprFunctionBody(FD, Body)))
8140      FD->setInvalidDecl();
8141
8142    assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
8143    assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
8144    assert(MaybeODRUseExprs.empty() &&
8145           "Leftover expressions for odr-use checking");
8146  }
8147
8148  if (!IsInstantiation)
8149    PopDeclContext();
8150
8151  PopFunctionScopeInfo(ActivePolicy, dcl);
8152
8153  // If any errors have occurred, clear out any temporaries that may have
8154  // been leftover. This ensures that these temporaries won't be picked up for
8155  // deletion in some later function.
8156  if (getDiagnostics().hasErrorOccurred()) {
8157    DiscardCleanupsInEvaluationContext();
8158  }
8159
8160  return dcl;
8161}
8162
8163
8164/// When we finish delayed parsing of an attribute, we must attach it to the
8165/// relevant Decl.
8166void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
8167                                       ParsedAttributes &Attrs) {
8168  // Always attach attributes to the underlying decl.
8169  if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
8170    D = TD->getTemplatedDecl();
8171  ProcessDeclAttributeList(S, D, Attrs.getList());
8172
8173  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
8174    if (Method->isStatic())
8175      checkThisInStaticMemberFunctionAttributes(Method);
8176}
8177
8178
8179/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
8180/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
8181NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
8182                                          IdentifierInfo &II, Scope *S) {
8183  // Before we produce a declaration for an implicitly defined
8184  // function, see whether there was a locally-scoped declaration of
8185  // this name as a function or variable. If so, use that
8186  // (non-visible) declaration, and complain about it.
8187  llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
8188    = findLocallyScopedExternalDecl(&II);
8189  if (Pos != LocallyScopedExternalDecls.end()) {
8190    Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
8191    Diag(Pos->second->getLocation(), diag::note_previous_declaration);
8192    return Pos->second;
8193  }
8194
8195  // Extension in C99.  Legal in C90, but warn about it.
8196  unsigned diag_id;
8197  if (II.getName().startswith("__builtin_"))
8198    diag_id = diag::warn_builtin_unknown;
8199  else if (getLangOpts().C99)
8200    diag_id = diag::ext_implicit_function_decl;
8201  else
8202    diag_id = diag::warn_implicit_function_decl;
8203  Diag(Loc, diag_id) << &II;
8204
8205  // Because typo correction is expensive, only do it if the implicit
8206  // function declaration is going to be treated as an error.
8207  if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
8208    TypoCorrection Corrected;
8209    DeclFilterCCC<FunctionDecl> Validator;
8210    if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
8211                                      LookupOrdinaryName, S, 0, Validator))) {
8212      std::string CorrectedStr = Corrected.getAsString(getLangOpts());
8213      std::string CorrectedQuotedStr = Corrected.getQuoted(getLangOpts());
8214      FunctionDecl *Func = Corrected.getCorrectionDeclAs<FunctionDecl>();
8215
8216      Diag(Loc, diag::note_function_suggestion) << CorrectedQuotedStr
8217          << FixItHint::CreateReplacement(Loc, CorrectedStr);
8218
8219      if (Func->getLocation().isValid()
8220          && !II.getName().startswith("__builtin_"))
8221        Diag(Func->getLocation(), diag::note_previous_decl)
8222            << CorrectedQuotedStr;
8223    }
8224  }
8225
8226  // Set a Declarator for the implicit definition: int foo();
8227  const char *Dummy;
8228  AttributeFactory attrFactory;
8229  DeclSpec DS(attrFactory);
8230  unsigned DiagID;
8231  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
8232  (void)Error; // Silence warning.
8233  assert(!Error && "Error setting up implicit decl!");
8234  SourceLocation NoLoc;
8235  Declarator D(DS, Declarator::BlockContext);
8236  D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
8237                                             /*IsAmbiguous=*/false,
8238                                             /*RParenLoc=*/NoLoc,
8239                                             /*ArgInfo=*/0,
8240                                             /*NumArgs=*/0,
8241                                             /*EllipsisLoc=*/NoLoc,
8242                                             /*RParenLoc=*/NoLoc,
8243                                             /*TypeQuals=*/0,
8244                                             /*RefQualifierIsLvalueRef=*/true,
8245                                             /*RefQualifierLoc=*/NoLoc,
8246                                             /*ConstQualifierLoc=*/NoLoc,
8247                                             /*VolatileQualifierLoc=*/NoLoc,
8248                                             /*MutableLoc=*/NoLoc,
8249                                             EST_None,
8250                                             /*ESpecLoc=*/NoLoc,
8251                                             /*Exceptions=*/0,
8252                                             /*ExceptionRanges=*/0,
8253                                             /*NumExceptions=*/0,
8254                                             /*NoexceptExpr=*/0,
8255                                             Loc, Loc, D),
8256                DS.getAttributes(),
8257                SourceLocation());
8258  D.SetIdentifier(&II, Loc);
8259
8260  // Insert this function into translation-unit scope.
8261
8262  DeclContext *PrevDC = CurContext;
8263  CurContext = Context.getTranslationUnitDecl();
8264
8265  FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
8266  FD->setImplicit();
8267
8268  CurContext = PrevDC;
8269
8270  AddKnownFunctionAttributes(FD);
8271
8272  return FD;
8273}
8274
8275/// \brief Adds any function attributes that we know a priori based on
8276/// the declaration of this function.
8277///
8278/// These attributes can apply both to implicitly-declared builtins
8279/// (like __builtin___printf_chk) or to library-declared functions
8280/// like NSLog or printf.
8281///
8282/// We need to check for duplicate attributes both here and where user-written
8283/// attributes are applied to declarations.
8284void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
8285  if (FD->isInvalidDecl())
8286    return;
8287
8288  // If this is a built-in function, map its builtin attributes to
8289  // actual attributes.
8290  if (unsigned BuiltinID = FD->getBuiltinID()) {
8291    // Handle printf-formatting attributes.
8292    unsigned FormatIdx;
8293    bool HasVAListArg;
8294    if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
8295      if (!FD->getAttr<FormatAttr>()) {
8296        const char *fmt = "printf";
8297        unsigned int NumParams = FD->getNumParams();
8298        if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
8299            FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
8300          fmt = "NSString";
8301        FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
8302                                               fmt, FormatIdx+1,
8303                                               HasVAListArg ? 0 : FormatIdx+2));
8304      }
8305    }
8306    if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
8307                                             HasVAListArg)) {
8308     if (!FD->getAttr<FormatAttr>())
8309       FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
8310                                              "scanf", FormatIdx+1,
8311                                              HasVAListArg ? 0 : FormatIdx+2));
8312    }
8313
8314    // Mark const if we don't care about errno and that is the only
8315    // thing preventing the function from being const. This allows
8316    // IRgen to use LLVM intrinsics for such functions.
8317    if (!getLangOpts().MathErrno &&
8318        Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
8319      if (!FD->getAttr<ConstAttr>())
8320        FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
8321    }
8322
8323    if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
8324        !FD->getAttr<ReturnsTwiceAttr>())
8325      FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
8326    if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
8327      FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
8328    if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
8329      FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
8330  }
8331
8332  IdentifierInfo *Name = FD->getIdentifier();
8333  if (!Name)
8334    return;
8335  if ((!getLangOpts().CPlusPlus &&
8336       FD->getDeclContext()->isTranslationUnit()) ||
8337      (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
8338       cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
8339       LinkageSpecDecl::lang_c)) {
8340    // Okay: this could be a libc/libm/Objective-C function we know
8341    // about.
8342  } else
8343    return;
8344
8345  if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
8346    // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
8347    // target-specific builtins, perhaps?
8348    if (!FD->getAttr<FormatAttr>())
8349      FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
8350                                             "printf", 2,
8351                                             Name->isStr("vasprintf") ? 0 : 3));
8352  }
8353
8354  if (Name->isStr("__CFStringMakeConstantString")) {
8355    // We already have a __builtin___CFStringMakeConstantString,
8356    // but builds that use -fno-constant-cfstrings don't go through that.
8357    if (!FD->getAttr<FormatArgAttr>())
8358      FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1));
8359  }
8360}
8361
8362TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
8363                                    TypeSourceInfo *TInfo) {
8364  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
8365  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
8366
8367  if (!TInfo) {
8368    assert(D.isInvalidType() && "no declarator info for valid type");
8369    TInfo = Context.getTrivialTypeSourceInfo(T);
8370  }
8371
8372  // Scope manipulation handled by caller.
8373  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
8374                                           D.getLocStart(),
8375                                           D.getIdentifierLoc(),
8376                                           D.getIdentifier(),
8377                                           TInfo);
8378
8379  // Bail out immediately if we have an invalid declaration.
8380  if (D.isInvalidType()) {
8381    NewTD->setInvalidDecl();
8382    return NewTD;
8383  }
8384
8385  if (D.getDeclSpec().isModulePrivateSpecified()) {
8386    if (CurContext->isFunctionOrMethod())
8387      Diag(NewTD->getLocation(), diag::err_module_private_local)
8388        << 2 << NewTD->getDeclName()
8389        << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
8390        << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
8391    else
8392      NewTD->setModulePrivate();
8393  }
8394
8395  // C++ [dcl.typedef]p8:
8396  //   If the typedef declaration defines an unnamed class (or
8397  //   enum), the first typedef-name declared by the declaration
8398  //   to be that class type (or enum type) is used to denote the
8399  //   class type (or enum type) for linkage purposes only.
8400  // We need to check whether the type was declared in the declaration.
8401  switch (D.getDeclSpec().getTypeSpecType()) {
8402  case TST_enum:
8403  case TST_struct:
8404  case TST_interface:
8405  case TST_union:
8406  case TST_class: {
8407    TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
8408
8409    // Do nothing if the tag is not anonymous or already has an
8410    // associated typedef (from an earlier typedef in this decl group).
8411    if (tagFromDeclSpec->getIdentifier()) break;
8412    if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
8413
8414    // A well-formed anonymous tag must always be a TUK_Definition.
8415    assert(tagFromDeclSpec->isThisDeclarationADefinition());
8416
8417    // The type must match the tag exactly;  no qualifiers allowed.
8418    if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
8419      break;
8420
8421    // Otherwise, set this is the anon-decl typedef for the tag.
8422    tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
8423    break;
8424  }
8425
8426  default:
8427    break;
8428  }
8429
8430  return NewTD;
8431}
8432
8433
8434/// \brief Check that this is a valid underlying type for an enum declaration.
8435bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
8436  SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
8437  QualType T = TI->getType();
8438
8439  if (T->isDependentType() || T->isIntegralType(Context))
8440    return false;
8441
8442  Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
8443  return true;
8444}
8445
8446/// Check whether this is a valid redeclaration of a previous enumeration.
8447/// \return true if the redeclaration was invalid.
8448bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
8449                                  QualType EnumUnderlyingTy,
8450                                  const EnumDecl *Prev) {
8451  bool IsFixed = !EnumUnderlyingTy.isNull();
8452
8453  if (IsScoped != Prev->isScoped()) {
8454    Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
8455      << Prev->isScoped();
8456    Diag(Prev->getLocation(), diag::note_previous_use);
8457    return true;
8458  }
8459
8460  if (IsFixed && Prev->isFixed()) {
8461    if (!EnumUnderlyingTy->isDependentType() &&
8462        !Prev->getIntegerType()->isDependentType() &&
8463        !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
8464                                        Prev->getIntegerType())) {
8465      Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
8466        << EnumUnderlyingTy << Prev->getIntegerType();
8467      Diag(Prev->getLocation(), diag::note_previous_use);
8468      return true;
8469    }
8470  } else if (IsFixed != Prev->isFixed()) {
8471    Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
8472      << Prev->isFixed();
8473    Diag(Prev->getLocation(), diag::note_previous_use);
8474    return true;
8475  }
8476
8477  return false;
8478}
8479
8480/// \brief Get diagnostic %select index for tag kind for
8481/// redeclaration diagnostic message.
8482/// WARNING: Indexes apply to particular diagnostics only!
8483///
8484/// \returns diagnostic %select index.
8485static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
8486  switch (Tag) {
8487  case TTK_Struct: return 0;
8488  case TTK_Interface: return 1;
8489  case TTK_Class:  return 2;
8490  default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
8491  }
8492}
8493
8494/// \brief Determine if tag kind is a class-key compatible with
8495/// class for redeclaration (class, struct, or __interface).
8496///
8497/// \returns true iff the tag kind is compatible.
8498static bool isClassCompatTagKind(TagTypeKind Tag)
8499{
8500  return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
8501}
8502
8503/// \brief Determine whether a tag with a given kind is acceptable
8504/// as a redeclaration of the given tag declaration.
8505///
8506/// \returns true if the new tag kind is acceptable, false otherwise.
8507bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
8508                                        TagTypeKind NewTag, bool isDefinition,
8509                                        SourceLocation NewTagLoc,
8510                                        const IdentifierInfo &Name) {
8511  // C++ [dcl.type.elab]p3:
8512  //   The class-key or enum keyword present in the
8513  //   elaborated-type-specifier shall agree in kind with the
8514  //   declaration to which the name in the elaborated-type-specifier
8515  //   refers. This rule also applies to the form of
8516  //   elaborated-type-specifier that declares a class-name or
8517  //   friend class since it can be construed as referring to the
8518  //   definition of the class. Thus, in any
8519  //   elaborated-type-specifier, the enum keyword shall be used to
8520  //   refer to an enumeration (7.2), the union class-key shall be
8521  //   used to refer to a union (clause 9), and either the class or
8522  //   struct class-key shall be used to refer to a class (clause 9)
8523  //   declared using the class or struct class-key.
8524  TagTypeKind OldTag = Previous->getTagKind();
8525  if (!isDefinition || !isClassCompatTagKind(NewTag))
8526    if (OldTag == NewTag)
8527      return true;
8528
8529  if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
8530    // Warn about the struct/class tag mismatch.
8531    bool isTemplate = false;
8532    if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
8533      isTemplate = Record->getDescribedClassTemplate();
8534
8535    if (!ActiveTemplateInstantiations.empty()) {
8536      // In a template instantiation, do not offer fix-its for tag mismatches
8537      // since they usually mess up the template instead of fixing the problem.
8538      Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
8539        << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
8540        << getRedeclDiagFromTagKind(OldTag);
8541      return true;
8542    }
8543
8544    if (isDefinition) {
8545      // On definitions, check previous tags and issue a fix-it for each
8546      // one that doesn't match the current tag.
8547      if (Previous->getDefinition()) {
8548        // Don't suggest fix-its for redefinitions.
8549        return true;
8550      }
8551
8552      bool previousMismatch = false;
8553      for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
8554           E(Previous->redecls_end()); I != E; ++I) {
8555        if (I->getTagKind() != NewTag) {
8556          if (!previousMismatch) {
8557            previousMismatch = true;
8558            Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
8559              << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
8560              << getRedeclDiagFromTagKind(I->getTagKind());
8561          }
8562          Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
8563            << getRedeclDiagFromTagKind(NewTag)
8564            << FixItHint::CreateReplacement(I->getInnerLocStart(),
8565                 TypeWithKeyword::getTagTypeKindName(NewTag));
8566        }
8567      }
8568      return true;
8569    }
8570
8571    // Check for a previous definition.  If current tag and definition
8572    // are same type, do nothing.  If no definition, but disagree with
8573    // with previous tag type, give a warning, but no fix-it.
8574    const TagDecl *Redecl = Previous->getDefinition() ?
8575                            Previous->getDefinition() : Previous;
8576    if (Redecl->getTagKind() == NewTag) {
8577      return true;
8578    }
8579
8580    Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
8581      << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
8582      << getRedeclDiagFromTagKind(OldTag);
8583    Diag(Redecl->getLocation(), diag::note_previous_use);
8584
8585    // If there is a previous defintion, suggest a fix-it.
8586    if (Previous->getDefinition()) {
8587        Diag(NewTagLoc, diag::note_struct_class_suggestion)
8588          << getRedeclDiagFromTagKind(Redecl->getTagKind())
8589          << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
8590               TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
8591    }
8592
8593    return true;
8594  }
8595  return false;
8596}
8597
8598/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
8599/// former case, Name will be non-null.  In the later case, Name will be null.
8600/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
8601/// reference/declaration/definition of a tag.
8602Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
8603                     SourceLocation KWLoc, CXXScopeSpec &SS,
8604                     IdentifierInfo *Name, SourceLocation NameLoc,
8605                     AttributeList *Attr, AccessSpecifier AS,
8606                     SourceLocation ModulePrivateLoc,
8607                     MultiTemplateParamsArg TemplateParameterLists,
8608                     bool &OwnedDecl, bool &IsDependent,
8609                     SourceLocation ScopedEnumKWLoc,
8610                     bool ScopedEnumUsesClassTag,
8611                     TypeResult UnderlyingType) {
8612  // If this is not a definition, it must have a name.
8613  IdentifierInfo *OrigName = Name;
8614  assert((Name != 0 || TUK == TUK_Definition) &&
8615         "Nameless record must be a definition!");
8616  assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
8617
8618  OwnedDecl = false;
8619  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8620  bool ScopedEnum = ScopedEnumKWLoc.isValid();
8621
8622  // FIXME: Check explicit specializations more carefully.
8623  bool isExplicitSpecialization = false;
8624  bool Invalid = false;
8625
8626  // We only need to do this matching if we have template parameters
8627  // or a scope specifier, which also conveniently avoids this work
8628  // for non-C++ cases.
8629  if (TemplateParameterLists.size() > 0 ||
8630      (SS.isNotEmpty() && TUK != TUK_Reference)) {
8631    if (TemplateParameterList *TemplateParams
8632          = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS,
8633                                                TemplateParameterLists.data(),
8634                                                TemplateParameterLists.size(),
8635                                                    TUK == TUK_Friend,
8636                                                    isExplicitSpecialization,
8637                                                    Invalid)) {
8638      if (TemplateParams->size() > 0) {
8639        // This is a declaration or definition of a class template (which may
8640        // be a member of another template).
8641
8642        if (Invalid)
8643          return 0;
8644
8645        OwnedDecl = false;
8646        DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
8647                                               SS, Name, NameLoc, Attr,
8648                                               TemplateParams, AS,
8649                                               ModulePrivateLoc,
8650                                               TemplateParameterLists.size()-1,
8651                                               TemplateParameterLists.data());
8652        return Result.get();
8653      } else {
8654        // The "template<>" header is extraneous.
8655        Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
8656          << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
8657        isExplicitSpecialization = true;
8658      }
8659    }
8660  }
8661
8662  // Figure out the underlying type if this a enum declaration. We need to do
8663  // this early, because it's needed to detect if this is an incompatible
8664  // redeclaration.
8665  llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
8666
8667  if (Kind == TTK_Enum) {
8668    if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
8669      // No underlying type explicitly specified, or we failed to parse the
8670      // type, default to int.
8671      EnumUnderlying = Context.IntTy.getTypePtr();
8672    else if (UnderlyingType.get()) {
8673      // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
8674      // integral type; any cv-qualification is ignored.
8675      TypeSourceInfo *TI = 0;
8676      GetTypeFromParser(UnderlyingType.get(), &TI);
8677      EnumUnderlying = TI;
8678
8679      if (CheckEnumUnderlyingType(TI))
8680        // Recover by falling back to int.
8681        EnumUnderlying = Context.IntTy.getTypePtr();
8682
8683      if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
8684                                          UPPC_FixedUnderlyingType))
8685        EnumUnderlying = Context.IntTy.getTypePtr();
8686
8687    } else if (getLangOpts().MicrosoftMode)
8688      // Microsoft enums are always of int type.
8689      EnumUnderlying = Context.IntTy.getTypePtr();
8690  }
8691
8692  DeclContext *SearchDC = CurContext;
8693  DeclContext *DC = CurContext;
8694  bool isStdBadAlloc = false;
8695
8696  RedeclarationKind Redecl = ForRedeclaration;
8697  if (TUK == TUK_Friend || TUK == TUK_Reference)
8698    Redecl = NotForRedeclaration;
8699
8700  LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
8701
8702  if (Name && SS.isNotEmpty()) {
8703    // We have a nested-name tag ('struct foo::bar').
8704
8705    // Check for invalid 'foo::'.
8706    if (SS.isInvalid()) {
8707      Name = 0;
8708      goto CreateNewDecl;
8709    }
8710
8711    // If this is a friend or a reference to a class in a dependent
8712    // context, don't try to make a decl for it.
8713    if (TUK == TUK_Friend || TUK == TUK_Reference) {
8714      DC = computeDeclContext(SS, false);
8715      if (!DC) {
8716        IsDependent = true;
8717        return 0;
8718      }
8719    } else {
8720      DC = computeDeclContext(SS, true);
8721      if (!DC) {
8722        Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
8723          << SS.getRange();
8724        return 0;
8725      }
8726    }
8727
8728    if (RequireCompleteDeclContext(SS, DC))
8729      return 0;
8730
8731    SearchDC = DC;
8732    // Look-up name inside 'foo::'.
8733    LookupQualifiedName(Previous, DC);
8734
8735    if (Previous.isAmbiguous())
8736      return 0;
8737
8738    if (Previous.empty()) {
8739      // Name lookup did not find anything. However, if the
8740      // nested-name-specifier refers to the current instantiation,
8741      // and that current instantiation has any dependent base
8742      // classes, we might find something at instantiation time: treat
8743      // this as a dependent elaborated-type-specifier.
8744      // But this only makes any sense for reference-like lookups.
8745      if (Previous.wasNotFoundInCurrentInstantiation() &&
8746          (TUK == TUK_Reference || TUK == TUK_Friend)) {
8747        IsDependent = true;
8748        return 0;
8749      }
8750
8751      // A tag 'foo::bar' must already exist.
8752      Diag(NameLoc, diag::err_not_tag_in_scope)
8753        << Kind << Name << DC << SS.getRange();
8754      Name = 0;
8755      Invalid = true;
8756      goto CreateNewDecl;
8757    }
8758  } else if (Name) {
8759    // If this is a named struct, check to see if there was a previous forward
8760    // declaration or definition.
8761    // FIXME: We're looking into outer scopes here, even when we
8762    // shouldn't be. Doing so can result in ambiguities that we
8763    // shouldn't be diagnosing.
8764    LookupName(Previous, S);
8765
8766    if (Previous.isAmbiguous() &&
8767        (TUK == TUK_Definition || TUK == TUK_Declaration)) {
8768      LookupResult::Filter F = Previous.makeFilter();
8769      while (F.hasNext()) {
8770        NamedDecl *ND = F.next();
8771        if (ND->getDeclContext()->getRedeclContext() != SearchDC)
8772          F.erase();
8773      }
8774      F.done();
8775    }
8776
8777    // Note:  there used to be some attempt at recovery here.
8778    if (Previous.isAmbiguous())
8779      return 0;
8780
8781    if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
8782      // FIXME: This makes sure that we ignore the contexts associated
8783      // with C structs, unions, and enums when looking for a matching
8784      // tag declaration or definition. See the similar lookup tweak
8785      // in Sema::LookupName; is there a better way to deal with this?
8786      while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
8787        SearchDC = SearchDC->getParent();
8788    }
8789  } else if (S->isFunctionPrototypeScope()) {
8790    // If this is an enum declaration in function prototype scope, set its
8791    // initial context to the translation unit.
8792    // FIXME: [citation needed]
8793    SearchDC = Context.getTranslationUnitDecl();
8794  }
8795
8796  if (Previous.isSingleResult() &&
8797      Previous.getFoundDecl()->isTemplateParameter()) {
8798    // Maybe we will complain about the shadowed template parameter.
8799    DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
8800    // Just pretend that we didn't see the previous declaration.
8801    Previous.clear();
8802  }
8803
8804  if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
8805      DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
8806    // This is a declaration of or a reference to "std::bad_alloc".
8807    isStdBadAlloc = true;
8808
8809    if (Previous.empty() && StdBadAlloc) {
8810      // std::bad_alloc has been implicitly declared (but made invisible to
8811      // name lookup). Fill in this implicit declaration as the previous
8812      // declaration, so that the declarations get chained appropriately.
8813      Previous.addDecl(getStdBadAlloc());
8814    }
8815  }
8816
8817  // If we didn't find a previous declaration, and this is a reference
8818  // (or friend reference), move to the correct scope.  In C++, we
8819  // also need to do a redeclaration lookup there, just in case
8820  // there's a shadow friend decl.
8821  if (Name && Previous.empty() &&
8822      (TUK == TUK_Reference || TUK == TUK_Friend)) {
8823    if (Invalid) goto CreateNewDecl;
8824    assert(SS.isEmpty());
8825
8826    if (TUK == TUK_Reference) {
8827      // C++ [basic.scope.pdecl]p5:
8828      //   -- for an elaborated-type-specifier of the form
8829      //
8830      //          class-key identifier
8831      //
8832      //      if the elaborated-type-specifier is used in the
8833      //      decl-specifier-seq or parameter-declaration-clause of a
8834      //      function defined in namespace scope, the identifier is
8835      //      declared as a class-name in the namespace that contains
8836      //      the declaration; otherwise, except as a friend
8837      //      declaration, the identifier is declared in the smallest
8838      //      non-class, non-function-prototype scope that contains the
8839      //      declaration.
8840      //
8841      // C99 6.7.2.3p8 has a similar (but not identical!) provision for
8842      // C structs and unions.
8843      //
8844      // It is an error in C++ to declare (rather than define) an enum
8845      // type, including via an elaborated type specifier.  We'll
8846      // diagnose that later; for now, declare the enum in the same
8847      // scope as we would have picked for any other tag type.
8848      //
8849      // GNU C also supports this behavior as part of its incomplete
8850      // enum types extension, while GNU C++ does not.
8851      //
8852      // Find the context where we'll be declaring the tag.
8853      // FIXME: We would like to maintain the current DeclContext as the
8854      // lexical context,
8855      while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
8856        SearchDC = SearchDC->getParent();
8857
8858      // Find the scope where we'll be declaring the tag.
8859      while (S->isClassScope() ||
8860             (getLangOpts().CPlusPlus &&
8861              S->isFunctionPrototypeScope()) ||
8862             ((S->getFlags() & Scope::DeclScope) == 0) ||
8863             (S->getEntity() &&
8864              ((DeclContext *)S->getEntity())->isTransparentContext()))
8865        S = S->getParent();
8866    } else {
8867      assert(TUK == TUK_Friend);
8868      // C++ [namespace.memdef]p3:
8869      //   If a friend declaration in a non-local class first declares a
8870      //   class or function, the friend class or function is a member of
8871      //   the innermost enclosing namespace.
8872      SearchDC = SearchDC->getEnclosingNamespaceContext();
8873    }
8874
8875    // In C++, we need to do a redeclaration lookup to properly
8876    // diagnose some problems.
8877    if (getLangOpts().CPlusPlus) {
8878      Previous.setRedeclarationKind(ForRedeclaration);
8879      LookupQualifiedName(Previous, SearchDC);
8880    }
8881  }
8882
8883  if (!Previous.empty()) {
8884    NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
8885
8886    // It's okay to have a tag decl in the same scope as a typedef
8887    // which hides a tag decl in the same scope.  Finding this
8888    // insanity with a redeclaration lookup can only actually happen
8889    // in C++.
8890    //
8891    // This is also okay for elaborated-type-specifiers, which is
8892    // technically forbidden by the current standard but which is
8893    // okay according to the likely resolution of an open issue;
8894    // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
8895    if (getLangOpts().CPlusPlus) {
8896      if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
8897        if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
8898          TagDecl *Tag = TT->getDecl();
8899          if (Tag->getDeclName() == Name &&
8900              Tag->getDeclContext()->getRedeclContext()
8901                          ->Equals(TD->getDeclContext()->getRedeclContext())) {
8902            PrevDecl = Tag;
8903            Previous.clear();
8904            Previous.addDecl(Tag);
8905            Previous.resolveKind();
8906          }
8907        }
8908      }
8909    }
8910
8911    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
8912      // If this is a use of a previous tag, or if the tag is already declared
8913      // in the same scope (so that the definition/declaration completes or
8914      // rementions the tag), reuse the decl.
8915      if (TUK == TUK_Reference || TUK == TUK_Friend ||
8916          isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
8917        // Make sure that this wasn't declared as an enum and now used as a
8918        // struct or something similar.
8919        if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
8920                                          TUK == TUK_Definition, KWLoc,
8921                                          *Name)) {
8922          bool SafeToContinue
8923            = (PrevTagDecl->getTagKind() != TTK_Enum &&
8924               Kind != TTK_Enum);
8925          if (SafeToContinue)
8926            Diag(KWLoc, diag::err_use_with_wrong_tag)
8927              << Name
8928              << FixItHint::CreateReplacement(SourceRange(KWLoc),
8929                                              PrevTagDecl->getKindName());
8930          else
8931            Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
8932          Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
8933
8934          if (SafeToContinue)
8935            Kind = PrevTagDecl->getTagKind();
8936          else {
8937            // Recover by making this an anonymous redefinition.
8938            Name = 0;
8939            Previous.clear();
8940            Invalid = true;
8941          }
8942        }
8943
8944        if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
8945          const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
8946
8947          // If this is an elaborated-type-specifier for a scoped enumeration,
8948          // the 'class' keyword is not necessary and not permitted.
8949          if (TUK == TUK_Reference || TUK == TUK_Friend) {
8950            if (ScopedEnum)
8951              Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
8952                << PrevEnum->isScoped()
8953                << FixItHint::CreateRemoval(ScopedEnumKWLoc);
8954            return PrevTagDecl;
8955          }
8956
8957          QualType EnumUnderlyingTy;
8958          if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
8959            EnumUnderlyingTy = TI->getType();
8960          else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
8961            EnumUnderlyingTy = QualType(T, 0);
8962
8963          // All conflicts with previous declarations are recovered by
8964          // returning the previous declaration, unless this is a definition,
8965          // in which case we want the caller to bail out.
8966          if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
8967                                     ScopedEnum, EnumUnderlyingTy, PrevEnum))
8968            return TUK == TUK_Declaration ? PrevTagDecl : 0;
8969        }
8970
8971        if (!Invalid) {
8972          // If this is a use, just return the declaration we found.
8973
8974          // FIXME: In the future, return a variant or some other clue
8975          // for the consumer of this Decl to know it doesn't own it.
8976          // For our current ASTs this shouldn't be a problem, but will
8977          // need to be changed with DeclGroups.
8978          if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
8979               getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
8980            return PrevTagDecl;
8981
8982          // Diagnose attempts to redefine a tag.
8983          if (TUK == TUK_Definition) {
8984            if (TagDecl *Def = PrevTagDecl->getDefinition()) {
8985              // If we're defining a specialization and the previous definition
8986              // is from an implicit instantiation, don't emit an error
8987              // here; we'll catch this in the general case below.
8988              bool IsExplicitSpecializationAfterInstantiation = false;
8989              if (isExplicitSpecialization) {
8990                if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
8991                  IsExplicitSpecializationAfterInstantiation =
8992                    RD->getTemplateSpecializationKind() !=
8993                    TSK_ExplicitSpecialization;
8994                else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
8995                  IsExplicitSpecializationAfterInstantiation =
8996                    ED->getTemplateSpecializationKind() !=
8997                    TSK_ExplicitSpecialization;
8998              }
8999
9000              if (!IsExplicitSpecializationAfterInstantiation) {
9001                // A redeclaration in function prototype scope in C isn't
9002                // visible elsewhere, so merely issue a warning.
9003                if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
9004                  Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
9005                else
9006                  Diag(NameLoc, diag::err_redefinition) << Name;
9007                Diag(Def->getLocation(), diag::note_previous_definition);
9008                // If this is a redefinition, recover by making this
9009                // struct be anonymous, which will make any later
9010                // references get the previous definition.
9011                Name = 0;
9012                Previous.clear();
9013                Invalid = true;
9014              }
9015            } else {
9016              // If the type is currently being defined, complain
9017              // about a nested redefinition.
9018              const TagType *Tag
9019                = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
9020              if (Tag->isBeingDefined()) {
9021                Diag(NameLoc, diag::err_nested_redefinition) << Name;
9022                Diag(PrevTagDecl->getLocation(),
9023                     diag::note_previous_definition);
9024                Name = 0;
9025                Previous.clear();
9026                Invalid = true;
9027              }
9028            }
9029
9030            // Okay, this is definition of a previously declared or referenced
9031            // tag PrevDecl. We're going to create a new Decl for it.
9032          }
9033        }
9034        // If we get here we have (another) forward declaration or we
9035        // have a definition.  Just create a new decl.
9036
9037      } else {
9038        // If we get here, this is a definition of a new tag type in a nested
9039        // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
9040        // new decl/type.  We set PrevDecl to NULL so that the entities
9041        // have distinct types.
9042        Previous.clear();
9043      }
9044      // If we get here, we're going to create a new Decl. If PrevDecl
9045      // is non-NULL, it's a definition of the tag declared by
9046      // PrevDecl. If it's NULL, we have a new definition.
9047
9048
9049    // Otherwise, PrevDecl is not a tag, but was found with tag
9050    // lookup.  This is only actually possible in C++, where a few
9051    // things like templates still live in the tag namespace.
9052    } else {
9053      // Use a better diagnostic if an elaborated-type-specifier
9054      // found the wrong kind of type on the first
9055      // (non-redeclaration) lookup.
9056      if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
9057          !Previous.isForRedeclaration()) {
9058        unsigned Kind = 0;
9059        if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
9060        else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
9061        else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
9062        Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
9063        Diag(PrevDecl->getLocation(), diag::note_declared_at);
9064        Invalid = true;
9065
9066      // Otherwise, only diagnose if the declaration is in scope.
9067      } else if (!isDeclInScope(PrevDecl, SearchDC, S,
9068                                isExplicitSpecialization)) {
9069        // do nothing
9070
9071      // Diagnose implicit declarations introduced by elaborated types.
9072      } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
9073        unsigned Kind = 0;
9074        if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
9075        else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
9076        else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
9077        Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
9078        Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
9079        Invalid = true;
9080
9081      // Otherwise it's a declaration.  Call out a particularly common
9082      // case here.
9083      } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
9084        unsigned Kind = 0;
9085        if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
9086        Diag(NameLoc, diag::err_tag_definition_of_typedef)
9087          << Name << Kind << TND->getUnderlyingType();
9088        Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
9089        Invalid = true;
9090
9091      // Otherwise, diagnose.
9092      } else {
9093        // The tag name clashes with something else in the target scope,
9094        // issue an error and recover by making this tag be anonymous.
9095        Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
9096        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
9097        Name = 0;
9098        Invalid = true;
9099      }
9100
9101      // The existing declaration isn't relevant to us; we're in a
9102      // new scope, so clear out the previous declaration.
9103      Previous.clear();
9104    }
9105  }
9106
9107CreateNewDecl:
9108
9109  TagDecl *PrevDecl = 0;
9110  if (Previous.isSingleResult())
9111    PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
9112
9113  // If there is an identifier, use the location of the identifier as the
9114  // location of the decl, otherwise use the location of the struct/union
9115  // keyword.
9116  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
9117
9118  // Otherwise, create a new declaration. If there is a previous
9119  // declaration of the same entity, the two will be linked via
9120  // PrevDecl.
9121  TagDecl *New;
9122
9123  bool IsForwardReference = false;
9124  if (Kind == TTK_Enum) {
9125    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
9126    // enum X { A, B, C } D;    D should chain to X.
9127    New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
9128                           cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
9129                           ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
9130    // If this is an undefined enum, warn.
9131    if (TUK != TUK_Definition && !Invalid) {
9132      TagDecl *Def;
9133      if (getLangOpts().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) {
9134        // C++0x: 7.2p2: opaque-enum-declaration.
9135        // Conflicts are diagnosed above. Do nothing.
9136      }
9137      else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
9138        Diag(Loc, diag::ext_forward_ref_enum_def)
9139          << New;
9140        Diag(Def->getLocation(), diag::note_previous_definition);
9141      } else {
9142        unsigned DiagID = diag::ext_forward_ref_enum;
9143        if (getLangOpts().MicrosoftMode)
9144          DiagID = diag::ext_ms_forward_ref_enum;
9145        else if (getLangOpts().CPlusPlus)
9146          DiagID = diag::err_forward_ref_enum;
9147        Diag(Loc, DiagID);
9148
9149        // If this is a forward-declared reference to an enumeration, make a
9150        // note of it; we won't actually be introducing the declaration into
9151        // the declaration context.
9152        if (TUK == TUK_Reference)
9153          IsForwardReference = true;
9154      }
9155    }
9156
9157    if (EnumUnderlying) {
9158      EnumDecl *ED = cast<EnumDecl>(New);
9159      if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
9160        ED->setIntegerTypeSourceInfo(TI);
9161      else
9162        ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
9163      ED->setPromotionType(ED->getIntegerType());
9164    }
9165
9166  } else {
9167    // struct/union/class
9168
9169    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
9170    // struct X { int A; } D;    D should chain to X.
9171    if (getLangOpts().CPlusPlus) {
9172      // FIXME: Look for a way to use RecordDecl for simple structs.
9173      New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
9174                                  cast_or_null<CXXRecordDecl>(PrevDecl));
9175
9176      if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
9177        StdBadAlloc = cast<CXXRecordDecl>(New);
9178    } else
9179      New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
9180                               cast_or_null<RecordDecl>(PrevDecl));
9181  }
9182
9183  // Maybe add qualifier info.
9184  if (SS.isNotEmpty()) {
9185    if (SS.isSet()) {
9186      // If this is either a declaration or a definition, check the
9187      // nested-name-specifier against the current context. We don't do this
9188      // for explicit specializations, because they have similar checking
9189      // (with more specific diagnostics) in the call to
9190      // CheckMemberSpecialization, below.
9191      if (!isExplicitSpecialization &&
9192          (TUK == TUK_Definition || TUK == TUK_Declaration) &&
9193          diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
9194        Invalid = true;
9195
9196      New->setQualifierInfo(SS.getWithLocInContext(Context));
9197      if (TemplateParameterLists.size() > 0) {
9198        New->setTemplateParameterListsInfo(Context,
9199                                           TemplateParameterLists.size(),
9200                                           TemplateParameterLists.data());
9201      }
9202    }
9203    else
9204      Invalid = true;
9205  }
9206
9207  if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
9208    // Add alignment attributes if necessary; these attributes are checked when
9209    // the ASTContext lays out the structure.
9210    //
9211    // It is important for implementing the correct semantics that this
9212    // happen here (in act on tag decl). The #pragma pack stack is
9213    // maintained as a result of parser callbacks which can occur at
9214    // many points during the parsing of a struct declaration (because
9215    // the #pragma tokens are effectively skipped over during the
9216    // parsing of the struct).
9217    if (TUK == TUK_Definition) {
9218      AddAlignmentAttributesForRecord(RD);
9219      AddMsStructLayoutForRecord(RD);
9220    }
9221  }
9222
9223  if (ModulePrivateLoc.isValid()) {
9224    if (isExplicitSpecialization)
9225      Diag(New->getLocation(), diag::err_module_private_specialization)
9226        << 2
9227        << FixItHint::CreateRemoval(ModulePrivateLoc);
9228    // __module_private__ does not apply to local classes. However, we only
9229    // diagnose this as an error when the declaration specifiers are
9230    // freestanding. Here, we just ignore the __module_private__.
9231    else if (!SearchDC->isFunctionOrMethod())
9232      New->setModulePrivate();
9233  }
9234
9235  // If this is a specialization of a member class (of a class template),
9236  // check the specialization.
9237  if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
9238    Invalid = true;
9239
9240  if (Invalid)
9241    New->setInvalidDecl();
9242
9243  if (Attr)
9244    ProcessDeclAttributeList(S, New, Attr);
9245
9246  // If we're declaring or defining a tag in function prototype scope
9247  // in C, note that this type can only be used within the function.
9248  if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
9249    Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
9250
9251  // Set the lexical context. If the tag has a C++ scope specifier, the
9252  // lexical context will be different from the semantic context.
9253  New->setLexicalDeclContext(CurContext);
9254
9255  // Mark this as a friend decl if applicable.
9256  // In Microsoft mode, a friend declaration also acts as a forward
9257  // declaration so we always pass true to setObjectOfFriendDecl to make
9258  // the tag name visible.
9259  if (TUK == TUK_Friend)
9260    New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() ||
9261                               getLangOpts().MicrosoftExt);
9262
9263  // Set the access specifier.
9264  if (!Invalid && SearchDC->isRecord())
9265    SetMemberAccessSpecifier(New, PrevDecl, AS);
9266
9267  if (TUK == TUK_Definition)
9268    New->startDefinition();
9269
9270  // If this has an identifier, add it to the scope stack.
9271  if (TUK == TUK_Friend) {
9272    // We might be replacing an existing declaration in the lookup tables;
9273    // if so, borrow its access specifier.
9274    if (PrevDecl)
9275      New->setAccess(PrevDecl->getAccess());
9276
9277    DeclContext *DC = New->getDeclContext()->getRedeclContext();
9278    DC->makeDeclVisibleInContext(New);
9279    if (Name) // can be null along some error paths
9280      if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
9281        PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
9282  } else if (Name) {
9283    S = getNonFieldDeclScope(S);
9284    PushOnScopeChains(New, S, !IsForwardReference);
9285    if (IsForwardReference)
9286      SearchDC->makeDeclVisibleInContext(New);
9287
9288  } else {
9289    CurContext->addDecl(New);
9290  }
9291
9292  // If this is the C FILE type, notify the AST context.
9293  if (IdentifierInfo *II = New->getIdentifier())
9294    if (!New->isInvalidDecl() &&
9295        New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
9296        II->isStr("FILE"))
9297      Context.setFILEDecl(New);
9298
9299  // If we were in function prototype scope (and not in C++ mode), add this
9300  // tag to the list of decls to inject into the function definition scope.
9301  if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
9302      InFunctionDeclarator && Name)
9303    DeclsInPrototypeScope.push_back(New);
9304
9305  if (PrevDecl)
9306    mergeDeclAttributes(New, PrevDecl);
9307
9308  // If there's a #pragma GCC visibility in scope, set the visibility of this
9309  // record.
9310  AddPushedVisibilityAttribute(New);
9311
9312  OwnedDecl = true;
9313  // In C++, don't return an invalid declaration. We can't recover well from
9314  // the cases where we make the type anonymous.
9315  return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
9316}
9317
9318void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
9319  AdjustDeclIfTemplate(TagD);
9320  TagDecl *Tag = cast<TagDecl>(TagD);
9321
9322  // Enter the tag context.
9323  PushDeclContext(S, Tag);
9324
9325  ActOnDocumentableDecl(TagD);
9326
9327  // If there's a #pragma GCC visibility in scope, set the visibility of this
9328  // record.
9329  AddPushedVisibilityAttribute(Tag);
9330}
9331
9332Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
9333  assert(isa<ObjCContainerDecl>(IDecl) &&
9334         "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
9335  DeclContext *OCD = cast<DeclContext>(IDecl);
9336  assert(getContainingDC(OCD) == CurContext &&
9337      "The next DeclContext should be lexically contained in the current one.");
9338  CurContext = OCD;
9339  return IDecl;
9340}
9341
9342void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
9343                                           SourceLocation FinalLoc,
9344                                           SourceLocation LBraceLoc) {
9345  AdjustDeclIfTemplate(TagD);
9346  CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
9347
9348  FieldCollector->StartClass();
9349
9350  if (!Record->getIdentifier())
9351    return;
9352
9353  if (FinalLoc.isValid())
9354    Record->addAttr(new (Context) FinalAttr(FinalLoc, Context));
9355
9356  // C++ [class]p2:
9357  //   [...] The class-name is also inserted into the scope of the
9358  //   class itself; this is known as the injected-class-name. For
9359  //   purposes of access checking, the injected-class-name is treated
9360  //   as if it were a public member name.
9361  CXXRecordDecl *InjectedClassName
9362    = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
9363                            Record->getLocStart(), Record->getLocation(),
9364                            Record->getIdentifier(),
9365                            /*PrevDecl=*/0,
9366                            /*DelayTypeCreation=*/true);
9367  Context.getTypeDeclType(InjectedClassName, Record);
9368  InjectedClassName->setImplicit();
9369  InjectedClassName->setAccess(AS_public);
9370  if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
9371      InjectedClassName->setDescribedClassTemplate(Template);
9372  PushOnScopeChains(InjectedClassName, S);
9373  assert(InjectedClassName->isInjectedClassName() &&
9374         "Broken injected-class-name");
9375}
9376
9377void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
9378                                    SourceLocation RBraceLoc) {
9379  AdjustDeclIfTemplate(TagD);
9380  TagDecl *Tag = cast<TagDecl>(TagD);
9381  Tag->setRBraceLoc(RBraceLoc);
9382
9383  // Make sure we "complete" the definition even it is invalid.
9384  if (Tag->isBeingDefined()) {
9385    assert(Tag->isInvalidDecl() && "We should already have completed it");
9386    if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
9387      RD->completeDefinition();
9388  }
9389
9390  if (isa<CXXRecordDecl>(Tag))
9391    FieldCollector->FinishClass();
9392
9393  // Exit this scope of this tag's definition.
9394  PopDeclContext();
9395
9396  // Notify the consumer that we've defined a tag.
9397  Consumer.HandleTagDeclDefinition(Tag);
9398}
9399
9400void Sema::ActOnObjCContainerFinishDefinition() {
9401  // Exit this scope of this interface definition.
9402  PopDeclContext();
9403}
9404
9405void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
9406  assert(DC == CurContext && "Mismatch of container contexts");
9407  OriginalLexicalContext = DC;
9408  ActOnObjCContainerFinishDefinition();
9409}
9410
9411void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
9412  ActOnObjCContainerStartDefinition(cast<Decl>(DC));
9413  OriginalLexicalContext = 0;
9414}
9415
9416void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
9417  AdjustDeclIfTemplate(TagD);
9418  TagDecl *Tag = cast<TagDecl>(TagD);
9419  Tag->setInvalidDecl();
9420
9421  // Make sure we "complete" the definition even it is invalid.
9422  if (Tag->isBeingDefined()) {
9423    if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
9424      RD->completeDefinition();
9425  }
9426
9427  // We're undoing ActOnTagStartDefinition here, not
9428  // ActOnStartCXXMemberDeclarations, so we don't have to mess with
9429  // the FieldCollector.
9430
9431  PopDeclContext();
9432}
9433
9434// Note that FieldName may be null for anonymous bitfields.
9435ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
9436                                IdentifierInfo *FieldName,
9437                                QualType FieldTy, Expr *BitWidth,
9438                                bool *ZeroWidth) {
9439  // Default to true; that shouldn't confuse checks for emptiness
9440  if (ZeroWidth)
9441    *ZeroWidth = true;
9442
9443  // C99 6.7.2.1p4 - verify the field type.
9444  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
9445  if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
9446    // Handle incomplete types with specific error.
9447    if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
9448      return ExprError();
9449    if (FieldName)
9450      return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
9451        << FieldName << FieldTy << BitWidth->getSourceRange();
9452    return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
9453      << FieldTy << BitWidth->getSourceRange();
9454  } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
9455                                             UPPC_BitFieldWidth))
9456    return ExprError();
9457
9458  // If the bit-width is type- or value-dependent, don't try to check
9459  // it now.
9460  if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
9461    return Owned(BitWidth);
9462
9463  llvm::APSInt Value;
9464  ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
9465  if (ICE.isInvalid())
9466    return ICE;
9467  BitWidth = ICE.take();
9468
9469  if (Value != 0 && ZeroWidth)
9470    *ZeroWidth = false;
9471
9472  // Zero-width bitfield is ok for anonymous field.
9473  if (Value == 0 && FieldName)
9474    return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
9475
9476  if (Value.isSigned() && Value.isNegative()) {
9477    if (FieldName)
9478      return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
9479               << FieldName << Value.toString(10);
9480    return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
9481      << Value.toString(10);
9482  }
9483
9484  if (!FieldTy->isDependentType()) {
9485    uint64_t TypeSize = Context.getTypeSize(FieldTy);
9486    if (Value.getZExtValue() > TypeSize) {
9487      if (!getLangOpts().CPlusPlus) {
9488        if (FieldName)
9489          return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
9490            << FieldName << (unsigned)Value.getZExtValue()
9491            << (unsigned)TypeSize;
9492
9493        return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
9494          << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
9495      }
9496
9497      if (FieldName)
9498        Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
9499          << FieldName << (unsigned)Value.getZExtValue()
9500          << (unsigned)TypeSize;
9501      else
9502        Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
9503          << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
9504    }
9505  }
9506
9507  return Owned(BitWidth);
9508}
9509
9510/// ActOnField - Each field of a C struct/union is passed into this in order
9511/// to create a FieldDecl object for it.
9512Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
9513                       Declarator &D, Expr *BitfieldWidth) {
9514  FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
9515                               DeclStart, D, static_cast<Expr*>(BitfieldWidth),
9516                               /*InitStyle=*/ICIS_NoInit, AS_public);
9517  return Res;
9518}
9519
9520/// HandleField - Analyze a field of a C struct or a C++ data member.
9521///
9522FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
9523                             SourceLocation DeclStart,
9524                             Declarator &D, Expr *BitWidth,
9525                             InClassInitStyle InitStyle,
9526                             AccessSpecifier AS) {
9527  IdentifierInfo *II = D.getIdentifier();
9528  SourceLocation Loc = DeclStart;
9529  if (II) Loc = D.getIdentifierLoc();
9530
9531  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9532  QualType T = TInfo->getType();
9533  if (getLangOpts().CPlusPlus) {
9534    CheckExtraCXXDefaultArguments(D);
9535
9536    if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9537                                        UPPC_DataMemberType)) {
9538      D.setInvalidType();
9539      T = Context.IntTy;
9540      TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
9541    }
9542  }
9543
9544  DiagnoseFunctionSpecifiers(D);
9545
9546  if (D.getDeclSpec().isThreadSpecified())
9547    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
9548  if (D.getDeclSpec().isConstexprSpecified())
9549    Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
9550      << 2;
9551
9552  // Check to see if this name was declared as a member previously
9553  NamedDecl *PrevDecl = 0;
9554  LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
9555  LookupName(Previous, S);
9556  switch (Previous.getResultKind()) {
9557    case LookupResult::Found:
9558    case LookupResult::FoundUnresolvedValue:
9559      PrevDecl = Previous.getAsSingle<NamedDecl>();
9560      break;
9561
9562    case LookupResult::FoundOverloaded:
9563      PrevDecl = Previous.getRepresentativeDecl();
9564      break;
9565
9566    case LookupResult::NotFound:
9567    case LookupResult::NotFoundInCurrentInstantiation:
9568    case LookupResult::Ambiguous:
9569      break;
9570  }
9571  Previous.suppressDiagnostics();
9572
9573  if (PrevDecl && PrevDecl->isTemplateParameter()) {
9574    // Maybe we will complain about the shadowed template parameter.
9575    DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9576    // Just pretend that we didn't see the previous declaration.
9577    PrevDecl = 0;
9578  }
9579
9580  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
9581    PrevDecl = 0;
9582
9583  bool Mutable
9584    = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
9585  SourceLocation TSSL = D.getLocStart();
9586  FieldDecl *NewFD
9587    = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
9588                     TSSL, AS, PrevDecl, &D);
9589
9590  if (NewFD->isInvalidDecl())
9591    Record->setInvalidDecl();
9592
9593  if (D.getDeclSpec().isModulePrivateSpecified())
9594    NewFD->setModulePrivate();
9595
9596  if (NewFD->isInvalidDecl() && PrevDecl) {
9597    // Don't introduce NewFD into scope; there's already something
9598    // with the same name in the same scope.
9599  } else if (II) {
9600    PushOnScopeChains(NewFD, S);
9601  } else
9602    Record->addDecl(NewFD);
9603
9604  return NewFD;
9605}
9606
9607/// \brief Build a new FieldDecl and check its well-formedness.
9608///
9609/// This routine builds a new FieldDecl given the fields name, type,
9610/// record, etc. \p PrevDecl should refer to any previous declaration
9611/// with the same name and in the same scope as the field to be
9612/// created.
9613///
9614/// \returns a new FieldDecl.
9615///
9616/// \todo The Declarator argument is a hack. It will be removed once
9617FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
9618                                TypeSourceInfo *TInfo,
9619                                RecordDecl *Record, SourceLocation Loc,
9620                                bool Mutable, Expr *BitWidth,
9621                                InClassInitStyle InitStyle,
9622                                SourceLocation TSSL,
9623                                AccessSpecifier AS, NamedDecl *PrevDecl,
9624                                Declarator *D) {
9625  IdentifierInfo *II = Name.getAsIdentifierInfo();
9626  bool InvalidDecl = false;
9627  if (D) InvalidDecl = D->isInvalidType();
9628
9629  // If we receive a broken type, recover by assuming 'int' and
9630  // marking this declaration as invalid.
9631  if (T.isNull()) {
9632    InvalidDecl = true;
9633    T = Context.IntTy;
9634  }
9635
9636  QualType EltTy = Context.getBaseElementType(T);
9637  if (!EltTy->isDependentType()) {
9638    if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
9639      // Fields of incomplete type force their record to be invalid.
9640      Record->setInvalidDecl();
9641      InvalidDecl = true;
9642    } else {
9643      NamedDecl *Def;
9644      EltTy->isIncompleteType(&Def);
9645      if (Def && Def->isInvalidDecl()) {
9646        Record->setInvalidDecl();
9647        InvalidDecl = true;
9648      }
9649    }
9650  }
9651
9652  // C99 6.7.2.1p8: A member of a structure or union may have any type other
9653  // than a variably modified type.
9654  if (!InvalidDecl && T->isVariablyModifiedType()) {
9655    bool SizeIsNegative;
9656    llvm::APSInt Oversized;
9657
9658    TypeSourceInfo *FixedTInfo =
9659      TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
9660                                                    SizeIsNegative,
9661                                                    Oversized);
9662    if (FixedTInfo) {
9663      Diag(Loc, diag::warn_illegal_constant_array_size);
9664      TInfo = FixedTInfo;
9665      T = FixedTInfo->getType();
9666    } else {
9667      if (SizeIsNegative)
9668        Diag(Loc, diag::err_typecheck_negative_array_size);
9669      else if (Oversized.getBoolValue())
9670        Diag(Loc, diag::err_array_too_large)
9671          << Oversized.toString(10);
9672      else
9673        Diag(Loc, diag::err_typecheck_field_variable_size);
9674      InvalidDecl = true;
9675    }
9676  }
9677
9678  // Fields can not have abstract class types
9679  if (!InvalidDecl && RequireNonAbstractType(Loc, T,
9680                                             diag::err_abstract_type_in_decl,
9681                                             AbstractFieldType))
9682    InvalidDecl = true;
9683
9684  bool ZeroWidth = false;
9685  // If this is declared as a bit-field, check the bit-field.
9686  if (!InvalidDecl && BitWidth) {
9687    BitWidth = VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth).take();
9688    if (!BitWidth) {
9689      InvalidDecl = true;
9690      BitWidth = 0;
9691      ZeroWidth = false;
9692    }
9693  }
9694
9695  // Check that 'mutable' is consistent with the type of the declaration.
9696  if (!InvalidDecl && Mutable) {
9697    unsigned DiagID = 0;
9698    if (T->isReferenceType())
9699      DiagID = diag::err_mutable_reference;
9700    else if (T.isConstQualified())
9701      DiagID = diag::err_mutable_const;
9702
9703    if (DiagID) {
9704      SourceLocation ErrLoc = Loc;
9705      if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
9706        ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
9707      Diag(ErrLoc, DiagID);
9708      Mutable = false;
9709      InvalidDecl = true;
9710    }
9711  }
9712
9713  FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
9714                                       BitWidth, Mutable, InitStyle);
9715  if (InvalidDecl)
9716    NewFD->setInvalidDecl();
9717
9718  if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
9719    Diag(Loc, diag::err_duplicate_member) << II;
9720    Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9721    NewFD->setInvalidDecl();
9722  }
9723
9724  if (!InvalidDecl && getLangOpts().CPlusPlus) {
9725    if (Record->isUnion()) {
9726      if (const RecordType *RT = EltTy->getAs<RecordType>()) {
9727        CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
9728        if (RDecl->getDefinition()) {
9729          // C++ [class.union]p1: An object of a class with a non-trivial
9730          // constructor, a non-trivial copy constructor, a non-trivial
9731          // destructor, or a non-trivial copy assignment operator
9732          // cannot be a member of a union, nor can an array of such
9733          // objects.
9734          if (CheckNontrivialField(NewFD))
9735            NewFD->setInvalidDecl();
9736        }
9737      }
9738
9739      // C++ [class.union]p1: If a union contains a member of reference type,
9740      // the program is ill-formed.
9741      if (EltTy->isReferenceType()) {
9742        Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type)
9743          << NewFD->getDeclName() << EltTy;
9744        NewFD->setInvalidDecl();
9745      }
9746    }
9747  }
9748
9749  // FIXME: We need to pass in the attributes given an AST
9750  // representation, not a parser representation.
9751  if (D)
9752    // FIXME: What to pass instead of TUScope?
9753    ProcessDeclAttributes(TUScope, NewFD, *D);
9754
9755  // In auto-retain/release, infer strong retension for fields of
9756  // retainable type.
9757  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
9758    NewFD->setInvalidDecl();
9759
9760  if (T.isObjCGCWeak())
9761    Diag(Loc, diag::warn_attribute_weak_on_field);
9762
9763  NewFD->setAccess(AS);
9764  return NewFD;
9765}
9766
9767bool Sema::CheckNontrivialField(FieldDecl *FD) {
9768  assert(FD);
9769  assert(getLangOpts().CPlusPlus && "valid check only for C++");
9770
9771  if (FD->isInvalidDecl())
9772    return true;
9773
9774  QualType EltTy = Context.getBaseElementType(FD->getType());
9775  if (const RecordType *RT = EltTy->getAs<RecordType>()) {
9776    CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
9777    if (RDecl->getDefinition()) {
9778      // We check for copy constructors before constructors
9779      // because otherwise we'll never get complaints about
9780      // copy constructors.
9781
9782      CXXSpecialMember member = CXXInvalid;
9783      // We're required to check for any non-trivial constructors. Since the
9784      // implicit default constructor is suppressed if there are any
9785      // user-declared constructors, we just need to check that there is a
9786      // trivial default constructor and a trivial copy constructor. (We don't
9787      // worry about move constructors here, since this is a C++98 check.)
9788      if (RDecl->hasNonTrivialCopyConstructor())
9789        member = CXXCopyConstructor;
9790      else if (!RDecl->hasTrivialDefaultConstructor())
9791        member = CXXDefaultConstructor;
9792      else if (RDecl->hasNonTrivialCopyAssignment())
9793        member = CXXCopyAssignment;
9794      else if (RDecl->hasNonTrivialDestructor())
9795        member = CXXDestructor;
9796
9797      if (member != CXXInvalid) {
9798        if (!getLangOpts().CPlusPlus0x &&
9799            getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
9800          // Objective-C++ ARC: it is an error to have a non-trivial field of
9801          // a union. However, system headers in Objective-C programs
9802          // occasionally have Objective-C lifetime objects within unions,
9803          // and rather than cause the program to fail, we make those
9804          // members unavailable.
9805          SourceLocation Loc = FD->getLocation();
9806          if (getSourceManager().isInSystemHeader(Loc)) {
9807            if (!FD->hasAttr<UnavailableAttr>())
9808              FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
9809                                  "this system field has retaining ownership"));
9810            return false;
9811          }
9812        }
9813
9814        Diag(FD->getLocation(), getLangOpts().CPlusPlus0x ?
9815               diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
9816               diag::err_illegal_union_or_anon_struct_member)
9817          << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
9818        DiagnoseNontrivial(RDecl, member);
9819        return !getLangOpts().CPlusPlus0x;
9820      }
9821    }
9822  }
9823
9824  return false;
9825}
9826
9827/// TranslateIvarVisibility - Translate visibility from a token ID to an
9828///  AST enum value.
9829static ObjCIvarDecl::AccessControl
9830TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
9831  switch (ivarVisibility) {
9832  default: llvm_unreachable("Unknown visitibility kind");
9833  case tok::objc_private: return ObjCIvarDecl::Private;
9834  case tok::objc_public: return ObjCIvarDecl::Public;
9835  case tok::objc_protected: return ObjCIvarDecl::Protected;
9836  case tok::objc_package: return ObjCIvarDecl::Package;
9837  }
9838}
9839
9840/// ActOnIvar - Each ivar field of an objective-c class is passed into this
9841/// in order to create an IvarDecl object for it.
9842Decl *Sema::ActOnIvar(Scope *S,
9843                                SourceLocation DeclStart,
9844                                Declarator &D, Expr *BitfieldWidth,
9845                                tok::ObjCKeywordKind Visibility) {
9846
9847  IdentifierInfo *II = D.getIdentifier();
9848  Expr *BitWidth = (Expr*)BitfieldWidth;
9849  SourceLocation Loc = DeclStart;
9850  if (II) Loc = D.getIdentifierLoc();
9851
9852  // FIXME: Unnamed fields can be handled in various different ways, for
9853  // example, unnamed unions inject all members into the struct namespace!
9854
9855  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9856  QualType T = TInfo->getType();
9857
9858  if (BitWidth) {
9859    // 6.7.2.1p3, 6.7.2.1p4
9860    BitWidth = VerifyBitField(Loc, II, T, BitWidth).take();
9861    if (!BitWidth)
9862      D.setInvalidType();
9863  } else {
9864    // Not a bitfield.
9865
9866    // validate II.
9867
9868  }
9869  if (T->isReferenceType()) {
9870    Diag(Loc, diag::err_ivar_reference_type);
9871    D.setInvalidType();
9872  }
9873  // C99 6.7.2.1p8: A member of a structure or union may have any type other
9874  // than a variably modified type.
9875  else if (T->isVariablyModifiedType()) {
9876    Diag(Loc, diag::err_typecheck_ivar_variable_size);
9877    D.setInvalidType();
9878  }
9879
9880  // Get the visibility (access control) for this ivar.
9881  ObjCIvarDecl::AccessControl ac =
9882    Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
9883                                        : ObjCIvarDecl::None;
9884  // Must set ivar's DeclContext to its enclosing interface.
9885  ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
9886  if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
9887    return 0;
9888  ObjCContainerDecl *EnclosingContext;
9889  if (ObjCImplementationDecl *IMPDecl =
9890      dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
9891    if (LangOpts.ObjCRuntime.isFragile()) {
9892    // Case of ivar declared in an implementation. Context is that of its class.
9893      EnclosingContext = IMPDecl->getClassInterface();
9894      assert(EnclosingContext && "Implementation has no class interface!");
9895    }
9896    else
9897      EnclosingContext = EnclosingDecl;
9898  } else {
9899    if (ObjCCategoryDecl *CDecl =
9900        dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
9901      if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
9902        Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
9903        return 0;
9904      }
9905    }
9906    EnclosingContext = EnclosingDecl;
9907  }
9908
9909  // Construct the decl.
9910  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
9911                                             DeclStart, Loc, II, T,
9912                                             TInfo, ac, (Expr *)BitfieldWidth);
9913
9914  if (II) {
9915    NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
9916                                           ForRedeclaration);
9917    if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
9918        && !isa<TagDecl>(PrevDecl)) {
9919      Diag(Loc, diag::err_duplicate_member) << II;
9920      Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9921      NewID->setInvalidDecl();
9922    }
9923  }
9924
9925  // Process attributes attached to the ivar.
9926  ProcessDeclAttributes(S, NewID, D);
9927
9928  if (D.isInvalidType())
9929    NewID->setInvalidDecl();
9930
9931  // In ARC, infer 'retaining' for ivars of retainable type.
9932  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
9933    NewID->setInvalidDecl();
9934
9935  if (D.getDeclSpec().isModulePrivateSpecified())
9936    NewID->setModulePrivate();
9937
9938  if (II) {
9939    // FIXME: When interfaces are DeclContexts, we'll need to add
9940    // these to the interface.
9941    S->AddDecl(NewID);
9942    IdResolver.AddDecl(NewID);
9943  }
9944
9945  if (LangOpts.ObjCRuntime.isNonFragile() &&
9946      !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
9947    Diag(Loc, diag::warn_ivars_in_interface);
9948
9949  return NewID;
9950}
9951
9952/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
9953/// class and class extensions. For every class @interface and class
9954/// extension @interface, if the last ivar is a bitfield of any type,
9955/// then add an implicit `char :0` ivar to the end of that interface.
9956void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
9957                             SmallVectorImpl<Decl *> &AllIvarDecls) {
9958  if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
9959    return;
9960
9961  Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
9962  ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
9963
9964  if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
9965    return;
9966  ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
9967  if (!ID) {
9968    if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
9969      if (!CD->IsClassExtension())
9970        return;
9971    }
9972    // No need to add this to end of @implementation.
9973    else
9974      return;
9975  }
9976  // All conditions are met. Add a new bitfield to the tail end of ivars.
9977  llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
9978  Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
9979
9980  Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
9981                              DeclLoc, DeclLoc, 0,
9982                              Context.CharTy,
9983                              Context.getTrivialTypeSourceInfo(Context.CharTy,
9984                                                               DeclLoc),
9985                              ObjCIvarDecl::Private, BW,
9986                              true);
9987  AllIvarDecls.push_back(Ivar);
9988}
9989
9990void Sema::ActOnFields(Scope* S,
9991                       SourceLocation RecLoc, Decl *EnclosingDecl,
9992                       llvm::ArrayRef<Decl *> Fields,
9993                       SourceLocation LBrac, SourceLocation RBrac,
9994                       AttributeList *Attr) {
9995  assert(EnclosingDecl && "missing record or interface decl");
9996
9997  // If this is an Objective-C @implementation or category and we have
9998  // new fields here we should reset the layout of the interface since
9999  // it will now change.
10000  if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
10001    ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
10002    switch (DC->getKind()) {
10003    default: break;
10004    case Decl::ObjCCategory:
10005      Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
10006      break;
10007    case Decl::ObjCImplementation:
10008      Context.
10009        ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
10010      break;
10011    }
10012  }
10013
10014  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
10015
10016  // Start counting up the number of named members; make sure to include
10017  // members of anonymous structs and unions in the total.
10018  unsigned NumNamedMembers = 0;
10019  if (Record) {
10020    for (RecordDecl::decl_iterator i = Record->decls_begin(),
10021                                   e = Record->decls_end(); i != e; i++) {
10022      if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
10023        if (IFD->getDeclName())
10024          ++NumNamedMembers;
10025    }
10026  }
10027
10028  // Verify that all the fields are okay.
10029  SmallVector<FieldDecl*, 32> RecFields;
10030
10031  bool ARCErrReported = false;
10032  for (llvm::ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
10033       i != end; ++i) {
10034    FieldDecl *FD = cast<FieldDecl>(*i);
10035
10036    // Get the type for the field.
10037    const Type *FDTy = FD->getType().getTypePtr();
10038
10039    if (!FD->isAnonymousStructOrUnion()) {
10040      // Remember all fields written by the user.
10041      RecFields.push_back(FD);
10042    }
10043
10044    // If the field is already invalid for some reason, don't emit more
10045    // diagnostics about it.
10046    if (FD->isInvalidDecl()) {
10047      EnclosingDecl->setInvalidDecl();
10048      continue;
10049    }
10050
10051    // C99 6.7.2.1p2:
10052    //   A structure or union shall not contain a member with
10053    //   incomplete or function type (hence, a structure shall not
10054    //   contain an instance of itself, but may contain a pointer to
10055    //   an instance of itself), except that the last member of a
10056    //   structure with more than one named member may have incomplete
10057    //   array type; such a structure (and any union containing,
10058    //   possibly recursively, a member that is such a structure)
10059    //   shall not be a member of a structure or an element of an
10060    //   array.
10061    if (FDTy->isFunctionType()) {
10062      // Field declared as a function.
10063      Diag(FD->getLocation(), diag::err_field_declared_as_function)
10064        << FD->getDeclName();
10065      FD->setInvalidDecl();
10066      EnclosingDecl->setInvalidDecl();
10067      continue;
10068    } else if (FDTy->isIncompleteArrayType() && Record &&
10069               ((i + 1 == Fields.end() && !Record->isUnion()) ||
10070                ((getLangOpts().MicrosoftExt ||
10071                  getLangOpts().CPlusPlus) &&
10072                 (i + 1 == Fields.end() || Record->isUnion())))) {
10073      // Flexible array member.
10074      // Microsoft and g++ is more permissive regarding flexible array.
10075      // It will accept flexible array in union and also
10076      // as the sole element of a struct/class.
10077      if (getLangOpts().MicrosoftExt) {
10078        if (Record->isUnion())
10079          Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
10080            << FD->getDeclName();
10081        else if (Fields.size() == 1)
10082          Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
10083            << FD->getDeclName() << Record->getTagKind();
10084      } else if (getLangOpts().CPlusPlus) {
10085        if (Record->isUnion())
10086          Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
10087            << FD->getDeclName();
10088        else if (Fields.size() == 1)
10089          Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
10090            << FD->getDeclName() << Record->getTagKind();
10091      } else if (!getLangOpts().C99) {
10092      if (Record->isUnion())
10093        Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
10094          << FD->getDeclName();
10095      else
10096        Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
10097          << FD->getDeclName() << Record->getTagKind();
10098      } else if (NumNamedMembers < 1) {
10099        Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
10100          << FD->getDeclName();
10101        FD->setInvalidDecl();
10102        EnclosingDecl->setInvalidDecl();
10103        continue;
10104      }
10105      if (!FD->getType()->isDependentType() &&
10106          !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
10107        Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
10108          << FD->getDeclName() << FD->getType();
10109        FD->setInvalidDecl();
10110        EnclosingDecl->setInvalidDecl();
10111        continue;
10112      }
10113      // Okay, we have a legal flexible array member at the end of the struct.
10114      if (Record)
10115        Record->setHasFlexibleArrayMember(true);
10116    } else if (!FDTy->isDependentType() &&
10117               RequireCompleteType(FD->getLocation(), FD->getType(),
10118                                   diag::err_field_incomplete)) {
10119      // Incomplete type
10120      FD->setInvalidDecl();
10121      EnclosingDecl->setInvalidDecl();
10122      continue;
10123    } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
10124      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
10125        // If this is a member of a union, then entire union becomes "flexible".
10126        if (Record && Record->isUnion()) {
10127          Record->setHasFlexibleArrayMember(true);
10128        } else {
10129          // If this is a struct/class and this is not the last element, reject
10130          // it.  Note that GCC supports variable sized arrays in the middle of
10131          // structures.
10132          if (i + 1 != Fields.end())
10133            Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
10134              << FD->getDeclName() << FD->getType();
10135          else {
10136            // We support flexible arrays at the end of structs in
10137            // other structs as an extension.
10138            Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
10139              << FD->getDeclName();
10140            if (Record)
10141              Record->setHasFlexibleArrayMember(true);
10142          }
10143        }
10144      }
10145      if (isa<ObjCContainerDecl>(EnclosingDecl) &&
10146          RequireNonAbstractType(FD->getLocation(), FD->getType(),
10147                                 diag::err_abstract_type_in_decl,
10148                                 AbstractIvarType)) {
10149        // Ivars can not have abstract class types
10150        FD->setInvalidDecl();
10151      }
10152      if (Record && FDTTy->getDecl()->hasObjectMember())
10153        Record->setHasObjectMember(true);
10154    } else if (FDTy->isObjCObjectType()) {
10155      /// A field cannot be an Objective-c object
10156      Diag(FD->getLocation(), diag::err_statically_allocated_object)
10157        << FixItHint::CreateInsertion(FD->getLocation(), "*");
10158      QualType T = Context.getObjCObjectPointerType(FD->getType());
10159      FD->setType(T);
10160    } else if (!getLangOpts().CPlusPlus) {
10161      if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported) {
10162        // It's an error in ARC if a field has lifetime.
10163        // We don't want to report this in a system header, though,
10164        // so we just make the field unavailable.
10165        // FIXME: that's really not sufficient; we need to make the type
10166        // itself invalid to, say, initialize or copy.
10167        QualType T = FD->getType();
10168        Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
10169        if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
10170          SourceLocation loc = FD->getLocation();
10171          if (getSourceManager().isInSystemHeader(loc)) {
10172            if (!FD->hasAttr<UnavailableAttr>()) {
10173              FD->addAttr(new (Context) UnavailableAttr(loc, Context,
10174                                "this system field has retaining ownership"));
10175            }
10176          } else {
10177            Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct)
10178              << T->isBlockPointerType();
10179          }
10180          ARCErrReported = true;
10181        }
10182      }
10183      else if (getLangOpts().ObjC1 &&
10184               getLangOpts().getGC() != LangOptions::NonGC &&
10185               Record && !Record->hasObjectMember()) {
10186        if (FD->getType()->isObjCObjectPointerType() ||
10187            FD->getType().isObjCGCStrong())
10188          Record->setHasObjectMember(true);
10189        else if (Context.getAsArrayType(FD->getType())) {
10190          QualType BaseType = Context.getBaseElementType(FD->getType());
10191          if (BaseType->isRecordType() &&
10192              BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
10193            Record->setHasObjectMember(true);
10194          else if (BaseType->isObjCObjectPointerType() ||
10195                   BaseType.isObjCGCStrong())
10196                 Record->setHasObjectMember(true);
10197        }
10198      }
10199    }
10200    // Keep track of the number of named members.
10201    if (FD->getIdentifier())
10202      ++NumNamedMembers;
10203  }
10204
10205  // Okay, we successfully defined 'Record'.
10206  if (Record) {
10207    bool Completed = false;
10208    if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
10209      if (!CXXRecord->isInvalidDecl()) {
10210        // Set access bits correctly on the directly-declared conversions.
10211        for (CXXRecordDecl::conversion_iterator
10212               I = CXXRecord->conversion_begin(),
10213               E = CXXRecord->conversion_end(); I != E; ++I)
10214          I.setAccess((*I)->getAccess());
10215
10216        if (!CXXRecord->isDependentType()) {
10217          // Adjust user-defined destructor exception spec.
10218          if (getLangOpts().CPlusPlus0x &&
10219              CXXRecord->hasUserDeclaredDestructor())
10220            AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor());
10221
10222          // Add any implicitly-declared members to this class.
10223          AddImplicitlyDeclaredMembersToClass(CXXRecord);
10224
10225          // If we have virtual base classes, we may end up finding multiple
10226          // final overriders for a given virtual function. Check for this
10227          // problem now.
10228          if (CXXRecord->getNumVBases()) {
10229            CXXFinalOverriderMap FinalOverriders;
10230            CXXRecord->getFinalOverriders(FinalOverriders);
10231
10232            for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
10233                                             MEnd = FinalOverriders.end();
10234                 M != MEnd; ++M) {
10235              for (OverridingMethods::iterator SO = M->second.begin(),
10236                                            SOEnd = M->second.end();
10237                   SO != SOEnd; ++SO) {
10238                assert(SO->second.size() > 0 &&
10239                       "Virtual function without overridding functions?");
10240                if (SO->second.size() == 1)
10241                  continue;
10242
10243                // C++ [class.virtual]p2:
10244                //   In a derived class, if a virtual member function of a base
10245                //   class subobject has more than one final overrider the
10246                //   program is ill-formed.
10247                Diag(Record->getLocation(), diag::err_multiple_final_overriders)
10248                  << (const NamedDecl *)M->first << Record;
10249                Diag(M->first->getLocation(),
10250                     diag::note_overridden_virtual_function);
10251                for (OverridingMethods::overriding_iterator
10252                          OM = SO->second.begin(),
10253                       OMEnd = SO->second.end();
10254                     OM != OMEnd; ++OM)
10255                  Diag(OM->Method->getLocation(), diag::note_final_overrider)
10256                    << (const NamedDecl *)M->first << OM->Method->getParent();
10257
10258                Record->setInvalidDecl();
10259              }
10260            }
10261            CXXRecord->completeDefinition(&FinalOverriders);
10262            Completed = true;
10263          }
10264        }
10265      }
10266    }
10267
10268    if (!Completed)
10269      Record->completeDefinition();
10270
10271  } else {
10272    ObjCIvarDecl **ClsFields =
10273      reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
10274    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
10275      ID->setEndOfDefinitionLoc(RBrac);
10276      // Add ivar's to class's DeclContext.
10277      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
10278        ClsFields[i]->setLexicalDeclContext(ID);
10279        ID->addDecl(ClsFields[i]);
10280      }
10281      // Must enforce the rule that ivars in the base classes may not be
10282      // duplicates.
10283      if (ID->getSuperClass())
10284        DiagnoseDuplicateIvars(ID, ID->getSuperClass());
10285    } else if (ObjCImplementationDecl *IMPDecl =
10286                  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
10287      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
10288      for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
10289        // Ivar declared in @implementation never belongs to the implementation.
10290        // Only it is in implementation's lexical context.
10291        ClsFields[I]->setLexicalDeclContext(IMPDecl);
10292      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
10293      IMPDecl->setIvarLBraceLoc(LBrac);
10294      IMPDecl->setIvarRBraceLoc(RBrac);
10295    } else if (ObjCCategoryDecl *CDecl =
10296                dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
10297      // case of ivars in class extension; all other cases have been
10298      // reported as errors elsewhere.
10299      // FIXME. Class extension does not have a LocEnd field.
10300      // CDecl->setLocEnd(RBrac);
10301      // Add ivar's to class extension's DeclContext.
10302      // Diagnose redeclaration of private ivars.
10303      ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
10304      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
10305        if (IDecl) {
10306          if (const ObjCIvarDecl *ClsIvar =
10307              IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
10308            Diag(ClsFields[i]->getLocation(),
10309                 diag::err_duplicate_ivar_declaration);
10310            Diag(ClsIvar->getLocation(), diag::note_previous_definition);
10311            continue;
10312          }
10313          for (const ObjCCategoryDecl *ClsExtDecl =
10314                IDecl->getFirstClassExtension();
10315               ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
10316            if (const ObjCIvarDecl *ClsExtIvar =
10317                ClsExtDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
10318              Diag(ClsFields[i]->getLocation(),
10319                   diag::err_duplicate_ivar_declaration);
10320              Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
10321              continue;
10322            }
10323          }
10324        }
10325        ClsFields[i]->setLexicalDeclContext(CDecl);
10326        CDecl->addDecl(ClsFields[i]);
10327      }
10328      CDecl->setIvarLBraceLoc(LBrac);
10329      CDecl->setIvarRBraceLoc(RBrac);
10330    }
10331  }
10332
10333  if (Attr)
10334    ProcessDeclAttributeList(S, Record, Attr);
10335}
10336
10337/// \brief Determine whether the given integral value is representable within
10338/// the given type T.
10339static bool isRepresentableIntegerValue(ASTContext &Context,
10340                                        llvm::APSInt &Value,
10341                                        QualType T) {
10342  assert(T->isIntegralType(Context) && "Integral type required!");
10343  unsigned BitWidth = Context.getIntWidth(T);
10344
10345  if (Value.isUnsigned() || Value.isNonNegative()) {
10346    if (T->isSignedIntegerOrEnumerationType())
10347      --BitWidth;
10348    return Value.getActiveBits() <= BitWidth;
10349  }
10350  return Value.getMinSignedBits() <= BitWidth;
10351}
10352
10353// \brief Given an integral type, return the next larger integral type
10354// (or a NULL type of no such type exists).
10355static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
10356  // FIXME: Int128/UInt128 support, which also needs to be introduced into
10357  // enum checking below.
10358  assert(T->isIntegralType(Context) && "Integral type required!");
10359  const unsigned NumTypes = 4;
10360  QualType SignedIntegralTypes[NumTypes] = {
10361    Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
10362  };
10363  QualType UnsignedIntegralTypes[NumTypes] = {
10364    Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
10365    Context.UnsignedLongLongTy
10366  };
10367
10368  unsigned BitWidth = Context.getTypeSize(T);
10369  QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
10370                                                        : UnsignedIntegralTypes;
10371  for (unsigned I = 0; I != NumTypes; ++I)
10372    if (Context.getTypeSize(Types[I]) > BitWidth)
10373      return Types[I];
10374
10375  return QualType();
10376}
10377
10378EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
10379                                          EnumConstantDecl *LastEnumConst,
10380                                          SourceLocation IdLoc,
10381                                          IdentifierInfo *Id,
10382                                          Expr *Val) {
10383  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
10384  llvm::APSInt EnumVal(IntWidth);
10385  QualType EltTy;
10386
10387  if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
10388    Val = 0;
10389
10390  if (Val)
10391    Val = DefaultLvalueConversion(Val).take();
10392
10393  if (Val) {
10394    if (Enum->isDependentType() || Val->isTypeDependent())
10395      EltTy = Context.DependentTy;
10396    else {
10397      SourceLocation ExpLoc;
10398      if (getLangOpts().CPlusPlus0x && Enum->isFixed() &&
10399          !getLangOpts().MicrosoftMode) {
10400        // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
10401        // constant-expression in the enumerator-definition shall be a converted
10402        // constant expression of the underlying type.
10403        EltTy = Enum->getIntegerType();
10404        ExprResult Converted =
10405          CheckConvertedConstantExpression(Val, EltTy, EnumVal,
10406                                           CCEK_Enumerator);
10407        if (Converted.isInvalid())
10408          Val = 0;
10409        else
10410          Val = Converted.take();
10411      } else if (!Val->isValueDependent() &&
10412                 !(Val = VerifyIntegerConstantExpression(Val,
10413                                                         &EnumVal).take())) {
10414        // C99 6.7.2.2p2: Make sure we have an integer constant expression.
10415      } else {
10416        if (Enum->isFixed()) {
10417          EltTy = Enum->getIntegerType();
10418
10419          // In Obj-C and Microsoft mode, require the enumeration value to be
10420          // representable in the underlying type of the enumeration. In C++11,
10421          // we perform a non-narrowing conversion as part of converted constant
10422          // expression checking.
10423          if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
10424            if (getLangOpts().MicrosoftMode) {
10425              Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
10426              Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
10427            } else
10428              Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
10429          } else
10430            Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
10431        } else if (getLangOpts().CPlusPlus) {
10432          // C++11 [dcl.enum]p5:
10433          //   If the underlying type is not fixed, the type of each enumerator
10434          //   is the type of its initializing value:
10435          //     - If an initializer is specified for an enumerator, the
10436          //       initializing value has the same type as the expression.
10437          EltTy = Val->getType();
10438        } else {
10439          // C99 6.7.2.2p2:
10440          //   The expression that defines the value of an enumeration constant
10441          //   shall be an integer constant expression that has a value
10442          //   representable as an int.
10443
10444          // Complain if the value is not representable in an int.
10445          if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
10446            Diag(IdLoc, diag::ext_enum_value_not_int)
10447              << EnumVal.toString(10) << Val->getSourceRange()
10448              << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
10449          else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
10450            // Force the type of the expression to 'int'.
10451            Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
10452          }
10453          EltTy = Val->getType();
10454        }
10455      }
10456    }
10457  }
10458
10459  if (!Val) {
10460    if (Enum->isDependentType())
10461      EltTy = Context.DependentTy;
10462    else if (!LastEnumConst) {
10463      // C++0x [dcl.enum]p5:
10464      //   If the underlying type is not fixed, the type of each enumerator
10465      //   is the type of its initializing value:
10466      //     - If no initializer is specified for the first enumerator, the
10467      //       initializing value has an unspecified integral type.
10468      //
10469      // GCC uses 'int' for its unspecified integral type, as does
10470      // C99 6.7.2.2p3.
10471      if (Enum->isFixed()) {
10472        EltTy = Enum->getIntegerType();
10473      }
10474      else {
10475        EltTy = Context.IntTy;
10476      }
10477    } else {
10478      // Assign the last value + 1.
10479      EnumVal = LastEnumConst->getInitVal();
10480      ++EnumVal;
10481      EltTy = LastEnumConst->getType();
10482
10483      // Check for overflow on increment.
10484      if (EnumVal < LastEnumConst->getInitVal()) {
10485        // C++0x [dcl.enum]p5:
10486        //   If the underlying type is not fixed, the type of each enumerator
10487        //   is the type of its initializing value:
10488        //
10489        //     - Otherwise the type of the initializing value is the same as
10490        //       the type of the initializing value of the preceding enumerator
10491        //       unless the incremented value is not representable in that type,
10492        //       in which case the type is an unspecified integral type
10493        //       sufficient to contain the incremented value. If no such type
10494        //       exists, the program is ill-formed.
10495        QualType T = getNextLargerIntegralType(Context, EltTy);
10496        if (T.isNull() || Enum->isFixed()) {
10497          // There is no integral type larger enough to represent this
10498          // value. Complain, then allow the value to wrap around.
10499          EnumVal = LastEnumConst->getInitVal();
10500          EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
10501          ++EnumVal;
10502          if (Enum->isFixed())
10503            // When the underlying type is fixed, this is ill-formed.
10504            Diag(IdLoc, diag::err_enumerator_wrapped)
10505              << EnumVal.toString(10)
10506              << EltTy;
10507          else
10508            Diag(IdLoc, diag::warn_enumerator_too_large)
10509              << EnumVal.toString(10);
10510        } else {
10511          EltTy = T;
10512        }
10513
10514        // Retrieve the last enumerator's value, extent that type to the
10515        // type that is supposed to be large enough to represent the incremented
10516        // value, then increment.
10517        EnumVal = LastEnumConst->getInitVal();
10518        EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
10519        EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
10520        ++EnumVal;
10521
10522        // If we're not in C++, diagnose the overflow of enumerator values,
10523        // which in C99 means that the enumerator value is not representable in
10524        // an int (C99 6.7.2.2p2). However, we support GCC's extension that
10525        // permits enumerator values that are representable in some larger
10526        // integral type.
10527        if (!getLangOpts().CPlusPlus && !T.isNull())
10528          Diag(IdLoc, diag::warn_enum_value_overflow);
10529      } else if (!getLangOpts().CPlusPlus &&
10530                 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
10531        // Enforce C99 6.7.2.2p2 even when we compute the next value.
10532        Diag(IdLoc, diag::ext_enum_value_not_int)
10533          << EnumVal.toString(10) << 1;
10534      }
10535    }
10536  }
10537
10538  if (!EltTy->isDependentType()) {
10539    // Make the enumerator value match the signedness and size of the
10540    // enumerator's type.
10541    EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
10542    EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
10543  }
10544
10545  return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
10546                                  Val, EnumVal);
10547}
10548
10549
10550Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
10551                              SourceLocation IdLoc, IdentifierInfo *Id,
10552                              AttributeList *Attr,
10553                              SourceLocation EqualLoc, Expr *Val) {
10554  EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
10555  EnumConstantDecl *LastEnumConst =
10556    cast_or_null<EnumConstantDecl>(lastEnumConst);
10557
10558  // The scope passed in may not be a decl scope.  Zip up the scope tree until
10559  // we find one that is.
10560  S = getNonFieldDeclScope(S);
10561
10562  // Verify that there isn't already something declared with this name in this
10563  // scope.
10564  NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
10565                                         ForRedeclaration);
10566  if (PrevDecl && PrevDecl->isTemplateParameter()) {
10567    // Maybe we will complain about the shadowed template parameter.
10568    DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
10569    // Just pretend that we didn't see the previous declaration.
10570    PrevDecl = 0;
10571  }
10572
10573  if (PrevDecl) {
10574    // When in C++, we may get a TagDecl with the same name; in this case the
10575    // enum constant will 'hide' the tag.
10576    assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
10577           "Received TagDecl when not in C++!");
10578    if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
10579      if (isa<EnumConstantDecl>(PrevDecl))
10580        Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
10581      else
10582        Diag(IdLoc, diag::err_redefinition) << Id;
10583      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10584      return 0;
10585    }
10586  }
10587
10588  // C++ [class.mem]p15:
10589  // If T is the name of a class, then each of the following shall have a name
10590  // different from T:
10591  // - every enumerator of every member of class T that is an unscoped
10592  // enumerated type
10593  if (CXXRecordDecl *Record
10594                      = dyn_cast<CXXRecordDecl>(
10595                             TheEnumDecl->getDeclContext()->getRedeclContext()))
10596    if (!TheEnumDecl->isScoped() &&
10597        Record->getIdentifier() && Record->getIdentifier() == Id)
10598      Diag(IdLoc, diag::err_member_name_of_class) << Id;
10599
10600  EnumConstantDecl *New =
10601    CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
10602
10603  if (New) {
10604    // Process attributes.
10605    if (Attr) ProcessDeclAttributeList(S, New, Attr);
10606
10607    // Register this decl in the current scope stack.
10608    New->setAccess(TheEnumDecl->getAccess());
10609    PushOnScopeChains(New, S);
10610  }
10611
10612  ActOnDocumentableDecl(New);
10613
10614  return New;
10615}
10616
10617void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
10618                         SourceLocation RBraceLoc, Decl *EnumDeclX,
10619                         Decl **Elements, unsigned NumElements,
10620                         Scope *S, AttributeList *Attr) {
10621  EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
10622  QualType EnumType = Context.getTypeDeclType(Enum);
10623
10624  if (Attr)
10625    ProcessDeclAttributeList(S, Enum, Attr);
10626
10627  if (Enum->isDependentType()) {
10628    for (unsigned i = 0; i != NumElements; ++i) {
10629      EnumConstantDecl *ECD =
10630        cast_or_null<EnumConstantDecl>(Elements[i]);
10631      if (!ECD) continue;
10632
10633      ECD->setType(EnumType);
10634    }
10635
10636    Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
10637    return;
10638  }
10639
10640  // TODO: If the result value doesn't fit in an int, it must be a long or long
10641  // long value.  ISO C does not support this, but GCC does as an extension,
10642  // emit a warning.
10643  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
10644  unsigned CharWidth = Context.getTargetInfo().getCharWidth();
10645  unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
10646
10647  // Verify that all the values are okay, compute the size of the values, and
10648  // reverse the list.
10649  unsigned NumNegativeBits = 0;
10650  unsigned NumPositiveBits = 0;
10651
10652  // Keep track of whether all elements have type int.
10653  bool AllElementsInt = true;
10654
10655  for (unsigned i = 0; i != NumElements; ++i) {
10656    EnumConstantDecl *ECD =
10657      cast_or_null<EnumConstantDecl>(Elements[i]);
10658    if (!ECD) continue;  // Already issued a diagnostic.
10659
10660    const llvm::APSInt &InitVal = ECD->getInitVal();
10661
10662    // Keep track of the size of positive and negative values.
10663    if (InitVal.isUnsigned() || InitVal.isNonNegative())
10664      NumPositiveBits = std::max(NumPositiveBits,
10665                                 (unsigned)InitVal.getActiveBits());
10666    else
10667      NumNegativeBits = std::max(NumNegativeBits,
10668                                 (unsigned)InitVal.getMinSignedBits());
10669
10670    // Keep track of whether every enum element has type int (very commmon).
10671    if (AllElementsInt)
10672      AllElementsInt = ECD->getType() == Context.IntTy;
10673  }
10674
10675  // Figure out the type that should be used for this enum.
10676  QualType BestType;
10677  unsigned BestWidth;
10678
10679  // C++0x N3000 [conv.prom]p3:
10680  //   An rvalue of an unscoped enumeration type whose underlying
10681  //   type is not fixed can be converted to an rvalue of the first
10682  //   of the following types that can represent all the values of
10683  //   the enumeration: int, unsigned int, long int, unsigned long
10684  //   int, long long int, or unsigned long long int.
10685  // C99 6.4.4.3p2:
10686  //   An identifier declared as an enumeration constant has type int.
10687  // The C99 rule is modified by a gcc extension
10688  QualType BestPromotionType;
10689
10690  bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
10691  // -fshort-enums is the equivalent to specifying the packed attribute on all
10692  // enum definitions.
10693  if (LangOpts.ShortEnums)
10694    Packed = true;
10695
10696  if (Enum->isFixed()) {
10697    BestType = Enum->getIntegerType();
10698    if (BestType->isPromotableIntegerType())
10699      BestPromotionType = Context.getPromotedIntegerType(BestType);
10700    else
10701      BestPromotionType = BestType;
10702    // We don't need to set BestWidth, because BestType is going to be the type
10703    // of the enumerators, but we do anyway because otherwise some compilers
10704    // warn that it might be used uninitialized.
10705    BestWidth = CharWidth;
10706  }
10707  else if (NumNegativeBits) {
10708    // If there is a negative value, figure out the smallest integer type (of
10709    // int/long/longlong) that fits.
10710    // If it's packed, check also if it fits a char or a short.
10711    if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
10712      BestType = Context.SignedCharTy;
10713      BestWidth = CharWidth;
10714    } else if (Packed && NumNegativeBits <= ShortWidth &&
10715               NumPositiveBits < ShortWidth) {
10716      BestType = Context.ShortTy;
10717      BestWidth = ShortWidth;
10718    } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
10719      BestType = Context.IntTy;
10720      BestWidth = IntWidth;
10721    } else {
10722      BestWidth = Context.getTargetInfo().getLongWidth();
10723
10724      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
10725        BestType = Context.LongTy;
10726      } else {
10727        BestWidth = Context.getTargetInfo().getLongLongWidth();
10728
10729        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
10730          Diag(Enum->getLocation(), diag::warn_enum_too_large);
10731        BestType = Context.LongLongTy;
10732      }
10733    }
10734    BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
10735  } else {
10736    // If there is no negative value, figure out the smallest type that fits
10737    // all of the enumerator values.
10738    // If it's packed, check also if it fits a char or a short.
10739    if (Packed && NumPositiveBits <= CharWidth) {
10740      BestType = Context.UnsignedCharTy;
10741      BestPromotionType = Context.IntTy;
10742      BestWidth = CharWidth;
10743    } else if (Packed && NumPositiveBits <= ShortWidth) {
10744      BestType = Context.UnsignedShortTy;
10745      BestPromotionType = Context.IntTy;
10746      BestWidth = ShortWidth;
10747    } else if (NumPositiveBits <= IntWidth) {
10748      BestType = Context.UnsignedIntTy;
10749      BestWidth = IntWidth;
10750      BestPromotionType
10751        = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
10752                           ? Context.UnsignedIntTy : Context.IntTy;
10753    } else if (NumPositiveBits <=
10754               (BestWidth = Context.getTargetInfo().getLongWidth())) {
10755      BestType = Context.UnsignedLongTy;
10756      BestPromotionType
10757        = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
10758                           ? Context.UnsignedLongTy : Context.LongTy;
10759    } else {
10760      BestWidth = Context.getTargetInfo().getLongLongWidth();
10761      assert(NumPositiveBits <= BestWidth &&
10762             "How could an initializer get larger than ULL?");
10763      BestType = Context.UnsignedLongLongTy;
10764      BestPromotionType
10765        = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
10766                           ? Context.UnsignedLongLongTy : Context.LongLongTy;
10767    }
10768  }
10769
10770  // Loop over all of the enumerator constants, changing their types to match
10771  // the type of the enum if needed.
10772  for (unsigned i = 0; i != NumElements; ++i) {
10773    EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
10774    if (!ECD) continue;  // Already issued a diagnostic.
10775
10776    // Standard C says the enumerators have int type, but we allow, as an
10777    // extension, the enumerators to be larger than int size.  If each
10778    // enumerator value fits in an int, type it as an int, otherwise type it the
10779    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
10780    // that X has type 'int', not 'unsigned'.
10781
10782    // Determine whether the value fits into an int.
10783    llvm::APSInt InitVal = ECD->getInitVal();
10784
10785    // If it fits into an integer type, force it.  Otherwise force it to match
10786    // the enum decl type.
10787    QualType NewTy;
10788    unsigned NewWidth;
10789    bool NewSign;
10790    if (!getLangOpts().CPlusPlus &&
10791        !Enum->isFixed() &&
10792        isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
10793      NewTy = Context.IntTy;
10794      NewWidth = IntWidth;
10795      NewSign = true;
10796    } else if (ECD->getType() == BestType) {
10797      // Already the right type!
10798      if (getLangOpts().CPlusPlus)
10799        // C++ [dcl.enum]p4: Following the closing brace of an
10800        // enum-specifier, each enumerator has the type of its
10801        // enumeration.
10802        ECD->setType(EnumType);
10803      continue;
10804    } else {
10805      NewTy = BestType;
10806      NewWidth = BestWidth;
10807      NewSign = BestType->isSignedIntegerOrEnumerationType();
10808    }
10809
10810    // Adjust the APSInt value.
10811    InitVal = InitVal.extOrTrunc(NewWidth);
10812    InitVal.setIsSigned(NewSign);
10813    ECD->setInitVal(InitVal);
10814
10815    // Adjust the Expr initializer and type.
10816    if (ECD->getInitExpr() &&
10817        !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
10818      ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
10819                                                CK_IntegralCast,
10820                                                ECD->getInitExpr(),
10821                                                /*base paths*/ 0,
10822                                                VK_RValue));
10823    if (getLangOpts().CPlusPlus)
10824      // C++ [dcl.enum]p4: Following the closing brace of an
10825      // enum-specifier, each enumerator has the type of its
10826      // enumeration.
10827      ECD->setType(EnumType);
10828    else
10829      ECD->setType(NewTy);
10830  }
10831
10832  Enum->completeDefinition(BestType, BestPromotionType,
10833                           NumPositiveBits, NumNegativeBits);
10834
10835  // If we're declaring a function, ensure this decl isn't forgotten about -
10836  // it needs to go into the function scope.
10837  if (InFunctionDeclarator)
10838    DeclsInPrototypeScope.push_back(Enum);
10839}
10840
10841Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
10842                                  SourceLocation StartLoc,
10843                                  SourceLocation EndLoc) {
10844  StringLiteral *AsmString = cast<StringLiteral>(expr);
10845
10846  FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
10847                                                   AsmString, StartLoc,
10848                                                   EndLoc);
10849  CurContext->addDecl(New);
10850  return New;
10851}
10852
10853DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
10854                                   SourceLocation ImportLoc,
10855                                   ModuleIdPath Path) {
10856  Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
10857                                                Module::AllVisible,
10858                                                /*IsIncludeDirective=*/false);
10859  if (!Mod)
10860    return true;
10861
10862  llvm::SmallVector<SourceLocation, 2> IdentifierLocs;
10863  Module *ModCheck = Mod;
10864  for (unsigned I = 0, N = Path.size(); I != N; ++I) {
10865    // If we've run out of module parents, just drop the remaining identifiers.
10866    // We need the length to be consistent.
10867    if (!ModCheck)
10868      break;
10869    ModCheck = ModCheck->Parent;
10870
10871    IdentifierLocs.push_back(Path[I].second);
10872  }
10873
10874  ImportDecl *Import = ImportDecl::Create(Context,
10875                                          Context.getTranslationUnitDecl(),
10876                                          AtLoc.isValid()? AtLoc : ImportLoc,
10877                                          Mod, IdentifierLocs);
10878  Context.getTranslationUnitDecl()->addDecl(Import);
10879  return Import;
10880}
10881
10882void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
10883                                      IdentifierInfo* AliasName,
10884                                      SourceLocation PragmaLoc,
10885                                      SourceLocation NameLoc,
10886                                      SourceLocation AliasNameLoc) {
10887  Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
10888                                    LookupOrdinaryName);
10889  AsmLabelAttr *Attr =
10890     ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
10891
10892  if (PrevDecl)
10893    PrevDecl->addAttr(Attr);
10894  else
10895    (void)ExtnameUndeclaredIdentifiers.insert(
10896      std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
10897}
10898
10899void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
10900                             SourceLocation PragmaLoc,
10901                             SourceLocation NameLoc) {
10902  Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
10903
10904  if (PrevDecl) {
10905    PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
10906  } else {
10907    (void)WeakUndeclaredIdentifiers.insert(
10908      std::pair<IdentifierInfo*,WeakInfo>
10909        (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
10910  }
10911}
10912
10913void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
10914                                IdentifierInfo* AliasName,
10915                                SourceLocation PragmaLoc,
10916                                SourceLocation NameLoc,
10917                                SourceLocation AliasNameLoc) {
10918  Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
10919                                    LookupOrdinaryName);
10920  WeakInfo W = WeakInfo(Name, NameLoc);
10921
10922  if (PrevDecl) {
10923    if (!PrevDecl->hasAttr<AliasAttr>())
10924      if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
10925        DeclApplyPragmaWeak(TUScope, ND, W);
10926  } else {
10927    (void)WeakUndeclaredIdentifiers.insert(
10928      std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
10929  }
10930}
10931
10932Decl *Sema::getObjCDeclContext() const {
10933  return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
10934}
10935
10936AvailabilityResult Sema::getCurContextAvailability() const {
10937  const Decl *D = cast<Decl>(getCurObjCLexicalContext());
10938  return D->getAvailability();
10939}
10940