SemaDecl.cpp revision ac5fc7c6bcb494b60fee7ce615ac931c5db6135e
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 "SemaInherit.h"
16#include "clang/AST/APValue.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/Analysis/CFG.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/StmtCXX.h"
24#include "clang/AST/StmtObjC.h"
25#include "clang/Parse/DeclSpec.h"
26#include "clang/Basic/TargetInfo.h"
27#include "clang/Basic/SourceManager.h"
28// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
29#include "clang/Lex/Preprocessor.h"
30#include "clang/Lex/HeaderSearch.h"
31#include "llvm/ADT/BitVector.h"
32#include "llvm/ADT/SmallSet.h"
33#include "llvm/ADT/STLExtras.h"
34#include <algorithm>
35#include <functional>
36#include <queue>
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, const CXXScopeSpec *SS) {
65  // C++ [temp.res]p3:
66  //   A qualified-id that refers to a type and in which the
67  //   nested-name-specifier depends on a template-parameter (14.6.2)
68  //   shall be prefixed by the keyword typename to indicate that the
69  //   qualified-id denotes a type, forming an
70  //   elaborated-type-specifier (7.1.5.3).
71  //
72  // We therefore do not perform any name lookup if the result would
73  // refer to a member of an unknown specialization.
74  if (SS && isUnknownSpecialization(*SS))
75    return 0;
76
77  LookupResult Result
78    = LookupParsedName(S, SS, &II, LookupOrdinaryName, false, false);
79
80  NamedDecl *IIDecl = 0;
81  switch (Result.getKind()) {
82  case LookupResult::NotFound:
83  case LookupResult::FoundOverloaded:
84    return 0;
85
86  case LookupResult::AmbiguousBaseSubobjectTypes:
87  case LookupResult::AmbiguousBaseSubobjects:
88  case LookupResult::AmbiguousReference: {
89    // Look to see if we have a type anywhere in the list of results.
90    for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
91         Res != ResEnd; ++Res) {
92      if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
93        if (!IIDecl ||
94            (*Res)->getLocation().getRawEncoding() <
95              IIDecl->getLocation().getRawEncoding())
96          IIDecl = *Res;
97      }
98    }
99
100    if (!IIDecl) {
101      // None of the entities we found is a type, so there is no way
102      // to even assume that the result is a type. In this case, don't
103      // complain about the ambiguity. The parser will either try to
104      // perform this lookup again (e.g., as an object name), which
105      // will produce the ambiguity, or will complain that it expected
106      // a type name.
107      Result.Destroy();
108      return 0;
109    }
110
111    // We found a type within the ambiguous lookup; diagnose the
112    // ambiguity and then return that type. This might be the right
113    // answer, or it might not be, but it suppresses any attempt to
114    // perform the name lookup again.
115    DiagnoseAmbiguousLookup(Result, DeclarationName(&II), NameLoc);
116    break;
117  }
118
119  case LookupResult::Found:
120    IIDecl = Result.getAsDecl();
121    break;
122  }
123
124  if (IIDecl) {
125    QualType T;
126
127    if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
128      // Check whether we can use this type
129      (void)DiagnoseUseOfDecl(IIDecl, NameLoc);
130
131      if (getLangOptions().CPlusPlus) {
132        // C++ [temp.local]p2:
133        //   Within the scope of a class template specialization or
134        //   partial specialization, when the injected-class-name is
135        //   not followed by a <, it is equivalent to the
136        //   injected-class-name followed by the template-argument s
137        //   of the class template specialization or partial
138        //   specialization enclosed in <>.
139        if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD))
140          if (RD->isInjectedClassName())
141            if (ClassTemplateDecl *Template = RD->getDescribedClassTemplate())
142              T = Template->getInjectedClassNameType(Context);
143      }
144
145      if (T.isNull())
146        T = Context.getTypeDeclType(TD);
147    } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
148      // Check whether we can use this interface.
149      (void)DiagnoseUseOfDecl(IIDecl, NameLoc);
150
151      T = Context.getObjCInterfaceType(IDecl);
152    } else
153      return 0;
154
155    if (SS)
156      T = getQualifiedNameType(*SS, T);
157
158    return T.getAsOpaquePtr();
159  }
160
161  return 0;
162}
163
164/// isTagName() - This method is called *for error recovery purposes only*
165/// to determine if the specified name is a valid tag name ("struct foo").  If
166/// so, this returns the TST for the tag corresponding to it (TST_enum,
167/// TST_union, TST_struct, TST_class).  This is used to diagnose cases in C
168/// where the user forgot to specify the tag.
169DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
170  // Do a tag name lookup in this scope.
171  LookupResult R = LookupName(S, &II, LookupTagName, false, false);
172  if (R.getKind() == LookupResult::Found)
173    if (const TagDecl *TD = dyn_cast<TagDecl>(R.getAsDecl())) {
174      switch (TD->getTagKind()) {
175      case TagDecl::TK_struct: return DeclSpec::TST_struct;
176      case TagDecl::TK_union:  return DeclSpec::TST_union;
177      case TagDecl::TK_class:  return DeclSpec::TST_class;
178      case TagDecl::TK_enum:   return DeclSpec::TST_enum;
179      }
180    }
181
182  return DeclSpec::TST_unspecified;
183}
184
185
186
187DeclContext *Sema::getContainingDC(DeclContext *DC) {
188  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
189    // A C++ out-of-line method will return to the file declaration context.
190    if (MD->isOutOfLine())
191      return MD->getLexicalDeclContext();
192
193    // A C++ inline method is parsed *after* the topmost class it was declared
194    // in is fully parsed (it's "complete").
195    // The parsing of a C++ inline method happens at the declaration context of
196    // the topmost (non-nested) class it is lexically declared in.
197    assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
198    DC = MD->getParent();
199    while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
200      DC = RD;
201
202    // Return the declaration context of the topmost class the inline method is
203    // declared in.
204    return DC;
205  }
206
207  if (isa<ObjCMethodDecl>(DC))
208    return Context.getTranslationUnitDecl();
209
210  return DC->getLexicalParent();
211}
212
213void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
214  assert(getContainingDC(DC) == CurContext &&
215      "The next DeclContext should be lexically contained in the current one.");
216  CurContext = DC;
217  S->setEntity(DC);
218}
219
220void Sema::PopDeclContext() {
221  assert(CurContext && "DeclContext imbalance!");
222
223  CurContext = getContainingDC(CurContext);
224}
225
226/// EnterDeclaratorContext - Used when we must lookup names in the context
227/// of a declarator's nested name specifier.
228void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
229  assert(PreDeclaratorDC == 0 && "Previous declarator context not popped?");
230  PreDeclaratorDC = static_cast<DeclContext*>(S->getEntity());
231  CurContext = DC;
232  assert(CurContext && "No context?");
233  S->setEntity(CurContext);
234}
235
236void Sema::ExitDeclaratorContext(Scope *S) {
237  S->setEntity(PreDeclaratorDC);
238  PreDeclaratorDC = 0;
239
240  // Reset CurContext to the nearest enclosing context.
241  while (!S->getEntity() && S->getParent())
242    S = S->getParent();
243  CurContext = static_cast<DeclContext*>(S->getEntity());
244  assert(CurContext && "No context?");
245}
246
247/// \brief Determine whether we allow overloading of the function
248/// PrevDecl with another declaration.
249///
250/// This routine determines whether overloading is possible, not
251/// whether some new function is actually an overload. It will return
252/// true in C++ (where we can always provide overloads) or, as an
253/// extension, in C when the previous function is already an
254/// overloaded function declaration or has the "overloadable"
255/// attribute.
256static bool AllowOverloadingOfFunction(Decl *PrevDecl, ASTContext &Context) {
257  if (Context.getLangOptions().CPlusPlus)
258    return true;
259
260  if (isa<OverloadedFunctionDecl>(PrevDecl))
261    return true;
262
263  return PrevDecl->getAttr<OverloadableAttr>() != 0;
264}
265
266/// Add this decl to the scope shadowed decl chains.
267void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
268  // Move up the scope chain until we find the nearest enclosing
269  // non-transparent context. The declaration will be introduced into this
270  // scope.
271  while (S->getEntity() &&
272         ((DeclContext *)S->getEntity())->isTransparentContext())
273    S = S->getParent();
274
275  S->AddDecl(DeclPtrTy::make(D));
276
277  // Add scoped declarations into their context, so that they can be
278  // found later. Declarations without a context won't be inserted
279  // into any context.
280  CurContext->addDecl(D);
281
282  // C++ [basic.scope]p4:
283  //   -- exactly one declaration shall declare a class name or
284  //   enumeration name that is not a typedef name and the other
285  //   declarations shall all refer to the same object or
286  //   enumerator, or all refer to functions and function templates;
287  //   in this case the class name or enumeration name is hidden.
288  if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
289    // We are pushing the name of a tag (enum or class).
290    if (CurContext->getLookupContext()
291          == TD->getDeclContext()->getLookupContext()) {
292      // We're pushing the tag into the current context, which might
293      // require some reshuffling in the identifier resolver.
294      IdentifierResolver::iterator
295        I = IdResolver.begin(TD->getDeclName()),
296        IEnd = IdResolver.end();
297      if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
298        NamedDecl *PrevDecl = *I;
299        for (; I != IEnd && isDeclInScope(*I, CurContext, S);
300             PrevDecl = *I, ++I) {
301          if (TD->declarationReplaces(*I)) {
302            // This is a redeclaration. Remove it from the chain and
303            // break out, so that we'll add in the shadowed
304            // declaration.
305            S->RemoveDecl(DeclPtrTy::make(*I));
306            if (PrevDecl == *I) {
307              IdResolver.RemoveDecl(*I);
308              IdResolver.AddDecl(TD);
309              return;
310            } else {
311              IdResolver.RemoveDecl(*I);
312              break;
313            }
314          }
315        }
316
317        // There is already a declaration with the same name in the same
318        // scope, which is not a tag declaration. It must be found
319        // before we find the new declaration, so insert the new
320        // declaration at the end of the chain.
321        IdResolver.AddShadowedDecl(TD, PrevDecl);
322
323        return;
324      }
325    }
326  } else if ((isa<FunctionDecl>(D) &&
327              AllowOverloadingOfFunction(D, Context)) ||
328             isa<FunctionTemplateDecl>(D)) {
329    // We are pushing the name of a function or function template,
330    // which might be an overloaded name.
331    IdentifierResolver::iterator Redecl
332      = std::find_if(IdResolver.begin(D->getDeclName()),
333                     IdResolver.end(),
334                     std::bind1st(std::mem_fun(&NamedDecl::declarationReplaces),
335                                  D));
336    if (Redecl != IdResolver.end() &&
337        S->isDeclScope(DeclPtrTy::make(*Redecl))) {
338      // There is already a declaration of a function on our
339      // IdResolver chain. Replace it with this declaration.
340      S->RemoveDecl(DeclPtrTy::make(*Redecl));
341      IdResolver.RemoveDecl(*Redecl);
342    }
343  } else if (isa<ObjCInterfaceDecl>(D)) {
344    // We're pushing an Objective-C interface into the current
345    // context. If there is already an alias declaration, remove it first.
346    for (IdentifierResolver::iterator
347           I = IdResolver.begin(D->getDeclName()), IEnd = IdResolver.end();
348         I != IEnd; ++I) {
349      if (isa<ObjCCompatibleAliasDecl>(*I)) {
350        S->RemoveDecl(DeclPtrTy::make(*I));
351        IdResolver.RemoveDecl(*I);
352        break;
353      }
354    }
355  }
356
357  IdResolver.AddDecl(D);
358}
359
360void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
361  if (S->decl_empty()) return;
362  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
363	 "Scope shouldn't contain decls!");
364
365  for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
366       I != E; ++I) {
367    Decl *TmpD = (*I).getAs<Decl>();
368    assert(TmpD && "This decl didn't get pushed??");
369
370    assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
371    NamedDecl *D = cast<NamedDecl>(TmpD);
372
373    if (!D->getDeclName()) continue;
374
375    // Remove this name from our lexical scope.
376    IdResolver.RemoveDecl(D);
377  }
378}
379
380/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
381/// return 0 if one not found.
382ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
383  // The third "scope" argument is 0 since we aren't enabling lazy built-in
384  // creation from this context.
385  NamedDecl *IDecl = LookupName(TUScope, Id, LookupOrdinaryName);
386
387  return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
388}
389
390/// getNonFieldDeclScope - Retrieves the innermost scope, starting
391/// from S, where a non-field would be declared. This routine copes
392/// with the difference between C and C++ scoping rules in structs and
393/// unions. For example, the following code is well-formed in C but
394/// ill-formed in C++:
395/// @code
396/// struct S6 {
397///   enum { BAR } e;
398/// };
399///
400/// void test_S6() {
401///   struct S6 a;
402///   a.e = BAR;
403/// }
404/// @endcode
405/// For the declaration of BAR, this routine will return a different
406/// scope. The scope S will be the scope of the unnamed enumeration
407/// within S6. In C++, this routine will return the scope associated
408/// with S6, because the enumeration's scope is a transparent
409/// context but structures can contain non-field names. In C, this
410/// routine will return the translation unit scope, since the
411/// enumeration's scope is a transparent context and structures cannot
412/// contain non-field names.
413Scope *Sema::getNonFieldDeclScope(Scope *S) {
414  while (((S->getFlags() & Scope::DeclScope) == 0) ||
415         (S->getEntity() &&
416          ((DeclContext *)S->getEntity())->isTransparentContext()) ||
417         (S->isClassScope() && !getLangOptions().CPlusPlus))
418    S = S->getParent();
419  return S;
420}
421
422void Sema::InitBuiltinVaListType() {
423  if (!Context.getBuiltinVaListType().isNull())
424    return;
425
426  IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
427  NamedDecl *VaDecl = LookupName(TUScope, VaIdent, LookupOrdinaryName);
428  TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
429  Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
430}
431
432/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
433/// file scope.  lazily create a decl for it. ForRedeclaration is true
434/// if we're creating this built-in in anticipation of redeclaring the
435/// built-in.
436NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
437                                     Scope *S, bool ForRedeclaration,
438                                     SourceLocation Loc) {
439  Builtin::ID BID = (Builtin::ID)bid;
440
441  if (Context.BuiltinInfo.hasVAListUse(BID))
442    InitBuiltinVaListType();
443
444  ASTContext::GetBuiltinTypeError Error;
445  QualType R = Context.GetBuiltinType(BID, Error);
446  switch (Error) {
447  case ASTContext::GE_None:
448    // Okay
449    break;
450
451  case ASTContext::GE_Missing_stdio:
452    if (ForRedeclaration)
453      Diag(Loc, diag::err_implicit_decl_requires_stdio)
454        << Context.BuiltinInfo.GetName(BID);
455    return 0;
456
457  case ASTContext::GE_Missing_setjmp:
458    if (ForRedeclaration)
459      Diag(Loc, diag::err_implicit_decl_requires_setjmp)
460        << Context.BuiltinInfo.GetName(BID);
461    return 0;
462  }
463
464  if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
465    Diag(Loc, diag::ext_implicit_lib_function_decl)
466      << Context.BuiltinInfo.GetName(BID)
467      << R;
468    if (Context.BuiltinInfo.getHeaderName(BID) &&
469        Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl)
470          != Diagnostic::Ignored)
471      Diag(Loc, diag::note_please_include_header)
472        << Context.BuiltinInfo.getHeaderName(BID)
473        << Context.BuiltinInfo.GetName(BID);
474  }
475
476  FunctionDecl *New = FunctionDecl::Create(Context,
477                                           Context.getTranslationUnitDecl(),
478                                           Loc, II, R,
479                                           FunctionDecl::Extern, false,
480                                           /*hasPrototype=*/true);
481  New->setImplicit();
482
483  // Create Decl objects for each parameter, adding them to the
484  // FunctionDecl.
485  if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
486    llvm::SmallVector<ParmVarDecl*, 16> Params;
487    for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
488      Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
489                                           FT->getArgType(i), VarDecl::None, 0));
490    New->setParams(Context, Params.data(), Params.size());
491  }
492
493  AddKnownFunctionAttributes(New);
494
495  // TUScope is the translation-unit scope to insert this function into.
496  // FIXME: This is hideous. We need to teach PushOnScopeChains to
497  // relate Scopes to DeclContexts, and probably eliminate CurContext
498  // entirely, but we're not there yet.
499  DeclContext *SavedContext = CurContext;
500  CurContext = Context.getTranslationUnitDecl();
501  PushOnScopeChains(New, TUScope);
502  CurContext = SavedContext;
503  return New;
504}
505
506/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
507/// everything from the standard library is defined.
508NamespaceDecl *Sema::GetStdNamespace() {
509  if (!StdNamespace) {
510    IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
511    DeclContext *Global = Context.getTranslationUnitDecl();
512    Decl *Std = LookupQualifiedName(Global, StdIdent, LookupNamespaceName);
513    StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
514  }
515  return StdNamespace;
516}
517
518/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the
519/// same name and scope as a previous declaration 'Old'.  Figure out
520/// how to resolve this situation, merging decls or emitting
521/// diagnostics as appropriate. If there was an error, set New to be invalid.
522///
523void Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
524  // If either decl is known invalid already, set the new one to be invalid and
525  // don't bother doing any merging checks.
526  if (New->isInvalidDecl() || OldD->isInvalidDecl())
527    return New->setInvalidDecl();
528
529  // Allow multiple definitions for ObjC built-in typedefs.
530  // FIXME: Verify the underlying types are equivalent!
531  if (getLangOptions().ObjC1) {
532    const IdentifierInfo *TypeID = New->getIdentifier();
533    switch (TypeID->getLength()) {
534    default: break;
535    case 2:
536      if (!TypeID->isStr("id"))
537        break;
538      // Install the built-in type for 'id', ignoring the current definition.
539      New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
540      return;
541    case 5:
542      if (!TypeID->isStr("Class"))
543        break;
544      // Install the built-in type for 'Class', ignoring the current definition.
545      New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
546      return;
547    case 3:
548      if (!TypeID->isStr("SEL"))
549        break;
550      Context.setObjCSelType(Context.getTypeDeclType(New));
551      return;
552    case 8:
553      if (!TypeID->isStr("Protocol"))
554        break;
555      Context.setObjCProtoType(New->getUnderlyingType());
556      return;
557    }
558    // Fall through - the typedef name was not a builtin type.
559  }
560  // Verify the old decl was also a type.
561  TypeDecl *Old = dyn_cast<TypeDecl>(OldD);
562  if (!Old) {
563    Diag(New->getLocation(), diag::err_redefinition_different_kind)
564      << New->getDeclName();
565    if (OldD->getLocation().isValid())
566      Diag(OldD->getLocation(), diag::note_previous_definition);
567    return New->setInvalidDecl();
568  }
569
570  // Determine the "old" type we'll use for checking and diagnostics.
571  QualType OldType;
572  if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
573    OldType = OldTypedef->getUnderlyingType();
574  else
575    OldType = Context.getTypeDeclType(Old);
576
577  // If the typedef types are not identical, reject them in all languages and
578  // with any extensions enabled.
579
580  if (OldType != New->getUnderlyingType() &&
581      Context.getCanonicalType(OldType) !=
582      Context.getCanonicalType(New->getUnderlyingType())) {
583    Diag(New->getLocation(), diag::err_redefinition_different_typedef)
584      << New->getUnderlyingType() << OldType;
585    if (Old->getLocation().isValid())
586      Diag(Old->getLocation(), diag::note_previous_definition);
587    return New->setInvalidDecl();
588  }
589
590  if (getLangOptions().Microsoft)
591    return;
592
593  // C++ [dcl.typedef]p2:
594  //   In a given non-class scope, a typedef specifier can be used to
595  //   redefine the name of any type declared in that scope to refer
596  //   to the type to which it already refers.
597  if (getLangOptions().CPlusPlus) {
598    if (!isa<CXXRecordDecl>(CurContext))
599      return;
600    Diag(New->getLocation(), diag::err_redefinition)
601      << New->getDeclName();
602    Diag(Old->getLocation(), diag::note_previous_definition);
603    return New->setInvalidDecl();
604  }
605
606  // If we have a redefinition of a typedef in C, emit a warning.  This warning
607  // is normally mapped to an error, but can be controlled with
608  // -Wtypedef-redefinition.  If either the original or the redefinition is
609  // in a system header, don't emit this for compatibility with GCC.
610  if (PP.getDiagnostics().getSuppressSystemWarnings() &&
611      (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
612       Context.getSourceManager().isInSystemHeader(New->getLocation())))
613    return;
614
615  Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
616    << New->getDeclName();
617  Diag(Old->getLocation(), diag::note_previous_definition);
618  return;
619}
620
621/// DeclhasAttr - returns true if decl Declaration already has the target
622/// attribute.
623static bool
624DeclHasAttr(const Decl *decl, const Attr *target) {
625  for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
626    if (attr->getKind() == target->getKind())
627      return true;
628
629  return false;
630}
631
632/// MergeAttributes - append attributes from the Old decl to the New one.
633static void MergeAttributes(Decl *New, Decl *Old, ASTContext &C) {
634  for (const Attr *attr = Old->getAttrs(); attr; attr = attr->getNext()) {
635    if (!DeclHasAttr(New, attr) && attr->isMerged()) {
636      Attr *NewAttr = attr->clone(C);
637      NewAttr->setInherited(true);
638      New->addAttr(NewAttr);
639    }
640  }
641}
642
643/// Used in MergeFunctionDecl to keep track of function parameters in
644/// C.
645struct GNUCompatibleParamWarning {
646  ParmVarDecl *OldParm;
647  ParmVarDecl *NewParm;
648  QualType PromotedType;
649};
650
651/// MergeFunctionDecl - We just parsed a function 'New' from
652/// declarator D which has the same name and scope as a previous
653/// declaration 'Old'.  Figure out how to resolve this situation,
654/// merging decls or emitting diagnostics as appropriate.
655///
656/// In C++, New and Old must be declarations that are not
657/// overloaded. Use IsOverload to determine whether New and Old are
658/// overloaded, and to select the Old declaration that New should be
659/// merged with.
660///
661/// Returns true if there was an error, false otherwise.
662bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
663  assert(!isa<OverloadedFunctionDecl>(OldD) &&
664         "Cannot merge with an overloaded function declaration");
665
666  // Verify the old decl was also a function.
667  FunctionDecl *Old = 0;
668  if (FunctionTemplateDecl *OldFunctionTemplate
669        = dyn_cast<FunctionTemplateDecl>(OldD))
670    Old = OldFunctionTemplate->getTemplatedDecl();
671  else
672    Old = dyn_cast<FunctionDecl>(OldD);
673  if (!Old) {
674    Diag(New->getLocation(), diag::err_redefinition_different_kind)
675      << New->getDeclName();
676    Diag(OldD->getLocation(), diag::note_previous_definition);
677    return true;
678  }
679
680  // Determine whether the previous declaration was a definition,
681  // implicit declaration, or a declaration.
682  diag::kind PrevDiag;
683  if (Old->isThisDeclarationADefinition())
684    PrevDiag = diag::note_previous_definition;
685  else if (Old->isImplicit())
686    PrevDiag = diag::note_previous_implicit_declaration;
687  else
688    PrevDiag = diag::note_previous_declaration;
689
690  QualType OldQType = Context.getCanonicalType(Old->getType());
691  QualType NewQType = Context.getCanonicalType(New->getType());
692
693  if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
694      New->getStorageClass() == FunctionDecl::Static &&
695      Old->getStorageClass() != FunctionDecl::Static) {
696    Diag(New->getLocation(), diag::err_static_non_static)
697      << New;
698    Diag(Old->getLocation(), PrevDiag);
699    return true;
700  }
701
702  if (getLangOptions().CPlusPlus) {
703    // (C++98 13.1p2):
704    //   Certain function declarations cannot be overloaded:
705    //     -- Function declarations that differ only in the return type
706    //        cannot be overloaded.
707    QualType OldReturnType
708      = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
709    QualType NewReturnType
710      = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
711    if (OldReturnType != NewReturnType) {
712      Diag(New->getLocation(), diag::err_ovl_diff_return_type);
713      Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
714      return true;
715    }
716
717    const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
718    const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
719    if (OldMethod && NewMethod &&
720        NewMethod->getLexicalDeclContext()->isRecord()) {
721      //    -- Member function declarations with the same name and the
722      //       same parameter types cannot be overloaded if any of them
723      //       is a static member function declaration.
724      if (OldMethod->isStatic() || NewMethod->isStatic()) {
725        Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
726        Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
727        return true;
728      }
729
730      // C++ [class.mem]p1:
731      //   [...] A member shall not be declared twice in the
732      //   member-specification, except that a nested class or member
733      //   class template can be declared and then later defined.
734      unsigned NewDiag;
735      if (isa<CXXConstructorDecl>(OldMethod))
736        NewDiag = diag::err_constructor_redeclared;
737      else if (isa<CXXDestructorDecl>(NewMethod))
738        NewDiag = diag::err_destructor_redeclared;
739      else if (isa<CXXConversionDecl>(NewMethod))
740        NewDiag = diag::err_conv_function_redeclared;
741      else
742        NewDiag = diag::err_member_redeclared;
743
744      Diag(New->getLocation(), NewDiag);
745      Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
746    }
747
748    // (C++98 8.3.5p3):
749    //   All declarations for a function shall agree exactly in both the
750    //   return type and the parameter-type-list.
751    if (OldQType == NewQType)
752      return MergeCompatibleFunctionDecls(New, Old);
753
754    // Fall through for conflicting redeclarations and redefinitions.
755  }
756
757  // C: Function types need to be compatible, not identical. This handles
758  // duplicate function decls like "void f(int); void f(enum X);" properly.
759  if (!getLangOptions().CPlusPlus &&
760      Context.typesAreCompatible(OldQType, NewQType)) {
761    const FunctionType *OldFuncType = OldQType->getAsFunctionType();
762    const FunctionType *NewFuncType = NewQType->getAsFunctionType();
763    const FunctionProtoType *OldProto = 0;
764    if (isa<FunctionNoProtoType>(NewFuncType) &&
765        (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
766      // The old declaration provided a function prototype, but the
767      // new declaration does not. Merge in the prototype.
768      assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
769      llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
770                                                 OldProto->arg_type_end());
771      NewQType = Context.getFunctionType(NewFuncType->getResultType(),
772                                         ParamTypes.data(), ParamTypes.size(),
773                                         OldProto->isVariadic(),
774                                         OldProto->getTypeQuals());
775      New->setType(NewQType);
776      New->setHasInheritedPrototype();
777
778      // Synthesize a parameter for each argument type.
779      llvm::SmallVector<ParmVarDecl*, 16> Params;
780      for (FunctionProtoType::arg_type_iterator
781             ParamType = OldProto->arg_type_begin(),
782             ParamEnd = OldProto->arg_type_end();
783           ParamType != ParamEnd; ++ParamType) {
784        ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
785                                                 SourceLocation(), 0,
786                                                 *ParamType, VarDecl::None,
787                                                 0);
788        Param->setImplicit();
789        Params.push_back(Param);
790      }
791
792      New->setParams(Context, Params.data(), Params.size());
793    }
794
795    return MergeCompatibleFunctionDecls(New, Old);
796  }
797
798  // GNU C permits a K&R definition to follow a prototype declaration
799  // if the declared types of the parameters in the K&R definition
800  // match the types in the prototype declaration, even when the
801  // promoted types of the parameters from the K&R definition differ
802  // from the types in the prototype. GCC then keeps the types from
803  // the prototype.
804  //
805  // If a variadic prototype is followed by a non-variadic K&R definition,
806  // the K&R definition becomes variadic.  This is sort of an edge case, but
807  // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
808  // C99 6.9.1p8.
809  if (!getLangOptions().CPlusPlus &&
810      Old->hasPrototype() && !New->hasPrototype() &&
811      New->getType()->getAsFunctionProtoType() &&
812      Old->getNumParams() == New->getNumParams()) {
813    llvm::SmallVector<QualType, 16> ArgTypes;
814    llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings;
815    const FunctionProtoType *OldProto
816      = Old->getType()->getAsFunctionProtoType();
817    const FunctionProtoType *NewProto
818      = New->getType()->getAsFunctionProtoType();
819
820    // Determine whether this is the GNU C extension.
821    QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
822                                               NewProto->getResultType());
823    bool LooseCompatible = !MergedReturn.isNull();
824    for (unsigned Idx = 0, End = Old->getNumParams();
825         LooseCompatible && Idx != End; ++Idx) {
826      ParmVarDecl *OldParm = Old->getParamDecl(Idx);
827      ParmVarDecl *NewParm = New->getParamDecl(Idx);
828      if (Context.typesAreCompatible(OldParm->getType(),
829                                     NewProto->getArgType(Idx))) {
830        ArgTypes.push_back(NewParm->getType());
831      } else if (Context.typesAreCompatible(OldParm->getType(),
832                                            NewParm->getType())) {
833        GNUCompatibleParamWarning Warn
834          = { OldParm, NewParm, NewProto->getArgType(Idx) };
835        Warnings.push_back(Warn);
836        ArgTypes.push_back(NewParm->getType());
837      } else
838        LooseCompatible = false;
839    }
840
841    if (LooseCompatible) {
842      for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
843        Diag(Warnings[Warn].NewParm->getLocation(),
844             diag::ext_param_promoted_not_compatible_with_prototype)
845          << Warnings[Warn].PromotedType
846          << Warnings[Warn].OldParm->getType();
847        Diag(Warnings[Warn].OldParm->getLocation(),
848             diag::note_previous_declaration);
849      }
850
851      New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
852                                           ArgTypes.size(),
853                                           OldProto->isVariadic(), 0));
854      return MergeCompatibleFunctionDecls(New, Old);
855    }
856
857    // Fall through to diagnose conflicting types.
858  }
859
860  // A function that has already been declared has been redeclared or defined
861  // with a different type- show appropriate diagnostic
862  if (unsigned BuiltinID = Old->getBuiltinID(Context)) {
863    // The user has declared a builtin function with an incompatible
864    // signature.
865    if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
866      // The function the user is redeclaring is a library-defined
867      // function like 'malloc' or 'printf'. Warn about the
868      // redeclaration, then pretend that we don't know about this
869      // library built-in.
870      Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
871      Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
872        << Old << Old->getType();
873      New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
874      Old->setInvalidDecl();
875      return false;
876    }
877
878    PrevDiag = diag::note_previous_builtin_declaration;
879  }
880
881  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
882  Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
883  return true;
884}
885
886/// \brief Completes the merge of two function declarations that are
887/// known to be compatible.
888///
889/// This routine handles the merging of attributes and other
890/// properties of function declarations form the old declaration to
891/// the new declaration, once we know that New is in fact a
892/// redeclaration of Old.
893///
894/// \returns false
895bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
896  // Merge the attributes
897  MergeAttributes(New, Old, Context);
898
899  // Merge the storage class.
900  if (Old->getStorageClass() != FunctionDecl::Extern)
901    New->setStorageClass(Old->getStorageClass());
902
903  // Merge "inline"
904  if (Old->isInline())
905    New->setInline(true);
906
907  // If this function declaration by itself qualifies as a C99 inline
908  // definition (C99 6.7.4p6), but the previous definition did not,
909  // then the function is not a C99 inline definition.
910  if (New->isC99InlineDefinition() && !Old->isC99InlineDefinition())
911    New->setC99InlineDefinition(false);
912  else if (Old->isC99InlineDefinition() && !New->isC99InlineDefinition()) {
913    // Mark all preceding definitions as not being C99 inline definitions.
914    for (const FunctionDecl *Prev = Old; Prev;
915         Prev = Prev->getPreviousDeclaration())
916      const_cast<FunctionDecl *>(Prev)->setC99InlineDefinition(false);
917  }
918
919  // Merge "pure" flag.
920  if (Old->isPure())
921    New->setPure();
922
923  // Merge the "deleted" flag.
924  if (Old->isDeleted())
925    New->setDeleted();
926
927  if (getLangOptions().CPlusPlus)
928    return MergeCXXFunctionDecl(New, Old);
929
930  return false;
931}
932
933/// MergeVarDecl - We just parsed a variable 'New' which has the same name
934/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
935/// situation, merging decls or emitting diagnostics as appropriate.
936///
937/// Tentative definition rules (C99 6.9.2p2) are checked by
938/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
939/// definitions here, since the initializer hasn't been attached.
940///
941void Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
942  // If either decl is invalid, make sure the new one is marked invalid and
943  // don't do any other checking.
944  if (New->isInvalidDecl() || OldD->isInvalidDecl())
945    return New->setInvalidDecl();
946
947  // Verify the old decl was also a variable.
948  VarDecl *Old = dyn_cast<VarDecl>(OldD);
949  if (!Old) {
950    Diag(New->getLocation(), diag::err_redefinition_different_kind)
951      << New->getDeclName();
952    Diag(OldD->getLocation(), diag::note_previous_definition);
953    return New->setInvalidDecl();
954  }
955
956  MergeAttributes(New, Old, Context);
957
958  // Merge the types
959  QualType MergedT;
960  if (getLangOptions().CPlusPlus) {
961    if (Context.hasSameType(New->getType(), Old->getType()))
962      MergedT = New->getType();
963  } else {
964    MergedT = Context.mergeTypes(New->getType(), Old->getType());
965  }
966  if (MergedT.isNull()) {
967    Diag(New->getLocation(), diag::err_redefinition_different_type)
968      << New->getDeclName();
969    Diag(Old->getLocation(), diag::note_previous_definition);
970    return New->setInvalidDecl();
971  }
972  New->setType(MergedT);
973
974  // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
975  if (New->getStorageClass() == VarDecl::Static &&
976      (Old->getStorageClass() == VarDecl::None || Old->hasExternalStorage())) {
977    Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
978    Diag(Old->getLocation(), diag::note_previous_definition);
979    return New->setInvalidDecl();
980  }
981  // C99 6.2.2p4:
982  //   For an identifier declared with the storage-class specifier
983  //   extern in a scope in which a prior declaration of that
984  //   identifier is visible,23) if the prior declaration specifies
985  //   internal or external linkage, the linkage of the identifier at
986  //   the later declaration is the same as the linkage specified at
987  //   the prior declaration. If no prior declaration is visible, or
988  //   if the prior declaration specifies no linkage, then the
989  //   identifier has external linkage.
990  if (New->hasExternalStorage() && Old->hasLinkage())
991    /* Okay */;
992  else if (New->getStorageClass() != VarDecl::Static &&
993           Old->getStorageClass() == VarDecl::Static) {
994    Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
995    Diag(Old->getLocation(), diag::note_previous_definition);
996    return New->setInvalidDecl();
997  }
998
999  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
1000
1001  // FIXME: The test for external storage here seems wrong? We still
1002  // need to check for mismatches.
1003  if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
1004      // Don't complain about out-of-line definitions of static members.
1005      !(Old->getLexicalDeclContext()->isRecord() &&
1006        !New->getLexicalDeclContext()->isRecord())) {
1007    Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
1008    Diag(Old->getLocation(), diag::note_previous_definition);
1009    return New->setInvalidDecl();
1010  }
1011
1012  if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
1013    Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
1014    Diag(Old->getLocation(), diag::note_previous_definition);
1015  } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
1016    Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
1017    Diag(Old->getLocation(), diag::note_previous_definition);
1018  }
1019
1020  // Keep a chain of previous declarations.
1021  New->setPreviousDeclaration(Old);
1022}
1023
1024/// CheckFallThrough - Check that we don't fall off the end of a
1025/// Statement that should return a value.
1026///
1027/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
1028/// MaybeFallThrough iff we might or might not fall off the end and
1029/// NeverFallThrough iff we never fall off the end of the statement.  We assume
1030/// that functions not marked noreturn will return.
1031Sema::ControlFlowKind Sema::CheckFallThrough(Stmt *Root) {
1032  llvm::OwningPtr<CFG> cfg (CFG::buildCFG(Root, &Context));
1033
1034  // FIXME: They should never return 0, fix that, delete this code.
1035  if (cfg == 0)
1036    return NeverFallThrough;
1037  // The CFG leaves in dead things, and we don't want to dead code paths to
1038  // confuse us, so we mark all live things first.
1039  std::queue<CFGBlock*> workq;
1040  llvm::BitVector live(cfg->getNumBlockIDs());
1041  // Prep work queue
1042  workq.push(&cfg->getEntry());
1043  // Solve
1044  while (!workq.empty()) {
1045    CFGBlock *item = workq.front();
1046    workq.pop();
1047    live.set(item->getBlockID());
1048    for (CFGBlock::succ_iterator I=item->succ_begin(),
1049           E=item->succ_end();
1050         I != E;
1051         ++I) {
1052      if ((*I) && !live[(*I)->getBlockID()]) {
1053        live.set((*I)->getBlockID());
1054        workq.push(*I);
1055      }
1056    }
1057  }
1058
1059  // Now we know what is live, we check the live precessors of the exit block
1060  // and look for fall through paths, being careful to ignore normal returns,
1061  // and exceptional paths.
1062  bool HasLiveReturn = false;
1063  bool HasFakeEdge = false;
1064  bool HasPlainEdge = false;
1065  for (CFGBlock::succ_iterator I=cfg->getExit().pred_begin(),
1066         E = cfg->getExit().pred_end();
1067       I != E;
1068       ++I) {
1069    CFGBlock& B = **I;
1070    if (!live[B.getBlockID()])
1071      continue;
1072    if (B.size() == 0) {
1073      // A labeled empty statement, or the entry block...
1074      HasPlainEdge = true;
1075      continue;
1076    }
1077    Stmt *S = B[B.size()-1];
1078    if (isa<ReturnStmt>(S)) {
1079      HasLiveReturn = true;
1080      continue;
1081    }
1082    if (isa<ObjCAtThrowStmt>(S)) {
1083      HasFakeEdge = true;
1084      continue;
1085    }
1086    if (isa<CXXThrowExpr>(S)) {
1087      HasFakeEdge = true;
1088      continue;
1089    }
1090    bool NoReturnEdge = false;
1091    if (CallExpr *C = dyn_cast<CallExpr>(S)) {
1092      Expr *CEE = C->getCallee()->IgnoreParenCasts();
1093      if (CEE->getType().getNoReturnAttr()) {
1094        NoReturnEdge = true;
1095        HasFakeEdge = true;
1096      } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) {
1097        if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1098          if (FD->hasAttr<NoReturnAttr>()) {
1099            NoReturnEdge = true;
1100            HasFakeEdge = true;
1101          }
1102        }
1103      }
1104    }
1105    // FIXME: Add noreturn message sends.
1106    if (NoReturnEdge == false)
1107      HasPlainEdge = true;
1108  }
1109  if (!HasPlainEdge)
1110    return NeverFallThrough;
1111  if (HasFakeEdge || HasLiveReturn)
1112    return MaybeFallThrough;
1113  // This says AlwaysFallThrough for calls to functions that are not marked
1114  // noreturn, that don't return.  If people would like this warning to be more
1115  // accurate, such functions should be marked as noreturn.
1116  return AlwaysFallThrough;
1117}
1118
1119/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
1120/// function that should return a value.  Check that we don't fall off the end
1121/// of a noreturn function.  We assume that functions and blocks not marked
1122/// noreturn will return.
1123void Sema::CheckFallThroughForFunctionDef(Decl *D, Stmt *Body) {
1124  // FIXME: Would be nice if we had a better way to control cascading errors,
1125  // but for now, avoid them.  The problem is that when Parse sees:
1126  //   int foo() { return a; }
1127  // The return is eaten and the Sema code sees just:
1128  //   int foo() { }
1129  // which this code would then warn about.
1130  if (getDiagnostics().hasErrorOccurred())
1131    return;
1132  bool ReturnsVoid = false;
1133  bool HasNoReturn = false;
1134  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1135    if (FD->getResultType()->isVoidType())
1136      ReturnsVoid = true;
1137    if (FD->hasAttr<NoReturnAttr>())
1138      HasNoReturn = true;
1139  } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
1140    if (MD->getResultType()->isVoidType())
1141      ReturnsVoid = true;
1142    if (MD->hasAttr<NoReturnAttr>())
1143      HasNoReturn = true;
1144  }
1145
1146  // Short circuit for compilation speed.
1147  if ((Diags.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function)
1148       == Diagnostic::Ignored || ReturnsVoid)
1149      && (Diags.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr)
1150          == Diagnostic::Ignored || !HasNoReturn)
1151      && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
1152          == Diagnostic::Ignored || !ReturnsVoid))
1153    return;
1154  // FIXME: Funtion try block
1155  if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
1156    switch (CheckFallThrough(Body)) {
1157    case MaybeFallThrough:
1158      if (HasNoReturn)
1159        Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function);
1160      else if (!ReturnsVoid)
1161        Diag(Compound->getRBracLoc(),diag::warn_maybe_falloff_nonvoid_function);
1162      break;
1163    case AlwaysFallThrough:
1164      if (HasNoReturn)
1165        Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function);
1166      else if (!ReturnsVoid)
1167        Diag(Compound->getRBracLoc(), diag::warn_falloff_nonvoid_function);
1168      break;
1169    case NeverFallThrough:
1170      if (ReturnsVoid)
1171        Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_function);
1172      break;
1173    }
1174  }
1175}
1176
1177/// CheckFallThroughForBlock - Check that we don't fall off the end of a block
1178/// that should return a value.  Check that we don't fall off the end of a
1179/// noreturn block.  We assume that functions and blocks not marked noreturn
1180/// will return.
1181void Sema::CheckFallThroughForBlock(QualType BlockTy, Stmt *Body) {
1182  // FIXME: Would be nice if we had a better way to control cascading errors,
1183  // but for now, avoid them.  The problem is that when Parse sees:
1184  //   int foo() { return a; }
1185  // The return is eaten and the Sema code sees just:
1186  //   int foo() { }
1187  // which this code would then warn about.
1188  if (getDiagnostics().hasErrorOccurred())
1189    return;
1190  bool ReturnsVoid = false;
1191  bool HasNoReturn = false;
1192  if (const FunctionType *FT = BlockTy->getPointeeType()->getAsFunctionType()) {
1193    if (FT->getResultType()->isVoidType())
1194      ReturnsVoid = true;
1195    if (FT->getNoReturnAttr())
1196      HasNoReturn = true;
1197  }
1198
1199  // Short circuit for compilation speed.
1200  if (ReturnsVoid
1201      && !HasNoReturn
1202      && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
1203          == Diagnostic::Ignored || !ReturnsVoid))
1204    return;
1205  // FIXME: Funtion try block
1206  if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
1207    switch (CheckFallThrough(Body)) {
1208    case MaybeFallThrough:
1209      if (HasNoReturn)
1210        Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr);
1211      else if (!ReturnsVoid)
1212        Diag(Compound->getRBracLoc(), diag::err_maybe_falloff_nonvoid_block);
1213      break;
1214    case AlwaysFallThrough:
1215      if (HasNoReturn)
1216        Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr);
1217      else if (!ReturnsVoid)
1218        Diag(Compound->getRBracLoc(), diag::err_falloff_nonvoid_block);
1219      break;
1220    case NeverFallThrough:
1221      if (ReturnsVoid)
1222        Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_block);
1223      break;
1224    }
1225  }
1226}
1227
1228/// CheckParmsForFunctionDef - Check that the parameters of the given
1229/// function are appropriate for the definition of a function. This
1230/// takes care of any checks that cannot be performed on the
1231/// declaration itself, e.g., that the types of each of the function
1232/// parameters are complete.
1233bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
1234  bool HasInvalidParm = false;
1235  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1236    ParmVarDecl *Param = FD->getParamDecl(p);
1237
1238    // C99 6.7.5.3p4: the parameters in a parameter type list in a
1239    // function declarator that is part of a function definition of
1240    // that function shall not have incomplete type.
1241    //
1242    // This is also C++ [dcl.fct]p6.
1243    if (!Param->isInvalidDecl() &&
1244        RequireCompleteType(Param->getLocation(), Param->getType(),
1245                               diag::err_typecheck_decl_incomplete_type)) {
1246      Param->setInvalidDecl();
1247      HasInvalidParm = true;
1248    }
1249
1250    // C99 6.9.1p5: If the declarator includes a parameter type list, the
1251    // declaration of each parameter shall include an identifier.
1252    if (Param->getIdentifier() == 0 &&
1253        !Param->isImplicit() &&
1254        !getLangOptions().CPlusPlus)
1255      Diag(Param->getLocation(), diag::err_parameter_name_omitted);
1256  }
1257
1258  return HasInvalidParm;
1259}
1260
1261/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
1262/// no declarator (e.g. "struct foo;") is parsed.
1263Sema::DeclPtrTy Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
1264  // FIXME: Error on auto/register at file scope
1265  // FIXME: Error on inline/virtual/explicit
1266  // FIXME: Error on invalid restrict
1267  // FIXME: Warn on useless __thread
1268  // FIXME: Warn on useless const/volatile
1269  // FIXME: Warn on useless static/extern/typedef/private_extern/mutable
1270  // FIXME: Warn on useless attributes
1271  TagDecl *Tag = 0;
1272  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
1273      DS.getTypeSpecType() == DeclSpec::TST_struct ||
1274      DS.getTypeSpecType() == DeclSpec::TST_union ||
1275      DS.getTypeSpecType() == DeclSpec::TST_enum) {
1276    if (!DS.getTypeRep()) // We probably had an error
1277      return DeclPtrTy();
1278
1279    Tag = dyn_cast<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
1280  }
1281
1282  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
1283    if (!Record->getDeclName() && Record->isDefinition() &&
1284        DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
1285      if (getLangOptions().CPlusPlus ||
1286          Record->getDeclContext()->isRecord())
1287        return BuildAnonymousStructOrUnion(S, DS, Record);
1288
1289      Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
1290        << DS.getSourceRange();
1291    }
1292
1293    // Microsoft allows unnamed struct/union fields. Don't complain
1294    // about them.
1295    // FIXME: Should we support Microsoft's extensions in this area?
1296    if (Record->getDeclName() && getLangOptions().Microsoft)
1297      return DeclPtrTy::make(Tag);
1298  }
1299
1300  if (!DS.isMissingDeclaratorOk() &&
1301      DS.getTypeSpecType() != DeclSpec::TST_error) {
1302    // Warn about typedefs of enums without names, since this is an
1303    // extension in both Microsoft an GNU.
1304    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
1305        Tag && isa<EnumDecl>(Tag)) {
1306      Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
1307        << DS.getSourceRange();
1308      return DeclPtrTy::make(Tag);
1309    }
1310
1311    Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
1312      << DS.getSourceRange();
1313    return DeclPtrTy();
1314  }
1315
1316  return DeclPtrTy::make(Tag);
1317}
1318
1319/// InjectAnonymousStructOrUnionMembers - Inject the members of the
1320/// anonymous struct or union AnonRecord into the owning context Owner
1321/// and scope S. This routine will be invoked just after we realize
1322/// that an unnamed union or struct is actually an anonymous union or
1323/// struct, e.g.,
1324///
1325/// @code
1326/// union {
1327///   int i;
1328///   float f;
1329/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
1330///    // f into the surrounding scope.x
1331/// @endcode
1332///
1333/// This routine is recursive, injecting the names of nested anonymous
1334/// structs/unions into the owning context and scope as well.
1335bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
1336                                               RecordDecl *AnonRecord) {
1337  bool Invalid = false;
1338  for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
1339                               FEnd = AnonRecord->field_end();
1340       F != FEnd; ++F) {
1341    if ((*F)->getDeclName()) {
1342      NamedDecl *PrevDecl = LookupQualifiedName(Owner, (*F)->getDeclName(),
1343                                                LookupOrdinaryName, true);
1344      if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
1345        // C++ [class.union]p2:
1346        //   The names of the members of an anonymous union shall be
1347        //   distinct from the names of any other entity in the
1348        //   scope in which the anonymous union is declared.
1349        unsigned diagKind
1350          = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
1351                                 : diag::err_anonymous_struct_member_redecl;
1352        Diag((*F)->getLocation(), diagKind)
1353          << (*F)->getDeclName();
1354        Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
1355        Invalid = true;
1356      } else {
1357        // C++ [class.union]p2:
1358        //   For the purpose of name lookup, after the anonymous union
1359        //   definition, the members of the anonymous union are
1360        //   considered to have been defined in the scope in which the
1361        //   anonymous union is declared.
1362        Owner->makeDeclVisibleInContext(*F);
1363        S->AddDecl(DeclPtrTy::make(*F));
1364        IdResolver.AddDecl(*F);
1365      }
1366    } else if (const RecordType *InnerRecordType
1367                 = (*F)->getType()->getAs<RecordType>()) {
1368      RecordDecl *InnerRecord = InnerRecordType->getDecl();
1369      if (InnerRecord->isAnonymousStructOrUnion())
1370        Invalid = Invalid ||
1371          InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
1372    }
1373  }
1374
1375  return Invalid;
1376}
1377
1378/// ActOnAnonymousStructOrUnion - Handle the declaration of an
1379/// anonymous structure or union. Anonymous unions are a C++ feature
1380/// (C++ [class.union]) and a GNU C extension; anonymous structures
1381/// are a GNU C and GNU C++ extension.
1382Sema::DeclPtrTy Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1383                                                  RecordDecl *Record) {
1384  DeclContext *Owner = Record->getDeclContext();
1385
1386  // Diagnose whether this anonymous struct/union is an extension.
1387  if (Record->isUnion() && !getLangOptions().CPlusPlus)
1388    Diag(Record->getLocation(), diag::ext_anonymous_union);
1389  else if (!Record->isUnion())
1390    Diag(Record->getLocation(), diag::ext_anonymous_struct);
1391
1392  // C and C++ require different kinds of checks for anonymous
1393  // structs/unions.
1394  bool Invalid = false;
1395  if (getLangOptions().CPlusPlus) {
1396    const char* PrevSpec = 0;
1397    unsigned DiagID;
1398    // C++ [class.union]p3:
1399    //   Anonymous unions declared in a named namespace or in the
1400    //   global namespace shall be declared static.
1401    if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
1402        (isa<TranslationUnitDecl>(Owner) ||
1403         (isa<NamespaceDecl>(Owner) &&
1404          cast<NamespaceDecl>(Owner)->getDeclName()))) {
1405      Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
1406      Invalid = true;
1407
1408      // Recover by adding 'static'.
1409      DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(),
1410                             PrevSpec, DiagID);
1411    }
1412    // C++ [class.union]p3:
1413    //   A storage class is not allowed in a declaration of an
1414    //   anonymous union in a class scope.
1415    else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1416             isa<RecordDecl>(Owner)) {
1417      Diag(DS.getStorageClassSpecLoc(),
1418           diag::err_anonymous_union_with_storage_spec);
1419      Invalid = true;
1420
1421      // Recover by removing the storage specifier.
1422      DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
1423                             PrevSpec, DiagID);
1424    }
1425
1426    // C++ [class.union]p2:
1427    //   The member-specification of an anonymous union shall only
1428    //   define non-static data members. [Note: nested types and
1429    //   functions cannot be declared within an anonymous union. ]
1430    for (DeclContext::decl_iterator Mem = Record->decls_begin(),
1431                                 MemEnd = Record->decls_end();
1432         Mem != MemEnd; ++Mem) {
1433      if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
1434        // C++ [class.union]p3:
1435        //   An anonymous union shall not have private or protected
1436        //   members (clause 11).
1437        if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
1438          Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
1439            << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
1440          Invalid = true;
1441        }
1442      } else if ((*Mem)->isImplicit()) {
1443        // Any implicit members are fine.
1444      } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
1445        // This is a type that showed up in an
1446        // elaborated-type-specifier inside the anonymous struct or
1447        // union, but which actually declares a type outside of the
1448        // anonymous struct or union. It's okay.
1449      } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
1450        if (!MemRecord->isAnonymousStructOrUnion() &&
1451            MemRecord->getDeclName()) {
1452          // This is a nested type declaration.
1453          Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
1454            << (int)Record->isUnion();
1455          Invalid = true;
1456        }
1457      } else {
1458        // We have something that isn't a non-static data
1459        // member. Complain about it.
1460        unsigned DK = diag::err_anonymous_record_bad_member;
1461        if (isa<TypeDecl>(*Mem))
1462          DK = diag::err_anonymous_record_with_type;
1463        else if (isa<FunctionDecl>(*Mem))
1464          DK = diag::err_anonymous_record_with_function;
1465        else if (isa<VarDecl>(*Mem))
1466          DK = diag::err_anonymous_record_with_static;
1467        Diag((*Mem)->getLocation(), DK)
1468            << (int)Record->isUnion();
1469          Invalid = true;
1470      }
1471    }
1472  }
1473
1474  if (!Record->isUnion() && !Owner->isRecord()) {
1475    Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
1476      << (int)getLangOptions().CPlusPlus;
1477    Invalid = true;
1478  }
1479
1480  // Create a declaration for this anonymous struct/union.
1481  NamedDecl *Anon = 0;
1482  if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
1483    Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
1484                             /*IdentifierInfo=*/0,
1485                             Context.getTypeDeclType(Record),
1486                             /*BitWidth=*/0, /*Mutable=*/false,
1487                             DS.getSourceRange().getBegin());
1488    Anon->setAccess(AS_public);
1489    if (getLangOptions().CPlusPlus)
1490      FieldCollector->Add(cast<FieldDecl>(Anon));
1491  } else {
1492    VarDecl::StorageClass SC;
1493    switch (DS.getStorageClassSpec()) {
1494    default: assert(0 && "Unknown storage class!");
1495    case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
1496    case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
1497    case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
1498    case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
1499    case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
1500    case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1501    case DeclSpec::SCS_mutable:
1502      // mutable can only appear on non-static class members, so it's always
1503      // an error here
1504      Diag(Record->getLocation(), diag::err_mutable_nonmember);
1505      Invalid = true;
1506      SC = VarDecl::None;
1507      break;
1508    }
1509
1510    Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
1511                           /*IdentifierInfo=*/0,
1512                           Context.getTypeDeclType(Record),
1513                           SC, DS.getSourceRange().getBegin());
1514  }
1515  Anon->setImplicit();
1516
1517  // Add the anonymous struct/union object to the current
1518  // context. We'll be referencing this object when we refer to one of
1519  // its members.
1520  Owner->addDecl(Anon);
1521
1522  // Inject the members of the anonymous struct/union into the owning
1523  // context and into the identifier resolver chain for name lookup
1524  // purposes.
1525  if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
1526    Invalid = true;
1527
1528  // Mark this as an anonymous struct/union type. Note that we do not
1529  // do this until after we have already checked and injected the
1530  // members of this anonymous struct/union type, because otherwise
1531  // the members could be injected twice: once by DeclContext when it
1532  // builds its lookup table, and once by
1533  // InjectAnonymousStructOrUnionMembers.
1534  Record->setAnonymousStructOrUnion(true);
1535
1536  if (Invalid)
1537    Anon->setInvalidDecl();
1538
1539  return DeclPtrTy::make(Anon);
1540}
1541
1542
1543/// GetNameForDeclarator - Determine the full declaration name for the
1544/// given Declarator.
1545DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1546  switch (D.getKind()) {
1547  case Declarator::DK_Abstract:
1548    assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1549    return DeclarationName();
1550
1551  case Declarator::DK_Normal:
1552    assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1553    return DeclarationName(D.getIdentifier());
1554
1555  case Declarator::DK_Constructor: {
1556    QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1557    Ty = Context.getCanonicalType(Ty);
1558    return Context.DeclarationNames.getCXXConstructorName(Ty);
1559  }
1560
1561  case Declarator::DK_Destructor: {
1562    QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1563    Ty = Context.getCanonicalType(Ty);
1564    return Context.DeclarationNames.getCXXDestructorName(Ty);
1565  }
1566
1567  case Declarator::DK_Conversion: {
1568    // FIXME: We'd like to keep the non-canonical type for diagnostics!
1569    QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1570    Ty = Context.getCanonicalType(Ty);
1571    return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1572  }
1573
1574  case Declarator::DK_Operator:
1575    assert(D.getIdentifier() == 0 && "operator names have no identifier");
1576    return Context.DeclarationNames.getCXXOperatorName(
1577                                                D.getOverloadedOperator());
1578  }
1579
1580  assert(false && "Unknown name kind");
1581  return DeclarationName();
1582}
1583
1584/// isNearlyMatchingFunction - Determine whether the C++ functions
1585/// Declaration and Definition are "nearly" matching. This heuristic
1586/// is used to improve diagnostics in the case where an out-of-line
1587/// function definition doesn't match any declaration within
1588/// the class or namespace.
1589static bool isNearlyMatchingFunction(ASTContext &Context,
1590                                     FunctionDecl *Declaration,
1591                                     FunctionDecl *Definition) {
1592  if (Declaration->param_size() != Definition->param_size())
1593    return false;
1594  for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1595    QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1596    QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1597
1598    DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1599    DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1600    if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1601      return false;
1602  }
1603
1604  return true;
1605}
1606
1607Sema::DeclPtrTy
1608Sema::HandleDeclarator(Scope *S, Declarator &D,
1609                       MultiTemplateParamsArg TemplateParamLists,
1610                       bool IsFunctionDefinition) {
1611  DeclarationName Name = GetNameForDeclarator(D);
1612
1613  // All of these full declarators require an identifier.  If it doesn't have
1614  // one, the ParsedFreeStandingDeclSpec action should be used.
1615  if (!Name) {
1616    if (!D.isInvalidType())  // Reject this if we think it is valid.
1617      Diag(D.getDeclSpec().getSourceRange().getBegin(),
1618           diag::err_declarator_need_ident)
1619        << D.getDeclSpec().getSourceRange() << D.getSourceRange();
1620    return DeclPtrTy();
1621  }
1622
1623  // The scope passed in may not be a decl scope.  Zip up the scope tree until
1624  // we find one that is.
1625  while ((S->getFlags() & Scope::DeclScope) == 0 ||
1626         (S->getFlags() & Scope::TemplateParamScope) != 0)
1627    S = S->getParent();
1628
1629  DeclContext *DC;
1630  NamedDecl *PrevDecl;
1631  NamedDecl *New;
1632
1633  QualType R = GetTypeForDeclarator(D, S);
1634
1635  // See if this is a redefinition of a variable in the same scope.
1636  if (D.getCXXScopeSpec().isInvalid()) {
1637    DC = CurContext;
1638    PrevDecl = 0;
1639    D.setInvalidType();
1640  } else if (!D.getCXXScopeSpec().isSet()) {
1641    LookupNameKind NameKind = LookupOrdinaryName;
1642
1643    // If the declaration we're planning to build will be a function
1644    // or object with linkage, then look for another declaration with
1645    // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
1646    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1647      /* Do nothing*/;
1648    else if (R->isFunctionType()) {
1649      if (CurContext->isFunctionOrMethod() ||
1650          D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
1651        NameKind = LookupRedeclarationWithLinkage;
1652    } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
1653      NameKind = LookupRedeclarationWithLinkage;
1654    else if (CurContext->getLookupContext()->isTranslationUnit() &&
1655             D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
1656      NameKind = LookupRedeclarationWithLinkage;
1657
1658    DC = CurContext;
1659    PrevDecl = LookupName(S, Name, NameKind, true,
1660                          NameKind == LookupRedeclarationWithLinkage,
1661                          D.getIdentifierLoc());
1662  } else { // Something like "int foo::x;"
1663    DC = computeDeclContext(D.getCXXScopeSpec(), true);
1664    // FIXME: RequireCompleteDeclContext(D.getCXXScopeSpec()); ?
1665    PrevDecl = LookupQualifiedName(DC, Name, LookupOrdinaryName, true);
1666
1667    // C++ 7.3.1.2p2:
1668    // Members (including explicit specializations of templates) of a named
1669    // namespace can also be defined outside that namespace by explicit
1670    // qualification of the name being defined, provided that the entity being
1671    // defined was already declared in the namespace and the definition appears
1672    // after the point of declaration in a namespace that encloses the
1673    // declarations namespace.
1674    //
1675    // Note that we only check the context at this point. We don't yet
1676    // have enough information to make sure that PrevDecl is actually
1677    // the declaration we want to match. For example, given:
1678    //
1679    //   class X {
1680    //     void f();
1681    //     void f(float);
1682    //   };
1683    //
1684    //   void X::f(int) { } // ill-formed
1685    //
1686    // In this case, PrevDecl will point to the overload set
1687    // containing the two f's declared in X, but neither of them
1688    // matches.
1689
1690    // First check whether we named the global scope.
1691    if (isa<TranslationUnitDecl>(DC)) {
1692      Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
1693        << Name << D.getCXXScopeSpec().getRange();
1694    } else if (!CurContext->Encloses(DC)) {
1695      // The qualifying scope doesn't enclose the original declaration.
1696      // Emit diagnostic based on current scope.
1697      SourceLocation L = D.getIdentifierLoc();
1698      SourceRange R = D.getCXXScopeSpec().getRange();
1699      if (isa<FunctionDecl>(CurContext))
1700        Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
1701      else
1702        Diag(L, diag::err_invalid_declarator_scope)
1703          << Name << cast<NamedDecl>(DC) << R;
1704      D.setInvalidType();
1705    }
1706  }
1707
1708  if (PrevDecl && PrevDecl->isTemplateParameter()) {
1709    // Maybe we will complain about the shadowed template parameter.
1710    if (!D.isInvalidType())
1711      if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl))
1712        D.setInvalidType();
1713
1714    // Just pretend that we didn't see the previous declaration.
1715    PrevDecl = 0;
1716  }
1717
1718  // In C++, the previous declaration we find might be a tag type
1719  // (class or enum). In this case, the new declaration will hide the
1720  // tag type. Note that this does does not apply if we're declaring a
1721  // typedef (C++ [dcl.typedef]p4).
1722  if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag &&
1723      D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
1724    PrevDecl = 0;
1725
1726  bool Redeclaration = false;
1727  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
1728    if (TemplateParamLists.size()) {
1729      Diag(D.getIdentifierLoc(), diag::err_template_typedef);
1730      return DeclPtrTy();
1731    }
1732
1733    New = ActOnTypedefDeclarator(S, D, DC, R, PrevDecl, Redeclaration);
1734  } else if (R->isFunctionType()) {
1735    New = ActOnFunctionDeclarator(S, D, DC, R, PrevDecl,
1736                                  move(TemplateParamLists),
1737                                  IsFunctionDefinition, Redeclaration);
1738  } else {
1739    New = ActOnVariableDeclarator(S, D, DC, R, PrevDecl,
1740                                  move(TemplateParamLists),
1741                                  Redeclaration);
1742  }
1743
1744  if (New == 0)
1745    return DeclPtrTy();
1746
1747  // If this has an identifier and is not an invalid redeclaration,
1748  // add it to the scope stack.
1749  if (Name && !(Redeclaration && New->isInvalidDecl()))
1750    PushOnScopeChains(New, S);
1751
1752  return DeclPtrTy::make(New);
1753}
1754
1755/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
1756/// types into constant array types in certain situations which would otherwise
1757/// be errors (for GCC compatibility).
1758static QualType TryToFixInvalidVariablyModifiedType(QualType T,
1759                                                    ASTContext &Context,
1760                                                    bool &SizeIsNegative) {
1761  // This method tries to turn a variable array into a constant
1762  // array even when the size isn't an ICE.  This is necessary
1763  // for compatibility with code that depends on gcc's buggy
1764  // constant expression folding, like struct {char x[(int)(char*)2];}
1765  SizeIsNegative = false;
1766
1767  if (const PointerType* PTy = dyn_cast<PointerType>(T)) {
1768    QualType Pointee = PTy->getPointeeType();
1769    QualType FixedType =
1770        TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative);
1771    if (FixedType.isNull()) return FixedType;
1772    FixedType = Context.getPointerType(FixedType);
1773    FixedType.setCVRQualifiers(T.getCVRQualifiers());
1774    return FixedType;
1775  }
1776
1777  const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
1778  if (!VLATy)
1779    return QualType();
1780  // FIXME: We should probably handle this case
1781  if (VLATy->getElementType()->isVariablyModifiedType())
1782    return QualType();
1783
1784  Expr::EvalResult EvalResult;
1785  if (!VLATy->getSizeExpr() ||
1786      !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) ||
1787      !EvalResult.Val.isInt())
1788    return QualType();
1789
1790  llvm::APSInt &Res = EvalResult.Val.getInt();
1791  if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned())) {
1792    Expr* ArySizeExpr = VLATy->getSizeExpr();
1793    // FIXME: here we could "steal" (how?) ArySizeExpr from the VLA,
1794    // so as to transfer ownership to the ConstantArrayWithExpr.
1795    // Alternatively, we could "clone" it (how?).
1796    // Since we don't know how to do things above, we just use the
1797    // very same Expr*.
1798    return Context.getConstantArrayWithExprType(VLATy->getElementType(),
1799                                                Res, ArySizeExpr,
1800                                                ArrayType::Normal, 0,
1801                                                VLATy->getBracketsRange());
1802  }
1803
1804  SizeIsNegative = true;
1805  return QualType();
1806}
1807
1808/// \brief Register the given locally-scoped external C declaration so
1809/// that it can be found later for redeclarations
1810void
1811Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, NamedDecl *PrevDecl,
1812                                       Scope *S) {
1813  assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
1814         "Decl is not a locally-scoped decl!");
1815  // Note that we have a locally-scoped external with this name.
1816  LocallyScopedExternalDecls[ND->getDeclName()] = ND;
1817
1818  if (!PrevDecl)
1819    return;
1820
1821  // If there was a previous declaration of this variable, it may be
1822  // in our identifier chain. Update the identifier chain with the new
1823  // declaration.
1824  if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
1825    // The previous declaration was found on the identifer resolver
1826    // chain, so remove it from its scope.
1827    while (S && !S->isDeclScope(DeclPtrTy::make(PrevDecl)))
1828      S = S->getParent();
1829
1830    if (S)
1831      S->RemoveDecl(DeclPtrTy::make(PrevDecl));
1832  }
1833}
1834
1835/// \brief Diagnose function specifiers on a declaration of an identifier that
1836/// does not identify a function.
1837void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
1838  // FIXME: We should probably indicate the identifier in question to avoid
1839  // confusion for constructs like "inline int a(), b;"
1840  if (D.getDeclSpec().isInlineSpecified())
1841    Diag(D.getDeclSpec().getInlineSpecLoc(),
1842         diag::err_inline_non_function);
1843
1844  if (D.getDeclSpec().isVirtualSpecified())
1845    Diag(D.getDeclSpec().getVirtualSpecLoc(),
1846         diag::err_virtual_non_function);
1847
1848  if (D.getDeclSpec().isExplicitSpecified())
1849    Diag(D.getDeclSpec().getExplicitSpecLoc(),
1850         diag::err_explicit_non_function);
1851}
1852
1853NamedDecl*
1854Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1855                             QualType R, Decl* PrevDecl, bool &Redeclaration) {
1856  // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1857  if (D.getCXXScopeSpec().isSet()) {
1858    Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1859      << D.getCXXScopeSpec().getRange();
1860    D.setInvalidType();
1861    // Pretend we didn't see the scope specifier.
1862    DC = 0;
1863  }
1864
1865  if (getLangOptions().CPlusPlus) {
1866    // Check that there are no default arguments (C++ only).
1867    CheckExtraCXXDefaultArguments(D);
1868  }
1869
1870  DiagnoseFunctionSpecifiers(D);
1871
1872  if (D.getDeclSpec().isThreadSpecified())
1873    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
1874
1875  TypedefDecl *NewTD = ParseTypedefDecl(S, D, R);
1876  if (!NewTD) return 0;
1877
1878  if (D.isInvalidType())
1879    NewTD->setInvalidDecl();
1880
1881  // Handle attributes prior to checking for duplicates in MergeVarDecl
1882  ProcessDeclAttributes(S, NewTD, D);
1883  // Merge the decl with the existing one if appropriate. If the decl is
1884  // in an outer scope, it isn't the same thing.
1885  if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1886    Redeclaration = true;
1887    MergeTypeDefDecl(NewTD, PrevDecl);
1888  }
1889
1890  // C99 6.7.7p2: If a typedef name specifies a variably modified type
1891  // then it shall have block scope.
1892  QualType T = NewTD->getUnderlyingType();
1893  if (T->isVariablyModifiedType()) {
1894    CurFunctionNeedsScopeChecking = true;
1895
1896    if (S->getFnParent() == 0) {
1897      bool SizeIsNegative;
1898      QualType FixedTy =
1899          TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
1900      if (!FixedTy.isNull()) {
1901        Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size);
1902        NewTD->setUnderlyingType(FixedTy);
1903      } else {
1904        if (SizeIsNegative)
1905          Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size);
1906        else if (T->isVariableArrayType())
1907          Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1908        else
1909          Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1910        NewTD->setInvalidDecl();
1911      }
1912    }
1913  }
1914
1915  // If this is the C FILE type, notify the AST context.
1916  if (IdentifierInfo *II = NewTD->getIdentifier())
1917    if (!NewTD->isInvalidDecl() &&
1918        NewTD->getDeclContext()->getLookupContext()->isTranslationUnit()) {
1919      if (II->isStr("FILE"))
1920        Context.setFILEDecl(NewTD);
1921      else if (II->isStr("jmp_buf"))
1922        Context.setjmp_bufDecl(NewTD);
1923      else if (II->isStr("sigjmp_buf"))
1924        Context.setsigjmp_bufDecl(NewTD);
1925    }
1926
1927  return NewTD;
1928}
1929
1930/// \brief Determines whether the given declaration is an out-of-scope
1931/// previous declaration.
1932///
1933/// This routine should be invoked when name lookup has found a
1934/// previous declaration (PrevDecl) that is not in the scope where a
1935/// new declaration by the same name is being introduced. If the new
1936/// declaration occurs in a local scope, previous declarations with
1937/// linkage may still be considered previous declarations (C99
1938/// 6.2.2p4-5, C++ [basic.link]p6).
1939///
1940/// \param PrevDecl the previous declaration found by name
1941/// lookup
1942///
1943/// \param DC the context in which the new declaration is being
1944/// declared.
1945///
1946/// \returns true if PrevDecl is an out-of-scope previous declaration
1947/// for a new delcaration with the same name.
1948static bool
1949isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
1950                                ASTContext &Context) {
1951  if (!PrevDecl)
1952    return 0;
1953
1954  // FIXME: PrevDecl could be an OverloadedFunctionDecl, in which
1955  // case we need to check each of the overloaded functions.
1956  if (!PrevDecl->hasLinkage())
1957    return false;
1958
1959  if (Context.getLangOptions().CPlusPlus) {
1960    // C++ [basic.link]p6:
1961    //   If there is a visible declaration of an entity with linkage
1962    //   having the same name and type, ignoring entities declared
1963    //   outside the innermost enclosing namespace scope, the block
1964    //   scope declaration declares that same entity and receives the
1965    //   linkage of the previous declaration.
1966    DeclContext *OuterContext = DC->getLookupContext();
1967    if (!OuterContext->isFunctionOrMethod())
1968      // This rule only applies to block-scope declarations.
1969      return false;
1970    else {
1971      DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
1972      if (PrevOuterContext->isRecord())
1973        // We found a member function: ignore it.
1974        return false;
1975      else {
1976        // Find the innermost enclosing namespace for the new and
1977        // previous declarations.
1978        while (!OuterContext->isFileContext())
1979          OuterContext = OuterContext->getParent();
1980        while (!PrevOuterContext->isFileContext())
1981          PrevOuterContext = PrevOuterContext->getParent();
1982
1983        // The previous declaration is in a different namespace, so it
1984        // isn't the same function.
1985        if (OuterContext->getPrimaryContext() !=
1986            PrevOuterContext->getPrimaryContext())
1987          return false;
1988      }
1989    }
1990  }
1991
1992  return true;
1993}
1994
1995NamedDecl*
1996Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1997                              QualType R,NamedDecl* PrevDecl,
1998                              MultiTemplateParamsArg TemplateParamLists,
1999                              bool &Redeclaration) {
2000  DeclarationName Name = GetNameForDeclarator(D);
2001
2002  // Check that there are no default arguments (C++ only).
2003  if (getLangOptions().CPlusPlus)
2004    CheckExtraCXXDefaultArguments(D);
2005
2006  VarDecl *NewVD;
2007  VarDecl::StorageClass SC;
2008  switch (D.getDeclSpec().getStorageClassSpec()) {
2009  default: assert(0 && "Unknown storage class!");
2010  case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
2011  case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
2012  case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
2013  case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
2014  case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
2015  case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
2016  case DeclSpec::SCS_mutable:
2017    // mutable can only appear on non-static class members, so it's always
2018    // an error here
2019    Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
2020    D.setInvalidType();
2021    SC = VarDecl::None;
2022    break;
2023  }
2024
2025  IdentifierInfo *II = Name.getAsIdentifierInfo();
2026  if (!II) {
2027    Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
2028      << Name.getAsString();
2029    return 0;
2030  }
2031
2032  DiagnoseFunctionSpecifiers(D);
2033
2034  if (!DC->isRecord() && S->getFnParent() == 0) {
2035    // C99 6.9p2: The storage-class specifiers auto and register shall not
2036    // appear in the declaration specifiers in an external declaration.
2037    if (SC == VarDecl::Auto || SC == VarDecl::Register) {
2038
2039      // If this is a register variable with an asm label specified, then this
2040      // is a GNU extension.
2041      if (SC == VarDecl::Register && D.getAsmLabel())
2042        Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
2043      else
2044        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
2045      D.setInvalidType();
2046    }
2047  }
2048  if (DC->isRecord() && !CurContext->isRecord()) {
2049    // This is an out-of-line definition of a static data member.
2050    if (SC == VarDecl::Static) {
2051      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2052           diag::err_static_out_of_line)
2053        << CodeModificationHint::CreateRemoval(
2054                       SourceRange(D.getDeclSpec().getStorageClassSpecLoc()));
2055    } else if (SC == VarDecl::None)
2056      SC = VarDecl::Static;
2057  }
2058  if (SC == VarDecl::Static) {
2059    if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
2060      if (RD->isLocalClass())
2061        Diag(D.getIdentifierLoc(),
2062             diag::err_static_data_member_not_allowed_in_local_class)
2063          << Name << RD->getDeclName();
2064    }
2065  }
2066
2067  // Check that we can declare a template here.
2068  if (TemplateParamLists.size() &&
2069      CheckTemplateDeclScope(S, TemplateParamLists))
2070    return 0;
2071
2072  // Match up the template parameter lists with the scope specifier, then
2073  // determine whether we have a template or a template specialization.
2074  if (TemplateParameterList *TemplateParams
2075      = MatchTemplateParametersToScopeSpecifier(
2076                                  D.getDeclSpec().getSourceRange().getBegin(),
2077                                                D.getCXXScopeSpec(),
2078                        (TemplateParameterList**)TemplateParamLists.get(),
2079                                                 TemplateParamLists.size())) {
2080    if (TemplateParams->size() > 0) {
2081      // There is no such thing as a variable template.
2082      Diag(D.getIdentifierLoc(), diag::err_template_variable)
2083        << II
2084        << SourceRange(TemplateParams->getTemplateLoc(),
2085                       TemplateParams->getRAngleLoc());
2086      return 0;
2087    } else {
2088      // There is an extraneous 'template<>' for this variable. Complain
2089      // about it, but allow the declaration of the variable.
2090      Diag(TemplateParams->getTemplateLoc(),
2091           diag::err_template_variable_noparams)
2092        << II
2093        << SourceRange(TemplateParams->getTemplateLoc(),
2094                       TemplateParams->getRAngleLoc());
2095    }
2096  }
2097
2098  NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
2099                          II, R, SC,
2100                          // FIXME: Move to DeclGroup...
2101                          D.getDeclSpec().getSourceRange().getBegin());
2102
2103  if (D.isInvalidType())
2104    NewVD->setInvalidDecl();
2105
2106  if (D.getDeclSpec().isThreadSpecified()) {
2107    if (NewVD->hasLocalStorage())
2108      Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
2109    else if (!Context.Target.isTLSSupported())
2110      Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
2111    else
2112      NewVD->setThreadSpecified(true);
2113  }
2114
2115  // Set the lexical context. If the declarator has a C++ scope specifier, the
2116  // lexical context will be different from the semantic context.
2117  NewVD->setLexicalDeclContext(CurContext);
2118
2119  // Handle attributes prior to checking for duplicates in MergeVarDecl
2120  ProcessDeclAttributes(S, NewVD, D);
2121
2122  // Handle GNU asm-label extension (encoded as an attribute).
2123  if (Expr *E = (Expr*) D.getAsmLabel()) {
2124    // The parser guarantees this is a string.
2125    StringLiteral *SE = cast<StringLiteral>(E);
2126    NewVD->addAttr(::new (Context) AsmLabelAttr(std::string(SE->getStrData(),
2127                                                        SE->getByteLength())));
2128  }
2129
2130  // If name lookup finds a previous declaration that is not in the
2131  // same scope as the new declaration, this may still be an
2132  // acceptable redeclaration.
2133  if (PrevDecl && !isDeclInScope(PrevDecl, DC, S) &&
2134      !(NewVD->hasLinkage() &&
2135        isOutOfScopePreviousDeclaration(PrevDecl, DC, Context)))
2136    PrevDecl = 0;
2137
2138  // Merge the decl with the existing one if appropriate.
2139  if (PrevDecl) {
2140    if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
2141      // The user tried to define a non-static data member
2142      // out-of-line (C++ [dcl.meaning]p1).
2143      Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
2144        << D.getCXXScopeSpec().getRange();
2145      PrevDecl = 0;
2146      NewVD->setInvalidDecl();
2147    }
2148  } else if (D.getCXXScopeSpec().isSet()) {
2149    // No previous declaration in the qualifying scope.
2150    Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
2151      << Name << D.getCXXScopeSpec().getRange();
2152    NewVD->setInvalidDecl();
2153  }
2154
2155  CheckVariableDeclaration(NewVD, PrevDecl, Redeclaration);
2156
2157  // attributes declared post-definition are currently ignored
2158  if (PrevDecl) {
2159    const VarDecl *Def = 0, *PrevVD = dyn_cast<VarDecl>(PrevDecl);
2160    if (PrevVD->getDefinition(Def) && D.hasAttributes()) {
2161      Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
2162      Diag(Def->getLocation(), diag::note_previous_definition);
2163    }
2164  }
2165
2166  // If this is a locally-scoped extern C variable, update the map of
2167  // such variables.
2168  if (CurContext->isFunctionOrMethod() && NewVD->isExternC(Context) &&
2169      !NewVD->isInvalidDecl())
2170    RegisterLocallyScopedExternCDecl(NewVD, PrevDecl, S);
2171
2172  return NewVD;
2173}
2174
2175/// \brief Perform semantic checking on a newly-created variable
2176/// declaration.
2177///
2178/// This routine performs all of the type-checking required for a
2179/// variable declaration once it has been built. It is used both to
2180/// check variables after they have been parsed and their declarators
2181/// have been translated into a declaration, and to check variables
2182/// that have been instantiated from a template.
2183///
2184/// Sets NewVD->isInvalidDecl() if an error was encountered.
2185void Sema::CheckVariableDeclaration(VarDecl *NewVD, NamedDecl *PrevDecl,
2186                                    bool &Redeclaration) {
2187  // If the decl is already known invalid, don't check it.
2188  if (NewVD->isInvalidDecl())
2189    return;
2190
2191  QualType T = NewVD->getType();
2192
2193  if (T->isObjCInterfaceType()) {
2194    Diag(NewVD->getLocation(), diag::err_statically_allocated_object);
2195    return NewVD->setInvalidDecl();
2196  }
2197
2198  // The variable can not have an abstract class type.
2199  if (RequireNonAbstractType(NewVD->getLocation(), T,
2200                             diag::err_abstract_type_in_decl,
2201                             AbstractVariableType))
2202    return NewVD->setInvalidDecl();
2203
2204  // Emit an error if an address space was applied to decl with local storage.
2205  // This includes arrays of objects with address space qualifiers, but not
2206  // automatic variables that point to other address spaces.
2207  // ISO/IEC TR 18037 S5.1.2
2208  if (NewVD->hasLocalStorage() && (T.getAddressSpace() != 0)) {
2209    Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
2210    return NewVD->setInvalidDecl();
2211  }
2212
2213  if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
2214      && !NewVD->hasAttr<BlocksAttr>())
2215    Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
2216
2217  bool isVM = T->isVariablyModifiedType();
2218  if (isVM || NewVD->hasAttr<CleanupAttr>() ||
2219      NewVD->hasAttr<BlocksAttr>())
2220    CurFunctionNeedsScopeChecking = true;
2221
2222  if ((isVM && NewVD->hasLinkage()) ||
2223      (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
2224    bool SizeIsNegative;
2225    QualType FixedTy =
2226        TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
2227
2228    if (FixedTy.isNull() && T->isVariableArrayType()) {
2229      const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
2230      // FIXME: This won't give the correct result for
2231      // int a[10][n];
2232      SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
2233
2234      if (NewVD->isFileVarDecl())
2235        Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
2236        << SizeRange;
2237      else if (NewVD->getStorageClass() == VarDecl::Static)
2238        Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
2239        << SizeRange;
2240      else
2241        Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
2242        << SizeRange;
2243      return NewVD->setInvalidDecl();
2244    }
2245
2246    if (FixedTy.isNull()) {
2247      if (NewVD->isFileVarDecl())
2248        Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
2249      else
2250        Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
2251      return NewVD->setInvalidDecl();
2252    }
2253
2254    Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
2255    NewVD->setType(FixedTy);
2256  }
2257
2258  if (!PrevDecl && NewVD->isExternC(Context)) {
2259    // Since we did not find anything by this name and we're declaring
2260    // an extern "C" variable, look for a non-visible extern "C"
2261    // declaration with the same name.
2262    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
2263      = LocallyScopedExternalDecls.find(NewVD->getDeclName());
2264    if (Pos != LocallyScopedExternalDecls.end())
2265      PrevDecl = Pos->second;
2266  }
2267
2268  if (T->isVoidType() && !NewVD->hasExternalStorage()) {
2269    Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
2270      << T;
2271    return NewVD->setInvalidDecl();
2272  }
2273
2274  if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
2275    Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
2276    return NewVD->setInvalidDecl();
2277  }
2278
2279  if (isVM && NewVD->hasAttr<BlocksAttr>()) {
2280    Diag(NewVD->getLocation(), diag::err_block_on_vm);
2281    return NewVD->setInvalidDecl();
2282  }
2283
2284  if (PrevDecl) {
2285    Redeclaration = true;
2286    MergeVarDecl(NewVD, PrevDecl);
2287  }
2288}
2289
2290NamedDecl*
2291Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2292                              QualType R, NamedDecl* PrevDecl,
2293                              MultiTemplateParamsArg TemplateParamLists,
2294                              bool IsFunctionDefinition, bool &Redeclaration) {
2295  assert(R.getTypePtr()->isFunctionType());
2296
2297  DeclarationName Name = GetNameForDeclarator(D);
2298  FunctionDecl::StorageClass SC = FunctionDecl::None;
2299  switch (D.getDeclSpec().getStorageClassSpec()) {
2300  default: assert(0 && "Unknown storage class!");
2301  case DeclSpec::SCS_auto:
2302  case DeclSpec::SCS_register:
2303  case DeclSpec::SCS_mutable:
2304    Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2305         diag::err_typecheck_sclass_func);
2306    D.setInvalidType();
2307    break;
2308  case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
2309  case DeclSpec::SCS_extern:      SC = FunctionDecl::Extern; break;
2310  case DeclSpec::SCS_static: {
2311    if (CurContext->getLookupContext()->isFunctionOrMethod()) {
2312      // C99 6.7.1p5:
2313      //   The declaration of an identifier for a function that has
2314      //   block scope shall have no explicit storage-class specifier
2315      //   other than extern
2316      // See also (C++ [dcl.stc]p4).
2317      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2318           diag::err_static_block_func);
2319      SC = FunctionDecl::None;
2320    } else
2321      SC = FunctionDecl::Static;
2322    break;
2323  }
2324  case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
2325  }
2326
2327  if (D.getDeclSpec().isThreadSpecified())
2328    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2329
2330  bool isInline = D.getDeclSpec().isInlineSpecified();
2331  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
2332  bool isExplicit = D.getDeclSpec().isExplicitSpecified();
2333
2334  // Check that the return type is not an abstract class type.
2335  // For record types, this is done by the AbstractClassUsageDiagnoser once
2336  // the class has been completely parsed.
2337  if (!DC->isRecord() &&
2338      RequireNonAbstractType(D.getIdentifierLoc(),
2339                             R->getAsFunctionType()->getResultType(),
2340                             diag::err_abstract_type_in_decl,
2341                             AbstractReturnType))
2342    D.setInvalidType();
2343
2344  // Do not allow returning a objc interface by-value.
2345  if (R->getAsFunctionType()->getResultType()->isObjCInterfaceType()) {
2346    Diag(D.getIdentifierLoc(),
2347         diag::err_object_cannot_be_passed_returned_by_value) << 0
2348      << R->getAsFunctionType()->getResultType();
2349    D.setInvalidType();
2350  }
2351
2352  // Check that we can declare a template here.
2353  if (TemplateParamLists.size() &&
2354      CheckTemplateDeclScope(S, TemplateParamLists))
2355    return 0;
2356
2357  bool isVirtualOkay = false;
2358  FunctionDecl *NewFD;
2359  if (D.getKind() == Declarator::DK_Constructor) {
2360    // This is a C++ constructor declaration.
2361    assert(DC->isRecord() &&
2362           "Constructors can only be declared in a member context");
2363
2364    R = CheckConstructorDeclarator(D, R, SC);
2365
2366    // Create the new declaration
2367    NewFD = CXXConstructorDecl::Create(Context,
2368                                       cast<CXXRecordDecl>(DC),
2369                                       D.getIdentifierLoc(), Name, R,
2370                                       isExplicit, isInline,
2371                                       /*isImplicitlyDeclared=*/false);
2372  } else if (D.getKind() == Declarator::DK_Destructor) {
2373    // This is a C++ destructor declaration.
2374    if (DC->isRecord()) {
2375      R = CheckDestructorDeclarator(D, SC);
2376
2377      NewFD = CXXDestructorDecl::Create(Context,
2378                                        cast<CXXRecordDecl>(DC),
2379                                        D.getIdentifierLoc(), Name, R,
2380                                        isInline,
2381                                        /*isImplicitlyDeclared=*/false);
2382
2383      isVirtualOkay = true;
2384    } else {
2385      Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
2386
2387      // Create a FunctionDecl to satisfy the function definition parsing
2388      // code path.
2389      NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
2390                                   Name, R, SC, isInline,
2391                                   /*hasPrototype=*/true,
2392                                   // FIXME: Move to DeclGroup...
2393                                   D.getDeclSpec().getSourceRange().getBegin());
2394      D.setInvalidType();
2395    }
2396  } else if (D.getKind() == Declarator::DK_Conversion) {
2397    if (!DC->isRecord()) {
2398      Diag(D.getIdentifierLoc(),
2399           diag::err_conv_function_not_member);
2400      return 0;
2401    }
2402
2403    CheckConversionDeclarator(D, R, SC);
2404    NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
2405                                      D.getIdentifierLoc(), Name, R,
2406                                      isInline, isExplicit);
2407
2408    isVirtualOkay = true;
2409  } else if (DC->isRecord()) {
2410    // If the of the function is the same as the name of the record, then this
2411    // must be an invalid constructor that has a return type.
2412    // (The parser checks for a return type and makes the declarator a
2413    // constructor if it has no return type).
2414    // must have an invalid constructor that has a return type
2415    if (Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
2416      Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
2417        << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2418        << SourceRange(D.getIdentifierLoc());
2419      return 0;
2420    }
2421
2422    // This is a C++ method declaration.
2423    NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
2424                                  D.getIdentifierLoc(), Name, R,
2425                                  (SC == FunctionDecl::Static), isInline);
2426
2427    isVirtualOkay = (SC != FunctionDecl::Static);
2428  } else {
2429    // Determine whether the function was written with a
2430    // prototype. This true when:
2431    //   - we're in C++ (where every function has a prototype),
2432    //   - there is a prototype in the declarator, or
2433    //   - the type R of the function is some kind of typedef or other reference
2434    //     to a type name (which eventually refers to a function type).
2435    bool HasPrototype =
2436       getLangOptions().CPlusPlus ||
2437       (D.getNumTypeObjects() && D.getTypeObject(0).Fun.hasPrototype) ||
2438       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
2439
2440    NewFD = FunctionDecl::Create(Context, DC,
2441                                 D.getIdentifierLoc(),
2442                                 Name, R, SC, isInline, HasPrototype,
2443                                 // FIXME: Move to DeclGroup...
2444                                 D.getDeclSpec().getSourceRange().getBegin());
2445  }
2446
2447  if (D.isInvalidType())
2448    NewFD->setInvalidDecl();
2449
2450  // Set the lexical context. If the declarator has a C++
2451  // scope specifier, the lexical context will be different
2452  // from the semantic context.
2453  NewFD->setLexicalDeclContext(CurContext);
2454
2455  // Match up the template parameter lists with the scope specifier, then
2456  // determine whether we have a template or a template specialization.
2457  FunctionTemplateDecl *FunctionTemplate = 0;
2458  if (TemplateParameterList *TemplateParams
2459        = MatchTemplateParametersToScopeSpecifier(
2460                                  D.getDeclSpec().getSourceRange().getBegin(),
2461                                  D.getCXXScopeSpec(),
2462                           (TemplateParameterList**)TemplateParamLists.get(),
2463                                                  TemplateParamLists.size())) {
2464    if (TemplateParams->size() > 0) {
2465      // This is a function template
2466      FunctionTemplate = FunctionTemplateDecl::Create(Context, CurContext,
2467                                                      NewFD->getLocation(),
2468                                                      Name, TemplateParams,
2469                                                      NewFD);
2470      NewFD->setDescribedFunctionTemplate(FunctionTemplate);
2471    } else {
2472      // FIXME: Handle function template specializations
2473    }
2474
2475    // FIXME: Free this memory properly.
2476    TemplateParamLists.release();
2477  }
2478
2479  // C++ [dcl.fct.spec]p5:
2480  //   The virtual specifier shall only be used in declarations of
2481  //   nonstatic class member functions that appear within a
2482  //   member-specification of a class declaration; see 10.3.
2483  //
2484  if (isVirtual && !NewFD->isInvalidDecl()) {
2485    if (!isVirtualOkay) {
2486       Diag(D.getDeclSpec().getVirtualSpecLoc(),
2487           diag::err_virtual_non_function);
2488    } else if (!CurContext->isRecord()) {
2489      // 'virtual' was specified outside of the class.
2490      Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_out_of_class)
2491        << CodeModificationHint::CreateRemoval(
2492                             SourceRange(D.getDeclSpec().getVirtualSpecLoc()));
2493    } else {
2494      // Okay: Add virtual to the method.
2495      cast<CXXMethodDecl>(NewFD)->setVirtualAsWritten(true);
2496      CXXRecordDecl *CurClass = cast<CXXRecordDecl>(DC);
2497      CurClass->setAggregate(false);
2498      CurClass->setPOD(false);
2499      CurClass->setPolymorphic(true);
2500      CurClass->setHasTrivialConstructor(false);
2501      CurClass->setHasTrivialCopyConstructor(false);
2502      CurClass->setHasTrivialCopyAssignment(false);
2503    }
2504  }
2505
2506  if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) {
2507    // Look for virtual methods in base classes that this method might override.
2508
2509    BasePaths Paths;
2510    if (LookupInBases(cast<CXXRecordDecl>(DC),
2511                      MemberLookupCriteria(NewMD), Paths)) {
2512      for (BasePaths::decl_iterator I = Paths.found_decls_begin(),
2513           E = Paths.found_decls_end(); I != E; ++I) {
2514        if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
2515          if (!CheckOverridingFunctionReturnType(NewMD, OldMD) &&
2516              !CheckOverridingFunctionExceptionSpec(NewMD, OldMD))
2517            NewMD->addOverriddenMethod(OldMD);
2518        }
2519      }
2520    }
2521  }
2522
2523  if (SC == FunctionDecl::Static && isa<CXXMethodDecl>(NewFD) &&
2524      !CurContext->isRecord()) {
2525    // C++ [class.static]p1:
2526    //   A data or function member of a class may be declared static
2527    //   in a class definition, in which case it is a static member of
2528    //   the class.
2529
2530    // Complain about the 'static' specifier if it's on an out-of-line
2531    // member function definition.
2532    Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2533         diag::err_static_out_of_line)
2534      << CodeModificationHint::CreateRemoval(
2535                      SourceRange(D.getDeclSpec().getStorageClassSpecLoc()));
2536  }
2537
2538  // Handle GNU asm-label extension (encoded as an attribute).
2539  if (Expr *E = (Expr*) D.getAsmLabel()) {
2540    // The parser guarantees this is a string.
2541    StringLiteral *SE = cast<StringLiteral>(E);
2542    NewFD->addAttr(::new (Context) AsmLabelAttr(std::string(SE->getStrData(),
2543                                                        SE->getByteLength())));
2544  }
2545
2546  // Copy the parameter declarations from the declarator D to the function
2547  // declaration NewFD, if they are available.  First scavenge them into Params.
2548  llvm::SmallVector<ParmVarDecl*, 16> Params;
2549  if (D.getNumTypeObjects() > 0) {
2550    DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2551
2552    // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
2553    // function that takes no arguments, not a function that takes a
2554    // single void argument.
2555    // We let through "const void" here because Sema::GetTypeForDeclarator
2556    // already checks for that case.
2557    if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2558        FTI.ArgInfo[0].Param &&
2559        FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()) {
2560      // Empty arg list, don't push any params.
2561      ParmVarDecl *Param = FTI.ArgInfo[0].Param.getAs<ParmVarDecl>();
2562
2563      // In C++, the empty parameter-type-list must be spelled "void"; a
2564      // typedef of void is not permitted.
2565      if (getLangOptions().CPlusPlus &&
2566          Param->getType().getUnqualifiedType() != Context.VoidTy)
2567        Diag(Param->getLocation(), diag::err_param_typedef_of_void);
2568      // FIXME: Leaks decl?
2569    } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
2570      for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
2571        ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
2572        assert(Param->getDeclContext() != NewFD && "Was set before ?");
2573        Param->setDeclContext(NewFD);
2574        Params.push_back(Param);
2575      }
2576    }
2577
2578  } else if (const FunctionProtoType *FT = R->getAsFunctionProtoType()) {
2579    // When we're declaring a function with a typedef, typeof, etc as in the
2580    // following example, we'll need to synthesize (unnamed)
2581    // parameters for use in the declaration.
2582    //
2583    // @code
2584    // typedef void fn(int);
2585    // fn f;
2586    // @endcode
2587
2588    // Synthesize a parameter for each argument type.
2589    for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
2590         AE = FT->arg_type_end(); AI != AE; ++AI) {
2591      ParmVarDecl *Param = ParmVarDecl::Create(Context, DC,
2592                                               SourceLocation(), 0,
2593                                               *AI, VarDecl::None, 0);
2594      Param->setImplicit();
2595      Params.push_back(Param);
2596    }
2597  } else {
2598    assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
2599           "Should not need args for typedef of non-prototype fn");
2600  }
2601  // Finally, we know we have the right number of parameters, install them.
2602  NewFD->setParams(Context, Params.data(), Params.size());
2603
2604  // If name lookup finds a previous declaration that is not in the
2605  // same scope as the new declaration, this may still be an
2606  // acceptable redeclaration.
2607  if (PrevDecl && !isDeclInScope(PrevDecl, DC, S) &&
2608      !(NewFD->hasLinkage() &&
2609        isOutOfScopePreviousDeclaration(PrevDecl, DC, Context)))
2610    PrevDecl = 0;
2611
2612  // Perform semantic checking on the function declaration.
2613  bool OverloadableAttrRequired = false; // FIXME: HACK!
2614  CheckFunctionDeclaration(NewFD, PrevDecl, Redeclaration,
2615                           /*FIXME:*/OverloadableAttrRequired);
2616
2617  if (D.getCXXScopeSpec().isSet() && !NewFD->isInvalidDecl()) {
2618    // An out-of-line member function declaration must also be a
2619    // definition (C++ [dcl.meaning]p1).
2620    if (!IsFunctionDefinition) {
2621      Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
2622        << D.getCXXScopeSpec().getRange();
2623      NewFD->setInvalidDecl();
2624    } else if (!Redeclaration && (!PrevDecl || !isa<UsingDecl>(PrevDecl))) {
2625      // The user tried to provide an out-of-line definition for a
2626      // function that is a member of a class or namespace, but there
2627      // was no such member function declared (C++ [class.mfct]p2,
2628      // C++ [namespace.memdef]p2). For example:
2629      //
2630      // class X {
2631      //   void f() const;
2632      // };
2633      //
2634      // void X::f() { } // ill-formed
2635      //
2636      // Complain about this problem, and attempt to suggest close
2637      // matches (e.g., those that differ only in cv-qualifiers and
2638      // whether the parameter types are references).
2639      Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
2640        << cast<NamedDecl>(DC) << D.getCXXScopeSpec().getRange();
2641      NewFD->setInvalidDecl();
2642
2643      LookupResult Prev = LookupQualifiedName(DC, Name, LookupOrdinaryName,
2644                                              true);
2645      assert(!Prev.isAmbiguous() &&
2646             "Cannot have an ambiguity in previous-declaration lookup");
2647      for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
2648           Func != FuncEnd; ++Func) {
2649        if (isa<FunctionDecl>(*Func) &&
2650            isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD))
2651          Diag((*Func)->getLocation(), diag::note_member_def_close_match);
2652      }
2653
2654      PrevDecl = 0;
2655    }
2656  }
2657
2658  // Handle attributes. We need to have merged decls when handling attributes
2659  // (for example to check for conflicts, etc).
2660  // FIXME: This needs to happen before we merge declarations. Then,
2661  // let attribute merging cope with attribute conflicts.
2662  ProcessDeclAttributes(S, NewFD, D);
2663
2664  // attributes declared post-definition are currently ignored
2665  if (PrevDecl) {
2666    const FunctionDecl *Def, *PrevFD = dyn_cast<FunctionDecl>(PrevDecl);
2667    if (PrevFD && PrevFD->getBody(Def) && D.hasAttributes()) {
2668      Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
2669      Diag(Def->getLocation(), diag::note_previous_definition);
2670    }
2671  }
2672
2673  AddKnownFunctionAttributes(NewFD);
2674
2675  if (OverloadableAttrRequired && !NewFD->getAttr<OverloadableAttr>()) {
2676    // If a function name is overloadable in C, then every function
2677    // with that name must be marked "overloadable".
2678    Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
2679      << Redeclaration << NewFD;
2680    if (PrevDecl)
2681      Diag(PrevDecl->getLocation(),
2682           diag::note_attribute_overloadable_prev_overload);
2683    NewFD->addAttr(::new (Context) OverloadableAttr());
2684  }
2685
2686  // If this is a locally-scoped extern C function, update the
2687  // map of such names.
2688  if (CurContext->isFunctionOrMethod() && NewFD->isExternC(Context)
2689      && !NewFD->isInvalidDecl())
2690    RegisterLocallyScopedExternCDecl(NewFD, PrevDecl, S);
2691
2692  // Set this FunctionDecl's range up to the right paren.
2693  NewFD->setLocEnd(D.getSourceRange().getEnd());
2694
2695  if (FunctionTemplate && NewFD->isInvalidDecl())
2696    FunctionTemplate->setInvalidDecl();
2697
2698  if (FunctionTemplate)
2699    return FunctionTemplate;
2700
2701  return NewFD;
2702}
2703
2704/// \brief Perform semantic checking of a new function declaration.
2705///
2706/// Performs semantic analysis of the new function declaration
2707/// NewFD. This routine performs all semantic checking that does not
2708/// require the actual declarator involved in the declaration, and is
2709/// used both for the declaration of functions as they are parsed
2710/// (called via ActOnDeclarator) and for the declaration of functions
2711/// that have been instantiated via C++ template instantiation (called
2712/// via InstantiateDecl).
2713///
2714/// This sets NewFD->isInvalidDecl() to true if there was an error.
2715void Sema::CheckFunctionDeclaration(FunctionDecl *NewFD, NamedDecl *&PrevDecl,
2716                                    bool &Redeclaration,
2717                                    bool &OverloadableAttrRequired) {
2718  // If NewFD is already known erroneous, don't do any of this checking.
2719  if (NewFD->isInvalidDecl())
2720    return;
2721
2722  if (NewFD->getResultType()->isVariablyModifiedType()) {
2723    // Functions returning a variably modified type violate C99 6.7.5.2p2
2724    // because all functions have linkage.
2725    Diag(NewFD->getLocation(), diag::err_vm_func_decl);
2726    return NewFD->setInvalidDecl();
2727  }
2728
2729  if (NewFD->isMain()) CheckMain(NewFD);
2730
2731  // Semantic checking for this function declaration (in isolation).
2732  if (getLangOptions().CPlusPlus) {
2733    // C++-specific checks.
2734    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
2735      CheckConstructor(Constructor);
2736    } else if (isa<CXXDestructorDecl>(NewFD)) {
2737      CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
2738      QualType ClassType = Context.getTypeDeclType(Record);
2739      if (!ClassType->isDependentType()) {
2740        ClassType = Context.getCanonicalType(ClassType);
2741        DeclarationName Name
2742          = Context.DeclarationNames.getCXXDestructorName(ClassType);
2743        if (NewFD->getDeclName() != Name) {
2744          Diag(NewFD->getLocation(), diag::err_destructor_name);
2745          return NewFD->setInvalidDecl();
2746        }
2747      }
2748      Record->setUserDeclaredDestructor(true);
2749      // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
2750      // user-defined destructor.
2751      Record->setPOD(false);
2752
2753      // C++ [class.dtor]p3: A destructor is trivial if it is an implicitly-
2754      // declared destructor.
2755      // FIXME: C++0x: don't do this for "= default" destructors
2756      Record->setHasTrivialDestructor(false);
2757    } else if (CXXConversionDecl *Conversion
2758               = dyn_cast<CXXConversionDecl>(NewFD))
2759      ActOnConversionDeclarator(Conversion);
2760
2761    // Extra checking for C++ overloaded operators (C++ [over.oper]).
2762    if (NewFD->isOverloadedOperator() &&
2763        CheckOverloadedOperatorDeclaration(NewFD))
2764      return NewFD->setInvalidDecl();
2765  }
2766
2767  // C99 6.7.4p6:
2768  //   [... ] For a function with external linkage, the following
2769  //   restrictions apply: [...] If all of the file scope declarations
2770  //   for a function in a translation unit include the inline
2771  //   function specifier without extern, then the definition in that
2772  //   translation unit is an inline definition. An inline definition
2773  //   does not provide an external definition for the function, and
2774  //   does not forbid an external definition in another translation
2775  //   unit.
2776  //
2777  // Here we determine whether this function, in isolation, would be a
2778  // C99 inline definition. MergeCompatibleFunctionDecls looks at
2779  // previous declarations.
2780  if (NewFD->isInline() && getLangOptions().C99 &&
2781      NewFD->getStorageClass() == FunctionDecl::None &&
2782      NewFD->getDeclContext()->getLookupContext()->isTranslationUnit())
2783    NewFD->setC99InlineDefinition(true);
2784
2785  // Check for a previous declaration of this name.
2786  if (!PrevDecl && NewFD->isExternC(Context)) {
2787    // Since we did not find anything by this name and we're declaring
2788    // an extern "C" function, look for a non-visible extern "C"
2789    // declaration with the same name.
2790    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
2791      = LocallyScopedExternalDecls.find(NewFD->getDeclName());
2792    if (Pos != LocallyScopedExternalDecls.end())
2793      PrevDecl = Pos->second;
2794  }
2795
2796  // Merge or overload the declaration with an existing declaration of
2797  // the same name, if appropriate.
2798  if (PrevDecl) {
2799    // Determine whether NewFD is an overload of PrevDecl or
2800    // a declaration that requires merging. If it's an overload,
2801    // there's no more work to do here; we'll just add the new
2802    // function to the scope.
2803    OverloadedFunctionDecl::function_iterator MatchedDecl;
2804
2805    if (!getLangOptions().CPlusPlus &&
2806        AllowOverloadingOfFunction(PrevDecl, Context)) {
2807      OverloadableAttrRequired = true;
2808
2809      // Functions marked "overloadable" must have a prototype (that
2810      // we can't get through declaration merging).
2811      if (!NewFD->getType()->getAsFunctionProtoType()) {
2812        Diag(NewFD->getLocation(), diag::err_attribute_overloadable_no_prototype)
2813          << NewFD;
2814        Redeclaration = true;
2815
2816        // Turn this into a variadic function with no parameters.
2817        QualType R = Context.getFunctionType(
2818                       NewFD->getType()->getAsFunctionType()->getResultType(),
2819                       0, 0, true, 0);
2820        NewFD->setType(R);
2821        return NewFD->setInvalidDecl();
2822      }
2823    }
2824
2825    if (PrevDecl &&
2826        (!AllowOverloadingOfFunction(PrevDecl, Context) ||
2827         !IsOverload(NewFD, PrevDecl, MatchedDecl)) &&
2828        !isa<UsingDecl>(PrevDecl)) {
2829      Redeclaration = true;
2830      Decl *OldDecl = PrevDecl;
2831
2832      // If PrevDecl was an overloaded function, extract the
2833      // FunctionDecl that matched.
2834      if (isa<OverloadedFunctionDecl>(PrevDecl))
2835        OldDecl = *MatchedDecl;
2836
2837      // NewFD and OldDecl represent declarations that need to be
2838      // merged.
2839      if (MergeFunctionDecl(NewFD, OldDecl))
2840        return NewFD->setInvalidDecl();
2841
2842      if (FunctionTemplateDecl *OldTemplateDecl
2843            = dyn_cast<FunctionTemplateDecl>(OldDecl))
2844        NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
2845      else {
2846        if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
2847          NewFD->setAccess(OldDecl->getAccess());
2848        NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
2849      }
2850    }
2851  }
2852
2853  // In C++, check default arguments now that we have merged decls. Unless
2854  // the lexical context is the class, because in this case this is done
2855  // during delayed parsing anyway.
2856  if (getLangOptions().CPlusPlus && !CurContext->isRecord())
2857    CheckCXXDefaultArguments(NewFD);
2858}
2859
2860void Sema::CheckMain(FunctionDecl* FD) {
2861  // C++ [basic.start.main]p3:  A program that declares main to be inline
2862  //   or static is ill-formed.
2863  // C99 6.7.4p4:  In a hosted environment, the inline function specifier
2864  //   shall not appear in a declaration of main.
2865  // static main is not an error under C99, but we should warn about it.
2866  bool isInline = FD->isInline();
2867  bool isStatic = FD->getStorageClass() == FunctionDecl::Static;
2868  if (isInline || isStatic) {
2869    unsigned diagID = diag::warn_unusual_main_decl;
2870    if (isInline || getLangOptions().CPlusPlus)
2871      diagID = diag::err_unusual_main_decl;
2872
2873    int which = isStatic + (isInline << 1) - 1;
2874    Diag(FD->getLocation(), diagID) << which;
2875  }
2876
2877  QualType T = FD->getType();
2878  assert(T->isFunctionType() && "function decl is not of function type");
2879  const FunctionType* FT = T->getAsFunctionType();
2880
2881  if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
2882    // TODO: add a replacement fixit to turn the return type into 'int'.
2883    Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
2884    FD->setInvalidDecl(true);
2885  }
2886
2887  // Treat protoless main() as nullary.
2888  if (isa<FunctionNoProtoType>(FT)) return;
2889
2890  const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
2891  unsigned nparams = FTP->getNumArgs();
2892  assert(FD->getNumParams() == nparams);
2893
2894  if (nparams > 3) {
2895    Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
2896    FD->setInvalidDecl(true);
2897    nparams = 3;
2898  }
2899
2900  // FIXME: a lot of the following diagnostics would be improved
2901  // if we had some location information about types.
2902
2903  QualType CharPP =
2904    Context.getPointerType(Context.getPointerType(Context.CharTy));
2905  QualType Expected[] = { Context.IntTy, CharPP, CharPP };
2906
2907  for (unsigned i = 0; i < nparams; ++i) {
2908    QualType AT = FTP->getArgType(i);
2909
2910    bool mismatch = true;
2911
2912    if (Context.hasSameUnqualifiedType(AT, Expected[i]))
2913      mismatch = false;
2914    else if (Expected[i] == CharPP) {
2915      // As an extension, the following forms are okay:
2916      //   char const **
2917      //   char const * const *
2918      //   char * const *
2919
2920      QualifierSet qs;
2921      const PointerType* PT;
2922      if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
2923          (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
2924          (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
2925        qs.removeConst();
2926        mismatch = !qs.empty();
2927      }
2928    }
2929
2930    if (mismatch) {
2931      Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
2932      // TODO: suggest replacing given type with expected type
2933      FD->setInvalidDecl(true);
2934    }
2935  }
2936
2937  if (nparams == 1 && !FD->isInvalidDecl()) {
2938    Diag(FD->getLocation(), diag::warn_main_one_arg);
2939  }
2940}
2941
2942bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
2943  // FIXME: Need strict checking.  In C89, we need to check for
2944  // any assignment, increment, decrement, function-calls, or
2945  // commas outside of a sizeof.  In C99, it's the same list,
2946  // except that the aforementioned are allowed in unevaluated
2947  // expressions.  Everything else falls under the
2948  // "may accept other forms of constant expressions" exception.
2949  // (We never end up here for C++, so the constant expression
2950  // rules there don't matter.)
2951  if (Init->isConstantInitializer(Context))
2952    return false;
2953  Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
2954    << Init->getSourceRange();
2955  return true;
2956}
2957
2958void Sema::AddInitializerToDecl(DeclPtrTy dcl, FullExprArg init) {
2959  AddInitializerToDecl(dcl, init.release(), /*DirectInit=*/false);
2960}
2961
2962/// AddInitializerToDecl - Adds the initializer Init to the
2963/// declaration dcl. If DirectInit is true, this is C++ direct
2964/// initialization rather than copy initialization.
2965void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init, bool DirectInit) {
2966  Decl *RealDecl = dcl.getAs<Decl>();
2967  // If there is no declaration, there was an error parsing it.  Just ignore
2968  // the initializer.
2969  if (RealDecl == 0)
2970    return;
2971
2972  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
2973    // With declarators parsed the way they are, the parser cannot
2974    // distinguish between a normal initializer and a pure-specifier.
2975    // Thus this grotesque test.
2976    IntegerLiteral *IL;
2977    Expr *Init = static_cast<Expr *>(init.get());
2978    if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
2979        Context.getCanonicalType(IL->getType()) == Context.IntTy) {
2980      if (Method->isVirtualAsWritten()) {
2981        Method->setPure();
2982
2983        // A class is abstract if at least one function is pure virtual.
2984        cast<CXXRecordDecl>(CurContext)->setAbstract(true);
2985      } else if (!Method->isInvalidDecl()) {
2986        Diag(Method->getLocation(), diag::err_non_virtual_pure)
2987          << Method->getDeclName() << Init->getSourceRange();
2988        Method->setInvalidDecl();
2989      }
2990    } else {
2991      Diag(Method->getLocation(), diag::err_member_function_initialization)
2992        << Method->getDeclName() << Init->getSourceRange();
2993      Method->setInvalidDecl();
2994    }
2995    return;
2996  }
2997
2998  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2999  if (!VDecl) {
3000    if (getLangOptions().CPlusPlus &&
3001        RealDecl->getLexicalDeclContext()->isRecord() &&
3002        isa<NamedDecl>(RealDecl))
3003      Diag(RealDecl->getLocation(), diag::err_member_initialization)
3004        << cast<NamedDecl>(RealDecl)->getDeclName();
3005    else
3006      Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3007    RealDecl->setInvalidDecl();
3008    return;
3009  }
3010
3011  if (!VDecl->getType()->isArrayType() &&
3012      RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3013                          diag::err_typecheck_decl_incomplete_type)) {
3014    RealDecl->setInvalidDecl();
3015    return;
3016  }
3017
3018  const VarDecl *Def = 0;
3019  if (VDecl->getDefinition(Def)) {
3020    Diag(VDecl->getLocation(), diag::err_redefinition)
3021      << VDecl->getDeclName();
3022    Diag(Def->getLocation(), diag::note_previous_definition);
3023    VDecl->setInvalidDecl();
3024    return;
3025  }
3026
3027  // Take ownership of the expression, now that we're sure we have somewhere
3028  // to put it.
3029  Expr *Init = init.takeAs<Expr>();
3030  assert(Init && "missing initializer");
3031
3032  // Get the decls type and save a reference for later, since
3033  // CheckInitializerTypes may change it.
3034  QualType DclT = VDecl->getType(), SavT = DclT;
3035  if (VDecl->isBlockVarDecl()) {
3036    if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
3037      Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
3038      VDecl->setInvalidDecl();
3039    } else if (!VDecl->isInvalidDecl()) {
3040      if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
3041                                VDecl->getDeclName(), DirectInit))
3042        VDecl->setInvalidDecl();
3043
3044      // C++ 3.6.2p2, allow dynamic initialization of static initializers.
3045      // Don't check invalid declarations to avoid emitting useless diagnostics.
3046      if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
3047        if (VDecl->getStorageClass() == VarDecl::Static) // C99 6.7.8p4.
3048          CheckForConstantInitializer(Init, DclT);
3049      }
3050    }
3051  } else if (VDecl->isStaticDataMember() &&
3052             VDecl->getLexicalDeclContext()->isRecord()) {
3053    // This is an in-class initialization for a static data member, e.g.,
3054    //
3055    // struct S {
3056    //   static const int value = 17;
3057    // };
3058
3059    // Attach the initializer
3060    VDecl->setInit(Context, Init);
3061
3062    // C++ [class.mem]p4:
3063    //   A member-declarator can contain a constant-initializer only
3064    //   if it declares a static member (9.4) of const integral or
3065    //   const enumeration type, see 9.4.2.
3066    QualType T = VDecl->getType();
3067    if (!T->isDependentType() &&
3068        (!Context.getCanonicalType(T).isConstQualified() ||
3069         !T->isIntegralType())) {
3070      Diag(VDecl->getLocation(), diag::err_member_initialization)
3071        << VDecl->getDeclName() << Init->getSourceRange();
3072      VDecl->setInvalidDecl();
3073    } else {
3074      // C++ [class.static.data]p4:
3075      //   If a static data member is of const integral or const
3076      //   enumeration type, its declaration in the class definition
3077      //   can specify a constant-initializer which shall be an
3078      //   integral constant expression (5.19).
3079      if (!Init->isTypeDependent() &&
3080          !Init->getType()->isIntegralType()) {
3081        // We have a non-dependent, non-integral or enumeration type.
3082        Diag(Init->getSourceRange().getBegin(),
3083             diag::err_in_class_initializer_non_integral_type)
3084          << Init->getType() << Init->getSourceRange();
3085        VDecl->setInvalidDecl();
3086      } else if (!Init->isTypeDependent() && !Init->isValueDependent()) {
3087        // Check whether the expression is a constant expression.
3088        llvm::APSInt Value;
3089        SourceLocation Loc;
3090        if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) {
3091          Diag(Loc, diag::err_in_class_initializer_non_constant)
3092            << Init->getSourceRange();
3093          VDecl->setInvalidDecl();
3094        } else if (!VDecl->getType()->isDependentType())
3095          ImpCastExprToType(Init, VDecl->getType());
3096      }
3097    }
3098  } else if (VDecl->isFileVarDecl()) {
3099    if (VDecl->getStorageClass() == VarDecl::Extern)
3100      Diag(VDecl->getLocation(), diag::warn_extern_init);
3101    if (!VDecl->isInvalidDecl())
3102      if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
3103                                VDecl->getDeclName(), DirectInit))
3104        VDecl->setInvalidDecl();
3105
3106    // C++ 3.6.2p2, allow dynamic initialization of static initializers.
3107    // Don't check invalid declarations to avoid emitting useless diagnostics.
3108    if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
3109      // C99 6.7.8p4. All file scoped initializers need to be constant.
3110      CheckForConstantInitializer(Init, DclT);
3111    }
3112  }
3113  // If the type changed, it means we had an incomplete type that was
3114  // completed by the initializer. For example:
3115  //   int ary[] = { 1, 3, 5 };
3116  // "ary" transitions from a VariableArrayType to a ConstantArrayType.
3117  if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
3118    VDecl->setType(DclT);
3119    Init->setType(DclT);
3120  }
3121
3122  // Attach the initializer to the decl.
3123  VDecl->setInit(Context, Init);
3124
3125  // If the previous declaration of VDecl was a tentative definition,
3126  // remove it from the set of tentative definitions.
3127  if (VDecl->getPreviousDeclaration() &&
3128      VDecl->getPreviousDeclaration()->isTentativeDefinition(Context)) {
3129    llvm::DenseMap<DeclarationName, VarDecl *>::iterator Pos
3130      = TentativeDefinitions.find(VDecl->getDeclName());
3131    assert(Pos != TentativeDefinitions.end() &&
3132           "Unrecorded tentative definition?");
3133    TentativeDefinitions.erase(Pos);
3134  }
3135
3136  return;
3137}
3138
3139void Sema::ActOnUninitializedDecl(DeclPtrTy dcl,
3140                                  bool TypeContainsUndeducedAuto) {
3141  Decl *RealDecl = dcl.getAs<Decl>();
3142
3143  // If there is no declaration, there was an error parsing it. Just ignore it.
3144  if (RealDecl == 0)
3145    return;
3146
3147  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
3148    QualType Type = Var->getType();
3149
3150    // Record tentative definitions.
3151    if (Var->isTentativeDefinition(Context))
3152      TentativeDefinitions[Var->getDeclName()] = Var;
3153
3154    // C++ [dcl.init.ref]p3:
3155    //   The initializer can be omitted for a reference only in a
3156    //   parameter declaration (8.3.5), in the declaration of a
3157    //   function return type, in the declaration of a class member
3158    //   within its class declaration (9.2), and where the extern
3159    //   specifier is explicitly used.
3160    if (Type->isReferenceType() && !Var->hasExternalStorage()) {
3161      Diag(Var->getLocation(), diag::err_reference_var_requires_init)
3162        << Var->getDeclName()
3163        << SourceRange(Var->getLocation(), Var->getLocation());
3164      Var->setInvalidDecl();
3165      return;
3166    }
3167
3168    // C++0x [dcl.spec.auto]p3
3169    if (TypeContainsUndeducedAuto) {
3170      Diag(Var->getLocation(), diag::err_auto_var_requires_init)
3171        << Var->getDeclName() << Type;
3172      Var->setInvalidDecl();
3173      return;
3174    }
3175
3176    // C++ [dcl.init]p9:
3177    //
3178    //   If no initializer is specified for an object, and the object
3179    //   is of (possibly cv-qualified) non-POD class type (or array
3180    //   thereof), the object shall be default-initialized; if the
3181    //   object is of const-qualified type, the underlying class type
3182    //   shall have a user-declared default constructor.
3183    if (getLangOptions().CPlusPlus) {
3184      QualType InitType = Type;
3185      if (const ArrayType *Array = Context.getAsArrayType(Type))
3186        InitType = Array->getElementType();
3187      if ((!Var->hasExternalStorage() && !Var->isExternC(Context)) &&
3188          InitType->isRecordType() && !InitType->isDependentType()) {
3189        CXXRecordDecl *RD =
3190          cast<CXXRecordDecl>(InitType->getAs<RecordType>()->getDecl());
3191        CXXConstructorDecl *Constructor = 0;
3192        if (!RequireCompleteType(Var->getLocation(), InitType,
3193                                    diag::err_invalid_incomplete_type_use))
3194          Constructor
3195            = PerformInitializationByConstructor(InitType, 0, 0,
3196                                                 Var->getLocation(),
3197                                               SourceRange(Var->getLocation(),
3198                                                           Var->getLocation()),
3199                                                 Var->getDeclName(),
3200                                                 IK_Default);
3201        if (!Constructor)
3202          Var->setInvalidDecl();
3203        else {
3204          if (!RD->hasTrivialConstructor())
3205            InitializeVarWithConstructor(Var, Constructor, InitType, 0, 0);
3206          FinalizeVarWithDestructor(Var, InitType);
3207        }
3208      }
3209    }
3210
3211#if 0
3212    // FIXME: Temporarily disabled because we are not properly parsing
3213    // linkage specifications on declarations, e.g.,
3214    //
3215    //   extern "C" const CGPoint CGPointerZero;
3216    //
3217    // C++ [dcl.init]p9:
3218    //
3219    //     If no initializer is specified for an object, and the
3220    //     object is of (possibly cv-qualified) non-POD class type (or
3221    //     array thereof), the object shall be default-initialized; if
3222    //     the object is of const-qualified type, the underlying class
3223    //     type shall have a user-declared default
3224    //     constructor. Otherwise, if no initializer is specified for
3225    //     an object, the object and its subobjects, if any, have an
3226    //     indeterminate initial value; if the object or any of its
3227    //     subobjects are of const-qualified type, the program is
3228    //     ill-formed.
3229    //
3230    // This isn't technically an error in C, so we don't diagnose it.
3231    //
3232    // FIXME: Actually perform the POD/user-defined default
3233    // constructor check.
3234    if (getLangOptions().CPlusPlus &&
3235        Context.getCanonicalType(Type).isConstQualified() &&
3236        !Var->hasExternalStorage())
3237      Diag(Var->getLocation(),  diag::err_const_var_requires_init)
3238        << Var->getName()
3239        << SourceRange(Var->getLocation(), Var->getLocation());
3240#endif
3241  }
3242}
3243
3244Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
3245                                                   DeclPtrTy *Group,
3246                                                   unsigned NumDecls) {
3247  llvm::SmallVector<Decl*, 8> Decls;
3248
3249  if (DS.isTypeSpecOwned())
3250    Decls.push_back((Decl*)DS.getTypeRep());
3251
3252  for (unsigned i = 0; i != NumDecls; ++i)
3253    if (Decl *D = Group[i].getAs<Decl>())
3254      Decls.push_back(D);
3255
3256  // Perform semantic analysis that depends on having fully processed both
3257  // the declarator and initializer.
3258  for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
3259    VarDecl *IDecl = dyn_cast<VarDecl>(Decls[i]);
3260    if (!IDecl)
3261      continue;
3262    QualType T = IDecl->getType();
3263
3264    // Block scope. C99 6.7p7: If an identifier for an object is declared with
3265    // no linkage (C99 6.2.2p6), the type for the object shall be complete...
3266    if (IDecl->isBlockVarDecl() && !IDecl->hasExternalStorage()) {
3267      if (!IDecl->isInvalidDecl() &&
3268          RequireCompleteType(IDecl->getLocation(), T,
3269                              diag::err_typecheck_decl_incomplete_type))
3270        IDecl->setInvalidDecl();
3271    }
3272    // File scope. C99 6.9.2p2: A declaration of an identifier for an
3273    // object that has file scope without an initializer, and without a
3274    // storage-class specifier or with the storage-class specifier "static",
3275    // constitutes a tentative definition. Note: A tentative definition with
3276    // external linkage is valid (C99 6.2.2p5).
3277    if (IDecl->isTentativeDefinition(Context) && !IDecl->isInvalidDecl()) {
3278      if (const IncompleteArrayType *ArrayT
3279          = Context.getAsIncompleteArrayType(T)) {
3280        if (RequireCompleteType(IDecl->getLocation(),
3281                                ArrayT->getElementType(),
3282                                diag::err_illegal_decl_array_incomplete_type))
3283          IDecl->setInvalidDecl();
3284      } else if (IDecl->getStorageClass() == VarDecl::Static) {
3285        // C99 6.9.2p3: If the declaration of an identifier for an object is
3286        // a tentative definition and has internal linkage (C99 6.2.2p3), the
3287        // declared type shall not be an incomplete type.
3288        // NOTE: code such as the following
3289        //     static struct s;
3290        //     struct s { int a; };
3291        // is accepted by gcc. Hence here we issue a warning instead of
3292        // an error and we do not invalidate the static declaration.
3293        // NOTE: to avoid multiple warnings, only check the first declaration.
3294        if (IDecl->getPreviousDeclaration() == 0)
3295          RequireCompleteType(IDecl->getLocation(), T,
3296                              diag::ext_typecheck_decl_incomplete_type);
3297      }
3298    }
3299  }
3300  return DeclGroupPtrTy::make(DeclGroupRef::Create(Context,
3301                                                   Decls.data(), Decls.size()));
3302}
3303
3304
3305/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
3306/// to introduce parameters into function prototype scope.
3307Sema::DeclPtrTy
3308Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
3309  const DeclSpec &DS = D.getDeclSpec();
3310
3311  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
3312  VarDecl::StorageClass StorageClass = VarDecl::None;
3313  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
3314    StorageClass = VarDecl::Register;
3315  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
3316    Diag(DS.getStorageClassSpecLoc(),
3317         diag::err_invalid_storage_class_in_func_decl);
3318    D.getMutableDeclSpec().ClearStorageClassSpecs();
3319  }
3320
3321  if (D.getDeclSpec().isThreadSpecified())
3322    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
3323
3324  DiagnoseFunctionSpecifiers(D);
3325
3326  // Check that there are no default arguments inside the type of this
3327  // parameter (C++ only).
3328  if (getLangOptions().CPlusPlus)
3329    CheckExtraCXXDefaultArguments(D);
3330
3331  TagDecl *OwnedDecl = 0;
3332  QualType parmDeclType = GetTypeForDeclarator(D, S, /*Skip=*/0, &OwnedDecl);
3333
3334  if (getLangOptions().CPlusPlus && OwnedDecl && OwnedDecl->isDefinition()) {
3335    // C++ [dcl.fct]p6:
3336    //   Types shall not be defined in return or parameter types.
3337    Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type)
3338      << Context.getTypeDeclType(OwnedDecl);
3339  }
3340
3341  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
3342  // Can this happen for params?  We already checked that they don't conflict
3343  // among each other.  Here they can only shadow globals, which is ok.
3344  IdentifierInfo *II = D.getIdentifier();
3345  if (II) {
3346    if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
3347      if (PrevDecl->isTemplateParameter()) {
3348        // Maybe we will complain about the shadowed template parameter.
3349        DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
3350        // Just pretend that we didn't see the previous declaration.
3351        PrevDecl = 0;
3352      } else if (S->isDeclScope(DeclPtrTy::make(PrevDecl))) {
3353        Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
3354
3355        // Recover by removing the name
3356        II = 0;
3357        D.SetIdentifier(0, D.getIdentifierLoc());
3358      }
3359    }
3360  }
3361
3362  // Parameters can not be abstract class types.
3363  // For record types, this is done by the AbstractClassUsageDiagnoser once
3364  // the class has been completely parsed.
3365  if (!CurContext->isRecord() &&
3366      RequireNonAbstractType(D.getIdentifierLoc(), parmDeclType,
3367                             diag::err_abstract_type_in_decl,
3368                             AbstractParamType))
3369    D.setInvalidType(true);
3370
3371  QualType T = adjustParameterType(parmDeclType);
3372
3373  ParmVarDecl *New;
3374  if (T == parmDeclType) // parameter type did not need adjustment
3375    New = ParmVarDecl::Create(Context, CurContext,
3376                              D.getIdentifierLoc(), II,
3377                              parmDeclType, StorageClass,
3378                              0);
3379  else // keep track of both the adjusted and unadjusted types
3380    New = OriginalParmVarDecl::Create(Context, CurContext,
3381                                      D.getIdentifierLoc(), II, T,
3382                                      parmDeclType, StorageClass, 0);
3383
3384  if (D.isInvalidType())
3385    New->setInvalidDecl();
3386
3387  // Parameter declarators cannot be interface types. All ObjC objects are
3388  // passed by reference.
3389  if (T->isObjCInterfaceType()) {
3390    Diag(D.getIdentifierLoc(),
3391         diag::err_object_cannot_be_passed_returned_by_value) << 1 << T;
3392    New->setInvalidDecl();
3393  }
3394
3395  // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
3396  if (D.getCXXScopeSpec().isSet()) {
3397    Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
3398      << D.getCXXScopeSpec().getRange();
3399    New->setInvalidDecl();
3400  }
3401
3402  // Add the parameter declaration into this scope.
3403  S->AddDecl(DeclPtrTy::make(New));
3404  if (II)
3405    IdResolver.AddDecl(New);
3406
3407  ProcessDeclAttributes(S, New, D);
3408
3409  if (New->hasAttr<BlocksAttr>()) {
3410    Diag(New->getLocation(), diag::err_block_on_nonlocal);
3411  }
3412  return DeclPtrTy::make(New);
3413}
3414
3415void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
3416                                           SourceLocation LocAfterDecls) {
3417  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3418         "Not a function declarator!");
3419  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3420
3421  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
3422  // for a K&R function.
3423  if (!FTI.hasPrototype) {
3424    for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
3425      --i;
3426      if (FTI.ArgInfo[i].Param == 0) {
3427        std::string Code = "  int ";
3428        Code += FTI.ArgInfo[i].Ident->getName();
3429        Code += ";\n";
3430        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
3431          << FTI.ArgInfo[i].Ident
3432          << CodeModificationHint::CreateInsertion(LocAfterDecls, Code);
3433
3434        // Implicitly declare the argument as type 'int' for lack of a better
3435        // type.
3436        DeclSpec DS;
3437        const char* PrevSpec; // unused
3438        unsigned DiagID; // unused
3439        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
3440                           PrevSpec, DiagID);
3441        Declarator ParamD(DS, Declarator::KNRTypeListContext);
3442        ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
3443        FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
3444      }
3445    }
3446  }
3447}
3448
3449Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
3450                                              Declarator &D) {
3451  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3452  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3453         "Not a function declarator!");
3454  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3455
3456  if (FTI.hasPrototype) {
3457    // FIXME: Diagnose arguments without names in C.
3458  }
3459
3460  Scope *ParentScope = FnBodyScope->getParent();
3461
3462  DeclPtrTy DP = HandleDeclarator(ParentScope, D,
3463                                  MultiTemplateParamsArg(*this),
3464                                  /*IsFunctionDefinition=*/true);
3465  return ActOnStartOfFunctionDef(FnBodyScope, DP);
3466}
3467
3468Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclPtrTy D) {
3469  if (!D)
3470    return D;
3471  FunctionDecl *FD = cast<FunctionDecl>(D.getAs<Decl>());
3472
3473  CurFunctionNeedsScopeChecking = false;
3474
3475  // See if this is a redefinition.
3476  const FunctionDecl *Definition;
3477  if (FD->getBody(Definition)) {
3478    Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
3479    Diag(Definition->getLocation(), diag::note_previous_definition);
3480  }
3481
3482  // Builtin functions cannot be defined.
3483  if (unsigned BuiltinID = FD->getBuiltinID(Context)) {
3484    if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3485      Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
3486      FD->setInvalidDecl();
3487    }
3488  }
3489
3490  // The return type of a function definition must be complete
3491  // (C99 6.9.1p3, C++ [dcl.fct]p6).
3492  QualType ResultType = FD->getResultType();
3493  if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
3494      !FD->isInvalidDecl() &&
3495      RequireCompleteType(FD->getLocation(), ResultType,
3496                          diag::err_func_def_incomplete_result))
3497    FD->setInvalidDecl();
3498
3499  // GNU warning -Wmissing-prototypes:
3500  //   Warn if a global function is defined without a previous
3501  //   prototype declaration. This warning is issued even if the
3502  //   definition itself provides a prototype. The aim is to detect
3503  //   global functions that fail to be declared in header files.
3504  if (!FD->isInvalidDecl() && FD->isGlobal() && !isa<CXXMethodDecl>(FD) &&
3505      !FD->isMain()) {
3506    bool MissingPrototype = true;
3507    for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
3508         Prev; Prev = Prev->getPreviousDeclaration()) {
3509      // Ignore any declarations that occur in function or method
3510      // scope, because they aren't visible from the header.
3511      if (Prev->getDeclContext()->isFunctionOrMethod())
3512        continue;
3513
3514      MissingPrototype = !Prev->getType()->isFunctionProtoType();
3515      break;
3516    }
3517
3518    if (MissingPrototype)
3519      Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
3520  }
3521
3522  if (FnBodyScope)
3523    PushDeclContext(FnBodyScope, FD);
3524
3525  // Check the validity of our function parameters
3526  CheckParmsForFunctionDef(FD);
3527
3528  // Introduce our parameters into the function scope
3529  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
3530    ParmVarDecl *Param = FD->getParamDecl(p);
3531    Param->setOwningFunction(FD);
3532
3533    // If this has an identifier, add it to the scope stack.
3534    if (Param->getIdentifier() && FnBodyScope)
3535      PushOnScopeChains(Param, FnBodyScope);
3536  }
3537
3538  // Checking attributes of current function definition
3539  // dllimport attribute.
3540  if (FD->getAttr<DLLImportAttr>() &&
3541      (!FD->getAttr<DLLExportAttr>())) {
3542    // dllimport attribute cannot be applied to definition.
3543    if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
3544      Diag(FD->getLocation(),
3545           diag::err_attribute_can_be_applied_only_to_symbol_declaration)
3546        << "dllimport";
3547      FD->setInvalidDecl();
3548      return DeclPtrTy::make(FD);
3549    } else {
3550      // If a symbol previously declared dllimport is later defined, the
3551      // attribute is ignored in subsequent references, and a warning is
3552      // emitted.
3553      Diag(FD->getLocation(),
3554           diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
3555        << FD->getNameAsCString() << "dllimport";
3556    }
3557  }
3558  return DeclPtrTy::make(FD);
3559}
3560
3561Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg) {
3562  return ActOnFinishFunctionBody(D, move(BodyArg), false);
3563}
3564
3565Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg,
3566                                              bool IsInstantiation) {
3567  Decl *dcl = D.getAs<Decl>();
3568  Stmt *Body = BodyArg.takeAs<Stmt>();
3569  if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
3570    FD->setBody(Body);
3571    if (FD->isMain())
3572      // C and C++ allow for main to automagically return 0.
3573      // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
3574      FD->setHasImplicitReturnZero(true);
3575    else
3576      CheckFallThroughForFunctionDef(FD, Body);
3577
3578    if (!FD->isInvalidDecl())
3579      DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
3580
3581    // C++ [basic.def.odr]p2:
3582    //   [...] A virtual member function is used if it is not pure. [...]
3583    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
3584      if (Method->isVirtual() && !Method->isPure())
3585        MarkDeclarationReferenced(Method->getLocation(), Method);
3586
3587    assert(FD == getCurFunctionDecl() && "Function parsing confused");
3588  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
3589    assert(MD == getCurMethodDecl() && "Method parsing confused");
3590    MD->setBody(Body);
3591    CheckFallThroughForFunctionDef(MD, Body);
3592    MD->setEndLoc(Body->getLocEnd());
3593
3594    if (!MD->isInvalidDecl())
3595      DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
3596  } else {
3597    Body->Destroy(Context);
3598    return DeclPtrTy();
3599  }
3600  if (!IsInstantiation)
3601    PopDeclContext();
3602
3603  // Verify and clean out per-function state.
3604
3605  assert(&getLabelMap() == &FunctionLabelMap && "Didn't pop block right?");
3606
3607  // Check goto/label use.
3608  for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
3609       I = FunctionLabelMap.begin(), E = FunctionLabelMap.end(); I != E; ++I) {
3610    LabelStmt *L = I->second;
3611
3612    // Verify that we have no forward references left.  If so, there was a goto
3613    // or address of a label taken, but no definition of it.  Label fwd
3614    // definitions are indicated with a null substmt.
3615    if (L->getSubStmt() != 0)
3616      continue;
3617
3618    // Emit error.
3619    Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
3620
3621    // At this point, we have gotos that use the bogus label.  Stitch it into
3622    // the function body so that they aren't leaked and that the AST is well
3623    // formed.
3624    if (Body == 0) {
3625      // The whole function wasn't parsed correctly, just delete this.
3626      L->Destroy(Context);
3627      continue;
3628    }
3629
3630    // Otherwise, the body is valid: we want to stitch the label decl into the
3631    // function somewhere so that it is properly owned and so that the goto
3632    // has a valid target.  Do this by creating a new compound stmt with the
3633    // label in it.
3634
3635    // Give the label a sub-statement.
3636    L->setSubStmt(new (Context) NullStmt(L->getIdentLoc()));
3637
3638    CompoundStmt *Compound = isa<CXXTryStmt>(Body) ?
3639                               cast<CXXTryStmt>(Body)->getTryBlock() :
3640                               cast<CompoundStmt>(Body);
3641    std::vector<Stmt*> Elements(Compound->body_begin(), Compound->body_end());
3642    Elements.push_back(L);
3643    Compound->setStmts(Context, &Elements[0], Elements.size());
3644  }
3645  FunctionLabelMap.clear();
3646
3647  if (!Body) return D;
3648
3649  // Verify that that gotos and switch cases don't jump into scopes illegally.
3650  if (CurFunctionNeedsScopeChecking)
3651    DiagnoseInvalidJumps(Body);
3652
3653  // C++ constructors that have function-try-blocks can't have return
3654  // statements in the handlers of that block. (C++ [except.handle]p14)
3655  // Verify this.
3656  if (isa<CXXConstructorDecl>(dcl) && isa<CXXTryStmt>(Body))
3657    DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
3658
3659  if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl))
3660    Destructor->computeBaseOrMembersToDestroy(Context);
3661  return D;
3662}
3663
3664/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
3665/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
3666NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
3667                                          IdentifierInfo &II, Scope *S) {
3668  // Before we produce a declaration for an implicitly defined
3669  // function, see whether there was a locally-scoped declaration of
3670  // this name as a function or variable. If so, use that
3671  // (non-visible) declaration, and complain about it.
3672  llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
3673    = LocallyScopedExternalDecls.find(&II);
3674  if (Pos != LocallyScopedExternalDecls.end()) {
3675    Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
3676    Diag(Pos->second->getLocation(), diag::note_previous_declaration);
3677    return Pos->second;
3678  }
3679
3680  // Extension in C99.  Legal in C90, but warn about it.
3681  if (getLangOptions().C99)
3682    Diag(Loc, diag::ext_implicit_function_decl) << &II;
3683  else
3684    Diag(Loc, diag::warn_implicit_function_decl) << &II;
3685
3686  // FIXME: handle stuff like:
3687  // void foo() { extern float X(); }
3688  // void bar() { X(); }  <-- implicit decl for X in another scope.
3689
3690  // Set a Declarator for the implicit definition: int foo();
3691  const char *Dummy;
3692  DeclSpec DS;
3693  unsigned DiagID;
3694  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
3695  Error = Error; // Silence warning.
3696  assert(!Error && "Error setting up implicit decl!");
3697  Declarator D(DS, Declarator::BlockContext);
3698  D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
3699                                             0, 0, false, SourceLocation(),
3700                                             false, 0,0,0, Loc, D),
3701                SourceLocation());
3702  D.SetIdentifier(&II, Loc);
3703
3704  // Insert this function into translation-unit scope.
3705
3706  DeclContext *PrevDC = CurContext;
3707  CurContext = Context.getTranslationUnitDecl();
3708
3709  FunctionDecl *FD =
3710 dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D).getAs<Decl>());
3711  FD->setImplicit();
3712
3713  CurContext = PrevDC;
3714
3715  AddKnownFunctionAttributes(FD);
3716
3717  return FD;
3718}
3719
3720/// \brief Adds any function attributes that we know a priori based on
3721/// the declaration of this function.
3722///
3723/// These attributes can apply both to implicitly-declared builtins
3724/// (like __builtin___printf_chk) or to library-declared functions
3725/// like NSLog or printf.
3726void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
3727  if (FD->isInvalidDecl())
3728    return;
3729
3730  // If this is a built-in function, map its builtin attributes to
3731  // actual attributes.
3732  if (unsigned BuiltinID = FD->getBuiltinID(Context)) {
3733    // Handle printf-formatting attributes.
3734    unsigned FormatIdx;
3735    bool HasVAListArg;
3736    if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
3737      if (!FD->getAttr<FormatAttr>())
3738        FD->addAttr(::new (Context) FormatAttr("printf", FormatIdx + 1,
3739                                             HasVAListArg ? 0 : FormatIdx + 2));
3740    }
3741
3742    // Mark const if we don't care about errno and that is the only
3743    // thing preventing the function from being const. This allows
3744    // IRgen to use LLVM intrinsics for such functions.
3745    if (!getLangOptions().MathErrno &&
3746        Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
3747      if (!FD->getAttr<ConstAttr>())
3748        FD->addAttr(::new (Context) ConstAttr());
3749    }
3750
3751    if (Context.BuiltinInfo.isNoReturn(BuiltinID))
3752      FD->addAttr(::new (Context) NoReturnAttr());
3753  }
3754
3755  IdentifierInfo *Name = FD->getIdentifier();
3756  if (!Name)
3757    return;
3758  if ((!getLangOptions().CPlusPlus &&
3759       FD->getDeclContext()->isTranslationUnit()) ||
3760      (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
3761       cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
3762       LinkageSpecDecl::lang_c)) {
3763    // Okay: this could be a libc/libm/Objective-C function we know
3764    // about.
3765  } else
3766    return;
3767
3768  if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
3769    // FIXME: NSLog and NSLogv should be target specific
3770    if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
3771      // FIXME: We known better than our headers.
3772      const_cast<FormatAttr *>(Format)->setType("printf");
3773    } else
3774      FD->addAttr(::new (Context) FormatAttr("printf", 1,
3775                                             Name->isStr("NSLogv") ? 0 : 2));
3776  } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
3777    // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
3778    // target-specific builtins, perhaps?
3779    if (!FD->getAttr<FormatAttr>())
3780      FD->addAttr(::new (Context) FormatAttr("printf", 2,
3781                                             Name->isStr("vasprintf") ? 0 : 3));
3782  }
3783}
3784
3785TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T) {
3786  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
3787  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3788
3789  // Scope manipulation handled by caller.
3790  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
3791                                           D.getIdentifierLoc(),
3792                                           D.getIdentifier(),
3793                                           T);
3794
3795  if (TagType *TT = dyn_cast<TagType>(T)) {
3796    TagDecl *TD = TT->getDecl();
3797
3798    // If the TagDecl that the TypedefDecl points to is an anonymous decl
3799    // keep track of the TypedefDecl.
3800    if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
3801      TD->setTypedefForAnonDecl(NewTD);
3802  }
3803
3804  if (D.isInvalidType())
3805    NewTD->setInvalidDecl();
3806  return NewTD;
3807}
3808
3809
3810/// \brief Determine whether a tag with a given kind is acceptable
3811/// as a redeclaration of the given tag declaration.
3812///
3813/// \returns true if the new tag kind is acceptable, false otherwise.
3814bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
3815                                        TagDecl::TagKind NewTag,
3816                                        SourceLocation NewTagLoc,
3817                                        const IdentifierInfo &Name) {
3818  // C++ [dcl.type.elab]p3:
3819  //   The class-key or enum keyword present in the
3820  //   elaborated-type-specifier shall agree in kind with the
3821  //   declaration to which the name in theelaborated-type-specifier
3822  //   refers. This rule also applies to the form of
3823  //   elaborated-type-specifier that declares a class-name or
3824  //   friend class since it can be construed as referring to the
3825  //   definition of the class. Thus, in any
3826  //   elaborated-type-specifier, the enum keyword shall be used to
3827  //   refer to an enumeration (7.2), the union class-keyshall be
3828  //   used to refer to a union (clause 9), and either the class or
3829  //   struct class-key shall be used to refer to a class (clause 9)
3830  //   declared using the class or struct class-key.
3831  TagDecl::TagKind OldTag = Previous->getTagKind();
3832  if (OldTag == NewTag)
3833    return true;
3834
3835  if ((OldTag == TagDecl::TK_struct || OldTag == TagDecl::TK_class) &&
3836      (NewTag == TagDecl::TK_struct || NewTag == TagDecl::TK_class)) {
3837    // Warn about the struct/class tag mismatch.
3838    bool isTemplate = false;
3839    if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
3840      isTemplate = Record->getDescribedClassTemplate();
3841
3842    Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
3843      << (NewTag == TagDecl::TK_class)
3844      << isTemplate << &Name
3845      << CodeModificationHint::CreateReplacement(SourceRange(NewTagLoc),
3846                              OldTag == TagDecl::TK_class? "class" : "struct");
3847    Diag(Previous->getLocation(), diag::note_previous_use);
3848    return true;
3849  }
3850  return false;
3851}
3852
3853/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
3854/// former case, Name will be non-null.  In the later case, Name will be null.
3855/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
3856/// reference/declaration/definition of a tag.
3857Sema::DeclPtrTy Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3858                               SourceLocation KWLoc, const CXXScopeSpec &SS,
3859                               IdentifierInfo *Name, SourceLocation NameLoc,
3860                               AttributeList *Attr, AccessSpecifier AS,
3861                               MultiTemplateParamsArg TemplateParameterLists,
3862                               bool &OwnedDecl) {
3863  // If this is not a definition, it must have a name.
3864  assert((Name != 0 || TUK == TUK_Definition) &&
3865         "Nameless record must be a definition!");
3866
3867  OwnedDecl = false;
3868  TagDecl::TagKind Kind;
3869  switch (TagSpec) {
3870  default: assert(0 && "Unknown tag type!");
3871  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3872  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
3873  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
3874  case DeclSpec::TST_enum:   Kind = TagDecl::TK_enum; break;
3875  }
3876
3877  if (TUK != TUK_Reference) {
3878    if (TemplateParameterList *TemplateParams
3879          = MatchTemplateParametersToScopeSpecifier(KWLoc, SS,
3880                        (TemplateParameterList**)TemplateParameterLists.get(),
3881                                              TemplateParameterLists.size())) {
3882      if (TemplateParams->size() > 0) {
3883        // This is a declaration or definition of a class template (which may
3884        // be a member of another template).
3885        OwnedDecl = false;
3886        DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
3887                                               SS, Name, NameLoc, Attr,
3888                                               move(TemplateParameterLists),
3889                                               AS);
3890        return Result.get();
3891      } else {
3892        // FIXME: diagnose the extraneous 'template<>', once we recover
3893        // slightly better in ParseTemplate.cpp from bogus template
3894        // parameters.
3895      }
3896    }
3897  }
3898
3899  DeclContext *SearchDC = CurContext;
3900  DeclContext *DC = CurContext;
3901  NamedDecl *PrevDecl = 0;
3902
3903  bool Invalid = false;
3904
3905  if (Name && SS.isNotEmpty()) {
3906    // We have a nested-name tag ('struct foo::bar').
3907
3908    // Check for invalid 'foo::'.
3909    if (SS.isInvalid()) {
3910      Name = 0;
3911      goto CreateNewDecl;
3912    }
3913
3914    if (RequireCompleteDeclContext(SS))
3915      return DeclPtrTy::make((Decl *)0);
3916
3917    DC = computeDeclContext(SS, true);
3918    SearchDC = DC;
3919    // Look-up name inside 'foo::'.
3920    PrevDecl
3921      = dyn_cast_or_null<TagDecl>(
3922               LookupQualifiedName(DC, Name, LookupTagName, true).getAsDecl());
3923
3924    // A tag 'foo::bar' must already exist.
3925    if (PrevDecl == 0) {
3926      Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
3927      Name = 0;
3928      Invalid = true;
3929      goto CreateNewDecl;
3930    }
3931  } else if (Name) {
3932    // If this is a named struct, check to see if there was a previous forward
3933    // declaration or definition.
3934    // FIXME: We're looking into outer scopes here, even when we
3935    // shouldn't be. Doing so can result in ambiguities that we
3936    // shouldn't be diagnosing.
3937    LookupResult R = LookupName(S, Name, LookupTagName,
3938                                /*RedeclarationOnly=*/(TUK != TUK_Reference));
3939    if (R.isAmbiguous()) {
3940      DiagnoseAmbiguousLookup(R, Name, NameLoc);
3941      // FIXME: This is not best way to recover from case like:
3942      //
3943      // struct S s;
3944      //
3945      // causes needless "incomplete type" error later.
3946      Name = 0;
3947      PrevDecl = 0;
3948      Invalid = true;
3949    } else
3950      PrevDecl = R;
3951
3952    if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
3953      // FIXME: This makes sure that we ignore the contexts associated
3954      // with C structs, unions, and enums when looking for a matching
3955      // tag declaration or definition. See the similar lookup tweak
3956      // in Sema::LookupName; is there a better way to deal with this?
3957      while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
3958        SearchDC = SearchDC->getParent();
3959    }
3960  }
3961
3962  if (PrevDecl && PrevDecl->isTemplateParameter()) {
3963    // Maybe we will complain about the shadowed template parameter.
3964    DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
3965    // Just pretend that we didn't see the previous declaration.
3966    PrevDecl = 0;
3967  }
3968
3969  if (PrevDecl) {
3970    // Check whether the previous declaration is usable.
3971    (void)DiagnoseUseOfDecl(PrevDecl, NameLoc);
3972
3973    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
3974      // If this is a use of a previous tag, or if the tag is already declared
3975      // in the same scope (so that the definition/declaration completes or
3976      // rementions the tag), reuse the decl.
3977      if (TUK == TUK_Reference || isDeclInScope(PrevDecl, SearchDC, S)) {
3978        // Make sure that this wasn't declared as an enum and now used as a
3979        // struct or something similar.
3980        if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, KWLoc, *Name)) {
3981          bool SafeToContinue
3982            = (PrevTagDecl->getTagKind() != TagDecl::TK_enum &&
3983               Kind != TagDecl::TK_enum);
3984          if (SafeToContinue)
3985            Diag(KWLoc, diag::err_use_with_wrong_tag)
3986              << Name
3987              << CodeModificationHint::CreateReplacement(SourceRange(KWLoc),
3988                                                  PrevTagDecl->getKindName());
3989          else
3990            Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
3991          Diag(PrevDecl->getLocation(), diag::note_previous_use);
3992
3993          if (SafeToContinue)
3994            Kind = PrevTagDecl->getTagKind();
3995          else {
3996            // Recover by making this an anonymous redefinition.
3997            Name = 0;
3998            PrevDecl = 0;
3999            Invalid = true;
4000          }
4001        }
4002
4003        if (!Invalid) {
4004          // If this is a use, just return the declaration we found.
4005
4006          // FIXME: In the future, return a variant or some other clue
4007          // for the consumer of this Decl to know it doesn't own it.
4008          // For our current ASTs this shouldn't be a problem, but will
4009          // need to be changed with DeclGroups.
4010          if (TUK == TUK_Reference)
4011            return DeclPtrTy::make(PrevDecl);
4012
4013          // Diagnose attempts to redefine a tag.
4014          if (TUK == TUK_Definition) {
4015            if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
4016              Diag(NameLoc, diag::err_redefinition) << Name;
4017              Diag(Def->getLocation(), diag::note_previous_definition);
4018              // If this is a redefinition, recover by making this
4019              // struct be anonymous, which will make any later
4020              // references get the previous definition.
4021              Name = 0;
4022              PrevDecl = 0;
4023              Invalid = true;
4024            } else {
4025              // If the type is currently being defined, complain
4026              // about a nested redefinition.
4027              TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
4028              if (Tag->isBeingDefined()) {
4029                Diag(NameLoc, diag::err_nested_redefinition) << Name;
4030                Diag(PrevTagDecl->getLocation(),
4031                     diag::note_previous_definition);
4032                Name = 0;
4033                PrevDecl = 0;
4034                Invalid = true;
4035              }
4036            }
4037
4038            // Okay, this is definition of a previously declared or referenced
4039            // tag PrevDecl. We're going to create a new Decl for it.
4040          }
4041        }
4042        // If we get here we have (another) forward declaration or we
4043        // have a definition.  Just create a new decl.
4044      } else {
4045        // If we get here, this is a definition of a new tag type in a nested
4046        // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
4047        // new decl/type.  We set PrevDecl to NULL so that the entities
4048        // have distinct types.
4049        PrevDecl = 0;
4050      }
4051      // If we get here, we're going to create a new Decl. If PrevDecl
4052      // is non-NULL, it's a definition of the tag declared by
4053      // PrevDecl. If it's NULL, we have a new definition.
4054    } else {
4055      // PrevDecl is a namespace, template, or anything else
4056      // that lives in the IDNS_Tag identifier namespace.
4057      if (isDeclInScope(PrevDecl, SearchDC, S)) {
4058        // The tag name clashes with a namespace name, issue an error and
4059        // recover by making this tag be anonymous.
4060        Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
4061        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4062        Name = 0;
4063        PrevDecl = 0;
4064        Invalid = true;
4065      } else {
4066        // The existing declaration isn't relevant to us; we're in a
4067        // new scope, so clear out the previous declaration.
4068        PrevDecl = 0;
4069      }
4070    }
4071  } else if (TUK == TUK_Reference && SS.isEmpty() && Name &&
4072             (Kind != TagDecl::TK_enum || !getLangOptions().CPlusPlus)) {
4073    // C++ [basic.scope.pdecl]p5:
4074    //   -- for an elaborated-type-specifier of the form
4075    //
4076    //          class-key identifier
4077    //
4078    //      if the elaborated-type-specifier is used in the
4079    //      decl-specifier-seq or parameter-declaration-clause of a
4080    //      function defined in namespace scope, the identifier is
4081    //      declared as a class-name in the namespace that contains
4082    //      the declaration; otherwise, except as a friend
4083    //      declaration, the identifier is declared in the smallest
4084    //      non-class, non-function-prototype scope that contains the
4085    //      declaration.
4086    //
4087    // C99 6.7.2.3p8 has a similar (but not identical!) provision for
4088    // C structs and unions.
4089    //
4090    // GNU C also supports this behavior as part of its incomplete
4091    // enum types extension, while GNU C++ does not.
4092    //
4093    // Find the context where we'll be declaring the tag.
4094    // FIXME: We would like to maintain the current DeclContext as the
4095    // lexical context,
4096    while (SearchDC->isRecord())
4097      SearchDC = SearchDC->getParent();
4098
4099    // Find the scope where we'll be declaring the tag.
4100    while (S->isClassScope() ||
4101           (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
4102           ((S->getFlags() & Scope::DeclScope) == 0) ||
4103           (S->getEntity() &&
4104            ((DeclContext *)S->getEntity())->isTransparentContext()))
4105      S = S->getParent();
4106  }
4107
4108CreateNewDecl:
4109
4110  // If there is an identifier, use the location of the identifier as the
4111  // location of the decl, otherwise use the location of the struct/union
4112  // keyword.
4113  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
4114
4115  // Otherwise, create a new declaration. If there is a previous
4116  // declaration of the same entity, the two will be linked via
4117  // PrevDecl.
4118  TagDecl *New;
4119
4120  if (Kind == TagDecl::TK_enum) {
4121    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
4122    // enum X { A, B, C } D;    D should chain to X.
4123    New = EnumDecl::Create(Context, SearchDC, Loc, Name, KWLoc,
4124                           cast_or_null<EnumDecl>(PrevDecl));
4125    // If this is an undefined enum, warn.
4126    if (TUK != TUK_Definition && !Invalid)  {
4127      unsigned DK = getLangOptions().CPlusPlus? diag::err_forward_ref_enum
4128                                              : diag::ext_forward_ref_enum;
4129      Diag(Loc, DK);
4130    }
4131  } else {
4132    // struct/union/class
4133
4134    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
4135    // struct X { int A; } D;    D should chain to X.
4136    if (getLangOptions().CPlusPlus)
4137      // FIXME: Look for a way to use RecordDecl for simple structs.
4138      New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
4139                                  cast_or_null<CXXRecordDecl>(PrevDecl));
4140    else
4141      New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
4142                               cast_or_null<RecordDecl>(PrevDecl));
4143  }
4144
4145  if (Kind != TagDecl::TK_enum) {
4146    // Handle #pragma pack: if the #pragma pack stack has non-default
4147    // alignment, make up a packed attribute for this decl. These
4148    // attributes are checked when the ASTContext lays out the
4149    // structure.
4150    //
4151    // It is important for implementing the correct semantics that this
4152    // happen here (in act on tag decl). The #pragma pack stack is
4153    // maintained as a result of parser callbacks which can occur at
4154    // many points during the parsing of a struct declaration (because
4155    // the #pragma tokens are effectively skipped over during the
4156    // parsing of the struct).
4157    if (unsigned Alignment = getPragmaPackAlignment())
4158      New->addAttr(::new (Context) PackedAttr(Alignment * 8));
4159  }
4160
4161  if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) {
4162    // C++ [dcl.typedef]p3:
4163    //   [...] Similarly, in a given scope, a class or enumeration
4164    //   shall not be declared with the same name as a typedef-name
4165    //   that is declared in that scope and refers to a type other
4166    //   than the class or enumeration itself.
4167    LookupResult Lookup = LookupName(S, Name, LookupOrdinaryName, true);
4168    TypedefDecl *PrevTypedef = 0;
4169    if (Lookup.getKind() == LookupResult::Found)
4170      PrevTypedef = dyn_cast<TypedefDecl>(Lookup.getAsDecl());
4171
4172    if (PrevTypedef && isDeclInScope(PrevTypedef, SearchDC, S) &&
4173        Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) !=
4174          Context.getCanonicalType(Context.getTypeDeclType(New))) {
4175      Diag(Loc, diag::err_tag_definition_of_typedef)
4176        << Context.getTypeDeclType(New)
4177        << PrevTypedef->getUnderlyingType();
4178      Diag(PrevTypedef->getLocation(), diag::note_previous_definition);
4179      Invalid = true;
4180    }
4181  }
4182
4183  if (Invalid)
4184    New->setInvalidDecl();
4185
4186  if (Attr)
4187    ProcessDeclAttributeList(S, New, Attr);
4188
4189  // If we're declaring or defining a tag in function prototype scope
4190  // in C, note that this type can only be used within the function.
4191  if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
4192    Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
4193
4194  // Set the lexical context. If the tag has a C++ scope specifier, the
4195  // lexical context will be different from the semantic context.
4196  New->setLexicalDeclContext(CurContext);
4197
4198  // Set the access specifier.
4199  if (!Invalid)
4200    SetMemberAccessSpecifier(New, PrevDecl, AS);
4201
4202  if (TUK == TUK_Definition)
4203    New->startDefinition();
4204
4205  // If this has an identifier, add it to the scope stack.
4206  if (Name) {
4207    S = getNonFieldDeclScope(S);
4208    PushOnScopeChains(New, S);
4209  } else {
4210    CurContext->addDecl(New);
4211  }
4212
4213  // If this is the C FILE type, notify the AST context.
4214  if (IdentifierInfo *II = New->getIdentifier())
4215    if (!New->isInvalidDecl() &&
4216        New->getDeclContext()->getLookupContext()->isTranslationUnit() &&
4217        II->isStr("FILE"))
4218      Context.setFILEDecl(New);
4219
4220  OwnedDecl = true;
4221  return DeclPtrTy::make(New);
4222}
4223
4224void Sema::ActOnTagStartDefinition(Scope *S, DeclPtrTy TagD) {
4225  AdjustDeclIfTemplate(TagD);
4226  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4227
4228  // Enter the tag context.
4229  PushDeclContext(S, Tag);
4230
4231  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
4232    FieldCollector->StartClass();
4233
4234    if (Record->getIdentifier()) {
4235      // C++ [class]p2:
4236      //   [...] The class-name is also inserted into the scope of the
4237      //   class itself; this is known as the injected-class-name. For
4238      //   purposes of access checking, the injected-class-name is treated
4239      //   as if it were a public member name.
4240      CXXRecordDecl *InjectedClassName
4241        = CXXRecordDecl::Create(Context, Record->getTagKind(),
4242                                CurContext, Record->getLocation(),
4243                                Record->getIdentifier(),
4244                                Record->getTagKeywordLoc(),
4245                                Record);
4246      InjectedClassName->setImplicit();
4247      InjectedClassName->setAccess(AS_public);
4248      if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
4249        InjectedClassName->setDescribedClassTemplate(Template);
4250      PushOnScopeChains(InjectedClassName, S);
4251      assert(InjectedClassName->isInjectedClassName() &&
4252             "Broken injected-class-name");
4253    }
4254  }
4255}
4256
4257void Sema::ActOnTagFinishDefinition(Scope *S, DeclPtrTy TagD,
4258                                    SourceLocation RBraceLoc) {
4259  AdjustDeclIfTemplate(TagD);
4260  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4261  Tag->setRBraceLoc(RBraceLoc);
4262
4263  if (isa<CXXRecordDecl>(Tag))
4264    FieldCollector->FinishClass();
4265
4266  // Exit this scope of this tag's definition.
4267  PopDeclContext();
4268
4269  // Notify the consumer that we've defined a tag.
4270  Consumer.HandleTagDeclDefinition(Tag);
4271}
4272
4273// Note that FieldName may be null for anonymous bitfields.
4274bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
4275                          QualType FieldTy, const Expr *BitWidth) {
4276
4277  // C99 6.7.2.1p4 - verify the field type.
4278  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
4279  if (!FieldTy->isDependentType() && !FieldTy->isIntegralType()) {
4280    // Handle incomplete types with specific error.
4281    if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
4282      return true;
4283    if (FieldName)
4284      return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
4285        << FieldName << FieldTy << BitWidth->getSourceRange();
4286    return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
4287      << FieldTy << BitWidth->getSourceRange();
4288  }
4289
4290  // If the bit-width is type- or value-dependent, don't try to check
4291  // it now.
4292  if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
4293    return false;
4294
4295  llvm::APSInt Value;
4296  if (VerifyIntegerConstantExpression(BitWidth, &Value))
4297    return true;
4298
4299  // Zero-width bitfield is ok for anonymous field.
4300  if (Value == 0 && FieldName)
4301    return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
4302
4303  if (Value.isSigned() && Value.isNegative()) {
4304    if (FieldName)
4305      return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
4306               << FieldName << Value.toString(10);
4307    return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
4308      << Value.toString(10);
4309  }
4310
4311  if (!FieldTy->isDependentType()) {
4312    uint64_t TypeSize = Context.getTypeSize(FieldTy);
4313    if (Value.getZExtValue() > TypeSize) {
4314      if (FieldName)
4315        return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
4316          << FieldName << (unsigned)TypeSize;
4317      return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
4318        << (unsigned)TypeSize;
4319    }
4320  }
4321
4322  return false;
4323}
4324
4325/// ActOnField - Each field of a struct/union/class is passed into this in order
4326/// to create a FieldDecl object for it.
4327Sema::DeclPtrTy Sema::ActOnField(Scope *S, DeclPtrTy TagD,
4328                                 SourceLocation DeclStart,
4329                                 Declarator &D, ExprTy *BitfieldWidth) {
4330  FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD.getAs<Decl>()),
4331                               DeclStart, D, static_cast<Expr*>(BitfieldWidth),
4332                               AS_public);
4333  return DeclPtrTy::make(Res);
4334}
4335
4336/// HandleField - Analyze a field of a C struct or a C++ data member.
4337///
4338FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
4339                             SourceLocation DeclStart,
4340                             Declarator &D, Expr *BitWidth,
4341                             AccessSpecifier AS) {
4342  IdentifierInfo *II = D.getIdentifier();
4343  SourceLocation Loc = DeclStart;
4344  if (II) Loc = D.getIdentifierLoc();
4345
4346  QualType T = GetTypeForDeclarator(D, S);
4347  if (getLangOptions().CPlusPlus)
4348    CheckExtraCXXDefaultArguments(D);
4349
4350  DiagnoseFunctionSpecifiers(D);
4351
4352  if (D.getDeclSpec().isThreadSpecified())
4353    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4354
4355  NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true);
4356
4357  if (PrevDecl && PrevDecl->isTemplateParameter()) {
4358    // Maybe we will complain about the shadowed template parameter.
4359    DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
4360    // Just pretend that we didn't see the previous declaration.
4361    PrevDecl = 0;
4362  }
4363
4364  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
4365    PrevDecl = 0;
4366
4367  bool Mutable
4368    = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
4369  SourceLocation TSSL = D.getSourceRange().getBegin();
4370  FieldDecl *NewFD
4371    = CheckFieldDecl(II, T, Record, Loc, Mutable, BitWidth, TSSL,
4372                     AS, PrevDecl, &D);
4373  if (NewFD->isInvalidDecl() && PrevDecl) {
4374    // Don't introduce NewFD into scope; there's already something
4375    // with the same name in the same scope.
4376  } else if (II) {
4377    PushOnScopeChains(NewFD, S);
4378  } else
4379    Record->addDecl(NewFD);
4380
4381  return NewFD;
4382}
4383
4384/// \brief Build a new FieldDecl and check its well-formedness.
4385///
4386/// This routine builds a new FieldDecl given the fields name, type,
4387/// record, etc. \p PrevDecl should refer to any previous declaration
4388/// with the same name and in the same scope as the field to be
4389/// created.
4390///
4391/// \returns a new FieldDecl.
4392///
4393/// \todo The Declarator argument is a hack. It will be removed once
4394FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
4395                                RecordDecl *Record, SourceLocation Loc,
4396                                bool Mutable, Expr *BitWidth,
4397                                SourceLocation TSSL,
4398                                AccessSpecifier AS, NamedDecl *PrevDecl,
4399                                Declarator *D) {
4400  IdentifierInfo *II = Name.getAsIdentifierInfo();
4401  bool InvalidDecl = false;
4402  if (D) InvalidDecl = D->isInvalidType();
4403
4404  // If we receive a broken type, recover by assuming 'int' and
4405  // marking this declaration as invalid.
4406  if (T.isNull()) {
4407    InvalidDecl = true;
4408    T = Context.IntTy;
4409  }
4410
4411  // C99 6.7.2.1p8: A member of a structure or union may have any type other
4412  // than a variably modified type.
4413  if (T->isVariablyModifiedType()) {
4414    bool SizeIsNegative;
4415    QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
4416                                                           SizeIsNegative);
4417    if (!FixedTy.isNull()) {
4418      Diag(Loc, diag::warn_illegal_constant_array_size);
4419      T = FixedTy;
4420    } else {
4421      if (SizeIsNegative)
4422        Diag(Loc, diag::err_typecheck_negative_array_size);
4423      else
4424        Diag(Loc, diag::err_typecheck_field_variable_size);
4425      InvalidDecl = true;
4426    }
4427  }
4428
4429  // Fields can not have abstract class types
4430  if (RequireNonAbstractType(Loc, T, diag::err_abstract_type_in_decl,
4431                             AbstractFieldType))
4432    InvalidDecl = true;
4433
4434  // If this is declared as a bit-field, check the bit-field.
4435  if (BitWidth && VerifyBitField(Loc, II, T, BitWidth)) {
4436    InvalidDecl = true;
4437    DeleteExpr(BitWidth);
4438    BitWidth = 0;
4439  }
4440
4441  FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, BitWidth,
4442                                       Mutable, TSSL);
4443  if (InvalidDecl)
4444    NewFD->setInvalidDecl();
4445
4446  if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
4447    Diag(Loc, diag::err_duplicate_member) << II;
4448    Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4449    NewFD->setInvalidDecl();
4450  }
4451
4452  if (getLangOptions().CPlusPlus) {
4453    QualType EltTy = Context.getBaseElementType(T);
4454
4455    if (const RecordType *RT = EltTy->getAs<RecordType>()) {
4456      CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
4457
4458      if (!RDecl->hasTrivialConstructor())
4459        cast<CXXRecordDecl>(Record)->setHasTrivialConstructor(false);
4460      if (!RDecl->hasTrivialCopyConstructor())
4461        cast<CXXRecordDecl>(Record)->setHasTrivialCopyConstructor(false);
4462      if (!RDecl->hasTrivialCopyAssignment())
4463        cast<CXXRecordDecl>(Record)->setHasTrivialCopyAssignment(false);
4464      if (!RDecl->hasTrivialDestructor())
4465        cast<CXXRecordDecl>(Record)->setHasTrivialDestructor(false);
4466
4467      // C++ 9.5p1: An object of a class with a non-trivial
4468      // constructor, a non-trivial copy constructor, a non-trivial
4469      // destructor, or a non-trivial copy assignment operator
4470      // cannot be a member of a union, nor can an array of such
4471      // objects.
4472      // TODO: C++0x alters this restriction significantly.
4473      if (Record->isUnion()) {
4474        // We check for copy constructors before constructors
4475        // because otherwise we'll never get complaints about
4476        // copy constructors.
4477
4478        const CXXSpecialMember invalid = (CXXSpecialMember) -1;
4479
4480        CXXSpecialMember member;
4481        if (!RDecl->hasTrivialCopyConstructor())
4482          member = CXXCopyConstructor;
4483        else if (!RDecl->hasTrivialConstructor())
4484          member = CXXDefaultConstructor;
4485        else if (!RDecl->hasTrivialCopyAssignment())
4486          member = CXXCopyAssignment;
4487        else if (!RDecl->hasTrivialDestructor())
4488          member = CXXDestructor;
4489        else
4490          member = invalid;
4491
4492        if (member != invalid) {
4493          Diag(Loc, diag::err_illegal_union_member) << Name << member;
4494          DiagnoseNontrivial(RT, member);
4495          NewFD->setInvalidDecl();
4496        }
4497      }
4498    }
4499  }
4500
4501  if (getLangOptions().CPlusPlus && !T->isPODType())
4502    cast<CXXRecordDecl>(Record)->setPOD(false);
4503
4504  // FIXME: We need to pass in the attributes given an AST
4505  // representation, not a parser representation.
4506  if (D)
4507    // FIXME: What to pass instead of TUScope?
4508    ProcessDeclAttributes(TUScope, NewFD, *D);
4509
4510  if (T.isObjCGCWeak())
4511    Diag(Loc, diag::warn_attribute_weak_on_field);
4512
4513  NewFD->setAccess(AS);
4514
4515  // C++ [dcl.init.aggr]p1:
4516  //   An aggregate is an array or a class (clause 9) with [...] no
4517  //   private or protected non-static data members (clause 11).
4518  // A POD must be an aggregate.
4519  if (getLangOptions().CPlusPlus &&
4520      (AS == AS_private || AS == AS_protected)) {
4521    CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
4522    CXXRecord->setAggregate(false);
4523    CXXRecord->setPOD(false);
4524  }
4525
4526  return NewFD;
4527}
4528
4529/// DiagnoseNontrivial - Given that a class has a non-trivial
4530/// special member, figure out why.
4531void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
4532  QualType QT(T, 0U);
4533  CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
4534
4535  // Check whether the member was user-declared.
4536  switch (member) {
4537  case CXXDefaultConstructor:
4538    if (RD->hasUserDeclaredConstructor()) {
4539      typedef CXXRecordDecl::ctor_iterator ctor_iter;
4540      for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce; ++ci)
4541        if (!ci->isImplicitlyDefined(Context)) {
4542          SourceLocation CtorLoc = ci->getLocation();
4543          Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
4544          return;
4545        }
4546
4547      assert(0 && "found no user-declared constructors");
4548      return;
4549    }
4550    break;
4551
4552  case CXXCopyConstructor:
4553    if (RD->hasUserDeclaredCopyConstructor()) {
4554      SourceLocation CtorLoc =
4555        RD->getCopyConstructor(Context, 0)->getLocation();
4556      Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
4557      return;
4558    }
4559    break;
4560
4561  case CXXCopyAssignment:
4562    if (RD->hasUserDeclaredCopyAssignment()) {
4563      // FIXME: this should use the location of the copy
4564      // assignment, not the type.
4565      SourceLocation TyLoc = RD->getSourceRange().getBegin();
4566      Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
4567      return;
4568    }
4569    break;
4570
4571  case CXXDestructor:
4572    if (RD->hasUserDeclaredDestructor()) {
4573      SourceLocation DtorLoc = RD->getDestructor(Context)->getLocation();
4574      Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
4575      return;
4576    }
4577    break;
4578  }
4579
4580  typedef CXXRecordDecl::base_class_iterator base_iter;
4581
4582  // Virtual bases and members inhibit trivial copying/construction,
4583  // but not trivial destruction.
4584  if (member != CXXDestructor) {
4585    // Check for virtual bases.  vbases includes indirect virtual bases,
4586    // so we just iterate through the direct bases.
4587    for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
4588      if (bi->isVirtual()) {
4589        SourceLocation BaseLoc = bi->getSourceRange().getBegin();
4590        Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
4591        return;
4592      }
4593
4594    // Check for virtual methods.
4595    typedef CXXRecordDecl::method_iterator meth_iter;
4596    for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
4597         ++mi) {
4598      if (mi->isVirtual()) {
4599        SourceLocation MLoc = mi->getSourceRange().getBegin();
4600        Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
4601        return;
4602      }
4603    }
4604  }
4605
4606  bool (CXXRecordDecl::*hasTrivial)() const;
4607  switch (member) {
4608  case CXXDefaultConstructor:
4609    hasTrivial = &CXXRecordDecl::hasTrivialConstructor; break;
4610  case CXXCopyConstructor:
4611    hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
4612  case CXXCopyAssignment:
4613    hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
4614  case CXXDestructor:
4615    hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
4616  default:
4617    assert(0 && "unexpected special member"); return;
4618  }
4619
4620  // Check for nontrivial bases (and recurse).
4621  for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
4622    const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
4623    assert(BaseRT);
4624    CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
4625    if (!(BaseRecTy->*hasTrivial)()) {
4626      SourceLocation BaseLoc = bi->getSourceRange().getBegin();
4627      Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
4628      DiagnoseNontrivial(BaseRT, member);
4629      return;
4630    }
4631  }
4632
4633  // Check for nontrivial members (and recurse).
4634  typedef RecordDecl::field_iterator field_iter;
4635  for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
4636       ++fi) {
4637    QualType EltTy = Context.getBaseElementType((*fi)->getType());
4638    if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
4639      CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
4640
4641      if (!(EltRD->*hasTrivial)()) {
4642        SourceLocation FLoc = (*fi)->getLocation();
4643        Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
4644        DiagnoseNontrivial(EltRT, member);
4645        return;
4646      }
4647    }
4648  }
4649
4650  assert(0 && "found no explanation for non-trivial member");
4651}
4652
4653/// TranslateIvarVisibility - Translate visibility from a token ID to an
4654///  AST enum value.
4655static ObjCIvarDecl::AccessControl
4656TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
4657  switch (ivarVisibility) {
4658  default: assert(0 && "Unknown visitibility kind");
4659  case tok::objc_private: return ObjCIvarDecl::Private;
4660  case tok::objc_public: return ObjCIvarDecl::Public;
4661  case tok::objc_protected: return ObjCIvarDecl::Protected;
4662  case tok::objc_package: return ObjCIvarDecl::Package;
4663  }
4664}
4665
4666/// ActOnIvar - Each ivar field of an objective-c class is passed into this
4667/// in order to create an IvarDecl object for it.
4668Sema::DeclPtrTy Sema::ActOnIvar(Scope *S,
4669                                SourceLocation DeclStart,
4670                                DeclPtrTy IntfDecl,
4671                                Declarator &D, ExprTy *BitfieldWidth,
4672                                tok::ObjCKeywordKind Visibility) {
4673
4674  IdentifierInfo *II = D.getIdentifier();
4675  Expr *BitWidth = (Expr*)BitfieldWidth;
4676  SourceLocation Loc = DeclStart;
4677  if (II) Loc = D.getIdentifierLoc();
4678
4679  // FIXME: Unnamed fields can be handled in various different ways, for
4680  // example, unnamed unions inject all members into the struct namespace!
4681
4682  QualType T = GetTypeForDeclarator(D, S);
4683
4684  if (BitWidth) {
4685    // 6.7.2.1p3, 6.7.2.1p4
4686    if (VerifyBitField(Loc, II, T, BitWidth)) {
4687      D.setInvalidType();
4688      DeleteExpr(BitWidth);
4689      BitWidth = 0;
4690    }
4691  } else {
4692    // Not a bitfield.
4693
4694    // validate II.
4695
4696  }
4697
4698  // C99 6.7.2.1p8: A member of a structure or union may have any type other
4699  // than a variably modified type.
4700  if (T->isVariablyModifiedType()) {
4701    Diag(Loc, diag::err_typecheck_ivar_variable_size);
4702    D.setInvalidType();
4703  }
4704
4705  // Get the visibility (access control) for this ivar.
4706  ObjCIvarDecl::AccessControl ac =
4707    Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
4708                                        : ObjCIvarDecl::None;
4709  // Must set ivar's DeclContext to its enclosing interface.
4710  Decl *EnclosingDecl = IntfDecl.getAs<Decl>();
4711  DeclContext *EnclosingContext;
4712  if (ObjCImplementationDecl *IMPDecl =
4713      dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
4714    // Case of ivar declared in an implementation. Context is that of its class.
4715    ObjCInterfaceDecl* IDecl = IMPDecl->getClassInterface();
4716    assert(IDecl && "No class- ActOnIvar");
4717    EnclosingContext = cast_or_null<DeclContext>(IDecl);
4718  } else
4719    EnclosingContext = dyn_cast<DeclContext>(EnclosingDecl);
4720  assert(EnclosingContext && "null DeclContext for ivar - ActOnIvar");
4721
4722  // Construct the decl.
4723  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context,
4724                                             EnclosingContext, Loc, II, T,ac,
4725                                             (Expr *)BitfieldWidth);
4726
4727  if (II) {
4728    NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true);
4729    if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
4730        && !isa<TagDecl>(PrevDecl)) {
4731      Diag(Loc, diag::err_duplicate_member) << II;
4732      Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4733      NewID->setInvalidDecl();
4734    }
4735  }
4736
4737  // Process attributes attached to the ivar.
4738  ProcessDeclAttributes(S, NewID, D);
4739
4740  if (D.isInvalidType())
4741    NewID->setInvalidDecl();
4742
4743  if (II) {
4744    // FIXME: When interfaces are DeclContexts, we'll need to add
4745    // these to the interface.
4746    S->AddDecl(DeclPtrTy::make(NewID));
4747    IdResolver.AddDecl(NewID);
4748  }
4749
4750  return DeclPtrTy::make(NewID);
4751}
4752
4753void Sema::ActOnFields(Scope* S,
4754                       SourceLocation RecLoc, DeclPtrTy RecDecl,
4755                       DeclPtrTy *Fields, unsigned NumFields,
4756                       SourceLocation LBrac, SourceLocation RBrac,
4757                       AttributeList *Attr) {
4758  Decl *EnclosingDecl = RecDecl.getAs<Decl>();
4759  assert(EnclosingDecl && "missing record or interface decl");
4760
4761  // If the decl this is being inserted into is invalid, then it may be a
4762  // redeclaration or some other bogus case.  Don't try to add fields to it.
4763  if (EnclosingDecl->isInvalidDecl()) {
4764    // FIXME: Deallocate fields?
4765    return;
4766  }
4767
4768
4769  // Verify that all the fields are okay.
4770  unsigned NumNamedMembers = 0;
4771  llvm::SmallVector<FieldDecl*, 32> RecFields;
4772
4773  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
4774  for (unsigned i = 0; i != NumFields; ++i) {
4775    FieldDecl *FD = cast<FieldDecl>(Fields[i].getAs<Decl>());
4776
4777    // Get the type for the field.
4778    Type *FDTy = FD->getType().getTypePtr();
4779
4780    if (!FD->isAnonymousStructOrUnion()) {
4781      // Remember all fields written by the user.
4782      RecFields.push_back(FD);
4783    }
4784
4785    // If the field is already invalid for some reason, don't emit more
4786    // diagnostics about it.
4787    if (FD->isInvalidDecl())
4788      continue;
4789
4790    // C99 6.7.2.1p2:
4791    //   A structure or union shall not contain a member with
4792    //   incomplete or function type (hence, a structure shall not
4793    //   contain an instance of itself, but may contain a pointer to
4794    //   an instance of itself), except that the last member of a
4795    //   structure with more than one named member may have incomplete
4796    //   array type; such a structure (and any union containing,
4797    //   possibly recursively, a member that is such a structure)
4798    //   shall not be a member of a structure or an element of an
4799    //   array.
4800    if (FDTy->isFunctionType()) {
4801      // Field declared as a function.
4802      Diag(FD->getLocation(), diag::err_field_declared_as_function)
4803        << FD->getDeclName();
4804      FD->setInvalidDecl();
4805      EnclosingDecl->setInvalidDecl();
4806      continue;
4807    } else if (FDTy->isIncompleteArrayType() && i == NumFields - 1 &&
4808               Record && Record->isStruct()) {
4809      // Flexible array member.
4810      if (NumNamedMembers < 1) {
4811        Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
4812          << FD->getDeclName();
4813        FD->setInvalidDecl();
4814        EnclosingDecl->setInvalidDecl();
4815        continue;
4816      }
4817      // Okay, we have a legal flexible array member at the end of the struct.
4818      if (Record)
4819        Record->setHasFlexibleArrayMember(true);
4820    } else if (!FDTy->isDependentType() &&
4821               RequireCompleteType(FD->getLocation(), FD->getType(),
4822                                   diag::err_field_incomplete)) {
4823      // Incomplete type
4824      FD->setInvalidDecl();
4825      EnclosingDecl->setInvalidDecl();
4826      continue;
4827    } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
4828      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
4829        // If this is a member of a union, then entire union becomes "flexible".
4830        if (Record && Record->isUnion()) {
4831          Record->setHasFlexibleArrayMember(true);
4832        } else {
4833          // If this is a struct/class and this is not the last element, reject
4834          // it.  Note that GCC supports variable sized arrays in the middle of
4835          // structures.
4836          if (i != NumFields-1)
4837            Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
4838              << FD->getDeclName() << FD->getType();
4839          else {
4840            // We support flexible arrays at the end of structs in
4841            // other structs as an extension.
4842            Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
4843              << FD->getDeclName();
4844            if (Record)
4845              Record->setHasFlexibleArrayMember(true);
4846          }
4847        }
4848      }
4849      if (Record && FDTTy->getDecl()->hasObjectMember())
4850        Record->setHasObjectMember(true);
4851    } else if (FDTy->isObjCInterfaceType()) {
4852      /// A field cannot be an Objective-c object
4853      Diag(FD->getLocation(), diag::err_statically_allocated_object);
4854      FD->setInvalidDecl();
4855      EnclosingDecl->setInvalidDecl();
4856      continue;
4857    } else if (getLangOptions().ObjC1 &&
4858               getLangOptions().getGCMode() != LangOptions::NonGC &&
4859               Record &&
4860               (FD->getType()->isObjCObjectPointerType() ||
4861                FD->getType().isObjCGCStrong()))
4862      Record->setHasObjectMember(true);
4863    // Keep track of the number of named members.
4864    if (FD->getIdentifier())
4865      ++NumNamedMembers;
4866  }
4867
4868  // Okay, we successfully defined 'Record'.
4869  if (Record) {
4870    Record->completeDefinition(Context);
4871  } else {
4872    ObjCIvarDecl **ClsFields =
4873      reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
4874    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
4875      ID->setIVarList(ClsFields, RecFields.size(), Context);
4876      ID->setLocEnd(RBrac);
4877      // Add ivar's to class's DeclContext.
4878      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
4879        ClsFields[i]->setLexicalDeclContext(ID);
4880        ID->addDecl(ClsFields[i]);
4881      }
4882      // Must enforce the rule that ivars in the base classes may not be
4883      // duplicates.
4884      if (ID->getSuperClass()) {
4885        for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
4886             IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
4887          ObjCIvarDecl* Ivar = (*IVI);
4888
4889          if (IdentifierInfo *II = Ivar->getIdentifier()) {
4890            ObjCIvarDecl* prevIvar =
4891              ID->getSuperClass()->lookupInstanceVariable(II);
4892            if (prevIvar) {
4893              Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
4894              Diag(prevIvar->getLocation(), diag::note_previous_declaration);
4895            }
4896          }
4897        }
4898      }
4899    } else if (ObjCImplementationDecl *IMPDecl =
4900                  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
4901      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
4902      for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
4903        // Ivar declared in @implementation never belongs to the implementation.
4904        // Only it is in implementation's lexical context.
4905        ClsFields[I]->setLexicalDeclContext(IMPDecl);
4906      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
4907    }
4908  }
4909
4910  if (Attr)
4911    ProcessDeclAttributeList(S, Record, Attr);
4912}
4913
4914EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
4915                                          EnumConstantDecl *LastEnumConst,
4916                                          SourceLocation IdLoc,
4917                                          IdentifierInfo *Id,
4918                                          ExprArg val) {
4919  Expr *Val = (Expr *)val.get();
4920
4921  llvm::APSInt EnumVal(32);
4922  QualType EltTy;
4923  if (Val && !Val->isTypeDependent()) {
4924    // Make sure to promote the operand type to int.
4925    UsualUnaryConversions(Val);
4926    if (Val != val.get()) {
4927      val.release();
4928      val = Val;
4929    }
4930
4931    // C99 6.7.2.2p2: Make sure we have an integer constant expression.
4932    SourceLocation ExpLoc;
4933    if (!Val->isValueDependent() &&
4934        VerifyIntegerConstantExpression(Val, &EnumVal)) {
4935      Val = 0;
4936    } else {
4937      EltTy = Val->getType();
4938    }
4939  }
4940
4941  if (!Val) {
4942    if (LastEnumConst) {
4943      // Assign the last value + 1.
4944      EnumVal = LastEnumConst->getInitVal();
4945      ++EnumVal;
4946
4947      // Check for overflow on increment.
4948      if (EnumVal < LastEnumConst->getInitVal())
4949        Diag(IdLoc, diag::warn_enum_value_overflow);
4950
4951      EltTy = LastEnumConst->getType();
4952    } else {
4953      // First value, set to zero.
4954      EltTy = Context.IntTy;
4955      EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
4956    }
4957  }
4958
4959  val.release();
4960  return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
4961                                  Val, EnumVal);
4962}
4963
4964
4965Sema::DeclPtrTy Sema::ActOnEnumConstant(Scope *S, DeclPtrTy theEnumDecl,
4966                                        DeclPtrTy lastEnumConst,
4967                                        SourceLocation IdLoc,
4968                                        IdentifierInfo *Id,
4969                                        SourceLocation EqualLoc, ExprTy *val) {
4970  EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl.getAs<Decl>());
4971  EnumConstantDecl *LastEnumConst =
4972    cast_or_null<EnumConstantDecl>(lastEnumConst.getAs<Decl>());
4973  Expr *Val = static_cast<Expr*>(val);
4974
4975  // The scope passed in may not be a decl scope.  Zip up the scope tree until
4976  // we find one that is.
4977  S = getNonFieldDeclScope(S);
4978
4979  // Verify that there isn't already something declared with this name in this
4980  // scope.
4981  NamedDecl *PrevDecl = LookupName(S, Id, LookupOrdinaryName);
4982  if (PrevDecl && PrevDecl->isTemplateParameter()) {
4983    // Maybe we will complain about the shadowed template parameter.
4984    DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
4985    // Just pretend that we didn't see the previous declaration.
4986    PrevDecl = 0;
4987  }
4988
4989  if (PrevDecl) {
4990    // When in C++, we may get a TagDecl with the same name; in this case the
4991    // enum constant will 'hide' the tag.
4992    assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
4993           "Received TagDecl when not in C++!");
4994    if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
4995      if (isa<EnumConstantDecl>(PrevDecl))
4996        Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
4997      else
4998        Diag(IdLoc, diag::err_redefinition) << Id;
4999      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5000      if (Val) Val->Destroy(Context);
5001      return DeclPtrTy();
5002    }
5003  }
5004
5005  EnumConstantDecl *New = CheckEnumConstant(TheEnumDecl, LastEnumConst,
5006                                            IdLoc, Id, Owned(Val));
5007
5008  // Register this decl in the current scope stack.
5009  if (New)
5010    PushOnScopeChains(New, S);
5011
5012  return DeclPtrTy::make(New);
5013}
5014
5015void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
5016                         SourceLocation RBraceLoc, DeclPtrTy EnumDeclX,
5017                         DeclPtrTy *Elements, unsigned NumElements) {
5018  EnumDecl *Enum = cast<EnumDecl>(EnumDeclX.getAs<Decl>());
5019  QualType EnumType = Context.getTypeDeclType(Enum);
5020
5021  // TODO: If the result value doesn't fit in an int, it must be a long or long
5022  // long value.  ISO C does not support this, but GCC does as an extension,
5023  // emit a warning.
5024  unsigned IntWidth = Context.Target.getIntWidth();
5025
5026  // Verify that all the values are okay, compute the size of the values, and
5027  // reverse the list.
5028  unsigned NumNegativeBits = 0;
5029  unsigned NumPositiveBits = 0;
5030
5031  // Keep track of whether all elements have type int.
5032  bool AllElementsInt = true;
5033
5034  for (unsigned i = 0; i != NumElements; ++i) {
5035    EnumConstantDecl *ECD =
5036      cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
5037    if (!ECD) continue;  // Already issued a diagnostic.
5038
5039    // If the enum value doesn't fit in an int, emit an extension warning.
5040    const llvm::APSInt &InitVal = ECD->getInitVal();
5041    assert(InitVal.getBitWidth() >= IntWidth &&
5042           "Should have promoted value to int");
5043    if (InitVal.getBitWidth() > IntWidth) {
5044      llvm::APSInt V(InitVal);
5045      V.trunc(IntWidth);
5046      V.extend(InitVal.getBitWidth());
5047      if (V != InitVal)
5048        Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
5049          << InitVal.toString(10);
5050    }
5051
5052    // Keep track of the size of positive and negative values.
5053    if (InitVal.isUnsigned() || InitVal.isNonNegative())
5054      NumPositiveBits = std::max(NumPositiveBits,
5055                                 (unsigned)InitVal.getActiveBits());
5056    else
5057      NumNegativeBits = std::max(NumNegativeBits,
5058                                 (unsigned)InitVal.getMinSignedBits());
5059
5060    // Keep track of whether every enum element has type int (very commmon).
5061    if (AllElementsInt)
5062      AllElementsInt = ECD->getType() == Context.IntTy;
5063  }
5064
5065  // Figure out the type that should be used for this enum.
5066  // FIXME: Support attribute(packed) on enums and -fshort-enums.
5067  QualType BestType;
5068  unsigned BestWidth;
5069
5070  if (NumNegativeBits) {
5071    // If there is a negative value, figure out the smallest integer type (of
5072    // int/long/longlong) that fits.
5073    if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5074      BestType = Context.IntTy;
5075      BestWidth = IntWidth;
5076    } else {
5077      BestWidth = Context.Target.getLongWidth();
5078
5079      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
5080        BestType = Context.LongTy;
5081      else {
5082        BestWidth = Context.Target.getLongLongWidth();
5083
5084        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5085          Diag(Enum->getLocation(), diag::warn_enum_too_large);
5086        BestType = Context.LongLongTy;
5087      }
5088    }
5089  } else {
5090    // If there is no negative value, figure out which of uint, ulong, ulonglong
5091    // fits.
5092    if (NumPositiveBits <= IntWidth) {
5093      BestType = Context.UnsignedIntTy;
5094      BestWidth = IntWidth;
5095    } else if (NumPositiveBits <=
5096               (BestWidth = Context.Target.getLongWidth())) {
5097      BestType = Context.UnsignedLongTy;
5098    } else {
5099      BestWidth = Context.Target.getLongLongWidth();
5100      assert(NumPositiveBits <= BestWidth &&
5101             "How could an initializer get larger than ULL?");
5102      BestType = Context.UnsignedLongLongTy;
5103    }
5104  }
5105
5106  // Loop over all of the enumerator constants, changing their types to match
5107  // the type of the enum if needed.
5108  for (unsigned i = 0; i != NumElements; ++i) {
5109    EnumConstantDecl *ECD =
5110      cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
5111    if (!ECD) continue;  // Already issued a diagnostic.
5112
5113    // Standard C says the enumerators have int type, but we allow, as an
5114    // extension, the enumerators to be larger than int size.  If each
5115    // enumerator value fits in an int, type it as an int, otherwise type it the
5116    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
5117    // that X has type 'int', not 'unsigned'.
5118    if (ECD->getType() == Context.IntTy) {
5119      // Make sure the init value is signed.
5120      llvm::APSInt IV = ECD->getInitVal();
5121      IV.setIsSigned(true);
5122      ECD->setInitVal(IV);
5123
5124      if (getLangOptions().CPlusPlus)
5125        // C++ [dcl.enum]p4: Following the closing brace of an
5126        // enum-specifier, each enumerator has the type of its
5127        // enumeration.
5128        ECD->setType(EnumType);
5129      continue;  // Already int type.
5130    }
5131
5132    // Determine whether the value fits into an int.
5133    llvm::APSInt InitVal = ECD->getInitVal();
5134    bool FitsInInt;
5135    if (InitVal.isUnsigned() || !InitVal.isNegative())
5136      FitsInInt = InitVal.getActiveBits() < IntWidth;
5137    else
5138      FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
5139
5140    // If it fits into an integer type, force it.  Otherwise force it to match
5141    // the enum decl type.
5142    QualType NewTy;
5143    unsigned NewWidth;
5144    bool NewSign;
5145    if (FitsInInt) {
5146      NewTy = Context.IntTy;
5147      NewWidth = IntWidth;
5148      NewSign = true;
5149    } else if (ECD->getType() == BestType) {
5150      // Already the right type!
5151      if (getLangOptions().CPlusPlus)
5152        // C++ [dcl.enum]p4: Following the closing brace of an
5153        // enum-specifier, each enumerator has the type of its
5154        // enumeration.
5155        ECD->setType(EnumType);
5156      continue;
5157    } else {
5158      NewTy = BestType;
5159      NewWidth = BestWidth;
5160      NewSign = BestType->isSignedIntegerType();
5161    }
5162
5163    // Adjust the APSInt value.
5164    InitVal.extOrTrunc(NewWidth);
5165    InitVal.setIsSigned(NewSign);
5166    ECD->setInitVal(InitVal);
5167
5168    // Adjust the Expr initializer and type.
5169    if (ECD->getInitExpr())
5170      ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy,
5171                                                      CastExpr::CK_Unknown,
5172                                                      ECD->getInitExpr(),
5173                                                      /*isLvalue=*/false));
5174    if (getLangOptions().CPlusPlus)
5175      // C++ [dcl.enum]p4: Following the closing brace of an
5176      // enum-specifier, each enumerator has the type of its
5177      // enumeration.
5178      ECD->setType(EnumType);
5179    else
5180      ECD->setType(NewTy);
5181  }
5182
5183  Enum->completeDefinition(Context, BestType);
5184}
5185
5186Sema::DeclPtrTy Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
5187                                            ExprArg expr) {
5188  StringLiteral *AsmString = cast<StringLiteral>(expr.takeAs<Expr>());
5189
5190  FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
5191                                                   Loc, AsmString);
5192  CurContext->addDecl(New);
5193  return DeclPtrTy::make(New);
5194}
5195
5196void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
5197                             SourceLocation PragmaLoc,
5198                             SourceLocation NameLoc) {
5199  Decl *PrevDecl = LookupName(TUScope, Name, LookupOrdinaryName);
5200
5201  if (PrevDecl) {
5202    PrevDecl->addAttr(::new (Context) WeakAttr());
5203  } else {
5204    (void)WeakUndeclaredIdentifiers.insert(
5205      std::pair<IdentifierInfo*,WeakInfo>
5206        (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
5207  }
5208}
5209
5210void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
5211                                IdentifierInfo* AliasName,
5212                                SourceLocation PragmaLoc,
5213                                SourceLocation NameLoc,
5214                                SourceLocation AliasNameLoc) {
5215  Decl *PrevDecl = LookupName(TUScope, AliasName, LookupOrdinaryName);
5216  WeakInfo W = WeakInfo(Name, NameLoc);
5217
5218  if (PrevDecl) {
5219    if (!PrevDecl->hasAttr<AliasAttr>())
5220      if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
5221        DeclApplyPragmaWeak(TUScope, ND, W);
5222  } else {
5223    (void)WeakUndeclaredIdentifiers.insert(
5224      std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
5225  }
5226}
5227