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