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