SemaDecl.cpp revision d945538a36642cb0f935b268acbc32a67fae85a6
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 "Sema.h"
15#include "SemaInit.h"
16#include "Lookup.h"
17#include "clang/AST/APValue.h"
18#include "clang/AST/ASTConsumer.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/CXXInheritance.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/StmtCXX.h"
24#include "clang/Parse/DeclSpec.h"
25#include "clang/Parse/ParseDiagnostic.h"
26#include "clang/Parse/Template.h"
27#include "clang/Basic/PartialDiagnostic.h"
28#include "clang/Basic/SourceManager.h"
29#include "clang/Basic/TargetInfo.h"
30// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
31#include "clang/Lex/Preprocessor.h"
32#include "clang/Lex/HeaderSearch.h"
33#include "llvm/ADT/Triple.h"
34#include <algorithm>
35#include <cstring>
36#include <functional>
37using namespace clang;
38
39/// getDeclName - Return a pretty name for the specified decl if possible, or
40/// an empty string if not.  This is used for pretty crash reporting.
41std::string Sema::getDeclName(DeclPtrTy d) {
42  Decl *D = d.getAs<Decl>();
43  if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(D))
44    return DN->getQualifiedNameAsString();
45  return "";
46}
47
48Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(DeclPtrTy Ptr) {
49  return DeclGroupPtrTy::make(DeclGroupRef(Ptr.getAs<Decl>()));
50}
51
52/// \brief If the identifier refers to a type name within this scope,
53/// return the declaration of that type.
54///
55/// This routine performs ordinary name lookup of the identifier II
56/// within the given scope, with optional C++ scope specifier SS, to
57/// determine whether the name refers to a type. If so, returns an
58/// opaque pointer (actually a QualType) corresponding to that
59/// type. Otherwise, returns NULL.
60///
61/// If name lookup results in an ambiguity, this routine will complain
62/// and then return NULL.
63Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
64                                Scope *S, CXXScopeSpec *SS,
65                                bool isClassName,
66                                TypeTy *ObjectTypePtr) {
67  // Determine where we will perform name lookup.
68  DeclContext *LookupCtx = 0;
69  if (ObjectTypePtr) {
70    QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
71    if (ObjectType->isRecordType())
72      LookupCtx = computeDeclContext(ObjectType);
73  } else if (SS && SS->isNotEmpty()) {
74    LookupCtx = computeDeclContext(*SS, false);
75
76    if (!LookupCtx) {
77      if (isDependentScopeSpecifier(*SS)) {
78        // C++ [temp.res]p3:
79        //   A qualified-id that refers to a type and in which the
80        //   nested-name-specifier depends on a template-parameter (14.6.2)
81        //   shall be prefixed by the keyword typename to indicate that the
82        //   qualified-id denotes a type, forming an
83        //   elaborated-type-specifier (7.1.5.3).
84        //
85        // We therefore do not perform any name lookup if the result would
86        // refer to a member of an unknown specialization.
87        if (!isClassName)
88          return 0;
89
90        // We know from the grammar that this name refers to a type,
91        // so build a dependent node to describe the type.
92        return CheckTypenameType(ETK_None,
93                                 (NestedNameSpecifier *)SS->getScopeRep(), II,
94                                 SourceLocation(), SS->getRange(), NameLoc
95                                 ).getAsOpaquePtr();
96      }
97
98      return 0;
99    }
100
101    if (!LookupCtx->isDependentContext() &&
102        RequireCompleteDeclContext(*SS, LookupCtx))
103      return 0;
104  }
105
106  // FIXME: LookupNestedNameSpecifierName isn't the right kind of
107  // lookup for class-names.
108  LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
109                                      LookupOrdinaryName;
110  LookupResult Result(*this, &II, NameLoc, Kind);
111  if (LookupCtx) {
112    // Perform "qualified" name lookup into the declaration context we
113    // computed, which is either the type of the base of a member access
114    // expression or the declaration context associated with a prior
115    // nested-name-specifier.
116    LookupQualifiedName(Result, LookupCtx);
117
118    if (ObjectTypePtr && Result.empty()) {
119      // C++ [basic.lookup.classref]p3:
120      //   If the unqualified-id is ~type-name, the type-name is looked up
121      //   in the context of the entire postfix-expression. If the type T of
122      //   the object expression is of a class type C, the type-name is also
123      //   looked up in the scope of class C. At least one of the lookups shall
124      //   find a name that refers to (possibly cv-qualified) T.
125      LookupName(Result, S);
126    }
127  } else {
128    // Perform unqualified name lookup.
129    LookupName(Result, S);
130  }
131
132  NamedDecl *IIDecl = 0;
133  switch (Result.getResultKind()) {
134  case LookupResult::NotFound:
135  case LookupResult::NotFoundInCurrentInstantiation:
136  case LookupResult::FoundOverloaded:
137  case LookupResult::FoundUnresolvedValue:
138    Result.suppressDiagnostics();
139    return 0;
140
141  case LookupResult::Ambiguous:
142    // Recover from type-hiding ambiguities by hiding the type.  We'll
143    // do the lookup again when looking for an object, and we can
144    // diagnose the error then.  If we don't do this, then the error
145    // about hiding the type will be immediately followed by an error
146    // that only makes sense if the identifier was treated like a type.
147    if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
148      Result.suppressDiagnostics();
149      return 0;
150    }
151
152    // Look to see if we have a type anywhere in the list of results.
153    for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
154         Res != ResEnd; ++Res) {
155      if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
156        if (!IIDecl ||
157            (*Res)->getLocation().getRawEncoding() <
158              IIDecl->getLocation().getRawEncoding())
159          IIDecl = *Res;
160      }
161    }
162
163    if (!IIDecl) {
164      // None of the entities we found is a type, so there is no way
165      // to even assume that the result is a type. In this case, don't
166      // complain about the ambiguity. The parser will either try to
167      // perform this lookup again (e.g., as an object name), which
168      // will produce the ambiguity, or will complain that it expected
169      // a type name.
170      Result.suppressDiagnostics();
171      return 0;
172    }
173
174    // We found a type within the ambiguous lookup; diagnose the
175    // ambiguity and then return that type. This might be the right
176    // answer, or it might not be, but it suppresses any attempt to
177    // perform the name lookup again.
178    break;
179
180  case LookupResult::Found:
181    IIDecl = Result.getFoundDecl();
182    break;
183  }
184
185  assert(IIDecl && "Didn't find decl");
186
187  QualType T;
188  if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
189    DiagnoseUseOfDecl(IIDecl, NameLoc);
190
191    if (T.isNull())
192      T = Context.getTypeDeclType(TD);
193
194    if (SS)
195      T = getElaboratedType(ETK_None, *SS, T);
196
197  } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
198    T = Context.getObjCInterfaceType(IDecl);
199  } else {
200    // If it's not plausibly a type, suppress diagnostics.
201    Result.suppressDiagnostics();
202    return 0;
203  }
204
205  return T.getAsOpaquePtr();
206}
207
208/// isTagName() - This method is called *for error recovery purposes only*
209/// to determine if the specified name is a valid tag name ("struct foo").  If
210/// so, this returns the TST for the tag corresponding to it (TST_enum,
211/// TST_union, TST_struct, TST_class).  This is used to diagnose cases in C
212/// where the user forgot to specify the tag.
213DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
214  // Do a tag name lookup in this scope.
215  LookupResult R(*this, &II, SourceLocation(), LookupTagName);
216  LookupName(R, S, false);
217  R.suppressDiagnostics();
218  if (R.getResultKind() == LookupResult::Found)
219    if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
220      switch (TD->getTagKind()) {
221      default:         return DeclSpec::TST_unspecified;
222      case TTK_Struct: return DeclSpec::TST_struct;
223      case TTK_Union:  return DeclSpec::TST_union;
224      case TTK_Class:  return DeclSpec::TST_class;
225      case TTK_Enum:   return DeclSpec::TST_enum;
226      }
227    }
228
229  return DeclSpec::TST_unspecified;
230}
231
232bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II,
233                                   SourceLocation IILoc,
234                                   Scope *S,
235                                   CXXScopeSpec *SS,
236                                   TypeTy *&SuggestedType) {
237  // We don't have anything to suggest (yet).
238  SuggestedType = 0;
239
240  // There may have been a typo in the name of the type. Look up typo
241  // results, in case we have something that we can suggest.
242  LookupResult Lookup(*this, &II, IILoc, LookupOrdinaryName,
243                      NotForRedeclaration);
244
245  if (DeclarationName Corrected = CorrectTypo(Lookup, S, SS, 0, 0, CTC_Type)) {
246    if (NamedDecl *Result = Lookup.getAsSingle<NamedDecl>()) {
247      if ((isa<TypeDecl>(Result) || isa<ObjCInterfaceDecl>(Result)) &&
248          !Result->isInvalidDecl()) {
249        // We found a similarly-named type or interface; suggest that.
250        if (!SS || !SS->isSet())
251          Diag(IILoc, diag::err_unknown_typename_suggest)
252            << &II << Lookup.getLookupName()
253            << FixItHint::CreateReplacement(SourceRange(IILoc),
254                                            Result->getNameAsString());
255        else if (DeclContext *DC = computeDeclContext(*SS, false))
256          Diag(IILoc, diag::err_unknown_nested_typename_suggest)
257            << &II << DC << Lookup.getLookupName() << SS->getRange()
258            << FixItHint::CreateReplacement(SourceRange(IILoc),
259                                            Result->getNameAsString());
260        else
261          llvm_unreachable("could not have corrected a typo here");
262
263        Diag(Result->getLocation(), diag::note_previous_decl)
264          << Result->getDeclName();
265
266        SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS);
267        return true;
268      }
269    } else if (Lookup.empty()) {
270      // We corrected to a keyword.
271      // FIXME: Actually recover with the keyword we suggest, and emit a fix-it.
272      Diag(IILoc, diag::err_unknown_typename_suggest)
273        << &II << Corrected;
274      return true;
275    }
276  }
277
278  if (getLangOptions().CPlusPlus) {
279    // See if II is a class template that the user forgot to pass arguments to.
280    UnqualifiedId Name;
281    Name.setIdentifier(&II, IILoc);
282    CXXScopeSpec EmptySS;
283    TemplateTy TemplateResult;
284    bool MemberOfUnknownSpecialization;
285    if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
286                       Name, 0, true, TemplateResult,
287                       MemberOfUnknownSpecialization) == TNK_Type_template) {
288      TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
289      Diag(IILoc, diag::err_template_missing_args) << TplName;
290      if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
291        Diag(TplDecl->getLocation(), diag::note_template_decl_here)
292          << TplDecl->getTemplateParameters()->getSourceRange();
293      }
294      return true;
295    }
296  }
297
298  // FIXME: Should we move the logic that tries to recover from a missing tag
299  // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
300
301  if (!SS || (!SS->isSet() && !SS->isInvalid()))
302    Diag(IILoc, diag::err_unknown_typename) << &II;
303  else if (DeclContext *DC = computeDeclContext(*SS, false))
304    Diag(IILoc, diag::err_typename_nested_not_found)
305      << &II << DC << SS->getRange();
306  else if (isDependentScopeSpecifier(*SS)) {
307    Diag(SS->getRange().getBegin(), diag::err_typename_missing)
308      << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
309      << SourceRange(SS->getRange().getBegin(), IILoc)
310      << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
311    SuggestedType = ActOnTypenameType(S, SourceLocation(), *SS, II, IILoc).get();
312  } else {
313    assert(SS && SS->isInvalid() &&
314           "Invalid scope specifier has already been diagnosed");
315  }
316
317  return true;
318}
319
320// Determines the context to return to after temporarily entering a
321// context.  This depends in an unnecessarily complicated way on the
322// exact ordering of callbacks from the parser.
323DeclContext *Sema::getContainingDC(DeclContext *DC) {
324
325  // Functions defined inline within classes aren't parsed until we've
326  // finished parsing the top-level class, so the top-level class is
327  // the context we'll need to return to.
328  if (isa<FunctionDecl>(DC)) {
329    DC = DC->getLexicalParent();
330
331    // A function not defined within a class will always return to its
332    // lexical context.
333    if (!isa<CXXRecordDecl>(DC))
334      return DC;
335
336    // A C++ inline method/friend is parsed *after* the topmost class
337    // it was declared in is fully parsed ("complete");  the topmost
338    // class is the context we need to return to.
339    while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
340      DC = RD;
341
342    // Return the declaration context of the topmost class the inline method is
343    // declared in.
344    return DC;
345  }
346
347  // ObjCMethodDecls are parsed (for some reason) outside the context
348  // of the class.
349  if (isa<ObjCMethodDecl>(DC))
350    return DC->getLexicalParent()->getLexicalParent();
351
352  return DC->getLexicalParent();
353}
354
355void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
356  assert(getContainingDC(DC) == CurContext &&
357      "The next DeclContext should be lexically contained in the current one.");
358  CurContext = DC;
359  S->setEntity(DC);
360}
361
362void Sema::PopDeclContext() {
363  assert(CurContext && "DeclContext imbalance!");
364
365  CurContext = getContainingDC(CurContext);
366  assert(CurContext && "Popped translation unit!");
367}
368
369/// EnterDeclaratorContext - Used when we must lookup names in the context
370/// of a declarator's nested name specifier.
371///
372void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
373  // C++0x [basic.lookup.unqual]p13:
374  //   A name used in the definition of a static data member of class
375  //   X (after the qualified-id of the static member) is looked up as
376  //   if the name was used in a member function of X.
377  // C++0x [basic.lookup.unqual]p14:
378  //   If a variable member of a namespace is defined outside of the
379  //   scope of its namespace then any name used in the definition of
380  //   the variable member (after the declarator-id) is looked up as
381  //   if the definition of the variable member occurred in its
382  //   namespace.
383  // Both of these imply that we should push a scope whose context
384  // is the semantic context of the declaration.  We can't use
385  // PushDeclContext here because that context is not necessarily
386  // lexically contained in the current context.  Fortunately,
387  // the containing scope should have the appropriate information.
388
389  assert(!S->getEntity() && "scope already has entity");
390
391#ifndef NDEBUG
392  Scope *Ancestor = S->getParent();
393  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
394  assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
395#endif
396
397  CurContext = DC;
398  S->setEntity(DC);
399}
400
401void Sema::ExitDeclaratorContext(Scope *S) {
402  assert(S->getEntity() == CurContext && "Context imbalance!");
403
404  // Switch back to the lexical context.  The safety of this is
405  // enforced by an assert in EnterDeclaratorContext.
406  Scope *Ancestor = S->getParent();
407  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
408  CurContext = (DeclContext*) Ancestor->getEntity();
409
410  // We don't need to do anything with the scope, which is going to
411  // disappear.
412}
413
414/// \brief Determine whether we allow overloading of the function
415/// PrevDecl with another declaration.
416///
417/// This routine determines whether overloading is possible, not
418/// whether some new function is actually an overload. It will return
419/// true in C++ (where we can always provide overloads) or, as an
420/// extension, in C when the previous function is already an
421/// overloaded function declaration or has the "overloadable"
422/// attribute.
423static bool AllowOverloadingOfFunction(LookupResult &Previous,
424                                       ASTContext &Context) {
425  if (Context.getLangOptions().CPlusPlus)
426    return true;
427
428  if (Previous.getResultKind() == LookupResult::FoundOverloaded)
429    return true;
430
431  return (Previous.getResultKind() == LookupResult::Found
432          && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
433}
434
435/// Add this decl to the scope shadowed decl chains.
436void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
437  // Move up the scope chain until we find the nearest enclosing
438  // non-transparent context. The declaration will be introduced into this
439  // scope.
440  while (S->getEntity() &&
441         ((DeclContext *)S->getEntity())->isTransparentContext())
442    S = S->getParent();
443
444  // Add scoped declarations into their context, so that they can be
445  // found later. Declarations without a context won't be inserted
446  // into any context.
447  if (AddToContext)
448    CurContext->addDecl(D);
449
450  // Out-of-line definitions shouldn't be pushed into scope in C++.
451  // Out-of-line variable and function definitions shouldn't even in C.
452  if ((getLangOptions().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
453      D->isOutOfLine())
454    return;
455
456  // Template instantiations should also not be pushed into scope.
457  if (isa<FunctionDecl>(D) &&
458      cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
459    return;
460
461  // If this replaces anything in the current scope,
462  IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
463                               IEnd = IdResolver.end();
464  for (; I != IEnd; ++I) {
465    if (S->isDeclScope(DeclPtrTy::make(*I)) && D->declarationReplaces(*I)) {
466      S->RemoveDecl(DeclPtrTy::make(*I));
467      IdResolver.RemoveDecl(*I);
468
469      // Should only need to replace one decl.
470      break;
471    }
472  }
473
474  S->AddDecl(DeclPtrTy::make(D));
475  IdResolver.AddDecl(D);
476}
477
478bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S) {
479  return IdResolver.isDeclInScope(D, Ctx, Context, S);
480}
481
482static bool isOutOfScopePreviousDeclaration(NamedDecl *,
483                                            DeclContext*,
484                                            ASTContext&);
485
486/// Filters out lookup results that don't fall within the given scope
487/// as determined by isDeclInScope.
488static void FilterLookupForScope(Sema &SemaRef, LookupResult &R,
489                                 DeclContext *Ctx, Scope *S,
490                                 bool ConsiderLinkage) {
491  LookupResult::Filter F = R.makeFilter();
492  while (F.hasNext()) {
493    NamedDecl *D = F.next();
494
495    if (SemaRef.isDeclInScope(D, Ctx, S))
496      continue;
497
498    if (ConsiderLinkage &&
499        isOutOfScopePreviousDeclaration(D, Ctx, SemaRef.Context))
500      continue;
501
502    F.erase();
503  }
504
505  F.done();
506}
507
508static bool isUsingDecl(NamedDecl *D) {
509  return isa<UsingShadowDecl>(D) ||
510         isa<UnresolvedUsingTypenameDecl>(D) ||
511         isa<UnresolvedUsingValueDecl>(D);
512}
513
514/// Removes using shadow declarations from the lookup results.
515static void RemoveUsingDecls(LookupResult &R) {
516  LookupResult::Filter F = R.makeFilter();
517  while (F.hasNext())
518    if (isUsingDecl(F.next()))
519      F.erase();
520
521  F.done();
522}
523
524static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
525  if (D->isInvalidDecl())
526    return false;
527
528  if (D->isUsed() || D->hasAttr<UnusedAttr>())
529    return false;
530
531  // White-list anything that isn't a local variable.
532  if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
533      !D->getDeclContext()->isFunctionOrMethod())
534    return false;
535
536  // Types of valid local variables should be complete, so this should succeed.
537  if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
538
539    // White-list anything with an __attribute__((unused)) type.
540    QualType Ty = VD->getType();
541
542    // Only look at the outermost level of typedef.
543    if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) {
544      if (TT->getDecl()->hasAttr<UnusedAttr>())
545        return false;
546    }
547
548    // If we failed to complete the type for some reason, or if the type is
549    // dependent, don't diagnose the variable.
550    if (Ty->isIncompleteType() || Ty->isDependentType())
551      return false;
552
553    if (const TagType *TT = Ty->getAs<TagType>()) {
554      const TagDecl *Tag = TT->getDecl();
555      if (Tag->hasAttr<UnusedAttr>())
556        return false;
557
558      if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
559        // FIXME: Checking for the presence of a user-declared constructor
560        // isn't completely accurate; we'd prefer to check that the initializer
561        // has no side effects.
562        if (RD->hasUserDeclaredConstructor() || !RD->hasTrivialDestructor())
563          return false;
564      }
565    }
566
567    // TODO: __attribute__((unused)) templates?
568  }
569
570  return true;
571}
572
573void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
574  if (!ShouldDiagnoseUnusedDecl(D))
575    return;
576
577  if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
578    Diag(D->getLocation(), diag::warn_unused_exception_param)
579    << D->getDeclName();
580  else
581    Diag(D->getLocation(), diag::warn_unused_variable)
582    << D->getDeclName();
583}
584
585void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
586  if (S->decl_empty()) return;
587  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
588         "Scope shouldn't contain decls!");
589
590  for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
591       I != E; ++I) {
592    Decl *TmpD = (*I).getAs<Decl>();
593    assert(TmpD && "This decl didn't get pushed??");
594
595    assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
596    NamedDecl *D = cast<NamedDecl>(TmpD);
597
598    if (!D->getDeclName()) continue;
599
600    // Diagnose unused variables in this scope.
601    if (S->getNumErrorsAtStart() == getDiagnostics().getNumErrors())
602      DiagnoseUnusedDecl(D);
603
604    // Remove this name from our lexical scope.
605    IdResolver.RemoveDecl(D);
606  }
607}
608
609/// \brief Look for an Objective-C class in the translation unit.
610///
611/// \param Id The name of the Objective-C class we're looking for. If
612/// typo-correction fixes this name, the Id will be updated
613/// to the fixed name.
614///
615/// \param IdLoc The location of the name in the translation unit.
616///
617/// \param TypoCorrection If true, this routine will attempt typo correction
618/// if there is no class with the given name.
619///
620/// \returns The declaration of the named Objective-C class, or NULL if the
621/// class could not be found.
622ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
623                                              SourceLocation IdLoc,
624                                              bool TypoCorrection) {
625  // The third "scope" argument is 0 since we aren't enabling lazy built-in
626  // creation from this context.
627  NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
628
629  if (!IDecl && TypoCorrection) {
630    // Perform typo correction at the given location, but only if we
631    // find an Objective-C class name.
632    LookupResult R(*this, Id, IdLoc, LookupOrdinaryName);
633    if (CorrectTypo(R, TUScope, 0, 0, false, CTC_NoKeywords) &&
634        (IDecl = R.getAsSingle<ObjCInterfaceDecl>())) {
635      Diag(IdLoc, diag::err_undef_interface_suggest)
636        << Id << IDecl->getDeclName()
637        << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
638      Diag(IDecl->getLocation(), diag::note_previous_decl)
639        << IDecl->getDeclName();
640
641      Id = IDecl->getIdentifier();
642    }
643  }
644
645  return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
646}
647
648/// getNonFieldDeclScope - Retrieves the innermost scope, starting
649/// from S, where a non-field would be declared. This routine copes
650/// with the difference between C and C++ scoping rules in structs and
651/// unions. For example, the following code is well-formed in C but
652/// ill-formed in C++:
653/// @code
654/// struct S6 {
655///   enum { BAR } e;
656/// };
657///
658/// void test_S6() {
659///   struct S6 a;
660///   a.e = BAR;
661/// }
662/// @endcode
663/// For the declaration of BAR, this routine will return a different
664/// scope. The scope S will be the scope of the unnamed enumeration
665/// within S6. In C++, this routine will return the scope associated
666/// with S6, because the enumeration's scope is a transparent
667/// context but structures can contain non-field names. In C, this
668/// routine will return the translation unit scope, since the
669/// enumeration's scope is a transparent context and structures cannot
670/// contain non-field names.
671Scope *Sema::getNonFieldDeclScope(Scope *S) {
672  while (((S->getFlags() & Scope::DeclScope) == 0) ||
673         (S->getEntity() &&
674          ((DeclContext *)S->getEntity())->isTransparentContext()) ||
675         (S->isClassScope() && !getLangOptions().CPlusPlus))
676    S = S->getParent();
677  return S;
678}
679
680void Sema::InitBuiltinVaListType() {
681  if (!Context.getBuiltinVaListType().isNull())
682    return;
683
684  IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
685  NamedDecl *VaDecl = LookupSingleName(TUScope, VaIdent, SourceLocation(),
686                                       LookupOrdinaryName, ForRedeclaration);
687  TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
688  Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
689}
690
691/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
692/// file scope.  lazily create a decl for it. ForRedeclaration is true
693/// if we're creating this built-in in anticipation of redeclaring the
694/// built-in.
695NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
696                                     Scope *S, bool ForRedeclaration,
697                                     SourceLocation Loc) {
698  Builtin::ID BID = (Builtin::ID)bid;
699
700  if (Context.BuiltinInfo.hasVAListUse(BID))
701    InitBuiltinVaListType();
702
703  ASTContext::GetBuiltinTypeError Error;
704  QualType R = Context.GetBuiltinType(BID, Error);
705  switch (Error) {
706  case ASTContext::GE_None:
707    // Okay
708    break;
709
710  case ASTContext::GE_Missing_stdio:
711    if (ForRedeclaration)
712      Diag(Loc, diag::err_implicit_decl_requires_stdio)
713        << Context.BuiltinInfo.GetName(BID);
714    return 0;
715
716  case ASTContext::GE_Missing_setjmp:
717    if (ForRedeclaration)
718      Diag(Loc, diag::err_implicit_decl_requires_setjmp)
719        << Context.BuiltinInfo.GetName(BID);
720    return 0;
721  }
722
723  if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
724    Diag(Loc, diag::ext_implicit_lib_function_decl)
725      << Context.BuiltinInfo.GetName(BID)
726      << R;
727    if (Context.BuiltinInfo.getHeaderName(BID) &&
728        Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl)
729          != Diagnostic::Ignored)
730      Diag(Loc, diag::note_please_include_header)
731        << Context.BuiltinInfo.getHeaderName(BID)
732        << Context.BuiltinInfo.GetName(BID);
733  }
734
735  FunctionDecl *New = FunctionDecl::Create(Context,
736                                           Context.getTranslationUnitDecl(),
737                                           Loc, II, R, /*TInfo=*/0,
738                                           FunctionDecl::Extern,
739                                           FunctionDecl::None, false,
740                                           /*hasPrototype=*/true);
741  New->setImplicit();
742
743  // Create Decl objects for each parameter, adding them to the
744  // FunctionDecl.
745  if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
746    llvm::SmallVector<ParmVarDecl*, 16> Params;
747    for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
748      Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
749                                           FT->getArgType(i), /*TInfo=*/0,
750                                           VarDecl::None, VarDecl::None, 0));
751    New->setParams(Params.data(), Params.size());
752  }
753
754  AddKnownFunctionAttributes(New);
755
756  // TUScope is the translation-unit scope to insert this function into.
757  // FIXME: This is hideous. We need to teach PushOnScopeChains to
758  // relate Scopes to DeclContexts, and probably eliminate CurContext
759  // entirely, but we're not there yet.
760  DeclContext *SavedContext = CurContext;
761  CurContext = Context.getTranslationUnitDecl();
762  PushOnScopeChains(New, TUScope);
763  CurContext = SavedContext;
764  return New;
765}
766
767/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the
768/// same name and scope as a previous declaration 'Old'.  Figure out
769/// how to resolve this situation, merging decls or emitting
770/// diagnostics as appropriate. If there was an error, set New to be invalid.
771///
772void Sema::MergeTypeDefDecl(TypedefDecl *New, LookupResult &OldDecls) {
773  // If the new decl is known invalid already, don't bother doing any
774  // merging checks.
775  if (New->isInvalidDecl()) return;
776
777  // Allow multiple definitions for ObjC built-in typedefs.
778  // FIXME: Verify the underlying types are equivalent!
779  if (getLangOptions().ObjC1) {
780    const IdentifierInfo *TypeID = New->getIdentifier();
781    switch (TypeID->getLength()) {
782    default: break;
783    case 2:
784      if (!TypeID->isStr("id"))
785        break;
786      Context.ObjCIdRedefinitionType = New->getUnderlyingType();
787      // Install the built-in type for 'id', ignoring the current definition.
788      New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
789      return;
790    case 5:
791      if (!TypeID->isStr("Class"))
792        break;
793      Context.ObjCClassRedefinitionType = New->getUnderlyingType();
794      // Install the built-in type for 'Class', ignoring the current definition.
795      New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
796      return;
797    case 3:
798      if (!TypeID->isStr("SEL"))
799        break;
800      Context.ObjCSelRedefinitionType = New->getUnderlyingType();
801      // Install the built-in type for 'SEL', ignoring the current definition.
802      New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
803      return;
804    case 8:
805      if (!TypeID->isStr("Protocol"))
806        break;
807      Context.setObjCProtoType(New->getUnderlyingType());
808      return;
809    }
810    // Fall through - the typedef name was not a builtin type.
811  }
812
813  // Verify the old decl was also a type.
814  TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
815  if (!Old) {
816    Diag(New->getLocation(), diag::err_redefinition_different_kind)
817      << New->getDeclName();
818
819    NamedDecl *OldD = OldDecls.getRepresentativeDecl();
820    if (OldD->getLocation().isValid())
821      Diag(OldD->getLocation(), diag::note_previous_definition);
822
823    return New->setInvalidDecl();
824  }
825
826  // If the old declaration is invalid, just give up here.
827  if (Old->isInvalidDecl())
828    return New->setInvalidDecl();
829
830  // Determine the "old" type we'll use for checking and diagnostics.
831  QualType OldType;
832  if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
833    OldType = OldTypedef->getUnderlyingType();
834  else
835    OldType = Context.getTypeDeclType(Old);
836
837  // If the typedef types are not identical, reject them in all languages and
838  // with any extensions enabled.
839
840  if (OldType != New->getUnderlyingType() &&
841      Context.getCanonicalType(OldType) !=
842      Context.getCanonicalType(New->getUnderlyingType())) {
843    Diag(New->getLocation(), diag::err_redefinition_different_typedef)
844      << New->getUnderlyingType() << OldType;
845    if (Old->getLocation().isValid())
846      Diag(Old->getLocation(), diag::note_previous_definition);
847    return New->setInvalidDecl();
848  }
849
850  // The types match.  Link up the redeclaration chain if the old
851  // declaration was a typedef.
852  // FIXME: this is a potential source of wierdness if the type
853  // spellings don't match exactly.
854  if (isa<TypedefDecl>(Old))
855    New->setPreviousDeclaration(cast<TypedefDecl>(Old));
856
857  if (getLangOptions().Microsoft)
858    return;
859
860  if (getLangOptions().CPlusPlus) {
861    // C++ [dcl.typedef]p2:
862    //   In a given non-class scope, a typedef specifier can be used to
863    //   redefine the name of any type declared in that scope to refer
864    //   to the type to which it already refers.
865    if (!isa<CXXRecordDecl>(CurContext))
866      return;
867
868    // C++0x [dcl.typedef]p4:
869    //   In a given class scope, a typedef specifier can be used to redefine
870    //   any class-name declared in that scope that is not also a typedef-name
871    //   to refer to the type to which it already refers.
872    //
873    // This wording came in via DR424, which was a correction to the
874    // wording in DR56, which accidentally banned code like:
875    //
876    //   struct S {
877    //     typedef struct A { } A;
878    //   };
879    //
880    // in the C++03 standard. We implement the C++0x semantics, which
881    // allow the above but disallow
882    //
883    //   struct S {
884    //     typedef int I;
885    //     typedef int I;
886    //   };
887    //
888    // since that was the intent of DR56.
889    if (!isa<TypedefDecl >(Old))
890      return;
891
892    Diag(New->getLocation(), diag::err_redefinition)
893      << New->getDeclName();
894    Diag(Old->getLocation(), diag::note_previous_definition);
895    return New->setInvalidDecl();
896  }
897
898  // If we have a redefinition of a typedef in C, emit a warning.  This warning
899  // is normally mapped to an error, but can be controlled with
900  // -Wtypedef-redefinition.  If either the original or the redefinition is
901  // in a system header, don't emit this for compatibility with GCC.
902  if (getDiagnostics().getSuppressSystemWarnings() &&
903      (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
904       Context.getSourceManager().isInSystemHeader(New->getLocation())))
905    return;
906
907  Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
908    << New->getDeclName();
909  Diag(Old->getLocation(), diag::note_previous_definition);
910  return;
911}
912
913/// DeclhasAttr - returns true if decl Declaration already has the target
914/// attribute.
915static bool
916DeclHasAttr(const Decl *decl, const Attr *target) {
917  for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
918    if (attr->getKind() == target->getKind())
919      return true;
920
921  return false;
922}
923
924/// MergeAttributes - append attributes from the Old decl to the New one.
925static void MergeAttributes(Decl *New, Decl *Old, ASTContext &C) {
926  for (const Attr *attr = Old->getAttrs(); attr; attr = attr->getNext()) {
927    if (!DeclHasAttr(New, attr) && attr->isMerged()) {
928      Attr *NewAttr = attr->clone(C);
929      NewAttr->setInherited(true);
930      New->addAttr(NewAttr);
931    }
932  }
933}
934
935namespace {
936
937/// Used in MergeFunctionDecl to keep track of function parameters in
938/// C.
939struct GNUCompatibleParamWarning {
940  ParmVarDecl *OldParm;
941  ParmVarDecl *NewParm;
942  QualType PromotedType;
943};
944
945}
946
947/// getSpecialMember - get the special member enum for a method.
948Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
949  if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
950    if (Ctor->isCopyConstructor())
951      return Sema::CXXCopyConstructor;
952
953    return Sema::CXXConstructor;
954  }
955
956  if (isa<CXXDestructorDecl>(MD))
957    return Sema::CXXDestructor;
958
959  assert(MD->isCopyAssignment() && "Must have copy assignment operator");
960  return Sema::CXXCopyAssignment;
961}
962
963/// canRedefineFunction - checks if a function can be redefined. Currently,
964/// only extern inline functions can be redefined, and even then only in
965/// GNU89 mode.
966static bool canRedefineFunction(const FunctionDecl *FD,
967                                const LangOptions& LangOpts) {
968  return (LangOpts.GNUMode && !LangOpts.C99 && !LangOpts.CPlusPlus &&
969          FD->isInlineSpecified() &&
970          FD->getStorageClass() == FunctionDecl::Extern);
971}
972
973/// MergeFunctionDecl - We just parsed a function 'New' from
974/// declarator D which has the same name and scope as a previous
975/// declaration 'Old'.  Figure out how to resolve this situation,
976/// merging decls or emitting diagnostics as appropriate.
977///
978/// In C++, New and Old must be declarations that are not
979/// overloaded. Use IsOverload to determine whether New and Old are
980/// overloaded, and to select the Old declaration that New should be
981/// merged with.
982///
983/// Returns true if there was an error, false otherwise.
984bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
985  // Verify the old decl was also a function.
986  FunctionDecl *Old = 0;
987  if (FunctionTemplateDecl *OldFunctionTemplate
988        = dyn_cast<FunctionTemplateDecl>(OldD))
989    Old = OldFunctionTemplate->getTemplatedDecl();
990  else
991    Old = dyn_cast<FunctionDecl>(OldD);
992  if (!Old) {
993    if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
994      Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
995      Diag(Shadow->getTargetDecl()->getLocation(),
996           diag::note_using_decl_target);
997      Diag(Shadow->getUsingDecl()->getLocation(),
998           diag::note_using_decl) << 0;
999      return true;
1000    }
1001
1002    Diag(New->getLocation(), diag::err_redefinition_different_kind)
1003      << New->getDeclName();
1004    Diag(OldD->getLocation(), diag::note_previous_definition);
1005    return true;
1006  }
1007
1008  // Determine whether the previous declaration was a definition,
1009  // implicit declaration, or a declaration.
1010  diag::kind PrevDiag;
1011  if (Old->isThisDeclarationADefinition())
1012    PrevDiag = diag::note_previous_definition;
1013  else if (Old->isImplicit())
1014    PrevDiag = diag::note_previous_implicit_declaration;
1015  else
1016    PrevDiag = diag::note_previous_declaration;
1017
1018  QualType OldQType = Context.getCanonicalType(Old->getType());
1019  QualType NewQType = Context.getCanonicalType(New->getType());
1020
1021  // Don't complain about this if we're in GNU89 mode and the old function
1022  // is an extern inline function.
1023  if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
1024      New->getStorageClass() == FunctionDecl::Static &&
1025      Old->getStorageClass() != FunctionDecl::Static &&
1026      !canRedefineFunction(Old, getLangOptions())) {
1027    Diag(New->getLocation(), diag::err_static_non_static)
1028      << New;
1029    Diag(Old->getLocation(), PrevDiag);
1030    return true;
1031  }
1032
1033  // If a function is first declared with a calling convention, but is
1034  // later declared or defined without one, the second decl assumes the
1035  // calling convention of the first.
1036  //
1037  // For the new decl, we have to look at the NON-canonical type to tell the
1038  // difference between a function that really doesn't have a calling
1039  // convention and one that is declared cdecl. That's because in
1040  // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
1041  // because it is the default calling convention.
1042  //
1043  // Note also that we DO NOT return at this point, because we still have
1044  // other tests to run.
1045  const FunctionType *OldType = OldQType->getAs<FunctionType>();
1046  const FunctionType *NewType = New->getType()->getAs<FunctionType>();
1047  const FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
1048  const FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
1049  if (OldTypeInfo.getCC() != CC_Default &&
1050      NewTypeInfo.getCC() == CC_Default) {
1051    NewQType = Context.getCallConvType(NewQType, OldTypeInfo.getCC());
1052    New->setType(NewQType);
1053    NewQType = Context.getCanonicalType(NewQType);
1054  } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
1055                                     NewTypeInfo.getCC())) {
1056    // Calling conventions really aren't compatible, so complain.
1057    Diag(New->getLocation(), diag::err_cconv_change)
1058      << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
1059      << (OldTypeInfo.getCC() == CC_Default)
1060      << (OldTypeInfo.getCC() == CC_Default ? "" :
1061          FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
1062    Diag(Old->getLocation(), diag::note_previous_declaration);
1063    return true;
1064  }
1065
1066  // FIXME: diagnose the other way around?
1067  if (OldType->getNoReturnAttr() && !NewType->getNoReturnAttr()) {
1068    NewQType = Context.getNoReturnType(NewQType);
1069    New->setType(NewQType);
1070    assert(NewQType.isCanonical());
1071  }
1072
1073  // Merge regparm attribute.
1074  if (OldType->getRegParmType() != NewType->getRegParmType()) {
1075    if (NewType->getRegParmType()) {
1076      Diag(New->getLocation(), diag::err_regparm_mismatch)
1077        << NewType->getRegParmType()
1078        << OldType->getRegParmType();
1079      Diag(Old->getLocation(), diag::note_previous_declaration);
1080      return true;
1081    }
1082
1083    NewQType = Context.getRegParmType(NewQType, OldType->getRegParmType());
1084    New->setType(NewQType);
1085    assert(NewQType.isCanonical());
1086  }
1087
1088  if (getLangOptions().CPlusPlus) {
1089    // (C++98 13.1p2):
1090    //   Certain function declarations cannot be overloaded:
1091    //     -- Function declarations that differ only in the return type
1092    //        cannot be overloaded.
1093    QualType OldReturnType
1094      = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
1095    QualType NewReturnType
1096      = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
1097    QualType ResQT;
1098    if (OldReturnType != NewReturnType) {
1099      if (NewReturnType->isObjCObjectPointerType()
1100          && OldReturnType->isObjCObjectPointerType())
1101        ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
1102      if (ResQT.isNull()) {
1103        Diag(New->getLocation(), diag::err_ovl_diff_return_type);
1104        Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1105        return true;
1106      }
1107      else
1108        NewQType = ResQT;
1109    }
1110
1111    const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
1112    CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
1113    if (OldMethod && NewMethod) {
1114      // Preserve triviality.
1115      NewMethod->setTrivial(OldMethod->isTrivial());
1116
1117      bool isFriend = NewMethod->getFriendObjectKind();
1118
1119      if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord()) {
1120        //    -- Member function declarations with the same name and the
1121        //       same parameter types cannot be overloaded if any of them
1122        //       is a static member function declaration.
1123        if (OldMethod->isStatic() || NewMethod->isStatic()) {
1124          Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
1125          Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1126          return true;
1127        }
1128
1129        // C++ [class.mem]p1:
1130        //   [...] A member shall not be declared twice in the
1131        //   member-specification, except that a nested class or member
1132        //   class template can be declared and then later defined.
1133        unsigned NewDiag;
1134        if (isa<CXXConstructorDecl>(OldMethod))
1135          NewDiag = diag::err_constructor_redeclared;
1136        else if (isa<CXXDestructorDecl>(NewMethod))
1137          NewDiag = diag::err_destructor_redeclared;
1138        else if (isa<CXXConversionDecl>(NewMethod))
1139          NewDiag = diag::err_conv_function_redeclared;
1140        else
1141          NewDiag = diag::err_member_redeclared;
1142
1143        Diag(New->getLocation(), NewDiag);
1144        Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1145
1146      // Complain if this is an explicit declaration of a special
1147      // member that was initially declared implicitly.
1148      //
1149      // As an exception, it's okay to befriend such methods in order
1150      // to permit the implicit constructor/destructor/operator calls.
1151      } else if (OldMethod->isImplicit()) {
1152        if (isFriend) {
1153          NewMethod->setImplicit();
1154        } else {
1155          Diag(NewMethod->getLocation(),
1156               diag::err_definition_of_implicitly_declared_member)
1157            << New << getSpecialMember(OldMethod);
1158          return true;
1159        }
1160      }
1161    }
1162
1163    // (C++98 8.3.5p3):
1164    //   All declarations for a function shall agree exactly in both the
1165    //   return type and the parameter-type-list.
1166    // attributes should be ignored when comparing.
1167    if (Context.getNoReturnType(OldQType, false) ==
1168        Context.getNoReturnType(NewQType, false))
1169      return MergeCompatibleFunctionDecls(New, Old);
1170
1171    // Fall through for conflicting redeclarations and redefinitions.
1172  }
1173
1174  // C: Function types need to be compatible, not identical. This handles
1175  // duplicate function decls like "void f(int); void f(enum X);" properly.
1176  if (!getLangOptions().CPlusPlus &&
1177      Context.typesAreCompatible(OldQType, NewQType)) {
1178    const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
1179    const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
1180    const FunctionProtoType *OldProto = 0;
1181    if (isa<FunctionNoProtoType>(NewFuncType) &&
1182        (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
1183      // The old declaration provided a function prototype, but the
1184      // new declaration does not. Merge in the prototype.
1185      assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
1186      llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
1187                                                 OldProto->arg_type_end());
1188      NewQType = Context.getFunctionType(NewFuncType->getResultType(),
1189                                         ParamTypes.data(), ParamTypes.size(),
1190                                         OldProto->isVariadic(),
1191                                         OldProto->getTypeQuals(),
1192                                         false, false, 0, 0,
1193                                         OldProto->getExtInfo());
1194      New->setType(NewQType);
1195      New->setHasInheritedPrototype();
1196
1197      // Synthesize a parameter for each argument type.
1198      llvm::SmallVector<ParmVarDecl*, 16> Params;
1199      for (FunctionProtoType::arg_type_iterator
1200             ParamType = OldProto->arg_type_begin(),
1201             ParamEnd = OldProto->arg_type_end();
1202           ParamType != ParamEnd; ++ParamType) {
1203        ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
1204                                                 SourceLocation(), 0,
1205                                                 *ParamType, /*TInfo=*/0,
1206                                                 VarDecl::None, VarDecl::None,
1207                                                 0);
1208        Param->setImplicit();
1209        Params.push_back(Param);
1210      }
1211
1212      New->setParams(Params.data(), Params.size());
1213    }
1214
1215    return MergeCompatibleFunctionDecls(New, Old);
1216  }
1217
1218  // GNU C permits a K&R definition to follow a prototype declaration
1219  // if the declared types of the parameters in the K&R definition
1220  // match the types in the prototype declaration, even when the
1221  // promoted types of the parameters from the K&R definition differ
1222  // from the types in the prototype. GCC then keeps the types from
1223  // the prototype.
1224  //
1225  // If a variadic prototype is followed by a non-variadic K&R definition,
1226  // the K&R definition becomes variadic.  This is sort of an edge case, but
1227  // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
1228  // C99 6.9.1p8.
1229  if (!getLangOptions().CPlusPlus &&
1230      Old->hasPrototype() && !New->hasPrototype() &&
1231      New->getType()->getAs<FunctionProtoType>() &&
1232      Old->getNumParams() == New->getNumParams()) {
1233    llvm::SmallVector<QualType, 16> ArgTypes;
1234    llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings;
1235    const FunctionProtoType *OldProto
1236      = Old->getType()->getAs<FunctionProtoType>();
1237    const FunctionProtoType *NewProto
1238      = New->getType()->getAs<FunctionProtoType>();
1239
1240    // Determine whether this is the GNU C extension.
1241    QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
1242                                               NewProto->getResultType());
1243    bool LooseCompatible = !MergedReturn.isNull();
1244    for (unsigned Idx = 0, End = Old->getNumParams();
1245         LooseCompatible && Idx != End; ++Idx) {
1246      ParmVarDecl *OldParm = Old->getParamDecl(Idx);
1247      ParmVarDecl *NewParm = New->getParamDecl(Idx);
1248      if (Context.typesAreCompatible(OldParm->getType(),
1249                                     NewProto->getArgType(Idx))) {
1250        ArgTypes.push_back(NewParm->getType());
1251      } else if (Context.typesAreCompatible(OldParm->getType(),
1252                                            NewParm->getType(),
1253                                            /*CompareUnqualified=*/true)) {
1254        GNUCompatibleParamWarning Warn
1255          = { OldParm, NewParm, NewProto->getArgType(Idx) };
1256        Warnings.push_back(Warn);
1257        ArgTypes.push_back(NewParm->getType());
1258      } else
1259        LooseCompatible = false;
1260    }
1261
1262    if (LooseCompatible) {
1263      for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
1264        Diag(Warnings[Warn].NewParm->getLocation(),
1265             diag::ext_param_promoted_not_compatible_with_prototype)
1266          << Warnings[Warn].PromotedType
1267          << Warnings[Warn].OldParm->getType();
1268        if (Warnings[Warn].OldParm->getLocation().isValid())
1269          Diag(Warnings[Warn].OldParm->getLocation(),
1270               diag::note_previous_declaration);
1271      }
1272
1273      New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
1274                                           ArgTypes.size(),
1275                                           OldProto->isVariadic(), 0,
1276                                           false, false, 0, 0,
1277                                           OldProto->getExtInfo()));
1278      return MergeCompatibleFunctionDecls(New, Old);
1279    }
1280
1281    // Fall through to diagnose conflicting types.
1282  }
1283
1284  // A function that has already been declared has been redeclared or defined
1285  // with a different type- show appropriate diagnostic
1286  if (unsigned BuiltinID = Old->getBuiltinID()) {
1287    // The user has declared a builtin function with an incompatible
1288    // signature.
1289    if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
1290      // The function the user is redeclaring is a library-defined
1291      // function like 'malloc' or 'printf'. Warn about the
1292      // redeclaration, then pretend that we don't know about this
1293      // library built-in.
1294      Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
1295      Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
1296        << Old << Old->getType();
1297      New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
1298      Old->setInvalidDecl();
1299      return false;
1300    }
1301
1302    PrevDiag = diag::note_previous_builtin_declaration;
1303  }
1304
1305  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
1306  Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1307  return true;
1308}
1309
1310/// \brief Completes the merge of two function declarations that are
1311/// known to be compatible.
1312///
1313/// This routine handles the merging of attributes and other
1314/// properties of function declarations form the old declaration to
1315/// the new declaration, once we know that New is in fact a
1316/// redeclaration of Old.
1317///
1318/// \returns false
1319bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
1320  // Merge the attributes
1321  MergeAttributes(New, Old, Context);
1322
1323  // Merge the storage class.
1324  if (Old->getStorageClass() != FunctionDecl::Extern &&
1325      Old->getStorageClass() != FunctionDecl::None)
1326    New->setStorageClass(Old->getStorageClass());
1327
1328  // Merge "pure" flag.
1329  if (Old->isPure())
1330    New->setPure();
1331
1332  // Merge the "deleted" flag.
1333  if (Old->isDeleted())
1334    New->setDeleted();
1335
1336  if (getLangOptions().CPlusPlus)
1337    return MergeCXXFunctionDecl(New, Old);
1338
1339  return false;
1340}
1341
1342/// MergeVarDecl - We just parsed a variable 'New' which has the same name
1343/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
1344/// situation, merging decls or emitting diagnostics as appropriate.
1345///
1346/// Tentative definition rules (C99 6.9.2p2) are checked by
1347/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
1348/// definitions here, since the initializer hasn't been attached.
1349///
1350void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
1351  // If the new decl is already invalid, don't do any other checking.
1352  if (New->isInvalidDecl())
1353    return;
1354
1355  // Verify the old decl was also a variable.
1356  VarDecl *Old = 0;
1357  if (!Previous.isSingleResult() ||
1358      !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
1359    Diag(New->getLocation(), diag::err_redefinition_different_kind)
1360      << New->getDeclName();
1361    Diag(Previous.getRepresentativeDecl()->getLocation(),
1362         diag::note_previous_definition);
1363    return New->setInvalidDecl();
1364  }
1365
1366  MergeAttributes(New, Old, Context);
1367
1368  // Merge the types
1369  QualType MergedT;
1370  if (getLangOptions().CPlusPlus) {
1371    if (Context.hasSameType(New->getType(), Old->getType()))
1372      MergedT = New->getType();
1373    // C++ [basic.link]p10:
1374    //   [...] the types specified by all declarations referring to a given
1375    //   object or function shall be identical, except that declarations for an
1376    //   array object can specify array types that differ by the presence or
1377    //   absence of a major array bound (8.3.4).
1378    else if (Old->getType()->isIncompleteArrayType() &&
1379             New->getType()->isArrayType()) {
1380      CanQual<ArrayType> OldArray
1381        = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1382      CanQual<ArrayType> NewArray
1383        = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1384      if (OldArray->getElementType() == NewArray->getElementType())
1385        MergedT = New->getType();
1386    } else if (Old->getType()->isArrayType() &&
1387             New->getType()->isIncompleteArrayType()) {
1388      CanQual<ArrayType> OldArray
1389        = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1390      CanQual<ArrayType> NewArray
1391        = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1392      if (OldArray->getElementType() == NewArray->getElementType())
1393        MergedT = Old->getType();
1394    } else if (New->getType()->isObjCObjectPointerType()
1395               && Old->getType()->isObjCObjectPointerType()) {
1396        MergedT = Context.mergeObjCGCQualifiers(New->getType(), Old->getType());
1397    }
1398  } else {
1399    MergedT = Context.mergeTypes(New->getType(), Old->getType());
1400  }
1401  if (MergedT.isNull()) {
1402    Diag(New->getLocation(), diag::err_redefinition_different_type)
1403      << New->getDeclName();
1404    Diag(Old->getLocation(), diag::note_previous_definition);
1405    return New->setInvalidDecl();
1406  }
1407  New->setType(MergedT);
1408
1409  // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
1410  if (New->getStorageClass() == VarDecl::Static &&
1411      (Old->getStorageClass() == VarDecl::None || Old->hasExternalStorage())) {
1412    Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
1413    Diag(Old->getLocation(), diag::note_previous_definition);
1414    return New->setInvalidDecl();
1415  }
1416  // C99 6.2.2p4:
1417  //   For an identifier declared with the storage-class specifier
1418  //   extern in a scope in which a prior declaration of that
1419  //   identifier is visible,23) if the prior declaration specifies
1420  //   internal or external linkage, the linkage of the identifier at
1421  //   the later declaration is the same as the linkage specified at
1422  //   the prior declaration. If no prior declaration is visible, or
1423  //   if the prior declaration specifies no linkage, then the
1424  //   identifier has external linkage.
1425  if (New->hasExternalStorage() && Old->hasLinkage())
1426    /* Okay */;
1427  else if (New->getStorageClass() != VarDecl::Static &&
1428           Old->getStorageClass() == VarDecl::Static) {
1429    Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
1430    Diag(Old->getLocation(), diag::note_previous_definition);
1431    return New->setInvalidDecl();
1432  }
1433
1434  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
1435
1436  // FIXME: The test for external storage here seems wrong? We still
1437  // need to check for mismatches.
1438  if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
1439      // Don't complain about out-of-line definitions of static members.
1440      !(Old->getLexicalDeclContext()->isRecord() &&
1441        !New->getLexicalDeclContext()->isRecord())) {
1442    Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
1443    Diag(Old->getLocation(), diag::note_previous_definition);
1444    return New->setInvalidDecl();
1445  }
1446
1447  if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
1448    Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
1449    Diag(Old->getLocation(), diag::note_previous_definition);
1450  } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
1451    Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
1452    Diag(Old->getLocation(), diag::note_previous_definition);
1453  }
1454
1455  // C++ doesn't have tentative definitions, so go right ahead and check here.
1456  const VarDecl *Def;
1457  if (getLangOptions().CPlusPlus &&
1458      New->isThisDeclarationADefinition() == VarDecl::Definition &&
1459      (Def = Old->getDefinition())) {
1460    Diag(New->getLocation(), diag::err_redefinition)
1461      << New->getDeclName();
1462    Diag(Def->getLocation(), diag::note_previous_definition);
1463    New->setInvalidDecl();
1464    return;
1465  }
1466  // c99 6.2.2 P4.
1467  // For an identifier declared with the storage-class specifier extern in a
1468  // scope in which a prior declaration of that identifier is visible, if
1469  // the prior declaration specifies internal or external linkage, the linkage
1470  // of the identifier at the later declaration is the same as the linkage
1471  // specified at the prior declaration.
1472  // FIXME. revisit this code.
1473  if (New->hasExternalStorage() &&
1474      Old->getLinkage() == InternalLinkage &&
1475      New->getDeclContext() == Old->getDeclContext())
1476    New->setStorageClass(Old->getStorageClass());
1477
1478  // Keep a chain of previous declarations.
1479  New->setPreviousDeclaration(Old);
1480
1481  // Inherit access appropriately.
1482  New->setAccess(Old->getAccess());
1483}
1484
1485/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
1486/// no declarator (e.g. "struct foo;") is parsed.
1487Sema::DeclPtrTy Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1488                                                 DeclSpec &DS) {
1489  // FIXME: Error on auto/register at file scope
1490  // FIXME: Error on inline/virtual/explicit
1491  // FIXME: Warn on useless __thread
1492  // FIXME: Warn on useless const/volatile
1493  // FIXME: Warn on useless static/extern/typedef/private_extern/mutable
1494  // FIXME: Warn on useless attributes
1495  Decl *TagD = 0;
1496  TagDecl *Tag = 0;
1497  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
1498      DS.getTypeSpecType() == DeclSpec::TST_struct ||
1499      DS.getTypeSpecType() == DeclSpec::TST_union ||
1500      DS.getTypeSpecType() == DeclSpec::TST_enum) {
1501    TagD = static_cast<Decl *>(DS.getTypeRep());
1502
1503    if (!TagD) // We probably had an error
1504      return DeclPtrTy();
1505
1506    // Note that the above type specs guarantee that the
1507    // type rep is a Decl, whereas in many of the others
1508    // it's a Type.
1509    Tag = dyn_cast<TagDecl>(TagD);
1510  }
1511
1512  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1513    // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
1514    // or incomplete types shall not be restrict-qualified."
1515    if (TypeQuals & DeclSpec::TQ_restrict)
1516      Diag(DS.getRestrictSpecLoc(),
1517           diag::err_typecheck_invalid_restrict_not_pointer_noarg)
1518           << DS.getSourceRange();
1519  }
1520
1521  if (DS.isFriendSpecified()) {
1522    // If we're dealing with a class template decl, assume that the
1523    // template routines are handling it.
1524    if (TagD && isa<ClassTemplateDecl>(TagD))
1525      return DeclPtrTy();
1526    return ActOnFriendTypeDecl(S, DS, MultiTemplateParamsArg(*this, 0, 0));
1527  }
1528
1529  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
1530    // If there are attributes in the DeclSpec, apply them to the record.
1531    if (const AttributeList *AL = DS.getAttributes())
1532      ProcessDeclAttributeList(S, Record, AL);
1533
1534    if (!Record->getDeclName() && Record->isDefinition() &&
1535        DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
1536      if (getLangOptions().CPlusPlus ||
1537          Record->getDeclContext()->isRecord())
1538        return BuildAnonymousStructOrUnion(S, DS, AS, Record);
1539
1540      Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
1541        << DS.getSourceRange();
1542    }
1543
1544    // Microsoft allows unnamed struct/union fields. Don't complain
1545    // about them.
1546    // FIXME: Should we support Microsoft's extensions in this area?
1547    if (Record->getDeclName() && getLangOptions().Microsoft)
1548      return DeclPtrTy::make(Tag);
1549  }
1550
1551  if (getLangOptions().CPlusPlus &&
1552      DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
1553    if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
1554      if (Enum->enumerator_begin() == Enum->enumerator_end() &&
1555          !Enum->getIdentifier() && !Enum->isInvalidDecl())
1556        Diag(Enum->getLocation(), diag::ext_no_declarators)
1557          << DS.getSourceRange();
1558
1559  if (!DS.isMissingDeclaratorOk() &&
1560      DS.getTypeSpecType() != DeclSpec::TST_error) {
1561    // Warn about typedefs of enums without names, since this is an
1562    // extension in both Microsoft and GNU.
1563    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
1564        Tag && isa<EnumDecl>(Tag)) {
1565      Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
1566        << DS.getSourceRange();
1567      return DeclPtrTy::make(Tag);
1568    }
1569
1570    Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
1571      << DS.getSourceRange();
1572  }
1573
1574  return DeclPtrTy::make(TagD);
1575}
1576
1577/// We are trying to inject an anonymous member into the given scope;
1578/// check if there's an existing declaration that can't be overloaded.
1579///
1580/// \return true if this is a forbidden redeclaration
1581static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
1582                                         Scope *S,
1583                                         DeclContext *Owner,
1584                                         DeclarationName Name,
1585                                         SourceLocation NameLoc,
1586                                         unsigned diagnostic) {
1587  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
1588                 Sema::ForRedeclaration);
1589  if (!SemaRef.LookupName(R, S)) return false;
1590
1591  if (R.getAsSingle<TagDecl>())
1592    return false;
1593
1594  // Pick a representative declaration.
1595  NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
1596  if (PrevDecl && Owner->isRecord()) {
1597    RecordDecl *Record = cast<RecordDecl>(Owner);
1598    if (!SemaRef.isDeclInScope(PrevDecl, Record, S))
1599      return false;
1600  }
1601
1602  SemaRef.Diag(NameLoc, diagnostic) << Name;
1603  SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
1604
1605  return true;
1606}
1607
1608/// InjectAnonymousStructOrUnionMembers - Inject the members of the
1609/// anonymous struct or union AnonRecord into the owning context Owner
1610/// and scope S. This routine will be invoked just after we realize
1611/// that an unnamed union or struct is actually an anonymous union or
1612/// struct, e.g.,
1613///
1614/// @code
1615/// union {
1616///   int i;
1617///   float f;
1618/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
1619///    // f into the surrounding scope.x
1620/// @endcode
1621///
1622/// This routine is recursive, injecting the names of nested anonymous
1623/// structs/unions into the owning context and scope as well.
1624static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
1625                                                DeclContext *Owner,
1626                                                RecordDecl *AnonRecord,
1627                                                AccessSpecifier AS) {
1628  unsigned diagKind
1629    = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
1630                            : diag::err_anonymous_struct_member_redecl;
1631
1632  bool Invalid = false;
1633  for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
1634                               FEnd = AnonRecord->field_end();
1635       F != FEnd; ++F) {
1636    if ((*F)->getDeclName()) {
1637      if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, (*F)->getDeclName(),
1638                                       (*F)->getLocation(), diagKind)) {
1639        // C++ [class.union]p2:
1640        //   The names of the members of an anonymous union shall be
1641        //   distinct from the names of any other entity in the
1642        //   scope in which the anonymous union is declared.
1643        Invalid = true;
1644      } else {
1645        // C++ [class.union]p2:
1646        //   For the purpose of name lookup, after the anonymous union
1647        //   definition, the members of the anonymous union are
1648        //   considered to have been defined in the scope in which the
1649        //   anonymous union is declared.
1650        Owner->makeDeclVisibleInContext(*F);
1651        S->AddDecl(Sema::DeclPtrTy::make(*F));
1652        SemaRef.IdResolver.AddDecl(*F);
1653
1654        // That includes picking up the appropriate access specifier.
1655        if (AS != AS_none) (*F)->setAccess(AS);
1656      }
1657    } else if (const RecordType *InnerRecordType
1658                 = (*F)->getType()->getAs<RecordType>()) {
1659      RecordDecl *InnerRecord = InnerRecordType->getDecl();
1660      if (InnerRecord->isAnonymousStructOrUnion())
1661        Invalid = Invalid ||
1662          InjectAnonymousStructOrUnionMembers(SemaRef, S, Owner,
1663                                              InnerRecord, AS);
1664    }
1665  }
1666
1667  return Invalid;
1668}
1669
1670/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
1671/// a VarDecl::StorageClass. Any error reporting is up to the caller:
1672/// illegal input values are mapped to VarDecl::None.
1673static VarDecl::StorageClass
1674StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
1675  switch (StorageClassSpec) {
1676  case DeclSpec::SCS_unspecified:    return VarDecl::None;
1677  case DeclSpec::SCS_extern:         return VarDecl::Extern;
1678  case DeclSpec::SCS_static:         return VarDecl::Static;
1679  case DeclSpec::SCS_auto:           return VarDecl::Auto;
1680  case DeclSpec::SCS_register:       return VarDecl::Register;
1681  case DeclSpec::SCS_private_extern: return VarDecl::PrivateExtern;
1682    // Illegal SCSs map to None: error reporting is up to the caller.
1683  case DeclSpec::SCS_mutable:        // Fall through.
1684  case DeclSpec::SCS_typedef:        return VarDecl::None;
1685  }
1686  llvm_unreachable("unknown storage class specifier");
1687}
1688
1689/// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
1690/// a FunctionDecl::StorageClass. Any error reporting is up to the caller:
1691/// illegal input values are mapped to FunctionDecl::None.
1692static FunctionDecl::StorageClass
1693StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
1694  switch (StorageClassSpec) {
1695  case DeclSpec::SCS_unspecified:    return FunctionDecl::None;
1696  case DeclSpec::SCS_extern:         return FunctionDecl::Extern;
1697  case DeclSpec::SCS_static:         return FunctionDecl::Static;
1698  case DeclSpec::SCS_private_extern: return FunctionDecl::PrivateExtern;
1699    // Illegal SCSs map to None: error reporting is up to the caller.
1700  case DeclSpec::SCS_auto:           // Fall through.
1701  case DeclSpec::SCS_mutable:        // Fall through.
1702  case DeclSpec::SCS_register:       // Fall through.
1703  case DeclSpec::SCS_typedef:        return FunctionDecl::None;
1704  }
1705  llvm_unreachable("unknown storage class specifier");
1706}
1707
1708/// ActOnAnonymousStructOrUnion - Handle the declaration of an
1709/// anonymous structure or union. Anonymous unions are a C++ feature
1710/// (C++ [class.union]) and a GNU C extension; anonymous structures
1711/// are a GNU C and GNU C++ extension.
1712Sema::DeclPtrTy Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1713                                                  AccessSpecifier AS,
1714                                                  RecordDecl *Record) {
1715  DeclContext *Owner = Record->getDeclContext();
1716
1717  // Diagnose whether this anonymous struct/union is an extension.
1718  if (Record->isUnion() && !getLangOptions().CPlusPlus)
1719    Diag(Record->getLocation(), diag::ext_anonymous_union);
1720  else if (!Record->isUnion())
1721    Diag(Record->getLocation(), diag::ext_anonymous_struct);
1722
1723  // C and C++ require different kinds of checks for anonymous
1724  // structs/unions.
1725  bool Invalid = false;
1726  if (getLangOptions().CPlusPlus) {
1727    const char* PrevSpec = 0;
1728    unsigned DiagID;
1729    // C++ [class.union]p3:
1730    //   Anonymous unions declared in a named namespace or in the
1731    //   global namespace shall be declared static.
1732    if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
1733        (isa<TranslationUnitDecl>(Owner) ||
1734         (isa<NamespaceDecl>(Owner) &&
1735          cast<NamespaceDecl>(Owner)->getDeclName()))) {
1736      Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
1737      Invalid = true;
1738
1739      // Recover by adding 'static'.
1740      DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(),
1741                             PrevSpec, DiagID);
1742    }
1743    // C++ [class.union]p3:
1744    //   A storage class is not allowed in a declaration of an
1745    //   anonymous union in a class scope.
1746    else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1747             isa<RecordDecl>(Owner)) {
1748      Diag(DS.getStorageClassSpecLoc(),
1749           diag::err_anonymous_union_with_storage_spec);
1750      Invalid = true;
1751
1752      // Recover by removing the storage specifier.
1753      DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
1754                             PrevSpec, DiagID);
1755    }
1756
1757    // C++ [class.union]p2:
1758    //   The member-specification of an anonymous union shall only
1759    //   define non-static data members. [Note: nested types and
1760    //   functions cannot be declared within an anonymous union. ]
1761    for (DeclContext::decl_iterator Mem = Record->decls_begin(),
1762                                 MemEnd = Record->decls_end();
1763         Mem != MemEnd; ++Mem) {
1764      if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
1765        // C++ [class.union]p3:
1766        //   An anonymous union shall not have private or protected
1767        //   members (clause 11).
1768        assert(FD->getAccess() != AS_none);
1769        if (FD->getAccess() != AS_public) {
1770          Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
1771            << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
1772          Invalid = true;
1773        }
1774      } else if ((*Mem)->isImplicit()) {
1775        // Any implicit members are fine.
1776      } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
1777        // This is a type that showed up in an
1778        // elaborated-type-specifier inside the anonymous struct or
1779        // union, but which actually declares a type outside of the
1780        // anonymous struct or union. It's okay.
1781      } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
1782        if (!MemRecord->isAnonymousStructOrUnion() &&
1783            MemRecord->getDeclName()) {
1784          // This is a nested type declaration.
1785          Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
1786            << (int)Record->isUnion();
1787          Invalid = true;
1788        }
1789      } else if (isa<AccessSpecDecl>(*Mem)) {
1790        // Any access specifier is fine.
1791      } else {
1792        // We have something that isn't a non-static data
1793        // member. Complain about it.
1794        unsigned DK = diag::err_anonymous_record_bad_member;
1795        if (isa<TypeDecl>(*Mem))
1796          DK = diag::err_anonymous_record_with_type;
1797        else if (isa<FunctionDecl>(*Mem))
1798          DK = diag::err_anonymous_record_with_function;
1799        else if (isa<VarDecl>(*Mem))
1800          DK = diag::err_anonymous_record_with_static;
1801        Diag((*Mem)->getLocation(), DK)
1802            << (int)Record->isUnion();
1803          Invalid = true;
1804      }
1805    }
1806  }
1807
1808  if (!Record->isUnion() && !Owner->isRecord()) {
1809    Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
1810      << (int)getLangOptions().CPlusPlus;
1811    Invalid = true;
1812  }
1813
1814  // Mock up a declarator.
1815  Declarator Dc(DS, Declarator::TypeNameContext);
1816  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
1817  assert(TInfo && "couldn't build declarator info for anonymous struct/union");
1818
1819  // Create a declaration for this anonymous struct/union.
1820  NamedDecl *Anon = 0;
1821  if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
1822    Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
1823                             /*IdentifierInfo=*/0,
1824                             Context.getTypeDeclType(Record),
1825                             TInfo,
1826                             /*BitWidth=*/0, /*Mutable=*/false);
1827    Anon->setAccess(AS);
1828    if (getLangOptions().CPlusPlus) {
1829      FieldCollector->Add(cast<FieldDecl>(Anon));
1830      if (!cast<CXXRecordDecl>(Record)->isEmpty())
1831        cast<CXXRecordDecl>(OwningClass)->setEmpty(false);
1832    }
1833  } else {
1834    DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
1835    assert(SCSpec != DeclSpec::SCS_typedef &&
1836           "Parser allowed 'typedef' as storage class VarDecl.");
1837    VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
1838    if (SCSpec == DeclSpec::SCS_mutable) {
1839      // mutable can only appear on non-static class members, so it's always
1840      // an error here
1841      Diag(Record->getLocation(), diag::err_mutable_nonmember);
1842      Invalid = true;
1843      SC = VarDecl::None;
1844    }
1845    SCSpec = DS.getStorageClassSpecAsWritten();
1846    VarDecl::StorageClass SCAsWritten
1847      = StorageClassSpecToVarDeclStorageClass(SCSpec);
1848
1849    Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
1850                           /*IdentifierInfo=*/0,
1851                           Context.getTypeDeclType(Record),
1852                           TInfo, SC, SCAsWritten);
1853  }
1854  Anon->setImplicit();
1855
1856  // Add the anonymous struct/union object to the current
1857  // context. We'll be referencing this object when we refer to one of
1858  // its members.
1859  Owner->addDecl(Anon);
1860
1861  // Inject the members of the anonymous struct/union into the owning
1862  // context and into the identifier resolver chain for name lookup
1863  // purposes.
1864  if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS))
1865    Invalid = true;
1866
1867  // Mark this as an anonymous struct/union type. Note that we do not
1868  // do this until after we have already checked and injected the
1869  // members of this anonymous struct/union type, because otherwise
1870  // the members could be injected twice: once by DeclContext when it
1871  // builds its lookup table, and once by
1872  // InjectAnonymousStructOrUnionMembers.
1873  Record->setAnonymousStructOrUnion(true);
1874
1875  if (Invalid)
1876    Anon->setInvalidDecl();
1877
1878  return DeclPtrTy::make(Anon);
1879}
1880
1881
1882/// GetNameForDeclarator - Determine the full declaration name for the
1883/// given Declarator.
1884DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1885  return GetNameFromUnqualifiedId(D.getName());
1886}
1887
1888/// \brief Retrieves the canonicalized name from a parsed unqualified-id.
1889DeclarationName Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
1890  switch (Name.getKind()) {
1891    case UnqualifiedId::IK_Identifier:
1892      return DeclarationName(Name.Identifier);
1893
1894    case UnqualifiedId::IK_OperatorFunctionId:
1895      return Context.DeclarationNames.getCXXOperatorName(
1896                                              Name.OperatorFunctionId.Operator);
1897
1898    case UnqualifiedId::IK_LiteralOperatorId:
1899      return Context.DeclarationNames.getCXXLiteralOperatorName(
1900                                                               Name.Identifier);
1901
1902    case UnqualifiedId::IK_ConversionFunctionId: {
1903      QualType Ty = GetTypeFromParser(Name.ConversionFunctionId);
1904      if (Ty.isNull())
1905        return DeclarationName();
1906
1907      return Context.DeclarationNames.getCXXConversionFunctionName(
1908                                                  Context.getCanonicalType(Ty));
1909    }
1910
1911    case UnqualifiedId::IK_ConstructorName: {
1912      QualType Ty = GetTypeFromParser(Name.ConstructorName);
1913      if (Ty.isNull())
1914        return DeclarationName();
1915
1916      return Context.DeclarationNames.getCXXConstructorName(
1917                                                  Context.getCanonicalType(Ty));
1918    }
1919
1920    case UnqualifiedId::IK_ConstructorTemplateId: {
1921      // In well-formed code, we can only have a constructor
1922      // template-id that refers to the current context, so go there
1923      // to find the actual type being constructed.
1924      CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
1925      if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
1926        return DeclarationName();
1927
1928      // Determine the type of the class being constructed.
1929      QualType CurClassType = Context.getTypeDeclType(CurClass);
1930
1931      // FIXME: Check two things: that the template-id names the same type as
1932      // CurClassType, and that the template-id does not occur when the name
1933      // was qualified.
1934
1935      return Context.DeclarationNames.getCXXConstructorName(
1936                                       Context.getCanonicalType(CurClassType));
1937    }
1938
1939    case UnqualifiedId::IK_DestructorName: {
1940      QualType Ty = GetTypeFromParser(Name.DestructorName);
1941      if (Ty.isNull())
1942        return DeclarationName();
1943
1944      return Context.DeclarationNames.getCXXDestructorName(
1945                                                           Context.getCanonicalType(Ty));
1946    }
1947
1948    case UnqualifiedId::IK_TemplateId: {
1949      TemplateName TName
1950        = TemplateName::getFromVoidPointer(Name.TemplateId->Template);
1951      return Context.getNameForTemplate(TName);
1952    }
1953  }
1954
1955  assert(false && "Unknown name kind");
1956  return DeclarationName();
1957}
1958
1959/// isNearlyMatchingFunction - Determine whether the C++ functions
1960/// Declaration and Definition are "nearly" matching. This heuristic
1961/// is used to improve diagnostics in the case where an out-of-line
1962/// function definition doesn't match any declaration within
1963/// the class or namespace.
1964static bool isNearlyMatchingFunction(ASTContext &Context,
1965                                     FunctionDecl *Declaration,
1966                                     FunctionDecl *Definition) {
1967  if (Declaration->param_size() != Definition->param_size())
1968    return false;
1969  for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1970    QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1971    QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1972
1973    if (!Context.hasSameUnqualifiedType(DeclParamTy.getNonReferenceType(),
1974                                        DefParamTy.getNonReferenceType()))
1975      return false;
1976  }
1977
1978  return true;
1979}
1980
1981/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
1982/// declarator needs to be rebuilt in the current instantiation.
1983/// Any bits of declarator which appear before the name are valid for
1984/// consideration here.  That's specifically the type in the decl spec
1985/// and the base type in any member-pointer chunks.
1986static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
1987                                                    DeclarationName Name) {
1988  // The types we specifically need to rebuild are:
1989  //   - typenames, typeofs, and decltypes
1990  //   - types which will become injected class names
1991  // Of course, we also need to rebuild any type referencing such a
1992  // type.  It's safest to just say "dependent", but we call out a
1993  // few cases here.
1994
1995  DeclSpec &DS = D.getMutableDeclSpec();
1996  switch (DS.getTypeSpecType()) {
1997  case DeclSpec::TST_typename:
1998  case DeclSpec::TST_typeofType:
1999  case DeclSpec::TST_typeofExpr:
2000  case DeclSpec::TST_decltype: {
2001    // Grab the type from the parser.
2002    TypeSourceInfo *TSI = 0;
2003    QualType T = S.GetTypeFromParser(DS.getTypeRep(), &TSI);
2004    if (T.isNull() || !T->isDependentType()) break;
2005
2006    // Make sure there's a type source info.  This isn't really much
2007    // of a waste; most dependent types should have type source info
2008    // attached already.
2009    if (!TSI)
2010      TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
2011
2012    // Rebuild the type in the current instantiation.
2013    TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
2014    if (!TSI) return true;
2015
2016    // Store the new type back in the decl spec.
2017    QualType LocType = S.CreateLocInfoType(TSI->getType(), TSI);
2018    DS.UpdateTypeRep(LocType.getAsOpaquePtr());
2019    break;
2020  }
2021
2022  default:
2023    // Nothing to do for these decl specs.
2024    break;
2025  }
2026
2027  // It doesn't matter what order we do this in.
2028  for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
2029    DeclaratorChunk &Chunk = D.getTypeObject(I);
2030
2031    // The only type information in the declarator which can come
2032    // before the declaration name is the base type of a member
2033    // pointer.
2034    if (Chunk.Kind != DeclaratorChunk::MemberPointer)
2035      continue;
2036
2037    // Rebuild the scope specifier in-place.
2038    CXXScopeSpec &SS = Chunk.Mem.Scope();
2039    if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
2040      return true;
2041  }
2042
2043  return false;
2044}
2045
2046Sema::DeclPtrTy
2047Sema::HandleDeclarator(Scope *S, Declarator &D,
2048                       MultiTemplateParamsArg TemplateParamLists,
2049                       bool IsFunctionDefinition) {
2050  DeclarationName Name = GetNameForDeclarator(D);
2051
2052  // All of these full declarators require an identifier.  If it doesn't have
2053  // one, the ParsedFreeStandingDeclSpec action should be used.
2054  if (!Name) {
2055    if (!D.isInvalidType())  // Reject this if we think it is valid.
2056      Diag(D.getDeclSpec().getSourceRange().getBegin(),
2057           diag::err_declarator_need_ident)
2058        << D.getDeclSpec().getSourceRange() << D.getSourceRange();
2059    return DeclPtrTy();
2060  }
2061
2062  // The scope passed in may not be a decl scope.  Zip up the scope tree until
2063  // we find one that is.
2064  while ((S->getFlags() & Scope::DeclScope) == 0 ||
2065         (S->getFlags() & Scope::TemplateParamScope) != 0)
2066    S = S->getParent();
2067
2068  DeclContext *DC = CurContext;
2069  if (D.getCXXScopeSpec().isInvalid())
2070    D.setInvalidType();
2071  else if (D.getCXXScopeSpec().isSet()) {
2072    bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
2073    DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
2074    if (!DC) {
2075      // If we could not compute the declaration context, it's because the
2076      // declaration context is dependent but does not refer to a class,
2077      // class template, or class template partial specialization. Complain
2078      // and return early, to avoid the coming semantic disaster.
2079      Diag(D.getIdentifierLoc(),
2080           diag::err_template_qualified_declarator_no_match)
2081        << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
2082        << D.getCXXScopeSpec().getRange();
2083      return DeclPtrTy();
2084    }
2085
2086    bool IsDependentContext = DC->isDependentContext();
2087
2088    if (!IsDependentContext &&
2089        RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
2090      return DeclPtrTy();
2091
2092    if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
2093      Diag(D.getIdentifierLoc(),
2094           diag::err_member_def_undefined_record)
2095        << Name << DC << D.getCXXScopeSpec().getRange();
2096      D.setInvalidType();
2097    }
2098
2099    // Check whether we need to rebuild the type of the given
2100    // declaration in the current instantiation.
2101    if (EnteringContext && IsDependentContext &&
2102        TemplateParamLists.size() != 0) {
2103      ContextRAII SavedContext(*this, DC);
2104      if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
2105        D.setInvalidType();
2106    }
2107  }
2108
2109  NamedDecl *New;
2110
2111  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
2112  QualType R = TInfo->getType();
2113
2114  LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
2115                        ForRedeclaration);
2116
2117  // See if this is a redefinition of a variable in the same scope.
2118  if (!D.getCXXScopeSpec().isSet()) {
2119    bool IsLinkageLookup = false;
2120
2121    // If the declaration we're planning to build will be a function
2122    // or object with linkage, then look for another declaration with
2123    // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
2124    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2125      /* Do nothing*/;
2126    else if (R->isFunctionType()) {
2127      if (CurContext->isFunctionOrMethod() ||
2128          D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
2129        IsLinkageLookup = true;
2130    } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
2131      IsLinkageLookup = true;
2132    else if (CurContext->getLookupContext()->isTranslationUnit() &&
2133             D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
2134      IsLinkageLookup = true;
2135
2136    if (IsLinkageLookup)
2137      Previous.clear(LookupRedeclarationWithLinkage);
2138
2139    LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
2140  } else { // Something like "int foo::x;"
2141    LookupQualifiedName(Previous, DC);
2142
2143    // Don't consider using declarations as previous declarations for
2144    // out-of-line members.
2145    RemoveUsingDecls(Previous);
2146
2147    // C++ 7.3.1.2p2:
2148    // Members (including explicit specializations of templates) of a named
2149    // namespace can also be defined outside that namespace by explicit
2150    // qualification of the name being defined, provided that the entity being
2151    // defined was already declared in the namespace and the definition appears
2152    // after the point of declaration in a namespace that encloses the
2153    // declarations namespace.
2154    //
2155    // Note that we only check the context at this point. We don't yet
2156    // have enough information to make sure that PrevDecl is actually
2157    // the declaration we want to match. For example, given:
2158    //
2159    //   class X {
2160    //     void f();
2161    //     void f(float);
2162    //   };
2163    //
2164    //   void X::f(int) { } // ill-formed
2165    //
2166    // In this case, PrevDecl will point to the overload set
2167    // containing the two f's declared in X, but neither of them
2168    // matches.
2169
2170    // First check whether we named the global scope.
2171    if (isa<TranslationUnitDecl>(DC)) {
2172      Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
2173        << Name << D.getCXXScopeSpec().getRange();
2174    } else {
2175      DeclContext *Cur = CurContext;
2176      while (isa<LinkageSpecDecl>(Cur))
2177        Cur = Cur->getParent();
2178      if (!Cur->Encloses(DC)) {
2179        // The qualifying scope doesn't enclose the original declaration.
2180        // Emit diagnostic based on current scope.
2181        SourceLocation L = D.getIdentifierLoc();
2182        SourceRange R = D.getCXXScopeSpec().getRange();
2183        if (isa<FunctionDecl>(Cur))
2184          Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
2185        else
2186          Diag(L, diag::err_invalid_declarator_scope)
2187            << Name << cast<NamedDecl>(DC) << R;
2188        D.setInvalidType();
2189      }
2190    }
2191  }
2192
2193  if (Previous.isSingleResult() &&
2194      Previous.getFoundDecl()->isTemplateParameter()) {
2195    // Maybe we will complain about the shadowed template parameter.
2196    if (!D.isInvalidType())
2197      if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
2198                                          Previous.getFoundDecl()))
2199        D.setInvalidType();
2200
2201    // Just pretend that we didn't see the previous declaration.
2202    Previous.clear();
2203  }
2204
2205  // In C++, the previous declaration we find might be a tag type
2206  // (class or enum). In this case, the new declaration will hide the
2207  // tag type. Note that this does does not apply if we're declaring a
2208  // typedef (C++ [dcl.typedef]p4).
2209  if (Previous.isSingleTagDecl() &&
2210      D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
2211    Previous.clear();
2212
2213  bool Redeclaration = false;
2214  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
2215    if (TemplateParamLists.size()) {
2216      Diag(D.getIdentifierLoc(), diag::err_template_typedef);
2217      return DeclPtrTy();
2218    }
2219
2220    New = ActOnTypedefDeclarator(S, D, DC, R, TInfo, Previous, Redeclaration);
2221  } else if (R->isFunctionType()) {
2222    New = ActOnFunctionDeclarator(S, D, DC, R, TInfo, Previous,
2223                                  move(TemplateParamLists),
2224                                  IsFunctionDefinition, Redeclaration);
2225  } else {
2226    New = ActOnVariableDeclarator(S, D, DC, R, TInfo, Previous,
2227                                  move(TemplateParamLists),
2228                                  Redeclaration);
2229  }
2230
2231  if (New == 0)
2232    return DeclPtrTy();
2233
2234  // If this has an identifier and is not an invalid redeclaration or
2235  // function template specialization, add it to the scope stack.
2236  if (New->getDeclName() && !(Redeclaration && New->isInvalidDecl()))
2237    PushOnScopeChains(New, S);
2238
2239  return DeclPtrTy::make(New);
2240}
2241
2242/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2243/// types into constant array types in certain situations which would otherwise
2244/// be errors (for GCC compatibility).
2245static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2246                                                    ASTContext &Context,
2247                                                    bool &SizeIsNegative) {
2248  // This method tries to turn a variable array into a constant
2249  // array even when the size isn't an ICE.  This is necessary
2250  // for compatibility with code that depends on gcc's buggy
2251  // constant expression folding, like struct {char x[(int)(char*)2];}
2252  SizeIsNegative = false;
2253
2254  QualifierCollector Qs;
2255  const Type *Ty = Qs.strip(T);
2256
2257  if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
2258    QualType Pointee = PTy->getPointeeType();
2259    QualType FixedType =
2260        TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative);
2261    if (FixedType.isNull()) return FixedType;
2262    FixedType = Context.getPointerType(FixedType);
2263    return Qs.apply(FixedType);
2264  }
2265
2266  const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2267  if (!VLATy)
2268    return QualType();
2269  // FIXME: We should probably handle this case
2270  if (VLATy->getElementType()->isVariablyModifiedType())
2271    return QualType();
2272
2273  Expr::EvalResult EvalResult;
2274  if (!VLATy->getSizeExpr() ||
2275      !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) ||
2276      !EvalResult.Val.isInt())
2277    return QualType();
2278
2279  llvm::APSInt &Res = EvalResult.Val.getInt();
2280  if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned())) {
2281    // TODO: preserve the size expression in declarator info
2282    return Context.getConstantArrayType(VLATy->getElementType(),
2283                                        Res, ArrayType::Normal, 0);
2284  }
2285
2286  SizeIsNegative = true;
2287  return QualType();
2288}
2289
2290/// \brief Register the given locally-scoped external C declaration so
2291/// that it can be found later for redeclarations
2292void
2293Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
2294                                       const LookupResult &Previous,
2295                                       Scope *S) {
2296  assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
2297         "Decl is not a locally-scoped decl!");
2298  // Note that we have a locally-scoped external with this name.
2299  LocallyScopedExternalDecls[ND->getDeclName()] = ND;
2300
2301  if (!Previous.isSingleResult())
2302    return;
2303
2304  NamedDecl *PrevDecl = Previous.getFoundDecl();
2305
2306  // If there was a previous declaration of this variable, it may be
2307  // in our identifier chain. Update the identifier chain with the new
2308  // declaration.
2309  if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
2310    // The previous declaration was found on the identifer resolver
2311    // chain, so remove it from its scope.
2312    while (S && !S->isDeclScope(DeclPtrTy::make(PrevDecl)))
2313      S = S->getParent();
2314
2315    if (S)
2316      S->RemoveDecl(DeclPtrTy::make(PrevDecl));
2317  }
2318}
2319
2320/// \brief Diagnose function specifiers on a declaration of an identifier that
2321/// does not identify a function.
2322void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
2323  // FIXME: We should probably indicate the identifier in question to avoid
2324  // confusion for constructs like "inline int a(), b;"
2325  if (D.getDeclSpec().isInlineSpecified())
2326    Diag(D.getDeclSpec().getInlineSpecLoc(),
2327         diag::err_inline_non_function);
2328
2329  if (D.getDeclSpec().isVirtualSpecified())
2330    Diag(D.getDeclSpec().getVirtualSpecLoc(),
2331         diag::err_virtual_non_function);
2332
2333  if (D.getDeclSpec().isExplicitSpecified())
2334    Diag(D.getDeclSpec().getExplicitSpecLoc(),
2335         diag::err_explicit_non_function);
2336}
2337
2338NamedDecl*
2339Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2340                             QualType R,  TypeSourceInfo *TInfo,
2341                             LookupResult &Previous, bool &Redeclaration) {
2342  // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
2343  if (D.getCXXScopeSpec().isSet()) {
2344    Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
2345      << D.getCXXScopeSpec().getRange();
2346    D.setInvalidType();
2347    // Pretend we didn't see the scope specifier.
2348    DC = CurContext;
2349    Previous.clear();
2350  }
2351
2352  if (getLangOptions().CPlusPlus) {
2353    // Check that there are no default arguments (C++ only).
2354    CheckExtraCXXDefaultArguments(D);
2355  }
2356
2357  DiagnoseFunctionSpecifiers(D);
2358
2359  if (D.getDeclSpec().isThreadSpecified())
2360    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2361
2362  if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
2363    Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
2364      << D.getName().getSourceRange();
2365    return 0;
2366  }
2367
2368  TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, TInfo);
2369  if (!NewTD) return 0;
2370
2371  // Handle attributes prior to checking for duplicates in MergeVarDecl
2372  ProcessDeclAttributes(S, NewTD, D);
2373
2374  // Merge the decl with the existing one if appropriate. If the decl is
2375  // in an outer scope, it isn't the same thing.
2376  FilterLookupForScope(*this, Previous, DC, S, /*ConsiderLinkage*/ false);
2377  if (!Previous.empty()) {
2378    Redeclaration = true;
2379    MergeTypeDefDecl(NewTD, Previous);
2380  }
2381
2382  // C99 6.7.7p2: If a typedef name specifies a variably modified type
2383  // then it shall have block scope.
2384  QualType T = NewTD->getUnderlyingType();
2385  if (T->isVariablyModifiedType()) {
2386    setFunctionHasBranchProtectedScope();
2387
2388    if (S->getFnParent() == 0) {
2389      bool SizeIsNegative;
2390      QualType FixedTy =
2391          TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
2392      if (!FixedTy.isNull()) {
2393        Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size);
2394        NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
2395      } else {
2396        if (SizeIsNegative)
2397          Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size);
2398        else if (T->isVariableArrayType())
2399          Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
2400        else
2401          Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
2402        NewTD->setInvalidDecl();
2403      }
2404    }
2405  }
2406
2407  // If this is the C FILE type, notify the AST context.
2408  if (IdentifierInfo *II = NewTD->getIdentifier())
2409    if (!NewTD->isInvalidDecl() &&
2410        NewTD->getDeclContext()->getLookupContext()->isTranslationUnit()) {
2411      if (II->isStr("FILE"))
2412        Context.setFILEDecl(NewTD);
2413      else if (II->isStr("jmp_buf"))
2414        Context.setjmp_bufDecl(NewTD);
2415      else if (II->isStr("sigjmp_buf"))
2416        Context.setsigjmp_bufDecl(NewTD);
2417    }
2418
2419  return NewTD;
2420}
2421
2422/// \brief Determines whether the given declaration is an out-of-scope
2423/// previous declaration.
2424///
2425/// This routine should be invoked when name lookup has found a
2426/// previous declaration (PrevDecl) that is not in the scope where a
2427/// new declaration by the same name is being introduced. If the new
2428/// declaration occurs in a local scope, previous declarations with
2429/// linkage may still be considered previous declarations (C99
2430/// 6.2.2p4-5, C++ [basic.link]p6).
2431///
2432/// \param PrevDecl the previous declaration found by name
2433/// lookup
2434///
2435/// \param DC the context in which the new declaration is being
2436/// declared.
2437///
2438/// \returns true if PrevDecl is an out-of-scope previous declaration
2439/// for a new delcaration with the same name.
2440static bool
2441isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
2442                                ASTContext &Context) {
2443  if (!PrevDecl)
2444    return 0;
2445
2446  if (!PrevDecl->hasLinkage())
2447    return false;
2448
2449  if (Context.getLangOptions().CPlusPlus) {
2450    // C++ [basic.link]p6:
2451    //   If there is a visible declaration of an entity with linkage
2452    //   having the same name and type, ignoring entities declared
2453    //   outside the innermost enclosing namespace scope, the block
2454    //   scope declaration declares that same entity and receives the
2455    //   linkage of the previous declaration.
2456    DeclContext *OuterContext = DC->getLookupContext();
2457    if (!OuterContext->isFunctionOrMethod())
2458      // This rule only applies to block-scope declarations.
2459      return false;
2460    else {
2461      DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
2462      if (PrevOuterContext->isRecord())
2463        // We found a member function: ignore it.
2464        return false;
2465      else {
2466        // Find the innermost enclosing namespace for the new and
2467        // previous declarations.
2468        while (!OuterContext->isFileContext())
2469          OuterContext = OuterContext->getParent();
2470        while (!PrevOuterContext->isFileContext())
2471          PrevOuterContext = PrevOuterContext->getParent();
2472
2473        // The previous declaration is in a different namespace, so it
2474        // isn't the same function.
2475        if (OuterContext->getPrimaryContext() !=
2476            PrevOuterContext->getPrimaryContext())
2477          return false;
2478      }
2479    }
2480  }
2481
2482  return true;
2483}
2484
2485static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
2486  CXXScopeSpec &SS = D.getCXXScopeSpec();
2487  if (!SS.isSet()) return;
2488  DD->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2489                       SS.getRange());
2490}
2491
2492NamedDecl*
2493Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2494                              QualType R, TypeSourceInfo *TInfo,
2495                              LookupResult &Previous,
2496                              MultiTemplateParamsArg TemplateParamLists,
2497                              bool &Redeclaration) {
2498  DeclarationName Name = GetNameForDeclarator(D);
2499
2500  // Check that there are no default arguments (C++ only).
2501  if (getLangOptions().CPlusPlus)
2502    CheckExtraCXXDefaultArguments(D);
2503
2504  DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
2505  assert(SCSpec != DeclSpec::SCS_typedef &&
2506         "Parser allowed 'typedef' as storage class VarDecl.");
2507  VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
2508  if (SCSpec == DeclSpec::SCS_mutable) {
2509    // mutable can only appear on non-static class members, so it's always
2510    // an error here
2511    Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
2512    D.setInvalidType();
2513    SC = VarDecl::None;
2514  }
2515  SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
2516  VarDecl::StorageClass SCAsWritten
2517    = StorageClassSpecToVarDeclStorageClass(SCSpec);
2518
2519  IdentifierInfo *II = Name.getAsIdentifierInfo();
2520  if (!II) {
2521    Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
2522      << Name.getAsString();
2523    return 0;
2524  }
2525
2526  DiagnoseFunctionSpecifiers(D);
2527
2528  if (!DC->isRecord() && S->getFnParent() == 0) {
2529    // C99 6.9p2: The storage-class specifiers auto and register shall not
2530    // appear in the declaration specifiers in an external declaration.
2531    if (SC == VarDecl::Auto || SC == VarDecl::Register) {
2532
2533      // If this is a register variable with an asm label specified, then this
2534      // is a GNU extension.
2535      if (SC == VarDecl::Register && D.getAsmLabel())
2536        Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
2537      else
2538        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
2539      D.setInvalidType();
2540    }
2541  }
2542  if (DC->isRecord() && !CurContext->isRecord()) {
2543    // This is an out-of-line definition of a static data member.
2544    if (SC == VarDecl::Static) {
2545      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2546           diag::err_static_out_of_line)
2547        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
2548    } else if (SC == VarDecl::None)
2549      SC = VarDecl::Static;
2550  }
2551  if (SC == VarDecl::Static) {
2552    if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
2553      if (RD->isLocalClass())
2554        Diag(D.getIdentifierLoc(),
2555             diag::err_static_data_member_not_allowed_in_local_class)
2556          << Name << RD->getDeclName();
2557    }
2558  }
2559
2560  // Match up the template parameter lists with the scope specifier, then
2561  // determine whether we have a template or a template specialization.
2562  bool isExplicitSpecialization = false;
2563  unsigned NumMatchedTemplateParamLists = TemplateParamLists.size();
2564  bool Invalid = false;
2565  if (TemplateParameterList *TemplateParams
2566        = MatchTemplateParametersToScopeSpecifier(
2567                                  D.getDeclSpec().getSourceRange().getBegin(),
2568                                                  D.getCXXScopeSpec(),
2569                        (TemplateParameterList**)TemplateParamLists.get(),
2570                                                   TemplateParamLists.size(),
2571                                                  /*never a friend*/ false,
2572                                                  isExplicitSpecialization,
2573                                                  Invalid)) {
2574    // All but one template parameter lists have been matching.
2575    --NumMatchedTemplateParamLists;
2576
2577    if (TemplateParams->size() > 0) {
2578      // There is no such thing as a variable template.
2579      Diag(D.getIdentifierLoc(), diag::err_template_variable)
2580        << II
2581        << SourceRange(TemplateParams->getTemplateLoc(),
2582                       TemplateParams->getRAngleLoc());
2583      return 0;
2584    } else {
2585      // There is an extraneous 'template<>' for this variable. Complain
2586      // about it, but allow the declaration of the variable.
2587      Diag(TemplateParams->getTemplateLoc(),
2588           diag::err_template_variable_noparams)
2589        << II
2590        << SourceRange(TemplateParams->getTemplateLoc(),
2591                       TemplateParams->getRAngleLoc());
2592
2593      isExplicitSpecialization = true;
2594    }
2595  }
2596
2597  VarDecl *NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
2598                                   II, R, TInfo, SC, SCAsWritten);
2599
2600  if (D.isInvalidType() || Invalid)
2601    NewVD->setInvalidDecl();
2602
2603  SetNestedNameSpecifier(NewVD, D);
2604
2605  if (NumMatchedTemplateParamLists > 0 && D.getCXXScopeSpec().isSet()) {
2606    NewVD->setTemplateParameterListsInfo(Context,
2607                                         NumMatchedTemplateParamLists,
2608                        (TemplateParameterList**)TemplateParamLists.release());
2609  }
2610
2611  if (D.getDeclSpec().isThreadSpecified()) {
2612    if (NewVD->hasLocalStorage())
2613      Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
2614    else if (!Context.Target.isTLSSupported())
2615      Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
2616    else
2617      NewVD->setThreadSpecified(true);
2618  }
2619
2620  // Set the lexical context. If the declarator has a C++ scope specifier, the
2621  // lexical context will be different from the semantic context.
2622  NewVD->setLexicalDeclContext(CurContext);
2623
2624  // Handle attributes prior to checking for duplicates in MergeVarDecl
2625  ProcessDeclAttributes(S, NewVD, D);
2626
2627  // Handle GNU asm-label extension (encoded as an attribute).
2628  if (Expr *E = (Expr*) D.getAsmLabel()) {
2629    // The parser guarantees this is a string.
2630    StringLiteral *SE = cast<StringLiteral>(E);
2631    NewVD->addAttr(::new (Context) AsmLabelAttr(Context, SE->getString()));
2632  }
2633
2634  // Diagnose shadowed variables before filtering for scope.
2635  if (!D.getCXXScopeSpec().isSet())
2636    CheckShadow(S, NewVD, Previous);
2637
2638  // Don't consider existing declarations that are in a different
2639  // scope and are out-of-semantic-context declarations (if the new
2640  // declaration has linkage).
2641  FilterLookupForScope(*this, Previous, DC, S, NewVD->hasLinkage());
2642
2643  // Merge the decl with the existing one if appropriate.
2644  if (!Previous.empty()) {
2645    if (Previous.isSingleResult() &&
2646        isa<FieldDecl>(Previous.getFoundDecl()) &&
2647        D.getCXXScopeSpec().isSet()) {
2648      // The user tried to define a non-static data member
2649      // out-of-line (C++ [dcl.meaning]p1).
2650      Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
2651        << D.getCXXScopeSpec().getRange();
2652      Previous.clear();
2653      NewVD->setInvalidDecl();
2654    }
2655  } else if (D.getCXXScopeSpec().isSet()) {
2656    // No previous declaration in the qualifying scope.
2657    Diag(D.getIdentifierLoc(), diag::err_no_member)
2658      << Name << computeDeclContext(D.getCXXScopeSpec(), true)
2659      << D.getCXXScopeSpec().getRange();
2660    NewVD->setInvalidDecl();
2661  }
2662
2663  CheckVariableDeclaration(NewVD, Previous, Redeclaration);
2664
2665  // This is an explicit specialization of a static data member. Check it.
2666  if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
2667      CheckMemberSpecialization(NewVD, Previous))
2668    NewVD->setInvalidDecl();
2669
2670  // attributes declared post-definition are currently ignored
2671  if (Previous.isSingleResult()) {
2672    VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl());
2673    if (Def && (Def = Def->getDefinition()) &&
2674        Def != NewVD && D.hasAttributes()) {
2675      Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
2676      Diag(Def->getLocation(), diag::note_previous_definition);
2677    }
2678  }
2679
2680  // If this is a locally-scoped extern C variable, update the map of
2681  // such variables.
2682  if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
2683      !NewVD->isInvalidDecl())
2684    RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
2685
2686  // If there's a #pragma GCC visibility in scope, and this isn't a class
2687  // member, set the visibility of this variable.
2688  if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord())
2689    AddPushedVisibilityAttribute(NewVD);
2690
2691  return NewVD;
2692}
2693
2694/// \brief Diagnose variable or built-in function shadowing.  Implements
2695/// -Wshadow.
2696///
2697/// This method is called whenever a VarDecl is added to a "useful"
2698/// scope.
2699///
2700/// \param S the scope in which the shadowing name is being declared
2701/// \param R the lookup of the name
2702///
2703void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
2704  // Return if warning is ignored.
2705  if (Diags.getDiagnosticLevel(diag::warn_decl_shadow) == Diagnostic::Ignored)
2706    return;
2707
2708  // Don't diagnose declarations at file scope.  The scope might not
2709  // have a DeclContext if (e.g.) we're parsing a function prototype.
2710  DeclContext *NewDC = static_cast<DeclContext*>(S->getEntity());
2711  if (NewDC && NewDC->isFileContext())
2712    return;
2713
2714  // Only diagnose if we're shadowing an unambiguous field or variable.
2715  if (R.getResultKind() != LookupResult::Found)
2716    return;
2717
2718  NamedDecl* ShadowedDecl = R.getFoundDecl();
2719  if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
2720    return;
2721
2722  DeclContext *OldDC = ShadowedDecl->getDeclContext();
2723
2724  // Only warn about certain kinds of shadowing for class members.
2725  if (NewDC && NewDC->isRecord()) {
2726    // In particular, don't warn about shadowing non-class members.
2727    if (!OldDC->isRecord())
2728      return;
2729
2730    // TODO: should we warn about static data members shadowing
2731    // static data members from base classes?
2732
2733    // TODO: don't diagnose for inaccessible shadowed members.
2734    // This is hard to do perfectly because we might friend the
2735    // shadowing context, but that's just a false negative.
2736  }
2737
2738  // Determine what kind of declaration we're shadowing.
2739  unsigned Kind;
2740  if (isa<RecordDecl>(OldDC)) {
2741    if (isa<FieldDecl>(ShadowedDecl))
2742      Kind = 3; // field
2743    else
2744      Kind = 2; // static data member
2745  } else if (OldDC->isFileContext())
2746    Kind = 1; // global
2747  else
2748    Kind = 0; // local
2749
2750  DeclarationName Name = R.getLookupName();
2751
2752  // Emit warning and note.
2753  Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
2754  Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
2755}
2756
2757/// \brief Check -Wshadow without the advantage of a previous lookup.
2758void Sema::CheckShadow(Scope *S, VarDecl *D) {
2759  LookupResult R(*this, D->getDeclName(), D->getLocation(),
2760                 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
2761  LookupName(R, S);
2762  CheckShadow(S, D, R);
2763}
2764
2765/// \brief Perform semantic checking on a newly-created variable
2766/// declaration.
2767///
2768/// This routine performs all of the type-checking required for a
2769/// variable declaration once it has been built. It is used both to
2770/// check variables after they have been parsed and their declarators
2771/// have been translated into a declaration, and to check variables
2772/// that have been instantiated from a template.
2773///
2774/// Sets NewVD->isInvalidDecl() if an error was encountered.
2775void Sema::CheckVariableDeclaration(VarDecl *NewVD,
2776                                    LookupResult &Previous,
2777                                    bool &Redeclaration) {
2778  // If the decl is already known invalid, don't check it.
2779  if (NewVD->isInvalidDecl())
2780    return;
2781
2782  QualType T = NewVD->getType();
2783
2784  if (T->isObjCObjectType()) {
2785    Diag(NewVD->getLocation(), diag::err_statically_allocated_object);
2786    return NewVD->setInvalidDecl();
2787  }
2788
2789  // Emit an error if an address space was applied to decl with local storage.
2790  // This includes arrays of objects with address space qualifiers, but not
2791  // automatic variables that point to other address spaces.
2792  // ISO/IEC TR 18037 S5.1.2
2793  if (NewVD->hasLocalStorage() && (T.getAddressSpace() != 0)) {
2794    Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
2795    return NewVD->setInvalidDecl();
2796  }
2797
2798  if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
2799      && !NewVD->hasAttr<BlocksAttr>())
2800    Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
2801
2802  bool isVM = T->isVariablyModifiedType();
2803  if (isVM || NewVD->hasAttr<CleanupAttr>() ||
2804      NewVD->hasAttr<BlocksAttr>())
2805    setFunctionHasBranchProtectedScope();
2806
2807  if ((isVM && NewVD->hasLinkage()) ||
2808      (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
2809    bool SizeIsNegative;
2810    QualType FixedTy =
2811        TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
2812
2813    if (FixedTy.isNull() && T->isVariableArrayType()) {
2814      const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
2815      // FIXME: This won't give the correct result for
2816      // int a[10][n];
2817      SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
2818
2819      if (NewVD->isFileVarDecl())
2820        Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
2821        << SizeRange;
2822      else if (NewVD->getStorageClass() == VarDecl::Static)
2823        Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
2824        << SizeRange;
2825      else
2826        Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
2827        << SizeRange;
2828      return NewVD->setInvalidDecl();
2829    }
2830
2831    if (FixedTy.isNull()) {
2832      if (NewVD->isFileVarDecl())
2833        Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
2834      else
2835        Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
2836      return NewVD->setInvalidDecl();
2837    }
2838
2839    Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
2840    NewVD->setType(FixedTy);
2841  }
2842
2843  if (Previous.empty() && NewVD->isExternC()) {
2844    // Since we did not find anything by this name and we're declaring
2845    // an extern "C" variable, look for a non-visible extern "C"
2846    // declaration with the same name.
2847    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
2848      = LocallyScopedExternalDecls.find(NewVD->getDeclName());
2849    if (Pos != LocallyScopedExternalDecls.end())
2850      Previous.addDecl(Pos->second);
2851  }
2852
2853  if (T->isVoidType() && !NewVD->hasExternalStorage()) {
2854    Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
2855      << T;
2856    return NewVD->setInvalidDecl();
2857  }
2858
2859  if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
2860    Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
2861    return NewVD->setInvalidDecl();
2862  }
2863
2864  if (isVM && NewVD->hasAttr<BlocksAttr>()) {
2865    Diag(NewVD->getLocation(), diag::err_block_on_vm);
2866    return NewVD->setInvalidDecl();
2867  }
2868
2869  // Function pointers and references cannot have qualified function type, only
2870  // function pointer-to-members can do that.
2871  QualType Pointee;
2872  unsigned PtrOrRef = 0;
2873  if (const PointerType *Ptr = T->getAs<PointerType>())
2874    Pointee = Ptr->getPointeeType();
2875  else if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
2876    Pointee = Ref->getPointeeType();
2877    PtrOrRef = 1;
2878  }
2879  if (!Pointee.isNull() && Pointee->isFunctionProtoType() &&
2880      Pointee->getAs<FunctionProtoType>()->getTypeQuals() != 0) {
2881    Diag(NewVD->getLocation(), diag::err_invalid_qualified_function_pointer)
2882        << PtrOrRef;
2883    return NewVD->setInvalidDecl();
2884  }
2885
2886  if (!Previous.empty()) {
2887    Redeclaration = true;
2888    MergeVarDecl(NewVD, Previous);
2889  }
2890}
2891
2892/// \brief Data used with FindOverriddenMethod
2893struct FindOverriddenMethodData {
2894  Sema *S;
2895  CXXMethodDecl *Method;
2896};
2897
2898/// \brief Member lookup function that determines whether a given C++
2899/// method overrides a method in a base class, to be used with
2900/// CXXRecordDecl::lookupInBases().
2901static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
2902                                 CXXBasePath &Path,
2903                                 void *UserData) {
2904  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
2905
2906  FindOverriddenMethodData *Data
2907    = reinterpret_cast<FindOverriddenMethodData*>(UserData);
2908
2909  DeclarationName Name = Data->Method->getDeclName();
2910
2911  // FIXME: Do we care about other names here too?
2912  if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
2913    // We really want to find the base class destructor here.
2914    QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
2915    CanQualType CT = Data->S->Context.getCanonicalType(T);
2916
2917    Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
2918  }
2919
2920  for (Path.Decls = BaseRecord->lookup(Name);
2921       Path.Decls.first != Path.Decls.second;
2922       ++Path.Decls.first) {
2923    NamedDecl *D = *Path.Decls.first;
2924    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
2925      if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
2926        return true;
2927    }
2928  }
2929
2930  return false;
2931}
2932
2933/// AddOverriddenMethods - See if a method overrides any in the base classes,
2934/// and if so, check that it's a valid override and remember it.
2935void Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
2936  // Look for virtual methods in base classes that this method might override.
2937  CXXBasePaths Paths;
2938  FindOverriddenMethodData Data;
2939  Data.Method = MD;
2940  Data.S = this;
2941  if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
2942    for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
2943         E = Paths.found_decls_end(); I != E; ++I) {
2944      if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
2945        if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
2946            !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
2947            !CheckOverridingFunctionAttributes(MD, OldMD))
2948          MD->addOverriddenMethod(OldMD->getCanonicalDecl());
2949      }
2950    }
2951  }
2952}
2953
2954NamedDecl*
2955Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2956                              QualType R, TypeSourceInfo *TInfo,
2957                              LookupResult &Previous,
2958                              MultiTemplateParamsArg TemplateParamLists,
2959                              bool IsFunctionDefinition, bool &Redeclaration) {
2960  assert(R.getTypePtr()->isFunctionType());
2961
2962  DeclarationName Name = GetNameForDeclarator(D);
2963  FunctionDecl::StorageClass SC = FunctionDecl::None;
2964  switch (D.getDeclSpec().getStorageClassSpec()) {
2965  default: assert(0 && "Unknown storage class!");
2966  case DeclSpec::SCS_auto:
2967  case DeclSpec::SCS_register:
2968  case DeclSpec::SCS_mutable:
2969    Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2970         diag::err_typecheck_sclass_func);
2971    D.setInvalidType();
2972    break;
2973  case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
2974  case DeclSpec::SCS_extern:      SC = FunctionDecl::Extern; break;
2975  case DeclSpec::SCS_static: {
2976    if (CurContext->getLookupContext()->isFunctionOrMethod()) {
2977      // C99 6.7.1p5:
2978      //   The declaration of an identifier for a function that has
2979      //   block scope shall have no explicit storage-class specifier
2980      //   other than extern
2981      // See also (C++ [dcl.stc]p4).
2982      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2983           diag::err_static_block_func);
2984      SC = FunctionDecl::None;
2985    } else
2986      SC = FunctionDecl::Static;
2987    break;
2988  }
2989  case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
2990  }
2991
2992  if (D.getDeclSpec().isThreadSpecified())
2993    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2994
2995  bool isFriend = D.getDeclSpec().isFriendSpecified();
2996  bool isInline = D.getDeclSpec().isInlineSpecified();
2997  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
2998  bool isExplicit = D.getDeclSpec().isExplicitSpecified();
2999
3000  DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
3001  FunctionDecl::StorageClass SCAsWritten
3002    = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
3003
3004  // Check that the return type is not an abstract class type.
3005  // For record types, this is done by the AbstractClassUsageDiagnoser once
3006  // the class has been completely parsed.
3007  if (!DC->isRecord() &&
3008      RequireNonAbstractType(D.getIdentifierLoc(),
3009                             R->getAs<FunctionType>()->getResultType(),
3010                             diag::err_abstract_type_in_decl,
3011                             AbstractReturnType))
3012    D.setInvalidType();
3013
3014  // Do not allow returning a objc interface by-value.
3015  if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) {
3016    Diag(D.getIdentifierLoc(),
3017         diag::err_object_cannot_be_passed_returned_by_value) << 0
3018      << R->getAs<FunctionType>()->getResultType();
3019    D.setInvalidType();
3020  }
3021
3022  bool isVirtualOkay = false;
3023  FunctionDecl *NewFD;
3024
3025  if (isFriend) {
3026    // C++ [class.friend]p5
3027    //   A function can be defined in a friend declaration of a
3028    //   class . . . . Such a function is implicitly inline.
3029    isInline |= IsFunctionDefinition;
3030  }
3031
3032  if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
3033    // This is a C++ constructor declaration.
3034    assert(DC->isRecord() &&
3035           "Constructors can only be declared in a member context");
3036
3037    R = CheckConstructorDeclarator(D, R, SC);
3038
3039    // Create the new declaration
3040    NewFD = CXXConstructorDecl::Create(Context,
3041                                       cast<CXXRecordDecl>(DC),
3042                                       D.getIdentifierLoc(), Name, R, TInfo,
3043                                       isExplicit, isInline,
3044                                       /*isImplicitlyDeclared=*/false);
3045  } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
3046    // This is a C++ destructor declaration.
3047    if (DC->isRecord()) {
3048      R = CheckDestructorDeclarator(D, R, SC);
3049
3050      NewFD = CXXDestructorDecl::Create(Context,
3051                                        cast<CXXRecordDecl>(DC),
3052                                        D.getIdentifierLoc(), Name, R,
3053                                        isInline,
3054                                        /*isImplicitlyDeclared=*/false);
3055      NewFD->setTypeSourceInfo(TInfo);
3056
3057      isVirtualOkay = true;
3058    } else {
3059      Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
3060
3061      // Create a FunctionDecl to satisfy the function definition parsing
3062      // code path.
3063      NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
3064                                   Name, R, TInfo, SC, SCAsWritten, isInline,
3065                                   /*hasPrototype=*/true);
3066      D.setInvalidType();
3067    }
3068  } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
3069    if (!DC->isRecord()) {
3070      Diag(D.getIdentifierLoc(),
3071           diag::err_conv_function_not_member);
3072      return 0;
3073    }
3074
3075    CheckConversionDeclarator(D, R, SC);
3076    NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
3077                                      D.getIdentifierLoc(), Name, R, TInfo,
3078                                      isInline, isExplicit);
3079
3080    isVirtualOkay = true;
3081  } else if (DC->isRecord()) {
3082    // If the of the function is the same as the name of the record, then this
3083    // must be an invalid constructor that has a return type.
3084    // (The parser checks for a return type and makes the declarator a
3085    // constructor if it has no return type).
3086    // must have an invalid constructor that has a return type
3087    if (Name.getAsIdentifierInfo() &&
3088        Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
3089      Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
3090        << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3091        << SourceRange(D.getIdentifierLoc());
3092      return 0;
3093    }
3094
3095    bool isStatic = SC == FunctionDecl::Static;
3096
3097    // [class.free]p1:
3098    // Any allocation function for a class T is a static member
3099    // (even if not explicitly declared static).
3100    if (Name.getCXXOverloadedOperator() == OO_New ||
3101        Name.getCXXOverloadedOperator() == OO_Array_New)
3102      isStatic = true;
3103
3104    // [class.free]p6 Any deallocation function for a class X is a static member
3105    // (even if not explicitly declared static).
3106    if (Name.getCXXOverloadedOperator() == OO_Delete ||
3107        Name.getCXXOverloadedOperator() == OO_Array_Delete)
3108      isStatic = true;
3109
3110    // This is a C++ method declaration.
3111    NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
3112                                  D.getIdentifierLoc(), Name, R, TInfo,
3113                                  isStatic, SCAsWritten, isInline);
3114
3115    isVirtualOkay = !isStatic;
3116  } else {
3117    // Determine whether the function was written with a
3118    // prototype. This true when:
3119    //   - we're in C++ (where every function has a prototype),
3120    //   - there is a prototype in the declarator, or
3121    //   - the type R of the function is some kind of typedef or other reference
3122    //     to a type name (which eventually refers to a function type).
3123    bool HasPrototype =
3124       getLangOptions().CPlusPlus ||
3125       (D.getNumTypeObjects() && D.getTypeObject(0).Fun.hasPrototype) ||
3126       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
3127
3128    NewFD = FunctionDecl::Create(Context, DC,
3129                                 D.getIdentifierLoc(),
3130                                 Name, R, TInfo, SC, SCAsWritten, isInline,
3131                                 HasPrototype);
3132  }
3133
3134  if (D.isInvalidType())
3135    NewFD->setInvalidDecl();
3136
3137  SetNestedNameSpecifier(NewFD, D);
3138
3139  // Set the lexical context. If the declarator has a C++
3140  // scope specifier, or is the object of a friend declaration, the
3141  // lexical context will be different from the semantic context.
3142  NewFD->setLexicalDeclContext(CurContext);
3143
3144  // Match up the template parameter lists with the scope specifier, then
3145  // determine whether we have a template or a template specialization.
3146  FunctionTemplateDecl *FunctionTemplate = 0;
3147  bool isExplicitSpecialization = false;
3148  bool isFunctionTemplateSpecialization = false;
3149  unsigned NumMatchedTemplateParamLists = TemplateParamLists.size();
3150  bool Invalid = false;
3151  if (TemplateParameterList *TemplateParams
3152        = MatchTemplateParametersToScopeSpecifier(
3153                                  D.getDeclSpec().getSourceRange().getBegin(),
3154                                  D.getCXXScopeSpec(),
3155                           (TemplateParameterList**)TemplateParamLists.get(),
3156                                                  TemplateParamLists.size(),
3157                                                  isFriend,
3158                                                  isExplicitSpecialization,
3159                                                  Invalid)) {
3160    // All but one template parameter lists have been matching.
3161    --NumMatchedTemplateParamLists;
3162
3163    if (TemplateParams->size() > 0) {
3164      // This is a function template
3165
3166      // Check that we can declare a template here.
3167      if (CheckTemplateDeclScope(S, TemplateParams))
3168        return 0;
3169
3170      FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
3171                                                      NewFD->getLocation(),
3172                                                      Name, TemplateParams,
3173                                                      NewFD);
3174      FunctionTemplate->setLexicalDeclContext(CurContext);
3175      NewFD->setDescribedFunctionTemplate(FunctionTemplate);
3176    } else {
3177      // This is a function template specialization.
3178      isFunctionTemplateSpecialization = true;
3179
3180      // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
3181      if (isFriend && isFunctionTemplateSpecialization) {
3182        // We want to remove the "template<>", found here.
3183        SourceRange RemoveRange = TemplateParams->getSourceRange();
3184
3185        // If we remove the template<> and the name is not a
3186        // template-id, we're actually silently creating a problem:
3187        // the friend declaration will refer to an untemplated decl,
3188        // and clearly the user wants a template specialization.  So
3189        // we need to insert '<>' after the name.
3190        SourceLocation InsertLoc;
3191        if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
3192          InsertLoc = D.getName().getSourceRange().getEnd();
3193          InsertLoc = PP.getLocForEndOfToken(InsertLoc);
3194        }
3195
3196        Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
3197          << Name << RemoveRange
3198          << FixItHint::CreateRemoval(RemoveRange)
3199          << FixItHint::CreateInsertion(InsertLoc, "<>");
3200      }
3201    }
3202  }
3203
3204  if (NumMatchedTemplateParamLists > 0 && D.getCXXScopeSpec().isSet()) {
3205    NewFD->setTemplateParameterListsInfo(Context,
3206                                         NumMatchedTemplateParamLists,
3207                        (TemplateParameterList**)TemplateParamLists.release());
3208  }
3209
3210  if (Invalid) {
3211    NewFD->setInvalidDecl();
3212    if (FunctionTemplate)
3213      FunctionTemplate->setInvalidDecl();
3214  }
3215
3216  // C++ [dcl.fct.spec]p5:
3217  //   The virtual specifier shall only be used in declarations of
3218  //   nonstatic class member functions that appear within a
3219  //   member-specification of a class declaration; see 10.3.
3220  //
3221  if (isVirtual && !NewFD->isInvalidDecl()) {
3222    if (!isVirtualOkay) {
3223       Diag(D.getDeclSpec().getVirtualSpecLoc(),
3224           diag::err_virtual_non_function);
3225    } else if (!CurContext->isRecord()) {
3226      // 'virtual' was specified outside of the class.
3227      Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_out_of_class)
3228        << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
3229    } else {
3230      // Okay: Add virtual to the method.
3231      CXXRecordDecl *CurClass = cast<CXXRecordDecl>(DC);
3232      CurClass->setMethodAsVirtual(NewFD);
3233    }
3234  }
3235
3236  // C++ [dcl.fct.spec]p3:
3237  //  The inline specifier shall not appear on a block scope function declaration.
3238  if (isInline && !NewFD->isInvalidDecl() && getLangOptions().CPlusPlus) {
3239    if (CurContext->isFunctionOrMethod()) {
3240      // 'inline' is not allowed on block scope function declaration.
3241      Diag(D.getDeclSpec().getInlineSpecLoc(),
3242           diag::err_inline_declaration_block_scope) << Name
3243        << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
3244    }
3245  }
3246
3247  // C++ [dcl.fct.spec]p6:
3248  //  The explicit specifier shall be used only in the declaration of a
3249  //  constructor or conversion function within its class definition; see 12.3.1
3250  //  and 12.3.2.
3251  if (isExplicit && !NewFD->isInvalidDecl()) {
3252    if (!CurContext->isRecord()) {
3253      // 'explicit' was specified outside of the class.
3254      Diag(D.getDeclSpec().getExplicitSpecLoc(),
3255           diag::err_explicit_out_of_class)
3256        << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
3257    } else if (!isa<CXXConstructorDecl>(NewFD) &&
3258               !isa<CXXConversionDecl>(NewFD)) {
3259      // 'explicit' was specified on a function that wasn't a constructor
3260      // or conversion function.
3261      Diag(D.getDeclSpec().getExplicitSpecLoc(),
3262           diag::err_explicit_non_ctor_or_conv_function)
3263        << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
3264    }
3265  }
3266
3267  // Filter out previous declarations that don't match the scope.
3268  FilterLookupForScope(*this, Previous, DC, S, NewFD->hasLinkage());
3269
3270  if (isFriend) {
3271    // DC is the namespace in which the function is being declared.
3272    assert((DC->isFileContext() || !Previous.empty()) &&
3273           "previously-undeclared friend function being created "
3274           "in a non-namespace context");
3275
3276    // For now, claim that the objects have no previous declaration.
3277    if (FunctionTemplate) {
3278      FunctionTemplate->setObjectOfFriendDecl(false);
3279      FunctionTemplate->setAccess(AS_public);
3280    }
3281    NewFD->setObjectOfFriendDecl(false);
3282    NewFD->setAccess(AS_public);
3283  }
3284
3285  if (SC == FunctionDecl::Static && isa<CXXMethodDecl>(NewFD) &&
3286      !CurContext->isRecord()) {
3287    // C++ [class.static]p1:
3288    //   A data or function member of a class may be declared static
3289    //   in a class definition, in which case it is a static member of
3290    //   the class.
3291
3292    // Complain about the 'static' specifier if it's on an out-of-line
3293    // member function definition.
3294    Diag(D.getDeclSpec().getStorageClassSpecLoc(),
3295         diag::err_static_out_of_line)
3296      << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3297  }
3298
3299  // Handle GNU asm-label extension (encoded as an attribute).
3300  if (Expr *E = (Expr*) D.getAsmLabel()) {
3301    // The parser guarantees this is a string.
3302    StringLiteral *SE = cast<StringLiteral>(E);
3303    NewFD->addAttr(::new (Context) AsmLabelAttr(Context, SE->getString()));
3304  }
3305
3306  // Copy the parameter declarations from the declarator D to the function
3307  // declaration NewFD, if they are available.  First scavenge them into Params.
3308  llvm::SmallVector<ParmVarDecl*, 16> Params;
3309  if (D.getNumTypeObjects() > 0) {
3310    DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3311
3312    // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
3313    // function that takes no arguments, not a function that takes a
3314    // single void argument.
3315    // We let through "const void" here because Sema::GetTypeForDeclarator
3316    // already checks for that case.
3317    if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3318        FTI.ArgInfo[0].Param &&
3319        FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()) {
3320      // Empty arg list, don't push any params.
3321      ParmVarDecl *Param = FTI.ArgInfo[0].Param.getAs<ParmVarDecl>();
3322
3323      // In C++, the empty parameter-type-list must be spelled "void"; a
3324      // typedef of void is not permitted.
3325      if (getLangOptions().CPlusPlus &&
3326          Param->getType().getUnqualifiedType() != Context.VoidTy)
3327        Diag(Param->getLocation(), diag::err_param_typedef_of_void);
3328      // FIXME: Leaks decl?
3329    } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
3330      for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
3331        ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
3332        assert(Param->getDeclContext() != NewFD && "Was set before ?");
3333        Param->setDeclContext(NewFD);
3334        Params.push_back(Param);
3335
3336        if (Param->isInvalidDecl())
3337          NewFD->setInvalidDecl();
3338      }
3339    }
3340
3341  } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
3342    // When we're declaring a function with a typedef, typeof, etc as in the
3343    // following example, we'll need to synthesize (unnamed)
3344    // parameters for use in the declaration.
3345    //
3346    // @code
3347    // typedef void fn(int);
3348    // fn f;
3349    // @endcode
3350
3351    // Synthesize a parameter for each argument type.
3352    for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
3353         AE = FT->arg_type_end(); AI != AE; ++AI) {
3354      ParmVarDecl *Param =
3355        BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
3356      Params.push_back(Param);
3357    }
3358  } else {
3359    assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
3360           "Should not need args for typedef of non-prototype fn");
3361  }
3362  // Finally, we know we have the right number of parameters, install them.
3363  NewFD->setParams(Params.data(), Params.size());
3364
3365  // If the declarator is a template-id, translate the parser's template
3366  // argument list into our AST format.
3367  bool HasExplicitTemplateArgs = false;
3368  TemplateArgumentListInfo TemplateArgs;
3369  if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
3370    TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
3371    TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
3372    TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
3373    ASTTemplateArgsPtr TemplateArgsPtr(*this,
3374                                       TemplateId->getTemplateArgs(),
3375                                       TemplateId->NumArgs);
3376    translateTemplateArguments(TemplateArgsPtr,
3377                               TemplateArgs);
3378    TemplateArgsPtr.release();
3379
3380    HasExplicitTemplateArgs = true;
3381
3382    if (FunctionTemplate) {
3383      // FIXME: Diagnose function template with explicit template
3384      // arguments.
3385      HasExplicitTemplateArgs = false;
3386    } else if (!isFunctionTemplateSpecialization &&
3387               !D.getDeclSpec().isFriendSpecified()) {
3388      // We have encountered something that the user meant to be a
3389      // specialization (because it has explicitly-specified template
3390      // arguments) but that was not introduced with a "template<>" (or had
3391      // too few of them).
3392      Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
3393        << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
3394        << FixItHint::CreateInsertion(
3395                                   D.getDeclSpec().getSourceRange().getBegin(),
3396                                                 "template<> ");
3397      isFunctionTemplateSpecialization = true;
3398    } else {
3399      // "friend void foo<>(int);" is an implicit specialization decl.
3400      isFunctionTemplateSpecialization = true;
3401    }
3402  } else if (isFriend && isFunctionTemplateSpecialization) {
3403    // This combination is only possible in a recovery case;  the user
3404    // wrote something like:
3405    //   template <> friend void foo(int);
3406    // which we're recovering from as if the user had written:
3407    //   friend void foo<>(int);
3408    // Go ahead and fake up a template id.
3409    HasExplicitTemplateArgs = true;
3410    TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
3411    TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
3412  }
3413
3414  // If it's a friend (and only if it's a friend), it's possible
3415  // that either the specialized function type or the specialized
3416  // template is dependent, and therefore matching will fail.  In
3417  // this case, don't check the specialization yet.
3418  if (isFunctionTemplateSpecialization && isFriend &&
3419      (NewFD->getType()->isDependentType() || DC->isDependentContext())) {
3420    assert(HasExplicitTemplateArgs &&
3421           "friend function specialization without template args");
3422    if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
3423                                                     Previous))
3424      NewFD->setInvalidDecl();
3425  } else if (isFunctionTemplateSpecialization) {
3426    if (CheckFunctionTemplateSpecialization(NewFD,
3427                               (HasExplicitTemplateArgs ? &TemplateArgs : 0),
3428                                            Previous))
3429      NewFD->setInvalidDecl();
3430  } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
3431    if (CheckMemberSpecialization(NewFD, Previous))
3432      NewFD->setInvalidDecl();
3433  }
3434
3435  // Perform semantic checking on the function declaration.
3436  bool OverloadableAttrRequired = false; // FIXME: HACK!
3437  CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization,
3438                           Redeclaration, /*FIXME:*/OverloadableAttrRequired);
3439
3440  assert((NewFD->isInvalidDecl() || !Redeclaration ||
3441          Previous.getResultKind() != LookupResult::FoundOverloaded) &&
3442         "previous declaration set still overloaded");
3443
3444  NamedDecl *PrincipalDecl = (FunctionTemplate
3445                              ? cast<NamedDecl>(FunctionTemplate)
3446                              : NewFD);
3447
3448  if (isFriend && Redeclaration) {
3449    AccessSpecifier Access = AS_public;
3450    if (!NewFD->isInvalidDecl())
3451      Access = NewFD->getPreviousDeclaration()->getAccess();
3452
3453    NewFD->setAccess(Access);
3454    if (FunctionTemplate) FunctionTemplate->setAccess(Access);
3455
3456    PrincipalDecl->setObjectOfFriendDecl(true);
3457  }
3458
3459  if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
3460      PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
3461    PrincipalDecl->setNonMemberOperator();
3462
3463  // If we have a function template, check the template parameter
3464  // list. This will check and merge default template arguments.
3465  if (FunctionTemplate) {
3466    FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDeclaration();
3467    CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
3468                      PrevTemplate? PrevTemplate->getTemplateParameters() : 0,
3469             D.getDeclSpec().isFriendSpecified()? TPC_FriendFunctionTemplate
3470                                                : TPC_FunctionTemplate);
3471  }
3472
3473  if (D.getCXXScopeSpec().isSet() && !NewFD->isInvalidDecl()) {
3474    // Fake up an access specifier if it's supposed to be a class member.
3475    if (!Redeclaration && isa<CXXRecordDecl>(NewFD->getDeclContext()))
3476      NewFD->setAccess(AS_public);
3477
3478    // An out-of-line member function declaration must also be a
3479    // definition (C++ [dcl.meaning]p1).
3480    // Note that this is not the case for explicit specializations of
3481    // function templates or member functions of class templates, per
3482    // C++ [temp.expl.spec]p2. We also allow these declarations as an extension
3483    // for compatibility with old SWIG code which likes to generate them.
3484    if (!IsFunctionDefinition && !isFriend &&
3485        !isFunctionTemplateSpecialization && !isExplicitSpecialization) {
3486      Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
3487        << D.getCXXScopeSpec().getRange();
3488    }
3489    if (!Redeclaration && !(isFriend && CurContext->isDependentContext())) {
3490      // The user tried to provide an out-of-line definition for a
3491      // function that is a member of a class or namespace, but there
3492      // was no such member function declared (C++ [class.mfct]p2,
3493      // C++ [namespace.memdef]p2). For example:
3494      //
3495      // class X {
3496      //   void f() const;
3497      // };
3498      //
3499      // void X::f() { } // ill-formed
3500      //
3501      // Complain about this problem, and attempt to suggest close
3502      // matches (e.g., those that differ only in cv-qualifiers and
3503      // whether the parameter types are references).
3504      Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
3505        << Name << DC << D.getCXXScopeSpec().getRange();
3506      NewFD->setInvalidDecl();
3507
3508      LookupResult Prev(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
3509                        ForRedeclaration);
3510      LookupQualifiedName(Prev, DC);
3511      assert(!Prev.isAmbiguous() &&
3512             "Cannot have an ambiguity in previous-declaration lookup");
3513      for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
3514           Func != FuncEnd; ++Func) {
3515        if (isa<FunctionDecl>(*Func) &&
3516            isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD))
3517          Diag((*Func)->getLocation(), diag::note_member_def_close_match);
3518      }
3519    }
3520  }
3521
3522  // Handle attributes. We need to have merged decls when handling attributes
3523  // (for example to check for conflicts, etc).
3524  // FIXME: This needs to happen before we merge declarations. Then,
3525  // let attribute merging cope with attribute conflicts.
3526  ProcessDeclAttributes(S, NewFD, D);
3527
3528  // attributes declared post-definition are currently ignored
3529  if (Redeclaration && Previous.isSingleResult()) {
3530    const FunctionDecl *Def;
3531    FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
3532    if (PrevFD && PrevFD->hasBody(Def) && D.hasAttributes()) {
3533      Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
3534      Diag(Def->getLocation(), diag::note_previous_definition);
3535    }
3536  }
3537
3538  AddKnownFunctionAttributes(NewFD);
3539
3540  if (OverloadableAttrRequired && !NewFD->getAttr<OverloadableAttr>()) {
3541    // If a function name is overloadable in C, then every function
3542    // with that name must be marked "overloadable".
3543    Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
3544      << Redeclaration << NewFD;
3545    if (!Previous.empty())
3546      Diag(Previous.getRepresentativeDecl()->getLocation(),
3547           diag::note_attribute_overloadable_prev_overload);
3548    NewFD->addAttr(::new (Context) OverloadableAttr());
3549  }
3550
3551  if (NewFD->hasAttr<OverloadableAttr>() &&
3552      !NewFD->getType()->getAs<FunctionProtoType>()) {
3553    Diag(NewFD->getLocation(),
3554         diag::err_attribute_overloadable_no_prototype)
3555      << NewFD;
3556
3557    // Turn this into a variadic function with no parameters.
3558    const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
3559    QualType R = Context.getFunctionType(FT->getResultType(),
3560                                         0, 0, true, 0, false, false, 0, 0,
3561                                         FT->getExtInfo());
3562    NewFD->setType(R);
3563  }
3564
3565  // If there's a #pragma GCC visibility in scope, and this isn't a class
3566  // member, set the visibility of this function.
3567  if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord())
3568    AddPushedVisibilityAttribute(NewFD);
3569
3570  // If this is a locally-scoped extern C function, update the
3571  // map of such names.
3572  if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
3573      && !NewFD->isInvalidDecl())
3574    RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
3575
3576  // Set this FunctionDecl's range up to the right paren.
3577  NewFD->setLocEnd(D.getSourceRange().getEnd());
3578
3579  if (FunctionTemplate && NewFD->isInvalidDecl())
3580    FunctionTemplate->setInvalidDecl();
3581
3582  if (FunctionTemplate)
3583    return FunctionTemplate;
3584
3585
3586  // Keep track of static, non-inlined function definitions that
3587  // have not been used. We will warn later.
3588  // FIXME: Also include static functions declared but not defined.
3589  if (!NewFD->isInvalidDecl() && IsFunctionDefinition
3590      && !NewFD->isInlined() && NewFD->getLinkage() == InternalLinkage
3591      && !NewFD->isUsed() && !NewFD->hasAttr<UnusedAttr>()
3592      && !NewFD->hasAttr<ConstructorAttr>()
3593      && !NewFD->hasAttr<DestructorAttr>())
3594    UnusedStaticFuncs.push_back(NewFD);
3595
3596  return NewFD;
3597}
3598
3599/// \brief Perform semantic checking of a new function declaration.
3600///
3601/// Performs semantic analysis of the new function declaration
3602/// NewFD. This routine performs all semantic checking that does not
3603/// require the actual declarator involved in the declaration, and is
3604/// used both for the declaration of functions as they are parsed
3605/// (called via ActOnDeclarator) and for the declaration of functions
3606/// that have been instantiated via C++ template instantiation (called
3607/// via InstantiateDecl).
3608///
3609/// \param IsExplicitSpecialiation whether this new function declaration is
3610/// an explicit specialization of the previous declaration.
3611///
3612/// This sets NewFD->isInvalidDecl() to true if there was an error.
3613void Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
3614                                    LookupResult &Previous,
3615                                    bool IsExplicitSpecialization,
3616                                    bool &Redeclaration,
3617                                    bool &OverloadableAttrRequired) {
3618  // If NewFD is already known erroneous, don't do any of this checking.
3619  if (NewFD->isInvalidDecl())
3620    return;
3621
3622  if (NewFD->getResultType()->isVariablyModifiedType()) {
3623    // Functions returning a variably modified type violate C99 6.7.5.2p2
3624    // because all functions have linkage.
3625    Diag(NewFD->getLocation(), diag::err_vm_func_decl);
3626    return NewFD->setInvalidDecl();
3627  }
3628
3629  if (NewFD->isMain())
3630    CheckMain(NewFD);
3631
3632  // Check for a previous declaration of this name.
3633  if (Previous.empty() && NewFD->isExternC()) {
3634    // Since we did not find anything by this name and we're declaring
3635    // an extern "C" function, look for a non-visible extern "C"
3636    // declaration with the same name.
3637    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
3638      = LocallyScopedExternalDecls.find(NewFD->getDeclName());
3639    if (Pos != LocallyScopedExternalDecls.end())
3640      Previous.addDecl(Pos->second);
3641  }
3642
3643  // Merge or overload the declaration with an existing declaration of
3644  // the same name, if appropriate.
3645  if (!Previous.empty()) {
3646    // Determine whether NewFD is an overload of PrevDecl or
3647    // a declaration that requires merging. If it's an overload,
3648    // there's no more work to do here; we'll just add the new
3649    // function to the scope.
3650
3651    NamedDecl *OldDecl = 0;
3652    if (!AllowOverloadingOfFunction(Previous, Context)) {
3653      Redeclaration = true;
3654      OldDecl = Previous.getFoundDecl();
3655    } else {
3656      if (!getLangOptions().CPlusPlus)
3657        OverloadableAttrRequired = true;
3658
3659      switch (CheckOverload(S, NewFD, Previous, OldDecl,
3660                            /*NewIsUsingDecl*/ false)) {
3661      case Ovl_Match:
3662        Redeclaration = true;
3663        break;
3664
3665      case Ovl_NonFunction:
3666        Redeclaration = true;
3667        break;
3668
3669      case Ovl_Overload:
3670        Redeclaration = false;
3671        break;
3672      }
3673    }
3674
3675    if (Redeclaration) {
3676      // NewFD and OldDecl represent declarations that need to be
3677      // merged.
3678      if (MergeFunctionDecl(NewFD, OldDecl))
3679        return NewFD->setInvalidDecl();
3680
3681      Previous.clear();
3682      Previous.addDecl(OldDecl);
3683
3684      if (FunctionTemplateDecl *OldTemplateDecl
3685                                    = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
3686        NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
3687        FunctionTemplateDecl *NewTemplateDecl
3688          = NewFD->getDescribedFunctionTemplate();
3689        assert(NewTemplateDecl && "Template/non-template mismatch");
3690        if (CXXMethodDecl *Method
3691              = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
3692          Method->setAccess(OldTemplateDecl->getAccess());
3693          NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
3694        }
3695
3696        // If this is an explicit specialization of a member that is a function
3697        // template, mark it as a member specialization.
3698        if (IsExplicitSpecialization &&
3699            NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
3700          NewTemplateDecl->setMemberSpecialization();
3701          assert(OldTemplateDecl->isMemberSpecialization());
3702        }
3703      } else {
3704        if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
3705          NewFD->setAccess(OldDecl->getAccess());
3706        NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
3707      }
3708    }
3709  }
3710
3711  // Semantic checking for this function declaration (in isolation).
3712  if (getLangOptions().CPlusPlus) {
3713    // C++-specific checks.
3714    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
3715      CheckConstructor(Constructor);
3716    } else if (CXXDestructorDecl *Destructor =
3717                dyn_cast<CXXDestructorDecl>(NewFD)) {
3718      CXXRecordDecl *Record = Destructor->getParent();
3719      QualType ClassType = Context.getTypeDeclType(Record);
3720
3721      // FIXME: Shouldn't we be able to perform this check even when the class
3722      // type is dependent? Both gcc and edg can handle that.
3723      if (!ClassType->isDependentType()) {
3724        DeclarationName Name
3725          = Context.DeclarationNames.getCXXDestructorName(
3726                                        Context.getCanonicalType(ClassType));
3727        if (NewFD->getDeclName() != Name) {
3728          Diag(NewFD->getLocation(), diag::err_destructor_name);
3729          return NewFD->setInvalidDecl();
3730        }
3731      }
3732
3733      Record->setUserDeclaredDestructor(true);
3734      // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
3735      // user-defined destructor.
3736      Record->setPOD(false);
3737
3738      // C++ [class.dtor]p3: A destructor is trivial if it is an implicitly-
3739      // declared destructor.
3740      // FIXME: C++0x: don't do this for "= default" destructors
3741      Record->setHasTrivialDestructor(false);
3742    } else if (CXXConversionDecl *Conversion
3743               = dyn_cast<CXXConversionDecl>(NewFD)) {
3744      ActOnConversionDeclarator(Conversion);
3745    }
3746
3747    // Find any virtual functions that this function overrides.
3748    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
3749      if (!Method->isFunctionTemplateSpecialization() &&
3750          !Method->getDescribedFunctionTemplate())
3751        AddOverriddenMethods(Method->getParent(), Method);
3752    }
3753
3754    // Extra checking for C++ overloaded operators (C++ [over.oper]).
3755    if (NewFD->isOverloadedOperator() &&
3756        CheckOverloadedOperatorDeclaration(NewFD))
3757      return NewFD->setInvalidDecl();
3758
3759    // Extra checking for C++0x literal operators (C++0x [over.literal]).
3760    if (NewFD->getLiteralIdentifier() &&
3761        CheckLiteralOperatorDeclaration(NewFD))
3762      return NewFD->setInvalidDecl();
3763
3764    // In C++, check default arguments now that we have merged decls. Unless
3765    // the lexical context is the class, because in this case this is done
3766    // during delayed parsing anyway.
3767    if (!CurContext->isRecord())
3768      CheckCXXDefaultArguments(NewFD);
3769  }
3770}
3771
3772void Sema::CheckMain(FunctionDecl* FD) {
3773  // C++ [basic.start.main]p3:  A program that declares main to be inline
3774  //   or static is ill-formed.
3775  // C99 6.7.4p4:  In a hosted environment, the inline function specifier
3776  //   shall not appear in a declaration of main.
3777  // static main is not an error under C99, but we should warn about it.
3778  bool isInline = FD->isInlineSpecified();
3779  bool isStatic = FD->getStorageClass() == FunctionDecl::Static;
3780  if (isInline || isStatic) {
3781    unsigned diagID = diag::warn_unusual_main_decl;
3782    if (isInline || getLangOptions().CPlusPlus)
3783      diagID = diag::err_unusual_main_decl;
3784
3785    int which = isStatic + (isInline << 1) - 1;
3786    Diag(FD->getLocation(), diagID) << which;
3787  }
3788
3789  QualType T = FD->getType();
3790  assert(T->isFunctionType() && "function decl is not of function type");
3791  const FunctionType* FT = T->getAs<FunctionType>();
3792
3793  if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
3794    // TODO: add a replacement fixit to turn the return type into 'int'.
3795    Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
3796    FD->setInvalidDecl(true);
3797  }
3798
3799  // Treat protoless main() as nullary.
3800  if (isa<FunctionNoProtoType>(FT)) return;
3801
3802  const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
3803  unsigned nparams = FTP->getNumArgs();
3804  assert(FD->getNumParams() == nparams);
3805
3806  bool HasExtraParameters = (nparams > 3);
3807
3808  // Darwin passes an undocumented fourth argument of type char**.  If
3809  // other platforms start sprouting these, the logic below will start
3810  // getting shifty.
3811  if (nparams == 4 &&
3812      Context.Target.getTriple().getOS() == llvm::Triple::Darwin)
3813    HasExtraParameters = false;
3814
3815  if (HasExtraParameters) {
3816    Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
3817    FD->setInvalidDecl(true);
3818    nparams = 3;
3819  }
3820
3821  // FIXME: a lot of the following diagnostics would be improved
3822  // if we had some location information about types.
3823
3824  QualType CharPP =
3825    Context.getPointerType(Context.getPointerType(Context.CharTy));
3826  QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
3827
3828  for (unsigned i = 0; i < nparams; ++i) {
3829    QualType AT = FTP->getArgType(i);
3830
3831    bool mismatch = true;
3832
3833    if (Context.hasSameUnqualifiedType(AT, Expected[i]))
3834      mismatch = false;
3835    else if (Expected[i] == CharPP) {
3836      // As an extension, the following forms are okay:
3837      //   char const **
3838      //   char const * const *
3839      //   char * const *
3840
3841      QualifierCollector qs;
3842      const PointerType* PT;
3843      if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
3844          (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
3845          (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
3846        qs.removeConst();
3847        mismatch = !qs.empty();
3848      }
3849    }
3850
3851    if (mismatch) {
3852      Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
3853      // TODO: suggest replacing given type with expected type
3854      FD->setInvalidDecl(true);
3855    }
3856  }
3857
3858  if (nparams == 1 && !FD->isInvalidDecl()) {
3859    Diag(FD->getLocation(), diag::warn_main_one_arg);
3860  }
3861}
3862
3863bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
3864  // FIXME: Need strict checking.  In C89, we need to check for
3865  // any assignment, increment, decrement, function-calls, or
3866  // commas outside of a sizeof.  In C99, it's the same list,
3867  // except that the aforementioned are allowed in unevaluated
3868  // expressions.  Everything else falls under the
3869  // "may accept other forms of constant expressions" exception.
3870  // (We never end up here for C++, so the constant expression
3871  // rules there don't matter.)
3872  if (Init->isConstantInitializer(Context, false))
3873    return false;
3874  Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
3875    << Init->getSourceRange();
3876  return true;
3877}
3878
3879void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init) {
3880  AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
3881}
3882
3883/// AddInitializerToDecl - Adds the initializer Init to the
3884/// declaration dcl. If DirectInit is true, this is C++ direct
3885/// initialization rather than copy initialization.
3886void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init, bool DirectInit) {
3887  Decl *RealDecl = dcl.getAs<Decl>();
3888  // If there is no declaration, there was an error parsing it.  Just ignore
3889  // the initializer.
3890  if (RealDecl == 0)
3891    return;
3892
3893  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
3894    // With declarators parsed the way they are, the parser cannot
3895    // distinguish between a normal initializer and a pure-specifier.
3896    // Thus this grotesque test.
3897    IntegerLiteral *IL;
3898    Expr *Init = static_cast<Expr *>(init.get());
3899    if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
3900        Context.getCanonicalType(IL->getType()) == Context.IntTy)
3901      CheckPureMethod(Method, Init->getSourceRange());
3902    else {
3903      Diag(Method->getLocation(), diag::err_member_function_initialization)
3904        << Method->getDeclName() << Init->getSourceRange();
3905      Method->setInvalidDecl();
3906    }
3907    return;
3908  }
3909
3910  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3911  if (!VDecl) {
3912    if (getLangOptions().CPlusPlus &&
3913        RealDecl->getLexicalDeclContext()->isRecord() &&
3914        isa<NamedDecl>(RealDecl))
3915      Diag(RealDecl->getLocation(), diag::err_member_initialization)
3916        << cast<NamedDecl>(RealDecl)->getDeclName();
3917    else
3918      Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3919    RealDecl->setInvalidDecl();
3920    return;
3921  }
3922
3923  // A definition must end up with a complete type, which means it must be
3924  // complete with the restriction that an array type might be completed by the
3925  // initializer; note that later code assumes this restriction.
3926  QualType BaseDeclType = VDecl->getType();
3927  if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
3928    BaseDeclType = Array->getElementType();
3929  if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
3930                          diag::err_typecheck_decl_incomplete_type)) {
3931    RealDecl->setInvalidDecl();
3932    return;
3933  }
3934
3935  // The variable can not have an abstract class type.
3936  if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
3937                             diag::err_abstract_type_in_decl,
3938                             AbstractVariableType))
3939    VDecl->setInvalidDecl();
3940
3941  const VarDecl *Def;
3942  if ((Def = VDecl->getDefinition()) && Def != VDecl) {
3943    Diag(VDecl->getLocation(), diag::err_redefinition)
3944      << VDecl->getDeclName();
3945    Diag(Def->getLocation(), diag::note_previous_definition);
3946    VDecl->setInvalidDecl();
3947    return;
3948  }
3949
3950  if (getLangOptions().CPlusPlus && VDecl->hasLocalStorage())
3951    setFunctionHasBranchProtectedScope();
3952
3953  // Take ownership of the expression, now that we're sure we have somewhere
3954  // to put it.
3955  Expr *Init = init.takeAs<Expr>();
3956  assert(Init && "missing initializer");
3957
3958  // Capture the variable that is being initialized and the style of
3959  // initialization.
3960  InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
3961
3962  // FIXME: Poor source location information.
3963  InitializationKind Kind
3964    = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(),
3965                                                   Init->getLocStart(),
3966                                                   Init->getLocEnd())
3967                : InitializationKind::CreateCopy(VDecl->getLocation(),
3968                                                 Init->getLocStart());
3969
3970  // Get the decls type and save a reference for later, since
3971  // CheckInitializerTypes may change it.
3972  QualType DclT = VDecl->getType(), SavT = DclT;
3973  if (VDecl->isBlockVarDecl()) {
3974    if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
3975      Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
3976      VDecl->setInvalidDecl();
3977    } else if (!VDecl->isInvalidDecl()) {
3978      InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
3979      OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3980                                          MultiExprArg(*this, (void**)&Init, 1),
3981                                                &DclT);
3982      if (Result.isInvalid()) {
3983        VDecl->setInvalidDecl();
3984        return;
3985      }
3986
3987      Init = Result.takeAs<Expr>();
3988
3989      // C++ 3.6.2p2, allow dynamic initialization of static initializers.
3990      // Don't check invalid declarations to avoid emitting useless diagnostics.
3991      if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
3992        if (VDecl->getStorageClass() == VarDecl::Static) // C99 6.7.8p4.
3993          CheckForConstantInitializer(Init, DclT);
3994      }
3995    }
3996  } else if (VDecl->isStaticDataMember() &&
3997             VDecl->getLexicalDeclContext()->isRecord()) {
3998    // This is an in-class initialization for a static data member, e.g.,
3999    //
4000    // struct S {
4001    //   static const int value = 17;
4002    // };
4003
4004    // Attach the initializer
4005    VDecl->setInit(Init);
4006
4007    // C++ [class.mem]p4:
4008    //   A member-declarator can contain a constant-initializer only
4009    //   if it declares a static member (9.4) of const integral or
4010    //   const enumeration type, see 9.4.2.
4011    QualType T = VDecl->getType();
4012    if (!T->isDependentType() &&
4013        (!Context.getCanonicalType(T).isConstQualified() ||
4014         !T->isIntegralOrEnumerationType())) {
4015      Diag(VDecl->getLocation(), diag::err_member_initialization)
4016        << VDecl->getDeclName() << Init->getSourceRange();
4017      VDecl->setInvalidDecl();
4018    } else {
4019      // C++ [class.static.data]p4:
4020      //   If a static data member is of const integral or const
4021      //   enumeration type, its declaration in the class definition
4022      //   can specify a constant-initializer which shall be an
4023      //   integral constant expression (5.19).
4024      if (!Init->isTypeDependent() &&
4025          !Init->getType()->isIntegralOrEnumerationType()) {
4026        // We have a non-dependent, non-integral or enumeration type.
4027        Diag(Init->getSourceRange().getBegin(),
4028             diag::err_in_class_initializer_non_integral_type)
4029          << Init->getType() << Init->getSourceRange();
4030        VDecl->setInvalidDecl();
4031      } else if (!Init->isTypeDependent() && !Init->isValueDependent()) {
4032        // Check whether the expression is a constant expression.
4033        llvm::APSInt Value;
4034        SourceLocation Loc;
4035        if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) {
4036          Diag(Loc, diag::err_in_class_initializer_non_constant)
4037            << Init->getSourceRange();
4038          VDecl->setInvalidDecl();
4039        } else if (!VDecl->getType()->isDependentType())
4040          ImpCastExprToType(Init, VDecl->getType(), CastExpr::CK_IntegralCast);
4041      }
4042    }
4043  } else if (VDecl->isFileVarDecl()) {
4044    if (VDecl->getStorageClass() == VarDecl::Extern &&
4045        (!getLangOptions().CPlusPlus ||
4046         !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
4047      Diag(VDecl->getLocation(), diag::warn_extern_init);
4048    if (!VDecl->isInvalidDecl()) {
4049      InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
4050      OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
4051                                          MultiExprArg(*this, (void**)&Init, 1),
4052                                                &DclT);
4053      if (Result.isInvalid()) {
4054        VDecl->setInvalidDecl();
4055        return;
4056      }
4057
4058      Init = Result.takeAs<Expr>();
4059    }
4060
4061    // C++ 3.6.2p2, allow dynamic initialization of static initializers.
4062    // Don't check invalid declarations to avoid emitting useless diagnostics.
4063    if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
4064      // C99 6.7.8p4. All file scoped initializers need to be constant.
4065      CheckForConstantInitializer(Init, DclT);
4066    }
4067  }
4068  // If the type changed, it means we had an incomplete type that was
4069  // completed by the initializer. For example:
4070  //   int ary[] = { 1, 3, 5 };
4071  // "ary" transitions from a VariableArrayType to a ConstantArrayType.
4072  if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
4073    VDecl->setType(DclT);
4074    Init->setType(DclT);
4075  }
4076
4077  Init = MaybeCreateCXXExprWithTemporaries(Init);
4078  // Attach the initializer to the decl.
4079  VDecl->setInit(Init);
4080
4081  if (getLangOptions().CPlusPlus) {
4082    if (!VDecl->isInvalidDecl() &&
4083        !VDecl->getDeclContext()->isDependentContext() &&
4084        VDecl->hasGlobalStorage() &&
4085        !Init->isConstantInitializer(Context,
4086                                     VDecl->getType()->isReferenceType()))
4087      Diag(VDecl->getLocation(), diag::warn_global_constructor)
4088        << Init->getSourceRange();
4089
4090    // Make sure we mark the destructor as used if necessary.
4091    QualType InitType = VDecl->getType();
4092    while (const ArrayType *Array = Context.getAsArrayType(InitType))
4093      InitType = Context.getBaseElementType(Array);
4094    if (const RecordType *Record = InitType->getAs<RecordType>())
4095      FinalizeVarWithDestructor(VDecl, Record);
4096  }
4097
4098  return;
4099}
4100
4101/// ActOnInitializerError - Given that there was an error parsing an
4102/// initializer for the given declaration, try to return to some form
4103/// of sanity.
4104void Sema::ActOnInitializerError(DeclPtrTy dcl) {
4105  // Our main concern here is re-establishing invariants like "a
4106  // variable's type is either dependent or complete".
4107  Decl *D = dcl.getAs<Decl>();
4108  if (!D || D->isInvalidDecl()) return;
4109
4110  VarDecl *VD = dyn_cast<VarDecl>(D);
4111  if (!VD) return;
4112
4113  QualType Ty = VD->getType();
4114  if (Ty->isDependentType()) return;
4115
4116  // Require a complete type.
4117  if (RequireCompleteType(VD->getLocation(),
4118                          Context.getBaseElementType(Ty),
4119                          diag::err_typecheck_decl_incomplete_type)) {
4120    VD->setInvalidDecl();
4121    return;
4122  }
4123
4124  // Require an abstract type.
4125  if (RequireNonAbstractType(VD->getLocation(), Ty,
4126                             diag::err_abstract_type_in_decl,
4127                             AbstractVariableType)) {
4128    VD->setInvalidDecl();
4129    return;
4130  }
4131
4132  // Don't bother complaining about constructors or destructors,
4133  // though.
4134}
4135
4136void Sema::ActOnUninitializedDecl(DeclPtrTy dcl,
4137                                  bool TypeContainsUndeducedAuto) {
4138  Decl *RealDecl = dcl.getAs<Decl>();
4139
4140  // If there is no declaration, there was an error parsing it. Just ignore it.
4141  if (RealDecl == 0)
4142    return;
4143
4144  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
4145    QualType Type = Var->getType();
4146
4147    // C++0x [dcl.spec.auto]p3
4148    if (TypeContainsUndeducedAuto) {
4149      Diag(Var->getLocation(), diag::err_auto_var_requires_init)
4150        << Var->getDeclName() << Type;
4151      Var->setInvalidDecl();
4152      return;
4153    }
4154
4155    switch (Var->isThisDeclarationADefinition()) {
4156    case VarDecl::Definition:
4157      if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
4158        break;
4159
4160      // We have an out-of-line definition of a static data member
4161      // that has an in-class initializer, so we type-check this like
4162      // a declaration.
4163      //
4164      // Fall through
4165
4166    case VarDecl::DeclarationOnly:
4167      // It's only a declaration.
4168
4169      // Block scope. C99 6.7p7: If an identifier for an object is
4170      // declared with no linkage (C99 6.2.2p6), the type for the
4171      // object shall be complete.
4172      if (!Type->isDependentType() && Var->isBlockVarDecl() &&
4173          !Var->getLinkage() && !Var->isInvalidDecl() &&
4174          RequireCompleteType(Var->getLocation(), Type,
4175                              diag::err_typecheck_decl_incomplete_type))
4176        Var->setInvalidDecl();
4177
4178      // Make sure that the type is not abstract.
4179      if (!Type->isDependentType() && !Var->isInvalidDecl() &&
4180          RequireNonAbstractType(Var->getLocation(), Type,
4181                                 diag::err_abstract_type_in_decl,
4182                                 AbstractVariableType))
4183        Var->setInvalidDecl();
4184      return;
4185
4186    case VarDecl::TentativeDefinition:
4187      // File scope. C99 6.9.2p2: A declaration of an identifier for an
4188      // object that has file scope without an initializer, and without a
4189      // storage-class specifier or with the storage-class specifier "static",
4190      // constitutes a tentative definition. Note: A tentative definition with
4191      // external linkage is valid (C99 6.2.2p5).
4192      if (!Var->isInvalidDecl()) {
4193        if (const IncompleteArrayType *ArrayT
4194                                    = Context.getAsIncompleteArrayType(Type)) {
4195          if (RequireCompleteType(Var->getLocation(),
4196                                  ArrayT->getElementType(),
4197                                  diag::err_illegal_decl_array_incomplete_type))
4198            Var->setInvalidDecl();
4199        } else if (Var->getStorageClass() == VarDecl::Static) {
4200          // C99 6.9.2p3: If the declaration of an identifier for an object is
4201          // a tentative definition and has internal linkage (C99 6.2.2p3), the
4202          // declared type shall not be an incomplete type.
4203          // NOTE: code such as the following
4204          //     static struct s;
4205          //     struct s { int a; };
4206          // is accepted by gcc. Hence here we issue a warning instead of
4207          // an error and we do not invalidate the static declaration.
4208          // NOTE: to avoid multiple warnings, only check the first declaration.
4209          if (Var->getPreviousDeclaration() == 0)
4210            RequireCompleteType(Var->getLocation(), Type,
4211                                diag::ext_typecheck_decl_incomplete_type);
4212        }
4213      }
4214
4215      // Record the tentative definition; we're done.
4216      if (!Var->isInvalidDecl())
4217        TentativeDefinitions.push_back(Var);
4218      return;
4219    }
4220
4221    // Provide a specific diagnostic for uninitialized variable
4222    // definitions with incomplete array type.
4223    if (Type->isIncompleteArrayType()) {
4224      Diag(Var->getLocation(),
4225           diag::err_typecheck_incomplete_array_needs_initializer);
4226      Var->setInvalidDecl();
4227      return;
4228    }
4229
4230    // Provide a specific diagnostic for uninitialized variable
4231    // definitions with reference type.
4232    if (Type->isReferenceType()) {
4233      Diag(Var->getLocation(), diag::err_reference_var_requires_init)
4234        << Var->getDeclName()
4235        << SourceRange(Var->getLocation(), Var->getLocation());
4236      Var->setInvalidDecl();
4237      return;
4238    }
4239
4240    // Do not attempt to type-check the default initializer for a
4241    // variable with dependent type.
4242    if (Type->isDependentType())
4243      return;
4244
4245    if (Var->isInvalidDecl())
4246      return;
4247
4248    if (RequireCompleteType(Var->getLocation(),
4249                            Context.getBaseElementType(Type),
4250                            diag::err_typecheck_decl_incomplete_type)) {
4251      Var->setInvalidDecl();
4252      return;
4253    }
4254
4255    // The variable can not have an abstract class type.
4256    if (RequireNonAbstractType(Var->getLocation(), Type,
4257                               diag::err_abstract_type_in_decl,
4258                               AbstractVariableType)) {
4259      Var->setInvalidDecl();
4260      return;
4261    }
4262
4263    const RecordType *Record
4264      = Context.getBaseElementType(Type)->getAs<RecordType>();
4265    if (Record && getLangOptions().CPlusPlus && !getLangOptions().CPlusPlus0x &&
4266        cast<CXXRecordDecl>(Record->getDecl())->isPOD()) {
4267      // C++03 [dcl.init]p9:
4268      //   If no initializer is specified for an object, and the
4269      //   object is of (possibly cv-qualified) non-POD class type (or
4270      //   array thereof), the object shall be default-initialized; if
4271      //   the object is of const-qualified type, the underlying class
4272      //   type shall have a user-declared default
4273      //   constructor. Otherwise, if no initializer is specified for
4274      //   a non- static object, the object and its subobjects, if
4275      //   any, have an indeterminate initial value); if the object
4276      //   or any of its subobjects are of const-qualified type, the
4277      //   program is ill-formed.
4278      // FIXME: DPG thinks it is very fishy that C++0x disables this.
4279    } else {
4280      // Check for jumps past the implicit initializer.  C++0x
4281      // clarifies that this applies to a "variable with automatic
4282      // storage duration", not a "local variable".
4283      if (getLangOptions().CPlusPlus && Var->hasLocalStorage())
4284        setFunctionHasBranchProtectedScope();
4285
4286      InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
4287      InitializationKind Kind
4288        = InitializationKind::CreateDefault(Var->getLocation());
4289
4290      InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
4291      OwningExprResult Init = InitSeq.Perform(*this, Entity, Kind,
4292                                              MultiExprArg(*this, 0, 0));
4293      if (Init.isInvalid())
4294        Var->setInvalidDecl();
4295      else if (Init.get()) {
4296        Var->setInit(MaybeCreateCXXExprWithTemporaries(Init.takeAs<Expr>()));
4297
4298        if (getLangOptions().CPlusPlus && !Var->isInvalidDecl() &&
4299            Var->hasGlobalStorage() &&
4300            !Var->getDeclContext()->isDependentContext() &&
4301            !Var->getInit()->isConstantInitializer(Context, false))
4302          Diag(Var->getLocation(), diag::warn_global_constructor);
4303      }
4304    }
4305
4306    if (!Var->isInvalidDecl() && getLangOptions().CPlusPlus && Record)
4307      FinalizeVarWithDestructor(Var, Record);
4308  }
4309}
4310
4311Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
4312                                                   DeclPtrTy *Group,
4313                                                   unsigned NumDecls) {
4314  llvm::SmallVector<Decl*, 8> Decls;
4315
4316  if (DS.isTypeSpecOwned())
4317    Decls.push_back((Decl*)DS.getTypeRep());
4318
4319  for (unsigned i = 0; i != NumDecls; ++i)
4320    if (Decl *D = Group[i].getAs<Decl>())
4321      Decls.push_back(D);
4322
4323  return DeclGroupPtrTy::make(DeclGroupRef::Create(Context,
4324                                                   Decls.data(), Decls.size()));
4325}
4326
4327
4328/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
4329/// to introduce parameters into function prototype scope.
4330Sema::DeclPtrTy
4331Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
4332  const DeclSpec &DS = D.getDeclSpec();
4333
4334  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
4335  VarDecl::StorageClass StorageClass = VarDecl::None;
4336  VarDecl::StorageClass StorageClassAsWritten = VarDecl::None;
4337  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
4338    StorageClass = VarDecl::Register;
4339    StorageClassAsWritten = VarDecl::Register;
4340  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
4341    Diag(DS.getStorageClassSpecLoc(),
4342         diag::err_invalid_storage_class_in_func_decl);
4343    D.getMutableDeclSpec().ClearStorageClassSpecs();
4344  }
4345
4346  if (D.getDeclSpec().isThreadSpecified())
4347    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4348
4349  DiagnoseFunctionSpecifiers(D);
4350
4351  // Check that there are no default arguments inside the type of this
4352  // parameter (C++ only).
4353  if (getLangOptions().CPlusPlus)
4354    CheckExtraCXXDefaultArguments(D);
4355
4356  TagDecl *OwnedDecl = 0;
4357  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedDecl);
4358  QualType parmDeclType = TInfo->getType();
4359
4360  if (getLangOptions().CPlusPlus && OwnedDecl && OwnedDecl->isDefinition()) {
4361    // C++ [dcl.fct]p6:
4362    //   Types shall not be defined in return or parameter types.
4363    Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type)
4364      << Context.getTypeDeclType(OwnedDecl);
4365  }
4366
4367  // Check for redeclaration of parameters, e.g. int foo(int x, int x);
4368  IdentifierInfo *II = D.getIdentifier();
4369  if (II) {
4370    LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
4371                   ForRedeclaration);
4372    LookupName(R, S);
4373    if (R.isSingleResult()) {
4374      NamedDecl *PrevDecl = R.getFoundDecl();
4375      if (PrevDecl->isTemplateParameter()) {
4376        // Maybe we will complain about the shadowed template parameter.
4377        DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
4378        // Just pretend that we didn't see the previous declaration.
4379        PrevDecl = 0;
4380      } else if (S->isDeclScope(DeclPtrTy::make(PrevDecl))) {
4381        Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
4382        Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4383
4384        // Recover by removing the name
4385        II = 0;
4386        D.SetIdentifier(0, D.getIdentifierLoc());
4387        D.setInvalidType(true);
4388      }
4389    }
4390  }
4391
4392  // Temporarily put parameter variables in the translation unit, not
4393  // the enclosing context.  This prevents them from accidentally
4394  // looking like class members in C++.
4395  ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
4396                                    TInfo, parmDeclType, II,
4397                                    D.getIdentifierLoc(),
4398                                    StorageClass, StorageClassAsWritten);
4399
4400  if (D.isInvalidType())
4401    New->setInvalidDecl();
4402
4403  // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
4404  if (D.getCXXScopeSpec().isSet()) {
4405    Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
4406      << D.getCXXScopeSpec().getRange();
4407    New->setInvalidDecl();
4408  }
4409
4410  // Add the parameter declaration into this scope.
4411  S->AddDecl(DeclPtrTy::make(New));
4412  if (II)
4413    IdResolver.AddDecl(New);
4414
4415  ProcessDeclAttributes(S, New, D);
4416
4417  if (New->hasAttr<BlocksAttr>()) {
4418    Diag(New->getLocation(), diag::err_block_on_nonlocal);
4419  }
4420  return DeclPtrTy::make(New);
4421}
4422
4423/// \brief Synthesizes a variable for a parameter arising from a
4424/// typedef.
4425ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
4426                                              SourceLocation Loc,
4427                                              QualType T) {
4428  ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, 0,
4429                                T, Context.getTrivialTypeSourceInfo(T, Loc),
4430                                           VarDecl::None, VarDecl::None, 0);
4431  Param->setImplicit();
4432  return Param;
4433}
4434
4435ParmVarDecl *Sema::CheckParameter(DeclContext *DC,
4436                                  TypeSourceInfo *TSInfo, QualType T,
4437                                  IdentifierInfo *Name,
4438                                  SourceLocation NameLoc,
4439                                  VarDecl::StorageClass StorageClass,
4440                                  VarDecl::StorageClass StorageClassAsWritten) {
4441  ParmVarDecl *New = ParmVarDecl::Create(Context, DC, NameLoc, Name,
4442                                         adjustParameterType(T), TSInfo,
4443                                         StorageClass, StorageClassAsWritten,
4444                                         0);
4445
4446  // Parameters can not be abstract class types.
4447  // For record types, this is done by the AbstractClassUsageDiagnoser once
4448  // the class has been completely parsed.
4449  if (!CurContext->isRecord() &&
4450      RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
4451                             AbstractParamType))
4452    New->setInvalidDecl();
4453
4454  // Parameter declarators cannot be interface types. All ObjC objects are
4455  // passed by reference.
4456  if (T->isObjCObjectType()) {
4457    Diag(NameLoc,
4458         diag::err_object_cannot_be_passed_returned_by_value) << 1 << T;
4459    New->setInvalidDecl();
4460  }
4461
4462  // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
4463  // duration shall not be qualified by an address-space qualifier."
4464  // Since all parameters have automatic store duration, they can not have
4465  // an address space.
4466  if (T.getAddressSpace() != 0) {
4467    Diag(NameLoc, diag::err_arg_with_address_space);
4468    New->setInvalidDecl();
4469  }
4470
4471  return New;
4472}
4473
4474void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
4475                                           SourceLocation LocAfterDecls) {
4476  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4477         "Not a function declarator!");
4478  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
4479
4480  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
4481  // for a K&R function.
4482  if (!FTI.hasPrototype) {
4483    for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
4484      --i;
4485      if (FTI.ArgInfo[i].Param == 0) {
4486        llvm::SmallString<256> Code;
4487        llvm::raw_svector_ostream(Code) << "  int "
4488                                        << FTI.ArgInfo[i].Ident->getName()
4489                                        << ";\n";
4490        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
4491          << FTI.ArgInfo[i].Ident
4492          << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
4493
4494        // Implicitly declare the argument as type 'int' for lack of a better
4495        // type.
4496        DeclSpec DS;
4497        const char* PrevSpec; // unused
4498        unsigned DiagID; // unused
4499        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
4500                           PrevSpec, DiagID);
4501        Declarator ParamD(DS, Declarator::KNRTypeListContext);
4502        ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
4503        FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
4504      }
4505    }
4506  }
4507}
4508
4509Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
4510                                              Declarator &D) {
4511  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4512  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4513         "Not a function declarator!");
4514  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
4515
4516  if (FTI.hasPrototype) {
4517    // FIXME: Diagnose arguments without names in C.
4518  }
4519
4520  Scope *ParentScope = FnBodyScope->getParent();
4521
4522  DeclPtrTy DP = HandleDeclarator(ParentScope, D,
4523                                  MultiTemplateParamsArg(*this),
4524                                  /*IsFunctionDefinition=*/true);
4525  return ActOnStartOfFunctionDef(FnBodyScope, DP);
4526}
4527
4528static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
4529  // Don't warn about invalid declarations.
4530  if (FD->isInvalidDecl())
4531    return false;
4532
4533  // Or declarations that aren't global.
4534  if (!FD->isGlobal())
4535    return false;
4536
4537  // Don't warn about C++ member functions.
4538  if (isa<CXXMethodDecl>(FD))
4539    return false;
4540
4541  // Don't warn about 'main'.
4542  if (FD->isMain())
4543    return false;
4544
4545  // Don't warn about inline functions.
4546  if (FD->isInlineSpecified())
4547    return false;
4548
4549  // Don't warn about function templates.
4550  if (FD->getDescribedFunctionTemplate())
4551    return false;
4552
4553  // Don't warn about function template specializations.
4554  if (FD->isFunctionTemplateSpecialization())
4555    return false;
4556
4557  bool MissingPrototype = true;
4558  for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
4559       Prev; Prev = Prev->getPreviousDeclaration()) {
4560    // Ignore any declarations that occur in function or method
4561    // scope, because they aren't visible from the header.
4562    if (Prev->getDeclContext()->isFunctionOrMethod())
4563      continue;
4564
4565    MissingPrototype = !Prev->getType()->isFunctionProtoType();
4566    break;
4567  }
4568
4569  return MissingPrototype;
4570}
4571
4572Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclPtrTy D) {
4573  // Clear the last template instantiation error context.
4574  LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
4575
4576  if (!D)
4577    return D;
4578  FunctionDecl *FD = 0;
4579
4580  if (FunctionTemplateDecl *FunTmpl
4581        = dyn_cast<FunctionTemplateDecl>(D.getAs<Decl>()))
4582    FD = FunTmpl->getTemplatedDecl();
4583  else
4584    FD = cast<FunctionDecl>(D.getAs<Decl>());
4585
4586  // Enter a new function scope
4587  PushFunctionScope();
4588
4589  // See if this is a redefinition.
4590  // But don't complain if we're in GNU89 mode and the previous definition
4591  // was an extern inline function.
4592  const FunctionDecl *Definition;
4593  if (FD->hasBody(Definition) &&
4594      !canRedefineFunction(Definition, getLangOptions())) {
4595    Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
4596    Diag(Definition->getLocation(), diag::note_previous_definition);
4597  }
4598
4599  // Builtin functions cannot be defined.
4600  if (unsigned BuiltinID = FD->getBuiltinID()) {
4601    if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4602      Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
4603      FD->setInvalidDecl();
4604    }
4605  }
4606
4607  // The return type of a function definition must be complete
4608  // (C99 6.9.1p3, C++ [dcl.fct]p6).
4609  QualType ResultType = FD->getResultType();
4610  if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
4611      !FD->isInvalidDecl() &&
4612      RequireCompleteType(FD->getLocation(), ResultType,
4613                          diag::err_func_def_incomplete_result))
4614    FD->setInvalidDecl();
4615
4616  // GNU warning -Wmissing-prototypes:
4617  //   Warn if a global function is defined without a previous
4618  //   prototype declaration. This warning is issued even if the
4619  //   definition itself provides a prototype. The aim is to detect
4620  //   global functions that fail to be declared in header files.
4621  if (ShouldWarnAboutMissingPrototype(FD))
4622    Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
4623
4624  if (FnBodyScope)
4625    PushDeclContext(FnBodyScope, FD);
4626
4627  // Check the validity of our function parameters
4628  CheckParmsForFunctionDef(FD);
4629
4630  bool ShouldCheckShadow =
4631    Diags.getDiagnosticLevel(diag::warn_decl_shadow) != Diagnostic::Ignored;
4632
4633  // Introduce our parameters into the function scope
4634  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
4635    ParmVarDecl *Param = FD->getParamDecl(p);
4636    Param->setOwningFunction(FD);
4637
4638    // If this has an identifier, add it to the scope stack.
4639    if (Param->getIdentifier() && FnBodyScope) {
4640      if (ShouldCheckShadow)
4641        CheckShadow(FnBodyScope, Param);
4642
4643      PushOnScopeChains(Param, FnBodyScope);
4644    }
4645  }
4646
4647  // Checking attributes of current function definition
4648  // dllimport attribute.
4649  if (FD->getAttr<DLLImportAttr>() &&
4650      (!FD->getAttr<DLLExportAttr>())) {
4651    // dllimport attribute cannot be applied to definition.
4652    if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
4653      Diag(FD->getLocation(),
4654           diag::err_attribute_can_be_applied_only_to_symbol_declaration)
4655        << "dllimport";
4656      FD->setInvalidDecl();
4657      return DeclPtrTy::make(FD);
4658    }
4659
4660    // Visual C++ appears to not think this is an issue, so only issue
4661    // a warning when Microsoft extensions are disabled.
4662    if (!LangOpts.Microsoft) {
4663      // If a symbol previously declared dllimport is later defined, the
4664      // attribute is ignored in subsequent references, and a warning is
4665      // emitted.
4666      Diag(FD->getLocation(),
4667           diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
4668        << FD->getNameAsCString() << "dllimport";
4669    }
4670  }
4671  return DeclPtrTy::make(FD);
4672}
4673
4674/// \brief Given the set of return statements within a function body,
4675/// compute the variables that are subject to the named return value
4676/// optimization.
4677///
4678/// Each of the variables that is subject to the named return value
4679/// optimization will be marked as NRVO variables in the AST, and any
4680/// return statement that has a marked NRVO variable as its NRVO candidate can
4681/// use the named return value optimization.
4682///
4683/// This function applies a very simplistic algorithm for NRVO: if every return
4684/// statement in the function has the same NRVO candidate, that candidate is
4685/// the NRVO variable.
4686///
4687/// FIXME: Employ a smarter algorithm that accounts for multiple return
4688/// statements and the lifetimes of the NRVO candidates. We should be able to
4689/// find a maximal set of NRVO variables.
4690static void ComputeNRVO(Stmt *Body, ReturnStmt **Returns, unsigned NumReturns) {
4691  const VarDecl *NRVOCandidate = 0;
4692  for (unsigned I = 0; I != NumReturns; ++I) {
4693    if (!Returns[I]->getNRVOCandidate())
4694      return;
4695
4696    if (!NRVOCandidate)
4697      NRVOCandidate = Returns[I]->getNRVOCandidate();
4698    else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
4699      return;
4700  }
4701
4702  if (NRVOCandidate)
4703    const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
4704}
4705
4706Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg) {
4707  return ActOnFinishFunctionBody(D, move(BodyArg), false);
4708}
4709
4710Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg,
4711                                              bool IsInstantiation) {
4712  Decl *dcl = D.getAs<Decl>();
4713  Stmt *Body = BodyArg.takeAs<Stmt>();
4714
4715  FunctionDecl *FD = 0;
4716  FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
4717  if (FunTmpl)
4718    FD = FunTmpl->getTemplatedDecl();
4719  else
4720    FD = dyn_cast_or_null<FunctionDecl>(dcl);
4721
4722  sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
4723
4724  if (FD) {
4725    FD->setBody(Body);
4726    if (FD->isMain()) {
4727      // C and C++ allow for main to automagically return 0.
4728      // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
4729      FD->setHasImplicitReturnZero(true);
4730      WP.disableCheckFallThrough();
4731    }
4732
4733    if (!FD->isInvalidDecl()) {
4734      DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
4735
4736      // If this is a constructor, we need a vtable.
4737      if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
4738        MarkVTableUsed(FD->getLocation(), Constructor->getParent());
4739
4740      ComputeNRVO(Body, FunctionScopes.back()->Returns.data(),
4741                  FunctionScopes.back()->Returns.size());
4742    }
4743
4744    assert(FD == getCurFunctionDecl() && "Function parsing confused");
4745  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
4746    assert(MD == getCurMethodDecl() && "Method parsing confused");
4747    MD->setBody(Body);
4748    MD->setEndLoc(Body->getLocEnd());
4749    if (!MD->isInvalidDecl())
4750      DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
4751  } else {
4752    return DeclPtrTy();
4753  }
4754
4755  // Verify and clean out per-function state.
4756
4757  // Check goto/label use.
4758  for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
4759       I = getLabelMap().begin(), E = getLabelMap().end(); I != E; ++I) {
4760    LabelStmt *L = I->second;
4761
4762    // Verify that we have no forward references left.  If so, there was a goto
4763    // or address of a label taken, but no definition of it.  Label fwd
4764    // definitions are indicated with a null substmt.
4765    if (L->getSubStmt() != 0)
4766      continue;
4767
4768    // Emit error.
4769    Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
4770
4771    // At this point, we have gotos that use the bogus label.  Stitch it into
4772    // the function body so that they aren't leaked and that the AST is well
4773    // formed.
4774    if (Body == 0) {
4775      // The whole function wasn't parsed correctly.
4776      continue;
4777    }
4778
4779    // Otherwise, the body is valid: we want to stitch the label decl into the
4780    // function somewhere so that it is properly owned and so that the goto
4781    // has a valid target.  Do this by creating a new compound stmt with the
4782    // label in it.
4783
4784    // Give the label a sub-statement.
4785    L->setSubStmt(new (Context) NullStmt(L->getIdentLoc()));
4786
4787    CompoundStmt *Compound = isa<CXXTryStmt>(Body) ?
4788                               cast<CXXTryStmt>(Body)->getTryBlock() :
4789                               cast<CompoundStmt>(Body);
4790    llvm::SmallVector<Stmt*, 64> Elements(Compound->body_begin(),
4791                                          Compound->body_end());
4792    Elements.push_back(L);
4793    Compound->setStmts(Context, Elements.data(), Elements.size());
4794  }
4795
4796  if (Body) {
4797    // C++ constructors that have function-try-blocks can't have return
4798    // statements in the handlers of that block. (C++ [except.handle]p14)
4799    // Verify this.
4800    if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
4801      DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
4802
4803    // Verify that that gotos and switch cases don't jump into scopes illegally.
4804    // Verify that that gotos and switch cases don't jump into scopes illegally.
4805    if (FunctionNeedsScopeChecking() &&
4806        !dcl->isInvalidDecl() &&
4807        !hasAnyErrorsInThisFunction())
4808      DiagnoseInvalidJumps(Body);
4809
4810    if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
4811      if (!Destructor->getParent()->isDependentType())
4812        CheckDestructor(Destructor);
4813
4814      MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4815                                             Destructor->getParent());
4816    }
4817
4818    // If any errors have occurred, clear out any temporaries that may have
4819    // been leftover. This ensures that these temporaries won't be picked up for
4820    // deletion in some later function.
4821    if (PP.getDiagnostics().hasErrorOccurred())
4822      ExprTemporaries.clear();
4823    else if (!isa<FunctionTemplateDecl>(dcl)) {
4824      // Since the body is valid, issue any analysis-based warnings that are
4825      // enabled.
4826      QualType ResultType;
4827      if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
4828        ResultType = FD->getResultType();
4829      }
4830      else {
4831        ObjCMethodDecl *MD = cast<ObjCMethodDecl>(dcl);
4832        ResultType = MD->getResultType();
4833      }
4834      AnalysisWarnings.IssueWarnings(WP, dcl);
4835    }
4836
4837    assert(ExprTemporaries.empty() && "Leftover temporaries in function");
4838  }
4839
4840  if (!IsInstantiation)
4841    PopDeclContext();
4842
4843  PopFunctionOrBlockScope();
4844
4845  // If any errors have occurred, clear out any temporaries that may have
4846  // been leftover. This ensures that these temporaries won't be picked up for
4847  // deletion in some later function.
4848  if (getDiagnostics().hasErrorOccurred())
4849    ExprTemporaries.clear();
4850
4851  return D;
4852}
4853
4854/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4855/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
4856NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
4857                                          IdentifierInfo &II, Scope *S) {
4858  // Before we produce a declaration for an implicitly defined
4859  // function, see whether there was a locally-scoped declaration of
4860  // this name as a function or variable. If so, use that
4861  // (non-visible) declaration, and complain about it.
4862  llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4863    = LocallyScopedExternalDecls.find(&II);
4864  if (Pos != LocallyScopedExternalDecls.end()) {
4865    Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
4866    Diag(Pos->second->getLocation(), diag::note_previous_declaration);
4867    return Pos->second;
4868  }
4869
4870  // Extension in C99.  Legal in C90, but warn about it.
4871  if (II.getName().startswith("__builtin_"))
4872    Diag(Loc, diag::warn_builtin_unknown) << &II;
4873  else if (getLangOptions().C99)
4874    Diag(Loc, diag::ext_implicit_function_decl) << &II;
4875  else
4876    Diag(Loc, diag::warn_implicit_function_decl) << &II;
4877
4878  // Set a Declarator for the implicit definition: int foo();
4879  const char *Dummy;
4880  DeclSpec DS;
4881  unsigned DiagID;
4882  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
4883  Error = Error; // Silence warning.
4884  assert(!Error && "Error setting up implicit decl!");
4885  Declarator D(DS, Declarator::BlockContext);
4886  D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
4887                                             0, 0, false, SourceLocation(),
4888                                             false, 0,0,0, Loc, Loc, D),
4889                SourceLocation());
4890  D.SetIdentifier(&II, Loc);
4891
4892  // Insert this function into translation-unit scope.
4893
4894  DeclContext *PrevDC = CurContext;
4895  CurContext = Context.getTranslationUnitDecl();
4896
4897  FunctionDecl *FD =
4898 dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D).getAs<Decl>());
4899  FD->setImplicit();
4900
4901  CurContext = PrevDC;
4902
4903  AddKnownFunctionAttributes(FD);
4904
4905  return FD;
4906}
4907
4908/// \brief Adds any function attributes that we know a priori based on
4909/// the declaration of this function.
4910///
4911/// These attributes can apply both to implicitly-declared builtins
4912/// (like __builtin___printf_chk) or to library-declared functions
4913/// like NSLog or printf.
4914void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
4915  if (FD->isInvalidDecl())
4916    return;
4917
4918  // If this is a built-in function, map its builtin attributes to
4919  // actual attributes.
4920  if (unsigned BuiltinID = FD->getBuiltinID()) {
4921    // Handle printf-formatting attributes.
4922    unsigned FormatIdx;
4923    bool HasVAListArg;
4924    if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
4925      if (!FD->getAttr<FormatAttr>())
4926        FD->addAttr(::new (Context) FormatAttr(Context, "printf", FormatIdx+1,
4927                                               HasVAListArg ? 0 : FormatIdx+2));
4928    }
4929    if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
4930                                             HasVAListArg)) {
4931     if (!FD->getAttr<FormatAttr>())
4932       FD->addAttr(::new (Context) FormatAttr(Context, "scanf", FormatIdx+1,
4933                                              HasVAListArg ? 0 : FormatIdx+2));
4934    }
4935
4936    // Mark const if we don't care about errno and that is the only
4937    // thing preventing the function from being const. This allows
4938    // IRgen to use LLVM intrinsics for such functions.
4939    if (!getLangOptions().MathErrno &&
4940        Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
4941      if (!FD->getAttr<ConstAttr>())
4942        FD->addAttr(::new (Context) ConstAttr());
4943    }
4944
4945    if (Context.BuiltinInfo.isNoReturn(BuiltinID))
4946      FD->setType(Context.getNoReturnType(FD->getType()));
4947    if (Context.BuiltinInfo.isNoThrow(BuiltinID))
4948      FD->addAttr(::new (Context) NoThrowAttr());
4949    if (Context.BuiltinInfo.isConst(BuiltinID))
4950      FD->addAttr(::new (Context) ConstAttr());
4951  }
4952
4953  IdentifierInfo *Name = FD->getIdentifier();
4954  if (!Name)
4955    return;
4956  if ((!getLangOptions().CPlusPlus &&
4957       FD->getDeclContext()->isTranslationUnit()) ||
4958      (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
4959       cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
4960       LinkageSpecDecl::lang_c)) {
4961    // Okay: this could be a libc/libm/Objective-C function we know
4962    // about.
4963  } else
4964    return;
4965
4966  if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
4967    // FIXME: NSLog and NSLogv should be target specific
4968    if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
4969      // FIXME: We known better than our headers.
4970      const_cast<FormatAttr *>(Format)->setType(Context, "printf");
4971    } else
4972      FD->addAttr(::new (Context) FormatAttr(Context, "printf", 1,
4973                                             Name->isStr("NSLogv") ? 0 : 2));
4974  } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
4975    // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
4976    // target-specific builtins, perhaps?
4977    if (!FD->getAttr<FormatAttr>())
4978      FD->addAttr(::new (Context) FormatAttr(Context, "printf", 2,
4979                                             Name->isStr("vasprintf") ? 0 : 3));
4980  }
4981}
4982
4983TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
4984                                    TypeSourceInfo *TInfo) {
4985  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
4986  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
4987
4988  if (!TInfo) {
4989    assert(D.isInvalidType() && "no declarator info for valid type");
4990    TInfo = Context.getTrivialTypeSourceInfo(T);
4991  }
4992
4993  // Scope manipulation handled by caller.
4994  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
4995                                           D.getIdentifierLoc(),
4996                                           D.getIdentifier(),
4997                                           TInfo);
4998
4999  if (const TagType *TT = T->getAs<TagType>()) {
5000    TagDecl *TD = TT->getDecl();
5001
5002    // If the TagDecl that the TypedefDecl points to is an anonymous decl
5003    // keep track of the TypedefDecl.
5004    if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
5005      TD->setTypedefForAnonDecl(NewTD);
5006  }
5007
5008  if (D.isInvalidType())
5009    NewTD->setInvalidDecl();
5010  return NewTD;
5011}
5012
5013
5014/// \brief Determine whether a tag with a given kind is acceptable
5015/// as a redeclaration of the given tag declaration.
5016///
5017/// \returns true if the new tag kind is acceptable, false otherwise.
5018bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
5019                                        TagTypeKind NewTag,
5020                                        SourceLocation NewTagLoc,
5021                                        const IdentifierInfo &Name) {
5022  // C++ [dcl.type.elab]p3:
5023  //   The class-key or enum keyword present in the
5024  //   elaborated-type-specifier shall agree in kind with the
5025  //   declaration to which the name in the elaborated-type-specifier
5026  //   refers. This rule also applies to the form of
5027  //   elaborated-type-specifier that declares a class-name or
5028  //   friend class since it can be construed as referring to the
5029  //   definition of the class. Thus, in any
5030  //   elaborated-type-specifier, the enum keyword shall be used to
5031  //   refer to an enumeration (7.2), the union class-key shall be
5032  //   used to refer to a union (clause 9), and either the class or
5033  //   struct class-key shall be used to refer to a class (clause 9)
5034  //   declared using the class or struct class-key.
5035  TagTypeKind OldTag = Previous->getTagKind();
5036  if (OldTag == NewTag)
5037    return true;
5038
5039  if ((OldTag == TTK_Struct || OldTag == TTK_Class) &&
5040      (NewTag == TTK_Struct || NewTag == TTK_Class)) {
5041    // Warn about the struct/class tag mismatch.
5042    bool isTemplate = false;
5043    if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
5044      isTemplate = Record->getDescribedClassTemplate();
5045
5046    Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
5047      << (NewTag == TTK_Class)
5048      << isTemplate << &Name
5049      << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
5050                              OldTag == TTK_Class? "class" : "struct");
5051    Diag(Previous->getLocation(), diag::note_previous_use);
5052    return true;
5053  }
5054  return false;
5055}
5056
5057/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
5058/// former case, Name will be non-null.  In the later case, Name will be null.
5059/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
5060/// reference/declaration/definition of a tag.
5061Sema::DeclPtrTy Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5062                               SourceLocation KWLoc, CXXScopeSpec &SS,
5063                               IdentifierInfo *Name, SourceLocation NameLoc,
5064                               AttributeList *Attr, AccessSpecifier AS,
5065                               MultiTemplateParamsArg TemplateParameterLists,
5066                               bool &OwnedDecl, bool &IsDependent) {
5067  // If this is not a definition, it must have a name.
5068  assert((Name != 0 || TUK == TUK_Definition) &&
5069         "Nameless record must be a definition!");
5070
5071  OwnedDecl = false;
5072  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
5073
5074  // FIXME: Check explicit specializations more carefully.
5075  bool isExplicitSpecialization = false;
5076  unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
5077  bool Invalid = false;
5078  if (TUK != TUK_Reference) {
5079    if (TemplateParameterList *TemplateParams
5080          = MatchTemplateParametersToScopeSpecifier(KWLoc, SS,
5081                        (TemplateParameterList**)TemplateParameterLists.get(),
5082                                              TemplateParameterLists.size(),
5083                                                    TUK == TUK_Friend,
5084                                                    isExplicitSpecialization,
5085                                                    Invalid)) {
5086      // All but one template parameter lists have been matching.
5087      --NumMatchedTemplateParamLists;
5088
5089      if (TemplateParams->size() > 0) {
5090        // This is a declaration or definition of a class template (which may
5091        // be a member of another template).
5092        if (Invalid)
5093          return DeclPtrTy();
5094
5095        OwnedDecl = false;
5096        DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
5097                                               SS, Name, NameLoc, Attr,
5098                                               TemplateParams,
5099                                               AS);
5100        TemplateParameterLists.release();
5101        return Result.get();
5102      } else {
5103        // The "template<>" header is extraneous.
5104        Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
5105          << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
5106        isExplicitSpecialization = true;
5107      }
5108    }
5109  }
5110
5111  DeclContext *SearchDC = CurContext;
5112  DeclContext *DC = CurContext;
5113  bool isStdBadAlloc = false;
5114
5115  RedeclarationKind Redecl = ForRedeclaration;
5116  if (TUK == TUK_Friend || TUK == TUK_Reference)
5117    Redecl = NotForRedeclaration;
5118
5119  LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
5120
5121  if (Name && SS.isNotEmpty()) {
5122    // We have a nested-name tag ('struct foo::bar').
5123
5124    // Check for invalid 'foo::'.
5125    if (SS.isInvalid()) {
5126      Name = 0;
5127      goto CreateNewDecl;
5128    }
5129
5130    // If this is a friend or a reference to a class in a dependent
5131    // context, don't try to make a decl for it.
5132    if (TUK == TUK_Friend || TUK == TUK_Reference) {
5133      DC = computeDeclContext(SS, false);
5134      if (!DC) {
5135        IsDependent = true;
5136        return DeclPtrTy();
5137      }
5138    } else {
5139      DC = computeDeclContext(SS, true);
5140      if (!DC) {
5141        Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
5142          << SS.getRange();
5143        return DeclPtrTy();
5144      }
5145    }
5146
5147    if (RequireCompleteDeclContext(SS, DC))
5148      return DeclPtrTy::make((Decl *)0);
5149
5150    SearchDC = DC;
5151    // Look-up name inside 'foo::'.
5152    LookupQualifiedName(Previous, DC);
5153
5154    if (Previous.isAmbiguous())
5155      return DeclPtrTy();
5156
5157    if (Previous.empty()) {
5158      // Name lookup did not find anything. However, if the
5159      // nested-name-specifier refers to the current instantiation,
5160      // and that current instantiation has any dependent base
5161      // classes, we might find something at instantiation time: treat
5162      // this as a dependent elaborated-type-specifier.
5163      if (Previous.wasNotFoundInCurrentInstantiation()) {
5164        IsDependent = true;
5165        return DeclPtrTy();
5166      }
5167
5168      // A tag 'foo::bar' must already exist.
5169      Diag(NameLoc, diag::err_not_tag_in_scope)
5170        << Kind << Name << DC << SS.getRange();
5171      Name = 0;
5172      Invalid = true;
5173      goto CreateNewDecl;
5174    }
5175  } else if (Name) {
5176    // If this is a named struct, check to see if there was a previous forward
5177    // declaration or definition.
5178    // FIXME: We're looking into outer scopes here, even when we
5179    // shouldn't be. Doing so can result in ambiguities that we
5180    // shouldn't be diagnosing.
5181    LookupName(Previous, S);
5182
5183    // Note:  there used to be some attempt at recovery here.
5184    if (Previous.isAmbiguous())
5185      return DeclPtrTy();
5186
5187    if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
5188      // FIXME: This makes sure that we ignore the contexts associated
5189      // with C structs, unions, and enums when looking for a matching
5190      // tag declaration or definition. See the similar lookup tweak
5191      // in Sema::LookupName; is there a better way to deal with this?
5192      while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
5193        SearchDC = SearchDC->getParent();
5194    }
5195  }
5196
5197  if (Previous.isSingleResult() &&
5198      Previous.getFoundDecl()->isTemplateParameter()) {
5199    // Maybe we will complain about the shadowed template parameter.
5200    DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
5201    // Just pretend that we didn't see the previous declaration.
5202    Previous.clear();
5203  }
5204
5205  if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
5206      DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
5207    // This is a declaration of or a reference to "std::bad_alloc".
5208    isStdBadAlloc = true;
5209
5210    if (Previous.empty() && StdBadAlloc) {
5211      // std::bad_alloc has been implicitly declared (but made invisible to
5212      // name lookup). Fill in this implicit declaration as the previous
5213      // declaration, so that the declarations get chained appropriately.
5214      Previous.addDecl(getStdBadAlloc());
5215    }
5216  }
5217
5218  // If we didn't find a previous declaration, and this is a reference
5219  // (or friend reference), move to the correct scope.  In C++, we
5220  // also need to do a redeclaration lookup there, just in case
5221  // there's a shadow friend decl.
5222  if (Name && Previous.empty() &&
5223      (TUK == TUK_Reference || TUK == TUK_Friend)) {
5224    if (Invalid) goto CreateNewDecl;
5225    assert(SS.isEmpty());
5226
5227    if (TUK == TUK_Reference) {
5228      // C++ [basic.scope.pdecl]p5:
5229      //   -- for an elaborated-type-specifier of the form
5230      //
5231      //          class-key identifier
5232      //
5233      //      if the elaborated-type-specifier is used in the
5234      //      decl-specifier-seq or parameter-declaration-clause of a
5235      //      function defined in namespace scope, the identifier is
5236      //      declared as a class-name in the namespace that contains
5237      //      the declaration; otherwise, except as a friend
5238      //      declaration, the identifier is declared in the smallest
5239      //      non-class, non-function-prototype scope that contains the
5240      //      declaration.
5241      //
5242      // C99 6.7.2.3p8 has a similar (but not identical!) provision for
5243      // C structs and unions.
5244      //
5245      // It is an error in C++ to declare (rather than define) an enum
5246      // type, including via an elaborated type specifier.  We'll
5247      // diagnose that later; for now, declare the enum in the same
5248      // scope as we would have picked for any other tag type.
5249      //
5250      // GNU C also supports this behavior as part of its incomplete
5251      // enum types extension, while GNU C++ does not.
5252      //
5253      // Find the context where we'll be declaring the tag.
5254      // FIXME: We would like to maintain the current DeclContext as the
5255      // lexical context,
5256      while (SearchDC->isRecord())
5257        SearchDC = SearchDC->getParent();
5258
5259      // Find the scope where we'll be declaring the tag.
5260      while (S->isClassScope() ||
5261             (getLangOptions().CPlusPlus &&
5262              S->isFunctionPrototypeScope()) ||
5263             ((S->getFlags() & Scope::DeclScope) == 0) ||
5264             (S->getEntity() &&
5265              ((DeclContext *)S->getEntity())->isTransparentContext()))
5266        S = S->getParent();
5267    } else {
5268      assert(TUK == TUK_Friend);
5269      // C++ [namespace.memdef]p3:
5270      //   If a friend declaration in a non-local class first declares a
5271      //   class or function, the friend class or function is a member of
5272      //   the innermost enclosing namespace.
5273      SearchDC = SearchDC->getEnclosingNamespaceContext();
5274    }
5275
5276    // In C++, we need to do a redeclaration lookup to properly
5277    // diagnose some problems.
5278    if (getLangOptions().CPlusPlus) {
5279      Previous.setRedeclarationKind(ForRedeclaration);
5280      LookupQualifiedName(Previous, SearchDC);
5281    }
5282  }
5283
5284  if (!Previous.empty()) {
5285    NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
5286
5287    // It's okay to have a tag decl in the same scope as a typedef
5288    // which hides a tag decl in the same scope.  Finding this
5289    // insanity with a redeclaration lookup can only actually happen
5290    // in C++.
5291    //
5292    // This is also okay for elaborated-type-specifiers, which is
5293    // technically forbidden by the current standard but which is
5294    // okay according to the likely resolution of an open issue;
5295    // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
5296    if (getLangOptions().CPlusPlus) {
5297      if (TypedefDecl *TD = dyn_cast<TypedefDecl>(PrevDecl)) {
5298        if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
5299          TagDecl *Tag = TT->getDecl();
5300          if (Tag->getDeclName() == Name &&
5301              Tag->getDeclContext()->getLookupContext()
5302                          ->Equals(TD->getDeclContext()->getLookupContext())) {
5303            PrevDecl = Tag;
5304            Previous.clear();
5305            Previous.addDecl(Tag);
5306          }
5307        }
5308      }
5309    }
5310
5311    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
5312      // If this is a use of a previous tag, or if the tag is already declared
5313      // in the same scope (so that the definition/declaration completes or
5314      // rementions the tag), reuse the decl.
5315      if (TUK == TUK_Reference || TUK == TUK_Friend ||
5316          isDeclInScope(PrevDecl, SearchDC, S)) {
5317        // Make sure that this wasn't declared as an enum and now used as a
5318        // struct or something similar.
5319        if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, KWLoc, *Name)) {
5320          bool SafeToContinue
5321            = (PrevTagDecl->getTagKind() != TTK_Enum &&
5322               Kind != TTK_Enum);
5323          if (SafeToContinue)
5324            Diag(KWLoc, diag::err_use_with_wrong_tag)
5325              << Name
5326              << FixItHint::CreateReplacement(SourceRange(KWLoc),
5327                                              PrevTagDecl->getKindName());
5328          else
5329            Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
5330          Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
5331
5332          if (SafeToContinue)
5333            Kind = PrevTagDecl->getTagKind();
5334          else {
5335            // Recover by making this an anonymous redefinition.
5336            Name = 0;
5337            Previous.clear();
5338            Invalid = true;
5339          }
5340        }
5341
5342        if (!Invalid) {
5343          // If this is a use, just return the declaration we found.
5344
5345          // FIXME: In the future, return a variant or some other clue
5346          // for the consumer of this Decl to know it doesn't own it.
5347          // For our current ASTs this shouldn't be a problem, but will
5348          // need to be changed with DeclGroups.
5349          if ((TUK == TUK_Reference && !PrevTagDecl->getFriendObjectKind()) ||
5350              TUK == TUK_Friend)
5351            return DeclPtrTy::make(PrevTagDecl);
5352
5353          // Diagnose attempts to redefine a tag.
5354          if (TUK == TUK_Definition) {
5355            if (TagDecl *Def = PrevTagDecl->getDefinition()) {
5356              // If we're defining a specialization and the previous definition
5357              // is from an implicit instantiation, don't emit an error
5358              // here; we'll catch this in the general case below.
5359              if (!isExplicitSpecialization ||
5360                  !isa<CXXRecordDecl>(Def) ||
5361                  cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind()
5362                                               == TSK_ExplicitSpecialization) {
5363                Diag(NameLoc, diag::err_redefinition) << Name;
5364                Diag(Def->getLocation(), diag::note_previous_definition);
5365                // If this is a redefinition, recover by making this
5366                // struct be anonymous, which will make any later
5367                // references get the previous definition.
5368                Name = 0;
5369                Previous.clear();
5370                Invalid = true;
5371              }
5372            } else {
5373              // If the type is currently being defined, complain
5374              // about a nested redefinition.
5375              TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
5376              if (Tag->isBeingDefined()) {
5377                Diag(NameLoc, diag::err_nested_redefinition) << Name;
5378                Diag(PrevTagDecl->getLocation(),
5379                     diag::note_previous_definition);
5380                Name = 0;
5381                Previous.clear();
5382                Invalid = true;
5383              }
5384            }
5385
5386            // Okay, this is definition of a previously declared or referenced
5387            // tag PrevDecl. We're going to create a new Decl for it.
5388          }
5389        }
5390        // If we get here we have (another) forward declaration or we
5391        // have a definition.  Just create a new decl.
5392
5393      } else {
5394        // If we get here, this is a definition of a new tag type in a nested
5395        // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
5396        // new decl/type.  We set PrevDecl to NULL so that the entities
5397        // have distinct types.
5398        Previous.clear();
5399      }
5400      // If we get here, we're going to create a new Decl. If PrevDecl
5401      // is non-NULL, it's a definition of the tag declared by
5402      // PrevDecl. If it's NULL, we have a new definition.
5403
5404
5405    // Otherwise, PrevDecl is not a tag, but was found with tag
5406    // lookup.  This is only actually possible in C++, where a few
5407    // things like templates still live in the tag namespace.
5408    } else {
5409      assert(getLangOptions().CPlusPlus);
5410
5411      // Use a better diagnostic if an elaborated-type-specifier
5412      // found the wrong kind of type on the first
5413      // (non-redeclaration) lookup.
5414      if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
5415          !Previous.isForRedeclaration()) {
5416        unsigned Kind = 0;
5417        if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
5418        else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 2;
5419        Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
5420        Diag(PrevDecl->getLocation(), diag::note_declared_at);
5421        Invalid = true;
5422
5423      // Otherwise, only diagnose if the declaration is in scope.
5424      } else if (!isDeclInScope(PrevDecl, SearchDC, S)) {
5425        // do nothing
5426
5427      // Diagnose implicit declarations introduced by elaborated types.
5428      } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
5429        unsigned Kind = 0;
5430        if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
5431        else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 2;
5432        Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
5433        Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
5434        Invalid = true;
5435
5436      // Otherwise it's a declaration.  Call out a particularly common
5437      // case here.
5438      } else if (isa<TypedefDecl>(PrevDecl)) {
5439        Diag(NameLoc, diag::err_tag_definition_of_typedef)
5440          << Name
5441          << cast<TypedefDecl>(PrevDecl)->getUnderlyingType();
5442        Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
5443        Invalid = true;
5444
5445      // Otherwise, diagnose.
5446      } else {
5447        // The tag name clashes with something else in the target scope,
5448        // issue an error and recover by making this tag be anonymous.
5449        Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
5450        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5451        Name = 0;
5452        Invalid = true;
5453      }
5454
5455      // The existing declaration isn't relevant to us; we're in a
5456      // new scope, so clear out the previous declaration.
5457      Previous.clear();
5458    }
5459  }
5460
5461CreateNewDecl:
5462
5463  TagDecl *PrevDecl = 0;
5464  if (Previous.isSingleResult())
5465    PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
5466
5467  // If there is an identifier, use the location of the identifier as the
5468  // location of the decl, otherwise use the location of the struct/union
5469  // keyword.
5470  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
5471
5472  // Otherwise, create a new declaration. If there is a previous
5473  // declaration of the same entity, the two will be linked via
5474  // PrevDecl.
5475  TagDecl *New;
5476
5477  if (Kind == TTK_Enum) {
5478    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
5479    // enum X { A, B, C } D;    D should chain to X.
5480    New = EnumDecl::Create(Context, SearchDC, Loc, Name, KWLoc,
5481                           cast_or_null<EnumDecl>(PrevDecl));
5482    // If this is an undefined enum, warn.
5483    if (TUK != TUK_Definition && !Invalid) {
5484      TagDecl *Def;
5485      if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
5486        Diag(Loc, diag::ext_forward_ref_enum_def)
5487          << New;
5488        Diag(Def->getLocation(), diag::note_previous_definition);
5489      } else {
5490        Diag(Loc,
5491             getLangOptions().CPlusPlus? diag::err_forward_ref_enum
5492                                       : diag::ext_forward_ref_enum);
5493      }
5494    }
5495  } else {
5496    // struct/union/class
5497
5498    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
5499    // struct X { int A; } D;    D should chain to X.
5500    if (getLangOptions().CPlusPlus) {
5501      // FIXME: Look for a way to use RecordDecl for simple structs.
5502      New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
5503                                  cast_or_null<CXXRecordDecl>(PrevDecl));
5504
5505      if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
5506        StdBadAlloc = cast<CXXRecordDecl>(New);
5507    } else
5508      New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
5509                               cast_or_null<RecordDecl>(PrevDecl));
5510  }
5511
5512  // Maybe add qualifier info.
5513  if (SS.isNotEmpty()) {
5514    if (SS.isSet()) {
5515      NestedNameSpecifier *NNS
5516        = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5517      New->setQualifierInfo(NNS, SS.getRange());
5518      if (NumMatchedTemplateParamLists > 0) {
5519        New->setTemplateParameterListsInfo(Context,
5520                                           NumMatchedTemplateParamLists,
5521                    (TemplateParameterList**) TemplateParameterLists.release());
5522      }
5523    }
5524    else
5525      Invalid = true;
5526  }
5527
5528  if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
5529    // Add alignment attributes if necessary; these attributes are checked when
5530    // the ASTContext lays out the structure.
5531    //
5532    // It is important for implementing the correct semantics that this
5533    // happen here (in act on tag decl). The #pragma pack stack is
5534    // maintained as a result of parser callbacks which can occur at
5535    // many points during the parsing of a struct declaration (because
5536    // the #pragma tokens are effectively skipped over during the
5537    // parsing of the struct).
5538    AddAlignmentAttributesForRecord(RD);
5539  }
5540
5541  // If this is a specialization of a member class (of a class template),
5542  // check the specialization.
5543  if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
5544    Invalid = true;
5545
5546  if (Invalid)
5547    New->setInvalidDecl();
5548
5549  if (Attr)
5550    ProcessDeclAttributeList(S, New, Attr);
5551
5552  // If we're declaring or defining a tag in function prototype scope
5553  // in C, note that this type can only be used within the function.
5554  if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
5555    Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
5556
5557  // Set the lexical context. If the tag has a C++ scope specifier, the
5558  // lexical context will be different from the semantic context.
5559  New->setLexicalDeclContext(CurContext);
5560
5561  // Mark this as a friend decl if applicable.
5562  if (TUK == TUK_Friend)
5563    New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty());
5564
5565  // Set the access specifier.
5566  if (!Invalid && SearchDC->isRecord())
5567    SetMemberAccessSpecifier(New, PrevDecl, AS);
5568
5569  if (TUK == TUK_Definition)
5570    New->startDefinition();
5571
5572  // If this has an identifier, add it to the scope stack.
5573  if (TUK == TUK_Friend) {
5574    // We might be replacing an existing declaration in the lookup tables;
5575    // if so, borrow its access specifier.
5576    if (PrevDecl)
5577      New->setAccess(PrevDecl->getAccess());
5578
5579    DeclContext *DC = New->getDeclContext()->getLookupContext();
5580    DC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
5581    if (Name) // can be null along some error paths
5582      if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
5583        PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
5584  } else if (Name) {
5585    S = getNonFieldDeclScope(S);
5586    PushOnScopeChains(New, S);
5587  } else {
5588    CurContext->addDecl(New);
5589  }
5590
5591  // If this is the C FILE type, notify the AST context.
5592  if (IdentifierInfo *II = New->getIdentifier())
5593    if (!New->isInvalidDecl() &&
5594        New->getDeclContext()->getLookupContext()->isTranslationUnit() &&
5595        II->isStr("FILE"))
5596      Context.setFILEDecl(New);
5597
5598  OwnedDecl = true;
5599  return DeclPtrTy::make(New);
5600}
5601
5602void Sema::ActOnTagStartDefinition(Scope *S, DeclPtrTy TagD) {
5603  AdjustDeclIfTemplate(TagD);
5604  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
5605
5606  // Enter the tag context.
5607  PushDeclContext(S, Tag);
5608}
5609
5610void Sema::ActOnStartCXXMemberDeclarations(Scope *S, DeclPtrTy TagD,
5611                                           SourceLocation LBraceLoc) {
5612  AdjustDeclIfTemplate(TagD);
5613  CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD.getAs<Decl>());
5614
5615  FieldCollector->StartClass();
5616
5617  if (!Record->getIdentifier())
5618    return;
5619
5620  // C++ [class]p2:
5621  //   [...] The class-name is also inserted into the scope of the
5622  //   class itself; this is known as the injected-class-name. For
5623  //   purposes of access checking, the injected-class-name is treated
5624  //   as if it were a public member name.
5625  CXXRecordDecl *InjectedClassName
5626    = CXXRecordDecl::Create(Context, Record->getTagKind(),
5627                            CurContext, Record->getLocation(),
5628                            Record->getIdentifier(),
5629                            Record->getTagKeywordLoc(),
5630                            Record);
5631  InjectedClassName->setImplicit();
5632  InjectedClassName->setAccess(AS_public);
5633  if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
5634      InjectedClassName->setDescribedClassTemplate(Template);
5635  PushOnScopeChains(InjectedClassName, S);
5636  assert(InjectedClassName->isInjectedClassName() &&
5637         "Broken injected-class-name");
5638}
5639
5640void Sema::ActOnTagFinishDefinition(Scope *S, DeclPtrTy TagD,
5641                                    SourceLocation RBraceLoc) {
5642  AdjustDeclIfTemplate(TagD);
5643  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
5644  Tag->setRBraceLoc(RBraceLoc);
5645
5646  if (isa<CXXRecordDecl>(Tag))
5647    FieldCollector->FinishClass();
5648
5649  // Exit this scope of this tag's definition.
5650  PopDeclContext();
5651
5652  // Notify the consumer that we've defined a tag.
5653  Consumer.HandleTagDeclDefinition(Tag);
5654}
5655
5656void Sema::ActOnTagDefinitionError(Scope *S, DeclPtrTy TagD) {
5657  AdjustDeclIfTemplate(TagD);
5658  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
5659  Tag->setInvalidDecl();
5660
5661  // We're undoing ActOnTagStartDefinition here, not
5662  // ActOnStartCXXMemberDeclarations, so we don't have to mess with
5663  // the FieldCollector.
5664
5665  PopDeclContext();
5666}
5667
5668// Note that FieldName may be null for anonymous bitfields.
5669bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
5670                          QualType FieldTy, const Expr *BitWidth,
5671                          bool *ZeroWidth) {
5672  // Default to true; that shouldn't confuse checks for emptiness
5673  if (ZeroWidth)
5674    *ZeroWidth = true;
5675
5676  // C99 6.7.2.1p4 - verify the field type.
5677  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
5678  if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
5679    // Handle incomplete types with specific error.
5680    if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
5681      return true;
5682    if (FieldName)
5683      return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
5684        << FieldName << FieldTy << BitWidth->getSourceRange();
5685    return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
5686      << FieldTy << BitWidth->getSourceRange();
5687  }
5688
5689  // If the bit-width is type- or value-dependent, don't try to check
5690  // it now.
5691  if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
5692    return false;
5693
5694  llvm::APSInt Value;
5695  if (VerifyIntegerConstantExpression(BitWidth, &Value))
5696    return true;
5697
5698  if (Value != 0 && ZeroWidth)
5699    *ZeroWidth = false;
5700
5701  // Zero-width bitfield is ok for anonymous field.
5702  if (Value == 0 && FieldName)
5703    return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
5704
5705  if (Value.isSigned() && Value.isNegative()) {
5706    if (FieldName)
5707      return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
5708               << FieldName << Value.toString(10);
5709    return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
5710      << Value.toString(10);
5711  }
5712
5713  if (!FieldTy->isDependentType()) {
5714    uint64_t TypeSize = Context.getTypeSize(FieldTy);
5715    if (Value.getZExtValue() > TypeSize) {
5716      if (!getLangOptions().CPlusPlus) {
5717        if (FieldName)
5718          return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
5719            << FieldName << (unsigned)Value.getZExtValue()
5720            << (unsigned)TypeSize;
5721
5722        return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
5723          << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
5724      }
5725
5726      if (FieldName)
5727        Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
5728          << FieldName << (unsigned)Value.getZExtValue()
5729          << (unsigned)TypeSize;
5730      else
5731        Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
5732          << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
5733    }
5734  }
5735
5736  return false;
5737}
5738
5739/// ActOnField - Each field of a struct/union/class is passed into this in order
5740/// to create a FieldDecl object for it.
5741Sema::DeclPtrTy Sema::ActOnField(Scope *S, DeclPtrTy TagD,
5742                                 SourceLocation DeclStart,
5743                                 Declarator &D, ExprTy *BitfieldWidth) {
5744  FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD.getAs<Decl>()),
5745                               DeclStart, D, static_cast<Expr*>(BitfieldWidth),
5746                               AS_public);
5747  return DeclPtrTy::make(Res);
5748}
5749
5750/// HandleField - Analyze a field of a C struct or a C++ data member.
5751///
5752FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
5753                             SourceLocation DeclStart,
5754                             Declarator &D, Expr *BitWidth,
5755                             AccessSpecifier AS) {
5756  IdentifierInfo *II = D.getIdentifier();
5757  SourceLocation Loc = DeclStart;
5758  if (II) Loc = D.getIdentifierLoc();
5759
5760  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5761  QualType T = TInfo->getType();
5762  if (getLangOptions().CPlusPlus)
5763    CheckExtraCXXDefaultArguments(D);
5764
5765  DiagnoseFunctionSpecifiers(D);
5766
5767  if (D.getDeclSpec().isThreadSpecified())
5768    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
5769
5770  NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
5771                                         ForRedeclaration);
5772
5773  if (PrevDecl && PrevDecl->isTemplateParameter()) {
5774    // Maybe we will complain about the shadowed template parameter.
5775    DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5776    // Just pretend that we didn't see the previous declaration.
5777    PrevDecl = 0;
5778  }
5779
5780  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
5781    PrevDecl = 0;
5782
5783  bool Mutable
5784    = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
5785  SourceLocation TSSL = D.getSourceRange().getBegin();
5786  FieldDecl *NewFD
5787    = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, TSSL,
5788                     AS, PrevDecl, &D);
5789
5790  if (NewFD->isInvalidDecl())
5791    Record->setInvalidDecl();
5792
5793  if (NewFD->isInvalidDecl() && PrevDecl) {
5794    // Don't introduce NewFD into scope; there's already something
5795    // with the same name in the same scope.
5796  } else if (II) {
5797    PushOnScopeChains(NewFD, S);
5798  } else
5799    Record->addDecl(NewFD);
5800
5801  return NewFD;
5802}
5803
5804/// \brief Build a new FieldDecl and check its well-formedness.
5805///
5806/// This routine builds a new FieldDecl given the fields name, type,
5807/// record, etc. \p PrevDecl should refer to any previous declaration
5808/// with the same name and in the same scope as the field to be
5809/// created.
5810///
5811/// \returns a new FieldDecl.
5812///
5813/// \todo The Declarator argument is a hack. It will be removed once
5814FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
5815                                TypeSourceInfo *TInfo,
5816                                RecordDecl *Record, SourceLocation Loc,
5817                                bool Mutable, Expr *BitWidth,
5818                                SourceLocation TSSL,
5819                                AccessSpecifier AS, NamedDecl *PrevDecl,
5820                                Declarator *D) {
5821  IdentifierInfo *II = Name.getAsIdentifierInfo();
5822  bool InvalidDecl = false;
5823  if (D) InvalidDecl = D->isInvalidType();
5824
5825  // If we receive a broken type, recover by assuming 'int' and
5826  // marking this declaration as invalid.
5827  if (T.isNull()) {
5828    InvalidDecl = true;
5829    T = Context.IntTy;
5830  }
5831
5832  QualType EltTy = Context.getBaseElementType(T);
5833  if (!EltTy->isDependentType() &&
5834      RequireCompleteType(Loc, EltTy, diag::err_field_incomplete))
5835    InvalidDecl = true;
5836
5837  // C99 6.7.2.1p8: A member of a structure or union may have any type other
5838  // than a variably modified type.
5839  if (!InvalidDecl && T->isVariablyModifiedType()) {
5840    bool SizeIsNegative;
5841    QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
5842                                                           SizeIsNegative);
5843    if (!FixedTy.isNull()) {
5844      Diag(Loc, diag::warn_illegal_constant_array_size);
5845      T = FixedTy;
5846    } else {
5847      if (SizeIsNegative)
5848        Diag(Loc, diag::err_typecheck_negative_array_size);
5849      else
5850        Diag(Loc, diag::err_typecheck_field_variable_size);
5851      InvalidDecl = true;
5852    }
5853  }
5854
5855  // Fields can not have abstract class types
5856  if (!InvalidDecl && RequireNonAbstractType(Loc, T,
5857                                             diag::err_abstract_type_in_decl,
5858                                             AbstractFieldType))
5859    InvalidDecl = true;
5860
5861  bool ZeroWidth = false;
5862  // If this is declared as a bit-field, check the bit-field.
5863  if (!InvalidDecl && BitWidth &&
5864      VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) {
5865    InvalidDecl = true;
5866    DeleteExpr(BitWidth);
5867    BitWidth = 0;
5868    ZeroWidth = false;
5869  }
5870
5871  // Check that 'mutable' is consistent with the type of the declaration.
5872  if (!InvalidDecl && Mutable) {
5873    unsigned DiagID = 0;
5874    if (T->isReferenceType())
5875      DiagID = diag::err_mutable_reference;
5876    else if (T.isConstQualified())
5877      DiagID = diag::err_mutable_const;
5878
5879    if (DiagID) {
5880      SourceLocation ErrLoc = Loc;
5881      if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
5882        ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
5883      Diag(ErrLoc, DiagID);
5884      Mutable = false;
5885      InvalidDecl = true;
5886    }
5887  }
5888
5889  FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, TInfo,
5890                                       BitWidth, Mutable);
5891  if (InvalidDecl)
5892    NewFD->setInvalidDecl();
5893
5894  if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
5895    Diag(Loc, diag::err_duplicate_member) << II;
5896    Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5897    NewFD->setInvalidDecl();
5898  }
5899
5900  if (!InvalidDecl && getLangOptions().CPlusPlus) {
5901    CXXRecordDecl* CXXRecord = cast<CXXRecordDecl>(Record);
5902
5903    if (!T->isPODType())
5904      CXXRecord->setPOD(false);
5905    if (!ZeroWidth)
5906      CXXRecord->setEmpty(false);
5907
5908    if (const RecordType *RT = EltTy->getAs<RecordType>()) {
5909      CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
5910      if (RDecl->getDefinition()) {
5911        if (!RDecl->hasTrivialConstructor())
5912          CXXRecord->setHasTrivialConstructor(false);
5913        if (!RDecl->hasTrivialCopyConstructor())
5914          CXXRecord->setHasTrivialCopyConstructor(false);
5915        if (!RDecl->hasTrivialCopyAssignment())
5916          CXXRecord->setHasTrivialCopyAssignment(false);
5917        if (!RDecl->hasTrivialDestructor())
5918          CXXRecord->setHasTrivialDestructor(false);
5919
5920        // C++ 9.5p1: An object of a class with a non-trivial
5921        // constructor, a non-trivial copy constructor, a non-trivial
5922        // destructor, or a non-trivial copy assignment operator
5923        // cannot be a member of a union, nor can an array of such
5924        // objects.
5925        // TODO: C++0x alters this restriction significantly.
5926        if (Record->isUnion()) {
5927          // We check for copy constructors before constructors
5928          // because otherwise we'll never get complaints about
5929          // copy constructors.
5930
5931          CXXSpecialMember member = CXXInvalid;
5932          if (!RDecl->hasTrivialCopyConstructor())
5933            member = CXXCopyConstructor;
5934          else if (!RDecl->hasTrivialConstructor())
5935            member = CXXConstructor;
5936          else if (!RDecl->hasTrivialCopyAssignment())
5937            member = CXXCopyAssignment;
5938          else if (!RDecl->hasTrivialDestructor())
5939            member = CXXDestructor;
5940
5941          if (member != CXXInvalid) {
5942            Diag(Loc, diag::err_illegal_union_member) << Name << member;
5943            DiagnoseNontrivial(RT, member);
5944            NewFD->setInvalidDecl();
5945          }
5946        }
5947      }
5948    }
5949  }
5950
5951  // FIXME: We need to pass in the attributes given an AST
5952  // representation, not a parser representation.
5953  if (D)
5954    // FIXME: What to pass instead of TUScope?
5955    ProcessDeclAttributes(TUScope, NewFD, *D);
5956
5957  if (T.isObjCGCWeak())
5958    Diag(Loc, diag::warn_attribute_weak_on_field);
5959
5960  NewFD->setAccess(AS);
5961
5962  // C++ [dcl.init.aggr]p1:
5963  //   An aggregate is an array or a class (clause 9) with [...] no
5964  //   private or protected non-static data members (clause 11).
5965  // A POD must be an aggregate.
5966  if (getLangOptions().CPlusPlus &&
5967      (AS == AS_private || AS == AS_protected)) {
5968    CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
5969    CXXRecord->setAggregate(false);
5970    CXXRecord->setPOD(false);
5971  }
5972
5973  return NewFD;
5974}
5975
5976/// DiagnoseNontrivial - Given that a class has a non-trivial
5977/// special member, figure out why.
5978void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
5979  QualType QT(T, 0U);
5980  CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
5981
5982  // Check whether the member was user-declared.
5983  switch (member) {
5984  case CXXInvalid:
5985    break;
5986
5987  case CXXConstructor:
5988    if (RD->hasUserDeclaredConstructor()) {
5989      typedef CXXRecordDecl::ctor_iterator ctor_iter;
5990      for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){
5991        const FunctionDecl *body = 0;
5992        ci->hasBody(body);
5993        if (!body || !cast<CXXConstructorDecl>(body)->isImplicitlyDefined()) {
5994          SourceLocation CtorLoc = ci->getLocation();
5995          Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5996          return;
5997        }
5998      }
5999
6000      assert(0 && "found no user-declared constructors");
6001      return;
6002    }
6003    break;
6004
6005  case CXXCopyConstructor:
6006    if (RD->hasUserDeclaredCopyConstructor()) {
6007      SourceLocation CtorLoc =
6008        RD->getCopyConstructor(Context, 0)->getLocation();
6009      Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
6010      return;
6011    }
6012    break;
6013
6014  case CXXCopyAssignment:
6015    if (RD->hasUserDeclaredCopyAssignment()) {
6016      // FIXME: this should use the location of the copy
6017      // assignment, not the type.
6018      SourceLocation TyLoc = RD->getSourceRange().getBegin();
6019      Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
6020      return;
6021    }
6022    break;
6023
6024  case CXXDestructor:
6025    if (RD->hasUserDeclaredDestructor()) {
6026      SourceLocation DtorLoc = LookupDestructor(RD)->getLocation();
6027      Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
6028      return;
6029    }
6030    break;
6031  }
6032
6033  typedef CXXRecordDecl::base_class_iterator base_iter;
6034
6035  // Virtual bases and members inhibit trivial copying/construction,
6036  // but not trivial destruction.
6037  if (member != CXXDestructor) {
6038    // Check for virtual bases.  vbases includes indirect virtual bases,
6039    // so we just iterate through the direct bases.
6040    for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
6041      if (bi->isVirtual()) {
6042        SourceLocation BaseLoc = bi->getSourceRange().getBegin();
6043        Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
6044        return;
6045      }
6046
6047    // Check for virtual methods.
6048    typedef CXXRecordDecl::method_iterator meth_iter;
6049    for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
6050         ++mi) {
6051      if (mi->isVirtual()) {
6052        SourceLocation MLoc = mi->getSourceRange().getBegin();
6053        Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
6054        return;
6055      }
6056    }
6057  }
6058
6059  bool (CXXRecordDecl::*hasTrivial)() const;
6060  switch (member) {
6061  case CXXConstructor:
6062    hasTrivial = &CXXRecordDecl::hasTrivialConstructor; break;
6063  case CXXCopyConstructor:
6064    hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
6065  case CXXCopyAssignment:
6066    hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
6067  case CXXDestructor:
6068    hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
6069  default:
6070    assert(0 && "unexpected special member"); return;
6071  }
6072
6073  // Check for nontrivial bases (and recurse).
6074  for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
6075    const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
6076    assert(BaseRT && "Don't know how to handle dependent bases");
6077    CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
6078    if (!(BaseRecTy->*hasTrivial)()) {
6079      SourceLocation BaseLoc = bi->getSourceRange().getBegin();
6080      Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
6081      DiagnoseNontrivial(BaseRT, member);
6082      return;
6083    }
6084  }
6085
6086  // Check for nontrivial members (and recurse).
6087  typedef RecordDecl::field_iterator field_iter;
6088  for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
6089       ++fi) {
6090    QualType EltTy = Context.getBaseElementType((*fi)->getType());
6091    if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
6092      CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
6093
6094      if (!(EltRD->*hasTrivial)()) {
6095        SourceLocation FLoc = (*fi)->getLocation();
6096        Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
6097        DiagnoseNontrivial(EltRT, member);
6098        return;
6099      }
6100    }
6101  }
6102
6103  assert(0 && "found no explanation for non-trivial member");
6104}
6105
6106/// TranslateIvarVisibility - Translate visibility from a token ID to an
6107///  AST enum value.
6108static ObjCIvarDecl::AccessControl
6109TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
6110  switch (ivarVisibility) {
6111  default: assert(0 && "Unknown visitibility kind");
6112  case tok::objc_private: return ObjCIvarDecl::Private;
6113  case tok::objc_public: return ObjCIvarDecl::Public;
6114  case tok::objc_protected: return ObjCIvarDecl::Protected;
6115  case tok::objc_package: return ObjCIvarDecl::Package;
6116  }
6117}
6118
6119/// ActOnIvar - Each ivar field of an objective-c class is passed into this
6120/// in order to create an IvarDecl object for it.
6121Sema::DeclPtrTy Sema::ActOnIvar(Scope *S,
6122                                SourceLocation DeclStart,
6123                                DeclPtrTy IntfDecl,
6124                                Declarator &D, ExprTy *BitfieldWidth,
6125                                tok::ObjCKeywordKind Visibility) {
6126
6127  IdentifierInfo *II = D.getIdentifier();
6128  Expr *BitWidth = (Expr*)BitfieldWidth;
6129  SourceLocation Loc = DeclStart;
6130  if (II) Loc = D.getIdentifierLoc();
6131
6132  // FIXME: Unnamed fields can be handled in various different ways, for
6133  // example, unnamed unions inject all members into the struct namespace!
6134
6135  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6136  QualType T = TInfo->getType();
6137
6138  if (BitWidth) {
6139    // 6.7.2.1p3, 6.7.2.1p4
6140    if (VerifyBitField(Loc, II, T, BitWidth)) {
6141      D.setInvalidType();
6142      DeleteExpr(BitWidth);
6143      BitWidth = 0;
6144    }
6145  } else {
6146    // Not a bitfield.
6147
6148    // validate II.
6149
6150  }
6151  if (T->isReferenceType()) {
6152    Diag(Loc, diag::err_ivar_reference_type);
6153    D.setInvalidType();
6154  }
6155  // C99 6.7.2.1p8: A member of a structure or union may have any type other
6156  // than a variably modified type.
6157  else if (T->isVariablyModifiedType()) {
6158    Diag(Loc, diag::err_typecheck_ivar_variable_size);
6159    D.setInvalidType();
6160  }
6161
6162  // Get the visibility (access control) for this ivar.
6163  ObjCIvarDecl::AccessControl ac =
6164    Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
6165                                        : ObjCIvarDecl::None;
6166  // Must set ivar's DeclContext to its enclosing interface.
6167  ObjCContainerDecl *EnclosingDecl = IntfDecl.getAs<ObjCContainerDecl>();
6168  ObjCContainerDecl *EnclosingContext;
6169  if (ObjCImplementationDecl *IMPDecl =
6170      dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
6171    // Case of ivar declared in an implementation. Context is that of its class.
6172    EnclosingContext = IMPDecl->getClassInterface();
6173    assert(EnclosingContext && "Implementation has no class interface!");
6174  } else {
6175    if (ObjCCategoryDecl *CDecl =
6176        dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
6177      if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) {
6178        Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
6179        return DeclPtrTy();
6180      }
6181    }
6182    EnclosingContext = EnclosingDecl;
6183  }
6184
6185  // Construct the decl.
6186  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context,
6187                                             EnclosingContext, Loc, II, T,
6188                                             TInfo, ac, (Expr *)BitfieldWidth);
6189
6190  if (II) {
6191    NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
6192                                           ForRedeclaration);
6193    if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
6194        && !isa<TagDecl>(PrevDecl)) {
6195      Diag(Loc, diag::err_duplicate_member) << II;
6196      Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
6197      NewID->setInvalidDecl();
6198    }
6199  }
6200
6201  // Process attributes attached to the ivar.
6202  ProcessDeclAttributes(S, NewID, D);
6203
6204  if (D.isInvalidType())
6205    NewID->setInvalidDecl();
6206
6207  if (II) {
6208    // FIXME: When interfaces are DeclContexts, we'll need to add
6209    // these to the interface.
6210    S->AddDecl(DeclPtrTy::make(NewID));
6211    IdResolver.AddDecl(NewID);
6212  }
6213
6214  return DeclPtrTy::make(NewID);
6215}
6216
6217void Sema::ActOnFields(Scope* S,
6218                       SourceLocation RecLoc, DeclPtrTy RecDecl,
6219                       DeclPtrTy *Fields, unsigned NumFields,
6220                       SourceLocation LBrac, SourceLocation RBrac,
6221                       AttributeList *Attr) {
6222  Decl *EnclosingDecl = RecDecl.getAs<Decl>();
6223  assert(EnclosingDecl && "missing record or interface decl");
6224
6225  // If the decl this is being inserted into is invalid, then it may be a
6226  // redeclaration or some other bogus case.  Don't try to add fields to it.
6227  if (EnclosingDecl->isInvalidDecl()) {
6228    // FIXME: Deallocate fields?
6229    return;
6230  }
6231
6232
6233  // Verify that all the fields are okay.
6234  unsigned NumNamedMembers = 0;
6235  llvm::SmallVector<FieldDecl*, 32> RecFields;
6236
6237  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
6238  for (unsigned i = 0; i != NumFields; ++i) {
6239    FieldDecl *FD = cast<FieldDecl>(Fields[i].getAs<Decl>());
6240
6241    // Get the type for the field.
6242    Type *FDTy = FD->getType().getTypePtr();
6243
6244    if (!FD->isAnonymousStructOrUnion()) {
6245      // Remember all fields written by the user.
6246      RecFields.push_back(FD);
6247    }
6248
6249    // If the field is already invalid for some reason, don't emit more
6250    // diagnostics about it.
6251    if (FD->isInvalidDecl()) {
6252      EnclosingDecl->setInvalidDecl();
6253      continue;
6254    }
6255
6256    // C99 6.7.2.1p2:
6257    //   A structure or union shall not contain a member with
6258    //   incomplete or function type (hence, a structure shall not
6259    //   contain an instance of itself, but may contain a pointer to
6260    //   an instance of itself), except that the last member of a
6261    //   structure with more than one named member may have incomplete
6262    //   array type; such a structure (and any union containing,
6263    //   possibly recursively, a member that is such a structure)
6264    //   shall not be a member of a structure or an element of an
6265    //   array.
6266    if (FDTy->isFunctionType()) {
6267      // Field declared as a function.
6268      Diag(FD->getLocation(), diag::err_field_declared_as_function)
6269        << FD->getDeclName();
6270      FD->setInvalidDecl();
6271      EnclosingDecl->setInvalidDecl();
6272      continue;
6273    } else if (FDTy->isIncompleteArrayType() && i == NumFields - 1 &&
6274               Record && Record->isStruct()) {
6275      // Flexible array member.
6276      if (NumNamedMembers < 1) {
6277        Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
6278          << FD->getDeclName();
6279        FD->setInvalidDecl();
6280        EnclosingDecl->setInvalidDecl();
6281        continue;
6282      }
6283      if (!FD->getType()->isDependentType() &&
6284          !Context.getBaseElementType(FD->getType())->isPODType()) {
6285        Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
6286          << FD->getDeclName() << FD->getType();
6287        FD->setInvalidDecl();
6288        EnclosingDecl->setInvalidDecl();
6289        continue;
6290      }
6291
6292      // Okay, we have a legal flexible array member at the end of the struct.
6293      if (Record)
6294        Record->setHasFlexibleArrayMember(true);
6295    } else if (!FDTy->isDependentType() &&
6296               RequireCompleteType(FD->getLocation(), FD->getType(),
6297                                   diag::err_field_incomplete)) {
6298      // Incomplete type
6299      FD->setInvalidDecl();
6300      EnclosingDecl->setInvalidDecl();
6301      continue;
6302    } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
6303      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
6304        // If this is a member of a union, then entire union becomes "flexible".
6305        if (Record && Record->isUnion()) {
6306          Record->setHasFlexibleArrayMember(true);
6307        } else {
6308          // If this is a struct/class and this is not the last element, reject
6309          // it.  Note that GCC supports variable sized arrays in the middle of
6310          // structures.
6311          if (i != NumFields-1)
6312            Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
6313              << FD->getDeclName() << FD->getType();
6314          else {
6315            // We support flexible arrays at the end of structs in
6316            // other structs as an extension.
6317            Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
6318              << FD->getDeclName();
6319            if (Record)
6320              Record->setHasFlexibleArrayMember(true);
6321          }
6322        }
6323      }
6324      if (Record && FDTTy->getDecl()->hasObjectMember())
6325        Record->setHasObjectMember(true);
6326    } else if (FDTy->isObjCObjectType()) {
6327      /// A field cannot be an Objective-c object
6328      Diag(FD->getLocation(), diag::err_statically_allocated_object);
6329      FD->setInvalidDecl();
6330      EnclosingDecl->setInvalidDecl();
6331      continue;
6332    } else if (getLangOptions().ObjC1 &&
6333               getLangOptions().getGCMode() != LangOptions::NonGC &&
6334               Record &&
6335               (FD->getType()->isObjCObjectPointerType() ||
6336                FD->getType().isObjCGCStrong()))
6337      Record->setHasObjectMember(true);
6338    else if (Context.getAsArrayType(FD->getType())) {
6339      QualType BaseType = Context.getBaseElementType(FD->getType());
6340      if (Record && BaseType->isRecordType() &&
6341          BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
6342        Record->setHasObjectMember(true);
6343    }
6344    // Keep track of the number of named members.
6345    if (FD->getIdentifier())
6346      ++NumNamedMembers;
6347  }
6348
6349  // Okay, we successfully defined 'Record'.
6350  if (Record) {
6351    Record->completeDefinition();
6352  } else {
6353    ObjCIvarDecl **ClsFields =
6354      reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
6355    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
6356      ID->setLocEnd(RBrac);
6357      // Add ivar's to class's DeclContext.
6358      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
6359        ClsFields[i]->setLexicalDeclContext(ID);
6360        ID->addDecl(ClsFields[i]);
6361      }
6362      // Must enforce the rule that ivars in the base classes may not be
6363      // duplicates.
6364      if (ID->getSuperClass())
6365        DiagnoseDuplicateIvars(ID, ID->getSuperClass());
6366    } else if (ObjCImplementationDecl *IMPDecl =
6367                  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
6368      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
6369      for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
6370        // Ivar declared in @implementation never belongs to the implementation.
6371        // Only it is in implementation's lexical context.
6372        ClsFields[I]->setLexicalDeclContext(IMPDecl);
6373      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
6374    } else if (ObjCCategoryDecl *CDecl =
6375                dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
6376      // case of ivars in class extension; all other cases have been
6377      // reported as errors elsewhere.
6378      // FIXME. Class extension does not have a LocEnd field.
6379      // CDecl->setLocEnd(RBrac);
6380      // Add ivar's to class extension's DeclContext.
6381      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
6382        ClsFields[i]->setLexicalDeclContext(CDecl);
6383        CDecl->addDecl(ClsFields[i]);
6384      }
6385    }
6386  }
6387
6388  if (Attr)
6389    ProcessDeclAttributeList(S, Record, Attr);
6390
6391  // If there's a #pragma GCC visibility in scope, and this isn't a subclass,
6392  // set the visibility of this record.
6393  if (Record && !Record->getDeclContext()->isRecord())
6394    AddPushedVisibilityAttribute(Record);
6395}
6396
6397/// \brief Determine whether the given integral value is representable within
6398/// the given type T.
6399static bool isRepresentableIntegerValue(ASTContext &Context,
6400                                        llvm::APSInt &Value,
6401                                        QualType T) {
6402  assert(T->isIntegralType(Context) && "Integral type required!");
6403  unsigned BitWidth = Context.getIntWidth(T);
6404
6405  if (Value.isUnsigned() || Value.isNonNegative())
6406    return Value.getActiveBits() < BitWidth;
6407
6408  return Value.getMinSignedBits() <= BitWidth;
6409}
6410
6411// \brief Given an integral type, return the next larger integral type
6412// (or a NULL type of no such type exists).
6413static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
6414  // FIXME: Int128/UInt128 support, which also needs to be introduced into
6415  // enum checking below.
6416  assert(T->isIntegralType(Context) && "Integral type required!");
6417  const unsigned NumTypes = 4;
6418  QualType SignedIntegralTypes[NumTypes] = {
6419    Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
6420  };
6421  QualType UnsignedIntegralTypes[NumTypes] = {
6422    Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
6423    Context.UnsignedLongLongTy
6424  };
6425
6426  unsigned BitWidth = Context.getTypeSize(T);
6427  QualType *Types = T->isSignedIntegerType()? SignedIntegralTypes
6428                                            : UnsignedIntegralTypes;
6429  for (unsigned I = 0; I != NumTypes; ++I)
6430    if (Context.getTypeSize(Types[I]) > BitWidth)
6431      return Types[I];
6432
6433  return QualType();
6434}
6435
6436EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
6437                                          EnumConstantDecl *LastEnumConst,
6438                                          SourceLocation IdLoc,
6439                                          IdentifierInfo *Id,
6440                                          ExprArg val) {
6441  Expr *Val = (Expr *)val.get();
6442
6443  unsigned IntWidth = Context.Target.getIntWidth();
6444  llvm::APSInt EnumVal(IntWidth);
6445  QualType EltTy;
6446  if (Val) {
6447    if (Enum->isDependentType() || Val->isTypeDependent())
6448      EltTy = Context.DependentTy;
6449    else {
6450      // C99 6.7.2.2p2: Make sure we have an integer constant expression.
6451      SourceLocation ExpLoc;
6452      if (!Val->isValueDependent() &&
6453          VerifyIntegerConstantExpression(Val, &EnumVal)) {
6454        Val = 0;
6455      } else {
6456        if (!getLangOptions().CPlusPlus) {
6457          // C99 6.7.2.2p2:
6458          //   The expression that defines the value of an enumeration constant
6459          //   shall be an integer constant expression that has a value
6460          //   representable as an int.
6461
6462          // Complain if the value is not representable in an int.
6463          if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
6464            Diag(IdLoc, diag::ext_enum_value_not_int)
6465              << EnumVal.toString(10) << Val->getSourceRange()
6466              << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
6467          else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
6468            // Force the type of the expression to 'int'.
6469            ImpCastExprToType(Val, Context.IntTy, CastExpr::CK_IntegralCast);
6470
6471            if (Val != val.get()) {
6472              val.release();
6473              val = Val;
6474            }
6475          }
6476        }
6477
6478        // C++0x [dcl.enum]p5:
6479        //   If the underlying type is not fixed, the type of each enumerator
6480        //   is the type of its initializing value:
6481        //     - If an initializer is specified for an enumerator, the
6482        //       initializing value has the same type as the expression.
6483        EltTy = Val->getType();
6484      }
6485    }
6486  }
6487
6488  if (!Val) {
6489    if (Enum->isDependentType())
6490      EltTy = Context.DependentTy;
6491    else if (!LastEnumConst) {
6492      // C++0x [dcl.enum]p5:
6493      //   If the underlying type is not fixed, the type of each enumerator
6494      //   is the type of its initializing value:
6495      //     - If no initializer is specified for the first enumerator, the
6496      //       initializing value has an unspecified integral type.
6497      //
6498      // GCC uses 'int' for its unspecified integral type, as does
6499      // C99 6.7.2.2p3.
6500      EltTy = Context.IntTy;
6501    } else {
6502      // Assign the last value + 1.
6503      EnumVal = LastEnumConst->getInitVal();
6504      ++EnumVal;
6505      EltTy = LastEnumConst->getType();
6506
6507      // Check for overflow on increment.
6508      if (EnumVal < LastEnumConst->getInitVal()) {
6509        // C++0x [dcl.enum]p5:
6510        //   If the underlying type is not fixed, the type of each enumerator
6511        //   is the type of its initializing value:
6512        //
6513        //     - Otherwise the type of the initializing value is the same as
6514        //       the type of the initializing value of the preceding enumerator
6515        //       unless the incremented value is not representable in that type,
6516        //       in which case the type is an unspecified integral type
6517        //       sufficient to contain the incremented value. If no such type
6518        //       exists, the program is ill-formed.
6519        QualType T = getNextLargerIntegralType(Context, EltTy);
6520        if (T.isNull()) {
6521          // There is no integral type larger enough to represent this
6522          // value. Complain, then allow the value to wrap around.
6523          EnumVal = LastEnumConst->getInitVal();
6524          EnumVal.zext(EnumVal.getBitWidth() * 2);
6525          Diag(IdLoc, diag::warn_enumerator_too_large)
6526            << EnumVal.toString(10);
6527        } else {
6528          EltTy = T;
6529        }
6530
6531        // Retrieve the last enumerator's value, extent that type to the
6532        // type that is supposed to be large enough to represent the incremented
6533        // value, then increment.
6534        EnumVal = LastEnumConst->getInitVal();
6535        EnumVal.setIsSigned(EltTy->isSignedIntegerType());
6536        EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
6537        ++EnumVal;
6538
6539        // If we're not in C++, diagnose the overflow of enumerator values,
6540        // which in C99 means that the enumerator value is not representable in
6541        // an int (C99 6.7.2.2p2). However, we support GCC's extension that
6542        // permits enumerator values that are representable in some larger
6543        // integral type.
6544        if (!getLangOptions().CPlusPlus && !T.isNull())
6545          Diag(IdLoc, diag::warn_enum_value_overflow);
6546      } else if (!getLangOptions().CPlusPlus &&
6547                 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
6548        // Enforce C99 6.7.2.2p2 even when we compute the next value.
6549        Diag(IdLoc, diag::ext_enum_value_not_int)
6550          << EnumVal.toString(10) << 1;
6551      }
6552    }
6553  }
6554
6555  if (!EltTy->isDependentType()) {
6556    // Make the enumerator value match the signedness and size of the
6557    // enumerator's type.
6558    EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
6559    EnumVal.setIsSigned(EltTy->isSignedIntegerType());
6560  }
6561
6562  val.release();
6563  return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
6564                                  Val, EnumVal);
6565}
6566
6567
6568Sema::DeclPtrTy Sema::ActOnEnumConstant(Scope *S, DeclPtrTy theEnumDecl,
6569                                        DeclPtrTy lastEnumConst,
6570                                        SourceLocation IdLoc,
6571                                        IdentifierInfo *Id,
6572                                        SourceLocation EqualLoc, ExprTy *val) {
6573  EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl.getAs<Decl>());
6574  EnumConstantDecl *LastEnumConst =
6575    cast_or_null<EnumConstantDecl>(lastEnumConst.getAs<Decl>());
6576  Expr *Val = static_cast<Expr*>(val);
6577
6578  // The scope passed in may not be a decl scope.  Zip up the scope tree until
6579  // we find one that is.
6580  S = getNonFieldDeclScope(S);
6581
6582  // Verify that there isn't already something declared with this name in this
6583  // scope.
6584  NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
6585                                         ForRedeclaration);
6586  if (PrevDecl && PrevDecl->isTemplateParameter()) {
6587    // Maybe we will complain about the shadowed template parameter.
6588    DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
6589    // Just pretend that we didn't see the previous declaration.
6590    PrevDecl = 0;
6591  }
6592
6593  if (PrevDecl) {
6594    // When in C++, we may get a TagDecl with the same name; in this case the
6595    // enum constant will 'hide' the tag.
6596    assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
6597           "Received TagDecl when not in C++!");
6598    if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
6599      if (isa<EnumConstantDecl>(PrevDecl))
6600        Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
6601      else
6602        Diag(IdLoc, diag::err_redefinition) << Id;
6603      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6604      return DeclPtrTy();
6605    }
6606  }
6607
6608  EnumConstantDecl *New = CheckEnumConstant(TheEnumDecl, LastEnumConst,
6609                                            IdLoc, Id, Owned(Val));
6610
6611  // Register this decl in the current scope stack.
6612  if (New) {
6613    New->setAccess(TheEnumDecl->getAccess());
6614    PushOnScopeChains(New, S);
6615  }
6616
6617  return DeclPtrTy::make(New);
6618}
6619
6620void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
6621                         SourceLocation RBraceLoc, DeclPtrTy EnumDeclX,
6622                         DeclPtrTy *Elements, unsigned NumElements,
6623                         Scope *S, AttributeList *Attr) {
6624  EnumDecl *Enum = cast<EnumDecl>(EnumDeclX.getAs<Decl>());
6625  QualType EnumType = Context.getTypeDeclType(Enum);
6626
6627  if (Attr)
6628    ProcessDeclAttributeList(S, Enum, Attr);
6629
6630  if (Enum->isDependentType()) {
6631    for (unsigned i = 0; i != NumElements; ++i) {
6632      EnumConstantDecl *ECD =
6633        cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
6634      if (!ECD) continue;
6635
6636      ECD->setType(EnumType);
6637    }
6638
6639    Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
6640    return;
6641  }
6642
6643  // TODO: If the result value doesn't fit in an int, it must be a long or long
6644  // long value.  ISO C does not support this, but GCC does as an extension,
6645  // emit a warning.
6646  unsigned IntWidth = Context.Target.getIntWidth();
6647  unsigned CharWidth = Context.Target.getCharWidth();
6648  unsigned ShortWidth = Context.Target.getShortWidth();
6649
6650  // Verify that all the values are okay, compute the size of the values, and
6651  // reverse the list.
6652  unsigned NumNegativeBits = 0;
6653  unsigned NumPositiveBits = 0;
6654
6655  // Keep track of whether all elements have type int.
6656  bool AllElementsInt = true;
6657
6658  for (unsigned i = 0; i != NumElements; ++i) {
6659    EnumConstantDecl *ECD =
6660      cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
6661    if (!ECD) continue;  // Already issued a diagnostic.
6662
6663    const llvm::APSInt &InitVal = ECD->getInitVal();
6664
6665    // Keep track of the size of positive and negative values.
6666    if (InitVal.isUnsigned() || InitVal.isNonNegative())
6667      NumPositiveBits = std::max(NumPositiveBits,
6668                                 (unsigned)InitVal.getActiveBits());
6669    else
6670      NumNegativeBits = std::max(NumNegativeBits,
6671                                 (unsigned)InitVal.getMinSignedBits());
6672
6673    // Keep track of whether every enum element has type int (very commmon).
6674    if (AllElementsInt)
6675      AllElementsInt = ECD->getType() == Context.IntTy;
6676  }
6677
6678  // Figure out the type that should be used for this enum.
6679  // FIXME: Support -fshort-enums.
6680  QualType BestType;
6681  unsigned BestWidth;
6682
6683  // C++0x N3000 [conv.prom]p3:
6684  //   An rvalue of an unscoped enumeration type whose underlying
6685  //   type is not fixed can be converted to an rvalue of the first
6686  //   of the following types that can represent all the values of
6687  //   the enumeration: int, unsigned int, long int, unsigned long
6688  //   int, long long int, or unsigned long long int.
6689  // C99 6.4.4.3p2:
6690  //   An identifier declared as an enumeration constant has type int.
6691  // The C99 rule is modified by a gcc extension
6692  QualType BestPromotionType;
6693
6694  bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
6695
6696  if (NumNegativeBits) {
6697    // If there is a negative value, figure out the smallest integer type (of
6698    // int/long/longlong) that fits.
6699    // If it's packed, check also if it fits a char or a short.
6700    if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
6701      BestType = Context.SignedCharTy;
6702      BestWidth = CharWidth;
6703    } else if (Packed && NumNegativeBits <= ShortWidth &&
6704               NumPositiveBits < ShortWidth) {
6705      BestType = Context.ShortTy;
6706      BestWidth = ShortWidth;
6707    } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
6708      BestType = Context.IntTy;
6709      BestWidth = IntWidth;
6710    } else {
6711      BestWidth = Context.Target.getLongWidth();
6712
6713      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
6714        BestType = Context.LongTy;
6715      } else {
6716        BestWidth = Context.Target.getLongLongWidth();
6717
6718        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
6719          Diag(Enum->getLocation(), diag::warn_enum_too_large);
6720        BestType = Context.LongLongTy;
6721      }
6722    }
6723    BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
6724  } else {
6725    // If there is no negative value, figure out the smallest type that fits
6726    // all of the enumerator values.
6727    // If it's packed, check also if it fits a char or a short.
6728    if (Packed && NumPositiveBits <= CharWidth) {
6729      BestType = Context.UnsignedCharTy;
6730      BestPromotionType = Context.IntTy;
6731      BestWidth = CharWidth;
6732    } else if (Packed && NumPositiveBits <= ShortWidth) {
6733      BestType = Context.UnsignedShortTy;
6734      BestPromotionType = Context.IntTy;
6735      BestWidth = ShortWidth;
6736    } else if (NumPositiveBits <= IntWidth) {
6737      BestType = Context.UnsignedIntTy;
6738      BestWidth = IntWidth;
6739      BestPromotionType
6740        = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
6741                           ? Context.UnsignedIntTy : Context.IntTy;
6742    } else if (NumPositiveBits <=
6743               (BestWidth = Context.Target.getLongWidth())) {
6744      BestType = Context.UnsignedLongTy;
6745      BestPromotionType
6746        = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
6747                           ? Context.UnsignedLongTy : Context.LongTy;
6748    } else {
6749      BestWidth = Context.Target.getLongLongWidth();
6750      assert(NumPositiveBits <= BestWidth &&
6751             "How could an initializer get larger than ULL?");
6752      BestType = Context.UnsignedLongLongTy;
6753      BestPromotionType
6754        = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
6755                           ? Context.UnsignedLongLongTy : Context.LongLongTy;
6756    }
6757  }
6758
6759  // Loop over all of the enumerator constants, changing their types to match
6760  // the type of the enum if needed.
6761  for (unsigned i = 0; i != NumElements; ++i) {
6762    EnumConstantDecl *ECD =
6763      cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
6764    if (!ECD) continue;  // Already issued a diagnostic.
6765
6766    // Standard C says the enumerators have int type, but we allow, as an
6767    // extension, the enumerators to be larger than int size.  If each
6768    // enumerator value fits in an int, type it as an int, otherwise type it the
6769    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
6770    // that X has type 'int', not 'unsigned'.
6771
6772    // Determine whether the value fits into an int.
6773    llvm::APSInt InitVal = ECD->getInitVal();
6774
6775    // If it fits into an integer type, force it.  Otherwise force it to match
6776    // the enum decl type.
6777    QualType NewTy;
6778    unsigned NewWidth;
6779    bool NewSign;
6780    if (!getLangOptions().CPlusPlus &&
6781        isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
6782      NewTy = Context.IntTy;
6783      NewWidth = IntWidth;
6784      NewSign = true;
6785    } else if (ECD->getType() == BestType) {
6786      // Already the right type!
6787      if (getLangOptions().CPlusPlus)
6788        // C++ [dcl.enum]p4: Following the closing brace of an
6789        // enum-specifier, each enumerator has the type of its
6790        // enumeration.
6791        ECD->setType(EnumType);
6792      continue;
6793    } else {
6794      NewTy = BestType;
6795      NewWidth = BestWidth;
6796      NewSign = BestType->isSignedIntegerType();
6797    }
6798
6799    // Adjust the APSInt value.
6800    InitVal.extOrTrunc(NewWidth);
6801    InitVal.setIsSigned(NewSign);
6802    ECD->setInitVal(InitVal);
6803
6804    // Adjust the Expr initializer and type.
6805    if (ECD->getInitExpr())
6806      ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy,
6807                                                      CastExpr::CK_IntegralCast,
6808                                                      ECD->getInitExpr(),
6809                                                      CXXBaseSpecifierArray(),
6810                                                     ImplicitCastExpr::RValue));
6811    if (getLangOptions().CPlusPlus)
6812      // C++ [dcl.enum]p4: Following the closing brace of an
6813      // enum-specifier, each enumerator has the type of its
6814      // enumeration.
6815      ECD->setType(EnumType);
6816    else
6817      ECD->setType(NewTy);
6818  }
6819
6820  Enum->completeDefinition(BestType, BestPromotionType,
6821                           NumPositiveBits, NumNegativeBits);
6822}
6823
6824Sema::DeclPtrTy Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
6825                                            ExprArg expr) {
6826  StringLiteral *AsmString = cast<StringLiteral>(expr.takeAs<Expr>());
6827
6828  FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
6829                                                   Loc, AsmString);
6830  CurContext->addDecl(New);
6831  return DeclPtrTy::make(New);
6832}
6833
6834void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
6835                             SourceLocation PragmaLoc,
6836                             SourceLocation NameLoc) {
6837  Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
6838
6839  if (PrevDecl) {
6840    PrevDecl->addAttr(::new (Context) WeakAttr());
6841  } else {
6842    (void)WeakUndeclaredIdentifiers.insert(
6843      std::pair<IdentifierInfo*,WeakInfo>
6844        (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
6845  }
6846}
6847
6848void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
6849                                IdentifierInfo* AliasName,
6850                                SourceLocation PragmaLoc,
6851                                SourceLocation NameLoc,
6852                                SourceLocation AliasNameLoc) {
6853  Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
6854                                    LookupOrdinaryName);
6855  WeakInfo W = WeakInfo(Name, NameLoc);
6856
6857  if (PrevDecl) {
6858    if (!PrevDecl->hasAttr<AliasAttr>())
6859      if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
6860        DeclApplyPragmaWeak(TUScope, ND, W);
6861  } else {
6862    (void)WeakUndeclaredIdentifiers.insert(
6863      std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
6864  }
6865}
6866