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