SemaDecl.cpp revision c7f0161766b7b551e21882add1e6e9599b820251
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 "clang/AST/APValue.h"
16#include "clang/AST/ASTConsumer.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/Parse/DeclSpec.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Basic/TargetInfo.h"
23#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
25#include "clang/Lex/Preprocessor.h"
26#include "clang/Lex/HeaderSearch.h"
27#include "llvm/ADT/SmallSet.h"
28#include "llvm/ADT/STLExtras.h"
29#include <algorithm>
30#include <functional>
31
32using namespace clang;
33
34Sema::TypeTy *Sema::isTypeName(IdentifierInfo &II, Scope *S,
35                               const CXXScopeSpec *SS) {
36  DeclContext *DC = 0;
37  if (SS) {
38    if (SS->isInvalid())
39      return 0;
40    DC = static_cast<DeclContext*>(SS->getScopeRep());
41  }
42  Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC, false);
43
44  if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
45                 isa<ObjCInterfaceDecl>(IIDecl) ||
46                 isa<TagDecl>(IIDecl) ||
47		 isa<TemplateTypeParmDecl>(IIDecl)))
48    return IIDecl;
49  return 0;
50}
51
52DeclContext *Sema::getContainingDC(DeclContext *DC) {
53  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
54    // A C++ out-of-line method will return to the file declaration context.
55    if (MD->isOutOfLineDefinition())
56      return MD->getLexicalDeclContext();
57
58    // A C++ inline method is parsed *after* the topmost class it was declared in
59    // is fully parsed (it's "complete").
60    // The parsing of a C++ inline method happens at the declaration context of
61    // the topmost (non-nested) class it is lexically declared in.
62    assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
63    DC = MD->getParent();
64    while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
65      DC = RD;
66
67    // Return the declaration context of the topmost class the inline method is
68    // declared in.
69    return DC;
70  }
71
72  if (isa<ObjCMethodDecl>(DC))
73    return Context.getTranslationUnitDecl();
74
75  if (ScopedDecl *SD = dyn_cast<ScopedDecl>(DC))
76    return SD->getLexicalDeclContext();
77
78  return DC->getLexicalParent();
79}
80
81void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
82  assert(getContainingDC(DC) == CurContext &&
83      "The next DeclContext should be lexically contained in the current one.");
84  CurContext = DC;
85  S->setEntity(DC);
86}
87
88void Sema::PopDeclContext() {
89  assert(CurContext && "DeclContext imbalance!");
90
91  CurContext = getContainingDC(CurContext);
92}
93
94/// Add this decl to the scope shadowed decl chains.
95void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
96  // Move up the scope chain until we find the nearest enclosing
97  // non-transparent context. The declaration will be introduced into this
98  // scope.
99  while (S->getEntity() &&
100         ((DeclContext *)S->getEntity())->isTransparentContext())
101    S = S->getParent();
102
103  S->AddDecl(D);
104
105  // Add scoped declarations into their context, so that they can be
106  // found later. Declarations without a context won't be inserted
107  // into any context.
108  if (ScopedDecl *SD = dyn_cast<ScopedDecl>(D))
109    CurContext->addDecl(Context, SD);
110
111  // C++ [basic.scope]p4:
112  //   -- exactly one declaration shall declare a class name or
113  //   enumeration name that is not a typedef name and the other
114  //   declarations shall all refer to the same object or
115  //   enumerator, or all refer to functions and function templates;
116  //   in this case the class name or enumeration name is hidden.
117  if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
118    // We are pushing the name of a tag (enum or class).
119    if (CurContext->getLookupContext()
120          == TD->getDeclContext()->getLookupContext()) {
121      // We're pushing the tag into the current context, which might
122      // require some reshuffling in the identifier resolver.
123      IdentifierResolver::iterator
124        I = IdResolver.begin(TD->getDeclName(), CurContext,
125                             false/*LookInParentCtx*/),
126        IEnd = IdResolver.end();
127      if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
128        NamedDecl *PrevDecl = *I;
129        for (; I != IEnd && isDeclInScope(*I, CurContext, S);
130             PrevDecl = *I, ++I) {
131          if (TD->declarationReplaces(*I)) {
132            // This is a redeclaration. Remove it from the chain and
133            // break out, so that we'll add in the shadowed
134            // declaration.
135            S->RemoveDecl(*I);
136            if (PrevDecl == *I) {
137              IdResolver.RemoveDecl(*I);
138              IdResolver.AddDecl(TD);
139              return;
140            } else {
141              IdResolver.RemoveDecl(*I);
142              break;
143            }
144          }
145        }
146
147        // There is already a declaration with the same name in the same
148        // scope, which is not a tag declaration. It must be found
149        // before we find the new declaration, so insert the new
150        // declaration at the end of the chain.
151        IdResolver.AddShadowedDecl(TD, PrevDecl);
152
153        return;
154      }
155    }
156  } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
157    // We are pushing the name of a function, which might be an
158    // overloaded name.
159    FunctionDecl *FD = cast<FunctionDecl>(D);
160    DeclContext *DC = FD->getDeclContext()->getLookupContext();
161    IdentifierResolver::iterator Redecl
162      = std::find_if(IdResolver.begin(FD->getDeclName(), DC,
163                                      false/*LookInParentCtx*/),
164                     IdResolver.end(),
165                     std::bind1st(std::mem_fun(&ScopedDecl::declarationReplaces),
166                                  FD));
167    if (Redecl != IdResolver.end()) {
168      // There is already a declaration of a function on our
169      // IdResolver chain. Replace it with this declaration.
170      S->RemoveDecl(*Redecl);
171      IdResolver.RemoveDecl(*Redecl);
172    }
173  }
174
175  IdResolver.AddDecl(D);
176}
177
178void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
179  if (S->decl_empty()) return;
180  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
181	 "Scope shouldn't contain decls!");
182
183  for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
184       I != E; ++I) {
185    Decl *TmpD = static_cast<Decl*>(*I);
186    assert(TmpD && "This decl didn't get pushed??");
187
188    assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
189    NamedDecl *D = cast<NamedDecl>(TmpD);
190
191    if (!D->getDeclName()) continue;
192
193    // Remove this name from our lexical scope.
194    IdResolver.RemoveDecl(D);
195  }
196}
197
198/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
199/// return 0 if one not found.
200ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
201  // The third "scope" argument is 0 since we aren't enabling lazy built-in
202  // creation from this context.
203  Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
204
205  return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
206}
207
208/// MaybeConstructOverloadSet - Name lookup has determined that the
209/// elements in [I, IEnd) have the name that we are looking for, and
210/// *I is a match for the namespace. This routine returns an
211/// appropriate Decl for name lookup, which may either be *I or an
212/// OverloadeFunctionDecl that represents the overloaded functions in
213/// [I, IEnd).
214///
215/// The existance of this routine is temporary; LookupDecl should
216/// probably be able to return multiple results, to deal with cases of
217/// ambiguity and overloaded functions without needing to create a
218/// Decl node.
219template<typename DeclIterator>
220static Decl *
221MaybeConstructOverloadSet(ASTContext &Context,
222                          DeclIterator I, DeclIterator IEnd) {
223  assert(I != IEnd && "Iterator range cannot be empty");
224  assert(!isa<OverloadedFunctionDecl>(*I) &&
225         "Cannot have an overloaded function");
226
227  if (isa<FunctionDecl>(*I)) {
228    // If we found a function, there might be more functions. If
229    // so, collect them into an overload set.
230    DeclIterator Last = I;
231    OverloadedFunctionDecl *Ovl = 0;
232    for (++Last; Last != IEnd && isa<FunctionDecl>(*Last); ++Last) {
233      if (!Ovl) {
234        // FIXME: We leak this overload set. Eventually, we want to
235        // stop building the declarations for these overload sets, so
236        // there will be nothing to leak.
237        Ovl = OverloadedFunctionDecl::Create(Context,
238                                         cast<ScopedDecl>(*I)->getDeclContext(),
239                                             (*I)->getDeclName());
240        Ovl->addOverload(cast<FunctionDecl>(*I));
241      }
242      Ovl->addOverload(cast<FunctionDecl>(*Last));
243    }
244
245    // If we had more than one function, we built an overload
246    // set. Return it.
247    if (Ovl)
248      return Ovl;
249  }
250
251  return *I;
252}
253
254/// LookupDecl - Look up the inner-most declaration in the specified
255/// namespace. NamespaceNameOnly - during lookup only namespace names
256/// are considered as required in C++ [basic.lookup.udir] 3.4.6.p1
257/// 'When looking up a namespace-name in a using-directive or
258/// namespace-alias-definition, only namespace names are considered.'
259Decl *Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
260                       const DeclContext *LookupCtx,
261                       bool enableLazyBuiltinCreation,
262                       bool LookInParent,
263                       bool NamespaceNameOnly) {
264  if (!Name) return 0;
265  unsigned NS = NSI;
266  if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
267    NS |= Decl::IDNS_Tag;
268
269  if (LookupCtx == 0 &&
270      (!getLangOptions().CPlusPlus || (NS == Decl::IDNS_Label))) {
271    // Unqualified name lookup in C/Objective-C and name lookup for
272    // labels in C++ is purely lexical, so search in the
273    // declarations attached to the name.
274    assert(!LookupCtx && "Can't perform qualified name lookup here");
275    assert(!NamespaceNameOnly && "Can't perform namespace name lookup here");
276    IdentifierResolver::iterator I
277      = IdResolver.begin(Name, CurContext, LookInParent);
278
279    // Scan up the scope chain looking for a decl that matches this
280    // identifier that is in the appropriate namespace.  This search
281    // should not take long, as shadowing of names is uncommon, and
282    // deep shadowing is extremely uncommon.
283    for (; I != IdResolver.end(); ++I)
284      if ((*I)->isInIdentifierNamespace(NS))
285        return *I;
286  } else if (LookupCtx) {
287    // Perform qualified name lookup into the LookupCtx.
288    // FIXME: Will need to look into base classes and such.
289    DeclContext::lookup_const_iterator I, E;
290    for (llvm::tie(I, E) = LookupCtx->lookup(Context, Name); I != E; ++I)
291      if ((*I)->isInIdentifierNamespace(NS)) {
292        // Ignore non-namespace names if we're only looking for namespaces.
293        if (NamespaceNameOnly && !isa<NamespaceDecl>(*I)) continue;
294
295        return MaybeConstructOverloadSet(Context, I, E);
296      }
297  } else {
298    // Name lookup for ordinary names and tag names in C++ requires
299    // looking into scopes that aren't strictly lexical, and
300    // therefore we walk through the context as well as walking
301    // through the scopes.
302    IdentifierResolver::iterator
303      I = IdResolver.begin(Name, CurContext, true/*LookInParentCtx*/),
304      IEnd = IdResolver.end();
305    for (; S; S = S->getParent()) {
306      // Check whether the IdResolver has anything in this scope.
307      // FIXME: The isDeclScope check could be expensive. Can we do better?
308      for (; I != IEnd && S->isDeclScope(*I); ++I) {
309        if ((*I)->isInIdentifierNamespace(NS)) {
310          // Ignore non-namespace names if we're only looking for namespaces.
311          if (NamespaceNameOnly && !isa<NamespaceDecl>(*I))
312            continue;
313
314          // We found something.  Look for anything else in our scope
315          // with this same name and in an acceptable identifier
316          // namespace, so that we can construct an overload set if we
317          // need to.
318          IdentifierResolver::iterator LastI = I;
319          for (++LastI; LastI != IEnd; ++LastI) {
320            if (!(*LastI)->isInIdentifierNamespace(NS) ||
321                !S->isDeclScope(*LastI))
322              break;
323          }
324          return MaybeConstructOverloadSet(Context, I, LastI);
325        }
326      }
327
328      // If there is an entity associated with this scope, it's a
329      // DeclContext. We might need to perform qualified lookup into
330      // it.
331      DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
332      while (Ctx && Ctx->isFunctionOrMethod())
333        Ctx = Ctx->getParent();
334      while (Ctx && (Ctx->isNamespace() || Ctx->isRecord())) {
335        // Look for declarations of this name in this scope.
336        DeclContext::lookup_const_iterator I, E;
337        for (llvm::tie(I, E) = Ctx->lookup(Context, Name); I != E; ++I) {
338          // FIXME: Cache this result in the IdResolver
339          if ((*I)->isInIdentifierNamespace(NS)) {
340            if (NamespaceNameOnly && !isa<NamespaceDecl>(*I))
341              continue;
342            return MaybeConstructOverloadSet(Context, I, E);
343          }
344        }
345
346        Ctx = Ctx->getParent();
347      }
348
349      if (!LookInParent && !Ctx->isTransparentContext())
350        return 0;
351    }
352  }
353
354  // If we didn't find a use of this identifier, and if the identifier
355  // corresponds to a compiler builtin, create the decl object for the builtin
356  // now, injecting it into translation unit scope, and return it.
357  if (NS & Decl::IDNS_Ordinary) {
358    IdentifierInfo *II = Name.getAsIdentifierInfo();
359    if (enableLazyBuiltinCreation && II &&
360        (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
361      // If this is a builtin on this (or all) targets, create the decl.
362      if (unsigned BuiltinID = II->getBuiltinID())
363        return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
364    }
365    if (getLangOptions().ObjC1 && II) {
366      // @interface and @compatibility_alias introduce typedef-like names.
367      // Unlike typedef's, they can only be introduced at file-scope (and are
368      // therefore not scoped decls). They can, however, be shadowed by
369      // other names in IDNS_Ordinary.
370      ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
371      if (IDI != ObjCInterfaceDecls.end())
372        return IDI->second;
373      ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
374      if (I != ObjCAliasDecls.end())
375        return I->second->getClassInterface();
376    }
377  }
378  return 0;
379}
380
381void Sema::InitBuiltinVaListType() {
382  if (!Context.getBuiltinVaListType().isNull())
383    return;
384
385  IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
386  Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
387  TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
388  Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
389}
390
391/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
392/// lazily create a decl for it.
393ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
394                                      Scope *S) {
395  Builtin::ID BID = (Builtin::ID)bid;
396
397  if (Context.BuiltinInfo.hasVAListUse(BID))
398    InitBuiltinVaListType();
399
400  QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
401  FunctionDecl *New = FunctionDecl::Create(Context,
402                                           Context.getTranslationUnitDecl(),
403                                           SourceLocation(), II, R,
404                                           FunctionDecl::Extern, false, 0);
405
406  // Create Decl objects for each parameter, adding them to the
407  // FunctionDecl.
408  if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
409    llvm::SmallVector<ParmVarDecl*, 16> Params;
410    for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
411      Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
412                                           FT->getArgType(i), VarDecl::None, 0,
413                                           0));
414    New->setParams(&Params[0], Params.size());
415  }
416
417
418
419  // TUScope is the translation-unit scope to insert this function into.
420  PushOnScopeChains(New, TUScope);
421  return New;
422}
423
424/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
425/// everything from the standard library is defined.
426NamespaceDecl *Sema::GetStdNamespace() {
427  if (!StdNamespace) {
428    IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
429    DeclContext *Global = Context.getTranslationUnitDecl();
430    Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Tag | Decl::IDNS_Ordinary,
431                           0, Global, /*enableLazyBuiltinCreation=*/false);
432    StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
433  }
434  return StdNamespace;
435}
436
437/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
438/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
439/// situation, merging decls or emitting diagnostics as appropriate.
440///
441TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
442  // Allow multiple definitions for ObjC built-in typedefs.
443  // FIXME: Verify the underlying types are equivalent!
444  if (getLangOptions().ObjC1) {
445    const IdentifierInfo *TypeID = New->getIdentifier();
446    switch (TypeID->getLength()) {
447    default: break;
448    case 2:
449      if (!TypeID->isStr("id"))
450        break;
451      Context.setObjCIdType(New);
452      return New;
453    case 5:
454      if (!TypeID->isStr("Class"))
455        break;
456      Context.setObjCClassType(New);
457      return New;
458    case 3:
459      if (!TypeID->isStr("SEL"))
460        break;
461      Context.setObjCSelType(New);
462      return New;
463    case 8:
464      if (!TypeID->isStr("Protocol"))
465        break;
466      Context.setObjCProtoType(New->getUnderlyingType());
467      return New;
468    }
469    // Fall through - the typedef name was not a builtin type.
470  }
471  // Verify the old decl was also a typedef.
472  TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
473  if (!Old) {
474    Diag(New->getLocation(), diag::err_redefinition_different_kind)
475      << New->getDeclName();
476    Diag(OldD->getLocation(), diag::note_previous_definition);
477    return New;
478  }
479
480  // If the typedef types are not identical, reject them in all languages and
481  // with any extensions enabled.
482  if (Old->getUnderlyingType() != New->getUnderlyingType() &&
483      Context.getCanonicalType(Old->getUnderlyingType()) !=
484      Context.getCanonicalType(New->getUnderlyingType())) {
485    Diag(New->getLocation(), diag::err_redefinition_different_typedef)
486      << New->getUnderlyingType() << Old->getUnderlyingType();
487    Diag(Old->getLocation(), diag::note_previous_definition);
488    return Old;
489  }
490
491  if (getLangOptions().Microsoft) return New;
492
493  // C++ [dcl.typedef]p2:
494  //   In a given non-class scope, a typedef specifier can be used to
495  //   redefine the name of any type declared in that scope to refer
496  //   to the type to which it already refers.
497  if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
498    return New;
499
500  // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
501  // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
502  // *either* declaration is in a system header. The code below implements
503  // this adhoc compatibility rule. FIXME: The following code will not
504  // work properly when compiling ".i" files (containing preprocessed output).
505  if (PP.getDiagnostics().getSuppressSystemWarnings()) {
506    SourceManager &SrcMgr = Context.getSourceManager();
507    if (SrcMgr.isInSystemHeader(Old->getLocation()))
508      return New;
509    if (SrcMgr.isInSystemHeader(New->getLocation()))
510      return New;
511  }
512
513  Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
514  Diag(Old->getLocation(), diag::note_previous_definition);
515  return New;
516}
517
518/// DeclhasAttr - returns true if decl Declaration already has the target
519/// attribute.
520static bool DeclHasAttr(const Decl *decl, const Attr *target) {
521  for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
522    if (attr->getKind() == target->getKind())
523      return true;
524
525  return false;
526}
527
528/// MergeAttributes - append attributes from the Old decl to the New one.
529static void MergeAttributes(Decl *New, Decl *Old) {
530  Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
531
532  while (attr) {
533     tmp = attr;
534     attr = attr->getNext();
535
536    if (!DeclHasAttr(New, tmp)) {
537       tmp->setInherited(true);
538       New->addAttr(tmp);
539    } else {
540       tmp->setNext(0);
541       delete(tmp);
542    }
543  }
544
545  Old->invalidateAttrs();
546}
547
548/// MergeFunctionDecl - We just parsed a function 'New' from
549/// declarator D which has the same name and scope as a previous
550/// declaration 'Old'.  Figure out how to resolve this situation,
551/// merging decls or emitting diagnostics as appropriate.
552/// Redeclaration will be set true if this New is a redeclaration OldD.
553///
554/// In C++, New and Old must be declarations that are not
555/// overloaded. Use IsOverload to determine whether New and Old are
556/// overloaded, and to select the Old declaration that New should be
557/// merged with.
558FunctionDecl *
559Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
560  assert(!isa<OverloadedFunctionDecl>(OldD) &&
561         "Cannot merge with an overloaded function declaration");
562
563  Redeclaration = false;
564  // Verify the old decl was also a function.
565  FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
566  if (!Old) {
567    Diag(New->getLocation(), diag::err_redefinition_different_kind)
568      << New->getDeclName();
569    Diag(OldD->getLocation(), diag::note_previous_definition);
570    return New;
571  }
572
573  // Determine whether the previous declaration was a definition,
574  // implicit declaration, or a declaration.
575  diag::kind PrevDiag;
576  if (Old->isThisDeclarationADefinition())
577    PrevDiag = diag::note_previous_definition;
578  else if (Old->isImplicit())
579    PrevDiag = diag::note_previous_implicit_declaration;
580  else
581    PrevDiag = diag::note_previous_declaration;
582
583  QualType OldQType = Context.getCanonicalType(Old->getType());
584  QualType NewQType = Context.getCanonicalType(New->getType());
585
586  if (getLangOptions().CPlusPlus) {
587    // (C++98 13.1p2):
588    //   Certain function declarations cannot be overloaded:
589    //     -- Function declarations that differ only in the return type
590    //        cannot be overloaded.
591    QualType OldReturnType
592      = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
593    QualType NewReturnType
594      = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
595    if (OldReturnType != NewReturnType) {
596      Diag(New->getLocation(), diag::err_ovl_diff_return_type);
597      Diag(Old->getLocation(), PrevDiag);
598      Redeclaration = true;
599      return New;
600    }
601
602    const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
603    const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
604    if (OldMethod && NewMethod) {
605      //    -- Member function declarations with the same name and the
606      //       same parameter types cannot be overloaded if any of them
607      //       is a static member function declaration.
608      if (OldMethod->isStatic() || NewMethod->isStatic()) {
609        Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
610        Diag(Old->getLocation(), PrevDiag);
611        return New;
612      }
613
614      // C++ [class.mem]p1:
615      //   [...] A member shall not be declared twice in the
616      //   member-specification, except that a nested class or member
617      //   class template can be declared and then later defined.
618      if (OldMethod->getLexicalDeclContext() ==
619            NewMethod->getLexicalDeclContext()) {
620        unsigned NewDiag;
621        if (isa<CXXConstructorDecl>(OldMethod))
622          NewDiag = diag::err_constructor_redeclared;
623        else if (isa<CXXDestructorDecl>(NewMethod))
624          NewDiag = diag::err_destructor_redeclared;
625        else if (isa<CXXConversionDecl>(NewMethod))
626          NewDiag = diag::err_conv_function_redeclared;
627        else
628          NewDiag = diag::err_member_redeclared;
629
630        Diag(New->getLocation(), NewDiag);
631        Diag(Old->getLocation(), PrevDiag);
632      }
633    }
634
635    // (C++98 8.3.5p3):
636    //   All declarations for a function shall agree exactly in both the
637    //   return type and the parameter-type-list.
638    if (OldQType == NewQType) {
639      // We have a redeclaration.
640      MergeAttributes(New, Old);
641      Redeclaration = true;
642      return MergeCXXFunctionDecl(New, Old);
643    }
644
645    // Fall through for conflicting redeclarations and redefinitions.
646  }
647
648  // C: Function types need to be compatible, not identical. This handles
649  // duplicate function decls like "void f(int); void f(enum X);" properly.
650  if (!getLangOptions().CPlusPlus &&
651      Context.typesAreCompatible(OldQType, NewQType)) {
652    MergeAttributes(New, Old);
653    Redeclaration = true;
654    return New;
655  }
656
657  // A function that has already been declared has been redeclared or defined
658  // with a different type- show appropriate diagnostic
659
660  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
661  // TODO: This is totally simplistic.  It should handle merging functions
662  // together etc, merging extern int X; int X; ...
663  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
664  Diag(Old->getLocation(), PrevDiag);
665  return New;
666}
667
668/// Predicate for C "tentative" external object definitions (C99 6.9.2).
669static bool isTentativeDefinition(VarDecl *VD) {
670  if (VD->isFileVarDecl())
671    return (!VD->getInit() &&
672            (VD->getStorageClass() == VarDecl::None ||
673             VD->getStorageClass() == VarDecl::Static));
674  return false;
675}
676
677/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
678/// when dealing with C "tentative" external object definitions (C99 6.9.2).
679void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
680  bool VDIsTentative = isTentativeDefinition(VD);
681  bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
682
683  // FIXME: I don't think this will actually see all of the
684  // redefinitions. Can't we check this property on-the-fly?
685  for (IdentifierResolver::iterator
686       I = IdResolver.begin(VD->getIdentifier(),
687                            VD->getDeclContext(), false/*LookInParentCtx*/),
688       E = IdResolver.end(); I != E; ++I) {
689    if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
690      VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
691
692      // Handle the following case:
693      //   int a[10];
694      //   int a[];   - the code below makes sure we set the correct type.
695      //   int a[11]; - this is an error, size isn't 10.
696      if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
697          OldDecl->getType()->isConstantArrayType())
698        VD->setType(OldDecl->getType());
699
700      // Check for "tentative" definitions. We can't accomplish this in
701      // MergeVarDecl since the initializer hasn't been attached.
702      if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
703        continue;
704
705      // Handle __private_extern__ just like extern.
706      if (OldDecl->getStorageClass() != VarDecl::Extern &&
707          OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
708          VD->getStorageClass() != VarDecl::Extern &&
709          VD->getStorageClass() != VarDecl::PrivateExtern) {
710        Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
711        Diag(OldDecl->getLocation(), diag::note_previous_definition);
712      }
713    }
714  }
715}
716
717/// MergeVarDecl - We just parsed a variable 'New' which has the same name
718/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
719/// situation, merging decls or emitting diagnostics as appropriate.
720///
721/// Tentative definition rules (C99 6.9.2p2) are checked by
722/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
723/// definitions here, since the initializer hasn't been attached.
724///
725VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
726  // Verify the old decl was also a variable.
727  VarDecl *Old = dyn_cast<VarDecl>(OldD);
728  if (!Old) {
729    Diag(New->getLocation(), diag::err_redefinition_different_kind)
730      << New->getDeclName();
731    Diag(OldD->getLocation(), diag::note_previous_definition);
732    return New;
733  }
734
735  MergeAttributes(New, Old);
736
737  // Verify the types match.
738  QualType OldCType = Context.getCanonicalType(Old->getType());
739  QualType NewCType = Context.getCanonicalType(New->getType());
740  if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
741    Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
742    Diag(Old->getLocation(), diag::note_previous_definition);
743    return New;
744  }
745  // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
746  if (New->getStorageClass() == VarDecl::Static &&
747      (Old->getStorageClass() == VarDecl::None ||
748       Old->getStorageClass() == VarDecl::Extern)) {
749    Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
750    Diag(Old->getLocation(), diag::note_previous_definition);
751    return New;
752  }
753  // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
754  if (New->getStorageClass() != VarDecl::Static &&
755      Old->getStorageClass() == VarDecl::Static) {
756    Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
757    Diag(Old->getLocation(), diag::note_previous_definition);
758    return New;
759  }
760  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
761  if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
762    Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
763    Diag(Old->getLocation(), diag::note_previous_definition);
764  }
765  return New;
766}
767
768/// CheckParmsForFunctionDef - Check that the parameters of the given
769/// function are appropriate for the definition of a function. This
770/// takes care of any checks that cannot be performed on the
771/// declaration itself, e.g., that the types of each of the function
772/// parameters are complete.
773bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
774  bool HasInvalidParm = false;
775  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
776    ParmVarDecl *Param = FD->getParamDecl(p);
777
778    // C99 6.7.5.3p4: the parameters in a parameter type list in a
779    // function declarator that is part of a function definition of
780    // that function shall not have incomplete type.
781    if (Param->getType()->isIncompleteType() &&
782        !Param->isInvalidDecl()) {
783      Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type)
784        << Param->getType();
785      Param->setInvalidDecl();
786      HasInvalidParm = true;
787    }
788
789    // C99 6.9.1p5: If the declarator includes a parameter type list, the
790    // declaration of each parameter shall include an identifier.
791    if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
792      Diag(Param->getLocation(), diag::err_parameter_name_omitted);
793  }
794
795  return HasInvalidParm;
796}
797
798/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
799/// no declarator (e.g. "struct foo;") is parsed.
800Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
801  // FIXME: Isn't that more of a parser diagnostic than a sema diagnostic?
802  if (!DS.isMissingDeclaratorOk()) {
803    // FIXME: This diagnostic is emitted even when various previous
804    // errors occurred (see e.g. test/Sema/decl-invalid.c). However,
805    // DeclSpec has no means of communicating this information, and the
806    // responsible parser functions are quite far apart.
807    Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
808      << DS.getSourceRange();
809    return 0;
810  }
811
812  TagDecl *Tag
813    = dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
814  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
815    if (!Record->getDeclName() && Record->isDefinition() &&
816        !Record->isInvalidDecl())
817      return BuildAnonymousStructOrUnion(S, DS, Record);
818  }
819
820  return Tag;
821}
822
823/// InjectAnonymousStructOrUnionMembers - Inject the members of the
824/// anonymous struct or union AnonRecord into the owning context Owner
825/// and scope S. This routine will be invoked just after we realize
826/// that an unnamed union or struct is actually an anonymous union or
827/// struct, e.g.,
828///
829/// @code
830/// union {
831///   int i;
832///   float f;
833/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
834///    // f into the surrounding scope.x
835/// @endcode
836///
837/// This routine is recursive, injecting the names of nested anonymous
838/// structs/unions into the owning context and scope as well.
839bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
840                                               RecordDecl *AnonRecord) {
841  bool Invalid = false;
842  for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
843                               FEnd = AnonRecord->field_end();
844       F != FEnd; ++F) {
845    if ((*F)->getDeclName()) {
846      Decl *PrevDecl = LookupDecl((*F)->getDeclName(), Decl::IDNS_Ordinary,
847                                  S, Owner, false, false, false);
848      if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
849        // C++ [class.union]p2:
850        //   The names of the members of an anonymous union shall be
851        //   distinct from the names of any other entity in the
852        //   scope in which the anonymous union is declared.
853        unsigned diagKind
854          = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
855                                 : diag::err_anonymous_struct_member_redecl;
856        Diag((*F)->getLocation(), diagKind)
857          << (*F)->getDeclName();
858        Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
859        Invalid = true;
860      } else {
861        // C++ [class.union]p2:
862        //   For the purpose of name lookup, after the anonymous union
863        //   definition, the members of the anonymous union are
864        //   considered to have been defined in the scope in which the
865        //   anonymous union is declared.
866        Owner->insert(Context, *F);
867        S->AddDecl(*F);
868        IdResolver.AddDecl(*F);
869      }
870    } else if (const RecordType *InnerRecordType
871                 = (*F)->getType()->getAsRecordType()) {
872      RecordDecl *InnerRecord = InnerRecordType->getDecl();
873      if (InnerRecord->isAnonymousStructOrUnion())
874        Invalid = Invalid ||
875          InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
876    }
877  }
878
879  return Invalid;
880}
881
882/// ActOnAnonymousStructOrUnion - Handle the declaration of an
883/// anonymous structure or union. Anonymous unions are a C++ feature
884/// (C++ [class.union]) and a GNU C extension; anonymous structures
885/// are a GNU C and GNU C++ extension.
886Sema::DeclTy *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
887                                                RecordDecl *Record) {
888  DeclContext *Owner = Record->getDeclContext();
889
890  // Diagnose whether this anonymous struct/union is an extension.
891  if (Record->isUnion() && !getLangOptions().CPlusPlus)
892    Diag(Record->getLocation(), diag::ext_anonymous_union);
893  else if (!Record->isUnion())
894    Diag(Record->getLocation(), diag::ext_anonymous_struct);
895
896  // C and C++ require different kinds of checks for anonymous
897  // structs/unions.
898  bool Invalid = false;
899  if (getLangOptions().CPlusPlus) {
900    const char* PrevSpec = 0;
901    // C++ [class.union]p3:
902    //   Anonymous unions declared in a named namespace or in the
903    //   global namespace shall be declared static.
904    if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
905        (isa<TranslationUnitDecl>(Owner) ||
906         (isa<NamespaceDecl>(Owner) &&
907          cast<NamespaceDecl>(Owner)->getDeclName()))) {
908      Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
909      Invalid = true;
910
911      // Recover by adding 'static'.
912      DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
913    }
914    // C++ [class.union]p3:
915    //   A storage class is not allowed in a declaration of an
916    //   anonymous union in a class scope.
917    else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
918             isa<RecordDecl>(Owner)) {
919      Diag(DS.getStorageClassSpecLoc(),
920           diag::err_anonymous_union_with_storage_spec);
921      Invalid = true;
922
923      // Recover by removing the storage specifier.
924      DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
925                             PrevSpec);
926    }
927
928    // C++ [class.union]p2:
929    //   The member-specification of an anonymous union shall only
930    //   define non-static data members. [Note: nested types and
931    //   functions cannot be declared within an anonymous union. ]
932    for (DeclContext::decl_iterator Mem = Record->decls_begin(),
933                                 MemEnd = Record->decls_end();
934         Mem != MemEnd; ++Mem) {
935      if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
936        // C++ [class.union]p3:
937        //   An anonymous union shall not have private or protected
938        //   members (clause 11).
939        if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
940          Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
941            << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
942          Invalid = true;
943        }
944      } else if ((*Mem)->isImplicit()) {
945        // Any implicit members are fine.
946      } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
947        if (!MemRecord->isAnonymousStructOrUnion() &&
948            MemRecord->getDeclName()) {
949          // This is a nested type declaration.
950          Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
951            << (int)Record->isUnion();
952          Invalid = true;
953        }
954      } else {
955        // We have something that isn't a non-static data
956        // member. Complain about it.
957        unsigned DK = diag::err_anonymous_record_bad_member;
958        if (isa<TypeDecl>(*Mem))
959          DK = diag::err_anonymous_record_with_type;
960        else if (isa<FunctionDecl>(*Mem))
961          DK = diag::err_anonymous_record_with_function;
962        else if (isa<VarDecl>(*Mem))
963          DK = diag::err_anonymous_record_with_static;
964        Diag((*Mem)->getLocation(), DK)
965            << (int)Record->isUnion();
966          Invalid = true;
967      }
968    }
969  } else {
970    // FIXME: Check GNU C semantics
971  }
972
973  if (!Record->isUnion() && !Owner->isRecord()) {
974    Diag(Record->getLocation(), diag::err_anonymous_struct_not_member);
975    Invalid = true;
976  }
977
978  // Create a declaration for this anonymous struct/union.
979  ScopedDecl *Anon = 0;
980  if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
981    Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
982                             /*IdentifierInfo=*/0,
983                             Context.getTypeDeclType(Record),
984                             /*BitWidth=*/0, /*Mutable=*/false,
985                             /*PrevDecl=*/0);
986    Anon->setAccess(AS_public);
987    if (getLangOptions().CPlusPlus)
988      FieldCollector->Add(cast<FieldDecl>(Anon));
989  } else {
990    VarDecl::StorageClass SC;
991    switch (DS.getStorageClassSpec()) {
992    default: assert(0 && "Unknown storage class!");
993    case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
994    case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
995    case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
996    case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
997    case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
998    case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
999    case DeclSpec::SCS_mutable:
1000      // mutable can only appear on non-static class members, so it's always
1001      // an error here
1002      Diag(Record->getLocation(), diag::err_mutable_nonmember);
1003      Invalid = true;
1004      SC = VarDecl::None;
1005      break;
1006    }
1007
1008    Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
1009                           /*IdentifierInfo=*/0,
1010                           Context.getTypeDeclType(Record),
1011                           SC, /*FIXME:LastDeclarator=*/0,
1012                           DS.getSourceRange().getBegin());
1013  }
1014  Anon->setImplicit();
1015
1016  // Add the anonymous struct/union object to the current
1017  // context. We'll be referencing this object when we refer to one of
1018  // its members.
1019  Owner->addDecl(Context, Anon);
1020
1021  // Inject the members of the anonymous struct/union into the owning
1022  // context and into the identifier resolver chain for name lookup
1023  // purposes.
1024  Invalid = Invalid || InjectAnonymousStructOrUnionMembers(S, Owner, Record);
1025
1026  // Mark this as an anonymous struct/union type. Note that we do not
1027  // do this until after we have already checked and injected the
1028  // members of this anonymous struct/union type, because otherwise
1029  // the members could be injected twice: once by DeclContext when it
1030  // builds its lookup table, and once by
1031  // InjectAnonymousStructOrUnionMembers.
1032  Record->setAnonymousStructOrUnion(true);
1033
1034  if (Invalid)
1035    Anon->setInvalidDecl();
1036
1037  return Anon;
1038}
1039
1040bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
1041  // Get the type before calling CheckSingleAssignmentConstraints(), since
1042  // it can promote the expression.
1043  QualType InitType = Init->getType();
1044
1045  if (getLangOptions().CPlusPlus)
1046    return PerformCopyInitialization(Init, DeclType, "initializing");
1047
1048  AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
1049  return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
1050                                  InitType, Init, "initializing");
1051}
1052
1053bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
1054  const ArrayType *AT = Context.getAsArrayType(DeclT);
1055
1056  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
1057    // C99 6.7.8p14. We have an array of character type with unknown size
1058    // being initialized to a string literal.
1059    llvm::APSInt ConstVal(32);
1060    ConstVal = strLiteral->getByteLength() + 1;
1061    // Return a new array type (C99 6.7.8p22).
1062    DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
1063                                         ArrayType::Normal, 0);
1064  } else {
1065    const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
1066    // C99 6.7.8p14. We have an array of character type with known size.
1067    // FIXME: Avoid truncation for 64-bit length strings.
1068    if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
1069      Diag(strLiteral->getSourceRange().getBegin(),
1070           diag::warn_initializer_string_for_char_array_too_long)
1071        << strLiteral->getSourceRange();
1072  }
1073  // Set type from "char *" to "constant array of char".
1074  strLiteral->setType(DeclT);
1075  // For now, we always return false (meaning success).
1076  return false;
1077}
1078
1079StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
1080  const ArrayType *AT = Context.getAsArrayType(DeclType);
1081  if (AT && AT->getElementType()->isCharType()) {
1082    return dyn_cast<StringLiteral>(Init);
1083  }
1084  return 0;
1085}
1086
1087bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
1088                                 SourceLocation InitLoc,
1089                                 DeclarationName InitEntity) {
1090  if (DeclType->isDependentType() || Init->isTypeDependent())
1091    return false;
1092
1093  // C++ [dcl.init.ref]p1:
1094  //   A variable declared to be a T&, that is "reference to type T"
1095  //   (8.3.2), shall be initialized by an object, or function, of
1096  //   type T or by an object that can be converted into a T.
1097  if (DeclType->isReferenceType())
1098    return CheckReferenceInit(Init, DeclType);
1099
1100  // C99 6.7.8p3: The type of the entity to be initialized shall be an array
1101  // of unknown size ("[]") or an object type that is not a variable array type.
1102  if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
1103    return Diag(InitLoc,  diag::err_variable_object_no_init)
1104      << VAT->getSizeExpr()->getSourceRange();
1105
1106  InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
1107  if (!InitList) {
1108    // FIXME: Handle wide strings
1109    if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
1110      return CheckStringLiteralInit(strLiteral, DeclType);
1111
1112    // C++ [dcl.init]p14:
1113    //   -- If the destination type is a (possibly cv-qualified) class
1114    //      type:
1115    if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
1116      QualType DeclTypeC = Context.getCanonicalType(DeclType);
1117      QualType InitTypeC = Context.getCanonicalType(Init->getType());
1118
1119      //   -- If the initialization is direct-initialization, or if it is
1120      //      copy-initialization where the cv-unqualified version of the
1121      //      source type is the same class as, or a derived class of, the
1122      //      class of the destination, constructors are considered.
1123      if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
1124          IsDerivedFrom(InitTypeC, DeclTypeC)) {
1125        CXXConstructorDecl *Constructor
1126          = PerformInitializationByConstructor(DeclType, &Init, 1,
1127                                               InitLoc, Init->getSourceRange(),
1128                                               InitEntity, IK_Copy);
1129        return Constructor == 0;
1130      }
1131
1132      //   -- Otherwise (i.e., for the remaining copy-initialization
1133      //      cases), user-defined conversion sequences that can
1134      //      convert from the source type to the destination type or
1135      //      (when a conversion function is used) to a derived class
1136      //      thereof are enumerated as described in 13.3.1.4, and the
1137      //      best one is chosen through overload resolution
1138      //      (13.3). If the conversion cannot be done or is
1139      //      ambiguous, the initialization is ill-formed. The
1140      //      function selected is called with the initializer
1141      //      expression as its argument; if the function is a
1142      //      constructor, the call initializes a temporary of the
1143      //      destination type.
1144      // FIXME: We're pretending to do copy elision here; return to
1145      // this when we have ASTs for such things.
1146      if (!PerformImplicitConversion(Init, DeclType, "initializing"))
1147        return false;
1148
1149      if (InitEntity)
1150        return Diag(InitLoc, diag::err_cannot_initialize_decl)
1151          << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1152          << Init->getType() << Init->getSourceRange();
1153      else
1154        return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
1155          << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1156          << Init->getType() << Init->getSourceRange();
1157    }
1158
1159    // C99 6.7.8p16.
1160    if (DeclType->isArrayType())
1161      return Diag(Init->getLocStart(), diag::err_array_init_list_required)
1162        << Init->getSourceRange();
1163
1164    return CheckSingleInitializer(Init, DeclType);
1165  } else if (getLangOptions().CPlusPlus) {
1166    // C++ [dcl.init]p14:
1167    //   [...] If the class is an aggregate (8.5.1), and the initializer
1168    //   is a brace-enclosed list, see 8.5.1.
1169    //
1170    // Note: 8.5.1 is handled below; here, we diagnose the case where
1171    // we have an initializer list and a destination type that is not
1172    // an aggregate.
1173    // FIXME: In C++0x, this is yet another form of initialization.
1174    if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
1175      const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1176      if (!ClassDecl->isAggregate())
1177        return Diag(InitLoc, diag::err_init_non_aggr_init_list)
1178           << DeclType << Init->getSourceRange();
1179    }
1180  }
1181
1182  InitListChecker CheckInitList(this, InitList, DeclType);
1183  return CheckInitList.HadError();
1184}
1185
1186/// GetNameForDeclarator - Determine the full declaration name for the
1187/// given Declarator.
1188DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1189  switch (D.getKind()) {
1190  case Declarator::DK_Abstract:
1191    assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1192    return DeclarationName();
1193
1194  case Declarator::DK_Normal:
1195    assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1196    return DeclarationName(D.getIdentifier());
1197
1198  case Declarator::DK_Constructor: {
1199    QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1200    Ty = Context.getCanonicalType(Ty);
1201    return Context.DeclarationNames.getCXXConstructorName(Ty);
1202  }
1203
1204  case Declarator::DK_Destructor: {
1205    QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1206    Ty = Context.getCanonicalType(Ty);
1207    return Context.DeclarationNames.getCXXDestructorName(Ty);
1208  }
1209
1210  case Declarator::DK_Conversion: {
1211    QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1212    Ty = Context.getCanonicalType(Ty);
1213    return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1214  }
1215
1216  case Declarator::DK_Operator:
1217    assert(D.getIdentifier() == 0 && "operator names have no identifier");
1218    return Context.DeclarationNames.getCXXOperatorName(
1219                                                D.getOverloadedOperator());
1220  }
1221
1222  assert(false && "Unknown name kind");
1223  return DeclarationName();
1224}
1225
1226/// isNearlyMatchingMemberFunction - Determine whether the C++ member
1227/// functions Declaration and Definition are "nearly" matching. This
1228/// heuristic is used to improve diagnostics in the case where an
1229/// out-of-line member function definition doesn't match any
1230/// declaration within the class.
1231static bool isNearlyMatchingMemberFunction(ASTContext &Context,
1232                                           FunctionDecl *Declaration,
1233                                           FunctionDecl *Definition) {
1234  if (Declaration->param_size() != Definition->param_size())
1235    return false;
1236  for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1237    QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1238    QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1239
1240    DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1241    DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1242    if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1243      return false;
1244  }
1245
1246  return true;
1247}
1248
1249Sema::DeclTy *
1250Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1251                      bool IsFunctionDefinition) {
1252  ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
1253  DeclarationName Name = GetNameForDeclarator(D);
1254
1255  // All of these full declarators require an identifier.  If it doesn't have
1256  // one, the ParsedFreeStandingDeclSpec action should be used.
1257  if (!Name) {
1258    if (!D.getInvalidType())  // Reject this if we think it is valid.
1259      Diag(D.getDeclSpec().getSourceRange().getBegin(),
1260           diag::err_declarator_need_ident)
1261        << D.getDeclSpec().getSourceRange() << D.getSourceRange();
1262    return 0;
1263  }
1264
1265  // The scope passed in may not be a decl scope.  Zip up the scope tree until
1266  // we find one that is.
1267  while ((S->getFlags() & Scope::DeclScope) == 0 ||
1268        (S->getFlags() & Scope::TemplateParamScope) != 0)
1269    S = S->getParent();
1270
1271  DeclContext *DC;
1272  Decl *PrevDecl;
1273  ScopedDecl *New;
1274  bool InvalidDecl = false;
1275
1276  // See if this is a redefinition of a variable in the same scope.
1277  if (!D.getCXXScopeSpec().isSet()) {
1278    DC = CurContext;
1279    PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
1280  } else { // Something like "int foo::x;"
1281    DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
1282    PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
1283
1284    // C++ 7.3.1.2p2:
1285    // Members (including explicit specializations of templates) of a named
1286    // namespace can also be defined outside that namespace by explicit
1287    // qualification of the name being defined, provided that the entity being
1288    // defined was already declared in the namespace and the definition appears
1289    // after the point of declaration in a namespace that encloses the
1290    // declarations namespace.
1291    //
1292    // Note that we only check the context at this point. We don't yet
1293    // have enough information to make sure that PrevDecl is actually
1294    // the declaration we want to match. For example, given:
1295    //
1296    //   class X {
1297    //     void f();
1298    //     void f(float);
1299    //   };
1300    //
1301    //   void X::f(int) { } // ill-formed
1302    //
1303    // In this case, PrevDecl will point to the overload set
1304    // containing the two f's declared in X, but neither of them
1305    // matches.
1306    if (!CurContext->Encloses(DC)) {
1307      // The qualifying scope doesn't enclose the original declaration.
1308      // Emit diagnostic based on current scope.
1309      SourceLocation L = D.getIdentifierLoc();
1310      SourceRange R = D.getCXXScopeSpec().getRange();
1311      if (isa<FunctionDecl>(CurContext)) {
1312        Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
1313      } else {
1314        Diag(L, diag::err_invalid_declarator_scope)
1315          << Name << cast<NamedDecl>(DC)->getDeclName() << R;
1316      }
1317      InvalidDecl = true;
1318    }
1319  }
1320
1321  if (PrevDecl && PrevDecl->isTemplateParameter()) {
1322    // Maybe we will complain about the shadowed template parameter.
1323    InvalidDecl = InvalidDecl
1324      || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
1325    // Just pretend that we didn't see the previous declaration.
1326    PrevDecl = 0;
1327  }
1328
1329  // In C++, the previous declaration we find might be a tag type
1330  // (class or enum). In this case, the new declaration will hide the
1331  // tag type.
1332  if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
1333    PrevDecl = 0;
1334
1335  QualType R = GetTypeForDeclarator(D, S);
1336  assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1337
1338  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
1339    // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1340    if (D.getCXXScopeSpec().isSet()) {
1341      Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1342        << D.getCXXScopeSpec().getRange();
1343      InvalidDecl = true;
1344      // Pretend we didn't see the scope specifier.
1345      DC = 0;
1346    }
1347
1348    // Check that there are no default arguments (C++ only).
1349    if (getLangOptions().CPlusPlus)
1350      CheckExtraCXXDefaultArguments(D);
1351
1352    TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
1353    if (!NewTD) return 0;
1354
1355    // Handle attributes prior to checking for duplicates in MergeVarDecl
1356    ProcessDeclAttributes(NewTD, D);
1357    // Merge the decl with the existing one if appropriate. If the decl is
1358    // in an outer scope, it isn't the same thing.
1359    if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1360      NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1361      if (NewTD == 0) return 0;
1362    }
1363    New = NewTD;
1364    if (S->getFnParent() == 0) {
1365      // C99 6.7.7p2: If a typedef name specifies a variably modified type
1366      // then it shall have block scope.
1367      if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
1368        if (NewTD->getUnderlyingType()->isVariableArrayType())
1369          Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1370        else
1371          Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1372
1373        InvalidDecl = true;
1374      }
1375    }
1376  } else if (R.getTypePtr()->isFunctionType()) {
1377    FunctionDecl::StorageClass SC = FunctionDecl::None;
1378    switch (D.getDeclSpec().getStorageClassSpec()) {
1379      default: assert(0 && "Unknown storage class!");
1380      case DeclSpec::SCS_auto:
1381      case DeclSpec::SCS_register:
1382      case DeclSpec::SCS_mutable:
1383        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
1384        InvalidDecl = true;
1385        break;
1386      case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1387      case DeclSpec::SCS_extern:      SC = FunctionDecl::Extern; break;
1388      case DeclSpec::SCS_static:      SC = FunctionDecl::Static; break;
1389      case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
1390    }
1391
1392    bool isInline = D.getDeclSpec().isInlineSpecified();
1393    // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1394    bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1395
1396    FunctionDecl *NewFD;
1397    if (D.getKind() == Declarator::DK_Constructor) {
1398      // This is a C++ constructor declaration.
1399      assert(DC->isRecord() &&
1400             "Constructors can only be declared in a member context");
1401
1402      InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
1403
1404      // Create the new declaration
1405      NewFD = CXXConstructorDecl::Create(Context,
1406                                         cast<CXXRecordDecl>(DC),
1407                                         D.getIdentifierLoc(), Name, R,
1408                                         isExplicit, isInline,
1409                                         /*isImplicitlyDeclared=*/false);
1410
1411      if (InvalidDecl)
1412        NewFD->setInvalidDecl();
1413    } else if (D.getKind() == Declarator::DK_Destructor) {
1414      // This is a C++ destructor declaration.
1415      if (DC->isRecord()) {
1416        InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
1417
1418        NewFD = CXXDestructorDecl::Create(Context,
1419                                          cast<CXXRecordDecl>(DC),
1420                                          D.getIdentifierLoc(), Name, R,
1421                                          isInline,
1422                                          /*isImplicitlyDeclared=*/false);
1423
1424        if (InvalidDecl)
1425          NewFD->setInvalidDecl();
1426      } else {
1427        Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1428
1429        // Create a FunctionDecl to satisfy the function definition parsing
1430        // code path.
1431        NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
1432                                     Name, R, SC, isInline, LastDeclarator,
1433                                     // FIXME: Move to DeclGroup...
1434                                   D.getDeclSpec().getSourceRange().getBegin());
1435        InvalidDecl = true;
1436        NewFD->setInvalidDecl();
1437      }
1438    } else if (D.getKind() == Declarator::DK_Conversion) {
1439      if (!DC->isRecord()) {
1440        Diag(D.getIdentifierLoc(),
1441             diag::err_conv_function_not_member);
1442        return 0;
1443      } else {
1444        InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
1445
1446        NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
1447                                          D.getIdentifierLoc(), Name, R,
1448                                          isInline, isExplicit);
1449
1450        if (InvalidDecl)
1451          NewFD->setInvalidDecl();
1452      }
1453    } else if (DC->isRecord()) {
1454      // This is a C++ method declaration.
1455      NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
1456                                    D.getIdentifierLoc(), Name, R,
1457                                    (SC == FunctionDecl::Static), isInline,
1458                                    LastDeclarator);
1459    } else {
1460      NewFD = FunctionDecl::Create(Context, DC,
1461                                   D.getIdentifierLoc(),
1462                                   Name, R, SC, isInline, LastDeclarator,
1463                                   // FIXME: Move to DeclGroup...
1464                                   D.getDeclSpec().getSourceRange().getBegin());
1465    }
1466
1467    // Set the lexical context. If the declarator has a C++
1468    // scope specifier, the lexical context will be different
1469    // from the semantic context.
1470    NewFD->setLexicalDeclContext(CurContext);
1471
1472    // Handle GNU asm-label extension (encoded as an attribute).
1473    if (Expr *E = (Expr*) D.getAsmLabel()) {
1474      // The parser guarantees this is a string.
1475      StringLiteral *SE = cast<StringLiteral>(E);
1476      NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1477                                                  SE->getByteLength())));
1478    }
1479
1480    // Copy the parameter declarations from the declarator D to
1481    // the function declaration NewFD, if they are available.
1482    if (D.getNumTypeObjects() > 0) {
1483      DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1484
1485      // Create Decl objects for each parameter, adding them to the
1486      // FunctionDecl.
1487      llvm::SmallVector<ParmVarDecl*, 16> Params;
1488
1489      // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1490      // function that takes no arguments, not a function that takes a
1491      // single void argument.
1492      // We let through "const void" here because Sema::GetTypeForDeclarator
1493      // already checks for that case.
1494      if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1495          FTI.ArgInfo[0].Param &&
1496          ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1497        // empty arg list, don't push any params.
1498        ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1499
1500        // In C++, the empty parameter-type-list must be spelled "void"; a
1501        // typedef of void is not permitted.
1502        if (getLangOptions().CPlusPlus &&
1503            Param->getType().getUnqualifiedType() != Context.VoidTy) {
1504          Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1505        }
1506      } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
1507        for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1508          Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1509      }
1510
1511      NewFD->setParams(&Params[0], Params.size());
1512    } else if (R->getAsTypedefType()) {
1513      // When we're declaring a function with a typedef, as in the
1514      // following example, we'll need to synthesize (unnamed)
1515      // parameters for use in the declaration.
1516      //
1517      // @code
1518      // typedef void fn(int);
1519      // fn f;
1520      // @endcode
1521      const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1522      if (!FT) {
1523        // This is a typedef of a function with no prototype, so we
1524        // don't need to do anything.
1525      } else if ((FT->getNumArgs() == 0) ||
1526          (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1527           FT->getArgType(0)->isVoidType())) {
1528        // This is a zero-argument function. We don't need to do anything.
1529      } else {
1530        // Synthesize a parameter for each argument type.
1531        llvm::SmallVector<ParmVarDecl*, 16> Params;
1532        for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1533             ArgType != FT->arg_type_end(); ++ArgType) {
1534          Params.push_back(ParmVarDecl::Create(Context, DC,
1535                                               SourceLocation(), 0,
1536                                               *ArgType, VarDecl::None,
1537                                               0, 0));
1538        }
1539
1540        NewFD->setParams(&Params[0], Params.size());
1541      }
1542    }
1543
1544    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1545      InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
1546    else if (isa<CXXDestructorDecl>(NewFD)) {
1547      CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1548      Record->setUserDeclaredDestructor(true);
1549      // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1550      // user-defined destructor.
1551      Record->setPOD(false);
1552    } else if (CXXConversionDecl *Conversion =
1553               dyn_cast<CXXConversionDecl>(NewFD))
1554      ActOnConversionDeclarator(Conversion);
1555
1556    // Extra checking for C++ overloaded operators (C++ [over.oper]).
1557    if (NewFD->isOverloadedOperator() &&
1558        CheckOverloadedOperatorDeclaration(NewFD))
1559      NewFD->setInvalidDecl();
1560
1561    // Merge the decl with the existing one if appropriate. Since C functions
1562    // are in a flat namespace, make sure we consider decls in outer scopes.
1563    if (PrevDecl &&
1564        (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
1565      bool Redeclaration = false;
1566
1567      // If C++, determine whether NewFD is an overload of PrevDecl or
1568      // a declaration that requires merging. If it's an overload,
1569      // there's no more work to do here; we'll just add the new
1570      // function to the scope.
1571      OverloadedFunctionDecl::function_iterator MatchedDecl;
1572      if (!getLangOptions().CPlusPlus ||
1573          !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1574        Decl *OldDecl = PrevDecl;
1575
1576        // If PrevDecl was an overloaded function, extract the
1577        // FunctionDecl that matched.
1578        if (isa<OverloadedFunctionDecl>(PrevDecl))
1579          OldDecl = *MatchedDecl;
1580
1581        // NewFD and PrevDecl represent declarations that need to be
1582        // merged.
1583        NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1584
1585        if (NewFD == 0) return 0;
1586        if (Redeclaration) {
1587          NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1588
1589          // An out-of-line member function declaration must also be a
1590          // definition (C++ [dcl.meaning]p1).
1591          if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1592              !InvalidDecl) {
1593            Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1594              << D.getCXXScopeSpec().getRange();
1595            NewFD->setInvalidDecl();
1596          }
1597        }
1598      }
1599
1600      if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1601        // The user tried to provide an out-of-line definition for a
1602        // member function, but there was no such member function
1603        // declared (C++ [class.mfct]p2). For example:
1604        //
1605        // class X {
1606        //   void f() const;
1607        // };
1608        //
1609        // void X::f() { } // ill-formed
1610        //
1611        // Complain about this problem, and attempt to suggest close
1612        // matches (e.g., those that differ only in cv-qualifiers and
1613        // whether the parameter types are references).
1614        Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1615          << cast<CXXRecordDecl>(DC)->getDeclName()
1616          << D.getCXXScopeSpec().getRange();
1617        InvalidDecl = true;
1618
1619        PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
1620        if (!PrevDecl) {
1621          // Nothing to suggest.
1622        } else if (OverloadedFunctionDecl *Ovl
1623                   = dyn_cast<OverloadedFunctionDecl>(PrevDecl)) {
1624          for (OverloadedFunctionDecl::function_iterator
1625                 Func = Ovl->function_begin(),
1626                 FuncEnd = Ovl->function_end();
1627               Func != FuncEnd; ++Func) {
1628            if (isNearlyMatchingMemberFunction(Context, *Func, NewFD))
1629              Diag((*Func)->getLocation(), diag::note_member_def_close_match);
1630
1631          }
1632        } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(PrevDecl)) {
1633          // Suggest this no matter how mismatched it is; it's the only
1634          // thing we have.
1635          unsigned diag;
1636          if (isNearlyMatchingMemberFunction(Context, Method, NewFD))
1637            diag = diag::note_member_def_close_match;
1638          else if (Method->getBody())
1639            diag = diag::note_previous_definition;
1640          else
1641            diag = diag::note_previous_declaration;
1642          Diag(Method->getLocation(), diag);
1643        }
1644
1645        PrevDecl = 0;
1646      }
1647    }
1648    // Handle attributes. We need to have merged decls when handling attributes
1649    // (for example to check for conflicts, etc).
1650    ProcessDeclAttributes(NewFD, D);
1651    New = NewFD;
1652
1653    if (getLangOptions().CPlusPlus) {
1654      // In C++, check default arguments now that we have merged decls.
1655      CheckCXXDefaultArguments(NewFD);
1656
1657      // An out-of-line member function declaration must also be a
1658      // definition (C++ [dcl.meaning]p1).
1659      if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
1660        Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1661          << D.getCXXScopeSpec().getRange();
1662        InvalidDecl = true;
1663      }
1664    }
1665  } else {
1666    // Check that there are no default arguments (C++ only).
1667    if (getLangOptions().CPlusPlus)
1668      CheckExtraCXXDefaultArguments(D);
1669
1670    if (R.getTypePtr()->isObjCInterfaceType()) {
1671      Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1672        << D.getIdentifier();
1673      InvalidDecl = true;
1674    }
1675
1676    VarDecl *NewVD;
1677    VarDecl::StorageClass SC;
1678    switch (D.getDeclSpec().getStorageClassSpec()) {
1679    default: assert(0 && "Unknown storage class!");
1680    case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
1681    case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
1682    case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
1683    case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
1684    case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
1685    case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1686    case DeclSpec::SCS_mutable:
1687      // mutable can only appear on non-static class members, so it's always
1688      // an error here
1689      Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1690      InvalidDecl = true;
1691      SC = VarDecl::None;
1692      break;
1693    }
1694
1695    IdentifierInfo *II = Name.getAsIdentifierInfo();
1696    if (!II) {
1697      Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1698       << Name.getAsString();
1699      return 0;
1700    }
1701
1702    if (DC->isRecord()) {
1703      // This is a static data member for a C++ class.
1704      NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
1705                                      D.getIdentifierLoc(), II,
1706                                      R, LastDeclarator);
1707    } else {
1708      bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
1709      if (S->getFnParent() == 0) {
1710        // C99 6.9p2: The storage-class specifiers auto and register shall not
1711        // appear in the declaration specifiers in an external declaration.
1712        if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1713          Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
1714          InvalidDecl = true;
1715        }
1716      }
1717      NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1718                              II, R, SC, LastDeclarator,
1719                              // FIXME: Move to DeclGroup...
1720                              D.getDeclSpec().getSourceRange().getBegin());
1721      NewVD->setThreadSpecified(ThreadSpecified);
1722    }
1723    // Handle attributes prior to checking for duplicates in MergeVarDecl
1724    ProcessDeclAttributes(NewVD, D);
1725
1726    // Handle GNU asm-label extension (encoded as an attribute).
1727    if (Expr *E = (Expr*) D.getAsmLabel()) {
1728      // The parser guarantees this is a string.
1729      StringLiteral *SE = cast<StringLiteral>(E);
1730      NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1731                                                  SE->getByteLength())));
1732    }
1733
1734    // Emit an error if an address space was applied to decl with local storage.
1735    // This includes arrays of objects with address space qualifiers, but not
1736    // automatic variables that point to other address spaces.
1737    // ISO/IEC TR 18037 S5.1.2
1738    if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1739      Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1740      InvalidDecl = true;
1741    }
1742    // Merge the decl with the existing one if appropriate. If the decl is
1743    // in an outer scope, it isn't the same thing.
1744    if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1745      if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1746        // The user tried to define a non-static data member
1747        // out-of-line (C++ [dcl.meaning]p1).
1748        Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1749          << D.getCXXScopeSpec().getRange();
1750        NewVD->Destroy(Context);
1751        return 0;
1752      }
1753
1754      NewVD = MergeVarDecl(NewVD, PrevDecl);
1755      if (NewVD == 0) return 0;
1756
1757      if (D.getCXXScopeSpec().isSet()) {
1758        // No previous declaration in the qualifying scope.
1759        Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1760          << Name << D.getCXXScopeSpec().getRange();
1761        InvalidDecl = true;
1762      }
1763    }
1764    New = NewVD;
1765  }
1766
1767  // Set the lexical context. If the declarator has a C++ scope specifier, the
1768  // lexical context will be different from the semantic context.
1769  New->setLexicalDeclContext(CurContext);
1770
1771  // If this has an identifier, add it to the scope stack.
1772  if (Name)
1773    PushOnScopeChains(New, S);
1774  // If any semantic error occurred, mark the decl as invalid.
1775  if (D.getInvalidType() || InvalidDecl)
1776    New->setInvalidDecl();
1777
1778  return New;
1779}
1780
1781void Sema::InitializerElementNotConstant(const Expr *Init) {
1782  Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1783    << Init->getSourceRange();
1784}
1785
1786bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1787  switch (Init->getStmtClass()) {
1788  default:
1789    InitializerElementNotConstant(Init);
1790    return true;
1791  case Expr::ParenExprClass: {
1792    const ParenExpr* PE = cast<ParenExpr>(Init);
1793    return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1794  }
1795  case Expr::CompoundLiteralExprClass:
1796    return cast<CompoundLiteralExpr>(Init)->isFileScope();
1797  case Expr::DeclRefExprClass:
1798  case Expr::QualifiedDeclRefExprClass: {
1799    const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1800    if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1801      if (VD->hasGlobalStorage())
1802        return false;
1803      InitializerElementNotConstant(Init);
1804      return true;
1805    }
1806    if (isa<FunctionDecl>(D))
1807      return false;
1808    InitializerElementNotConstant(Init);
1809    return true;
1810  }
1811  case Expr::MemberExprClass: {
1812    const MemberExpr *M = cast<MemberExpr>(Init);
1813    if (M->isArrow())
1814      return CheckAddressConstantExpression(M->getBase());
1815    return CheckAddressConstantExpressionLValue(M->getBase());
1816  }
1817  case Expr::ArraySubscriptExprClass: {
1818    // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1819    const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1820    return CheckAddressConstantExpression(ASE->getBase()) ||
1821           CheckArithmeticConstantExpression(ASE->getIdx());
1822  }
1823  case Expr::StringLiteralClass:
1824  case Expr::PredefinedExprClass:
1825    return false;
1826  case Expr::UnaryOperatorClass: {
1827    const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1828
1829    // C99 6.6p9
1830    if (Exp->getOpcode() == UnaryOperator::Deref)
1831      return CheckAddressConstantExpression(Exp->getSubExpr());
1832
1833    InitializerElementNotConstant(Init);
1834    return true;
1835  }
1836  }
1837}
1838
1839bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1840  switch (Init->getStmtClass()) {
1841  default:
1842    InitializerElementNotConstant(Init);
1843    return true;
1844  case Expr::ParenExprClass:
1845    return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
1846  case Expr::StringLiteralClass:
1847  case Expr::ObjCStringLiteralClass:
1848    return false;
1849  case Expr::CallExprClass:
1850  case Expr::CXXOperatorCallExprClass:
1851    // __builtin___CFStringMakeConstantString is a valid constant l-value.
1852    if (cast<CallExpr>(Init)->isBuiltinCall() ==
1853           Builtin::BI__builtin___CFStringMakeConstantString)
1854      return false;
1855
1856    InitializerElementNotConstant(Init);
1857    return true;
1858
1859  case Expr::UnaryOperatorClass: {
1860    const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1861
1862    // C99 6.6p9
1863    if (Exp->getOpcode() == UnaryOperator::AddrOf)
1864      return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1865
1866    if (Exp->getOpcode() == UnaryOperator::Extension)
1867      return CheckAddressConstantExpression(Exp->getSubExpr());
1868
1869    InitializerElementNotConstant(Init);
1870    return true;
1871  }
1872  case Expr::BinaryOperatorClass: {
1873    // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1874    const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1875
1876    Expr *PExp = Exp->getLHS();
1877    Expr *IExp = Exp->getRHS();
1878    if (IExp->getType()->isPointerType())
1879      std::swap(PExp, IExp);
1880
1881    // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1882    return CheckAddressConstantExpression(PExp) ||
1883           CheckArithmeticConstantExpression(IExp);
1884  }
1885  case Expr::ImplicitCastExprClass:
1886  case Expr::CStyleCastExprClass: {
1887    const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
1888    if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1889      // Check for implicit promotion
1890      if (SubExpr->getType()->isFunctionType() ||
1891          SubExpr->getType()->isArrayType())
1892        return CheckAddressConstantExpressionLValue(SubExpr);
1893    }
1894
1895    // Check for pointer->pointer cast
1896    if (SubExpr->getType()->isPointerType())
1897      return CheckAddressConstantExpression(SubExpr);
1898
1899    if (SubExpr->getType()->isIntegralType()) {
1900      // Check for the special-case of a pointer->int->pointer cast;
1901      // this isn't standard, but some code requires it. See
1902      // PR2720 for an example.
1903      if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1904        if (SubCast->getSubExpr()->getType()->isPointerType()) {
1905          unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1906          unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1907          if (IntWidth >= PointerWidth) {
1908            return CheckAddressConstantExpression(SubCast->getSubExpr());
1909          }
1910        }
1911      }
1912    }
1913    if (SubExpr->getType()->isArithmeticType()) {
1914      return CheckArithmeticConstantExpression(SubExpr);
1915    }
1916
1917    InitializerElementNotConstant(Init);
1918    return true;
1919  }
1920  case Expr::ConditionalOperatorClass: {
1921    // FIXME: Should we pedwarn here?
1922    const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1923    if (!Exp->getCond()->getType()->isArithmeticType()) {
1924      InitializerElementNotConstant(Init);
1925      return true;
1926    }
1927    if (CheckArithmeticConstantExpression(Exp->getCond()))
1928      return true;
1929    if (Exp->getLHS() &&
1930        CheckAddressConstantExpression(Exp->getLHS()))
1931      return true;
1932    return CheckAddressConstantExpression(Exp->getRHS());
1933  }
1934  case Expr::AddrLabelExprClass:
1935    return false;
1936  }
1937}
1938
1939static const Expr* FindExpressionBaseAddress(const Expr* E);
1940
1941static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1942  switch (E->getStmtClass()) {
1943  default:
1944    return E;
1945  case Expr::ParenExprClass: {
1946    const ParenExpr* PE = cast<ParenExpr>(E);
1947    return FindExpressionBaseAddressLValue(PE->getSubExpr());
1948  }
1949  case Expr::MemberExprClass: {
1950    const MemberExpr *M = cast<MemberExpr>(E);
1951    if (M->isArrow())
1952      return FindExpressionBaseAddress(M->getBase());
1953    return FindExpressionBaseAddressLValue(M->getBase());
1954  }
1955  case Expr::ArraySubscriptExprClass: {
1956    const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1957    return FindExpressionBaseAddress(ASE->getBase());
1958  }
1959  case Expr::UnaryOperatorClass: {
1960    const UnaryOperator *Exp = cast<UnaryOperator>(E);
1961
1962    if (Exp->getOpcode() == UnaryOperator::Deref)
1963      return FindExpressionBaseAddress(Exp->getSubExpr());
1964
1965    return E;
1966  }
1967  }
1968}
1969
1970static const Expr* FindExpressionBaseAddress(const Expr* E) {
1971  switch (E->getStmtClass()) {
1972  default:
1973    return E;
1974  case Expr::ParenExprClass: {
1975    const ParenExpr* PE = cast<ParenExpr>(E);
1976    return FindExpressionBaseAddress(PE->getSubExpr());
1977  }
1978  case Expr::UnaryOperatorClass: {
1979    const UnaryOperator *Exp = cast<UnaryOperator>(E);
1980
1981    // C99 6.6p9
1982    if (Exp->getOpcode() == UnaryOperator::AddrOf)
1983      return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1984
1985    if (Exp->getOpcode() == UnaryOperator::Extension)
1986      return FindExpressionBaseAddress(Exp->getSubExpr());
1987
1988    return E;
1989  }
1990  case Expr::BinaryOperatorClass: {
1991    const BinaryOperator *Exp = cast<BinaryOperator>(E);
1992
1993    Expr *PExp = Exp->getLHS();
1994    Expr *IExp = Exp->getRHS();
1995    if (IExp->getType()->isPointerType())
1996      std::swap(PExp, IExp);
1997
1998    return FindExpressionBaseAddress(PExp);
1999  }
2000  case Expr::ImplicitCastExprClass: {
2001    const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
2002
2003    // Check for implicit promotion
2004    if (SubExpr->getType()->isFunctionType() ||
2005        SubExpr->getType()->isArrayType())
2006      return FindExpressionBaseAddressLValue(SubExpr);
2007
2008    // Check for pointer->pointer cast
2009    if (SubExpr->getType()->isPointerType())
2010      return FindExpressionBaseAddress(SubExpr);
2011
2012    // We assume that we have an arithmetic expression here;
2013    // if we don't, we'll figure it out later
2014    return 0;
2015  }
2016  case Expr::CStyleCastExprClass: {
2017    const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
2018
2019    // Check for pointer->pointer cast
2020    if (SubExpr->getType()->isPointerType())
2021      return FindExpressionBaseAddress(SubExpr);
2022
2023    // We assume that we have an arithmetic expression here;
2024    // if we don't, we'll figure it out later
2025    return 0;
2026  }
2027  }
2028}
2029
2030bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
2031  switch (Init->getStmtClass()) {
2032  default:
2033    InitializerElementNotConstant(Init);
2034    return true;
2035  case Expr::ParenExprClass: {
2036    const ParenExpr* PE = cast<ParenExpr>(Init);
2037    return CheckArithmeticConstantExpression(PE->getSubExpr());
2038  }
2039  case Expr::FloatingLiteralClass:
2040  case Expr::IntegerLiteralClass:
2041  case Expr::CharacterLiteralClass:
2042  case Expr::ImaginaryLiteralClass:
2043  case Expr::TypesCompatibleExprClass:
2044  case Expr::CXXBoolLiteralExprClass:
2045    return false;
2046  case Expr::CallExprClass:
2047  case Expr::CXXOperatorCallExprClass: {
2048    const CallExpr *CE = cast<CallExpr>(Init);
2049
2050    // Allow any constant foldable calls to builtins.
2051    if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
2052      return false;
2053
2054    InitializerElementNotConstant(Init);
2055    return true;
2056  }
2057  case Expr::DeclRefExprClass:
2058  case Expr::QualifiedDeclRefExprClass: {
2059    const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
2060    if (isa<EnumConstantDecl>(D))
2061      return false;
2062    InitializerElementNotConstant(Init);
2063    return true;
2064  }
2065  case Expr::CompoundLiteralExprClass:
2066    // Allow "(vector type){2,4}"; normal C constraints don't allow this,
2067    // but vectors are allowed to be magic.
2068    if (Init->getType()->isVectorType())
2069      return false;
2070    InitializerElementNotConstant(Init);
2071    return true;
2072  case Expr::UnaryOperatorClass: {
2073    const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2074
2075    switch (Exp->getOpcode()) {
2076    // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2077    // See C99 6.6p3.
2078    default:
2079      InitializerElementNotConstant(Init);
2080      return true;
2081    case UnaryOperator::OffsetOf:
2082      if (Exp->getSubExpr()->getType()->isConstantSizeType())
2083        return false;
2084      InitializerElementNotConstant(Init);
2085      return true;
2086    case UnaryOperator::Extension:
2087    case UnaryOperator::LNot:
2088    case UnaryOperator::Plus:
2089    case UnaryOperator::Minus:
2090    case UnaryOperator::Not:
2091      return CheckArithmeticConstantExpression(Exp->getSubExpr());
2092    }
2093  }
2094  case Expr::SizeOfAlignOfExprClass: {
2095    const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
2096    // Special check for void types, which are allowed as an extension
2097    if (Exp->getTypeOfArgument()->isVoidType())
2098      return false;
2099    // alignof always evaluates to a constant.
2100    // FIXME: is sizeof(int[3.0]) a constant expression?
2101    if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
2102      InitializerElementNotConstant(Init);
2103      return true;
2104    }
2105    return false;
2106  }
2107  case Expr::BinaryOperatorClass: {
2108    const BinaryOperator *Exp = cast<BinaryOperator>(Init);
2109
2110    if (Exp->getLHS()->getType()->isArithmeticType() &&
2111        Exp->getRHS()->getType()->isArithmeticType()) {
2112      return CheckArithmeticConstantExpression(Exp->getLHS()) ||
2113             CheckArithmeticConstantExpression(Exp->getRHS());
2114    }
2115
2116    if (Exp->getLHS()->getType()->isPointerType() &&
2117        Exp->getRHS()->getType()->isPointerType()) {
2118      const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
2119      const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
2120
2121      // Only allow a null (constant integer) base; we could
2122      // allow some additional cases if necessary, but this
2123      // is sufficient to cover offsetof-like constructs.
2124      if (!LHSBase && !RHSBase) {
2125        return CheckAddressConstantExpression(Exp->getLHS()) ||
2126               CheckAddressConstantExpression(Exp->getRHS());
2127      }
2128    }
2129
2130    InitializerElementNotConstant(Init);
2131    return true;
2132  }
2133  case Expr::ImplicitCastExprClass:
2134  case Expr::CStyleCastExprClass: {
2135    const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
2136    if (SubExpr->getType()->isArithmeticType())
2137      return CheckArithmeticConstantExpression(SubExpr);
2138
2139    if (SubExpr->getType()->isPointerType()) {
2140      const Expr* Base = FindExpressionBaseAddress(SubExpr);
2141      // If the pointer has a null base, this is an offsetof-like construct
2142      if (!Base)
2143        return CheckAddressConstantExpression(SubExpr);
2144    }
2145
2146    InitializerElementNotConstant(Init);
2147    return true;
2148  }
2149  case Expr::ConditionalOperatorClass: {
2150    const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
2151
2152    // If GNU extensions are disabled, we require all operands to be arithmetic
2153    // constant expressions.
2154    if (getLangOptions().NoExtensions) {
2155      return CheckArithmeticConstantExpression(Exp->getCond()) ||
2156          (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
2157             CheckArithmeticConstantExpression(Exp->getRHS());
2158    }
2159
2160    // Otherwise, we have to emulate some of the behavior of fold here.
2161    // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
2162    // because it can constant fold things away.  To retain compatibility with
2163    // GCC code, we see if we can fold the condition to a constant (which we
2164    // should always be able to do in theory).  If so, we only require the
2165    // specified arm of the conditional to be a constant.  This is a horrible
2166    // hack, but is require by real world code that uses __builtin_constant_p.
2167    Expr::EvalResult EvalResult;
2168    if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
2169        EvalResult.HasSideEffects) {
2170      // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
2171      // won't be able to either.  Use it to emit the diagnostic though.
2172      bool Res = CheckArithmeticConstantExpression(Exp->getCond());
2173      assert(Res && "Evaluate couldn't evaluate this constant?");
2174      return Res;
2175    }
2176
2177    // Verify that the side following the condition is also a constant.
2178    const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
2179    if (EvalResult.Val.getInt() == 0)
2180      std::swap(TrueSide, FalseSide);
2181
2182    if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
2183      return true;
2184
2185    // Okay, the evaluated side evaluates to a constant, so we accept this.
2186    // Check to see if the other side is obviously not a constant.  If so,
2187    // emit a warning that this is a GNU extension.
2188    if (FalseSide && !FalseSide->isEvaluatable(Context))
2189      Diag(Init->getExprLoc(),
2190           diag::ext_typecheck_expression_not_constant_but_accepted)
2191        << FalseSide->getSourceRange();
2192    return false;
2193  }
2194  }
2195}
2196
2197bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
2198  Expr::EvalResult Result;
2199
2200  Init = Init->IgnoreParens();
2201
2202  if (Init->Evaluate(Result, Context) && !Result.HasSideEffects)
2203    return false;
2204
2205  // Look through CXXDefaultArgExprs; they have no meaning in this context.
2206  if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
2207    return CheckForConstantInitializer(DAE->getExpr(), DclT);
2208
2209  if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
2210    return CheckForConstantInitializer(e->getInitializer(), DclT);
2211
2212  if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
2213    unsigned numInits = Exp->getNumInits();
2214    for (unsigned i = 0; i < numInits; i++) {
2215      // FIXME: Need to get the type of the declaration for C++,
2216      // because it could be a reference?
2217      if (CheckForConstantInitializer(Exp->getInit(i),
2218                                      Exp->getInit(i)->getType()))
2219        return true;
2220    }
2221    return false;
2222  }
2223
2224  // FIXME: We can probably remove some of this code below, now that
2225  // Expr::Evaluate is doing the heavy lifting for scalars.
2226
2227  if (Init->isNullPointerConstant(Context))
2228    return false;
2229  if (Init->getType()->isArithmeticType()) {
2230    QualType InitTy = Context.getCanonicalType(Init->getType())
2231                             .getUnqualifiedType();
2232    if (InitTy == Context.BoolTy) {
2233      // Special handling for pointers implicitly cast to bool;
2234      // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
2235      if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
2236        Expr* SubE = ICE->getSubExpr();
2237        if (SubE->getType()->isPointerType() ||
2238            SubE->getType()->isArrayType() ||
2239            SubE->getType()->isFunctionType()) {
2240          return CheckAddressConstantExpression(Init);
2241        }
2242      }
2243    } else if (InitTy->isIntegralType()) {
2244      Expr* SubE = 0;
2245      if (CastExpr* CE = dyn_cast<CastExpr>(Init))
2246        SubE = CE->getSubExpr();
2247      // Special check for pointer cast to int; we allow as an extension
2248      // an address constant cast to an integer if the integer
2249      // is of an appropriate width (this sort of code is apparently used
2250      // in some places).
2251      // FIXME: Add pedwarn?
2252      // FIXME: Don't allow bitfields here!  Need the FieldDecl for that.
2253      if (SubE && (SubE->getType()->isPointerType() ||
2254                   SubE->getType()->isArrayType() ||
2255                   SubE->getType()->isFunctionType())) {
2256        unsigned IntWidth = Context.getTypeSize(Init->getType());
2257        unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2258        if (IntWidth >= PointerWidth)
2259          return CheckAddressConstantExpression(Init);
2260      }
2261    }
2262
2263    return CheckArithmeticConstantExpression(Init);
2264  }
2265
2266  if (Init->getType()->isPointerType())
2267    return CheckAddressConstantExpression(Init);
2268
2269  // An array type at the top level that isn't an init-list must
2270  // be a string literal
2271  if (Init->getType()->isArrayType())
2272    return false;
2273
2274  if (Init->getType()->isFunctionType())
2275    return false;
2276
2277  // Allow block exprs at top level.
2278  if (Init->getType()->isBlockPointerType())
2279    return false;
2280
2281  InitializerElementNotConstant(Init);
2282  return true;
2283}
2284
2285void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
2286  Decl *RealDecl = static_cast<Decl *>(dcl);
2287  Expr *Init = static_cast<Expr *>(init.release());
2288  assert(Init && "missing initializer");
2289
2290  // If there is no declaration, there was an error parsing it.  Just ignore
2291  // the initializer.
2292  if (RealDecl == 0) {
2293    delete Init;
2294    return;
2295  }
2296
2297  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2298  if (!VDecl) {
2299    Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
2300         diag::err_illegal_initializer);
2301    RealDecl->setInvalidDecl();
2302    return;
2303  }
2304  // Get the decls type and save a reference for later, since
2305  // CheckInitializerTypes may change it.
2306  QualType DclT = VDecl->getType(), SavT = DclT;
2307  if (VDecl->isBlockVarDecl()) {
2308    VarDecl::StorageClass SC = VDecl->getStorageClass();
2309    if (SC == VarDecl::Extern) { // C99 6.7.8p5
2310      Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
2311      VDecl->setInvalidDecl();
2312    } else if (!VDecl->isInvalidDecl()) {
2313      if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
2314                                VDecl->getDeclName()))
2315        VDecl->setInvalidDecl();
2316
2317      // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2318      if (!getLangOptions().CPlusPlus) {
2319        if (SC == VarDecl::Static) // C99 6.7.8p4.
2320          CheckForConstantInitializer(Init, DclT);
2321      }
2322    }
2323  } else if (VDecl->isFileVarDecl()) {
2324    if (VDecl->getStorageClass() == VarDecl::Extern)
2325      Diag(VDecl->getLocation(), diag::warn_extern_init);
2326    if (!VDecl->isInvalidDecl())
2327      if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
2328                                VDecl->getDeclName()))
2329        VDecl->setInvalidDecl();
2330
2331    // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2332    if (!getLangOptions().CPlusPlus) {
2333      // C99 6.7.8p4. All file scoped initializers need to be constant.
2334      CheckForConstantInitializer(Init, DclT);
2335    }
2336  }
2337  // If the type changed, it means we had an incomplete type that was
2338  // completed by the initializer. For example:
2339  //   int ary[] = { 1, 3, 5 };
2340  // "ary" transitions from a VariableArrayType to a ConstantArrayType.
2341  if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
2342    VDecl->setType(DclT);
2343    Init->setType(DclT);
2344  }
2345
2346  // Attach the initializer to the decl.
2347  VDecl->setInit(Init);
2348  return;
2349}
2350
2351void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2352  Decl *RealDecl = static_cast<Decl *>(dcl);
2353
2354  // If there is no declaration, there was an error parsing it. Just ignore it.
2355  if (RealDecl == 0)
2356    return;
2357
2358  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2359    QualType Type = Var->getType();
2360    // C++ [dcl.init.ref]p3:
2361    //   The initializer can be omitted for a reference only in a
2362    //   parameter declaration (8.3.5), in the declaration of a
2363    //   function return type, in the declaration of a class member
2364    //   within its class declaration (9.2), and where the extern
2365    //   specifier is explicitly used.
2366    if (Type->isReferenceType() &&
2367        Var->getStorageClass() != VarDecl::Extern &&
2368        Var->getStorageClass() != VarDecl::PrivateExtern) {
2369      Diag(Var->getLocation(), diag::err_reference_var_requires_init)
2370        << Var->getDeclName()
2371        << SourceRange(Var->getLocation(), Var->getLocation());
2372      Var->setInvalidDecl();
2373      return;
2374    }
2375
2376    // C++ [dcl.init]p9:
2377    //
2378    //   If no initializer is specified for an object, and the object
2379    //   is of (possibly cv-qualified) non-POD class type (or array
2380    //   thereof), the object shall be default-initialized; if the
2381    //   object is of const-qualified type, the underlying class type
2382    //   shall have a user-declared default constructor.
2383    if (getLangOptions().CPlusPlus) {
2384      QualType InitType = Type;
2385      if (const ArrayType *Array = Context.getAsArrayType(Type))
2386        InitType = Array->getElementType();
2387      if (Var->getStorageClass() != VarDecl::Extern &&
2388          Var->getStorageClass() != VarDecl::PrivateExtern &&
2389          InitType->isRecordType()) {
2390        const CXXConstructorDecl *Constructor
2391          = PerformInitializationByConstructor(InitType, 0, 0,
2392                                               Var->getLocation(),
2393                                               SourceRange(Var->getLocation(),
2394                                                           Var->getLocation()),
2395                                               Var->getDeclName(),
2396                                               IK_Default);
2397        if (!Constructor)
2398          Var->setInvalidDecl();
2399      }
2400    }
2401
2402#if 0
2403    // FIXME: Temporarily disabled because we are not properly parsing
2404    // linkage specifications on declarations, e.g.,
2405    //
2406    //   extern "C" const CGPoint CGPointerZero;
2407    //
2408    // C++ [dcl.init]p9:
2409    //
2410    //     If no initializer is specified for an object, and the
2411    //     object is of (possibly cv-qualified) non-POD class type (or
2412    //     array thereof), the object shall be default-initialized; if
2413    //     the object is of const-qualified type, the underlying class
2414    //     type shall have a user-declared default
2415    //     constructor. Otherwise, if no initializer is specified for
2416    //     an object, the object and its subobjects, if any, have an
2417    //     indeterminate initial value; if the object or any of its
2418    //     subobjects are of const-qualified type, the program is
2419    //     ill-formed.
2420    //
2421    // This isn't technically an error in C, so we don't diagnose it.
2422    //
2423    // FIXME: Actually perform the POD/user-defined default
2424    // constructor check.
2425    if (getLangOptions().CPlusPlus &&
2426        Context.getCanonicalType(Type).isConstQualified() &&
2427        Var->getStorageClass() != VarDecl::Extern)
2428      Diag(Var->getLocation(),  diag::err_const_var_requires_init)
2429        << Var->getName()
2430        << SourceRange(Var->getLocation(), Var->getLocation());
2431#endif
2432  }
2433}
2434
2435/// The declarators are chained together backwards, reverse the list.
2436Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2437  // Often we have single declarators, handle them quickly.
2438  Decl *GroupDecl = static_cast<Decl*>(group);
2439  if (GroupDecl == 0)
2440    return 0;
2441
2442  ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
2443  ScopedDecl *NewGroup = 0;
2444  if (Group->getNextDeclarator() == 0)
2445    NewGroup = Group;
2446  else { // reverse the list.
2447    while (Group) {
2448      ScopedDecl *Next = Group->getNextDeclarator();
2449      Group->setNextDeclarator(NewGroup);
2450      NewGroup = Group;
2451      Group = Next;
2452    }
2453  }
2454  // Perform semantic analysis that depends on having fully processed both
2455  // the declarator and initializer.
2456  for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
2457    VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2458    if (!IDecl)
2459      continue;
2460    QualType T = IDecl->getType();
2461
2462    if (T->isVariableArrayType()) {
2463      const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
2464
2465      // FIXME: This won't give the correct result for
2466      // int a[10][n];
2467      SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
2468      if (IDecl->isFileVarDecl()) {
2469        Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2470          SizeRange;
2471
2472        IDecl->setInvalidDecl();
2473      } else {
2474        // C99 6.7.5.2p2: If an identifier is declared to be an object with
2475        // static storage duration, it shall not have a variable length array.
2476        if (IDecl->getStorageClass() == VarDecl::Static) {
2477          Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2478            << SizeRange;
2479          IDecl->setInvalidDecl();
2480        } else if (IDecl->getStorageClass() == VarDecl::Extern) {
2481          Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2482            << SizeRange;
2483          IDecl->setInvalidDecl();
2484        }
2485      }
2486    } else if (T->isVariablyModifiedType()) {
2487      if (IDecl->isFileVarDecl()) {
2488        Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2489        IDecl->setInvalidDecl();
2490      } else {
2491        if (IDecl->getStorageClass() == VarDecl::Extern) {
2492          Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2493          IDecl->setInvalidDecl();
2494        }
2495      }
2496    }
2497
2498    // Block scope. C99 6.7p7: If an identifier for an object is declared with
2499    // no linkage (C99 6.2.2p6), the type for the object shall be complete...
2500    if (IDecl->isBlockVarDecl() &&
2501        IDecl->getStorageClass() != VarDecl::Extern) {
2502      if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
2503        Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
2504        IDecl->setInvalidDecl();
2505      }
2506    }
2507    // File scope. C99 6.9.2p2: A declaration of an identifier for and
2508    // object that has file scope without an initializer, and without a
2509    // storage-class specifier or with the storage-class specifier "static",
2510    // constitutes a tentative definition. Note: A tentative definition with
2511    // external linkage is valid (C99 6.2.2p5).
2512    if (isTentativeDefinition(IDecl)) {
2513      if (T->isIncompleteArrayType()) {
2514        // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2515        // array to be completed. Don't issue a diagnostic.
2516      } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
2517        // C99 6.9.2p3: If the declaration of an identifier for an object is
2518        // a tentative definition and has internal linkage (C99 6.2.2p3), the
2519        // declared type shall not be an incomplete type.
2520        Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
2521        IDecl->setInvalidDecl();
2522      }
2523    }
2524    if (IDecl->isFileVarDecl())
2525      CheckForFileScopedRedefinitions(S, IDecl);
2526  }
2527  return NewGroup;
2528}
2529
2530/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2531/// to introduce parameters into function prototype scope.
2532Sema::DeclTy *
2533Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
2534  const DeclSpec &DS = D.getDeclSpec();
2535
2536  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
2537  VarDecl::StorageClass StorageClass = VarDecl::None;
2538  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2539    StorageClass = VarDecl::Register;
2540  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
2541    Diag(DS.getStorageClassSpecLoc(),
2542         diag::err_invalid_storage_class_in_func_decl);
2543    D.getMutableDeclSpec().ClearStorageClassSpecs();
2544  }
2545  if (DS.isThreadSpecified()) {
2546    Diag(DS.getThreadSpecLoc(),
2547         diag::err_invalid_storage_class_in_func_decl);
2548    D.getMutableDeclSpec().ClearStorageClassSpecs();
2549  }
2550
2551  // Check that there are no default arguments inside the type of this
2552  // parameter (C++ only).
2553  if (getLangOptions().CPlusPlus)
2554    CheckExtraCXXDefaultArguments(D);
2555
2556  // In this context, we *do not* check D.getInvalidType(). If the declarator
2557  // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2558  // though it will not reflect the user specified type.
2559  QualType parmDeclType = GetTypeForDeclarator(D, S);
2560
2561  assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2562
2563  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2564  // Can this happen for params?  We already checked that they don't conflict
2565  // among each other.  Here they can only shadow globals, which is ok.
2566  IdentifierInfo *II = D.getIdentifier();
2567  if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
2568    if (PrevDecl->isTemplateParameter()) {
2569      // Maybe we will complain about the shadowed template parameter.
2570      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2571      // Just pretend that we didn't see the previous declaration.
2572      PrevDecl = 0;
2573    } else if (S->isDeclScope(PrevDecl)) {
2574      Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
2575
2576      // Recover by removing the name
2577      II = 0;
2578      D.SetIdentifier(0, D.getIdentifierLoc());
2579    }
2580  }
2581
2582  // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2583  // Doing the promotion here has a win and a loss. The win is the type for
2584  // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2585  // code generator). The loss is the orginal type isn't preserved. For example:
2586  //
2587  // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2588  //    int blockvardecl[5];
2589  //    sizeof(parmvardecl);  // size == 4
2590  //    sizeof(blockvardecl); // size == 20
2591  // }
2592  //
2593  // For expressions, all implicit conversions are captured using the
2594  // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2595  //
2596  // FIXME: If a source translation tool needs to see the original type, then
2597  // we need to consider storing both types (in ParmVarDecl)...
2598  //
2599  if (parmDeclType->isArrayType()) {
2600    // int x[restrict 4] ->  int *restrict
2601    parmDeclType = Context.getArrayDecayedType(parmDeclType);
2602  } else if (parmDeclType->isFunctionType())
2603    parmDeclType = Context.getPointerType(parmDeclType);
2604
2605  ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2606                                         D.getIdentifierLoc(), II,
2607                                         parmDeclType, StorageClass,
2608                                         0, 0);
2609
2610  if (D.getInvalidType())
2611    New->setInvalidDecl();
2612
2613  // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2614  if (D.getCXXScopeSpec().isSet()) {
2615    Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2616      << D.getCXXScopeSpec().getRange();
2617    New->setInvalidDecl();
2618  }
2619
2620  // Add the parameter declaration into this scope.
2621  S->AddDecl(New);
2622  if (II)
2623    IdResolver.AddDecl(New);
2624
2625  ProcessDeclAttributes(New, D);
2626  return New;
2627
2628}
2629
2630Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
2631  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2632  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2633         "Not a function declarator!");
2634  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2635
2636  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2637  // for a K&R function.
2638  if (!FTI.hasPrototype) {
2639    for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
2640      if (FTI.ArgInfo[i].Param == 0) {
2641        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2642          << FTI.ArgInfo[i].Ident;
2643        // Implicitly declare the argument as type 'int' for lack of a better
2644        // type.
2645        DeclSpec DS;
2646        const char* PrevSpec; // unused
2647        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2648                           PrevSpec);
2649        Declarator ParamD(DS, Declarator::KNRTypeListContext);
2650        ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2651        FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
2652      }
2653    }
2654  } else {
2655    // FIXME: Diagnose arguments without names in C.
2656  }
2657
2658  Scope *ParentScope = FnBodyScope->getParent();
2659
2660  return ActOnStartOfFunctionDef(FnBodyScope,
2661                                 ActOnDeclarator(ParentScope, D, 0,
2662                                                 /*IsFunctionDefinition=*/true));
2663}
2664
2665Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2666  Decl *decl = static_cast<Decl*>(D);
2667  FunctionDecl *FD = cast<FunctionDecl>(decl);
2668
2669  // See if this is a redefinition.
2670  const FunctionDecl *Definition;
2671  if (FD->getBody(Definition)) {
2672    Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
2673    Diag(Definition->getLocation(), diag::note_previous_definition);
2674  }
2675
2676  PushDeclContext(FnBodyScope, FD);
2677
2678  // Check the validity of our function parameters
2679  CheckParmsForFunctionDef(FD);
2680
2681  // Introduce our parameters into the function scope
2682  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2683    ParmVarDecl *Param = FD->getParamDecl(p);
2684    // If this has an identifier, add it to the scope stack.
2685    if (Param->getIdentifier())
2686      PushOnScopeChains(Param, FnBodyScope);
2687  }
2688
2689  // Checking attributes of current function definition
2690  // dllimport attribute.
2691  if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2692    // dllimport attribute cannot be applied to definition.
2693    if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2694      Diag(FD->getLocation(),
2695           diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2696        << "dllimport";
2697      FD->setInvalidDecl();
2698      return FD;
2699    } else {
2700      // If a symbol previously declared dllimport is later defined, the
2701      // attribute is ignored in subsequent references, and a warning is
2702      // emitted.
2703      Diag(FD->getLocation(),
2704           diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2705        << FD->getNameAsCString() << "dllimport";
2706    }
2707  }
2708  return FD;
2709}
2710
2711Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
2712  Decl *dcl = static_cast<Decl *>(D);
2713  Stmt *Body = static_cast<Stmt*>(BodyArg.release());
2714  if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
2715    FD->setBody(Body);
2716    assert(FD == getCurFunctionDecl() && "Function parsing confused");
2717  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
2718    MD->setBody((Stmt*)Body);
2719  } else
2720    return 0;
2721  PopDeclContext();
2722  // Verify and clean out per-function state.
2723
2724  // Check goto/label use.
2725  for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2726       I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2727    // Verify that we have no forward references left.  If so, there was a goto
2728    // or address of a label taken, but no definition of it.  Label fwd
2729    // definitions are indicated with a null substmt.
2730    if (I->second->getSubStmt() == 0) {
2731      LabelStmt *L = I->second;
2732      // Emit error.
2733      Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
2734
2735      // At this point, we have gotos that use the bogus label.  Stitch it into
2736      // the function body so that they aren't leaked and that the AST is well
2737      // formed.
2738      if (Body) {
2739        L->setSubStmt(new NullStmt(L->getIdentLoc()));
2740        cast<CompoundStmt>(Body)->push_back(L);
2741      } else {
2742        // The whole function wasn't parsed correctly, just delete this.
2743        delete L;
2744      }
2745    }
2746  }
2747  LabelMap.clear();
2748
2749  return D;
2750}
2751
2752/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2753/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
2754ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2755                                           IdentifierInfo &II, Scope *S) {
2756  // Extension in C99.  Legal in C90, but warn about it.
2757  if (getLangOptions().C99)
2758    Diag(Loc, diag::ext_implicit_function_decl) << &II;
2759  else
2760    Diag(Loc, diag::warn_implicit_function_decl) << &II;
2761
2762  // FIXME: handle stuff like:
2763  // void foo() { extern float X(); }
2764  // void bar() { X(); }  <-- implicit decl for X in another scope.
2765
2766  // Set a Declarator for the implicit definition: int foo();
2767  const char *Dummy;
2768  DeclSpec DS;
2769  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2770  Error = Error; // Silence warning.
2771  assert(!Error && "Error setting up implicit decl!");
2772  Declarator D(DS, Declarator::BlockContext);
2773  D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
2774  D.SetIdentifier(&II, Loc);
2775
2776  // Insert this function into translation-unit scope.
2777
2778  DeclContext *PrevDC = CurContext;
2779  CurContext = Context.getTranslationUnitDecl();
2780
2781  FunctionDecl *FD =
2782    dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
2783  FD->setImplicit();
2784
2785  CurContext = PrevDC;
2786
2787  return FD;
2788}
2789
2790
2791TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2792                                    ScopedDecl *LastDeclarator) {
2793  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
2794  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2795
2796  // Scope manipulation handled by caller.
2797  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2798                                           D.getIdentifierLoc(),
2799                                           D.getIdentifier(),
2800                                           T, LastDeclarator);
2801  if (D.getInvalidType())
2802    NewTD->setInvalidDecl();
2803  return NewTD;
2804}
2805
2806/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
2807/// former case, Name will be non-null.  In the later case, Name will be null.
2808/// TagType indicates what kind of tag this is. TK indicates whether this is a
2809/// reference/declaration/definition of a tag.
2810Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
2811                             SourceLocation KWLoc, const CXXScopeSpec &SS,
2812                             IdentifierInfo *Name, SourceLocation NameLoc,
2813                             AttributeList *Attr,
2814                             MultiTemplateParamsArg TemplateParameterLists) {
2815  // If this is not a definition, it must have a name.
2816  assert((Name != 0 || TK == TK_Definition) &&
2817         "Nameless record must be a definition!");
2818
2819  TagDecl::TagKind Kind;
2820  switch (TagType) {
2821  default: assert(0 && "Unknown tag type!");
2822  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2823  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
2824  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
2825  case DeclSpec::TST_enum:   Kind = TagDecl::TK_enum; break;
2826  }
2827
2828  DeclContext *DC = CurContext;
2829  ScopedDecl *PrevDecl = 0;
2830
2831  if (Name && SS.isNotEmpty()) {
2832    // We have a nested-name tag ('struct foo::bar').
2833
2834    // Check for invalid 'foo::'.
2835    if (SS.isInvalid()) {
2836      Name = 0;
2837      goto CreateNewDecl;
2838    }
2839
2840    DC = static_cast<DeclContext*>(SS.getScopeRep());
2841    // Look-up name inside 'foo::'.
2842    PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2843
2844    // A tag 'foo::bar' must already exist.
2845    if (PrevDecl == 0) {
2846      Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
2847      Name = 0;
2848      goto CreateNewDecl;
2849    }
2850  } else {
2851    // If this is a named struct, check to see if there was a previous forward
2852    // declaration or definition.
2853    // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2854    PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2855  }
2856
2857  if (PrevDecl && PrevDecl->isTemplateParameter()) {
2858    // Maybe we will complain about the shadowed template parameter.
2859    DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2860    // Just pretend that we didn't see the previous declaration.
2861    PrevDecl = 0;
2862  }
2863
2864  if (PrevDecl) {
2865    assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2866            "unexpected Decl type");
2867    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
2868      // If this is a use of a previous tag, or if the tag is already declared
2869      // in the same scope (so that the definition/declaration completes or
2870      // rementions the tag), reuse the decl.
2871      if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
2872        // Make sure that this wasn't declared as an enum and now used as a
2873        // struct or something similar.
2874        if (PrevTagDecl->getTagKind() != Kind) {
2875          Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
2876          Diag(PrevDecl->getLocation(), diag::note_previous_use);
2877          // Recover by making this an anonymous redefinition.
2878          Name = 0;
2879          PrevDecl = 0;
2880        } else {
2881          // If this is a use, just return the declaration we found.
2882
2883          // FIXME: In the future, return a variant or some other clue
2884          // for the consumer of this Decl to know it doesn't own it.
2885          // For our current ASTs this shouldn't be a problem, but will
2886          // need to be changed with DeclGroups.
2887          if (TK == TK_Reference)
2888            return PrevDecl;
2889
2890          // Diagnose attempts to redefine a tag.
2891          if (TK == TK_Definition) {
2892            if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2893              Diag(NameLoc, diag::err_redefinition) << Name;
2894              Diag(Def->getLocation(), diag::note_previous_definition);
2895              // If this is a redefinition, recover by making this struct be
2896              // anonymous, which will make any later references get the previous
2897              // definition.
2898              Name = 0;
2899              PrevDecl = 0;
2900            }
2901            // Okay, this is definition of a previously declared or referenced
2902            // tag PrevDecl. We're going to create a new Decl for it.
2903          }
2904        }
2905        // If we get here we have (another) forward declaration or we
2906        // have a definition.  Just create a new decl.
2907      } else {
2908        // If we get here, this is a definition of a new tag type in a nested
2909        // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2910        // new decl/type.  We set PrevDecl to NULL so that the entities
2911        // have distinct types.
2912        PrevDecl = 0;
2913      }
2914      // If we get here, we're going to create a new Decl. If PrevDecl
2915      // is non-NULL, it's a definition of the tag declared by
2916      // PrevDecl. If it's NULL, we have a new definition.
2917    } else {
2918      // PrevDecl is a namespace.
2919      if (isDeclInScope(PrevDecl, DC, S)) {
2920        // The tag name clashes with a namespace name, issue an error and
2921        // recover by making this tag be anonymous.
2922        Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2923        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2924        Name = 0;
2925        PrevDecl = 0;
2926      } else {
2927        // The existing declaration isn't relevant to us; we're in a
2928        // new scope, so clear out the previous declaration.
2929        PrevDecl = 0;
2930      }
2931    }
2932  }
2933
2934CreateNewDecl:
2935
2936  // If there is an identifier, use the location of the identifier as the
2937  // location of the decl, otherwise use the location of the struct/union
2938  // keyword.
2939  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2940
2941  // Otherwise, create a new declaration. If there is a previous
2942  // declaration of the same entity, the two will be linked via
2943  // PrevDecl.
2944  TagDecl *New;
2945
2946  if (Kind == TagDecl::TK_enum) {
2947    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2948    // enum X { A, B, C } D;    D should chain to X.
2949    New = EnumDecl::Create(Context, DC, Loc, Name,
2950                           cast_or_null<EnumDecl>(PrevDecl));
2951    // If this is an undefined enum, warn.
2952    if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
2953  } else {
2954    // struct/union/class
2955
2956    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2957    // struct X { int A; } D;    D should chain to X.
2958    if (getLangOptions().CPlusPlus)
2959      // FIXME: Look for a way to use RecordDecl for simple structs.
2960      New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
2961                                  cast_or_null<CXXRecordDecl>(PrevDecl));
2962    else
2963      New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
2964                               cast_or_null<RecordDecl>(PrevDecl));
2965  }
2966
2967  if (Kind != TagDecl::TK_enum) {
2968    // Handle #pragma pack: if the #pragma pack stack has non-default
2969    // alignment, make up a packed attribute for this decl. These
2970    // attributes are checked when the ASTContext lays out the
2971    // structure.
2972    //
2973    // It is important for implementing the correct semantics that this
2974    // happen here (in act on tag decl). The #pragma pack stack is
2975    // maintained as a result of parser callbacks which can occur at
2976    // many points during the parsing of a struct declaration (because
2977    // the #pragma tokens are effectively skipped over during the
2978    // parsing of the struct).
2979    if (unsigned Alignment = PackContext.getAlignment())
2980      New->addAttr(new PackedAttr(Alignment * 8));
2981  }
2982
2983  if (Attr)
2984    ProcessDeclAttributeList(New, Attr);
2985
2986  // Set the lexical context. If the tag has a C++ scope specifier, the
2987  // lexical context will be different from the semantic context.
2988  New->setLexicalDeclContext(CurContext);
2989
2990  // If this has an identifier, add it to the scope stack.
2991  if (Name) {
2992    // The scope passed in may not be a decl scope.  Zip up the scope tree until
2993    // we find one that is.
2994    while ((S->getFlags() & Scope::DeclScope) == 0)
2995      S = S->getParent();
2996
2997    // Add it to the decl chain.
2998    PushOnScopeChains(New, S);
2999  } else if (getLangOptions().CPlusPlus) {
3000    // FIXME: We also want to do this for C, but if this tag is
3001    // defined within a structure CurContext will point to the context
3002    // enclosing the structure, and we would end up inserting the tag
3003    // type into the wrong place.
3004    CurContext->addDecl(Context, New);
3005  }
3006
3007  return New;
3008}
3009
3010
3011/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3012/// types into constant array types in certain situations which would otherwise
3013/// be errors (for GCC compatibility).
3014static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3015                                                    ASTContext &Context) {
3016  // This method tries to turn a variable array into a constant
3017  // array even when the size isn't an ICE.  This is necessary
3018  // for compatibility with code that depends on gcc's buggy
3019  // constant expression folding, like struct {char x[(int)(char*)2];}
3020  const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3021  if (!VLATy) return QualType();
3022
3023  Expr::EvalResult EvalResult;
3024  if (!VLATy->getSizeExpr() ||
3025      !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
3026    return QualType();
3027
3028  assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
3029  llvm::APSInt &Res = EvalResult.Val.getInt();
3030  if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
3031    return Context.getConstantArrayType(VLATy->getElementType(),
3032                                        Res, ArrayType::Normal, 0);
3033  return QualType();
3034}
3035
3036bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
3037                          QualType FieldTy, const Expr *BitWidth) {
3038  // FIXME: 6.7.2.1p4 - verify the field type.
3039
3040  llvm::APSInt Value;
3041  if (VerifyIntegerConstantExpression(BitWidth, &Value))
3042    return true;
3043
3044  // Zero-width bitfield is ok for anonymous field.
3045  if (Value == 0 && FieldName)
3046    return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3047
3048  if (Value.isNegative())
3049    return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
3050
3051  uint64_t TypeSize = Context.getTypeSize(FieldTy);
3052  // FIXME: We won't need the 0 size once we check that the field type is valid.
3053  if (TypeSize && Value.getZExtValue() > TypeSize)
3054    return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3055       << FieldName << (unsigned)TypeSize;
3056
3057  return false;
3058}
3059
3060/// ActOnField - Each field of a struct/union/class is passed into this in order
3061/// to create a FieldDecl object for it.
3062Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
3063                               SourceLocation DeclStart,
3064                               Declarator &D, ExprTy *BitfieldWidth) {
3065  IdentifierInfo *II = D.getIdentifier();
3066  Expr *BitWidth = (Expr*)BitfieldWidth;
3067  SourceLocation Loc = DeclStart;
3068  RecordDecl *Record = (RecordDecl *)TagD;
3069  if (II) Loc = D.getIdentifierLoc();
3070
3071  // FIXME: Unnamed fields can be handled in various different ways, for
3072  // example, unnamed unions inject all members into the struct namespace!
3073
3074  QualType T = GetTypeForDeclarator(D, S);
3075  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3076  bool InvalidDecl = false;
3077
3078  // C99 6.7.2.1p8: A member of a structure or union may have any type other
3079  // than a variably modified type.
3080  if (T->isVariablyModifiedType()) {
3081    QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
3082    if (!FixedTy.isNull()) {
3083      Diag(Loc, diag::warn_illegal_constant_array_size);
3084      T = FixedTy;
3085    } else {
3086      Diag(Loc, diag::err_typecheck_field_variable_size);
3087      T = Context.IntTy;
3088      InvalidDecl = true;
3089    }
3090  }
3091
3092  if (BitWidth) {
3093    if (VerifyBitField(Loc, II, T, BitWidth))
3094      InvalidDecl = true;
3095  } else {
3096    // Not a bitfield.
3097
3098    // validate II.
3099
3100  }
3101
3102  // FIXME: Chain fielddecls together.
3103  FieldDecl *NewFD;
3104
3105  NewFD = FieldDecl::Create(Context, Record,
3106                            Loc, II, T, BitWidth,
3107                            D.getDeclSpec().getStorageClassSpec() ==
3108                              DeclSpec::SCS_mutable,
3109                            /*PrevDecl=*/0);
3110
3111  if (getLangOptions().CPlusPlus) {
3112    CheckExtraCXXDefaultArguments(D);
3113    if (!T->isPODType())
3114      cast<CXXRecordDecl>(Record)->setPOD(false);
3115  }
3116
3117  ProcessDeclAttributes(NewFD, D);
3118
3119  if (D.getInvalidType() || InvalidDecl)
3120    NewFD->setInvalidDecl();
3121
3122  if (II && getLangOptions().CPlusPlus)
3123    PushOnScopeChains(NewFD, S);
3124  else
3125    Record->addDecl(Context, NewFD);
3126
3127  return NewFD;
3128}
3129
3130/// TranslateIvarVisibility - Translate visibility from a token ID to an
3131///  AST enum value.
3132static ObjCIvarDecl::AccessControl
3133TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
3134  switch (ivarVisibility) {
3135  default: assert(0 && "Unknown visitibility kind");
3136  case tok::objc_private: return ObjCIvarDecl::Private;
3137  case tok::objc_public: return ObjCIvarDecl::Public;
3138  case tok::objc_protected: return ObjCIvarDecl::Protected;
3139  case tok::objc_package: return ObjCIvarDecl::Package;
3140  }
3141}
3142
3143/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3144/// in order to create an IvarDecl object for it.
3145Sema::DeclTy *Sema::ActOnIvar(Scope *S,
3146                              SourceLocation DeclStart,
3147                              Declarator &D, ExprTy *BitfieldWidth,
3148                              tok::ObjCKeywordKind Visibility) {
3149  IdentifierInfo *II = D.getIdentifier();
3150  Expr *BitWidth = (Expr*)BitfieldWidth;
3151  SourceLocation Loc = DeclStart;
3152  if (II) Loc = D.getIdentifierLoc();
3153
3154  // FIXME: Unnamed fields can be handled in various different ways, for
3155  // example, unnamed unions inject all members into the struct namespace!
3156
3157  QualType T = GetTypeForDeclarator(D, S);
3158  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3159  bool InvalidDecl = false;
3160
3161  if (BitWidth) {
3162    // TODO: Validate.
3163    //printf("WARNING: BITFIELDS IGNORED!\n");
3164
3165    // 6.7.2.1p3
3166    // 6.7.2.1p4
3167
3168  } else {
3169    // Not a bitfield.
3170
3171    // validate II.
3172
3173  }
3174
3175  // C99 6.7.2.1p8: A member of a structure or union may have any type other
3176  // than a variably modified type.
3177  if (T->isVariablyModifiedType()) {
3178    Diag(Loc, diag::err_typecheck_ivar_variable_size);
3179    InvalidDecl = true;
3180  }
3181
3182  // Get the visibility (access control) for this ivar.
3183  ObjCIvarDecl::AccessControl ac =
3184    Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3185                                        : ObjCIvarDecl::None;
3186
3187  // Construct the decl.
3188  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
3189                                             (Expr *)BitfieldWidth);
3190
3191  // Process attributes attached to the ivar.
3192  ProcessDeclAttributes(NewID, D);
3193
3194  if (D.getInvalidType() || InvalidDecl)
3195    NewID->setInvalidDecl();
3196
3197  return NewID;
3198}
3199
3200void Sema::ActOnFields(Scope* S,
3201                       SourceLocation RecLoc, DeclTy *RecDecl,
3202                       DeclTy **Fields, unsigned NumFields,
3203                       SourceLocation LBrac, SourceLocation RBrac,
3204                       AttributeList *Attr) {
3205  Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
3206  assert(EnclosingDecl && "missing record or interface decl");
3207  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
3208
3209  if (Record)
3210    if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
3211      // Diagnose code like:
3212      //     struct S { struct S {} X; };
3213      // We discover this when we complete the outer S.  Reject and ignore the
3214      // outer S.
3215      Diag(DefRecord->getLocation(), diag::err_nested_redefinition)
3216        << DefRecord->getDeclName();
3217      Diag(RecLoc, diag::note_previous_definition);
3218      Record->setInvalidDecl();
3219      return;
3220    }
3221
3222  // Verify that all the fields are okay.
3223  unsigned NumNamedMembers = 0;
3224  llvm::SmallVector<FieldDecl*, 32> RecFields;
3225
3226  // FIXME: Eventually, we'd like to eliminate this in favor of
3227  // checking for redeclarations on-the-fly.
3228  llvm::DenseMap<const IdentifierInfo*, FieldDecl *> FieldIDs;
3229
3230  for (unsigned i = 0; i != NumFields; ++i) {
3231    FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
3232    assert(FD && "missing field decl");
3233
3234    // Get the type for the field.
3235    Type *FDTy = FD->getType().getTypePtr();
3236
3237    if (FD->isAnonymousStructOrUnion()) {
3238      // We have found a field that represents an anonymous struct
3239      // or union. Introduce all of the inner fields (recursively)
3240      // into the list of fields we know about, so that we can produce
3241      // an appropriate error message in cases like:
3242      //
3243      //   struct X {
3244      //     union {
3245      //       int x;
3246      //       float f;
3247      //     };
3248      //     double x;
3249      //   };
3250      llvm::SmallVector<FieldDecl *, 4> AnonStructUnionFields;
3251      AnonStructUnionFields.push_back(FD);
3252      while (!AnonStructUnionFields.empty()) {
3253        FieldDecl *AnonField = AnonStructUnionFields.back();
3254        AnonStructUnionFields.pop_back();
3255
3256        RecordDecl *AnonRecord
3257          = AnonField->getType()->getAsRecordType()->getDecl();
3258        for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
3259                                     FEnd = AnonRecord->field_end();
3260             F != FEnd; ++F) {
3261          if ((*F)->isAnonymousStructOrUnion())
3262            AnonStructUnionFields.push_back(*F);
3263          else if (const IdentifierInfo *II = (*F)->getIdentifier())
3264            FieldIDs[II] = *F;
3265        }
3266      }
3267    } else {
3268      // Remember all fields written by the user.
3269      RecFields.push_back(FD);
3270    }
3271
3272    // C99 6.7.2.1p2 - A field may not be a function type.
3273    if (FDTy->isFunctionType()) {
3274      Diag(FD->getLocation(), diag::err_field_declared_as_function)
3275        << FD->getDeclName();
3276      FD->setInvalidDecl();
3277      EnclosingDecl->setInvalidDecl();
3278      continue;
3279    }
3280    // C99 6.7.2.1p2 - A field may not be an incomplete type except...
3281    if (FDTy->isIncompleteType()) {
3282      if (!Record) {  // Incomplete ivar type is always an error.
3283        Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
3284        FD->setInvalidDecl();
3285        EnclosingDecl->setInvalidDecl();
3286        continue;
3287      }
3288      if (i != NumFields-1 ||                   // ... that the last member ...
3289          !Record->isStruct() ||  // ... of a structure ...
3290          !FDTy->isArrayType()) {         //... may have incomplete array type.
3291        Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
3292        FD->setInvalidDecl();
3293        EnclosingDecl->setInvalidDecl();
3294        continue;
3295      }
3296      if (NumNamedMembers < 1) {  //... must have more than named member ...
3297        Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
3298          << FD->getDeclName();
3299        FD->setInvalidDecl();
3300        EnclosingDecl->setInvalidDecl();
3301        continue;
3302      }
3303      // Okay, we have a legal flexible array member at the end of the struct.
3304      if (Record)
3305        Record->setHasFlexibleArrayMember(true);
3306    }
3307    /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3308    /// field of another structure or the element of an array.
3309    if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
3310      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3311        // If this is a member of a union, then entire union becomes "flexible".
3312        if (Record && Record->isUnion()) {
3313          Record->setHasFlexibleArrayMember(true);
3314        } else {
3315          // If this is a struct/class and this is not the last element, reject
3316          // it.  Note that GCC supports variable sized arrays in the middle of
3317          // structures.
3318          if (i != NumFields-1) {
3319            Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
3320              << FD->getDeclName();
3321            FD->setInvalidDecl();
3322            EnclosingDecl->setInvalidDecl();
3323            continue;
3324          }
3325          // We support flexible arrays at the end of structs in other structs
3326          // as an extension.
3327          Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
3328            << FD->getDeclName();
3329          if (Record)
3330            Record->setHasFlexibleArrayMember(true);
3331        }
3332      }
3333    }
3334    /// A field cannot be an Objective-c object
3335    if (FDTy->isObjCInterfaceType()) {
3336      Diag(FD->getLocation(), diag::err_statically_allocated_object)
3337        << FD->getDeclName();
3338      FD->setInvalidDecl();
3339      EnclosingDecl->setInvalidDecl();
3340      continue;
3341    }
3342    // Keep track of the number of named members.
3343    if (IdentifierInfo *II = FD->getIdentifier()) {
3344      // Detect duplicate member names.
3345      if (FieldIDs[II]) {
3346        Diag(FD->getLocation(), diag::err_duplicate_member) << II;
3347        // Find the previous decl.
3348        Diag(FieldIDs[II]->getLocation(), diag::note_previous_definition);
3349        FD->setInvalidDecl();
3350        EnclosingDecl->setInvalidDecl();
3351        continue;
3352      }
3353      ++NumNamedMembers;
3354      FieldIDs[II] = FD;
3355    }
3356  }
3357
3358  // Okay, we successfully defined 'Record'.
3359  if (Record) {
3360    Record->completeDefinition(Context);
3361    // If this is a C++ record, HandleTagDeclDefinition will be invoked in
3362    // Sema::ActOnFinishCXXClassDef.
3363    if (!isa<CXXRecordDecl>(Record))
3364      Consumer.HandleTagDeclDefinition(Record);
3365  } else {
3366    ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
3367    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
3368      ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
3369      // Must enforce the rule that ivars in the base classes may not be
3370      // duplicates.
3371      if (ID->getSuperClass()) {
3372        for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3373             IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3374          ObjCIvarDecl* Ivar = (*IVI);
3375          IdentifierInfo *II = Ivar->getIdentifier();
3376          ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3377          if (prevIvar) {
3378            Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3379            Diag(prevIvar->getLocation(), diag::note_previous_definition);
3380          }
3381        }
3382      }
3383    }
3384    else if (ObjCImplementationDecl *IMPDecl =
3385               dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
3386      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3387      IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
3388      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
3389    }
3390  }
3391
3392  if (Attr)
3393    ProcessDeclAttributeList(Record, Attr);
3394}
3395
3396void Sema::ActOnEnumStartDefinition(Scope *S, DeclTy *EnumD) {
3397  EnumDecl *Enum = cast<EnumDecl>((Decl *)EnumD);
3398
3399  // Enter the enumeration context.
3400  PushDeclContext(S, Enum);
3401}
3402
3403Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
3404                                      DeclTy *lastEnumConst,
3405                                      SourceLocation IdLoc, IdentifierInfo *Id,
3406                                      SourceLocation EqualLoc, ExprTy *val) {
3407  EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
3408  EnumConstantDecl *LastEnumConst =
3409    cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3410  Expr *Val = static_cast<Expr*>(val);
3411
3412  // The scope passed in may not be a decl scope.  Zip up the scope tree until
3413  // we find one that is.
3414  while ((S->getFlags() & Scope::DeclScope) == 0)
3415    S = S->getParent();
3416
3417  // Verify that there isn't already something declared with this name in this
3418  // scope.
3419  Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S);
3420  if (PrevDecl && PrevDecl->isTemplateParameter()) {
3421    // Maybe we will complain about the shadowed template parameter.
3422    DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3423    // Just pretend that we didn't see the previous declaration.
3424    PrevDecl = 0;
3425  }
3426
3427  if (PrevDecl) {
3428    // When in C++, we may get a TagDecl with the same name; in this case the
3429    // enum constant will 'hide' the tag.
3430    assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3431           "Received TagDecl when not in C++!");
3432    if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
3433      if (isa<EnumConstantDecl>(PrevDecl))
3434        Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
3435      else
3436        Diag(IdLoc, diag::err_redefinition) << Id;
3437      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3438      delete Val;
3439      return 0;
3440    }
3441  }
3442
3443  llvm::APSInt EnumVal(32);
3444  QualType EltTy;
3445  if (Val) {
3446    // Make sure to promote the operand type to int.
3447    UsualUnaryConversions(Val);
3448
3449    // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3450    SourceLocation ExpLoc;
3451    if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
3452      delete Val;
3453      Val = 0;  // Just forget about it.
3454    } else {
3455      EltTy = Val->getType();
3456    }
3457  }
3458
3459  if (!Val) {
3460    if (LastEnumConst) {
3461      // Assign the last value + 1.
3462      EnumVal = LastEnumConst->getInitVal();
3463      ++EnumVal;
3464
3465      // Check for overflow on increment.
3466      if (EnumVal < LastEnumConst->getInitVal())
3467        Diag(IdLoc, diag::warn_enum_value_overflow);
3468
3469      EltTy = LastEnumConst->getType();
3470    } else {
3471      // First value, set to zero.
3472      EltTy = Context.IntTy;
3473      EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
3474    }
3475  }
3476
3477  EnumConstantDecl *New =
3478    EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
3479                             Val, EnumVal,
3480                             LastEnumConst);
3481
3482  // Register this decl in the current scope stack.
3483  PushOnScopeChains(New, S);
3484
3485  // Add this enumerator into the enum itself.
3486  // FIXME: This means that the enumerator is stored in two
3487  // DeclContexts. This is not a long-term solution.
3488  New->setLexicalDeclContext(TheEnumDecl);
3489  TheEnumDecl->addDecl(Context, New, true);
3490  return New;
3491}
3492
3493// FIXME: For consistency with ActOnFields(), we should have the parser
3494// pass in the source location for the left/right braces.
3495void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
3496                         DeclTy **Elements, unsigned NumElements) {
3497  EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
3498  QualType EnumType = Context.getTypeDeclType(Enum);
3499
3500  if (EnumType->getAsEnumType()->getDecl()->isDefinition()) {
3501    EnumDecl *Def = EnumType->getAsEnumType()->getDecl();
3502    // Diagnose code like:
3503    //   enum e0 {
3504    //     E0 = sizeof(enum e0 { E1 })
3505    //   };
3506    Diag(Def->getLocation(), diag::err_nested_redefinition)
3507      << Enum->getDeclName();
3508    Diag(Enum->getLocation(), diag::note_previous_definition);
3509    Enum->setInvalidDecl();
3510    PopDeclContext();
3511    return;
3512  }
3513
3514  // TODO: If the result value doesn't fit in an int, it must be a long or long
3515  // long value.  ISO C does not support this, but GCC does as an extension,
3516  // emit a warning.
3517  unsigned IntWidth = Context.Target.getIntWidth();
3518
3519  // Verify that all the values are okay, compute the size of the values, and
3520  // reverse the list.
3521  unsigned NumNegativeBits = 0;
3522  unsigned NumPositiveBits = 0;
3523
3524  // Keep track of whether all elements have type int.
3525  bool AllElementsInt = true;
3526
3527  EnumConstantDecl *EltList = 0;
3528  for (unsigned i = 0; i != NumElements; ++i) {
3529    EnumConstantDecl *ECD =
3530      cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3531    if (!ECD) continue;  // Already issued a diagnostic.
3532
3533    // If the enum value doesn't fit in an int, emit an extension warning.
3534    const llvm::APSInt &InitVal = ECD->getInitVal();
3535    assert(InitVal.getBitWidth() >= IntWidth &&
3536           "Should have promoted value to int");
3537    if (InitVal.getBitWidth() > IntWidth) {
3538      llvm::APSInt V(InitVal);
3539      V.trunc(IntWidth);
3540      V.extend(InitVal.getBitWidth());
3541      if (V != InitVal)
3542        Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3543          << InitVal.toString(10);
3544    }
3545
3546    // Keep track of the size of positive and negative values.
3547    if (InitVal.isUnsigned() || InitVal.isNonNegative())
3548      NumPositiveBits = std::max(NumPositiveBits,
3549                                 (unsigned)InitVal.getActiveBits());
3550    else
3551      NumNegativeBits = std::max(NumNegativeBits,
3552                                 (unsigned)InitVal.getMinSignedBits());
3553
3554    // Keep track of whether every enum element has type int (very commmon).
3555    if (AllElementsInt)
3556      AllElementsInt = ECD->getType() == Context.IntTy;
3557
3558    ECD->setNextDeclarator(EltList);
3559    EltList = ECD;
3560  }
3561
3562  // Figure out the type that should be used for this enum.
3563  // FIXME: Support attribute(packed) on enums and -fshort-enums.
3564  QualType BestType;
3565  unsigned BestWidth;
3566
3567  if (NumNegativeBits) {
3568    // If there is a negative value, figure out the smallest integer type (of
3569    // int/long/longlong) that fits.
3570    if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
3571      BestType = Context.IntTy;
3572      BestWidth = IntWidth;
3573    } else {
3574      BestWidth = Context.Target.getLongWidth();
3575
3576      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
3577        BestType = Context.LongTy;
3578      else {
3579        BestWidth = Context.Target.getLongLongWidth();
3580
3581        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
3582          Diag(Enum->getLocation(), diag::warn_enum_too_large);
3583        BestType = Context.LongLongTy;
3584      }
3585    }
3586  } else {
3587    // If there is no negative value, figure out which of uint, ulong, ulonglong
3588    // fits.
3589    if (NumPositiveBits <= IntWidth) {
3590      BestType = Context.UnsignedIntTy;
3591      BestWidth = IntWidth;
3592    } else if (NumPositiveBits <=
3593               (BestWidth = Context.Target.getLongWidth())) {
3594      BestType = Context.UnsignedLongTy;
3595    } else {
3596      BestWidth = Context.Target.getLongLongWidth();
3597      assert(NumPositiveBits <= BestWidth &&
3598             "How could an initializer get larger than ULL?");
3599      BestType = Context.UnsignedLongLongTy;
3600    }
3601  }
3602
3603  // Loop over all of the enumerator constants, changing their types to match
3604  // the type of the enum if needed.
3605  for (unsigned i = 0; i != NumElements; ++i) {
3606    EnumConstantDecl *ECD =
3607      cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3608    if (!ECD) continue;  // Already issued a diagnostic.
3609
3610    // Standard C says the enumerators have int type, but we allow, as an
3611    // extension, the enumerators to be larger than int size.  If each
3612    // enumerator value fits in an int, type it as an int, otherwise type it the
3613    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
3614    // that X has type 'int', not 'unsigned'.
3615    if (ECD->getType() == Context.IntTy) {
3616      // Make sure the init value is signed.
3617      llvm::APSInt IV = ECD->getInitVal();
3618      IV.setIsSigned(true);
3619      ECD->setInitVal(IV);
3620
3621      if (getLangOptions().CPlusPlus)
3622        // C++ [dcl.enum]p4: Following the closing brace of an
3623        // enum-specifier, each enumerator has the type of its
3624        // enumeration.
3625        ECD->setType(EnumType);
3626      continue;  // Already int type.
3627    }
3628
3629    // Determine whether the value fits into an int.
3630    llvm::APSInt InitVal = ECD->getInitVal();
3631    bool FitsInInt;
3632    if (InitVal.isUnsigned() || !InitVal.isNegative())
3633      FitsInInt = InitVal.getActiveBits() < IntWidth;
3634    else
3635      FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3636
3637    // If it fits into an integer type, force it.  Otherwise force it to match
3638    // the enum decl type.
3639    QualType NewTy;
3640    unsigned NewWidth;
3641    bool NewSign;
3642    if (FitsInInt) {
3643      NewTy = Context.IntTy;
3644      NewWidth = IntWidth;
3645      NewSign = true;
3646    } else if (ECD->getType() == BestType) {
3647      // Already the right type!
3648      if (getLangOptions().CPlusPlus)
3649        // C++ [dcl.enum]p4: Following the closing brace of an
3650        // enum-specifier, each enumerator has the type of its
3651        // enumeration.
3652        ECD->setType(EnumType);
3653      continue;
3654    } else {
3655      NewTy = BestType;
3656      NewWidth = BestWidth;
3657      NewSign = BestType->isSignedIntegerType();
3658    }
3659
3660    // Adjust the APSInt value.
3661    InitVal.extOrTrunc(NewWidth);
3662    InitVal.setIsSigned(NewSign);
3663    ECD->setInitVal(InitVal);
3664
3665    // Adjust the Expr initializer and type.
3666    ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3667                                          /*isLvalue=*/false));
3668    if (getLangOptions().CPlusPlus)
3669      // C++ [dcl.enum]p4: Following the closing brace of an
3670      // enum-specifier, each enumerator has the type of its
3671      // enumeration.
3672      ECD->setType(EnumType);
3673    else
3674      ECD->setType(NewTy);
3675  }
3676
3677  Enum->completeDefinition(Context, BestType);
3678  Consumer.HandleTagDeclDefinition(Enum);
3679
3680  // Leave the context of the enumeration.
3681  PopDeclContext();
3682}
3683
3684Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
3685                                          ExprArg expr) {
3686  StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3687
3688  return FileScopeAsmDecl::Create(Context, Loc, AsmString);
3689}
3690
3691
3692void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3693                           ExprTy *alignment, SourceLocation PragmaLoc,
3694                           SourceLocation LParenLoc, SourceLocation RParenLoc) {
3695  Expr *Alignment = static_cast<Expr *>(alignment);
3696
3697  // If specified then alignment must be a "small" power of two.
3698  unsigned AlignmentVal = 0;
3699  if (Alignment) {
3700    llvm::APSInt Val;
3701    if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3702        !Val.isPowerOf2() ||
3703        Val.getZExtValue() > 16) {
3704      Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3705      delete Alignment;
3706      return; // Ignore
3707    }
3708
3709    AlignmentVal = (unsigned) Val.getZExtValue();
3710  }
3711
3712  switch (Kind) {
3713  case Action::PPK_Default: // pack([n])
3714    PackContext.setAlignment(AlignmentVal);
3715    break;
3716
3717  case Action::PPK_Show: // pack(show)
3718    // Show the current alignment, making sure to show the right value
3719    // for the default.
3720    AlignmentVal = PackContext.getAlignment();
3721    // FIXME: This should come from the target.
3722    if (AlignmentVal == 0)
3723      AlignmentVal = 8;
3724    Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
3725    break;
3726
3727  case Action::PPK_Push: // pack(push [, id] [, [n])
3728    PackContext.push(Name);
3729    // Set the new alignment if specified.
3730    if (Alignment)
3731      PackContext.setAlignment(AlignmentVal);
3732    break;
3733
3734  case Action::PPK_Pop: // pack(pop [, id] [,  n])
3735    // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3736    // "#pragma pack(pop, identifier, n) is undefined"
3737    if (Alignment && Name)
3738      Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3739
3740    // Do the pop.
3741    if (!PackContext.pop(Name)) {
3742      // If a name was specified then failure indicates the name
3743      // wasn't found. Otherwise failure indicates the stack was
3744      // empty.
3745      Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3746        << (Name ? "no record matching name" : "stack empty");
3747
3748      // FIXME: Warn about popping named records as MSVC does.
3749    } else {
3750      // Pop succeeded, set the new alignment if specified.
3751      if (Alignment)
3752        PackContext.setAlignment(AlignmentVal);
3753    }
3754    break;
3755
3756  default:
3757    assert(0 && "Invalid #pragma pack kind.");
3758  }
3759}
3760
3761bool PragmaPackStack::pop(IdentifierInfo *Name) {
3762  if (Stack.empty())
3763    return false;
3764
3765  // If name is empty just pop top.
3766  if (!Name) {
3767    Alignment = Stack.back().first;
3768    Stack.pop_back();
3769    return true;
3770  }
3771
3772  // Otherwise, find the named record.
3773  for (unsigned i = Stack.size(); i != 0; ) {
3774    --i;
3775    if (Stack[i].second == Name) {
3776      // Found it, pop up to and including this record.
3777      Alignment = Stack[i].first;
3778      Stack.erase(Stack.begin() + i, Stack.end());
3779      return true;
3780    }
3781  }
3782
3783  return false;
3784}
3785