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