SemaDecl.cpp revision 0486d746019f8310589b1f0d92edcc4bb3916b33
101e2320f66a5aeb203f53b51037e37d3d51ce288Marcel Holtmann//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
201e2320f66a5aeb203f53b51037e37d3d51ce288Marcel Holtmann//
301e2320f66a5aeb203f53b51037e37d3d51ce288Marcel Holtmann//                     The LLVM Compiler Infrastructure
401e2320f66a5aeb203f53b51037e37d3d51ce288Marcel Holtmann//
501e2320f66a5aeb203f53b51037e37d3d51ce288Marcel Holtmann// This file is distributed under the University of Illinois Open Source
601e2320f66a5aeb203f53b51037e37d3d51ce288Marcel Holtmann// License. See LICENSE.TXT for details.
701e2320f66a5aeb203f53b51037e37d3d51ce288Marcel Holtmann//
801e2320f66a5aeb203f53b51037e37d3d51ce288Marcel Holtmann//===----------------------------------------------------------------------===//
901e2320f66a5aeb203f53b51037e37d3d51ce288Marcel Holtmann//
1001e2320f66a5aeb203f53b51037e37d3d51ce288Marcel Holtmann//  This file implements semantic analysis for declarations.
11161915e640404db7a46321e59127a666b992b0dfMarcel Holtmann//
12ff58ff2df51c81f7c9a20d4ea0f10ddb7192ab4fMarcel Holtmann//===----------------------------------------------------------------------===//
1301e2320f66a5aeb203f53b51037e37d3d51ce288Marcel Holtmann
1401e2320f66a5aeb203f53b51037e37d3d51ce288Marcel Holtmann#include "Sema.h"
1501e2320f66a5aeb203f53b51037e37d3d51ce288Marcel Holtmann#include "Lookup.h"
1601e2320f66a5aeb203f53b51037e37d3d51ce288Marcel Holtmann#include "clang/AST/APValue.h"
1701e2320f66a5aeb203f53b51037e37d3d51ce288Marcel Holtmann#include "clang/AST/ASTConsumer.h"
1801e2320f66a5aeb203f53b51037e37d3d51ce288Marcel Holtmann#include "clang/AST/ASTContext.h"
1901e2320f66a5aeb203f53b51037e37d3d51ce288Marcel Holtmann#include "clang/Analysis/CFG.h"
203ee81cab2ed66b7f3d4fbd6ba6676d5d9448d6dcLuiz Augusto von Dentz#include "clang/AST/CXXInheritance.h"
213ee81cab2ed66b7f3d4fbd6ba6676d5d9448d6dcLuiz Augusto von Dentz#include "clang/AST/DeclObjC.h"
223ee81cab2ed66b7f3d4fbd6ba6676d5d9448d6dcLuiz Augusto von Dentz#include "clang/AST/DeclTemplate.h"
233ee81cab2ed66b7f3d4fbd6ba6676d5d9448d6dcLuiz Augusto von Dentz#include "clang/AST/ExprCXX.h"
243ee81cab2ed66b7f3d4fbd6ba6676d5d9448d6dcLuiz Augusto von Dentz#include "clang/AST/StmtCXX.h"
2501e2320f66a5aeb203f53b51037e37d3d51ce288Marcel Holtmann#include "clang/AST/StmtObjC.h"
26ff58ff2df51c81f7c9a20d4ea0f10ddb7192ab4fMarcel Holtmann#include "clang/Parse/DeclSpec.h"
2701e2320f66a5aeb203f53b51037e37d3d51ce288Marcel Holtmann#include "clang/Parse/ParseDiagnostic.h"
2801e2320f66a5aeb203f53b51037e37d3d51ce288Marcel Holtmann#include "clang/Parse/Template.h"
2975c562d773e5fe37f4257631318d7f918edc5b53Luiz Augusto von Dentz#include "clang/Basic/PartialDiagnostic.h"
30ff58ff2df51c81f7c9a20d4ea0f10ddb7192ab4fMarcel Holtmann#include "clang/Basic/SourceManager.h"
3175c562d773e5fe37f4257631318d7f918edc5b53Luiz Augusto von Dentz#include "clang/Basic/TargetInfo.h"
32bf64c9b32825beba09cd0e96fc93ce9a4cf4f352Johan Hedberg// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
330dbebcc5f0f201a53133bed184c70566166633dbJohan Hedberg#include "clang/Lex/Preprocessor.h"
340dbebcc5f0f201a53133bed184c70566166633dbJohan Hedberg#include "clang/Lex/HeaderSearch.h"
35bf64c9b32825beba09cd0e96fc93ce9a4cf4f352Johan Hedberg#include "llvm/ADT/BitVector.h"
36ff58ff2df51c81f7c9a20d4ea0f10ddb7192ab4fMarcel Holtmann#include "llvm/ADT/STLExtras.h"
37ff58ff2df51c81f7c9a20d4ea0f10ddb7192ab4fMarcel Holtmann#include <algorithm>
38ff58ff2df51c81f7c9a20d4ea0f10ddb7192ab4fMarcel Holtmann#include <cstring>
39ff58ff2df51c81f7c9a20d4ea0f10ddb7192ab4fMarcel Holtmann#include <functional>
40#include <queue>
41using namespace clang;
42
43/// getDeclName - Return a pretty name for the specified decl if possible, or
44/// an empty string if not.  This is used for pretty crash reporting.
45std::string Sema::getDeclName(DeclPtrTy d) {
46  Decl *D = d.getAs<Decl>();
47  if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(D))
48    return DN->getQualifiedNameAsString();
49  return "";
50}
51
52Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(DeclPtrTy Ptr) {
53  return DeclGroupPtrTy::make(DeclGroupRef(Ptr.getAs<Decl>()));
54}
55
56/// \brief If the identifier refers to a type name within this scope,
57/// return the declaration of that type.
58///
59/// This routine performs ordinary name lookup of the identifier II
60/// within the given scope, with optional C++ scope specifier SS, to
61/// determine whether the name refers to a type. If so, returns an
62/// opaque pointer (actually a QualType) corresponding to that
63/// type. Otherwise, returns NULL.
64///
65/// If name lookup results in an ambiguity, this routine will complain
66/// and then return NULL.
67Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
68                                Scope *S, const CXXScopeSpec *SS,
69                                bool isClassName,
70                                TypeTy *ObjectTypePtr) {
71  // Determine where we will perform name lookup.
72  DeclContext *LookupCtx = 0;
73  if (ObjectTypePtr) {
74    QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
75    if (ObjectType->isRecordType())
76      LookupCtx = computeDeclContext(ObjectType);
77  } else if (SS && SS->isSet()) {
78    LookupCtx = computeDeclContext(*SS, false);
79
80    if (!LookupCtx) {
81      if (isDependentScopeSpecifier(*SS)) {
82        // C++ [temp.res]p3:
83        //   A qualified-id that refers to a type and in which the
84        //   nested-name-specifier depends on a template-parameter (14.6.2)
85        //   shall be prefixed by the keyword typename to indicate that the
86        //   qualified-id denotes a type, forming an
87        //   elaborated-type-specifier (7.1.5.3).
88        //
89        // We therefore do not perform any name lookup if the result would
90        // refer to a member of an unknown specialization.
91        if (!isClassName)
92          return 0;
93
94        // We know from the grammar that this name refers to a type, so build a
95        // TypenameType node to describe the type.
96        // FIXME: Record somewhere that this TypenameType node has no "typename"
97        // keyword associated with it.
98        return CheckTypenameType((NestedNameSpecifier *)SS->getScopeRep(),
99                                 II, SS->getRange()).getAsOpaquePtr();
100      }
101
102      return 0;
103    }
104
105    if (!LookupCtx->isDependentContext() && RequireCompleteDeclContext(*SS))
106      return 0;
107  }
108
109  LookupResult Result(*this, &II, NameLoc, LookupOrdinaryName);
110  if (LookupCtx) {
111    // Perform "qualified" name lookup into the declaration context we
112    // computed, which is either the type of the base of a member access
113    // expression or the declaration context associated with a prior
114    // nested-name-specifier.
115    LookupQualifiedName(Result, LookupCtx);
116
117    if (ObjectTypePtr && Result.empty()) {
118      // C++ [basic.lookup.classref]p3:
119      //   If the unqualified-id is ~type-name, the type-name is looked up
120      //   in the context of the entire postfix-expression. If the type T of
121      //   the object expression is of a class type C, the type-name is also
122      //   looked up in the scope of class C. At least one of the lookups shall
123      //   find a name that refers to (possibly cv-qualified) T.
124      LookupName(Result, S);
125    }
126  } else {
127    // Perform unqualified name lookup.
128    LookupName(Result, S);
129  }
130
131  NamedDecl *IIDecl = 0;
132  switch (Result.getResultKind()) {
133  case LookupResult::NotFound:
134  case LookupResult::FoundOverloaded:
135  case LookupResult::FoundUnresolvedValue:
136    return 0;
137
138  case LookupResult::Ambiguous:
139    // Recover from type-hiding ambiguities by hiding the type.  We'll
140    // do the lookup again when looking for an object, and we can
141    // diagnose the error then.  If we don't do this, then the error
142    // about hiding the type will be immediately followed by an error
143    // that only makes sense if the identifier was treated like a type.
144    if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
145      Result.suppressDiagnostics();
146      return 0;
147    }
148
149    // Look to see if we have a type anywhere in the list of results.
150    for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
151         Res != ResEnd; ++Res) {
152      if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
153        if (!IIDecl ||
154            (*Res)->getLocation().getRawEncoding() <
155              IIDecl->getLocation().getRawEncoding())
156          IIDecl = *Res;
157      }
158    }
159
160    if (!IIDecl) {
161      // None of the entities we found is a type, so there is no way
162      // to even assume that the result is a type. In this case, don't
163      // complain about the ambiguity. The parser will either try to
164      // perform this lookup again (e.g., as an object name), which
165      // will produce the ambiguity, or will complain that it expected
166      // a type name.
167      Result.suppressDiagnostics();
168      return 0;
169    }
170
171    // We found a type within the ambiguous lookup; diagnose the
172    // ambiguity and then return that type. This might be the right
173    // answer, or it might not be, but it suppresses any attempt to
174    // perform the name lookup again.
175    break;
176
177  case LookupResult::Found:
178    IIDecl = Result.getFoundDecl();
179    break;
180  }
181
182  assert(IIDecl && "Didn't find decl");
183
184  QualType T;
185  if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
186    DiagnoseUseOfDecl(IIDecl, NameLoc);
187
188    // C++ [temp.local]p2:
189    //   Within the scope of a class template specialization or
190    //   partial specialization, when the injected-class-name is
191    //   not followed by a <, it is equivalent to the
192    //   injected-class-name followed by the template-argument s
193    //   of the class template specialization or partial
194    //   specialization enclosed in <>.
195    if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD))
196      if (RD->isInjectedClassName())
197        if (ClassTemplateDecl *Template = RD->getDescribedClassTemplate())
198          T = Template->getInjectedClassNameType(Context);
199
200    if (T.isNull())
201      T = Context.getTypeDeclType(TD);
202
203    if (SS)
204      T = getQualifiedNameType(*SS, T);
205
206  } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
207    T = Context.getObjCInterfaceType(IDecl);
208  } else if (UnresolvedUsingTypenameDecl *UUDecl =
209               dyn_cast<UnresolvedUsingTypenameDecl>(IIDecl)) {
210    // FIXME: preserve source structure information.
211    T = Context.getTypenameType(UUDecl->getTargetNestedNameSpecifier(), &II);
212  } else {
213    // If it's not plausibly a type, suppress diagnostics.
214    Result.suppressDiagnostics();
215    return 0;
216  }
217
218  return T.getAsOpaquePtr();
219}
220
221/// isTagName() - This method is called *for error recovery purposes only*
222/// to determine if the specified name is a valid tag name ("struct foo").  If
223/// so, this returns the TST for the tag corresponding to it (TST_enum,
224/// TST_union, TST_struct, TST_class).  This is used to diagnose cases in C
225/// where the user forgot to specify the tag.
226DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
227  // Do a tag name lookup in this scope.
228  LookupResult R(*this, &II, SourceLocation(), LookupTagName);
229  LookupName(R, S, false);
230  R.suppressDiagnostics();
231  if (R.getResultKind() == LookupResult::Found)
232    if (const TagDecl *TD = dyn_cast<TagDecl>(R.getAsSingleDecl(Context))) {
233      switch (TD->getTagKind()) {
234      case TagDecl::TK_struct: return DeclSpec::TST_struct;
235      case TagDecl::TK_union:  return DeclSpec::TST_union;
236      case TagDecl::TK_class:  return DeclSpec::TST_class;
237      case TagDecl::TK_enum:   return DeclSpec::TST_enum;
238      }
239    }
240
241  return DeclSpec::TST_unspecified;
242}
243
244bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II,
245                                   SourceLocation IILoc,
246                                   Scope *S,
247                                   const CXXScopeSpec *SS,
248                                   TypeTy *&SuggestedType) {
249  // We don't have anything to suggest (yet).
250  SuggestedType = 0;
251
252  // FIXME: Should we move the logic that tries to recover from a missing tag
253  // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
254
255  if (!SS)
256    Diag(IILoc, diag::err_unknown_typename) << &II;
257  else if (DeclContext *DC = computeDeclContext(*SS, false))
258    Diag(IILoc, diag::err_typename_nested_not_found)
259      << &II << DC << SS->getRange();
260  else if (isDependentScopeSpecifier(*SS)) {
261    Diag(SS->getRange().getBegin(), diag::err_typename_missing)
262      << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
263      << SourceRange(SS->getRange().getBegin(), IILoc)
264      << CodeModificationHint::CreateInsertion(SS->getRange().getBegin(),
265                                               "typename ");
266    SuggestedType = ActOnTypenameType(SourceLocation(), *SS, II, IILoc).get();
267  } else {
268    assert(SS && SS->isInvalid() &&
269           "Invalid scope specifier has already been diagnosed");
270  }
271
272  return true;
273}
274
275// Determines the context to return to after temporarily entering a
276// context.  This depends in an unnecessarily complicated way on the
277// exact ordering of callbacks from the parser.
278DeclContext *Sema::getContainingDC(DeclContext *DC) {
279
280  // Functions defined inline within classes aren't parsed until we've
281  // finished parsing the top-level class, so the top-level class is
282  // the context we'll need to return to.
283  if (isa<FunctionDecl>(DC)) {
284    DC = DC->getLexicalParent();
285
286    // A function not defined within a class will always return to its
287    // lexical context.
288    if (!isa<CXXRecordDecl>(DC))
289      return DC;
290
291    // A C++ inline method/friend is parsed *after* the topmost class
292    // it was declared in is fully parsed ("complete");  the topmost
293    // class is the context we need to return to.
294    while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
295      DC = RD;
296
297    // Return the declaration context of the topmost class the inline method is
298    // declared in.
299    return DC;
300  }
301
302  if (isa<ObjCMethodDecl>(DC))
303    return Context.getTranslationUnitDecl();
304
305  return DC->getLexicalParent();
306}
307
308void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
309  assert(getContainingDC(DC) == CurContext &&
310      "The next DeclContext should be lexically contained in the current one.");
311  CurContext = DC;
312  S->setEntity(DC);
313}
314
315void Sema::PopDeclContext() {
316  assert(CurContext && "DeclContext imbalance!");
317
318  CurContext = getContainingDC(CurContext);
319}
320
321/// EnterDeclaratorContext - Used when we must lookup names in the context
322/// of a declarator's nested name specifier.
323void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
324  assert(PreDeclaratorDC == 0 && "Previous declarator context not popped?");
325  PreDeclaratorDC = static_cast<DeclContext*>(S->getEntity());
326  CurContext = DC;
327  assert(CurContext && "No context?");
328  S->setEntity(CurContext);
329}
330
331void Sema::ExitDeclaratorContext(Scope *S) {
332  S->setEntity(PreDeclaratorDC);
333  PreDeclaratorDC = 0;
334
335  // Reset CurContext to the nearest enclosing context.
336  while (!S->getEntity() && S->getParent())
337    S = S->getParent();
338  CurContext = static_cast<DeclContext*>(S->getEntity());
339  assert(CurContext && "No context?");
340}
341
342/// \brief Determine whether we allow overloading of the function
343/// PrevDecl with another declaration.
344///
345/// This routine determines whether overloading is possible, not
346/// whether some new function is actually an overload. It will return
347/// true in C++ (where we can always provide overloads) or, as an
348/// extension, in C when the previous function is already an
349/// overloaded function declaration or has the "overloadable"
350/// attribute.
351static bool AllowOverloadingOfFunction(LookupResult &Previous,
352                                       ASTContext &Context) {
353  if (Context.getLangOptions().CPlusPlus)
354    return true;
355
356  if (Previous.getResultKind() == LookupResult::FoundOverloaded)
357    return true;
358
359  return (Previous.getResultKind() == LookupResult::Found
360          && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
361}
362
363/// Add this decl to the scope shadowed decl chains.
364void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
365  // Move up the scope chain until we find the nearest enclosing
366  // non-transparent context. The declaration will be introduced into this
367  // scope.
368  while (S->getEntity() &&
369         ((DeclContext *)S->getEntity())->isTransparentContext())
370    S = S->getParent();
371
372  // Add scoped declarations into their context, so that they can be
373  // found later. Declarations without a context won't be inserted
374  // into any context.
375  if (AddToContext)
376    CurContext->addDecl(D);
377
378  // Out-of-line function and variable definitions should not be pushed into
379  // scope.
380  if ((isa<FunctionTemplateDecl>(D) &&
381       cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->isOutOfLine()) ||
382      (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isOutOfLine()) ||
383      (isa<VarDecl>(D) && cast<VarDecl>(D)->isOutOfLine()))
384    return;
385
386  // If this replaces anything in the current scope,
387  IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
388                               IEnd = IdResolver.end();
389  for (; I != IEnd; ++I) {
390    if (S->isDeclScope(DeclPtrTy::make(*I)) && D->declarationReplaces(*I)) {
391      S->RemoveDecl(DeclPtrTy::make(*I));
392      IdResolver.RemoveDecl(*I);
393
394      // Should only need to replace one decl.
395      break;
396    }
397  }
398
399  S->AddDecl(DeclPtrTy::make(D));
400  IdResolver.AddDecl(D);
401}
402
403bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S) {
404  if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D)) {
405    // Look inside the overload set to determine if any of the declarations
406    // are in scope. (Possibly) build a new overload set containing only
407    // those declarations that are in scope.
408    OverloadedFunctionDecl *NewOvl = 0;
409    bool FoundInScope = false;
410    for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
411         FEnd = Ovl->function_end();
412         F != FEnd; ++F) {
413      NamedDecl *FD = F->get();
414      if (!isDeclInScope(FD, Ctx, S)) {
415        if (!NewOvl && F != Ovl->function_begin()) {
416          NewOvl = OverloadedFunctionDecl::Create(Context,
417                                                  F->get()->getDeclContext(),
418                                                  F->get()->getDeclName());
419          D = NewOvl;
420          for (OverloadedFunctionDecl::function_iterator
421               First = Ovl->function_begin();
422               First != F; ++First)
423            NewOvl->addOverload(*First);
424        }
425      } else {
426        FoundInScope = true;
427        if (NewOvl)
428          NewOvl->addOverload(*F);
429      }
430    }
431
432    return FoundInScope;
433  }
434
435  return IdResolver.isDeclInScope(D, Ctx, Context, S);
436}
437
438static bool isOutOfScopePreviousDeclaration(NamedDecl *,
439                                            DeclContext*,
440                                            ASTContext&);
441
442/// Filters out lookup results that don't fall within the given scope
443/// as determined by isDeclInScope.
444static void FilterLookupForScope(Sema &SemaRef, LookupResult &R,
445                                 DeclContext *Ctx, Scope *S,
446                                 bool ConsiderLinkage) {
447  LookupResult::Filter F = R.makeFilter();
448  while (F.hasNext()) {
449    NamedDecl *D = F.next();
450
451    if (SemaRef.isDeclInScope(D, Ctx, S))
452      continue;
453
454    if (ConsiderLinkage &&
455        isOutOfScopePreviousDeclaration(D, Ctx, SemaRef.Context))
456      continue;
457
458    F.erase();
459  }
460
461  F.done();
462}
463
464static bool isUsingDecl(NamedDecl *D) {
465  return isa<UsingShadowDecl>(D) ||
466         isa<UnresolvedUsingTypenameDecl>(D) ||
467         isa<UnresolvedUsingValueDecl>(D);
468}
469
470/// Removes using shadow declarations from the lookup results.
471static void RemoveUsingDecls(LookupResult &R) {
472  LookupResult::Filter F = R.makeFilter();
473  while (F.hasNext())
474    if (isUsingDecl(F.next()))
475      F.erase();
476
477  F.done();
478}
479
480static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
481  if (D->isUsed() || D->hasAttr<UnusedAttr>())
482    return false;
483
484  if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
485    if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
486      if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
487        if (!RD->hasTrivialConstructor())
488          return false;
489        if (!RD->hasTrivialDestructor())
490          return false;
491      }
492    }
493  }
494
495  return (isa<VarDecl>(D) && !isa<ParmVarDecl>(D) &&
496          !isa<ImplicitParamDecl>(D) &&
497          D->getDeclContext()->isFunctionOrMethod());
498}
499
500void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
501  if (S->decl_empty()) return;
502  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
503         "Scope shouldn't contain decls!");
504
505  for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
506       I != E; ++I) {
507    Decl *TmpD = (*I).getAs<Decl>();
508    assert(TmpD && "This decl didn't get pushed??");
509
510    assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
511    NamedDecl *D = cast<NamedDecl>(TmpD);
512
513    if (!D->getDeclName()) continue;
514
515    // Diagnose unused variables in this scope.
516    if (ShouldDiagnoseUnusedDecl(D))
517      Diag(D->getLocation(), diag::warn_unused_variable) << D->getDeclName();
518
519    // Remove this name from our lexical scope.
520    IdResolver.RemoveDecl(D);
521  }
522}
523
524/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
525/// return 0 if one not found.
526ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
527  // The third "scope" argument is 0 since we aren't enabling lazy built-in
528  // creation from this context.
529  NamedDecl *IDecl = LookupSingleName(TUScope, Id, LookupOrdinaryName);
530
531  return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
532}
533
534/// getNonFieldDeclScope - Retrieves the innermost scope, starting
535/// from S, where a non-field would be declared. This routine copes
536/// with the difference between C and C++ scoping rules in structs and
537/// unions. For example, the following code is well-formed in C but
538/// ill-formed in C++:
539/// @code
540/// struct S6 {
541///   enum { BAR } e;
542/// };
543///
544/// void test_S6() {
545///   struct S6 a;
546///   a.e = BAR;
547/// }
548/// @endcode
549/// For the declaration of BAR, this routine will return a different
550/// scope. The scope S will be the scope of the unnamed enumeration
551/// within S6. In C++, this routine will return the scope associated
552/// with S6, because the enumeration's scope is a transparent
553/// context but structures can contain non-field names. In C, this
554/// routine will return the translation unit scope, since the
555/// enumeration's scope is a transparent context and structures cannot
556/// contain non-field names.
557Scope *Sema::getNonFieldDeclScope(Scope *S) {
558  while (((S->getFlags() & Scope::DeclScope) == 0) ||
559         (S->getEntity() &&
560          ((DeclContext *)S->getEntity())->isTransparentContext()) ||
561         (S->isClassScope() && !getLangOptions().CPlusPlus))
562    S = S->getParent();
563  return S;
564}
565
566void Sema::InitBuiltinVaListType() {
567  if (!Context.getBuiltinVaListType().isNull())
568    return;
569
570  IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
571  NamedDecl *VaDecl = LookupSingleName(TUScope, VaIdent, LookupOrdinaryName);
572  TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
573  Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
574}
575
576/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
577/// file scope.  lazily create a decl for it. ForRedeclaration is true
578/// if we're creating this built-in in anticipation of redeclaring the
579/// built-in.
580NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
581                                     Scope *S, bool ForRedeclaration,
582                                     SourceLocation Loc) {
583  Builtin::ID BID = (Builtin::ID)bid;
584
585  if (Context.BuiltinInfo.hasVAListUse(BID))
586    InitBuiltinVaListType();
587
588  ASTContext::GetBuiltinTypeError Error;
589  QualType R = Context.GetBuiltinType(BID, Error);
590  switch (Error) {
591  case ASTContext::GE_None:
592    // Okay
593    break;
594
595  case ASTContext::GE_Missing_stdio:
596    if (ForRedeclaration)
597      Diag(Loc, diag::err_implicit_decl_requires_stdio)
598        << Context.BuiltinInfo.GetName(BID);
599    return 0;
600
601  case ASTContext::GE_Missing_setjmp:
602    if (ForRedeclaration)
603      Diag(Loc, diag::err_implicit_decl_requires_setjmp)
604        << Context.BuiltinInfo.GetName(BID);
605    return 0;
606  }
607
608  if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
609    Diag(Loc, diag::ext_implicit_lib_function_decl)
610      << Context.BuiltinInfo.GetName(BID)
611      << R;
612    if (Context.BuiltinInfo.getHeaderName(BID) &&
613        Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl)
614          != Diagnostic::Ignored)
615      Diag(Loc, diag::note_please_include_header)
616        << Context.BuiltinInfo.getHeaderName(BID)
617        << Context.BuiltinInfo.GetName(BID);
618  }
619
620  FunctionDecl *New = FunctionDecl::Create(Context,
621                                           Context.getTranslationUnitDecl(),
622                                           Loc, II, R, /*DInfo=*/0,
623                                           FunctionDecl::Extern, false,
624                                           /*hasPrototype=*/true);
625  New->setImplicit();
626
627  // Create Decl objects for each parameter, adding them to the
628  // FunctionDecl.
629  if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
630    llvm::SmallVector<ParmVarDecl*, 16> Params;
631    for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
632      Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
633                                           FT->getArgType(i), /*DInfo=*/0,
634                                           VarDecl::None, 0));
635    New->setParams(Context, Params.data(), Params.size());
636  }
637
638  AddKnownFunctionAttributes(New);
639
640  // TUScope is the translation-unit scope to insert this function into.
641  // FIXME: This is hideous. We need to teach PushOnScopeChains to
642  // relate Scopes to DeclContexts, and probably eliminate CurContext
643  // entirely, but we're not there yet.
644  DeclContext *SavedContext = CurContext;
645  CurContext = Context.getTranslationUnitDecl();
646  PushOnScopeChains(New, TUScope);
647  CurContext = SavedContext;
648  return New;
649}
650
651/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the
652/// same name and scope as a previous declaration 'Old'.  Figure out
653/// how to resolve this situation, merging decls or emitting
654/// diagnostics as appropriate. If there was an error, set New to be invalid.
655///
656void Sema::MergeTypeDefDecl(TypedefDecl *New, LookupResult &OldDecls) {
657  // If the new decl is known invalid already, don't bother doing any
658  // merging checks.
659  if (New->isInvalidDecl()) return;
660
661  // Allow multiple definitions for ObjC built-in typedefs.
662  // FIXME: Verify the underlying types are equivalent!
663  if (getLangOptions().ObjC1) {
664    const IdentifierInfo *TypeID = New->getIdentifier();
665    switch (TypeID->getLength()) {
666    default: break;
667    case 2:
668      if (!TypeID->isStr("id"))
669        break;
670      Context.ObjCIdRedefinitionType = New->getUnderlyingType();
671      // Install the built-in type for 'id', ignoring the current definition.
672      New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
673      return;
674    case 5:
675      if (!TypeID->isStr("Class"))
676        break;
677      Context.ObjCClassRedefinitionType = New->getUnderlyingType();
678      // Install the built-in type for 'Class', ignoring the current definition.
679      New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
680      return;
681    case 3:
682      if (!TypeID->isStr("SEL"))
683        break;
684      Context.ObjCSelRedefinitionType = New->getUnderlyingType();
685      // Install the built-in type for 'SEL', ignoring the current definition.
686      New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
687      return;
688    case 8:
689      if (!TypeID->isStr("Protocol"))
690        break;
691      Context.setObjCProtoType(New->getUnderlyingType());
692      return;
693    }
694    // Fall through - the typedef name was not a builtin type.
695  }
696
697  // Verify the old decl was also a type.
698  TypeDecl *Old = 0;
699  if (!OldDecls.isSingleResult() ||
700      !(Old = dyn_cast<TypeDecl>(OldDecls.getFoundDecl()))) {
701    Diag(New->getLocation(), diag::err_redefinition_different_kind)
702      << New->getDeclName();
703
704    NamedDecl *OldD = OldDecls.getRepresentativeDecl();
705    if (OldD->getLocation().isValid())
706      Diag(OldD->getLocation(), diag::note_previous_definition);
707
708    return New->setInvalidDecl();
709  }
710
711  // If the old declaration is invalid, just give up here.
712  if (Old->isInvalidDecl())
713    return New->setInvalidDecl();
714
715  // Determine the "old" type we'll use for checking and diagnostics.
716  QualType OldType;
717  if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
718    OldType = OldTypedef->getUnderlyingType();
719  else
720    OldType = Context.getTypeDeclType(Old);
721
722  // If the typedef types are not identical, reject them in all languages and
723  // with any extensions enabled.
724
725  if (OldType != New->getUnderlyingType() &&
726      Context.getCanonicalType(OldType) !=
727      Context.getCanonicalType(New->getUnderlyingType())) {
728    Diag(New->getLocation(), diag::err_redefinition_different_typedef)
729      << New->getUnderlyingType() << OldType;
730    if (Old->getLocation().isValid())
731      Diag(Old->getLocation(), diag::note_previous_definition);
732    return New->setInvalidDecl();
733  }
734
735  if (getLangOptions().Microsoft)
736    return;
737
738  // C++ [dcl.typedef]p2:
739  //   In a given non-class scope, a typedef specifier can be used to
740  //   redefine the name of any type declared in that scope to refer
741  //   to the type to which it already refers.
742  if (getLangOptions().CPlusPlus) {
743    if (!isa<CXXRecordDecl>(CurContext))
744      return;
745    Diag(New->getLocation(), diag::err_redefinition)
746      << New->getDeclName();
747    Diag(Old->getLocation(), diag::note_previous_definition);
748    return New->setInvalidDecl();
749  }
750
751  // If we have a redefinition of a typedef in C, emit a warning.  This warning
752  // is normally mapped to an error, but can be controlled with
753  // -Wtypedef-redefinition.  If either the original or the redefinition is
754  // in a system header, don't emit this for compatibility with GCC.
755  if (PP.getDiagnostics().getSuppressSystemWarnings() &&
756      (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
757       Context.getSourceManager().isInSystemHeader(New->getLocation())))
758    return;
759
760  Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
761    << New->getDeclName();
762  Diag(Old->getLocation(), diag::note_previous_definition);
763  return;
764}
765
766/// DeclhasAttr - returns true if decl Declaration already has the target
767/// attribute.
768static bool
769DeclHasAttr(const Decl *decl, const Attr *target) {
770  for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
771    if (attr->getKind() == target->getKind())
772      return true;
773
774  return false;
775}
776
777/// MergeAttributes - append attributes from the Old decl to the New one.
778static void MergeAttributes(Decl *New, Decl *Old, ASTContext &C) {
779  for (const Attr *attr = Old->getAttrs(); attr; attr = attr->getNext()) {
780    if (!DeclHasAttr(New, attr) && attr->isMerged()) {
781      Attr *NewAttr = attr->clone(C);
782      NewAttr->setInherited(true);
783      New->addAttr(NewAttr);
784    }
785  }
786}
787
788/// Used in MergeFunctionDecl to keep track of function parameters in
789/// C.
790struct GNUCompatibleParamWarning {
791  ParmVarDecl *OldParm;
792  ParmVarDecl *NewParm;
793  QualType PromotedType;
794};
795
796/// MergeFunctionDecl - We just parsed a function 'New' from
797/// declarator D which has the same name and scope as a previous
798/// declaration 'Old'.  Figure out how to resolve this situation,
799/// merging decls or emitting diagnostics as appropriate.
800///
801/// In C++, New and Old must be declarations that are not
802/// overloaded. Use IsOverload to determine whether New and Old are
803/// overloaded, and to select the Old declaration that New should be
804/// merged with.
805///
806/// Returns true if there was an error, false otherwise.
807bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
808  assert(!isa<OverloadedFunctionDecl>(OldD) &&
809         "Cannot merge with an overloaded function declaration");
810
811  // Verify the old decl was also a function.
812  FunctionDecl *Old = 0;
813  if (FunctionTemplateDecl *OldFunctionTemplate
814        = dyn_cast<FunctionTemplateDecl>(OldD))
815    Old = OldFunctionTemplate->getTemplatedDecl();
816  else
817    Old = dyn_cast<FunctionDecl>(OldD);
818  if (!Old) {
819    Diag(New->getLocation(), diag::err_redefinition_different_kind)
820      << New->getDeclName();
821    Diag(OldD->getLocation(), diag::note_previous_definition);
822    return true;
823  }
824
825  // Determine whether the previous declaration was a definition,
826  // implicit declaration, or a declaration.
827  diag::kind PrevDiag;
828  if (Old->isThisDeclarationADefinition())
829    PrevDiag = diag::note_previous_definition;
830  else if (Old->isImplicit())
831    PrevDiag = diag::note_previous_implicit_declaration;
832  else
833    PrevDiag = diag::note_previous_declaration;
834
835  QualType OldQType = Context.getCanonicalType(Old->getType());
836  QualType NewQType = Context.getCanonicalType(New->getType());
837
838  if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
839      New->getStorageClass() == FunctionDecl::Static &&
840      Old->getStorageClass() != FunctionDecl::Static) {
841    Diag(New->getLocation(), diag::err_static_non_static)
842      << New;
843    Diag(Old->getLocation(), PrevDiag);
844    return true;
845  }
846
847  if (getLangOptions().CPlusPlus) {
848    // (C++98 13.1p2):
849    //   Certain function declarations cannot be overloaded:
850    //     -- Function declarations that differ only in the return type
851    //        cannot be overloaded.
852    QualType OldReturnType
853      = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
854    QualType NewReturnType
855      = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
856    if (OldReturnType != NewReturnType) {
857      Diag(New->getLocation(), diag::err_ovl_diff_return_type);
858      Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
859      return true;
860    }
861
862    const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
863    const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
864    if (OldMethod && NewMethod && !NewMethod->getFriendObjectKind() &&
865        NewMethod->getLexicalDeclContext()->isRecord()) {
866      //    -- Member function declarations with the same name and the
867      //       same parameter types cannot be overloaded if any of them
868      //       is a static member function declaration.
869      if (OldMethod->isStatic() || NewMethod->isStatic()) {
870        Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
871        Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
872        return true;
873      }
874
875      // C++ [class.mem]p1:
876      //   [...] A member shall not be declared twice in the
877      //   member-specification, except that a nested class or member
878      //   class template can be declared and then later defined.
879      unsigned NewDiag;
880      if (isa<CXXConstructorDecl>(OldMethod))
881        NewDiag = diag::err_constructor_redeclared;
882      else if (isa<CXXDestructorDecl>(NewMethod))
883        NewDiag = diag::err_destructor_redeclared;
884      else if (isa<CXXConversionDecl>(NewMethod))
885        NewDiag = diag::err_conv_function_redeclared;
886      else
887        NewDiag = diag::err_member_redeclared;
888
889      Diag(New->getLocation(), NewDiag);
890      Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
891    }
892
893    // (C++98 8.3.5p3):
894    //   All declarations for a function shall agree exactly in both the
895    //   return type and the parameter-type-list.
896    if (OldQType == NewQType)
897      return MergeCompatibleFunctionDecls(New, Old);
898
899    // Fall through for conflicting redeclarations and redefinitions.
900  }
901
902  // C: Function types need to be compatible, not identical. This handles
903  // duplicate function decls like "void f(int); void f(enum X);" properly.
904  if (!getLangOptions().CPlusPlus &&
905      Context.typesAreCompatible(OldQType, NewQType)) {
906    const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
907    const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
908    const FunctionProtoType *OldProto = 0;
909    if (isa<FunctionNoProtoType>(NewFuncType) &&
910        (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
911      // The old declaration provided a function prototype, but the
912      // new declaration does not. Merge in the prototype.
913      assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
914      llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
915                                                 OldProto->arg_type_end());
916      NewQType = Context.getFunctionType(NewFuncType->getResultType(),
917                                         ParamTypes.data(), ParamTypes.size(),
918                                         OldProto->isVariadic(),
919                                         OldProto->getTypeQuals());
920      New->setType(NewQType);
921      New->setHasInheritedPrototype();
922
923      // Synthesize a parameter for each argument type.
924      llvm::SmallVector<ParmVarDecl*, 16> Params;
925      for (FunctionProtoType::arg_type_iterator
926             ParamType = OldProto->arg_type_begin(),
927             ParamEnd = OldProto->arg_type_end();
928           ParamType != ParamEnd; ++ParamType) {
929        ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
930                                                 SourceLocation(), 0,
931                                                 *ParamType, /*DInfo=*/0,
932                                                 VarDecl::None, 0);
933        Param->setImplicit();
934        Params.push_back(Param);
935      }
936
937      New->setParams(Context, Params.data(), Params.size());
938    }
939
940    return MergeCompatibleFunctionDecls(New, Old);
941  }
942
943  // GNU C permits a K&R definition to follow a prototype declaration
944  // if the declared types of the parameters in the K&R definition
945  // match the types in the prototype declaration, even when the
946  // promoted types of the parameters from the K&R definition differ
947  // from the types in the prototype. GCC then keeps the types from
948  // the prototype.
949  //
950  // If a variadic prototype is followed by a non-variadic K&R definition,
951  // the K&R definition becomes variadic.  This is sort of an edge case, but
952  // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
953  // C99 6.9.1p8.
954  if (!getLangOptions().CPlusPlus &&
955      Old->hasPrototype() && !New->hasPrototype() &&
956      New->getType()->getAs<FunctionProtoType>() &&
957      Old->getNumParams() == New->getNumParams()) {
958    llvm::SmallVector<QualType, 16> ArgTypes;
959    llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings;
960    const FunctionProtoType *OldProto
961      = Old->getType()->getAs<FunctionProtoType>();
962    const FunctionProtoType *NewProto
963      = New->getType()->getAs<FunctionProtoType>();
964
965    // Determine whether this is the GNU C extension.
966    QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
967                                               NewProto->getResultType());
968    bool LooseCompatible = !MergedReturn.isNull();
969    for (unsigned Idx = 0, End = Old->getNumParams();
970         LooseCompatible && Idx != End; ++Idx) {
971      ParmVarDecl *OldParm = Old->getParamDecl(Idx);
972      ParmVarDecl *NewParm = New->getParamDecl(Idx);
973      if (Context.typesAreCompatible(OldParm->getType(),
974                                     NewProto->getArgType(Idx))) {
975        ArgTypes.push_back(NewParm->getType());
976      } else if (Context.typesAreCompatible(OldParm->getType(),
977                                            NewParm->getType())) {
978        GNUCompatibleParamWarning Warn
979          = { OldParm, NewParm, NewProto->getArgType(Idx) };
980        Warnings.push_back(Warn);
981        ArgTypes.push_back(NewParm->getType());
982      } else
983        LooseCompatible = false;
984    }
985
986    if (LooseCompatible) {
987      for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
988        Diag(Warnings[Warn].NewParm->getLocation(),
989             diag::ext_param_promoted_not_compatible_with_prototype)
990          << Warnings[Warn].PromotedType
991          << Warnings[Warn].OldParm->getType();
992        Diag(Warnings[Warn].OldParm->getLocation(),
993             diag::note_previous_declaration);
994      }
995
996      New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
997                                           ArgTypes.size(),
998                                           OldProto->isVariadic(), 0));
999      return MergeCompatibleFunctionDecls(New, Old);
1000    }
1001
1002    // Fall through to diagnose conflicting types.
1003  }
1004
1005  // A function that has already been declared has been redeclared or defined
1006  // with a different type- show appropriate diagnostic
1007  if (unsigned BuiltinID = Old->getBuiltinID()) {
1008    // The user has declared a builtin function with an incompatible
1009    // signature.
1010    if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
1011      // The function the user is redeclaring is a library-defined
1012      // function like 'malloc' or 'printf'. Warn about the
1013      // redeclaration, then pretend that we don't know about this
1014      // library built-in.
1015      Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
1016      Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
1017        << Old << Old->getType();
1018      New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
1019      Old->setInvalidDecl();
1020      return false;
1021    }
1022
1023    PrevDiag = diag::note_previous_builtin_declaration;
1024  }
1025
1026  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
1027  Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1028  return true;
1029}
1030
1031/// \brief Completes the merge of two function declarations that are
1032/// known to be compatible.
1033///
1034/// This routine handles the merging of attributes and other
1035/// properties of function declarations form the old declaration to
1036/// the new declaration, once we know that New is in fact a
1037/// redeclaration of Old.
1038///
1039/// \returns false
1040bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
1041  // Merge the attributes
1042  MergeAttributes(New, Old, Context);
1043
1044  // Merge the storage class.
1045  if (Old->getStorageClass() != FunctionDecl::Extern &&
1046      Old->getStorageClass() != FunctionDecl::None)
1047    New->setStorageClass(Old->getStorageClass());
1048
1049  // Merge "pure" flag.
1050  if (Old->isPure())
1051    New->setPure();
1052
1053  // Merge the "deleted" flag.
1054  if (Old->isDeleted())
1055    New->setDeleted();
1056
1057  if (getLangOptions().CPlusPlus)
1058    return MergeCXXFunctionDecl(New, Old);
1059
1060  return false;
1061}
1062
1063/// MergeVarDecl - We just parsed a variable 'New' which has the same name
1064/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
1065/// situation, merging decls or emitting diagnostics as appropriate.
1066///
1067/// Tentative definition rules (C99 6.9.2p2) are checked by
1068/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
1069/// definitions here, since the initializer hasn't been attached.
1070///
1071void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
1072  // If the new decl is already invalid, don't do any other checking.
1073  if (New->isInvalidDecl())
1074    return;
1075
1076  // Verify the old decl was also a variable.
1077  VarDecl *Old = 0;
1078  if (!Previous.isSingleResult() ||
1079      !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
1080    Diag(New->getLocation(), diag::err_redefinition_different_kind)
1081      << New->getDeclName();
1082    Diag(Previous.getRepresentativeDecl()->getLocation(),
1083         diag::note_previous_definition);
1084    return New->setInvalidDecl();
1085  }
1086
1087  MergeAttributes(New, Old, Context);
1088
1089  // Merge the types
1090  QualType MergedT;
1091  if (getLangOptions().CPlusPlus) {
1092    if (Context.hasSameType(New->getType(), Old->getType()))
1093      MergedT = New->getType();
1094    // C++ [basic.types]p7:
1095    //   [...] The declared type of an array object might be an array of
1096    //   unknown size and therefore be incomplete at one point in a
1097    //   translation unit and complete later on; [...]
1098    else if (Old->getType()->isIncompleteArrayType() &&
1099             New->getType()->isArrayType()) {
1100      CanQual<ArrayType> OldArray
1101        = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1102      CanQual<ArrayType> NewArray
1103        = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1104      if (OldArray->getElementType() == NewArray->getElementType())
1105        MergedT = New->getType();
1106    }
1107  } else {
1108    MergedT = Context.mergeTypes(New->getType(), Old->getType());
1109  }
1110  if (MergedT.isNull()) {
1111    Diag(New->getLocation(), diag::err_redefinition_different_type)
1112      << New->getDeclName();
1113    Diag(Old->getLocation(), diag::note_previous_definition);
1114    return New->setInvalidDecl();
1115  }
1116  New->setType(MergedT);
1117
1118  // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
1119  if (New->getStorageClass() == VarDecl::Static &&
1120      (Old->getStorageClass() == VarDecl::None || Old->hasExternalStorage())) {
1121    Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
1122    Diag(Old->getLocation(), diag::note_previous_definition);
1123    return New->setInvalidDecl();
1124  }
1125  // C99 6.2.2p4:
1126  //   For an identifier declared with the storage-class specifier
1127  //   extern in a scope in which a prior declaration of that
1128  //   identifier is visible,23) if the prior declaration specifies
1129  //   internal or external linkage, the linkage of the identifier at
1130  //   the later declaration is the same as the linkage specified at
1131  //   the prior declaration. If no prior declaration is visible, or
1132  //   if the prior declaration specifies no linkage, then the
1133  //   identifier has external linkage.
1134  if (New->hasExternalStorage() && Old->hasLinkage())
1135    /* Okay */;
1136  else if (New->getStorageClass() != VarDecl::Static &&
1137           Old->getStorageClass() == VarDecl::Static) {
1138    Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
1139    Diag(Old->getLocation(), diag::note_previous_definition);
1140    return New->setInvalidDecl();
1141  }
1142
1143  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
1144
1145  // FIXME: The test for external storage here seems wrong? We still
1146  // need to check for mismatches.
1147  if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
1148      // Don't complain about out-of-line definitions of static members.
1149      !(Old->getLexicalDeclContext()->isRecord() &&
1150        !New->getLexicalDeclContext()->isRecord())) {
1151    Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
1152    Diag(Old->getLocation(), diag::note_previous_definition);
1153    return New->setInvalidDecl();
1154  }
1155
1156  if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
1157    Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
1158    Diag(Old->getLocation(), diag::note_previous_definition);
1159  } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
1160    Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
1161    Diag(Old->getLocation(), diag::note_previous_definition);
1162  }
1163
1164  // Keep a chain of previous declarations.
1165  New->setPreviousDeclaration(Old);
1166}
1167
1168/// CheckFallThrough - Check that we don't fall off the end of a
1169/// Statement that should return a value.
1170///
1171/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
1172/// MaybeFallThrough iff we might or might not fall off the end,
1173/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
1174/// return.  We assume NeverFallThrough iff we never fall off the end of the
1175/// statement but we may return.  We assume that functions not marked noreturn
1176/// will return.
1177Sema::ControlFlowKind Sema::CheckFallThrough(Stmt *Root) {
1178  // FIXME: Eventually share this CFG object when we have other warnings based
1179  // of the CFG.  This can be done using AnalysisContext.
1180  llvm::OwningPtr<CFG> cfg (CFG::buildCFG(Root, &Context));
1181
1182  // FIXME: They should never return 0, fix that, delete this code.
1183  if (cfg == 0)
1184    // FIXME: This should be NeverFallThrough
1185    return NeverFallThroughOrReturn;
1186  // The CFG leaves in dead things, and we don't want to dead code paths to
1187  // confuse us, so we mark all live things first.
1188  std::queue<CFGBlock*> workq;
1189  llvm::BitVector live(cfg->getNumBlockIDs());
1190  // Prep work queue
1191  workq.push(&cfg->getEntry());
1192  // Solve
1193  while (!workq.empty()) {
1194    CFGBlock *item = workq.front();
1195    workq.pop();
1196    live.set(item->getBlockID());
1197    for (CFGBlock::succ_iterator I=item->succ_begin(),
1198           E=item->succ_end();
1199         I != E;
1200         ++I) {
1201      if ((*I) && !live[(*I)->getBlockID()]) {
1202        live.set((*I)->getBlockID());
1203        workq.push(*I);
1204      }
1205    }
1206  }
1207
1208  // Now we know what is live, we check the live precessors of the exit block
1209  // and look for fall through paths, being careful to ignore normal returns,
1210  // and exceptional paths.
1211  bool HasLiveReturn = false;
1212  bool HasFakeEdge = false;
1213  bool HasPlainEdge = false;
1214  for (CFGBlock::pred_iterator I=cfg->getExit().pred_begin(),
1215         E = cfg->getExit().pred_end();
1216       I != E;
1217       ++I) {
1218    CFGBlock& B = **I;
1219    if (!live[B.getBlockID()])
1220      continue;
1221    if (B.size() == 0) {
1222      // A labeled empty statement, or the entry block...
1223      HasPlainEdge = true;
1224      continue;
1225    }
1226    Stmt *S = B[B.size()-1];
1227    if (isa<ReturnStmt>(S)) {
1228      HasLiveReturn = true;
1229      continue;
1230    }
1231    if (isa<ObjCAtThrowStmt>(S)) {
1232      HasFakeEdge = true;
1233      continue;
1234    }
1235    if (isa<CXXThrowExpr>(S)) {
1236      HasFakeEdge = true;
1237      continue;
1238    }
1239    bool NoReturnEdge = false;
1240    if (CallExpr *C = dyn_cast<CallExpr>(S)) {
1241      Expr *CEE = C->getCallee()->IgnoreParenCasts();
1242      if (CEE->getType().getNoReturnAttr()) {
1243        NoReturnEdge = true;
1244        HasFakeEdge = true;
1245      } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) {
1246        if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1247          if (FD->hasAttr<NoReturnAttr>()) {
1248            NoReturnEdge = true;
1249            HasFakeEdge = true;
1250          }
1251        }
1252      }
1253    }
1254    // FIXME: Add noreturn message sends.
1255    if (NoReturnEdge == false)
1256      HasPlainEdge = true;
1257  }
1258  if (!HasPlainEdge) {
1259    if (HasLiveReturn)
1260      return NeverFallThrough;
1261    return NeverFallThroughOrReturn;
1262  }
1263  if (HasFakeEdge || HasLiveReturn)
1264    return MaybeFallThrough;
1265  // This says AlwaysFallThrough for calls to functions that are not marked
1266  // noreturn, that don't return.  If people would like this warning to be more
1267  // accurate, such functions should be marked as noreturn.
1268  return AlwaysFallThrough;
1269}
1270
1271/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
1272/// function that should return a value.  Check that we don't fall off the end
1273/// of a noreturn function.  We assume that functions and blocks not marked
1274/// noreturn will return.
1275void Sema::CheckFallThroughForFunctionDef(Decl *D, Stmt *Body) {
1276  // FIXME: Would be nice if we had a better way to control cascading errors,
1277  // but for now, avoid them.  The problem is that when Parse sees:
1278  //   int foo() { return a; }
1279  // The return is eaten and the Sema code sees just:
1280  //   int foo() { }
1281  // which this code would then warn about.
1282  if (getDiagnostics().hasErrorOccurred())
1283    return;
1284
1285  bool ReturnsVoid = false;
1286  bool HasNoReturn = false;
1287  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1288    // If the result type of the function is a dependent type, we don't know
1289    // whether it will be void or not, so don't
1290    if (FD->getResultType()->isDependentType())
1291      return;
1292    if (FD->getResultType()->isVoidType())
1293      ReturnsVoid = true;
1294    if (FD->hasAttr<NoReturnAttr>())
1295      HasNoReturn = true;
1296  } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
1297    if (MD->getResultType()->isVoidType())
1298      ReturnsVoid = true;
1299    if (MD->hasAttr<NoReturnAttr>())
1300      HasNoReturn = true;
1301  }
1302
1303  // Short circuit for compilation speed.
1304  if ((Diags.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function)
1305       == Diagnostic::Ignored || ReturnsVoid)
1306      && (Diags.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr)
1307          == Diagnostic::Ignored || !HasNoReturn)
1308      && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
1309          == Diagnostic::Ignored || !ReturnsVoid))
1310    return;
1311  // FIXME: Function try block
1312  if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
1313    switch (CheckFallThrough(Body)) {
1314    case MaybeFallThrough:
1315      if (HasNoReturn)
1316        Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function);
1317      else if (!ReturnsVoid)
1318        Diag(Compound->getRBracLoc(),diag::warn_maybe_falloff_nonvoid_function);
1319      break;
1320    case AlwaysFallThrough:
1321      if (HasNoReturn)
1322        Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function);
1323      else if (!ReturnsVoid)
1324        Diag(Compound->getRBracLoc(), diag::warn_falloff_nonvoid_function);
1325      break;
1326    case NeverFallThroughOrReturn:
1327      if (ReturnsVoid && !HasNoReturn)
1328        Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_function);
1329      break;
1330    case NeverFallThrough:
1331      break;
1332    }
1333  }
1334}
1335
1336/// CheckFallThroughForBlock - Check that we don't fall off the end of a block
1337/// that should return a value.  Check that we don't fall off the end of a
1338/// noreturn block.  We assume that functions and blocks not marked noreturn
1339/// will return.
1340void Sema::CheckFallThroughForBlock(QualType BlockTy, Stmt *Body) {
1341  // FIXME: Would be nice if we had a better way to control cascading errors,
1342  // but for now, avoid them.  The problem is that when Parse sees:
1343  //   int foo() { return a; }
1344  // The return is eaten and the Sema code sees just:
1345  //   int foo() { }
1346  // which this code would then warn about.
1347  if (getDiagnostics().hasErrorOccurred())
1348    return;
1349  bool ReturnsVoid = false;
1350  bool HasNoReturn = false;
1351  if (const FunctionType *FT =BlockTy->getPointeeType()->getAs<FunctionType>()){
1352    if (FT->getResultType()->isVoidType())
1353      ReturnsVoid = true;
1354    if (FT->getNoReturnAttr())
1355      HasNoReturn = true;
1356  }
1357
1358  // Short circuit for compilation speed.
1359  if (ReturnsVoid
1360      && !HasNoReturn
1361      && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
1362          == Diagnostic::Ignored || !ReturnsVoid))
1363    return;
1364  // FIXME: Funtion try block
1365  if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
1366    switch (CheckFallThrough(Body)) {
1367    case MaybeFallThrough:
1368      if (HasNoReturn)
1369        Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr);
1370      else if (!ReturnsVoid)
1371        Diag(Compound->getRBracLoc(), diag::err_maybe_falloff_nonvoid_block);
1372      break;
1373    case AlwaysFallThrough:
1374      if (HasNoReturn)
1375        Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr);
1376      else if (!ReturnsVoid)
1377        Diag(Compound->getRBracLoc(), diag::err_falloff_nonvoid_block);
1378      break;
1379    case NeverFallThroughOrReturn:
1380      if (ReturnsVoid)
1381        Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_block);
1382      break;
1383    case NeverFallThrough:
1384      break;
1385    }
1386  }
1387}
1388
1389/// CheckParmsForFunctionDef - Check that the parameters of the given
1390/// function are appropriate for the definition of a function. This
1391/// takes care of any checks that cannot be performed on the
1392/// declaration itself, e.g., that the types of each of the function
1393/// parameters are complete.
1394bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
1395  bool HasInvalidParm = false;
1396  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1397    ParmVarDecl *Param = FD->getParamDecl(p);
1398
1399    // C99 6.7.5.3p4: the parameters in a parameter type list in a
1400    // function declarator that is part of a function definition of
1401    // that function shall not have incomplete type.
1402    //
1403    // This is also C++ [dcl.fct]p6.
1404    if (!Param->isInvalidDecl() &&
1405        RequireCompleteType(Param->getLocation(), Param->getType(),
1406                               diag::err_typecheck_decl_incomplete_type)) {
1407      Param->setInvalidDecl();
1408      HasInvalidParm = true;
1409    }
1410
1411    // C99 6.9.1p5: If the declarator includes a parameter type list, the
1412    // declaration of each parameter shall include an identifier.
1413    if (Param->getIdentifier() == 0 &&
1414        !Param->isImplicit() &&
1415        !getLangOptions().CPlusPlus)
1416      Diag(Param->getLocation(), diag::err_parameter_name_omitted);
1417  }
1418
1419  return HasInvalidParm;
1420}
1421
1422/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
1423/// no declarator (e.g. "struct foo;") is parsed.
1424Sema::DeclPtrTy Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
1425  // FIXME: Error on auto/register at file scope
1426  // FIXME: Error on inline/virtual/explicit
1427  // FIXME: Error on invalid restrict
1428  // FIXME: Warn on useless __thread
1429  // FIXME: Warn on useless const/volatile
1430  // FIXME: Warn on useless static/extern/typedef/private_extern/mutable
1431  // FIXME: Warn on useless attributes
1432  Decl *TagD = 0;
1433  TagDecl *Tag = 0;
1434  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
1435      DS.getTypeSpecType() == DeclSpec::TST_struct ||
1436      DS.getTypeSpecType() == DeclSpec::TST_union ||
1437      DS.getTypeSpecType() == DeclSpec::TST_enum) {
1438    TagD = static_cast<Decl *>(DS.getTypeRep());
1439
1440    if (!TagD) // We probably had an error
1441      return DeclPtrTy();
1442
1443    // Note that the above type specs guarantee that the
1444    // type rep is a Decl, whereas in many of the others
1445    // it's a Type.
1446    Tag = dyn_cast<TagDecl>(TagD);
1447  }
1448
1449  if (DS.isFriendSpecified()) {
1450    // If we're dealing with a class template decl, assume that the
1451    // template routines are handling it.
1452    if (TagD && isa<ClassTemplateDecl>(TagD))
1453      return DeclPtrTy();
1454    return ActOnFriendTypeDecl(S, DS, MultiTemplateParamsArg(*this, 0, 0));
1455  }
1456
1457  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
1458    // If there are attributes in the DeclSpec, apply them to the record.
1459    if (const AttributeList *AL = DS.getAttributes())
1460      ProcessDeclAttributeList(S, Record, AL);
1461
1462    if (!Record->getDeclName() && Record->isDefinition() &&
1463        DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
1464      if (getLangOptions().CPlusPlus ||
1465          Record->getDeclContext()->isRecord())
1466        return BuildAnonymousStructOrUnion(S, DS, Record);
1467
1468      Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
1469        << DS.getSourceRange();
1470    }
1471
1472    // Microsoft allows unnamed struct/union fields. Don't complain
1473    // about them.
1474    // FIXME: Should we support Microsoft's extensions in this area?
1475    if (Record->getDeclName() && getLangOptions().Microsoft)
1476      return DeclPtrTy::make(Tag);
1477  }
1478
1479  if (!DS.isMissingDeclaratorOk() &&
1480      DS.getTypeSpecType() != DeclSpec::TST_error) {
1481    // Warn about typedefs of enums without names, since this is an
1482    // extension in both Microsoft an GNU.
1483    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
1484        Tag && isa<EnumDecl>(Tag)) {
1485      Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
1486        << DS.getSourceRange();
1487      return DeclPtrTy::make(Tag);
1488    }
1489
1490    Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
1491      << DS.getSourceRange();
1492    return DeclPtrTy();
1493  }
1494
1495  return DeclPtrTy::make(Tag);
1496}
1497
1498/// We are trying to introduce the given name into the given context;
1499/// check if there's an existing declaration that can't be overloaded.
1500///
1501/// \return true if this is a forbidden redeclaration
1502bool Sema::CheckRedeclaration(DeclContext *DC,
1503                              DeclarationName Name,
1504                              SourceLocation NameLoc,
1505                              unsigned diagnostic) {
1506  LookupResult R(*this, Name, NameLoc, LookupOrdinaryName,
1507                 ForRedeclaration);
1508  LookupQualifiedName(R, DC);
1509
1510  if (R.empty()) return false;
1511
1512  if (R.getResultKind() == LookupResult::Found &&
1513      isa<TagDecl>(R.getFoundDecl()))
1514    return false;
1515
1516  // Pick a representative declaration.
1517  NamedDecl *PrevDecl = (*R.begin())->getUnderlyingDecl();
1518
1519  Diag(NameLoc, diagnostic) << Name;
1520  Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
1521
1522  return true;
1523}
1524
1525/// InjectAnonymousStructOrUnionMembers - Inject the members of the
1526/// anonymous struct or union AnonRecord into the owning context Owner
1527/// and scope S. This routine will be invoked just after we realize
1528/// that an unnamed union or struct is actually an anonymous union or
1529/// struct, e.g.,
1530///
1531/// @code
1532/// union {
1533///   int i;
1534///   float f;
1535/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
1536///    // f into the surrounding scope.x
1537/// @endcode
1538///
1539/// This routine is recursive, injecting the names of nested anonymous
1540/// structs/unions into the owning context and scope as well.
1541bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
1542                                               RecordDecl *AnonRecord) {
1543  unsigned diagKind
1544    = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
1545                            : diag::err_anonymous_struct_member_redecl;
1546
1547  bool Invalid = false;
1548  for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
1549                               FEnd = AnonRecord->field_end();
1550       F != FEnd; ++F) {
1551    if ((*F)->getDeclName()) {
1552      if (CheckRedeclaration(Owner, (*F)->getDeclName(),
1553                             (*F)->getLocation(), diagKind)) {
1554        // C++ [class.union]p2:
1555        //   The names of the members of an anonymous union shall be
1556        //   distinct from the names of any other entity in the
1557        //   scope in which the anonymous union is declared.
1558        Invalid = true;
1559      } else {
1560        // C++ [class.union]p2:
1561        //   For the purpose of name lookup, after the anonymous union
1562        //   definition, the members of the anonymous union are
1563        //   considered to have been defined in the scope in which the
1564        //   anonymous union is declared.
1565        Owner->makeDeclVisibleInContext(*F);
1566        S->AddDecl(DeclPtrTy::make(*F));
1567        IdResolver.AddDecl(*F);
1568      }
1569    } else if (const RecordType *InnerRecordType
1570                 = (*F)->getType()->getAs<RecordType>()) {
1571      RecordDecl *InnerRecord = InnerRecordType->getDecl();
1572      if (InnerRecord->isAnonymousStructOrUnion())
1573        Invalid = Invalid ||
1574          InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
1575    }
1576  }
1577
1578  return Invalid;
1579}
1580
1581/// ActOnAnonymousStructOrUnion - Handle the declaration of an
1582/// anonymous structure or union. Anonymous unions are a C++ feature
1583/// (C++ [class.union]) and a GNU C extension; anonymous structures
1584/// are a GNU C and GNU C++ extension.
1585Sema::DeclPtrTy Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1586                                                  RecordDecl *Record) {
1587  DeclContext *Owner = Record->getDeclContext();
1588
1589  // Diagnose whether this anonymous struct/union is an extension.
1590  if (Record->isUnion() && !getLangOptions().CPlusPlus)
1591    Diag(Record->getLocation(), diag::ext_anonymous_union);
1592  else if (!Record->isUnion())
1593    Diag(Record->getLocation(), diag::ext_anonymous_struct);
1594
1595  // C and C++ require different kinds of checks for anonymous
1596  // structs/unions.
1597  bool Invalid = false;
1598  if (getLangOptions().CPlusPlus) {
1599    const char* PrevSpec = 0;
1600    unsigned DiagID;
1601    // C++ [class.union]p3:
1602    //   Anonymous unions declared in a named namespace or in the
1603    //   global namespace shall be declared static.
1604    if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
1605        (isa<TranslationUnitDecl>(Owner) ||
1606         (isa<NamespaceDecl>(Owner) &&
1607          cast<NamespaceDecl>(Owner)->getDeclName()))) {
1608      Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
1609      Invalid = true;
1610
1611      // Recover by adding 'static'.
1612      DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(),
1613                             PrevSpec, DiagID);
1614    }
1615    // C++ [class.union]p3:
1616    //   A storage class is not allowed in a declaration of an
1617    //   anonymous union in a class scope.
1618    else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1619             isa<RecordDecl>(Owner)) {
1620      Diag(DS.getStorageClassSpecLoc(),
1621           diag::err_anonymous_union_with_storage_spec);
1622      Invalid = true;
1623
1624      // Recover by removing the storage specifier.
1625      DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
1626                             PrevSpec, DiagID);
1627    }
1628
1629    // C++ [class.union]p2:
1630    //   The member-specification of an anonymous union shall only
1631    //   define non-static data members. [Note: nested types and
1632    //   functions cannot be declared within an anonymous union. ]
1633    for (DeclContext::decl_iterator Mem = Record->decls_begin(),
1634                                 MemEnd = Record->decls_end();
1635         Mem != MemEnd; ++Mem) {
1636      if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
1637        // C++ [class.union]p3:
1638        //   An anonymous union shall not have private or protected
1639        //   members (clause 11).
1640        if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
1641          Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
1642            << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
1643          Invalid = true;
1644        }
1645      } else if ((*Mem)->isImplicit()) {
1646        // Any implicit members are fine.
1647      } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
1648        // This is a type that showed up in an
1649        // elaborated-type-specifier inside the anonymous struct or
1650        // union, but which actually declares a type outside of the
1651        // anonymous struct or union. It's okay.
1652      } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
1653        if (!MemRecord->isAnonymousStructOrUnion() &&
1654            MemRecord->getDeclName()) {
1655          // This is a nested type declaration.
1656          Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
1657            << (int)Record->isUnion();
1658          Invalid = true;
1659        }
1660      } else {
1661        // We have something that isn't a non-static data
1662        // member. Complain about it.
1663        unsigned DK = diag::err_anonymous_record_bad_member;
1664        if (isa<TypeDecl>(*Mem))
1665          DK = diag::err_anonymous_record_with_type;
1666        else if (isa<FunctionDecl>(*Mem))
1667          DK = diag::err_anonymous_record_with_function;
1668        else if (isa<VarDecl>(*Mem))
1669          DK = diag::err_anonymous_record_with_static;
1670        Diag((*Mem)->getLocation(), DK)
1671            << (int)Record->isUnion();
1672          Invalid = true;
1673      }
1674    }
1675  }
1676
1677  if (!Record->isUnion() && !Owner->isRecord()) {
1678    Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
1679      << (int)getLangOptions().CPlusPlus;
1680    Invalid = true;
1681  }
1682
1683  // Mock up a declarator.
1684  Declarator Dc(DS, Declarator::TypeNameContext);
1685  DeclaratorInfo *DInfo = 0;
1686  GetTypeForDeclarator(Dc, S, &DInfo);
1687  assert(DInfo && "couldn't build declarator info for anonymous struct/union");
1688
1689  // Create a declaration for this anonymous struct/union.
1690  NamedDecl *Anon = 0;
1691  if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
1692    Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
1693                             /*IdentifierInfo=*/0,
1694                             Context.getTypeDeclType(Record),
1695                             DInfo,
1696                             /*BitWidth=*/0, /*Mutable=*/false);
1697    Anon->setAccess(AS_public);
1698    if (getLangOptions().CPlusPlus)
1699      FieldCollector->Add(cast<FieldDecl>(Anon));
1700  } else {
1701    VarDecl::StorageClass SC;
1702    switch (DS.getStorageClassSpec()) {
1703    default: assert(0 && "Unknown storage class!");
1704    case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
1705    case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
1706    case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
1707    case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
1708    case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
1709    case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1710    case DeclSpec::SCS_mutable:
1711      // mutable can only appear on non-static class members, so it's always
1712      // an error here
1713      Diag(Record->getLocation(), diag::err_mutable_nonmember);
1714      Invalid = true;
1715      SC = VarDecl::None;
1716      break;
1717    }
1718
1719    Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
1720                           /*IdentifierInfo=*/0,
1721                           Context.getTypeDeclType(Record),
1722                           DInfo,
1723                           SC);
1724  }
1725  Anon->setImplicit();
1726
1727  // Add the anonymous struct/union object to the current
1728  // context. We'll be referencing this object when we refer to one of
1729  // its members.
1730  Owner->addDecl(Anon);
1731
1732  // Inject the members of the anonymous struct/union into the owning
1733  // context and into the identifier resolver chain for name lookup
1734  // purposes.
1735  if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
1736    Invalid = true;
1737
1738  // Mark this as an anonymous struct/union type. Note that we do not
1739  // do this until after we have already checked and injected the
1740  // members of this anonymous struct/union type, because otherwise
1741  // the members could be injected twice: once by DeclContext when it
1742  // builds its lookup table, and once by
1743  // InjectAnonymousStructOrUnionMembers.
1744  Record->setAnonymousStructOrUnion(true);
1745
1746  if (Invalid)
1747    Anon->setInvalidDecl();
1748
1749  return DeclPtrTy::make(Anon);
1750}
1751
1752
1753/// GetNameForDeclarator - Determine the full declaration name for the
1754/// given Declarator.
1755DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1756  return GetNameFromUnqualifiedId(D.getName());
1757}
1758
1759/// \brief Retrieves the canonicalized name from a parsed unqualified-id.
1760DeclarationName Sema::GetNameFromUnqualifiedId(UnqualifiedId &Name) {
1761  switch (Name.getKind()) {
1762    case UnqualifiedId::IK_Identifier:
1763      return DeclarationName(Name.Identifier);
1764
1765    case UnqualifiedId::IK_OperatorFunctionId:
1766      return Context.DeclarationNames.getCXXOperatorName(
1767                                                         Name.OperatorFunctionId.Operator);
1768
1769    case UnqualifiedId::IK_LiteralOperatorId:
1770      assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1771
1772    case UnqualifiedId::IK_ConversionFunctionId: {
1773      QualType Ty = GetTypeFromParser(Name.ConversionFunctionId);
1774      if (Ty.isNull())
1775        return DeclarationName();
1776
1777      return Context.DeclarationNames.getCXXConversionFunctionName(
1778                                                                   Context.getCanonicalType(Ty));
1779    }
1780
1781    case UnqualifiedId::IK_ConstructorName: {
1782      QualType Ty = GetTypeFromParser(Name.ConstructorName);
1783      if (Ty.isNull())
1784        return DeclarationName();
1785
1786      return Context.DeclarationNames.getCXXConstructorName(
1787                                                            Context.getCanonicalType(Ty));
1788    }
1789
1790    case UnqualifiedId::IK_DestructorName: {
1791      QualType Ty = GetTypeFromParser(Name.DestructorName);
1792      if (Ty.isNull())
1793        return DeclarationName();
1794
1795      return Context.DeclarationNames.getCXXDestructorName(
1796                                                           Context.getCanonicalType(Ty));
1797    }
1798
1799    case UnqualifiedId::IK_TemplateId: {
1800      TemplateName TName
1801        = TemplateName::getFromVoidPointer(Name.TemplateId->Template);
1802      if (TemplateDecl *Template = TName.getAsTemplateDecl())
1803        return Template->getDeclName();
1804      if (OverloadedFunctionDecl *Ovl = TName.getAsOverloadedFunctionDecl())
1805        return Ovl->getDeclName();
1806
1807      return DeclarationName();
1808    }
1809  }
1810
1811  assert(false && "Unknown name kind");
1812  return DeclarationName();
1813}
1814
1815/// isNearlyMatchingFunction - Determine whether the C++ functions
1816/// Declaration and Definition are "nearly" matching. This heuristic
1817/// is used to improve diagnostics in the case where an out-of-line
1818/// function definition doesn't match any declaration within
1819/// the class or namespace.
1820static bool isNearlyMatchingFunction(ASTContext &Context,
1821                                     FunctionDecl *Declaration,
1822                                     FunctionDecl *Definition) {
1823  if (Declaration->param_size() != Definition->param_size())
1824    return false;
1825  for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1826    QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1827    QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1828
1829    if (!Context.hasSameUnqualifiedType(DeclParamTy.getNonReferenceType(),
1830                                        DefParamTy.getNonReferenceType()))
1831      return false;
1832  }
1833
1834  return true;
1835}
1836
1837Sema::DeclPtrTy
1838Sema::HandleDeclarator(Scope *S, Declarator &D,
1839                       MultiTemplateParamsArg TemplateParamLists,
1840                       bool IsFunctionDefinition) {
1841  DeclarationName Name = GetNameForDeclarator(D);
1842
1843  // All of these full declarators require an identifier.  If it doesn't have
1844  // one, the ParsedFreeStandingDeclSpec action should be used.
1845  if (!Name) {
1846    if (!D.isInvalidType())  // Reject this if we think it is valid.
1847      Diag(D.getDeclSpec().getSourceRange().getBegin(),
1848           diag::err_declarator_need_ident)
1849        << D.getDeclSpec().getSourceRange() << D.getSourceRange();
1850    return DeclPtrTy();
1851  }
1852
1853  // The scope passed in may not be a decl scope.  Zip up the scope tree until
1854  // we find one that is.
1855  while ((S->getFlags() & Scope::DeclScope) == 0 ||
1856         (S->getFlags() & Scope::TemplateParamScope) != 0)
1857    S = S->getParent();
1858
1859  // If this is an out-of-line definition of a member of a class template
1860  // or class template partial specialization, we may need to rebuild the
1861  // type specifier in the declarator. See RebuildTypeInCurrentInstantiation()
1862  // for more information.
1863  // FIXME: cope with decltype(expr) and typeof(expr) once the rebuilder can
1864  // handle expressions properly.
1865  DeclSpec &DS = const_cast<DeclSpec&>(D.getDeclSpec());
1866  if (D.getCXXScopeSpec().isSet() && !D.getCXXScopeSpec().isInvalid() &&
1867      isDependentScopeSpecifier(D.getCXXScopeSpec()) &&
1868      (DS.getTypeSpecType() == DeclSpec::TST_typename ||
1869       DS.getTypeSpecType() == DeclSpec::TST_typeofType ||
1870       DS.getTypeSpecType() == DeclSpec::TST_typeofExpr ||
1871       DS.getTypeSpecType() == DeclSpec::TST_decltype)) {
1872    if (DeclContext *DC = computeDeclContext(D.getCXXScopeSpec(), true)) {
1873      // FIXME: Preserve type source info.
1874      QualType T = GetTypeFromParser(DS.getTypeRep());
1875      EnterDeclaratorContext(S, DC);
1876      T = RebuildTypeInCurrentInstantiation(T, D.getIdentifierLoc(), Name);
1877      ExitDeclaratorContext(S);
1878      if (T.isNull())
1879        return DeclPtrTy();
1880      DS.UpdateTypeRep(T.getAsOpaquePtr());
1881    }
1882  }
1883
1884  DeclContext *DC;
1885  NamedDecl *New;
1886
1887  DeclaratorInfo *DInfo = 0;
1888  QualType R = GetTypeForDeclarator(D, S, &DInfo);
1889
1890  LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
1891                        ForRedeclaration);
1892
1893  // See if this is a redefinition of a variable in the same scope.
1894  if (D.getCXXScopeSpec().isInvalid()) {
1895    DC = CurContext;
1896    D.setInvalidType();
1897  } else if (!D.getCXXScopeSpec().isSet()) {
1898    bool IsLinkageLookup = false;
1899
1900    // If the declaration we're planning to build will be a function
1901    // or object with linkage, then look for another declaration with
1902    // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
1903    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1904      /* Do nothing*/;
1905    else if (R->isFunctionType()) {
1906      if (CurContext->isFunctionOrMethod() ||
1907          D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
1908        IsLinkageLookup = true;
1909    } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
1910      IsLinkageLookup = true;
1911    else if (CurContext->getLookupContext()->isTranslationUnit() &&
1912             D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
1913      IsLinkageLookup = true;
1914
1915    if (IsLinkageLookup)
1916      Previous.clear(LookupRedeclarationWithLinkage);
1917
1918    DC = CurContext;
1919    LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
1920  } else { // Something like "int foo::x;"
1921    DC = computeDeclContext(D.getCXXScopeSpec(), true);
1922
1923    if (!DC) {
1924      // If we could not compute the declaration context, it's because the
1925      // declaration context is dependent but does not refer to a class,
1926      // class template, or class template partial specialization. Complain
1927      // and return early, to avoid the coming semantic disaster.
1928      Diag(D.getIdentifierLoc(),
1929           diag::err_template_qualified_declarator_no_match)
1930        << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
1931        << D.getCXXScopeSpec().getRange();
1932      return DeclPtrTy();
1933    }
1934
1935    if (!DC->isDependentContext() &&
1936        RequireCompleteDeclContext(D.getCXXScopeSpec()))
1937      return DeclPtrTy();
1938
1939    LookupQualifiedName(Previous, DC);
1940
1941    // Don't consider using declarations as previous declarations for
1942    // out-of-line members.
1943    RemoveUsingDecls(Previous);
1944
1945    // C++ 7.3.1.2p2:
1946    // Members (including explicit specializations of templates) of a named
1947    // namespace can also be defined outside that namespace by explicit
1948    // qualification of the name being defined, provided that the entity being
1949    // defined was already declared in the namespace and the definition appears
1950    // after the point of declaration in a namespace that encloses the
1951    // declarations namespace.
1952    //
1953    // Note that we only check the context at this point. We don't yet
1954    // have enough information to make sure that PrevDecl is actually
1955    // the declaration we want to match. For example, given:
1956    //
1957    //   class X {
1958    //     void f();
1959    //     void f(float);
1960    //   };
1961    //
1962    //   void X::f(int) { } // ill-formed
1963    //
1964    // In this case, PrevDecl will point to the overload set
1965    // containing the two f's declared in X, but neither of them
1966    // matches.
1967
1968    // First check whether we named the global scope.
1969    if (isa<TranslationUnitDecl>(DC)) {
1970      Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
1971        << Name << D.getCXXScopeSpec().getRange();
1972    } else {
1973      DeclContext *Cur = CurContext;
1974      while (isa<LinkageSpecDecl>(Cur))
1975        Cur = Cur->getParent();
1976      if (!Cur->Encloses(DC)) {
1977        // The qualifying scope doesn't enclose the original declaration.
1978        // Emit diagnostic based on current scope.
1979        SourceLocation L = D.getIdentifierLoc();
1980        SourceRange R = D.getCXXScopeSpec().getRange();
1981        if (isa<FunctionDecl>(Cur))
1982          Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
1983        else
1984          Diag(L, diag::err_invalid_declarator_scope)
1985            << Name << cast<NamedDecl>(DC) << R;
1986        D.setInvalidType();
1987      }
1988    }
1989  }
1990
1991  if (Previous.isSingleResult() &&
1992      Previous.getFoundDecl()->isTemplateParameter()) {
1993    // Maybe we will complain about the shadowed template parameter.
1994    if (!D.isInvalidType())
1995      if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
1996                                          Previous.getFoundDecl()))
1997        D.setInvalidType();
1998
1999    // Just pretend that we didn't see the previous declaration.
2000    Previous.clear();
2001  }
2002
2003  // In C++, the previous declaration we find might be a tag type
2004  // (class or enum). In this case, the new declaration will hide the
2005  // tag type. Note that this does does not apply if we're declaring a
2006  // typedef (C++ [dcl.typedef]p4).
2007  if (Previous.isSingleTagDecl() &&
2008      D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
2009    Previous.clear();
2010
2011  bool Redeclaration = false;
2012  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
2013    if (TemplateParamLists.size()) {
2014      Diag(D.getIdentifierLoc(), diag::err_template_typedef);
2015      return DeclPtrTy();
2016    }
2017
2018    New = ActOnTypedefDeclarator(S, D, DC, R, DInfo, Previous, Redeclaration);
2019  } else if (R->isFunctionType()) {
2020    New = ActOnFunctionDeclarator(S, D, DC, R, DInfo, Previous,
2021                                  move(TemplateParamLists),
2022                                  IsFunctionDefinition, Redeclaration);
2023  } else {
2024    New = ActOnVariableDeclarator(S, D, DC, R, DInfo, Previous,
2025                                  move(TemplateParamLists),
2026                                  Redeclaration);
2027  }
2028
2029  if (New == 0)
2030    return DeclPtrTy();
2031
2032  // If this has an identifier and is not an invalid redeclaration or
2033  // function template specialization, add it to the scope stack.
2034  if (Name && !(Redeclaration && New->isInvalidDecl()) &&
2035      !(isa<FunctionDecl>(New) &&
2036        cast<FunctionDecl>(New)->isFunctionTemplateSpecialization()))
2037    PushOnScopeChains(New, S);
2038
2039  return DeclPtrTy::make(New);
2040}
2041
2042/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2043/// types into constant array types in certain situations which would otherwise
2044/// be errors (for GCC compatibility).
2045static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2046                                                    ASTContext &Context,
2047                                                    bool &SizeIsNegative) {
2048  // This method tries to turn a variable array into a constant
2049  // array even when the size isn't an ICE.  This is necessary
2050  // for compatibility with code that depends on gcc's buggy
2051  // constant expression folding, like struct {char x[(int)(char*)2];}
2052  SizeIsNegative = false;
2053
2054  QualifierCollector Qs;
2055  const Type *Ty = Qs.strip(T);
2056
2057  if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
2058    QualType Pointee = PTy->getPointeeType();
2059    QualType FixedType =
2060        TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative);
2061    if (FixedType.isNull()) return FixedType;
2062    FixedType = Context.getPointerType(FixedType);
2063    return Qs.apply(FixedType);
2064  }
2065
2066  const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2067  if (!VLATy)
2068    return QualType();
2069  // FIXME: We should probably handle this case
2070  if (VLATy->getElementType()->isVariablyModifiedType())
2071    return QualType();
2072
2073  Expr::EvalResult EvalResult;
2074  if (!VLATy->getSizeExpr() ||
2075      !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) ||
2076      !EvalResult.Val.isInt())
2077    return QualType();
2078
2079  llvm::APSInt &Res = EvalResult.Val.getInt();
2080  if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned())) {
2081    // TODO: preserve the size expression in declarator info
2082    return Context.getConstantArrayType(VLATy->getElementType(),
2083                                        Res, ArrayType::Normal, 0);
2084  }
2085
2086  SizeIsNegative = true;
2087  return QualType();
2088}
2089
2090/// \brief Register the given locally-scoped external C declaration so
2091/// that it can be found later for redeclarations
2092void
2093Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
2094                                       const LookupResult &Previous,
2095                                       Scope *S) {
2096  assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
2097         "Decl is not a locally-scoped decl!");
2098  // Note that we have a locally-scoped external with this name.
2099  LocallyScopedExternalDecls[ND->getDeclName()] = ND;
2100
2101  if (!Previous.isSingleResult())
2102    return;
2103
2104  NamedDecl *PrevDecl = Previous.getFoundDecl();
2105
2106  // If there was a previous declaration of this variable, it may be
2107  // in our identifier chain. Update the identifier chain with the new
2108  // declaration.
2109  if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
2110    // The previous declaration was found on the identifer resolver
2111    // chain, so remove it from its scope.
2112    while (S && !S->isDeclScope(DeclPtrTy::make(PrevDecl)))
2113      S = S->getParent();
2114
2115    if (S)
2116      S->RemoveDecl(DeclPtrTy::make(PrevDecl));
2117  }
2118}
2119
2120/// \brief Diagnose function specifiers on a declaration of an identifier that
2121/// does not identify a function.
2122void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
2123  // FIXME: We should probably indicate the identifier in question to avoid
2124  // confusion for constructs like "inline int a(), b;"
2125  if (D.getDeclSpec().isInlineSpecified())
2126    Diag(D.getDeclSpec().getInlineSpecLoc(),
2127         diag::err_inline_non_function);
2128
2129  if (D.getDeclSpec().isVirtualSpecified())
2130    Diag(D.getDeclSpec().getVirtualSpecLoc(),
2131         diag::err_virtual_non_function);
2132
2133  if (D.getDeclSpec().isExplicitSpecified())
2134    Diag(D.getDeclSpec().getExplicitSpecLoc(),
2135         diag::err_explicit_non_function);
2136}
2137
2138NamedDecl*
2139Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2140                             QualType R,  DeclaratorInfo *DInfo,
2141                             LookupResult &Previous, bool &Redeclaration) {
2142  // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
2143  if (D.getCXXScopeSpec().isSet()) {
2144    Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
2145      << D.getCXXScopeSpec().getRange();
2146    D.setInvalidType();
2147    // Pretend we didn't see the scope specifier.
2148    DC = 0;
2149  }
2150
2151  if (getLangOptions().CPlusPlus) {
2152    // Check that there are no default arguments (C++ only).
2153    CheckExtraCXXDefaultArguments(D);
2154  }
2155
2156  DiagnoseFunctionSpecifiers(D);
2157
2158  if (D.getDeclSpec().isThreadSpecified())
2159    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2160
2161  TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, DInfo);
2162  if (!NewTD) return 0;
2163
2164  // Handle attributes prior to checking for duplicates in MergeVarDecl
2165  ProcessDeclAttributes(S, NewTD, D);
2166
2167  // Merge the decl with the existing one if appropriate. If the decl is
2168  // in an outer scope, it isn't the same thing.
2169  FilterLookupForScope(*this, Previous, DC, S, /*ConsiderLinkage*/ false);
2170  if (!Previous.empty()) {
2171    Redeclaration = true;
2172    MergeTypeDefDecl(NewTD, Previous);
2173  }
2174
2175  // C99 6.7.7p2: If a typedef name specifies a variably modified type
2176  // then it shall have block scope.
2177  QualType T = NewTD->getUnderlyingType();
2178  if (T->isVariablyModifiedType()) {
2179    CurFunctionNeedsScopeChecking = true;
2180
2181    if (S->getFnParent() == 0) {
2182      bool SizeIsNegative;
2183      QualType FixedTy =
2184          TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
2185      if (!FixedTy.isNull()) {
2186        Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size);
2187        NewTD->setTypeDeclaratorInfo(Context.getTrivialDeclaratorInfo(FixedTy));
2188      } else {
2189        if (SizeIsNegative)
2190          Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size);
2191        else if (T->isVariableArrayType())
2192          Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
2193        else
2194          Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
2195        NewTD->setInvalidDecl();
2196      }
2197    }
2198  }
2199
2200  // If this is the C FILE type, notify the AST context.
2201  if (IdentifierInfo *II = NewTD->getIdentifier())
2202    if (!NewTD->isInvalidDecl() &&
2203        NewTD->getDeclContext()->getLookupContext()->isTranslationUnit()) {
2204      if (II->isStr("FILE"))
2205        Context.setFILEDecl(NewTD);
2206      else if (II->isStr("jmp_buf"))
2207        Context.setjmp_bufDecl(NewTD);
2208      else if (II->isStr("sigjmp_buf"))
2209        Context.setsigjmp_bufDecl(NewTD);
2210    }
2211
2212  return NewTD;
2213}
2214
2215/// \brief Determines whether the given declaration is an out-of-scope
2216/// previous declaration.
2217///
2218/// This routine should be invoked when name lookup has found a
2219/// previous declaration (PrevDecl) that is not in the scope where a
2220/// new declaration by the same name is being introduced. If the new
2221/// declaration occurs in a local scope, previous declarations with
2222/// linkage may still be considered previous declarations (C99
2223/// 6.2.2p4-5, C++ [basic.link]p6).
2224///
2225/// \param PrevDecl the previous declaration found by name
2226/// lookup
2227///
2228/// \param DC the context in which the new declaration is being
2229/// declared.
2230///
2231/// \returns true if PrevDecl is an out-of-scope previous declaration
2232/// for a new delcaration with the same name.
2233static bool
2234isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
2235                                ASTContext &Context) {
2236  if (!PrevDecl)
2237    return 0;
2238
2239  // FIXME: PrevDecl could be an OverloadedFunctionDecl, in which
2240  // case we need to check each of the overloaded functions.
2241  if (!PrevDecl->hasLinkage())
2242    return false;
2243
2244  if (Context.getLangOptions().CPlusPlus) {
2245    // C++ [basic.link]p6:
2246    //   If there is a visible declaration of an entity with linkage
2247    //   having the same name and type, ignoring entities declared
2248    //   outside the innermost enclosing namespace scope, the block
2249    //   scope declaration declares that same entity and receives the
2250    //   linkage of the previous declaration.
2251    DeclContext *OuterContext = DC->getLookupContext();
2252    if (!OuterContext->isFunctionOrMethod())
2253      // This rule only applies to block-scope declarations.
2254      return false;
2255    else {
2256      DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
2257      if (PrevOuterContext->isRecord())
2258        // We found a member function: ignore it.
2259        return false;
2260      else {
2261        // Find the innermost enclosing namespace for the new and
2262        // previous declarations.
2263        while (!OuterContext->isFileContext())
2264          OuterContext = OuterContext->getParent();
2265        while (!PrevOuterContext->isFileContext())
2266          PrevOuterContext = PrevOuterContext->getParent();
2267
2268        // The previous declaration is in a different namespace, so it
2269        // isn't the same function.
2270        if (OuterContext->getPrimaryContext() !=
2271            PrevOuterContext->getPrimaryContext())
2272          return false;
2273      }
2274    }
2275  }
2276
2277  return true;
2278}
2279
2280NamedDecl*
2281Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2282                              QualType R, DeclaratorInfo *DInfo,
2283                              LookupResult &Previous,
2284                              MultiTemplateParamsArg TemplateParamLists,
2285                              bool &Redeclaration) {
2286  DeclarationName Name = GetNameForDeclarator(D);
2287
2288  // Check that there are no default arguments (C++ only).
2289  if (getLangOptions().CPlusPlus)
2290    CheckExtraCXXDefaultArguments(D);
2291
2292  VarDecl *NewVD;
2293  VarDecl::StorageClass SC;
2294  switch (D.getDeclSpec().getStorageClassSpec()) {
2295  default: assert(0 && "Unknown storage class!");
2296  case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
2297  case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
2298  case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
2299  case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
2300  case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
2301  case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
2302  case DeclSpec::SCS_mutable:
2303    // mutable can only appear on non-static class members, so it's always
2304    // an error here
2305    Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
2306    D.setInvalidType();
2307    SC = VarDecl::None;
2308    break;
2309  }
2310
2311  IdentifierInfo *II = Name.getAsIdentifierInfo();
2312  if (!II) {
2313    Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
2314      << Name.getAsString();
2315    return 0;
2316  }
2317
2318  DiagnoseFunctionSpecifiers(D);
2319
2320  if (!DC->isRecord() && S->getFnParent() == 0) {
2321    // C99 6.9p2: The storage-class specifiers auto and register shall not
2322    // appear in the declaration specifiers in an external declaration.
2323    if (SC == VarDecl::Auto || SC == VarDecl::Register) {
2324
2325      // If this is a register variable with an asm label specified, then this
2326      // is a GNU extension.
2327      if (SC == VarDecl::Register && D.getAsmLabel())
2328        Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
2329      else
2330        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
2331      D.setInvalidType();
2332    }
2333  }
2334  if (DC->isRecord() && !CurContext->isRecord()) {
2335    // This is an out-of-line definition of a static data member.
2336    if (SC == VarDecl::Static) {
2337      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2338           diag::err_static_out_of_line)
2339        << CodeModificationHint::CreateRemoval(
2340                       SourceRange(D.getDeclSpec().getStorageClassSpecLoc()));
2341    } else if (SC == VarDecl::None)
2342      SC = VarDecl::Static;
2343  }
2344  if (SC == VarDecl::Static) {
2345    if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
2346      if (RD->isLocalClass())
2347        Diag(D.getIdentifierLoc(),
2348             diag::err_static_data_member_not_allowed_in_local_class)
2349          << Name << RD->getDeclName();
2350    }
2351  }
2352
2353  // Match up the template parameter lists with the scope specifier, then
2354  // determine whether we have a template or a template specialization.
2355  bool isExplicitSpecialization = false;
2356  if (TemplateParameterList *TemplateParams
2357        = MatchTemplateParametersToScopeSpecifier(
2358                                  D.getDeclSpec().getSourceRange().getBegin(),
2359                                                  D.getCXXScopeSpec(),
2360                        (TemplateParameterList**)TemplateParamLists.get(),
2361                                                   TemplateParamLists.size(),
2362                                                  isExplicitSpecialization)) {
2363    if (TemplateParams->size() > 0) {
2364      // There is no such thing as a variable template.
2365      Diag(D.getIdentifierLoc(), diag::err_template_variable)
2366        << II
2367        << SourceRange(TemplateParams->getTemplateLoc(),
2368                       TemplateParams->getRAngleLoc());
2369      return 0;
2370    } else {
2371      // There is an extraneous 'template<>' for this variable. Complain
2372      // about it, but allow the declaration of the variable.
2373      Diag(TemplateParams->getTemplateLoc(),
2374           diag::err_template_variable_noparams)
2375        << II
2376        << SourceRange(TemplateParams->getTemplateLoc(),
2377                       TemplateParams->getRAngleLoc());
2378
2379      isExplicitSpecialization = true;
2380    }
2381  }
2382
2383  NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
2384                          II, R, DInfo, SC);
2385
2386  if (D.isInvalidType())
2387    NewVD->setInvalidDecl();
2388
2389  if (D.getDeclSpec().isThreadSpecified()) {
2390    if (NewVD->hasLocalStorage())
2391      Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
2392    else if (!Context.Target.isTLSSupported())
2393      Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
2394    else
2395      NewVD->setThreadSpecified(true);
2396  }
2397
2398  // Set the lexical context. If the declarator has a C++ scope specifier, the
2399  // lexical context will be different from the semantic context.
2400  NewVD->setLexicalDeclContext(CurContext);
2401
2402  // Handle attributes prior to checking for duplicates in MergeVarDecl
2403  ProcessDeclAttributes(S, NewVD, D);
2404
2405  // Handle GNU asm-label extension (encoded as an attribute).
2406  if (Expr *E = (Expr*) D.getAsmLabel()) {
2407    // The parser guarantees this is a string.
2408    StringLiteral *SE = cast<StringLiteral>(E);
2409    NewVD->addAttr(::new (Context) AsmLabelAttr(std::string(SE->getStrData(),
2410                                                        SE->getByteLength())));
2411  }
2412
2413  // Don't consider existing declarations that are in a different
2414  // scope and are out-of-semantic-context declarations (if the new
2415  // declaration has linkage).
2416  FilterLookupForScope(*this, Previous, DC, S, NewVD->hasLinkage());
2417
2418  // Merge the decl with the existing one if appropriate.
2419  if (!Previous.empty()) {
2420    if (Previous.isSingleResult() &&
2421        isa<FieldDecl>(Previous.getFoundDecl()) &&
2422        D.getCXXScopeSpec().isSet()) {
2423      // The user tried to define a non-static data member
2424      // out-of-line (C++ [dcl.meaning]p1).
2425      Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
2426        << D.getCXXScopeSpec().getRange();
2427      Previous.clear();
2428      NewVD->setInvalidDecl();
2429    }
2430  } else if (D.getCXXScopeSpec().isSet()) {
2431    // No previous declaration in the qualifying scope.
2432    Diag(D.getIdentifierLoc(), diag::err_no_member)
2433      << Name << computeDeclContext(D.getCXXScopeSpec(), true)
2434      << D.getCXXScopeSpec().getRange();
2435    NewVD->setInvalidDecl();
2436  }
2437
2438  CheckVariableDeclaration(NewVD, Previous, Redeclaration);
2439
2440  // This is an explicit specialization of a static data member. Check it.
2441  if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
2442      CheckMemberSpecialization(NewVD, Previous))
2443    NewVD->setInvalidDecl();
2444
2445  // attributes declared post-definition are currently ignored
2446  if (Previous.isSingleResult()) {
2447    const VarDecl *Def = 0;
2448    VarDecl *PrevDecl = dyn_cast<VarDecl>(Previous.getFoundDecl());
2449    if (PrevDecl && PrevDecl->getDefinition(Def) && D.hasAttributes()) {
2450      Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
2451      Diag(Def->getLocation(), diag::note_previous_definition);
2452    }
2453  }
2454
2455  // If this is a locally-scoped extern C variable, update the map of
2456  // such variables.
2457  if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
2458      !NewVD->isInvalidDecl())
2459    RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
2460
2461  return NewVD;
2462}
2463
2464/// \brief Perform semantic checking on a newly-created variable
2465/// declaration.
2466///
2467/// This routine performs all of the type-checking required for a
2468/// variable declaration once it has been built. It is used both to
2469/// check variables after they have been parsed and their declarators
2470/// have been translated into a declaration, and to check variables
2471/// that have been instantiated from a template.
2472///
2473/// Sets NewVD->isInvalidDecl() if an error was encountered.
2474void Sema::CheckVariableDeclaration(VarDecl *NewVD,
2475                                    LookupResult &Previous,
2476                                    bool &Redeclaration) {
2477  // If the decl is already known invalid, don't check it.
2478  if (NewVD->isInvalidDecl())
2479    return;
2480
2481  QualType T = NewVD->getType();
2482
2483  if (T->isObjCInterfaceType()) {
2484    Diag(NewVD->getLocation(), diag::err_statically_allocated_object);
2485    return NewVD->setInvalidDecl();
2486  }
2487
2488  // The variable can not have an abstract class type.
2489  if (RequireNonAbstractType(NewVD->getLocation(), T,
2490                             diag::err_abstract_type_in_decl,
2491                             AbstractVariableType))
2492    return NewVD->setInvalidDecl();
2493
2494  // Emit an error if an address space was applied to decl with local storage.
2495  // This includes arrays of objects with address space qualifiers, but not
2496  // automatic variables that point to other address spaces.
2497  // ISO/IEC TR 18037 S5.1.2
2498  if (NewVD->hasLocalStorage() && (T.getAddressSpace() != 0)) {
2499    Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
2500    return NewVD->setInvalidDecl();
2501  }
2502
2503  if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
2504      && !NewVD->hasAttr<BlocksAttr>())
2505    Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
2506
2507  bool isVM = T->isVariablyModifiedType();
2508  if (isVM || NewVD->hasAttr<CleanupAttr>() ||
2509      NewVD->hasAttr<BlocksAttr>())
2510    CurFunctionNeedsScopeChecking = true;
2511
2512  if ((isVM && NewVD->hasLinkage()) ||
2513      (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
2514    bool SizeIsNegative;
2515    QualType FixedTy =
2516        TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
2517
2518    if (FixedTy.isNull() && T->isVariableArrayType()) {
2519      const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
2520      // FIXME: This won't give the correct result for
2521      // int a[10][n];
2522      SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
2523
2524      if (NewVD->isFileVarDecl())
2525        Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
2526        << SizeRange;
2527      else if (NewVD->getStorageClass() == VarDecl::Static)
2528        Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
2529        << SizeRange;
2530      else
2531        Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
2532        << SizeRange;
2533      return NewVD->setInvalidDecl();
2534    }
2535
2536    if (FixedTy.isNull()) {
2537      if (NewVD->isFileVarDecl())
2538        Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
2539      else
2540        Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
2541      return NewVD->setInvalidDecl();
2542    }
2543
2544    Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
2545    NewVD->setType(FixedTy);
2546  }
2547
2548  if (Previous.empty() && NewVD->isExternC()) {
2549    // Since we did not find anything by this name and we're declaring
2550    // an extern "C" variable, look for a non-visible extern "C"
2551    // declaration with the same name.
2552    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
2553      = LocallyScopedExternalDecls.find(NewVD->getDeclName());
2554    if (Pos != LocallyScopedExternalDecls.end())
2555      Previous.addDecl(Pos->second);
2556  }
2557
2558  if (T->isVoidType() && !NewVD->hasExternalStorage()) {
2559    Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
2560      << T;
2561    return NewVD->setInvalidDecl();
2562  }
2563
2564  if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
2565    Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
2566    return NewVD->setInvalidDecl();
2567  }
2568
2569  if (isVM && NewVD->hasAttr<BlocksAttr>()) {
2570    Diag(NewVD->getLocation(), diag::err_block_on_vm);
2571    return NewVD->setInvalidDecl();
2572  }
2573
2574  if (!Previous.empty()) {
2575    Redeclaration = true;
2576    MergeVarDecl(NewVD, Previous);
2577  }
2578}
2579
2580/// \brief Data used with FindOverriddenMethod
2581struct FindOverriddenMethodData {
2582  Sema *S;
2583  CXXMethodDecl *Method;
2584};
2585
2586/// \brief Member lookup function that determines whether a given C++
2587/// method overrides a method in a base class, to be used with
2588/// CXXRecordDecl::lookupInBases().
2589static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
2590                                 CXXBasePath &Path,
2591                                 void *UserData) {
2592  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
2593
2594  FindOverriddenMethodData *Data
2595    = reinterpret_cast<FindOverriddenMethodData*>(UserData);
2596
2597  DeclarationName Name = Data->Method->getDeclName();
2598
2599  // FIXME: Do we care about other names here too?
2600  if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
2601    // We really want to find the base class constructor here.
2602    QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
2603    CanQualType CT = Data->S->Context.getCanonicalType(T);
2604
2605    Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
2606  }
2607
2608  for (Path.Decls = BaseRecord->lookup(Name);
2609       Path.Decls.first != Path.Decls.second;
2610       ++Path.Decls.first) {
2611    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*Path.Decls.first)) {
2612      if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD))
2613        return true;
2614    }
2615  }
2616
2617  return false;
2618}
2619
2620/// AddOverriddenMethods - See if a method overrides any in the base classes,
2621/// and if so, check that it's a valid override and remember it.
2622void Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
2623  // Look for virtual methods in base classes that this method might override.
2624  CXXBasePaths Paths;
2625  FindOverriddenMethodData Data;
2626  Data.Method = MD;
2627  Data.S = this;
2628  if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
2629    for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
2630         E = Paths.found_decls_end(); I != E; ++I) {
2631      if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
2632        if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
2633            !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
2634            !CheckOverridingFunctionAttributes(MD, OldMD))
2635          MD->addOverriddenMethod(OldMD);
2636      }
2637    }
2638  }
2639}
2640
2641NamedDecl*
2642Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2643                              QualType R, DeclaratorInfo *DInfo,
2644                              LookupResult &Previous,
2645                              MultiTemplateParamsArg TemplateParamLists,
2646                              bool IsFunctionDefinition, bool &Redeclaration) {
2647  assert(R.getTypePtr()->isFunctionType());
2648
2649  DeclarationName Name = GetNameForDeclarator(D);
2650  FunctionDecl::StorageClass SC = FunctionDecl::None;
2651  switch (D.getDeclSpec().getStorageClassSpec()) {
2652  default: assert(0 && "Unknown storage class!");
2653  case DeclSpec::SCS_auto:
2654  case DeclSpec::SCS_register:
2655  case DeclSpec::SCS_mutable:
2656    Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2657         diag::err_typecheck_sclass_func);
2658    D.setInvalidType();
2659    break;
2660  case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
2661  case DeclSpec::SCS_extern:      SC = FunctionDecl::Extern; break;
2662  case DeclSpec::SCS_static: {
2663    if (CurContext->getLookupContext()->isFunctionOrMethod()) {
2664      // C99 6.7.1p5:
2665      //   The declaration of an identifier for a function that has
2666      //   block scope shall have no explicit storage-class specifier
2667      //   other than extern
2668      // See also (C++ [dcl.stc]p4).
2669      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2670           diag::err_static_block_func);
2671      SC = FunctionDecl::None;
2672    } else
2673      SC = FunctionDecl::Static;
2674    break;
2675  }
2676  case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
2677  }
2678
2679  if (D.getDeclSpec().isThreadSpecified())
2680    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2681
2682  bool isFriend = D.getDeclSpec().isFriendSpecified();
2683  bool isInline = D.getDeclSpec().isInlineSpecified();
2684  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
2685  bool isExplicit = D.getDeclSpec().isExplicitSpecified();
2686
2687  // Check that the return type is not an abstract class type.
2688  // For record types, this is done by the AbstractClassUsageDiagnoser once
2689  // the class has been completely parsed.
2690  if (!DC->isRecord() &&
2691      RequireNonAbstractType(D.getIdentifierLoc(),
2692                             R->getAs<FunctionType>()->getResultType(),
2693                             diag::err_abstract_type_in_decl,
2694                             AbstractReturnType))
2695    D.setInvalidType();
2696
2697  // Do not allow returning a objc interface by-value.
2698  if (R->getAs<FunctionType>()->getResultType()->isObjCInterfaceType()) {
2699    Diag(D.getIdentifierLoc(),
2700         diag::err_object_cannot_be_passed_returned_by_value) << 0
2701      << R->getAs<FunctionType>()->getResultType();
2702    D.setInvalidType();
2703  }
2704
2705  bool isVirtualOkay = false;
2706  FunctionDecl *NewFD;
2707
2708  if (isFriend) {
2709    // C++ [class.friend]p5
2710    //   A function can be defined in a friend declaration of a
2711    //   class . . . . Such a function is implicitly inline.
2712    isInline |= IsFunctionDefinition;
2713  }
2714
2715  if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
2716    // This is a C++ constructor declaration.
2717    assert(DC->isRecord() &&
2718           "Constructors can only be declared in a member context");
2719
2720    R = CheckConstructorDeclarator(D, R, SC);
2721
2722    // Create the new declaration
2723    NewFD = CXXConstructorDecl::Create(Context,
2724                                       cast<CXXRecordDecl>(DC),
2725                                       D.getIdentifierLoc(), Name, R, DInfo,
2726                                       isExplicit, isInline,
2727                                       /*isImplicitlyDeclared=*/false);
2728  } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
2729    // This is a C++ destructor declaration.
2730    if (DC->isRecord()) {
2731      R = CheckDestructorDeclarator(D, SC);
2732
2733      NewFD = CXXDestructorDecl::Create(Context,
2734                                        cast<CXXRecordDecl>(DC),
2735                                        D.getIdentifierLoc(), Name, R,
2736                                        isInline,
2737                                        /*isImplicitlyDeclared=*/false);
2738
2739      isVirtualOkay = true;
2740    } else {
2741      Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
2742
2743      // Create a FunctionDecl to satisfy the function definition parsing
2744      // code path.
2745      NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
2746                                   Name, R, DInfo, SC, isInline,
2747                                   /*hasPrototype=*/true);
2748      D.setInvalidType();
2749    }
2750  } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2751    if (!DC->isRecord()) {
2752      Diag(D.getIdentifierLoc(),
2753           diag::err_conv_function_not_member);
2754      return 0;
2755    }
2756
2757    CheckConversionDeclarator(D, R, SC);
2758    NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
2759                                      D.getIdentifierLoc(), Name, R, DInfo,
2760                                      isInline, isExplicit);
2761
2762    isVirtualOkay = true;
2763  } else if (DC->isRecord()) {
2764    // If the of the function is the same as the name of the record, then this
2765    // must be an invalid constructor that has a return type.
2766    // (The parser checks for a return type and makes the declarator a
2767    // constructor if it has no return type).
2768    // must have an invalid constructor that has a return type
2769    if (Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
2770      Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
2771        << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2772        << SourceRange(D.getIdentifierLoc());
2773      return 0;
2774    }
2775
2776    bool isStatic = SC == FunctionDecl::Static;
2777
2778    // [class.free]p1:
2779    // Any allocation function for a class T is a static member
2780    // (even if not explicitly declared static).
2781    if (Name.getCXXOverloadedOperator() == OO_New ||
2782        Name.getCXXOverloadedOperator() == OO_Array_New)
2783      isStatic = true;
2784
2785    // [class.free]p6 Any deallocation function for a class X is a static member
2786    // (even if not explicitly declared static).
2787    if (Name.getCXXOverloadedOperator() == OO_Delete ||
2788        Name.getCXXOverloadedOperator() == OO_Array_Delete)
2789      isStatic = true;
2790
2791    // This is a C++ method declaration.
2792    NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
2793                                  D.getIdentifierLoc(), Name, R, DInfo,
2794                                  isStatic, isInline);
2795
2796    isVirtualOkay = !isStatic;
2797  } else {
2798    // Determine whether the function was written with a
2799    // prototype. This true when:
2800    //   - we're in C++ (where every function has a prototype),
2801    //   - there is a prototype in the declarator, or
2802    //   - the type R of the function is some kind of typedef or other reference
2803    //     to a type name (which eventually refers to a function type).
2804    bool HasPrototype =
2805       getLangOptions().CPlusPlus ||
2806       (D.getNumTypeObjects() && D.getTypeObject(0).Fun.hasPrototype) ||
2807       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
2808
2809    NewFD = FunctionDecl::Create(Context, DC,
2810                                 D.getIdentifierLoc(),
2811                                 Name, R, DInfo, SC, isInline, HasPrototype);
2812  }
2813
2814  if (D.isInvalidType())
2815    NewFD->setInvalidDecl();
2816
2817  // Set the lexical context. If the declarator has a C++
2818  // scope specifier, or is the object of a friend declaration, the
2819  // lexical context will be different from the semantic context.
2820  NewFD->setLexicalDeclContext(CurContext);
2821
2822  // Match up the template parameter lists with the scope specifier, then
2823  // determine whether we have a template or a template specialization.
2824  FunctionTemplateDecl *FunctionTemplate = 0;
2825  bool isExplicitSpecialization = false;
2826  bool isFunctionTemplateSpecialization = false;
2827  if (TemplateParameterList *TemplateParams
2828        = MatchTemplateParametersToScopeSpecifier(
2829                                  D.getDeclSpec().getSourceRange().getBegin(),
2830                                  D.getCXXScopeSpec(),
2831                           (TemplateParameterList**)TemplateParamLists.get(),
2832                                                  TemplateParamLists.size(),
2833                                                  isExplicitSpecialization)) {
2834    if (TemplateParams->size() > 0) {
2835      // This is a function template
2836
2837      // Check that we can declare a template here.
2838      if (CheckTemplateDeclScope(S, TemplateParams))
2839        return 0;
2840
2841      FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
2842                                                      NewFD->getLocation(),
2843                                                      Name, TemplateParams,
2844                                                      NewFD);
2845      FunctionTemplate->setLexicalDeclContext(CurContext);
2846      NewFD->setDescribedFunctionTemplate(FunctionTemplate);
2847    } else {
2848      // This is a function template specialization.
2849      isFunctionTemplateSpecialization = true;
2850    }
2851
2852    // FIXME: Free this memory properly.
2853    TemplateParamLists.release();
2854  }
2855
2856  // C++ [dcl.fct.spec]p5:
2857  //   The virtual specifier shall only be used in declarations of
2858  //   nonstatic class member functions that appear within a
2859  //   member-specification of a class declaration; see 10.3.
2860  //
2861  if (isVirtual && !NewFD->isInvalidDecl()) {
2862    if (!isVirtualOkay) {
2863       Diag(D.getDeclSpec().getVirtualSpecLoc(),
2864           diag::err_virtual_non_function);
2865    } else if (!CurContext->isRecord()) {
2866      // 'virtual' was specified outside of the class.
2867      Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_out_of_class)
2868        << CodeModificationHint::CreateRemoval(
2869                             SourceRange(D.getDeclSpec().getVirtualSpecLoc()));
2870    } else {
2871      // Okay: Add virtual to the method.
2872      cast<CXXMethodDecl>(NewFD)->setVirtualAsWritten(true);
2873      CXXRecordDecl *CurClass = cast<CXXRecordDecl>(DC);
2874      CurClass->setAggregate(false);
2875      CurClass->setPOD(false);
2876      CurClass->setEmpty(false);
2877      CurClass->setPolymorphic(true);
2878      CurClass->setHasTrivialConstructor(false);
2879      CurClass->setHasTrivialCopyConstructor(false);
2880      CurClass->setHasTrivialCopyAssignment(false);
2881    }
2882  }
2883
2884  // Filter out previous declarations that don't match the scope.
2885  FilterLookupForScope(*this, Previous, DC, S, NewFD->hasLinkage());
2886
2887  if (isFriend) {
2888    // DC is the namespace in which the function is being declared.
2889    assert((DC->isFileContext() || !Previous.empty()) &&
2890           "previously-undeclared friend function being created "
2891           "in a non-namespace context");
2892
2893    if (FunctionTemplate) {
2894      FunctionTemplate->setObjectOfFriendDecl(
2895                                   /* PreviouslyDeclared= */ !Previous.empty());
2896      FunctionTemplate->setAccess(AS_public);
2897    }
2898    else
2899      NewFD->setObjectOfFriendDecl(/* PreviouslyDeclared= */ !Previous.empty());
2900
2901    NewFD->setAccess(AS_public);
2902  }
2903
2904  if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
2905    AddOverriddenMethods(cast<CXXRecordDecl>(DC), NewMD);
2906
2907  if (SC == FunctionDecl::Static && isa<CXXMethodDecl>(NewFD) &&
2908      !CurContext->isRecord()) {
2909    // C++ [class.static]p1:
2910    //   A data or function member of a class may be declared static
2911    //   in a class definition, in which case it is a static member of
2912    //   the class.
2913
2914    // Complain about the 'static' specifier if it's on an out-of-line
2915    // member function definition.
2916    Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2917         diag::err_static_out_of_line)
2918      << CodeModificationHint::CreateRemoval(
2919                      SourceRange(D.getDeclSpec().getStorageClassSpecLoc()));
2920  }
2921
2922  // Handle GNU asm-label extension (encoded as an attribute).
2923  if (Expr *E = (Expr*) D.getAsmLabel()) {
2924    // The parser guarantees this is a string.
2925    StringLiteral *SE = cast<StringLiteral>(E);
2926    NewFD->addAttr(::new (Context) AsmLabelAttr(std::string(SE->getStrData(),
2927                                                        SE->getByteLength())));
2928  }
2929
2930  // Copy the parameter declarations from the declarator D to the function
2931  // declaration NewFD, if they are available.  First scavenge them into Params.
2932  llvm::SmallVector<ParmVarDecl*, 16> Params;
2933  if (D.getNumTypeObjects() > 0) {
2934    DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2935
2936    // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
2937    // function that takes no arguments, not a function that takes a
2938    // single void argument.
2939    // We let through "const void" here because Sema::GetTypeForDeclarator
2940    // already checks for that case.
2941    if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2942        FTI.ArgInfo[0].Param &&
2943        FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()) {
2944      // Empty arg list, don't push any params.
2945      ParmVarDecl *Param = FTI.ArgInfo[0].Param.getAs<ParmVarDecl>();
2946
2947      // In C++, the empty parameter-type-list must be spelled "void"; a
2948      // typedef of void is not permitted.
2949      if (getLangOptions().CPlusPlus &&
2950          Param->getType().getUnqualifiedType() != Context.VoidTy)
2951        Diag(Param->getLocation(), diag::err_param_typedef_of_void);
2952      // FIXME: Leaks decl?
2953    } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
2954      for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
2955        ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
2956        assert(Param->getDeclContext() != NewFD && "Was set before ?");
2957        Param->setDeclContext(NewFD);
2958        Params.push_back(Param);
2959      }
2960    }
2961
2962  } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
2963    // When we're declaring a function with a typedef, typeof, etc as in the
2964    // following example, we'll need to synthesize (unnamed)
2965    // parameters for use in the declaration.
2966    //
2967    // @code
2968    // typedef void fn(int);
2969    // fn f;
2970    // @endcode
2971
2972    // Synthesize a parameter for each argument type.
2973    for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
2974         AE = FT->arg_type_end(); AI != AE; ++AI) {
2975      ParmVarDecl *Param = ParmVarDecl::Create(Context, DC,
2976                                               SourceLocation(), 0,
2977                                               *AI, /*DInfo=*/0,
2978                                               VarDecl::None, 0);
2979      Param->setImplicit();
2980      Params.push_back(Param);
2981    }
2982  } else {
2983    assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
2984           "Should not need args for typedef of non-prototype fn");
2985  }
2986  // Finally, we know we have the right number of parameters, install them.
2987  NewFD->setParams(Context, Params.data(), Params.size());
2988
2989  // If the declarator is a template-id, translate the parser's template
2990  // argument list into our AST format.
2991  bool HasExplicitTemplateArgs = false;
2992  TemplateArgumentListInfo TemplateArgs;
2993  if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
2994    TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
2995    TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
2996    TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
2997    ASTTemplateArgsPtr TemplateArgsPtr(*this,
2998                                       TemplateId->getTemplateArgs(),
2999                                       TemplateId->NumArgs);
3000    translateTemplateArguments(TemplateArgsPtr,
3001                               TemplateArgs);
3002    TemplateArgsPtr.release();
3003
3004    HasExplicitTemplateArgs = true;
3005
3006    if (FunctionTemplate) {
3007      // FIXME: Diagnose function template with explicit template
3008      // arguments.
3009      HasExplicitTemplateArgs = false;
3010    } else if (!isFunctionTemplateSpecialization &&
3011               !D.getDeclSpec().isFriendSpecified()) {
3012      // We have encountered something that the user meant to be a
3013      // specialization (because it has explicitly-specified template
3014      // arguments) but that was not introduced with a "template<>" (or had
3015      // too few of them).
3016      Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
3017        << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
3018        << CodeModificationHint::CreateInsertion(
3019                                   D.getDeclSpec().getSourceRange().getBegin(),
3020                                                 "template<> ");
3021      isFunctionTemplateSpecialization = true;
3022    }
3023  }
3024
3025  if (isFunctionTemplateSpecialization) {
3026      if (CheckFunctionTemplateSpecialization(NewFD,
3027                               (HasExplicitTemplateArgs ? &TemplateArgs : 0),
3028                                              Previous))
3029        NewFD->setInvalidDecl();
3030  } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD) &&
3031             CheckMemberSpecialization(NewFD, Previous))
3032    NewFD->setInvalidDecl();
3033
3034  // Perform semantic checking on the function declaration.
3035  bool OverloadableAttrRequired = false; // FIXME: HACK!
3036  CheckFunctionDeclaration(NewFD, Previous, isExplicitSpecialization,
3037                           Redeclaration, /*FIXME:*/OverloadableAttrRequired);
3038
3039  assert((NewFD->isInvalidDecl() || !Redeclaration ||
3040          Previous.getResultKind() != LookupResult::FoundOverloaded) &&
3041         "previous declaration set still overloaded");
3042
3043  // If we have a function template, check the template parameter
3044  // list. This will check and merge default template arguments.
3045  if (FunctionTemplate) {
3046    FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDeclaration();
3047    CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
3048                      PrevTemplate? PrevTemplate->getTemplateParameters() : 0,
3049             D.getDeclSpec().isFriendSpecified()? TPC_FriendFunctionTemplate
3050                                                : TPC_FunctionTemplate);
3051  }
3052
3053  if (D.getCXXScopeSpec().isSet() && !NewFD->isInvalidDecl()) {
3054    // An out-of-line member function declaration must also be a
3055    // definition (C++ [dcl.meaning]p1).
3056    // Note that this is not the case for explicit specializations of
3057    // function templates or member functions of class templates, per
3058    // C++ [temp.expl.spec]p2.
3059    if (!IsFunctionDefinition && !isFriend &&
3060        !isFunctionTemplateSpecialization && !isExplicitSpecialization) {
3061      Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
3062        << D.getCXXScopeSpec().getRange();
3063      NewFD->setInvalidDecl();
3064    } else if (!Redeclaration) {
3065      // The user tried to provide an out-of-line definition for a
3066      // function that is a member of a class or namespace, but there
3067      // was no such member function declared (C++ [class.mfct]p2,
3068      // C++ [namespace.memdef]p2). For example:
3069      //
3070      // class X {
3071      //   void f() const;
3072      // };
3073      //
3074      // void X::f() { } // ill-formed
3075      //
3076      // Complain about this problem, and attempt to suggest close
3077      // matches (e.g., those that differ only in cv-qualifiers and
3078      // whether the parameter types are references).
3079      Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
3080        << Name << DC << D.getCXXScopeSpec().getRange();
3081      NewFD->setInvalidDecl();
3082
3083      LookupResult Prev(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
3084                        ForRedeclaration);
3085      LookupQualifiedName(Prev, DC);
3086      assert(!Prev.isAmbiguous() &&
3087             "Cannot have an ambiguity in previous-declaration lookup");
3088      for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
3089           Func != FuncEnd; ++Func) {
3090        if (isa<FunctionDecl>(*Func) &&
3091            isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD))
3092          Diag((*Func)->getLocation(), diag::note_member_def_close_match);
3093      }
3094    }
3095  }
3096
3097  // Handle attributes. We need to have merged decls when handling attributes
3098  // (for example to check for conflicts, etc).
3099  // FIXME: This needs to happen before we merge declarations. Then,
3100  // let attribute merging cope with attribute conflicts.
3101  ProcessDeclAttributes(S, NewFD, D);
3102
3103  // attributes declared post-definition are currently ignored
3104  if (Redeclaration && Previous.isSingleResult()) {
3105    const FunctionDecl *Def;
3106    FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
3107    if (PrevFD && PrevFD->getBody(Def) && D.hasAttributes()) {
3108      Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
3109      Diag(Def->getLocation(), diag::note_previous_definition);
3110    }
3111  }
3112
3113  AddKnownFunctionAttributes(NewFD);
3114
3115  if (OverloadableAttrRequired && !NewFD->getAttr<OverloadableAttr>()) {
3116    // If a function name is overloadable in C, then every function
3117    // with that name must be marked "overloadable".
3118    Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
3119      << Redeclaration << NewFD;
3120    if (!Previous.empty())
3121      Diag(Previous.getRepresentativeDecl()->getLocation(),
3122           diag::note_attribute_overloadable_prev_overload);
3123    NewFD->addAttr(::new (Context) OverloadableAttr());
3124  }
3125
3126  // If this is a locally-scoped extern C function, update the
3127  // map of such names.
3128  if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
3129      && !NewFD->isInvalidDecl())
3130    RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
3131
3132  // Set this FunctionDecl's range up to the right paren.
3133  NewFD->setLocEnd(D.getSourceRange().getEnd());
3134
3135  if (FunctionTemplate && NewFD->isInvalidDecl())
3136    FunctionTemplate->setInvalidDecl();
3137
3138  if (FunctionTemplate)
3139    return FunctionTemplate;
3140
3141  return NewFD;
3142}
3143
3144/// \brief Perform semantic checking of a new function declaration.
3145///
3146/// Performs semantic analysis of the new function declaration
3147/// NewFD. This routine performs all semantic checking that does not
3148/// require the actual declarator involved in the declaration, and is
3149/// used both for the declaration of functions as they are parsed
3150/// (called via ActOnDeclarator) and for the declaration of functions
3151/// that have been instantiated via C++ template instantiation (called
3152/// via InstantiateDecl).
3153///
3154/// \param IsExplicitSpecialiation whether this new function declaration is
3155/// an explicit specialization of the previous declaration.
3156///
3157/// This sets NewFD->isInvalidDecl() to true if there was an error.
3158void Sema::CheckFunctionDeclaration(FunctionDecl *NewFD,
3159                                    LookupResult &Previous,
3160                                    bool IsExplicitSpecialization,
3161                                    bool &Redeclaration,
3162                                    bool &OverloadableAttrRequired) {
3163  // If NewFD is already known erroneous, don't do any of this checking.
3164  if (NewFD->isInvalidDecl())
3165    return;
3166
3167  if (NewFD->getResultType()->isVariablyModifiedType()) {
3168    // Functions returning a variably modified type violate C99 6.7.5.2p2
3169    // because all functions have linkage.
3170    Diag(NewFD->getLocation(), diag::err_vm_func_decl);
3171    return NewFD->setInvalidDecl();
3172  }
3173
3174  if (NewFD->isMain())
3175    CheckMain(NewFD);
3176
3177  // Check for a previous declaration of this name.
3178  if (Previous.empty() && NewFD->isExternC()) {
3179    // Since we did not find anything by this name and we're declaring
3180    // an extern "C" function, look for a non-visible extern "C"
3181    // declaration with the same name.
3182    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
3183      = LocallyScopedExternalDecls.find(NewFD->getDeclName());
3184    if (Pos != LocallyScopedExternalDecls.end())
3185      Previous.addDecl(Pos->second);
3186  }
3187
3188  // Merge or overload the declaration with an existing declaration of
3189  // the same name, if appropriate.
3190  if (!Previous.empty()) {
3191    // Determine whether NewFD is an overload of PrevDecl or
3192    // a declaration that requires merging. If it's an overload,
3193    // there's no more work to do here; we'll just add the new
3194    // function to the scope.
3195
3196    if (!getLangOptions().CPlusPlus &&
3197        AllowOverloadingOfFunction(Previous, Context)) {
3198      OverloadableAttrRequired = true;
3199
3200      // Functions marked "overloadable" must have a prototype (that
3201      // we can't get through declaration merging).
3202      if (!NewFD->getType()->getAs<FunctionProtoType>()) {
3203        Diag(NewFD->getLocation(), diag::err_attribute_overloadable_no_prototype)
3204          << NewFD;
3205        Redeclaration = true;
3206
3207        // Turn this into a variadic function with no parameters.
3208        QualType R = Context.getFunctionType(
3209                       NewFD->getType()->getAs<FunctionType>()->getResultType(),
3210                       0, 0, true, 0);
3211        NewFD->setType(R);
3212        return NewFD->setInvalidDecl();
3213      }
3214    }
3215
3216    NamedDecl *OldDecl = 0;
3217    if (!Previous.empty()) {
3218      if (!AllowOverloadingOfFunction(Previous, Context)) {
3219        Redeclaration = true;
3220        OldDecl = Previous.getFoundDecl();
3221      } else if (!IsOverload(NewFD, Previous, OldDecl)) {
3222        if (!isUsingDecl(OldDecl))
3223          Redeclaration = true;
3224      }
3225    }
3226
3227    if (Redeclaration) {
3228      // NewFD and OldDecl represent declarations that need to be
3229      // merged.
3230      if (MergeFunctionDecl(NewFD, OldDecl))
3231        return NewFD->setInvalidDecl();
3232
3233      Previous.clear();
3234      Previous.addDecl(OldDecl);
3235
3236      if (FunctionTemplateDecl *OldTemplateDecl
3237                                    = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
3238        NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
3239        FunctionTemplateDecl *NewTemplateDecl
3240          = NewFD->getDescribedFunctionTemplate();
3241        assert(NewTemplateDecl && "Template/non-template mismatch");
3242        if (CXXMethodDecl *Method
3243              = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
3244          Method->setAccess(OldTemplateDecl->getAccess());
3245          NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
3246        }
3247
3248        // If this is an explicit specialization of a member that is a function
3249        // template, mark it as a member specialization.
3250        if (IsExplicitSpecialization &&
3251            NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
3252          NewTemplateDecl->setMemberSpecialization();
3253          assert(OldTemplateDecl->isMemberSpecialization());
3254        }
3255      } else {
3256        if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
3257          NewFD->setAccess(OldDecl->getAccess());
3258        NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
3259      }
3260    }
3261  }
3262
3263  // Semantic checking for this function declaration (in isolation).
3264  if (getLangOptions().CPlusPlus) {
3265    // C++-specific checks.
3266    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
3267      CheckConstructor(Constructor);
3268    } else if (CXXDestructorDecl *Destructor =
3269                dyn_cast<CXXDestructorDecl>(NewFD)) {
3270      CXXRecordDecl *Record = Destructor->getParent();
3271      QualType ClassType = Context.getTypeDeclType(Record);
3272
3273      // FIXME: Shouldn't we be able to perform thisc heck even when the class
3274      // type is dependent? Both gcc and edg can handle that.
3275      if (!ClassType->isDependentType()) {
3276        DeclarationName Name
3277          = Context.DeclarationNames.getCXXDestructorName(
3278                                        Context.getCanonicalType(ClassType));
3279        if (NewFD->getDeclName() != Name) {
3280          Diag(NewFD->getLocation(), diag::err_destructor_name);
3281          return NewFD->setInvalidDecl();
3282        }
3283
3284        CheckDestructor(Destructor);
3285      }
3286
3287      Record->setUserDeclaredDestructor(true);
3288      // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
3289      // user-defined destructor.
3290      Record->setPOD(false);
3291
3292      // C++ [class.dtor]p3: A destructor is trivial if it is an implicitly-
3293      // declared destructor.
3294      // FIXME: C++0x: don't do this for "= default" destructors
3295      Record->setHasTrivialDestructor(false);
3296    } else if (CXXConversionDecl *Conversion
3297               = dyn_cast<CXXConversionDecl>(NewFD))
3298      ActOnConversionDeclarator(Conversion);
3299
3300    // Extra checking for C++ overloaded operators (C++ [over.oper]).
3301    if (NewFD->isOverloadedOperator() &&
3302        CheckOverloadedOperatorDeclaration(NewFD))
3303      return NewFD->setInvalidDecl();
3304
3305    // In C++, check default arguments now that we have merged decls. Unless
3306    // the lexical context is the class, because in this case this is done
3307    // during delayed parsing anyway.
3308    if (!CurContext->isRecord())
3309      CheckCXXDefaultArguments(NewFD);
3310  }
3311}
3312
3313void Sema::CheckMain(FunctionDecl* FD) {
3314  // C++ [basic.start.main]p3:  A program that declares main to be inline
3315  //   or static is ill-formed.
3316  // C99 6.7.4p4:  In a hosted environment, the inline function specifier
3317  //   shall not appear in a declaration of main.
3318  // static main is not an error under C99, but we should warn about it.
3319  bool isInline = FD->isInlineSpecified();
3320  bool isStatic = FD->getStorageClass() == FunctionDecl::Static;
3321  if (isInline || isStatic) {
3322    unsigned diagID = diag::warn_unusual_main_decl;
3323    if (isInline || getLangOptions().CPlusPlus)
3324      diagID = diag::err_unusual_main_decl;
3325
3326    int which = isStatic + (isInline << 1) - 1;
3327    Diag(FD->getLocation(), diagID) << which;
3328  }
3329
3330  QualType T = FD->getType();
3331  assert(T->isFunctionType() && "function decl is not of function type");
3332  const FunctionType* FT = T->getAs<FunctionType>();
3333
3334  if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
3335    // TODO: add a replacement fixit to turn the return type into 'int'.
3336    Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
3337    FD->setInvalidDecl(true);
3338  }
3339
3340  // Treat protoless main() as nullary.
3341  if (isa<FunctionNoProtoType>(FT)) return;
3342
3343  const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
3344  unsigned nparams = FTP->getNumArgs();
3345  assert(FD->getNumParams() == nparams);
3346
3347  if (nparams > 3) {
3348    Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
3349    FD->setInvalidDecl(true);
3350    nparams = 3;
3351  }
3352
3353  // FIXME: a lot of the following diagnostics would be improved
3354  // if we had some location information about types.
3355
3356  QualType CharPP =
3357    Context.getPointerType(Context.getPointerType(Context.CharTy));
3358  QualType Expected[] = { Context.IntTy, CharPP, CharPP };
3359
3360  for (unsigned i = 0; i < nparams; ++i) {
3361    QualType AT = FTP->getArgType(i);
3362
3363    bool mismatch = true;
3364
3365    if (Context.hasSameUnqualifiedType(AT, Expected[i]))
3366      mismatch = false;
3367    else if (Expected[i] == CharPP) {
3368      // As an extension, the following forms are okay:
3369      //   char const **
3370      //   char const * const *
3371      //   char * const *
3372
3373      QualifierCollector qs;
3374      const PointerType* PT;
3375      if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
3376          (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
3377          (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
3378        qs.removeConst();
3379        mismatch = !qs.empty();
3380      }
3381    }
3382
3383    if (mismatch) {
3384      Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
3385      // TODO: suggest replacing given type with expected type
3386      FD->setInvalidDecl(true);
3387    }
3388  }
3389
3390  if (nparams == 1 && !FD->isInvalidDecl()) {
3391    Diag(FD->getLocation(), diag::warn_main_one_arg);
3392  }
3393}
3394
3395bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
3396  // FIXME: Need strict checking.  In C89, we need to check for
3397  // any assignment, increment, decrement, function-calls, or
3398  // commas outside of a sizeof.  In C99, it's the same list,
3399  // except that the aforementioned are allowed in unevaluated
3400  // expressions.  Everything else falls under the
3401  // "may accept other forms of constant expressions" exception.
3402  // (We never end up here for C++, so the constant expression
3403  // rules there don't matter.)
3404  if (Init->isConstantInitializer(Context))
3405    return false;
3406  Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
3407    << Init->getSourceRange();
3408  return true;
3409}
3410
3411void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init) {
3412  AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
3413}
3414
3415/// AddInitializerToDecl - Adds the initializer Init to the
3416/// declaration dcl. If DirectInit is true, this is C++ direct
3417/// initialization rather than copy initialization.
3418void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init, bool DirectInit) {
3419  Decl *RealDecl = dcl.getAs<Decl>();
3420  // If there is no declaration, there was an error parsing it.  Just ignore
3421  // the initializer.
3422  if (RealDecl == 0)
3423    return;
3424
3425  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
3426    // With declarators parsed the way they are, the parser cannot
3427    // distinguish between a normal initializer and a pure-specifier.
3428    // Thus this grotesque test.
3429    IntegerLiteral *IL;
3430    Expr *Init = static_cast<Expr *>(init.get());
3431    if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
3432        Context.getCanonicalType(IL->getType()) == Context.IntTy) {
3433      if (Method->isVirtualAsWritten()) {
3434        Method->setPure();
3435
3436        // A class is abstract if at least one function is pure virtual.
3437        cast<CXXRecordDecl>(CurContext)->setAbstract(true);
3438      } else if (!Method->isInvalidDecl()) {
3439        Diag(Method->getLocation(), diag::err_non_virtual_pure)
3440          << Method->getDeclName() << Init->getSourceRange();
3441        Method->setInvalidDecl();
3442      }
3443    } else {
3444      Diag(Method->getLocation(), diag::err_member_function_initialization)
3445        << Method->getDeclName() << Init->getSourceRange();
3446      Method->setInvalidDecl();
3447    }
3448    return;
3449  }
3450
3451  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3452  if (!VDecl) {
3453    if (getLangOptions().CPlusPlus &&
3454        RealDecl->getLexicalDeclContext()->isRecord() &&
3455        isa<NamedDecl>(RealDecl))
3456      Diag(RealDecl->getLocation(), diag::err_member_initialization)
3457        << cast<NamedDecl>(RealDecl)->getDeclName();
3458    else
3459      Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3460    RealDecl->setInvalidDecl();
3461    return;
3462  }
3463
3464  // A definition must end up with a complete type, which means it must be
3465  // complete with the restriction that an array type might be completed by the
3466  // initializer; note that later code assumes this restriction.
3467  QualType BaseDeclType = VDecl->getType();
3468  if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
3469    BaseDeclType = Array->getElementType();
3470  if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
3471                          diag::err_typecheck_decl_incomplete_type)) {
3472    RealDecl->setInvalidDecl();
3473    return;
3474  }
3475
3476  const VarDecl *Def = 0;
3477  if (VDecl->getDefinition(Def)) {
3478    Diag(VDecl->getLocation(), diag::err_redefinition)
3479      << VDecl->getDeclName();
3480    Diag(Def->getLocation(), diag::note_previous_definition);
3481    VDecl->setInvalidDecl();
3482    return;
3483  }
3484
3485  // Take ownership of the expression, now that we're sure we have somewhere
3486  // to put it.
3487  Expr *Init = init.takeAs<Expr>();
3488  assert(Init && "missing initializer");
3489
3490  // Get the decls type and save a reference for later, since
3491  // CheckInitializerTypes may change it.
3492  QualType DclT = VDecl->getType(), SavT = DclT;
3493  if (VDecl->isBlockVarDecl()) {
3494    if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
3495      Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
3496      VDecl->setInvalidDecl();
3497    } else if (!VDecl->isInvalidDecl()) {
3498      if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
3499                                VDecl->getDeclName(), DirectInit))
3500        VDecl->setInvalidDecl();
3501
3502      // C++ 3.6.2p2, allow dynamic initialization of static initializers.
3503      // Don't check invalid declarations to avoid emitting useless diagnostics.
3504      if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
3505        if (VDecl->getStorageClass() == VarDecl::Static) // C99 6.7.8p4.
3506          CheckForConstantInitializer(Init, DclT);
3507      }
3508    }
3509  } else if (VDecl->isStaticDataMember() &&
3510             VDecl->getLexicalDeclContext()->isRecord()) {
3511    // This is an in-class initialization for a static data member, e.g.,
3512    //
3513    // struct S {
3514    //   static const int value = 17;
3515    // };
3516
3517    // Attach the initializer
3518    VDecl->setInit(Context, Init);
3519
3520    // C++ [class.mem]p4:
3521    //   A member-declarator can contain a constant-initializer only
3522    //   if it declares a static member (9.4) of const integral or
3523    //   const enumeration type, see 9.4.2.
3524    QualType T = VDecl->getType();
3525    if (!T->isDependentType() &&
3526        (!Context.getCanonicalType(T).isConstQualified() ||
3527         !T->isIntegralType())) {
3528      Diag(VDecl->getLocation(), diag::err_member_initialization)
3529        << VDecl->getDeclName() << Init->getSourceRange();
3530      VDecl->setInvalidDecl();
3531    } else {
3532      // C++ [class.static.data]p4:
3533      //   If a static data member is of const integral or const
3534      //   enumeration type, its declaration in the class definition
3535      //   can specify a constant-initializer which shall be an
3536      //   integral constant expression (5.19).
3537      if (!Init->isTypeDependent() &&
3538          !Init->getType()->isIntegralType()) {
3539        // We have a non-dependent, non-integral or enumeration type.
3540        Diag(Init->getSourceRange().getBegin(),
3541             diag::err_in_class_initializer_non_integral_type)
3542          << Init->getType() << Init->getSourceRange();
3543        VDecl->setInvalidDecl();
3544      } else if (!Init->isTypeDependent() && !Init->isValueDependent()) {
3545        // Check whether the expression is a constant expression.
3546        llvm::APSInt Value;
3547        SourceLocation Loc;
3548        if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) {
3549          Diag(Loc, diag::err_in_class_initializer_non_constant)
3550            << Init->getSourceRange();
3551          VDecl->setInvalidDecl();
3552        } else if (!VDecl->getType()->isDependentType())
3553          ImpCastExprToType(Init, VDecl->getType(), CastExpr::CK_IntegralCast);
3554      }
3555    }
3556  } else if (VDecl->isFileVarDecl()) {
3557    if (VDecl->getStorageClass() == VarDecl::Extern)
3558      Diag(VDecl->getLocation(), diag::warn_extern_init);
3559    if (!VDecl->isInvalidDecl())
3560      if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
3561                                VDecl->getDeclName(), DirectInit))
3562        VDecl->setInvalidDecl();
3563
3564    // C++ 3.6.2p2, allow dynamic initialization of static initializers.
3565    // Don't check invalid declarations to avoid emitting useless diagnostics.
3566    if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
3567      // C99 6.7.8p4. All file scoped initializers need to be constant.
3568      CheckForConstantInitializer(Init, DclT);
3569    }
3570  }
3571  // If the type changed, it means we had an incomplete type that was
3572  // completed by the initializer. For example:
3573  //   int ary[] = { 1, 3, 5 };
3574  // "ary" transitions from a VariableArrayType to a ConstantArrayType.
3575  if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
3576    VDecl->setType(DclT);
3577    Init->setType(DclT);
3578  }
3579
3580  Init = MaybeCreateCXXExprWithTemporaries(Init,
3581                                           /*ShouldDestroyTemporaries=*/true);
3582  // Attach the initializer to the decl.
3583  VDecl->setInit(Context, Init);
3584
3585  // If the previous declaration of VDecl was a tentative definition,
3586  // remove it from the set of tentative definitions.
3587  if (VDecl->getPreviousDeclaration() &&
3588      VDecl->getPreviousDeclaration()->isTentativeDefinition(Context)) {
3589    bool Deleted = TentativeDefinitions.erase(VDecl->getDeclName());
3590    assert(Deleted && "Unrecorded tentative definition?"); Deleted=Deleted;
3591  }
3592
3593  return;
3594}
3595
3596void Sema::ActOnUninitializedDecl(DeclPtrTy dcl,
3597                                  bool TypeContainsUndeducedAuto) {
3598  Decl *RealDecl = dcl.getAs<Decl>();
3599
3600  // If there is no declaration, there was an error parsing it. Just ignore it.
3601  if (RealDecl == 0)
3602    return;
3603
3604  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
3605    QualType Type = Var->getType();
3606
3607    // Record tentative definitions.
3608    if (Var->isTentativeDefinition(Context)) {
3609      std::pair<llvm::DenseMap<DeclarationName, VarDecl *>::iterator, bool>
3610        InsertPair =
3611           TentativeDefinitions.insert(std::make_pair(Var->getDeclName(), Var));
3612
3613      // Keep the latest definition in the map.  If we see 'int i; int i;' we
3614      // want the second one in the map.
3615      InsertPair.first->second = Var;
3616
3617      // However, for the list, we don't care about the order, just make sure
3618      // that there are no dupes for a given declaration name.
3619      if (InsertPair.second)
3620        TentativeDefinitionList.push_back(Var->getDeclName());
3621    }
3622
3623    // C++ [dcl.init.ref]p3:
3624    //   The initializer can be omitted for a reference only in a
3625    //   parameter declaration (8.3.5), in the declaration of a
3626    //   function return type, in the declaration of a class member
3627    //   within its class declaration (9.2), and where the extern
3628    //   specifier is explicitly used.
3629    if (Type->isReferenceType() && !Var->hasExternalStorage()) {
3630      Diag(Var->getLocation(), diag::err_reference_var_requires_init)
3631        << Var->getDeclName()
3632        << SourceRange(Var->getLocation(), Var->getLocation());
3633      Var->setInvalidDecl();
3634      return;
3635    }
3636
3637    // C++0x [dcl.spec.auto]p3
3638    if (TypeContainsUndeducedAuto) {
3639      Diag(Var->getLocation(), diag::err_auto_var_requires_init)
3640        << Var->getDeclName() << Type;
3641      Var->setInvalidDecl();
3642      return;
3643    }
3644
3645    // An array without size is an incomplete type, and there are no special
3646    // rules in C++ to make such a definition acceptable.
3647    if (getLangOptions().CPlusPlus && Type->isIncompleteArrayType() &&
3648        !Var->hasExternalStorage()) {
3649      Diag(Var->getLocation(),
3650           diag::err_typecheck_incomplete_array_needs_initializer);
3651      Var->setInvalidDecl();
3652      return;
3653    }
3654
3655    // C++ [temp.expl.spec]p15:
3656    //   An explicit specialization of a static data member of a template is a
3657    //   definition if the declaration includes an initializer; otherwise, it
3658    //   is a declaration.
3659    if (Var->isStaticDataMember() &&
3660        Var->getInstantiatedFromStaticDataMember() &&
3661        Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3662      return;
3663
3664    // C++ [dcl.init]p9:
3665    //   If no initializer is specified for an object, and the object
3666    //   is of (possibly cv-qualified) non-POD class type (or array
3667    //   thereof), the object shall be default-initialized; if the
3668    //   object is of const-qualified type, the underlying class type
3669    //   shall have a user-declared default constructor.
3670    //
3671    // FIXME: Diagnose the "user-declared default constructor" bit.
3672    if (getLangOptions().CPlusPlus) {
3673      QualType InitType = Type;
3674      if (const ArrayType *Array = Context.getAsArrayType(Type))
3675        InitType = Context.getBaseElementType(Array);
3676      if ((!Var->hasExternalStorage() && !Var->isExternC()) &&
3677          InitType->isRecordType() && !InitType->isDependentType()) {
3678        if (!RequireCompleteType(Var->getLocation(), InitType,
3679                                 diag::err_invalid_incomplete_type_use)) {
3680          ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3681
3682          CXXConstructorDecl *Constructor
3683            = PerformInitializationByConstructor(InitType,
3684                                                 MultiExprArg(*this, 0, 0),
3685                                                 Var->getLocation(),
3686                                               SourceRange(Var->getLocation(),
3687                                                           Var->getLocation()),
3688                                                 Var->getDeclName(),
3689                                                 IK_Default,
3690                                                 ConstructorArgs);
3691
3692          // FIXME: Location info for the variable initialization?
3693          if (!Constructor)
3694            Var->setInvalidDecl();
3695          else {
3696            // FIXME: Cope with initialization of arrays
3697            if (!Constructor->isTrivial() &&
3698                InitializeVarWithConstructor(Var, Constructor,
3699                                             move_arg(ConstructorArgs)))
3700              Var->setInvalidDecl();
3701
3702            FinalizeVarWithDestructor(Var, InitType);
3703          }
3704        } else {
3705          Var->setInvalidDecl();
3706        }
3707      }
3708    }
3709
3710#if 0
3711    // FIXME: Temporarily disabled because we are not properly parsing
3712    // linkage specifications on declarations, e.g.,
3713    //
3714    //   extern "C" const CGPoint CGPointerZero;
3715    //
3716    // C++ [dcl.init]p9:
3717    //
3718    //     If no initializer is specified for an object, and the
3719    //     object is of (possibly cv-qualified) non-POD class type (or
3720    //     array thereof), the object shall be default-initialized; if
3721    //     the object is of const-qualified type, the underlying class
3722    //     type shall have a user-declared default
3723    //     constructor. Otherwise, if no initializer is specified for
3724    //     an object, the object and its subobjects, if any, have an
3725    //     indeterminate initial value; if the object or any of its
3726    //     subobjects are of const-qualified type, the program is
3727    //     ill-formed.
3728    //
3729    // This isn't technically an error in C, so we don't diagnose it.
3730    //
3731    // FIXME: Actually perform the POD/user-defined default
3732    // constructor check.
3733    if (getLangOptions().CPlusPlus &&
3734        Context.getCanonicalType(Type).isConstQualified() &&
3735        !Var->hasExternalStorage())
3736      Diag(Var->getLocation(),  diag::err_const_var_requires_init)
3737        << Var->getName()
3738        << SourceRange(Var->getLocation(), Var->getLocation());
3739#endif
3740  }
3741}
3742
3743Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
3744                                                   DeclPtrTy *Group,
3745                                                   unsigned NumDecls) {
3746  llvm::SmallVector<Decl*, 8> Decls;
3747
3748  if (DS.isTypeSpecOwned())
3749    Decls.push_back((Decl*)DS.getTypeRep());
3750
3751  for (unsigned i = 0; i != NumDecls; ++i)
3752    if (Decl *D = Group[i].getAs<Decl>())
3753      Decls.push_back(D);
3754
3755  // Perform semantic analysis that depends on having fully processed both
3756  // the declarator and initializer.
3757  for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
3758    VarDecl *IDecl = dyn_cast<VarDecl>(Decls[i]);
3759    if (!IDecl)
3760      continue;
3761    QualType T = IDecl->getType();
3762
3763    // Block scope. C99 6.7p7: If an identifier for an object is declared with
3764    // no linkage (C99 6.2.2p6), the type for the object shall be complete...
3765    if (IDecl->isBlockVarDecl() && !IDecl->hasExternalStorage()) {
3766      if (T->isDependentType()) {
3767        // If T is dependent, we should not require a complete type.
3768        // (RequireCompleteType shouldn't be called with dependent types.)
3769        // But we still can at least check if we've got an array of unspecified
3770        // size without an initializer.
3771        if (!IDecl->isInvalidDecl() && T->isIncompleteArrayType() &&
3772            !IDecl->getInit()) {
3773          Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
3774            << T;
3775          IDecl->setInvalidDecl();
3776        }
3777      } else if (!IDecl->isInvalidDecl()) {
3778        // If T is an incomplete array type with an initializer list that is
3779        // dependent on something, its size has not been fixed. We could attempt
3780        // to fix the size for such arrays, but we would still have to check
3781        // here for initializers containing a C++0x vararg expansion, e.g.
3782        // template <typename... Args> void f(Args... args) {
3783        //   int vals[] = { args };
3784        // }
3785        const IncompleteArrayType *IAT = Context.getAsIncompleteArrayType(T);
3786        Expr *Init = IDecl->getInit();
3787        if (IAT && Init &&
3788            (Init->isTypeDependent() || Init->isValueDependent())) {
3789          // Check that the member type of the array is complete, at least.
3790          if (RequireCompleteType(IDecl->getLocation(), IAT->getElementType(),
3791                                  diag::err_typecheck_decl_incomplete_type))
3792            IDecl->setInvalidDecl();
3793        } else if (RequireCompleteType(IDecl->getLocation(), T,
3794                                      diag::err_typecheck_decl_incomplete_type))
3795          IDecl->setInvalidDecl();
3796      }
3797    }
3798    // File scope. C99 6.9.2p2: A declaration of an identifier for an
3799    // object that has file scope without an initializer, and without a
3800    // storage-class specifier or with the storage-class specifier "static",
3801    // constitutes a tentative definition. Note: A tentative definition with
3802    // external linkage is valid (C99 6.2.2p5).
3803    if (IDecl->isTentativeDefinition(Context) && !IDecl->isInvalidDecl()) {
3804      if (const IncompleteArrayType *ArrayT
3805          = Context.getAsIncompleteArrayType(T)) {
3806        if (RequireCompleteType(IDecl->getLocation(),
3807                                ArrayT->getElementType(),
3808                                diag::err_illegal_decl_array_incomplete_type))
3809          IDecl->setInvalidDecl();
3810      } else if (IDecl->getStorageClass() == VarDecl::Static) {
3811        // C99 6.9.2p3: If the declaration of an identifier for an object is
3812        // a tentative definition and has internal linkage (C99 6.2.2p3), the
3813        // declared type shall not be an incomplete type.
3814        // NOTE: code such as the following
3815        //     static struct s;
3816        //     struct s { int a; };
3817        // is accepted by gcc. Hence here we issue a warning instead of
3818        // an error and we do not invalidate the static declaration.
3819        // NOTE: to avoid multiple warnings, only check the first declaration.
3820        if (IDecl->getPreviousDeclaration() == 0)
3821          RequireCompleteType(IDecl->getLocation(), T,
3822                              diag::ext_typecheck_decl_incomplete_type);
3823      }
3824    }
3825  }
3826  return DeclGroupPtrTy::make(DeclGroupRef::Create(Context,
3827                                                   Decls.data(), Decls.size()));
3828}
3829
3830
3831/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
3832/// to introduce parameters into function prototype scope.
3833Sema::DeclPtrTy
3834Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
3835  const DeclSpec &DS = D.getDeclSpec();
3836
3837  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
3838  VarDecl::StorageClass StorageClass = VarDecl::None;
3839  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
3840    StorageClass = VarDecl::Register;
3841  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
3842    Diag(DS.getStorageClassSpecLoc(),
3843         diag::err_invalid_storage_class_in_func_decl);
3844    D.getMutableDeclSpec().ClearStorageClassSpecs();
3845  }
3846
3847  if (D.getDeclSpec().isThreadSpecified())
3848    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
3849
3850  DiagnoseFunctionSpecifiers(D);
3851
3852  // Check that there are no default arguments inside the type of this
3853  // parameter (C++ only).
3854  if (getLangOptions().CPlusPlus)
3855    CheckExtraCXXDefaultArguments(D);
3856
3857  DeclaratorInfo *DInfo = 0;
3858  TagDecl *OwnedDecl = 0;
3859  QualType parmDeclType = GetTypeForDeclarator(D, S, &DInfo, &OwnedDecl);
3860
3861  if (getLangOptions().CPlusPlus && OwnedDecl && OwnedDecl->isDefinition()) {
3862    // C++ [dcl.fct]p6:
3863    //   Types shall not be defined in return or parameter types.
3864    Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type)
3865      << Context.getTypeDeclType(OwnedDecl);
3866  }
3867
3868  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
3869  // Can this happen for params?  We already checked that they don't conflict
3870  // among each other.  Here they can only shadow globals, which is ok.
3871  IdentifierInfo *II = D.getIdentifier();
3872  if (II) {
3873    if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
3874      if (PrevDecl->isTemplateParameter()) {
3875        // Maybe we will complain about the shadowed template parameter.
3876        DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
3877        // Just pretend that we didn't see the previous declaration.
3878        PrevDecl = 0;
3879      } else if (S->isDeclScope(DeclPtrTy::make(PrevDecl))) {
3880        Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
3881
3882        // Recover by removing the name
3883        II = 0;
3884        D.SetIdentifier(0, D.getIdentifierLoc());
3885      }
3886    }
3887  }
3888
3889  // Parameters can not be abstract class types.
3890  // For record types, this is done by the AbstractClassUsageDiagnoser once
3891  // the class has been completely parsed.
3892  if (!CurContext->isRecord() &&
3893      RequireNonAbstractType(D.getIdentifierLoc(), parmDeclType,
3894                             diag::err_abstract_type_in_decl,
3895                             AbstractParamType))
3896    D.setInvalidType(true);
3897
3898  QualType T = adjustParameterType(parmDeclType);
3899
3900  ParmVarDecl *New
3901    = ParmVarDecl::Create(Context, CurContext, D.getIdentifierLoc(), II,
3902                          T, DInfo, StorageClass, 0);
3903
3904  if (D.isInvalidType())
3905    New->setInvalidDecl();
3906
3907  // Parameter declarators cannot be interface types. All ObjC objects are
3908  // passed by reference.
3909  if (T->isObjCInterfaceType()) {
3910    Diag(D.getIdentifierLoc(),
3911         diag::err_object_cannot_be_passed_returned_by_value) << 1 << T;
3912    New->setInvalidDecl();
3913  }
3914
3915  // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
3916  if (D.getCXXScopeSpec().isSet()) {
3917    Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
3918      << D.getCXXScopeSpec().getRange();
3919    New->setInvalidDecl();
3920  }
3921
3922  // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
3923  // duration shall not be qualified by an address-space qualifier."
3924  // Since all parameters have automatic store duration, they can not have
3925  // an address space.
3926  if (T.getAddressSpace() != 0) {
3927    Diag(D.getIdentifierLoc(),
3928         diag::err_arg_with_address_space);
3929    New->setInvalidDecl();
3930  }
3931
3932
3933  // Add the parameter declaration into this scope.
3934  S->AddDecl(DeclPtrTy::make(New));
3935  if (II)
3936    IdResolver.AddDecl(New);
3937
3938  ProcessDeclAttributes(S, New, D);
3939
3940  if (New->hasAttr<BlocksAttr>()) {
3941    Diag(New->getLocation(), diag::err_block_on_nonlocal);
3942  }
3943  return DeclPtrTy::make(New);
3944}
3945
3946void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
3947                                           SourceLocation LocAfterDecls) {
3948  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3949         "Not a function declarator!");
3950  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3951
3952  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
3953  // for a K&R function.
3954  if (!FTI.hasPrototype) {
3955    for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
3956      --i;
3957      if (FTI.ArgInfo[i].Param == 0) {
3958        llvm::SmallString<256> Code;
3959        llvm::raw_svector_ostream(Code) << "  int "
3960                                        << FTI.ArgInfo[i].Ident->getName()
3961                                        << ";\n";
3962        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
3963          << FTI.ArgInfo[i].Ident
3964          << CodeModificationHint::CreateInsertion(LocAfterDecls, Code.str());
3965
3966        // Implicitly declare the argument as type 'int' for lack of a better
3967        // type.
3968        DeclSpec DS;
3969        const char* PrevSpec; // unused
3970        unsigned DiagID; // unused
3971        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
3972                           PrevSpec, DiagID);
3973        Declarator ParamD(DS, Declarator::KNRTypeListContext);
3974        ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
3975        FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
3976      }
3977    }
3978  }
3979}
3980
3981Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
3982                                              Declarator &D) {
3983  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3984  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3985         "Not a function declarator!");
3986  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3987
3988  if (FTI.hasPrototype) {
3989    // FIXME: Diagnose arguments without names in C.
3990  }
3991
3992  Scope *ParentScope = FnBodyScope->getParent();
3993
3994  DeclPtrTy DP = HandleDeclarator(ParentScope, D,
3995                                  MultiTemplateParamsArg(*this),
3996                                  /*IsFunctionDefinition=*/true);
3997  return ActOnStartOfFunctionDef(FnBodyScope, DP);
3998}
3999
4000Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclPtrTy D) {
4001  // Clear the last template instantiation error context.
4002  LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
4003
4004  if (!D)
4005    return D;
4006  FunctionDecl *FD = 0;
4007
4008  if (FunctionTemplateDecl *FunTmpl
4009        = dyn_cast<FunctionTemplateDecl>(D.getAs<Decl>()))
4010    FD = FunTmpl->getTemplatedDecl();
4011  else
4012    FD = cast<FunctionDecl>(D.getAs<Decl>());
4013
4014  CurFunctionNeedsScopeChecking = false;
4015
4016  // See if this is a redefinition.
4017  const FunctionDecl *Definition;
4018  if (FD->getBody(Definition)) {
4019    Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
4020    Diag(Definition->getLocation(), diag::note_previous_definition);
4021  }
4022
4023  // Builtin functions cannot be defined.
4024  if (unsigned BuiltinID = FD->getBuiltinID()) {
4025    if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4026      Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
4027      FD->setInvalidDecl();
4028    }
4029  }
4030
4031  // The return type of a function definition must be complete
4032  // (C99 6.9.1p3, C++ [dcl.fct]p6).
4033  QualType ResultType = FD->getResultType();
4034  if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
4035      !FD->isInvalidDecl() &&
4036      RequireCompleteType(FD->getLocation(), ResultType,
4037                          diag::err_func_def_incomplete_result))
4038    FD->setInvalidDecl();
4039
4040  // GNU warning -Wmissing-prototypes:
4041  //   Warn if a global function is defined without a previous
4042  //   prototype declaration. This warning is issued even if the
4043  //   definition itself provides a prototype. The aim is to detect
4044  //   global functions that fail to be declared in header files.
4045  if (!FD->isInvalidDecl() && FD->isGlobal() && !isa<CXXMethodDecl>(FD) &&
4046      !FD->isMain()) {
4047    bool MissingPrototype = true;
4048    for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
4049         Prev; Prev = Prev->getPreviousDeclaration()) {
4050      // Ignore any declarations that occur in function or method
4051      // scope, because they aren't visible from the header.
4052      if (Prev->getDeclContext()->isFunctionOrMethod())
4053        continue;
4054
4055      MissingPrototype = !Prev->getType()->isFunctionProtoType();
4056      break;
4057    }
4058
4059    if (MissingPrototype)
4060      Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
4061  }
4062
4063  if (FnBodyScope)
4064    PushDeclContext(FnBodyScope, FD);
4065
4066  // Check the validity of our function parameters
4067  CheckParmsForFunctionDef(FD);
4068
4069  // Introduce our parameters into the function scope
4070  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
4071    ParmVarDecl *Param = FD->getParamDecl(p);
4072    Param->setOwningFunction(FD);
4073
4074    // If this has an identifier, add it to the scope stack.
4075    if (Param->getIdentifier() && FnBodyScope)
4076      PushOnScopeChains(Param, FnBodyScope);
4077  }
4078
4079  // Checking attributes of current function definition
4080  // dllimport attribute.
4081  if (FD->getAttr<DLLImportAttr>() &&
4082      (!FD->getAttr<DLLExportAttr>())) {
4083    // dllimport attribute cannot be applied to definition.
4084    if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
4085      Diag(FD->getLocation(),
4086           diag::err_attribute_can_be_applied_only_to_symbol_declaration)
4087        << "dllimport";
4088      FD->setInvalidDecl();
4089      return DeclPtrTy::make(FD);
4090    } else {
4091      // If a symbol previously declared dllimport is later defined, the
4092      // attribute is ignored in subsequent references, and a warning is
4093      // emitted.
4094      Diag(FD->getLocation(),
4095           diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
4096        << FD->getNameAsCString() << "dllimport";
4097    }
4098  }
4099  return DeclPtrTy::make(FD);
4100}
4101
4102Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg) {
4103  return ActOnFinishFunctionBody(D, move(BodyArg), false);
4104}
4105
4106Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg,
4107                                              bool IsInstantiation) {
4108  Decl *dcl = D.getAs<Decl>();
4109  Stmt *Body = BodyArg.takeAs<Stmt>();
4110
4111  FunctionDecl *FD = 0;
4112  FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
4113  if (FunTmpl)
4114    FD = FunTmpl->getTemplatedDecl();
4115  else
4116    FD = dyn_cast_or_null<FunctionDecl>(dcl);
4117
4118  if (FD) {
4119    FD->setBody(Body);
4120    if (FD->isMain())
4121      // C and C++ allow for main to automagically return 0.
4122      // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
4123      FD->setHasImplicitReturnZero(true);
4124    else
4125      CheckFallThroughForFunctionDef(FD, Body);
4126
4127    if (!FD->isInvalidDecl())
4128      DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
4129
4130    // C++ [basic.def.odr]p2:
4131    //   [...] A virtual member function is used if it is not pure. [...]
4132    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
4133      if (Method->isVirtual() && !Method->isPure())
4134        MarkDeclarationReferenced(Method->getLocation(), Method);
4135
4136    assert(FD == getCurFunctionDecl() && "Function parsing confused");
4137  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
4138    assert(MD == getCurMethodDecl() && "Method parsing confused");
4139    MD->setBody(Body);
4140    CheckFallThroughForFunctionDef(MD, Body);
4141    MD->setEndLoc(Body->getLocEnd());
4142
4143    if (!MD->isInvalidDecl())
4144      DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
4145  } else {
4146    Body->Destroy(Context);
4147    return DeclPtrTy();
4148  }
4149  if (!IsInstantiation)
4150    PopDeclContext();
4151
4152  // Verify and clean out per-function state.
4153
4154  assert(&getLabelMap() == &FunctionLabelMap && "Didn't pop block right?");
4155
4156  // Check goto/label use.
4157  for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
4158       I = FunctionLabelMap.begin(), E = FunctionLabelMap.end(); I != E; ++I) {
4159    LabelStmt *L = I->second;
4160
4161    // Verify that we have no forward references left.  If so, there was a goto
4162    // or address of a label taken, but no definition of it.  Label fwd
4163    // definitions are indicated with a null substmt.
4164    if (L->getSubStmt() != 0)
4165      continue;
4166
4167    // Emit error.
4168    Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
4169
4170    // At this point, we have gotos that use the bogus label.  Stitch it into
4171    // the function body so that they aren't leaked and that the AST is well
4172    // formed.
4173    if (Body == 0) {
4174      // The whole function wasn't parsed correctly, just delete this.
4175      L->Destroy(Context);
4176      continue;
4177    }
4178
4179    // Otherwise, the body is valid: we want to stitch the label decl into the
4180    // function somewhere so that it is properly owned and so that the goto
4181    // has a valid target.  Do this by creating a new compound stmt with the
4182    // label in it.
4183
4184    // Give the label a sub-statement.
4185    L->setSubStmt(new (Context) NullStmt(L->getIdentLoc()));
4186
4187    CompoundStmt *Compound = isa<CXXTryStmt>(Body) ?
4188                               cast<CXXTryStmt>(Body)->getTryBlock() :
4189                               cast<CompoundStmt>(Body);
4190    std::vector<Stmt*> Elements(Compound->body_begin(), Compound->body_end());
4191    Elements.push_back(L);
4192    Compound->setStmts(Context, &Elements[0], Elements.size());
4193  }
4194  FunctionLabelMap.clear();
4195
4196  if (!Body) return D;
4197
4198  // Verify that that gotos and switch cases don't jump into scopes illegally.
4199  if (CurFunctionNeedsScopeChecking)
4200    DiagnoseInvalidJumps(Body);
4201
4202  // C++ constructors that have function-try-blocks can't have return
4203  // statements in the handlers of that block. (C++ [except.handle]p14)
4204  // Verify this.
4205  if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
4206    DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
4207
4208  if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl))
4209    MarkBaseAndMemberDestructorsReferenced(Destructor);
4210
4211  // If any errors have occurred, clear out any temporaries that may have
4212  // been leftover. This ensures that these temporaries won't be picked up for
4213  // deletion in some later function.
4214  if (PP.getDiagnostics().hasErrorOccurred())
4215    ExprTemporaries.clear();
4216
4217  assert(ExprTemporaries.empty() && "Leftover temporaries in function");
4218  return D;
4219}
4220
4221/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4222/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
4223NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
4224                                          IdentifierInfo &II, Scope *S) {
4225  // Before we produce a declaration for an implicitly defined
4226  // function, see whether there was a locally-scoped declaration of
4227  // this name as a function or variable. If so, use that
4228  // (non-visible) declaration, and complain about it.
4229  llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4230    = LocallyScopedExternalDecls.find(&II);
4231  if (Pos != LocallyScopedExternalDecls.end()) {
4232    Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
4233    Diag(Pos->second->getLocation(), diag::note_previous_declaration);
4234    return Pos->second;
4235  }
4236
4237  // Extension in C99.  Legal in C90, but warn about it.
4238  if (II.getName().startswith("__builtin_"))
4239    Diag(Loc, diag::warn_builtin_unknown) << &II;
4240  else if (getLangOptions().C99)
4241    Diag(Loc, diag::ext_implicit_function_decl) << &II;
4242  else
4243    Diag(Loc, diag::warn_implicit_function_decl) << &II;
4244
4245  // Set a Declarator for the implicit definition: int foo();
4246  const char *Dummy;
4247  DeclSpec DS;
4248  unsigned DiagID;
4249  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
4250  Error = Error; // Silence warning.
4251  assert(!Error && "Error setting up implicit decl!");
4252  Declarator D(DS, Declarator::BlockContext);
4253  D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
4254                                             0, 0, false, SourceLocation(),
4255                                             false, 0,0,0, Loc, Loc, D),
4256                SourceLocation());
4257  D.SetIdentifier(&II, Loc);
4258
4259  // Insert this function into translation-unit scope.
4260
4261  DeclContext *PrevDC = CurContext;
4262  CurContext = Context.getTranslationUnitDecl();
4263
4264  FunctionDecl *FD =
4265 dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D).getAs<Decl>());
4266  FD->setImplicit();
4267
4268  CurContext = PrevDC;
4269
4270  AddKnownFunctionAttributes(FD);
4271
4272  return FD;
4273}
4274
4275/// \brief Adds any function attributes that we know a priori based on
4276/// the declaration of this function.
4277///
4278/// These attributes can apply both to implicitly-declared builtins
4279/// (like __builtin___printf_chk) or to library-declared functions
4280/// like NSLog or printf.
4281void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
4282  if (FD->isInvalidDecl())
4283    return;
4284
4285  // If this is a built-in function, map its builtin attributes to
4286  // actual attributes.
4287  if (unsigned BuiltinID = FD->getBuiltinID()) {
4288    // Handle printf-formatting attributes.
4289    unsigned FormatIdx;
4290    bool HasVAListArg;
4291    if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
4292      if (!FD->getAttr<FormatAttr>())
4293        FD->addAttr(::new (Context) FormatAttr("printf", FormatIdx + 1,
4294                                             HasVAListArg ? 0 : FormatIdx + 2));
4295    }
4296
4297    // Mark const if we don't care about errno and that is the only
4298    // thing preventing the function from being const. This allows
4299    // IRgen to use LLVM intrinsics for such functions.
4300    if (!getLangOptions().MathErrno &&
4301        Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
4302      if (!FD->getAttr<ConstAttr>())
4303        FD->addAttr(::new (Context) ConstAttr());
4304    }
4305
4306    if (Context.BuiltinInfo.isNoReturn(BuiltinID))
4307      FD->addAttr(::new (Context) NoReturnAttr());
4308  }
4309
4310  IdentifierInfo *Name = FD->getIdentifier();
4311  if (!Name)
4312    return;
4313  if ((!getLangOptions().CPlusPlus &&
4314       FD->getDeclContext()->isTranslationUnit()) ||
4315      (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
4316       cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
4317       LinkageSpecDecl::lang_c)) {
4318    // Okay: this could be a libc/libm/Objective-C function we know
4319    // about.
4320  } else
4321    return;
4322
4323  if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
4324    // FIXME: NSLog and NSLogv should be target specific
4325    if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
4326      // FIXME: We known better than our headers.
4327      const_cast<FormatAttr *>(Format)->setType("printf");
4328    } else
4329      FD->addAttr(::new (Context) FormatAttr("printf", 1,
4330                                             Name->isStr("NSLogv") ? 0 : 2));
4331  } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
4332    // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
4333    // target-specific builtins, perhaps?
4334    if (!FD->getAttr<FormatAttr>())
4335      FD->addAttr(::new (Context) FormatAttr("printf", 2,
4336                                             Name->isStr("vasprintf") ? 0 : 3));
4337  }
4338}
4339
4340TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
4341                                    DeclaratorInfo *DInfo) {
4342  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
4343  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
4344
4345  if (!DInfo) {
4346    assert(D.isInvalidType() && "no declarator info for valid type");
4347    DInfo = Context.getTrivialDeclaratorInfo(T);
4348  }
4349
4350  // Scope manipulation handled by caller.
4351  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
4352                                           D.getIdentifierLoc(),
4353                                           D.getIdentifier(),
4354                                           DInfo);
4355
4356  if (const TagType *TT = T->getAs<TagType>()) {
4357    TagDecl *TD = TT->getDecl();
4358
4359    // If the TagDecl that the TypedefDecl points to is an anonymous decl
4360    // keep track of the TypedefDecl.
4361    if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
4362      TD->setTypedefForAnonDecl(NewTD);
4363  }
4364
4365  if (D.isInvalidType())
4366    NewTD->setInvalidDecl();
4367  return NewTD;
4368}
4369
4370
4371/// \brief Determine whether a tag with a given kind is acceptable
4372/// as a redeclaration of the given tag declaration.
4373///
4374/// \returns true if the new tag kind is acceptable, false otherwise.
4375bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
4376                                        TagDecl::TagKind NewTag,
4377                                        SourceLocation NewTagLoc,
4378                                        const IdentifierInfo &Name) {
4379  // C++ [dcl.type.elab]p3:
4380  //   The class-key or enum keyword present in the
4381  //   elaborated-type-specifier shall agree in kind with the
4382  //   declaration to which the name in theelaborated-type-specifier
4383  //   refers. This rule also applies to the form of
4384  //   elaborated-type-specifier that declares a class-name or
4385  //   friend class since it can be construed as referring to the
4386  //   definition of the class. Thus, in any
4387  //   elaborated-type-specifier, the enum keyword shall be used to
4388  //   refer to an enumeration (7.2), the union class-keyshall be
4389  //   used to refer to a union (clause 9), and either the class or
4390  //   struct class-key shall be used to refer to a class (clause 9)
4391  //   declared using the class or struct class-key.
4392  TagDecl::TagKind OldTag = Previous->getTagKind();
4393  if (OldTag == NewTag)
4394    return true;
4395
4396  if ((OldTag == TagDecl::TK_struct || OldTag == TagDecl::TK_class) &&
4397      (NewTag == TagDecl::TK_struct || NewTag == TagDecl::TK_class)) {
4398    // Warn about the struct/class tag mismatch.
4399    bool isTemplate = false;
4400    if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
4401      isTemplate = Record->getDescribedClassTemplate();
4402
4403    Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
4404      << (NewTag == TagDecl::TK_class)
4405      << isTemplate << &Name
4406      << CodeModificationHint::CreateReplacement(SourceRange(NewTagLoc),
4407                              OldTag == TagDecl::TK_class? "class" : "struct");
4408    Diag(Previous->getLocation(), diag::note_previous_use);
4409    return true;
4410  }
4411  return false;
4412}
4413
4414/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
4415/// former case, Name will be non-null.  In the later case, Name will be null.
4416/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
4417/// reference/declaration/definition of a tag.
4418Sema::DeclPtrTy Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4419                               SourceLocation KWLoc, const CXXScopeSpec &SS,
4420                               IdentifierInfo *Name, SourceLocation NameLoc,
4421                               AttributeList *Attr, AccessSpecifier AS,
4422                               MultiTemplateParamsArg TemplateParameterLists,
4423                               bool &OwnedDecl, bool &IsDependent) {
4424  // If this is not a definition, it must have a name.
4425  assert((Name != 0 || TUK == TUK_Definition) &&
4426         "Nameless record must be a definition!");
4427
4428  OwnedDecl = false;
4429  TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
4430
4431  // FIXME: Check explicit specializations more carefully.
4432  bool isExplicitSpecialization = false;
4433  if (TUK != TUK_Reference) {
4434    if (TemplateParameterList *TemplateParams
4435          = MatchTemplateParametersToScopeSpecifier(KWLoc, SS,
4436                        (TemplateParameterList**)TemplateParameterLists.get(),
4437                                              TemplateParameterLists.size(),
4438                                                    isExplicitSpecialization)) {
4439      if (TemplateParams->size() > 0) {
4440        // This is a declaration or definition of a class template (which may
4441        // be a member of another template).
4442        OwnedDecl = false;
4443        DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
4444                                               SS, Name, NameLoc, Attr,
4445                                               TemplateParams,
4446                                               AS);
4447        TemplateParameterLists.release();
4448        return Result.get();
4449      } else {
4450        // The "template<>" header is extraneous.
4451        Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
4452          << ElaboratedType::getNameForTagKind(Kind) << Name;
4453        isExplicitSpecialization = true;
4454      }
4455    }
4456
4457    TemplateParameterLists.release();
4458  }
4459
4460  DeclContext *SearchDC = CurContext;
4461  DeclContext *DC = CurContext;
4462  bool isStdBadAlloc = false;
4463  bool Invalid = false;
4464
4465  RedeclarationKind Redecl = (TUK != TUK_Reference ? ForRedeclaration
4466                                                   : NotForRedeclaration);
4467
4468  LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
4469
4470  if (Name && SS.isNotEmpty()) {
4471    // We have a nested-name tag ('struct foo::bar').
4472
4473    // Check for invalid 'foo::'.
4474    if (SS.isInvalid()) {
4475      Name = 0;
4476      goto CreateNewDecl;
4477    }
4478
4479    // If this is a friend or a reference to a class in a dependent
4480    // context, don't try to make a decl for it.
4481    if (TUK == TUK_Friend || TUK == TUK_Reference) {
4482      DC = computeDeclContext(SS, false);
4483      if (!DC) {
4484        IsDependent = true;
4485        return DeclPtrTy();
4486      }
4487    }
4488
4489    if (RequireCompleteDeclContext(SS))
4490      return DeclPtrTy::make((Decl *)0);
4491
4492    DC = computeDeclContext(SS, true);
4493    SearchDC = DC;
4494    // Look-up name inside 'foo::'.
4495    LookupQualifiedName(Previous, DC);
4496
4497    if (Previous.isAmbiguous())
4498      return DeclPtrTy();
4499
4500    // A tag 'foo::bar' must already exist.
4501    if (Previous.empty()) {
4502      Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
4503      Name = 0;
4504      Invalid = true;
4505      goto CreateNewDecl;
4506    }
4507  } else if (Name) {
4508    // If this is a named struct, check to see if there was a previous forward
4509    // declaration or definition.
4510    // FIXME: We're looking into outer scopes here, even when we
4511    // shouldn't be. Doing so can result in ambiguities that we
4512    // shouldn't be diagnosing.
4513    LookupName(Previous, S);
4514
4515    // Note:  there used to be some attempt at recovery here.
4516    if (Previous.isAmbiguous())
4517      return DeclPtrTy();
4518
4519    if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
4520      // FIXME: This makes sure that we ignore the contexts associated
4521      // with C structs, unions, and enums when looking for a matching
4522      // tag declaration or definition. See the similar lookup tweak
4523      // in Sema::LookupName; is there a better way to deal with this?
4524      while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
4525        SearchDC = SearchDC->getParent();
4526    }
4527  }
4528
4529  if (Previous.isSingleResult() &&
4530      Previous.getFoundDecl()->isTemplateParameter()) {
4531    // Maybe we will complain about the shadowed template parameter.
4532    DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
4533    // Just pretend that we didn't see the previous declaration.
4534    Previous.clear();
4535  }
4536
4537  if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
4538      DC->Equals(StdNamespace) && Name->isStr("bad_alloc")) {
4539    // This is a declaration of or a reference to "std::bad_alloc".
4540    isStdBadAlloc = true;
4541
4542    if (Previous.empty() && StdBadAlloc) {
4543      // std::bad_alloc has been implicitly declared (but made invisible to
4544      // name lookup). Fill in this implicit declaration as the previous
4545      // declaration, so that the declarations get chained appropriately.
4546      Previous.addDecl(StdBadAlloc);
4547    }
4548  }
4549
4550  if (!Previous.empty()) {
4551    assert(Previous.isSingleResult());
4552    NamedDecl *PrevDecl = Previous.getFoundDecl();
4553    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
4554      // If this is a use of a previous tag, or if the tag is already declared
4555      // in the same scope (so that the definition/declaration completes or
4556      // rementions the tag), reuse the decl.
4557      if (TUK == TUK_Reference || TUK == TUK_Friend ||
4558          isDeclInScope(PrevDecl, SearchDC, S)) {
4559        // Make sure that this wasn't declared as an enum and now used as a
4560        // struct or something similar.
4561        if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, KWLoc, *Name)) {
4562          bool SafeToContinue
4563            = (PrevTagDecl->getTagKind() != TagDecl::TK_enum &&
4564               Kind != TagDecl::TK_enum);
4565          if (SafeToContinue)
4566            Diag(KWLoc, diag::err_use_with_wrong_tag)
4567              << Name
4568              << CodeModificationHint::CreateReplacement(SourceRange(KWLoc),
4569                                                  PrevTagDecl->getKindName());
4570          else
4571            Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
4572          Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
4573
4574          if (SafeToContinue)
4575            Kind = PrevTagDecl->getTagKind();
4576          else {
4577            // Recover by making this an anonymous redefinition.
4578            Name = 0;
4579            Previous.clear();
4580            Invalid = true;
4581          }
4582        }
4583
4584        if (!Invalid) {
4585          // If this is a use, just return the declaration we found.
4586
4587          // FIXME: In the future, return a variant or some other clue
4588          // for the consumer of this Decl to know it doesn't own it.
4589          // For our current ASTs this shouldn't be a problem, but will
4590          // need to be changed with DeclGroups.
4591          if (TUK == TUK_Reference || TUK == TUK_Friend)
4592            return DeclPtrTy::make(PrevTagDecl);
4593
4594          // Diagnose attempts to redefine a tag.
4595          if (TUK == TUK_Definition) {
4596            if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
4597              // If we're defining a specialization and the previous definition
4598              // is from an implicit instantiation, don't emit an error
4599              // here; we'll catch this in the general case below.
4600              if (!isExplicitSpecialization ||
4601                  !isa<CXXRecordDecl>(Def) ||
4602                  cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind()
4603                                               == TSK_ExplicitSpecialization) {
4604                Diag(NameLoc, diag::err_redefinition) << Name;
4605                Diag(Def->getLocation(), diag::note_previous_definition);
4606                // If this is a redefinition, recover by making this
4607                // struct be anonymous, which will make any later
4608                // references get the previous definition.
4609                Name = 0;
4610                Previous.clear();
4611                Invalid = true;
4612              }
4613            } else {
4614              // If the type is currently being defined, complain
4615              // about a nested redefinition.
4616              TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
4617              if (Tag->isBeingDefined()) {
4618                Diag(NameLoc, diag::err_nested_redefinition) << Name;
4619                Diag(PrevTagDecl->getLocation(),
4620                     diag::note_previous_definition);
4621                Name = 0;
4622                Previous.clear();
4623                Invalid = true;
4624              }
4625            }
4626
4627            // Okay, this is definition of a previously declared or referenced
4628            // tag PrevDecl. We're going to create a new Decl for it.
4629          }
4630        }
4631        // If we get here we have (another) forward declaration or we
4632        // have a definition.  Just create a new decl.
4633
4634      } else {
4635        // If we get here, this is a definition of a new tag type in a nested
4636        // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
4637        // new decl/type.  We set PrevDecl to NULL so that the entities
4638        // have distinct types.
4639        Previous.clear();
4640      }
4641      // If we get here, we're going to create a new Decl. If PrevDecl
4642      // is non-NULL, it's a definition of the tag declared by
4643      // PrevDecl. If it's NULL, we have a new definition.
4644    } else {
4645      // PrevDecl is a namespace, template, or anything else
4646      // that lives in the IDNS_Tag identifier namespace.
4647      if (isDeclInScope(PrevDecl, SearchDC, S)) {
4648        // The tag name clashes with a namespace name, issue an error and
4649        // recover by making this tag be anonymous.
4650        Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
4651        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4652        Name = 0;
4653        Previous.clear();
4654        Invalid = true;
4655      } else {
4656        // The existing declaration isn't relevant to us; we're in a
4657        // new scope, so clear out the previous declaration.
4658        Previous.clear();
4659      }
4660    }
4661  } else if (TUK == TUK_Reference && SS.isEmpty() && Name &&
4662             (Kind != TagDecl::TK_enum || !getLangOptions().CPlusPlus)) {
4663    // C++ [basic.scope.pdecl]p5:
4664    //   -- for an elaborated-type-specifier of the form
4665    //
4666    //          class-key identifier
4667    //
4668    //      if the elaborated-type-specifier is used in the
4669    //      decl-specifier-seq or parameter-declaration-clause of a
4670    //      function defined in namespace scope, the identifier is
4671    //      declared as a class-name in the namespace that contains
4672    //      the declaration; otherwise, except as a friend
4673    //      declaration, the identifier is declared in the smallest
4674    //      non-class, non-function-prototype scope that contains the
4675    //      declaration.
4676    //
4677    // C99 6.7.2.3p8 has a similar (but not identical!) provision for
4678    // C structs and unions.
4679    //
4680    // GNU C also supports this behavior as part of its incomplete
4681    // enum types extension, while GNU C++ does not.
4682    //
4683    // Find the context where we'll be declaring the tag.
4684    // FIXME: We would like to maintain the current DeclContext as the
4685    // lexical context,
4686    while (SearchDC->isRecord())
4687      SearchDC = SearchDC->getParent();
4688
4689    // Find the scope where we'll be declaring the tag.
4690    while (S->isClassScope() ||
4691           (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
4692           ((S->getFlags() & Scope::DeclScope) == 0) ||
4693           (S->getEntity() &&
4694            ((DeclContext *)S->getEntity())->isTransparentContext()))
4695      S = S->getParent();
4696
4697  } else if (TUK == TUK_Friend && SS.isEmpty() && Name) {
4698    // C++ [namespace.memdef]p3:
4699    //   If a friend declaration in a non-local class first declares a
4700    //   class or function, the friend class or function is a member of
4701    //   the innermost enclosing namespace.
4702    while (!SearchDC->isFileContext())
4703      SearchDC = SearchDC->getParent();
4704
4705    // The entity of a decl scope is a DeclContext; see PushDeclContext.
4706    while (S->getEntity() != SearchDC)
4707      S = S->getParent();
4708  }
4709
4710CreateNewDecl:
4711
4712  TagDecl *PrevDecl = 0;
4713  if (Previous.isSingleResult())
4714    PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
4715
4716  // If there is an identifier, use the location of the identifier as the
4717  // location of the decl, otherwise use the location of the struct/union
4718  // keyword.
4719  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
4720
4721  // Otherwise, create a new declaration. If there is a previous
4722  // declaration of the same entity, the two will be linked via
4723  // PrevDecl.
4724  TagDecl *New;
4725
4726  if (Kind == TagDecl::TK_enum) {
4727    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
4728    // enum X { A, B, C } D;    D should chain to X.
4729    New = EnumDecl::Create(Context, SearchDC, Loc, Name, KWLoc,
4730                           cast_or_null<EnumDecl>(PrevDecl));
4731    // If this is an undefined enum, warn.
4732    if (TUK != TUK_Definition && !Invalid)  {
4733      unsigned DK = getLangOptions().CPlusPlus? diag::err_forward_ref_enum
4734                                              : diag::ext_forward_ref_enum;
4735      Diag(Loc, DK);
4736    }
4737  } else {
4738    // struct/union/class
4739
4740    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
4741    // struct X { int A; } D;    D should chain to X.
4742    if (getLangOptions().CPlusPlus) {
4743      // FIXME: Look for a way to use RecordDecl for simple structs.
4744      New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
4745                                  cast_or_null<CXXRecordDecl>(PrevDecl));
4746
4747      if (isStdBadAlloc && (!StdBadAlloc || StdBadAlloc->isImplicit()))
4748        StdBadAlloc = cast<CXXRecordDecl>(New);
4749    } else
4750      New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
4751                               cast_or_null<RecordDecl>(PrevDecl));
4752  }
4753
4754  if (Kind != TagDecl::TK_enum) {
4755    // Handle #pragma pack: if the #pragma pack stack has non-default
4756    // alignment, make up a packed attribute for this decl. These
4757    // attributes are checked when the ASTContext lays out the
4758    // structure.
4759    //
4760    // It is important for implementing the correct semantics that this
4761    // happen here (in act on tag decl). The #pragma pack stack is
4762    // maintained as a result of parser callbacks which can occur at
4763    // many points during the parsing of a struct declaration (because
4764    // the #pragma tokens are effectively skipped over during the
4765    // parsing of the struct).
4766    if (unsigned Alignment = getPragmaPackAlignment())
4767      New->addAttr(::new (Context) PragmaPackAttr(Alignment * 8));
4768  }
4769
4770  if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) {
4771    // C++ [dcl.typedef]p3:
4772    //   [...] Similarly, in a given scope, a class or enumeration
4773    //   shall not be declared with the same name as a typedef-name
4774    //   that is declared in that scope and refers to a type other
4775    //   than the class or enumeration itself.
4776    LookupResult Lookup(*this, Name, NameLoc, LookupOrdinaryName,
4777                        ForRedeclaration);
4778    LookupName(Lookup, S);
4779    TypedefDecl *PrevTypedef = 0;
4780    if (NamedDecl *Prev = Lookup.getAsSingleDecl(Context))
4781      PrevTypedef = dyn_cast<TypedefDecl>(Prev);
4782
4783    NamedDecl *PrevTypedefNamed = PrevTypedef;
4784    if (PrevTypedef && isDeclInScope(PrevTypedefNamed, SearchDC, S) &&
4785        Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) !=
4786          Context.getCanonicalType(Context.getTypeDeclType(New))) {
4787      Diag(Loc, diag::err_tag_definition_of_typedef)
4788        << Context.getTypeDeclType(New)
4789        << PrevTypedef->getUnderlyingType();
4790      Diag(PrevTypedef->getLocation(), diag::note_previous_definition);
4791      Invalid = true;
4792    }
4793  }
4794
4795  // If this is a specialization of a member class (of a class template),
4796  // check the specialization.
4797  if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
4798    Invalid = true;
4799
4800  if (Invalid)
4801    New->setInvalidDecl();
4802
4803  if (Attr)
4804    ProcessDeclAttributeList(S, New, Attr);
4805
4806  // If we're declaring or defining a tag in function prototype scope
4807  // in C, note that this type can only be used within the function.
4808  if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
4809    Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
4810
4811  // Set the lexical context. If the tag has a C++ scope specifier, the
4812  // lexical context will be different from the semantic context.
4813  New->setLexicalDeclContext(CurContext);
4814
4815  // Mark this as a friend decl if applicable.
4816  if (TUK == TUK_Friend)
4817    New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty());
4818
4819  // Set the access specifier.
4820  if (!Invalid && TUK != TUK_Friend)
4821    SetMemberAccessSpecifier(New, PrevDecl, AS);
4822
4823  if (TUK == TUK_Definition)
4824    New->startDefinition();
4825
4826  // If this has an identifier, add it to the scope stack.
4827  if (TUK == TUK_Friend) {
4828    // We might be replacing an existing declaration in the lookup tables;
4829    // if so, borrow its access specifier.
4830    if (PrevDecl)
4831      New->setAccess(PrevDecl->getAccess());
4832
4833    // Friend tag decls are visible in fairly strange ways.
4834    if (!CurContext->isDependentContext()) {
4835      DeclContext *DC = New->getDeclContext()->getLookupContext();
4836      DC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
4837      if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
4838        PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
4839    }
4840  } else if (Name) {
4841    S = getNonFieldDeclScope(S);
4842    PushOnScopeChains(New, S);
4843  } else {
4844    CurContext->addDecl(New);
4845  }
4846
4847  // If this is the C FILE type, notify the AST context.
4848  if (IdentifierInfo *II = New->getIdentifier())
4849    if (!New->isInvalidDecl() &&
4850        New->getDeclContext()->getLookupContext()->isTranslationUnit() &&
4851        II->isStr("FILE"))
4852      Context.setFILEDecl(New);
4853
4854  OwnedDecl = true;
4855  return DeclPtrTy::make(New);
4856}
4857
4858void Sema::ActOnTagStartDefinition(Scope *S, DeclPtrTy TagD) {
4859  AdjustDeclIfTemplate(TagD);
4860  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4861
4862  // Enter the tag context.
4863  PushDeclContext(S, Tag);
4864
4865  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
4866    FieldCollector->StartClass();
4867
4868    if (Record->getIdentifier()) {
4869      // C++ [class]p2:
4870      //   [...] The class-name is also inserted into the scope of the
4871      //   class itself; this is known as the injected-class-name. For
4872      //   purposes of access checking, the injected-class-name is treated
4873      //   as if it were a public member name.
4874      CXXRecordDecl *InjectedClassName
4875        = CXXRecordDecl::Create(Context, Record->getTagKind(),
4876                                CurContext, Record->getLocation(),
4877                                Record->getIdentifier(),
4878                                Record->getTagKeywordLoc(),
4879                                Record);
4880      InjectedClassName->setImplicit();
4881      InjectedClassName->setAccess(AS_public);
4882      if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
4883        InjectedClassName->setDescribedClassTemplate(Template);
4884      PushOnScopeChains(InjectedClassName, S);
4885      assert(InjectedClassName->isInjectedClassName() &&
4886             "Broken injected-class-name");
4887    }
4888  }
4889}
4890
4891void Sema::ActOnTagFinishDefinition(Scope *S, DeclPtrTy TagD,
4892                                    SourceLocation RBraceLoc) {
4893  AdjustDeclIfTemplate(TagD);
4894  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4895  Tag->setRBraceLoc(RBraceLoc);
4896
4897  if (isa<CXXRecordDecl>(Tag))
4898    FieldCollector->FinishClass();
4899
4900  // Exit this scope of this tag's definition.
4901  PopDeclContext();
4902
4903  // Notify the consumer that we've defined a tag.
4904  Consumer.HandleTagDeclDefinition(Tag);
4905}
4906
4907// Note that FieldName may be null for anonymous bitfields.
4908bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
4909                          QualType FieldTy, const Expr *BitWidth,
4910                          bool *ZeroWidth) {
4911  // Default to true; that shouldn't confuse checks for emptiness
4912  if (ZeroWidth)
4913    *ZeroWidth = true;
4914
4915  // C99 6.7.2.1p4 - verify the field type.
4916  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
4917  if (!FieldTy->isDependentType() && !FieldTy->isIntegralType()) {
4918    // Handle incomplete types with specific error.
4919    if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
4920      return true;
4921    if (FieldName)
4922      return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
4923        << FieldName << FieldTy << BitWidth->getSourceRange();
4924    return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
4925      << FieldTy << BitWidth->getSourceRange();
4926  }
4927
4928  // If the bit-width is type- or value-dependent, don't try to check
4929  // it now.
4930  if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
4931    return false;
4932
4933  llvm::APSInt Value;
4934  if (VerifyIntegerConstantExpression(BitWidth, &Value))
4935    return true;
4936
4937  if (Value != 0 && ZeroWidth)
4938    *ZeroWidth = false;
4939
4940  // Zero-width bitfield is ok for anonymous field.
4941  if (Value == 0 && FieldName)
4942    return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
4943
4944  if (Value.isSigned() && Value.isNegative()) {
4945    if (FieldName)
4946      return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
4947               << FieldName << Value.toString(10);
4948    return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
4949      << Value.toString(10);
4950  }
4951
4952  if (!FieldTy->isDependentType()) {
4953    uint64_t TypeSize = Context.getTypeSize(FieldTy);
4954    if (Value.getZExtValue() > TypeSize) {
4955      if (FieldName)
4956        return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
4957          << FieldName << (unsigned)TypeSize;
4958      return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
4959        << (unsigned)TypeSize;
4960    }
4961  }
4962
4963  return false;
4964}
4965
4966/// ActOnField - Each field of a struct/union/class is passed into this in order
4967/// to create a FieldDecl object for it.
4968Sema::DeclPtrTy Sema::ActOnField(Scope *S, DeclPtrTy TagD,
4969                                 SourceLocation DeclStart,
4970                                 Declarator &D, ExprTy *BitfieldWidth) {
4971  FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD.getAs<Decl>()),
4972                               DeclStart, D, static_cast<Expr*>(BitfieldWidth),
4973                               AS_public);
4974  return DeclPtrTy::make(Res);
4975}
4976
4977/// HandleField - Analyze a field of a C struct or a C++ data member.
4978///
4979FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
4980                             SourceLocation DeclStart,
4981                             Declarator &D, Expr *BitWidth,
4982                             AccessSpecifier AS) {
4983  IdentifierInfo *II = D.getIdentifier();
4984  SourceLocation Loc = DeclStart;
4985  if (II) Loc = D.getIdentifierLoc();
4986
4987  DeclaratorInfo *DInfo = 0;
4988  QualType T = GetTypeForDeclarator(D, S, &DInfo);
4989  if (getLangOptions().CPlusPlus)
4990    CheckExtraCXXDefaultArguments(D);
4991
4992  DiagnoseFunctionSpecifiers(D);
4993
4994  if (D.getDeclSpec().isThreadSpecified())
4995    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4996
4997  NamedDecl *PrevDecl = LookupSingleName(S, II, LookupMemberName,
4998                                         ForRedeclaration);
4999
5000  if (PrevDecl && PrevDecl->isTemplateParameter()) {
5001    // Maybe we will complain about the shadowed template parameter.
5002    DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5003    // Just pretend that we didn't see the previous declaration.
5004    PrevDecl = 0;
5005  }
5006
5007  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
5008    PrevDecl = 0;
5009
5010  bool Mutable
5011    = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
5012  SourceLocation TSSL = D.getSourceRange().getBegin();
5013  FieldDecl *NewFD
5014    = CheckFieldDecl(II, T, DInfo, Record, Loc, Mutable, BitWidth, TSSL,
5015                     AS, PrevDecl, &D);
5016  if (NewFD->isInvalidDecl() && PrevDecl) {
5017    // Don't introduce NewFD into scope; there's already something
5018    // with the same name in the same scope.
5019  } else if (II) {
5020    PushOnScopeChains(NewFD, S);
5021  } else
5022    Record->addDecl(NewFD);
5023
5024  return NewFD;
5025}
5026
5027/// \brief Build a new FieldDecl and check its well-formedness.
5028///
5029/// This routine builds a new FieldDecl given the fields name, type,
5030/// record, etc. \p PrevDecl should refer to any previous declaration
5031/// with the same name and in the same scope as the field to be
5032/// created.
5033///
5034/// \returns a new FieldDecl.
5035///
5036/// \todo The Declarator argument is a hack. It will be removed once
5037FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
5038                                DeclaratorInfo *DInfo,
5039                                RecordDecl *Record, SourceLocation Loc,
5040                                bool Mutable, Expr *BitWidth,
5041                                SourceLocation TSSL,
5042                                AccessSpecifier AS, NamedDecl *PrevDecl,
5043                                Declarator *D) {
5044  IdentifierInfo *II = Name.getAsIdentifierInfo();
5045  bool InvalidDecl = false;
5046  if (D) InvalidDecl = D->isInvalidType();
5047
5048  // If we receive a broken type, recover by assuming 'int' and
5049  // marking this declaration as invalid.
5050  if (T.isNull()) {
5051    InvalidDecl = true;
5052    T = Context.IntTy;
5053  }
5054
5055  // C99 6.7.2.1p8: A member of a structure or union may have any type other
5056  // than a variably modified type.
5057  if (T->isVariablyModifiedType()) {
5058    bool SizeIsNegative;
5059    QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
5060                                                           SizeIsNegative);
5061    if (!FixedTy.isNull()) {
5062      Diag(Loc, diag::warn_illegal_constant_array_size);
5063      T = FixedTy;
5064    } else {
5065      if (SizeIsNegative)
5066        Diag(Loc, diag::err_typecheck_negative_array_size);
5067      else
5068        Diag(Loc, diag::err_typecheck_field_variable_size);
5069      InvalidDecl = true;
5070    }
5071  }
5072
5073  // Fields can not have abstract class types
5074  if (RequireNonAbstractType(Loc, T, diag::err_abstract_type_in_decl,
5075                             AbstractFieldType))
5076    InvalidDecl = true;
5077
5078  bool ZeroWidth = false;
5079  // If this is declared as a bit-field, check the bit-field.
5080  if (BitWidth && VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) {
5081    InvalidDecl = true;
5082    DeleteExpr(BitWidth);
5083    BitWidth = 0;
5084    ZeroWidth = false;
5085  }
5086
5087  FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, DInfo,
5088                                       BitWidth, Mutable);
5089  if (InvalidDecl)
5090    NewFD->setInvalidDecl();
5091
5092  if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
5093    Diag(Loc, diag::err_duplicate_member) << II;
5094    Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5095    NewFD->setInvalidDecl();
5096  }
5097
5098  if (getLangOptions().CPlusPlus) {
5099    QualType EltTy = Context.getBaseElementType(T);
5100
5101    CXXRecordDecl* CXXRecord = cast<CXXRecordDecl>(Record);
5102
5103    if (!T->isPODType())
5104      CXXRecord->setPOD(false);
5105    if (!ZeroWidth)
5106      CXXRecord->setEmpty(false);
5107
5108    if (const RecordType *RT = EltTy->getAs<RecordType>()) {
5109      CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
5110
5111      if (!RDecl->hasTrivialConstructor())
5112        CXXRecord->setHasTrivialConstructor(false);
5113      if (!RDecl->hasTrivialCopyConstructor())
5114        CXXRecord->setHasTrivialCopyConstructor(false);
5115      if (!RDecl->hasTrivialCopyAssignment())
5116        CXXRecord->setHasTrivialCopyAssignment(false);
5117      if (!RDecl->hasTrivialDestructor())
5118        CXXRecord->setHasTrivialDestructor(false);
5119
5120      // C++ 9.5p1: An object of a class with a non-trivial
5121      // constructor, a non-trivial copy constructor, a non-trivial
5122      // destructor, or a non-trivial copy assignment operator
5123      // cannot be a member of a union, nor can an array of such
5124      // objects.
5125      // TODO: C++0x alters this restriction significantly.
5126      if (Record->isUnion()) {
5127        // We check for copy constructors before constructors
5128        // because otherwise we'll never get complaints about
5129        // copy constructors.
5130
5131        const CXXSpecialMember invalid = (CXXSpecialMember) -1;
5132
5133        CXXSpecialMember member;
5134        if (!RDecl->hasTrivialCopyConstructor())
5135          member = CXXCopyConstructor;
5136        else if (!RDecl->hasTrivialConstructor())
5137          member = CXXDefaultConstructor;
5138        else if (!RDecl->hasTrivialCopyAssignment())
5139          member = CXXCopyAssignment;
5140        else if (!RDecl->hasTrivialDestructor())
5141          member = CXXDestructor;
5142        else
5143          member = invalid;
5144
5145        if (member != invalid) {
5146          Diag(Loc, diag::err_illegal_union_member) << Name << member;
5147          DiagnoseNontrivial(RT, member);
5148          NewFD->setInvalidDecl();
5149        }
5150      }
5151    }
5152  }
5153
5154  // FIXME: We need to pass in the attributes given an AST
5155  // representation, not a parser representation.
5156  if (D)
5157    // FIXME: What to pass instead of TUScope?
5158    ProcessDeclAttributes(TUScope, NewFD, *D);
5159
5160  if (T.isObjCGCWeak())
5161    Diag(Loc, diag::warn_attribute_weak_on_field);
5162
5163  NewFD->setAccess(AS);
5164
5165  // C++ [dcl.init.aggr]p1:
5166  //   An aggregate is an array or a class (clause 9) with [...] no
5167  //   private or protected non-static data members (clause 11).
5168  // A POD must be an aggregate.
5169  if (getLangOptions().CPlusPlus &&
5170      (AS == AS_private || AS == AS_protected)) {
5171    CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
5172    CXXRecord->setAggregate(false);
5173    CXXRecord->setPOD(false);
5174  }
5175
5176  return NewFD;
5177}
5178
5179/// DiagnoseNontrivial - Given that a class has a non-trivial
5180/// special member, figure out why.
5181void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
5182  QualType QT(T, 0U);
5183  CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
5184
5185  // Check whether the member was user-declared.
5186  switch (member) {
5187  case CXXDefaultConstructor:
5188    if (RD->hasUserDeclaredConstructor()) {
5189      typedef CXXRecordDecl::ctor_iterator ctor_iter;
5190      for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){
5191        const FunctionDecl *body = 0;
5192        ci->getBody(body);
5193        if (!body ||
5194            !cast<CXXConstructorDecl>(body)->isImplicitlyDefined(Context)) {
5195          SourceLocation CtorLoc = ci->getLocation();
5196          Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5197          return;
5198        }
5199      }
5200
5201      assert(0 && "found no user-declared constructors");
5202      return;
5203    }
5204    break;
5205
5206  case CXXCopyConstructor:
5207    if (RD->hasUserDeclaredCopyConstructor()) {
5208      SourceLocation CtorLoc =
5209        RD->getCopyConstructor(Context, 0)->getLocation();
5210      Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5211      return;
5212    }
5213    break;
5214
5215  case CXXCopyAssignment:
5216    if (RD->hasUserDeclaredCopyAssignment()) {
5217      // FIXME: this should use the location of the copy
5218      // assignment, not the type.
5219      SourceLocation TyLoc = RD->getSourceRange().getBegin();
5220      Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
5221      return;
5222    }
5223    break;
5224
5225  case CXXDestructor:
5226    if (RD->hasUserDeclaredDestructor()) {
5227      SourceLocation DtorLoc = RD->getDestructor(Context)->getLocation();
5228      Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5229      return;
5230    }
5231    break;
5232  }
5233
5234  typedef CXXRecordDecl::base_class_iterator base_iter;
5235
5236  // Virtual bases and members inhibit trivial copying/construction,
5237  // but not trivial destruction.
5238  if (member != CXXDestructor) {
5239    // Check for virtual bases.  vbases includes indirect virtual bases,
5240    // so we just iterate through the direct bases.
5241    for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
5242      if (bi->isVirtual()) {
5243        SourceLocation BaseLoc = bi->getSourceRange().getBegin();
5244        Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
5245        return;
5246      }
5247
5248    // Check for virtual methods.
5249    typedef CXXRecordDecl::method_iterator meth_iter;
5250    for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
5251         ++mi) {
5252      if (mi->isVirtual()) {
5253        SourceLocation MLoc = mi->getSourceRange().getBegin();
5254        Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
5255        return;
5256      }
5257    }
5258  }
5259
5260  bool (CXXRecordDecl::*hasTrivial)() const;
5261  switch (member) {
5262  case CXXDefaultConstructor:
5263    hasTrivial = &CXXRecordDecl::hasTrivialConstructor; break;
5264  case CXXCopyConstructor:
5265    hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
5266  case CXXCopyAssignment:
5267    hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
5268  case CXXDestructor:
5269    hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
5270  default:
5271    assert(0 && "unexpected special member"); return;
5272  }
5273
5274  // Check for nontrivial bases (and recurse).
5275  for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
5276    const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
5277    assert(BaseRT && "Don't know how to handle dependent bases");
5278    CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
5279    if (!(BaseRecTy->*hasTrivial)()) {
5280      SourceLocation BaseLoc = bi->getSourceRange().getBegin();
5281      Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
5282      DiagnoseNontrivial(BaseRT, member);
5283      return;
5284    }
5285  }
5286
5287  // Check for nontrivial members (and recurse).
5288  typedef RecordDecl::field_iterator field_iter;
5289  for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
5290       ++fi) {
5291    QualType EltTy = Context.getBaseElementType((*fi)->getType());
5292    if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
5293      CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
5294
5295      if (!(EltRD->*hasTrivial)()) {
5296        SourceLocation FLoc = (*fi)->getLocation();
5297        Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
5298        DiagnoseNontrivial(EltRT, member);
5299        return;
5300      }
5301    }
5302  }
5303
5304  assert(0 && "found no explanation for non-trivial member");
5305}
5306
5307/// TranslateIvarVisibility - Translate visibility from a token ID to an
5308///  AST enum value.
5309static ObjCIvarDecl::AccessControl
5310TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
5311  switch (ivarVisibility) {
5312  default: assert(0 && "Unknown visitibility kind");
5313  case tok::objc_private: return ObjCIvarDecl::Private;
5314  case tok::objc_public: return ObjCIvarDecl::Public;
5315  case tok::objc_protected: return ObjCIvarDecl::Protected;
5316  case tok::objc_package: return ObjCIvarDecl::Package;
5317  }
5318}
5319
5320/// ActOnIvar - Each ivar field of an objective-c class is passed into this
5321/// in order to create an IvarDecl object for it.
5322Sema::DeclPtrTy Sema::ActOnIvar(Scope *S,
5323                                SourceLocation DeclStart,
5324                                DeclPtrTy IntfDecl,
5325                                Declarator &D, ExprTy *BitfieldWidth,
5326                                tok::ObjCKeywordKind Visibility) {
5327
5328  IdentifierInfo *II = D.getIdentifier();
5329  Expr *BitWidth = (Expr*)BitfieldWidth;
5330  SourceLocation Loc = DeclStart;
5331  if (II) Loc = D.getIdentifierLoc();
5332
5333  // FIXME: Unnamed fields can be handled in various different ways, for
5334  // example, unnamed unions inject all members into the struct namespace!
5335
5336  DeclaratorInfo *DInfo = 0;
5337  QualType T = GetTypeForDeclarator(D, S, &DInfo);
5338
5339  if (BitWidth) {
5340    // 6.7.2.1p3, 6.7.2.1p4
5341    if (VerifyBitField(Loc, II, T, BitWidth)) {
5342      D.setInvalidType();
5343      DeleteExpr(BitWidth);
5344      BitWidth = 0;
5345    }
5346  } else {
5347    // Not a bitfield.
5348
5349    // validate II.
5350
5351  }
5352
5353  // C99 6.7.2.1p8: A member of a structure or union may have any type other
5354  // than a variably modified type.
5355  if (T->isVariablyModifiedType()) {
5356    Diag(Loc, diag::err_typecheck_ivar_variable_size);
5357    D.setInvalidType();
5358  }
5359
5360  // Get the visibility (access control) for this ivar.
5361  ObjCIvarDecl::AccessControl ac =
5362    Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
5363                                        : ObjCIvarDecl::None;
5364  // Must set ivar's DeclContext to its enclosing interface.
5365  Decl *EnclosingDecl = IntfDecl.getAs<Decl>();
5366  DeclContext *EnclosingContext;
5367  if (ObjCImplementationDecl *IMPDecl =
5368      dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
5369    // Case of ivar declared in an implementation. Context is that of its class.
5370    ObjCInterfaceDecl* IDecl = IMPDecl->getClassInterface();
5371    assert(IDecl && "No class- ActOnIvar");
5372    EnclosingContext = cast_or_null<DeclContext>(IDecl);
5373  } else
5374    EnclosingContext = dyn_cast<DeclContext>(EnclosingDecl);
5375  assert(EnclosingContext && "null DeclContext for ivar - ActOnIvar");
5376
5377  // Construct the decl.
5378  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context,
5379                                             EnclosingContext, Loc, II, T,
5380                                             DInfo, ac, (Expr *)BitfieldWidth);
5381
5382  if (II) {
5383    NamedDecl *PrevDecl = LookupSingleName(S, II, LookupMemberName,
5384                                           ForRedeclaration);
5385    if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
5386        && !isa<TagDecl>(PrevDecl)) {
5387      Diag(Loc, diag::err_duplicate_member) << II;
5388      Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5389      NewID->setInvalidDecl();
5390    }
5391  }
5392
5393  // Process attributes attached to the ivar.
5394  ProcessDeclAttributes(S, NewID, D);
5395
5396  if (D.isInvalidType())
5397    NewID->setInvalidDecl();
5398
5399  if (II) {
5400    // FIXME: When interfaces are DeclContexts, we'll need to add
5401    // these to the interface.
5402    S->AddDecl(DeclPtrTy::make(NewID));
5403    IdResolver.AddDecl(NewID);
5404  }
5405
5406  return DeclPtrTy::make(NewID);
5407}
5408
5409void Sema::ActOnFields(Scope* S,
5410                       SourceLocation RecLoc, DeclPtrTy RecDecl,
5411                       DeclPtrTy *Fields, unsigned NumFields,
5412                       SourceLocation LBrac, SourceLocation RBrac,
5413                       AttributeList *Attr) {
5414  Decl *EnclosingDecl = RecDecl.getAs<Decl>();
5415  assert(EnclosingDecl && "missing record or interface decl");
5416
5417  // If the decl this is being inserted into is invalid, then it may be a
5418  // redeclaration or some other bogus case.  Don't try to add fields to it.
5419  if (EnclosingDecl->isInvalidDecl()) {
5420    // FIXME: Deallocate fields?
5421    return;
5422  }
5423
5424
5425  // Verify that all the fields are okay.
5426  unsigned NumNamedMembers = 0;
5427  llvm::SmallVector<FieldDecl*, 32> RecFields;
5428
5429  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
5430  for (unsigned i = 0; i != NumFields; ++i) {
5431    FieldDecl *FD = cast<FieldDecl>(Fields[i].getAs<Decl>());
5432
5433    // Get the type for the field.
5434    Type *FDTy = FD->getType().getTypePtr();
5435
5436    if (!FD->isAnonymousStructOrUnion()) {
5437      // Remember all fields written by the user.
5438      RecFields.push_back(FD);
5439    }
5440
5441    // If the field is already invalid for some reason, don't emit more
5442    // diagnostics about it.
5443    if (FD->isInvalidDecl())
5444      continue;
5445
5446    // C99 6.7.2.1p2:
5447    //   A structure or union shall not contain a member with
5448    //   incomplete or function type (hence, a structure shall not
5449    //   contain an instance of itself, but may contain a pointer to
5450    //   an instance of itself), except that the last member of a
5451    //   structure with more than one named member may have incomplete
5452    //   array type; such a structure (and any union containing,
5453    //   possibly recursively, a member that is such a structure)
5454    //   shall not be a member of a structure or an element of an
5455    //   array.
5456    if (FDTy->isFunctionType()) {
5457      // Field declared as a function.
5458      Diag(FD->getLocation(), diag::err_field_declared_as_function)
5459        << FD->getDeclName();
5460      FD->setInvalidDecl();
5461      EnclosingDecl->setInvalidDecl();
5462      continue;
5463    } else if (FDTy->isIncompleteArrayType() && i == NumFields - 1 &&
5464               Record && Record->isStruct()) {
5465      // Flexible array member.
5466      if (NumNamedMembers < 1) {
5467        Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
5468          << FD->getDeclName();
5469        FD->setInvalidDecl();
5470        EnclosingDecl->setInvalidDecl();
5471        continue;
5472      }
5473      // Okay, we have a legal flexible array member at the end of the struct.
5474      if (Record)
5475        Record->setHasFlexibleArrayMember(true);
5476    } else if (!FDTy->isDependentType() &&
5477               RequireCompleteType(FD->getLocation(), FD->getType(),
5478                                   diag::err_field_incomplete)) {
5479      // Incomplete type
5480      FD->setInvalidDecl();
5481      EnclosingDecl->setInvalidDecl();
5482      continue;
5483    } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
5484      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
5485        // If this is a member of a union, then entire union becomes "flexible".
5486        if (Record && Record->isUnion()) {
5487          Record->setHasFlexibleArrayMember(true);
5488        } else {
5489          // If this is a struct/class and this is not the last element, reject
5490          // it.  Note that GCC supports variable sized arrays in the middle of
5491          // structures.
5492          if (i != NumFields-1)
5493            Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
5494              << FD->getDeclName() << FD->getType();
5495          else {
5496            // We support flexible arrays at the end of structs in
5497            // other structs as an extension.
5498            Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
5499              << FD->getDeclName();
5500            if (Record)
5501              Record->setHasFlexibleArrayMember(true);
5502          }
5503        }
5504      }
5505      if (Record && FDTTy->getDecl()->hasObjectMember())
5506        Record->setHasObjectMember(true);
5507    } else if (FDTy->isObjCInterfaceType()) {
5508      /// A field cannot be an Objective-c object
5509      Diag(FD->getLocation(), diag::err_statically_allocated_object);
5510      FD->setInvalidDecl();
5511      EnclosingDecl->setInvalidDecl();
5512      continue;
5513    } else if (getLangOptions().ObjC1 &&
5514               getLangOptions().getGCMode() != LangOptions::NonGC &&
5515               Record &&
5516               (FD->getType()->isObjCObjectPointerType() ||
5517                FD->getType().isObjCGCStrong()))
5518      Record->setHasObjectMember(true);
5519    // Keep track of the number of named members.
5520    if (FD->getIdentifier())
5521      ++NumNamedMembers;
5522  }
5523
5524  // Okay, we successfully defined 'Record'.
5525  if (Record) {
5526    Record->completeDefinition(Context);
5527  } else {
5528    ObjCIvarDecl **ClsFields =
5529      reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
5530    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
5531      ID->setIVarList(ClsFields, RecFields.size(), Context);
5532      ID->setLocEnd(RBrac);
5533      // Add ivar's to class's DeclContext.
5534      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
5535        ClsFields[i]->setLexicalDeclContext(ID);
5536        ID->addDecl(ClsFields[i]);
5537      }
5538      // Must enforce the rule that ivars in the base classes may not be
5539      // duplicates.
5540      if (ID->getSuperClass()) {
5541        for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
5542             IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
5543          ObjCIvarDecl* Ivar = (*IVI);
5544
5545          if (IdentifierInfo *II = Ivar->getIdentifier()) {
5546            ObjCIvarDecl* prevIvar =
5547              ID->getSuperClass()->lookupInstanceVariable(II);
5548            if (prevIvar) {
5549              Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
5550              Diag(prevIvar->getLocation(), diag::note_previous_declaration);
5551            }
5552          }
5553        }
5554      }
5555    } else if (ObjCImplementationDecl *IMPDecl =
5556                  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
5557      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
5558      for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
5559        // Ivar declared in @implementation never belongs to the implementation.
5560        // Only it is in implementation's lexical context.
5561        ClsFields[I]->setLexicalDeclContext(IMPDecl);
5562      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
5563    }
5564  }
5565
5566  if (Attr)
5567    ProcessDeclAttributeList(S, Record, Attr);
5568}
5569
5570EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
5571                                          EnumConstantDecl *LastEnumConst,
5572                                          SourceLocation IdLoc,
5573                                          IdentifierInfo *Id,
5574                                          ExprArg val) {
5575  Expr *Val = (Expr *)val.get();
5576
5577  llvm::APSInt EnumVal(32);
5578  QualType EltTy;
5579  if (Val) {
5580    if (Val->isTypeDependent())
5581      EltTy = Context.DependentTy;
5582    else {
5583      // Make sure to promote the operand type to int.
5584      UsualUnaryConversions(Val);
5585      if (Val != val.get()) {
5586        val.release();
5587        val = Val;
5588      }
5589
5590      // C99 6.7.2.2p2: Make sure we have an integer constant expression.
5591      SourceLocation ExpLoc;
5592      if (!Val->isValueDependent() &&
5593          VerifyIntegerConstantExpression(Val, &EnumVal)) {
5594        Val = 0;
5595      } else {
5596        EltTy = Val->getType();
5597      }
5598    }
5599  }
5600
5601  if (!Val) {
5602    if (LastEnumConst) {
5603      // Assign the last value + 1.
5604      EnumVal = LastEnumConst->getInitVal();
5605      ++EnumVal;
5606
5607      // Check for overflow on increment.
5608      if (EnumVal < LastEnumConst->getInitVal())
5609        Diag(IdLoc, diag::warn_enum_value_overflow);
5610
5611      EltTy = LastEnumConst->getType();
5612    } else {
5613      // First value, set to zero.
5614      EltTy = Context.IntTy;
5615      EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
5616    }
5617  }
5618
5619  assert(!EltTy.isNull() && "Enum constant with NULL type");
5620
5621  val.release();
5622  return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
5623                                  Val, EnumVal);
5624}
5625
5626
5627Sema::DeclPtrTy Sema::ActOnEnumConstant(Scope *S, DeclPtrTy theEnumDecl,
5628                                        DeclPtrTy lastEnumConst,
5629                                        SourceLocation IdLoc,
5630                                        IdentifierInfo *Id,
5631                                        SourceLocation EqualLoc, ExprTy *val) {
5632  EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl.getAs<Decl>());
5633  EnumConstantDecl *LastEnumConst =
5634    cast_or_null<EnumConstantDecl>(lastEnumConst.getAs<Decl>());
5635  Expr *Val = static_cast<Expr*>(val);
5636
5637  // The scope passed in may not be a decl scope.  Zip up the scope tree until
5638  // we find one that is.
5639  S = getNonFieldDeclScope(S);
5640
5641  // Verify that there isn't already something declared with this name in this
5642  // scope.
5643  NamedDecl *PrevDecl = LookupSingleName(S, Id, LookupOrdinaryName);
5644  if (PrevDecl && PrevDecl->isTemplateParameter()) {
5645    // Maybe we will complain about the shadowed template parameter.
5646    DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
5647    // Just pretend that we didn't see the previous declaration.
5648    PrevDecl = 0;
5649  }
5650
5651  if (PrevDecl) {
5652    // When in C++, we may get a TagDecl with the same name; in this case the
5653    // enum constant will 'hide' the tag.
5654    assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
5655           "Received TagDecl when not in C++!");
5656    if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
5657      if (isa<EnumConstantDecl>(PrevDecl))
5658        Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
5659      else
5660        Diag(IdLoc, diag::err_redefinition) << Id;
5661      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5662      if (Val) Val->Destroy(Context);
5663      return DeclPtrTy();
5664    }
5665  }
5666
5667  EnumConstantDecl *New = CheckEnumConstant(TheEnumDecl, LastEnumConst,
5668                                            IdLoc, Id, Owned(Val));
5669
5670  // Register this decl in the current scope stack.
5671  if (New)
5672    PushOnScopeChains(New, S);
5673
5674  return DeclPtrTy::make(New);
5675}
5676
5677void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
5678                         SourceLocation RBraceLoc, DeclPtrTy EnumDeclX,
5679                         DeclPtrTy *Elements, unsigned NumElements,
5680                         Scope *S, AttributeList *Attr) {
5681  EnumDecl *Enum = cast<EnumDecl>(EnumDeclX.getAs<Decl>());
5682  QualType EnumType = Context.getTypeDeclType(Enum);
5683
5684  if (Attr)
5685    ProcessDeclAttributeList(S, Enum, Attr);
5686
5687  // TODO: If the result value doesn't fit in an int, it must be a long or long
5688  // long value.  ISO C does not support this, but GCC does as an extension,
5689  // emit a warning.
5690  unsigned IntWidth = Context.Target.getIntWidth();
5691  unsigned CharWidth = Context.Target.getCharWidth();
5692  unsigned ShortWidth = Context.Target.getShortWidth();
5693
5694  // Verify that all the values are okay, compute the size of the values, and
5695  // reverse the list.
5696  unsigned NumNegativeBits = 0;
5697  unsigned NumPositiveBits = 0;
5698
5699  // Keep track of whether all elements have type int.
5700  bool AllElementsInt = true;
5701
5702  for (unsigned i = 0; i != NumElements; ++i) {
5703    EnumConstantDecl *ECD =
5704      cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
5705    if (!ECD) continue;  // Already issued a diagnostic.
5706
5707    // If the enum value doesn't fit in an int, emit an extension warning.
5708    const llvm::APSInt &InitVal = ECD->getInitVal();
5709    assert(InitVal.getBitWidth() >= IntWidth &&
5710           "Should have promoted value to int");
5711    if (InitVal.getBitWidth() > IntWidth) {
5712      llvm::APSInt V(InitVal);
5713      V.trunc(IntWidth);
5714      V.extend(InitVal.getBitWidth());
5715      if (V != InitVal)
5716        Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
5717          << InitVal.toString(10);
5718    }
5719
5720    // Keep track of the size of positive and negative values.
5721    if (InitVal.isUnsigned() || InitVal.isNonNegative())
5722      NumPositiveBits = std::max(NumPositiveBits,
5723                                 (unsigned)InitVal.getActiveBits());
5724    else
5725      NumNegativeBits = std::max(NumNegativeBits,
5726                                 (unsigned)InitVal.getMinSignedBits());
5727
5728    // Keep track of whether every enum element has type int (very commmon).
5729    if (AllElementsInt)
5730      AllElementsInt = ECD->getType() == Context.IntTy;
5731  }
5732
5733  // Figure out the type that should be used for this enum.
5734  // FIXME: Support -fshort-enums.
5735  QualType BestType;
5736  unsigned BestWidth;
5737
5738  bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
5739
5740  if (NumNegativeBits) {
5741    // If there is a negative value, figure out the smallest integer type (of
5742    // int/long/longlong) that fits.
5743    // If it's packed, check also if it fits a char or a short.
5744    if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
5745        BestType = Context.SignedCharTy;
5746        BestWidth = CharWidth;
5747    } else if (Packed && NumNegativeBits <= ShortWidth &&
5748               NumPositiveBits < ShortWidth) {
5749        BestType = Context.ShortTy;
5750        BestWidth = ShortWidth;
5751    }
5752    else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5753      BestType = Context.IntTy;
5754      BestWidth = IntWidth;
5755    } else {
5756      BestWidth = Context.Target.getLongWidth();
5757
5758      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
5759        BestType = Context.LongTy;
5760      else {
5761        BestWidth = Context.Target.getLongLongWidth();
5762
5763        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5764          Diag(Enum->getLocation(), diag::warn_enum_too_large);
5765        BestType = Context.LongLongTy;
5766      }
5767    }
5768  } else {
5769    // If there is no negative value, figure out which of uint, ulong, ulonglong
5770    // fits.
5771    // If it's packed, check also if it fits a char or a short.
5772    if (Packed && NumPositiveBits <= CharWidth) {
5773        BestType = Context.UnsignedCharTy;
5774        BestWidth = CharWidth;
5775    } else if (Packed && NumPositiveBits <= ShortWidth) {
5776        BestType = Context.UnsignedShortTy;
5777        BestWidth = ShortWidth;
5778    }
5779    else if (NumPositiveBits <= IntWidth) {
5780      BestType = Context.UnsignedIntTy;
5781      BestWidth = IntWidth;
5782    } else if (NumPositiveBits <=
5783               (BestWidth = Context.Target.getLongWidth())) {
5784      BestType = Context.UnsignedLongTy;
5785    } else {
5786      BestWidth = Context.Target.getLongLongWidth();
5787      assert(NumPositiveBits <= BestWidth &&
5788             "How could an initializer get larger than ULL?");
5789      BestType = Context.UnsignedLongLongTy;
5790    }
5791  }
5792
5793  // Loop over all of the enumerator constants, changing their types to match
5794  // the type of the enum if needed.
5795  for (unsigned i = 0; i != NumElements; ++i) {
5796    EnumConstantDecl *ECD =
5797      cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
5798    if (!ECD) continue;  // Already issued a diagnostic.
5799
5800    // Standard C says the enumerators have int type, but we allow, as an
5801    // extension, the enumerators to be larger than int size.  If each
5802    // enumerator value fits in an int, type it as an int, otherwise type it the
5803    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
5804    // that X has type 'int', not 'unsigned'.
5805    if (ECD->getType() == Context.IntTy) {
5806      // Make sure the init value is signed.
5807      llvm::APSInt IV = ECD->getInitVal();
5808      IV.setIsSigned(true);
5809      ECD->setInitVal(IV);
5810
5811      if (getLangOptions().CPlusPlus)
5812        // C++ [dcl.enum]p4: Following the closing brace of an
5813        // enum-specifier, each enumerator has the type of its
5814        // enumeration.
5815        ECD->setType(EnumType);
5816      continue;  // Already int type.
5817    }
5818
5819    // Determine whether the value fits into an int.
5820    llvm::APSInt InitVal = ECD->getInitVal();
5821    bool FitsInInt;
5822    if (InitVal.isUnsigned() || !InitVal.isNegative())
5823      FitsInInt = InitVal.getActiveBits() < IntWidth;
5824    else
5825      FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
5826
5827    // If it fits into an integer type, force it.  Otherwise force it to match
5828    // the enum decl type.
5829    QualType NewTy;
5830    unsigned NewWidth;
5831    bool NewSign;
5832    if (FitsInInt) {
5833      NewTy = Context.IntTy;
5834      NewWidth = IntWidth;
5835      NewSign = true;
5836    } else if (ECD->getType() == BestType) {
5837      // Already the right type!
5838      if (getLangOptions().CPlusPlus)
5839        // C++ [dcl.enum]p4: Following the closing brace of an
5840        // enum-specifier, each enumerator has the type of its
5841        // enumeration.
5842        ECD->setType(EnumType);
5843      continue;
5844    } else {
5845      NewTy = BestType;
5846      NewWidth = BestWidth;
5847      NewSign = BestType->isSignedIntegerType();
5848    }
5849
5850    // Adjust the APSInt value.
5851    InitVal.extOrTrunc(NewWidth);
5852    InitVal.setIsSigned(NewSign);
5853    ECD->setInitVal(InitVal);
5854
5855    // Adjust the Expr initializer and type.
5856    if (ECD->getInitExpr())
5857      ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy,
5858                                                      CastExpr::CK_IntegralCast,
5859                                                      ECD->getInitExpr(),
5860                                                      /*isLvalue=*/false));
5861    if (getLangOptions().CPlusPlus)
5862      // C++ [dcl.enum]p4: Following the closing brace of an
5863      // enum-specifier, each enumerator has the type of its
5864      // enumeration.
5865      ECD->setType(EnumType);
5866    else
5867      ECD->setType(NewTy);
5868  }
5869
5870  Enum->completeDefinition(Context, BestType);
5871}
5872
5873Sema::DeclPtrTy Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
5874                                            ExprArg expr) {
5875  StringLiteral *AsmString = cast<StringLiteral>(expr.takeAs<Expr>());
5876
5877  FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
5878                                                   Loc, AsmString);
5879  CurContext->addDecl(New);
5880  return DeclPtrTy::make(New);
5881}
5882
5883void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
5884                             SourceLocation PragmaLoc,
5885                             SourceLocation NameLoc) {
5886  Decl *PrevDecl = LookupSingleName(TUScope, Name, LookupOrdinaryName);
5887
5888  if (PrevDecl) {
5889    PrevDecl->addAttr(::new (Context) WeakAttr());
5890  } else {
5891    (void)WeakUndeclaredIdentifiers.insert(
5892      std::pair<IdentifierInfo*,WeakInfo>
5893        (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
5894  }
5895}
5896
5897void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
5898                                IdentifierInfo* AliasName,
5899                                SourceLocation PragmaLoc,
5900                                SourceLocation NameLoc,
5901                                SourceLocation AliasNameLoc) {
5902  Decl *PrevDecl = LookupSingleName(TUScope, AliasName, LookupOrdinaryName);
5903  WeakInfo W = WeakInfo(Name, NameLoc);
5904
5905  if (PrevDecl) {
5906    if (!PrevDecl->hasAttr<AliasAttr>())
5907      if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
5908        DeclApplyPragmaWeak(TUScope, ND, W);
5909  } else {
5910    (void)WeakUndeclaredIdentifiers.insert(
5911      std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
5912  }
5913}
5914