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