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