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