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