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