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