SemaDecl.cpp revision 23a48cc69e7ed4f219996a8864cb7d3f24f1157f
15f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
25f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
35f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//                     The LLVM Compiler Infrastructure
45f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
50bc735ffcfb223c0186419547abaa5c84482663eChris Lattner// This file is distributed under the University of Illinois Open Source
60bc735ffcfb223c0186419547abaa5c84482663eChris Lattner// License. See LICENSE.TXT for details.
75f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
85f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//===----------------------------------------------------------------------===//
95f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
105f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//  This file implements semantic analysis for declarations.
115f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
125f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//===----------------------------------------------------------------------===//
135f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
145f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "Sema.h"
15bd3606426d389370616126af969904ec493cb105Chris Lattner#include "clang/AST/APValue.h"
165f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "clang/AST/ASTConsumer.h"
173d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman#include "clang/AST/ASTContext.h"
180dbe227feccf6a8dbadfff8ca3f80416b7bf2f28Daniel Dunbar#include "clang/AST/DeclObjC.h"
196c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne#include "clang/AST/DeclTemplate.h"
204c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall#include "clang/AST/ExprCXX.h"
21af2f62ce32e462f256855cd24b06dec4755d2827Daniel Dunbar#include "clang/Parse/DeclSpec.h"
228c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne#include "clang/Basic/TargetInfo.h"
2382d0a418c8699fc6f4a9417457ffe93d43bba1c1Anton Korobeynikov#include "clang/Basic/SourceManager.h"
2406057cef0bcd7804e80f3ce2bbe352178396c715Chandler Carruth// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
255f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "clang/Lex/Preprocessor.h"
26687cc4a850b59116efee061018f0d8df50728b82Ken Dyck#include "clang/Lex/HeaderSearch.h"
27c4a1dea2dc56bd1357ec91b829a0b9e68229a13eDaniel Dunbar#include "llvm/ADT/SmallSet.h"
2821ef7ae45c8b91f23cf5eab2263421bb398a644bChris Lattner#include "llvm/ADT/STLExtras.h"
29af896897f7485176f43d40c4adced7efb0fb2b06Douglas Gregor#include <algorithm>
3014110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne#include <functional>
311a5e0d7f18485e4fb958f96dcddff3e4486a4069Anders Carlssonusing namespace clang;
32a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola
332c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner/// getDeclName - Return a pretty name for the specified decl if possible, or
348bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman/// an empty string if not.  This is used for pretty crash reporting.
355f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencerstd::string Sema::getDeclName(DeclPtrTy d) {
36e9b7d8ace8674585818990cff585daae7745bd88Steve Naroff  Decl *D = d.getAs<Decl>();
37ec9426ca6039279bcc99bc2c625bb2abe4f0353dNate Begeman  if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(D))
38bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner    return DN->getQualifiedNameAsString();
395f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  return "";
40d5b8902c0329d80a216803b58dc3b689349a0c11Chris Lattner}
416374c3307e2d73348f7b8cc73eeeb0998ad0ac94John McCall
42c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael EspindolaSema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(DeclPtrTy Ptr) {
4320ff3108fcd2c3bd734dc79efc22ebaa090abd41Anton Korobeynikov  return DeclGroupPtrTy::make(DeclGroupRef(Ptr.getAs<Decl>()));
446ba728d9687b2617793f5afd410650a8d6c71080Gabor Greif}
4578f7ece00e2ddfb64d4ed72a7be770b5b9b805e3Chris Lattner
465f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer/// \brief If the identifier refers to a type name within this scope,
475f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer/// return the declaration of that type.
485f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer///
4977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge/// This routine performs ordinary name lookup of the identifier II
5077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge/// within the given scope, with optional C++ scope specifier SS, to
51f16aa103d3afd42fbca2ab346f191bf745cec092John McCall/// determine whether the name refers to a type. If so, returns an
52bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor/// opaque pointer (actually a QualType) corresponding to that
53f16aa103d3afd42fbca2ab346f191bf745cec092John McCall/// type. Otherwise, returns NULL.
54f16aa103d3afd42fbca2ab346f191bf745cec092John McCall///
55f16aa103d3afd42fbca2ab346f191bf745cec092John McCall/// If name lookup results in an ambiguity, this routine will complain
56f16aa103d3afd42fbca2ab346f191bf745cec092John McCall/// and then return NULL.
57f16aa103d3afd42fbca2ab346f191bf745cec092John McCallSema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
58f16aa103d3afd42fbca2ab346f191bf745cec092John McCall                                Scope *S, const CXXScopeSpec *SS) {
59f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  // C++ [temp.res]p3:
60f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  //   A qualified-id that refers to a type and in which the
61f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  //   nested-name-specifier depends on a template-parameter (14.6.2)
625f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  //   shall be prefixed by the keyword typename to indicate that the
632811ccf48d6d898c42cc4cfad37abedb36236d20Chandler Carruth  //   qualified-id denotes a type, forming an
64468ec6c0266e48fccb26ce50d5b915c645bb3c7bJohn McCall  //   elaborated-type-specifier (7.1.5.3).
65d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie  //
66d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall  // We therefore do not perform any name lookup up SS is a dependent
67468ec6c0266e48fccb26ce50d5b915c645bb3c7bJohn McCall  // scope name. FIXME: we will need to perform a special kind of
68f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  // lookup if the scope specifier names a member of the current
6908d4792bb5d9e0e7f122c6273636807029c06aaaDaniel Dunbar  // instantiation.
703d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman  if (SS && isDependentScopeSpecifier(*SS))
716c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne    return 0;
726c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne
736c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne  NamedDecl *IIDecl = 0;
74673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar  LookupResult Result = LookupParsedName(S, SS, &II, LookupOrdinaryName,
75673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar                                         false, false);
76d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall  switch (Result.getKind()) {
77d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall  case LookupResult::NotFound:
7860be607e5d71627bf3dab8f51c3fdca74267c692David Chisnall  case LookupResult::FoundOverloaded:
798c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne    return 0;
808c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne
818c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne  case LookupResult::AmbiguousBaseSubobjectTypes:
826c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne  case LookupResult::AmbiguousBaseSubobjects:
836c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne  case LookupResult::AmbiguousReference: {
84e8b9f5b8ea60983c4a74cb8b63879616b914b65aSanjiv Gupta    // Look to see if we have a type anywhere in the list of results.
853d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman    for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
863d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman         Res != ResEnd; ++Res) {
870b5c4fc2ae3b503c2b1f354bf52b718aa50a6aeeDan Gohman      if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
880b5c4fc2ae3b503c2b1f354bf52b718aa50a6aeeDan Gohman        if (!IIDecl ||
893d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman            (*Res)->getLocation().getRawEncoding() <
90e8ba8d78a258ec992d3521eebdae8324db777b14Nick Lewycky              IIDecl->getLocation().getRawEncoding())
91e8ba8d78a258ec992d3521eebdae8324db777b14Nick Lewycky          IIDecl = *Res;
92e8ba8d78a258ec992d3521eebdae8324db777b14Nick Lewycky      }
93e8ba8d78a258ec992d3521eebdae8324db777b14Nick Lewycky    }
94e8ba8d78a258ec992d3521eebdae8324db777b14Nick Lewycky
95d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall    if (!IIDecl) {
96d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall      // None of the entities we found is a type, so there is no way
975936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall      // to even assume that the result is a type. In this case, don't
98f85e193739c953358c865005855253af4f68a497John McCall      // complain about the ambiguity. The parser will either try to
99f85e193739c953358c865005855253af4f68a497John McCall      // perform this lookup again (e.g., as an object name), which
100f85e193739c953358c865005855253af4f68a497John McCall      // will produce the ambiguity, or will complain that it expected
101f85e193739c953358c865005855253af4f68a497John McCall      // a type name.
1025936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall      Result.Destroy();
1035936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall      return 0;
1040774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall    }
1050774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall
1060774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall    // We found a type within the ambiguous lookup; diagnose the
1070774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall    // ambiguity and then return that type. This might be the right
108bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor    // answer, or it might not be, but it suppresses any attempt to
10934695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall    // perform the name lookup again.
110bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor    DiagnoseAmbiguousLookup(Result, DeclarationName(&II), NameLoc);
111bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor    break;
1125936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall  }
1135936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall
1145936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall  case LookupResult::Found:
1152b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris Lattner    IIDecl = Result.getAsDecl();
1162b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris Lattner    break;
1172b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris Lattner  }
118e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne
1198c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne  if (IIDecl) {
1206c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne    QualType T;
1210628b724ff68105dc88af00a39f859447f22981eTed Kremenek
122f16aa103d3afd42fbca2ab346f191bf745cec092John McCall    if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
1234376c85fb0ac9e7fd779d246efc77e1169179138Dan Gohman      // Check whether we can use this type
124815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek      (void)DiagnoseUseOfDecl(IIDecl, NameLoc);
125f85e193739c953358c865005855253af4f68a497John McCall
126f85e193739c953358c865005855253af4f68a497John McCall      T = Context.getTypeDeclType(TD);
127815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek    } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
128815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek      // Check whether we can use this interface.
1290d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnall      (void)DiagnoseUseOfDecl(IIDecl, NameLoc);
1300d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnall
131e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne      T = Context.getObjCInterfaceType(IDecl);
1320d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnall    } else
133e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne      return 0;
1340d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnall
1350d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnall    if (SS)
1368c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne      T = getQualifiedNameType(*SS, T);
1378c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne
1388c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne    return T.getAsOpaquePtr();
1398c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne  }
1406c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne
1416c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne  return 0;
1426c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne}
1436c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne
144815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek/// isTagName() - This method is called *for error recovery purposes only*
14582227ff4eb665bbf41720ebdc0dc9215a86ba838Chris Lattner/// to determine if the specified name is a valid tag name ("struct foo").  If
1466c6bda3b0b1d8adaac2ba3f4da7056e9f1eef52eEli Friedman/// so, this returns the TST for the tag corresponding to it (TST_enum,
147efb0fa9e11f75af51744a6159530ef7cc8efa24aDaniel Dunbar/// TST_union, TST_struct, TST_class).  This is used to diagnose cases in C
148e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne/// where the user forgot to specify the tag.
149e926523105dd2604ccd5c101605dea43c5269965Peter CollingbourneDeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
150208ff5e8a073de2a5d15cbe03cab8a4c0d935e28Daniel Dunbar  // Do a tag name lookup in this scope.
1516bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  LookupResult R = LookupName(S, &II, LookupTagName, false, false);
1526bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  if (R.getKind() == LookupResult::Found)
15377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    if (const TagDecl *TD = dyn_cast<TagDecl>(R.getAsDecl())) {
1540269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar      switch (TD->getTagKind()) {
155744016dde06fcffd50931e94a98c850f8b12cd87John McCall      case TagDecl::TK_struct: return DeclSpec::TST_struct;
156b25938303de0976b9f189363d43033e5788e3d36John McCall      case TagDecl::TK_union:  return DeclSpec::TST_union;
157b25938303de0976b9f189363d43033e5788e3d36John McCall      case TagDecl::TK_class:  return DeclSpec::TST_class;
158744016dde06fcffd50931e94a98c850f8b12cd87John McCall      case TagDecl::TK_enum:   return DeclSpec::TST_enum;
159744016dde06fcffd50931e94a98c850f8b12cd87John McCall      }
1605ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky    }
1615ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky
1623dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky  return DeclSpec::TST_unspecified;
163f391dbe39dca85f2a2c6ea558811dacc571c223eDevang Patel}
164f391dbe39dca85f2a2c6ea558811dacc571c223eDevang Patel
165f391dbe39dca85f2a2c6ea558811dacc571c223eDevang Patel
166f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel Dunbar
167f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel DunbarDeclContext *Sema::getContainingDC(DeclContext *DC) {
168e80d56771736c85fd8365c394a6731923b17e91dDevang Patel  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
169e80d56771736c85fd8365c394a6731923b17e91dDevang Patel    // A C++ out-of-line method will return to the file declaration context.
170e80d56771736c85fd8365c394a6731923b17e91dDevang Patel    if (MD->isOutOfLineDefinition())
171e80d56771736c85fd8365c394a6731923b17e91dDevang Patel      return MD->getLexicalDeclContext();
172e80d56771736c85fd8365c394a6731923b17e91dDevang Patel
173e80d56771736c85fd8365c394a6731923b17e91dDevang Patel    // A C++ inline method is parsed *after* the topmost class it was declared
174e80d56771736c85fd8365c394a6731923b17e91dDevang Patel    // in is fully parsed (it's "complete").
1753d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman    // The parsing of a C++ inline method happens at the declaration context of
1763d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman    // the topmost (non-nested) class it is lexically declared in.
1773d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman    assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
1783d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman    DC = MD->getParent();
1793d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman    while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1803d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman      DC = RD;
1813d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman
1823d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman    // Return the declaration context of the topmost class the inline method is
1833d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman    // declared in.
1843d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman    return DC;
1853d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman  }
1866374c3307e2d73348f7b8cc73eeeb0998ad0ac94John McCall
187bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor  if (isa<ObjCMethodDecl>(DC))
1886374c3307e2d73348f7b8cc73eeeb0998ad0ac94John McCall    return Context.getTranslationUnitDecl();
1896374c3307e2d73348f7b8cc73eeeb0998ad0ac94John McCall
1905f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  return DC->getLexicalParent();
191d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie}
19232096695c76033a6b0b1747c439f7378a11e8312John McCall
19332096695c76033a6b0b1747c439f7378a11e8312John McCallvoid Sema::PushDeclContext(Scope *S, DeclContext *DC) {
19432096695c76033a6b0b1747c439f7378a11e8312John McCall  assert(getContainingDC(DC) == CurContext &&
195488e993a135ce700b982bf099c3d6b856301d642Daniel Dunbar      "The next DeclContext should be lexically contained in the current one.");
1962c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner  CurContext = DC;
19790df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar  S->setEntity(DC);
19890df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar}
19990df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar
20090df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbarvoid Sema::PopDeclContext() {
201d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie  assert(CurContext && "DeclContext imbalance!");
20256b8001b42bd603ef593e3cb278d8b9b9ba26ca9Daniel Dunbar
2032c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner  CurContext = getContainingDC(CurContext);
2040a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner}
2050a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner
2062c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner/// \brief Determine whether we allow overloading of the function
20758c3f9ec11cbe852a518bf2f83af46f938b7b852Chris Lattner/// PrevDecl with another declaration.
208488e993a135ce700b982bf099c3d6b856301d642Daniel Dunbar///
209c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner/// This routine determines whether overloading is possible, not
21090df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar/// whether some new function is actually an overload. It will return
21190df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar/// true in C++ (where we can always provide overloads) or, as an
21290df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar/// extension, in C when the previous function is already an
21390df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar/// overloaded function declaration or has the "overloadable"
214d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie/// attribute.
21556b8001b42bd603ef593e3cb278d8b9b9ba26ca9Daniel Dunbarstatic bool AllowOverloadingOfFunction(Decl *PrevDecl, ASTContext &Context) {
216c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner  if (Context.getLangOptions().CPlusPlus)
2170a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner    return true;
218c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner
219c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner  if (isa<OverloadedFunctionDecl>(PrevDecl))
220bc8d40d85f3fa1e34569834916f18fecaa635152John McCall    return true;
221bc8d40d85f3fa1e34569834916f18fecaa635152John McCall
222bc8d40d85f3fa1e34569834916f18fecaa635152John McCall  return PrevDecl->getAttr<OverloadableAttr>() != 0;
223bc8d40d85f3fa1e34569834916f18fecaa635152John McCall}
2241eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2250ffeaad72cb335b926b064379be4c9886bbff004Anders Carlsson/// Add this decl to the scope shadowed decl chains.
22604d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbarvoid Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
227df102fcb978588d5edbc661fb5da0b6922f9ab1cChris Lattner  // Move up the scope chain until we find the nearest enclosing
2287e714cd931fa3a90bfd728318a92485aa3e95748Daniel Dunbar  // non-transparent context. The declaration will be introduced into this
2296ab187a49a42de6d351248d8a6e0206e39743a0cDaniel Dunbar  // scope.
2307e714cd931fa3a90bfd728318a92485aa3e95748Daniel Dunbar  while (S->getEntity() &&
2316ab187a49a42de6d351248d8a6e0206e39743a0cDaniel Dunbar         ((DeclContext *)S->getEntity())->isTransparentContext())
232af14603ca61757cf4361b583b45639a04c57e651John McCall    S = S->getParent();
233af14603ca61757cf4361b583b45639a04c57e651John McCall
234c7c9058f4977ef4584d68718e23f34504b150ef4Fariborz Jahanian  S->AddDecl(DeclPtrTy::make(D));
235c7c9058f4977ef4584d68718e23f34504b150ef4Fariborz Jahanian
2367cd2e93125e2f3b6ca01b24ed0c3fd7e94683fd9Fariborz Jahanian  // Add scoped declarations into their context, so that they can be
2377cd2e93125e2f3b6ca01b24ed0c3fd7e94683fd9Fariborz Jahanian  // found later. Declarations without a context won't be inserted
238cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // into any context.
239cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  CurContext->addDecl(Context, D);
240cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
241cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // C++ [basic.scope]p4:
242fa2e99f72f9bfe2270ea8caf76d0eef11c45259fAnders Carlsson  //   -- exactly one declaration shall declare a class name or
2430ffeaad72cb335b926b064379be4c9886bbff004Anders Carlsson  //   enumeration name that is not a typedef name and the other
244cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  //   declarations shall all refer to the same object or
245279b5eb6910d64a293e9c0e2887a05c65d8737d7John McCall  //   enumerator, or all refer to functions and function templates;
246279b5eb6910d64a293e9c0e2887a05c65d8737d7John McCall  //   in this case the class name or enumeration name is hidden.
247279b5eb6910d64a293e9c0e2887a05c65d8737d7John McCall  if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2489a86a137b0872bad25161fb3408a71d919638757Anders Carlsson    // We are pushing the name of a tag (enum or class).
2499a86a137b0872bad25161fb3408a71d919638757Anders Carlsson    if (CurContext->getLookupContext()
2509a86a137b0872bad25161fb3408a71d919638757Anders Carlsson          == TD->getDeclContext()->getLookupContext()) {
2519a86a137b0872bad25161fb3408a71d919638757Anders Carlsson      // We're pushing the tag into the current context, which might
252cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall      // require some reshuffling in the identifier resolver.
253cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall      IdentifierResolver::iterator
254cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall        I = IdResolver.begin(TD->getDeclName()),
255cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall        IEnd = IdResolver.end();
2567a536907da776bdc47a704e7cafd641e8150e653John McCall      if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
2577a536907da776bdc47a704e7cafd641e8150e653John McCall        NamedDecl *PrevDecl = *I;
2587a536907da776bdc47a704e7cafd641e8150e653John McCall        for (; I != IEnd && isDeclInScope(*I, CurContext, S);
259cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall             PrevDecl = *I, ++I) {
260f502d93b0ea970bfbd897e657f8d940a20984de2Anders Carlsson          if (TD->declarationReplaces(*I)) {
261cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall            // This is a redeclaration. Remove it from the chain and
262cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall            // break out, so that we'll add in the shadowed
263cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall            // declaration.
264cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall            S->RemoveDecl(DeclPtrTy::make(*I));
2654421d2b341d041df44013769f23c306308bbab83Douglas Gregor            if (PrevDecl == *I) {
266cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall              IdResolver.RemoveDecl(*I);
267cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall              IdResolver.AddDecl(TD);
268cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall              return;
269cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall            } else {
270cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall              IdResolver.RemoveDecl(*I);
271cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall              break;
272cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall            }
273cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall          }
274cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall        }
2757a536907da776bdc47a704e7cafd641e8150e653John McCall
276cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall        // There is already a declaration with the same name in the same
277cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall        // scope, which is not a tag declaration. It must be found
278cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall        // before we find the new declaration, so insert the new
2797a536907da776bdc47a704e7cafd641e8150e653John McCall        // declaration at the end of the chain.
2807a536907da776bdc47a704e7cafd641e8150e653John McCall        IdResolver.AddShadowedDecl(TD, PrevDecl);
2817a536907da776bdc47a704e7cafd641e8150e653John McCall
2827a536907da776bdc47a704e7cafd641e8150e653John McCall        return;
2837a536907da776bdc47a704e7cafd641e8150e653John McCall      }
2847a536907da776bdc47a704e7cafd641e8150e653John McCall    }
2857a536907da776bdc47a704e7cafd641e8150e653John McCall  } else if (isa<FunctionDecl>(D) &&
286cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall             AllowOverloadingOfFunction(D, Context)) {
287279b5eb6910d64a293e9c0e2887a05c65d8737d7John McCall    // We are pushing the name of a function, which might be an
2887a536907da776bdc47a704e7cafd641e8150e653John McCall    // overloaded name.
289cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    FunctionDecl *FD = cast<FunctionDecl>(D);
290cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    IdentifierResolver::iterator Redecl
291cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall      = std::find_if(IdResolver.begin(FD->getDeclName()),
292cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall                     IdResolver.end(),
293cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall                     std::bind1st(std::mem_fun(&NamedDecl::declarationReplaces),
294cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall                                  FD));
295fa2e99f72f9bfe2270ea8caf76d0eef11c45259fAnders Carlsson    if (Redecl != IdResolver.end() &&
296cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall        S->isDeclScope(DeclPtrTy::make(*Redecl))) {
297cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall      // There is already a declaration of a function on our
298fa2e99f72f9bfe2270ea8caf76d0eef11c45259fAnders Carlsson      // IdResolver chain. Replace it with this declaration.
299cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall      S->RemoveDecl(DeclPtrTy::make(*Redecl));
300cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall      IdResolver.RemoveDecl(*Redecl);
301cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    }
302b1c65ff108de47a89585ad37874bd6cb232664cdRafael Espindola  }
303cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
304cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  IdResolver.AddDecl(D);
3055f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner}
306793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
307793a990774826a0c20b0da66cec0991badfb8b63Anders Carlssonvoid Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
3085f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  if (S->decl_empty()) return;
309793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
310793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson	 "Scope shouldn't contain decls!");
311793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
3124c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall  for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
313793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson       I != E; ++I) {
314793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    Decl *TmpD = (*I).getAs<Decl>();
315793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    assert(TmpD && "This decl didn't get pushed??");
316793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
317793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
318793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    NamedDecl *D = cast<NamedDecl>(TmpD);
319793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
320793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    if (!D->getDeclName()) continue;
321c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola
322793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    // Remove this name from our lexical scope.
323c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    IdResolver.RemoveDecl(D);
324793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  }
325c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola}
326793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
327c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
328793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson/// return 0 if one not found.
329c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael EspindolaObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
330793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  // The third "scope" argument is 0 since we aren't enabling lazy built-in
331793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  // creation from this context.
332c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola  NamedDecl *IDecl = LookupName(TUScope, Id, LookupOrdinaryName);
333793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
334793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
335793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson}
336793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
3375f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner/// getNonFieldDeclScope - Retrieves the innermost scope, starting
338793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson/// from S, where a non-field would be declared. This routine copes
339793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson/// with the difference between C and C++ scoping rules in structs and
340793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson/// unions. For example, the following code is well-formed in C but
341793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson/// ill-formed in C++:
34214110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne/// @code
34314110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne/// struct S6 {
34414110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne///   enum { BAR } e;
34514110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne/// };
346c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola///
34714110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne/// void test_S6() {
348c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola///   struct S6 a;
34914110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne///   a.e = BAR;
350c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola/// }
35114110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne/// @endcode
352c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola/// For the declaration of BAR, this routine will return a different
35314110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne/// scope. The scope S will be the scope of the unnamed enumeration
354c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola/// within S6. In C++, this routine will return the scope associated
3559a8822bb154b792cdb18fe4cfb34480ca0ec7661Anders Carlsson/// with S6, because the enumeration's scope is a transparent
3569a8822bb154b792cdb18fe4cfb34480ca0ec7661Anders Carlsson/// context but structures can contain non-field names. In C, this
3575f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner/// routine will return the translation unit scope, since the
358f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall/// enumeration's scope is a transparent context and structures cannot
3595f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor/// contain non-field names.
3605f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas GregorScope *Sema::getNonFieldDeclScope(Scope *S) {
3616d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner  while (((S->getFlags() & Scope::DeclScope) == 0) ||
3626d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner         (S->getEntity() &&
3636bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar          ((DeclContext *)S->getEntity())->isTransparentContext()) ||
36449988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar         (S->isClassScope() && !getLangOptions().CPlusPlus))
3656bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar    S = S->getParent();
3666d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner  return S;
3676d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner}
3686bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
3696bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbarvoid Sema::InitBuiltinVaListType() {
3706bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  if (!Context.getBuiltinVaListType().isNull())
37149988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar    return;
3726bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
3736bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
3746bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  NamedDecl *VaDecl = LookupName(TUScope, VaIdent, LookupOrdinaryName);
3756bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
3766bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
3770774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall}
37896e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson
3796bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
3806bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar/// file scope.  lazily create a decl for it. ForRedeclaration is true
381c5cbb909e8a27deb8f1a2b6b7bf56a96051af81aChris Lattner/// if we're creating this built-in in anticipation of redeclaring the
3827650d95a1a616ea300f37126a8dfc93dc19a662aChris Lattner/// built-in.
38396e0fc726c6fe7538522c60743705d5e696b40afOwen AndersonNamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
3846bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar                                     Scope *S, bool ForRedeclaration,
3856bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar                                     SourceLocation Loc) {
3866bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  Builtin::ID BID = (Builtin::ID)bid;
3876bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
3886bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  if (Context.BuiltinInfo.hasVAListUse(BID))
3891eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    InitBuiltinVaListType();
3900032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson
3913c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson  Builtin::Context::GetBuiltinTypeError Error;
39208e252425ca2cbdc44ba65d9a657ed5398014e36Owen Anderson  QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context, Error);
3936bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  switch (Error) {
3946bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  case Builtin::Context::GE_None:
3956bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar    // Okay
39696e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson    break;
3971c431b323d776362490bbf7cc796b74fedaf19f2Owen Anderson
398572cf09ae8a78af1c56d40b016ec4cf1837163acChris Lattner  case Builtin::Context::GE_Missing_FILE:
3997db6d838aad4083fe86d7bf703a75fe6e8a17856Owen Anderson    if (ForRedeclaration)
4001c431b323d776362490bbf7cc796b74fedaf19f2Owen Anderson      Diag(Loc, diag::err_implicit_decl_requires_stdio)
4016d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner        << Context.BuiltinInfo.GetName(BID);
4026d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner    return 0;
4036d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner  }
404d46f98573ba104eda102dd3224b2dca69f1c6336John McCall
405d46f98573ba104eda102dd3224b2dca69f1c6336John McCall  if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
40690e99a84ddd020e8fda79643748243725a2ed071Argyrios Kyrtzidis    Diag(Loc, diag::ext_implicit_lib_function_decl)
4077c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar      << Context.BuiltinInfo.GetName(BID)
408f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner      << R;
409d46f98573ba104eda102dd3224b2dca69f1c6336John McCall    if (Context.BuiltinInfo.getHeaderName(BID) &&
410f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner        Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl)
411f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner          != Diagnostic::Ignored)
412d46f98573ba104eda102dd3224b2dca69f1c6336John McCall      Diag(Loc, diag::note_please_include_header)
413f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner        << Context.BuiltinInfo.getHeaderName(BID)
414f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner        << Context.BuiltinInfo.GetName(BID);
415d46f98573ba104eda102dd3224b2dca69f1c6336John McCall  }
416f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
417f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  FunctionDecl *New = FunctionDecl::Create(Context,
418f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner                                           Context.getTranslationUnitDecl(),
419f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner                                           Loc, II, R,
420fd0f89d3d7e4220327abdec1cb115474d70219dcFariborz Jahanian                                           FunctionDecl::Extern, false,
4215584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall                                           /*hasPrototype=*/true);
4225584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall  New->setImplicit();
4235584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall
4245584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall  // Create Decl objects for each parameter, adding them to the
4255584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall  // FunctionDecl.
4265584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall  if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
427f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner    llvm::SmallVector<ParmVarDecl*, 16> Params;
428f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner    for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
429f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner      Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
430f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner                                           FT->getArgType(i), VarDecl::None, 0));
431f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner    New->setParams(Context, &Params[0], Params.size());
432f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  }
433f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
434142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian  AddKnownFunctionAttributes(New);
435142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian
436142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian  // TUScope is the translation-unit scope to insert this function into.
437f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // FIXME: This is hideous. We need to teach PushOnScopeChains to
438f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // relate Scopes to DeclContexts, and probably eliminate CurContext
439f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // entirely, but we're not there yet.
440f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  DeclContext *SavedContext = CurContext;
441f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  CurContext = Context.getTranslationUnitDecl();
442f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  PushOnScopeChains(New, TUScope);
443142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian  CurContext = SavedContext;
444142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian  return New;
4455584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall}
446f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
447f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
448f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner/// everything from the standard library is defined.
449f815306571385e2892e079a409f1b5b11f5e5cbbChris LattnerNamespaceDecl *Sema::GetStdNamespace() {
450d46f98573ba104eda102dd3224b2dca69f1c6336John McCall  if (!StdNamespace) {
451d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes    IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
452d46f98573ba104eda102dd3224b2dca69f1c6336John McCall    DeclContext *Global = Context.getTranslationUnitDecl();
453d46f98573ba104eda102dd3224b2dca69f1c6336John McCall    Decl *Std = LookupQualifiedName(Global, StdIdent, LookupNamespaceName);
454d46f98573ba104eda102dd3224b2dca69f1c6336John McCall    StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
455d46f98573ba104eda102dd3224b2dca69f1c6336John McCall  }
456d46f98573ba104eda102dd3224b2dca69f1c6336John McCall  return StdNamespace;
457d46f98573ba104eda102dd3224b2dca69f1c6336John McCall}
458d46f98573ba104eda102dd3224b2dca69f1c6336John McCall
4597c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the
460d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes/// same name and scope as a previous declaration 'Old'.  Figure out
461d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes/// how to resolve this situation, merging decls or emitting
4627dbd8197040313d796282d4af06eccdf8a17319cDaniel Dunbar/// diagnostics as appropriate. Returns true if there was an error,
4631eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump/// false otherwise.
4647dbd8197040313d796282d4af06eccdf8a17319cDaniel Dunbar///
465ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbarbool Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
466761d7f78e2dac7ea5f35828c2271e60d91e106ceDevang Patel  bool objc_types = false;
467ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar  // Allow multiple definitions for ObjC built-in typedefs.
468761d7f78e2dac7ea5f35828c2271e60d91e106ceDevang Patel  // FIXME: Verify the underlying types are equivalent!
469ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar  if (getLangOptions().ObjC1) {
470ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar    const IdentifierInfo *TypeID = New->getIdentifier();
471f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar    switch (TypeID->getLength()) {
472f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar    default: break;
473d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall    case 2:
474d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall      if (!TypeID->isStr("id"))
475d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall        break;
476d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall      Context.setObjCIdType(New);
477d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall      objc_types = true;
478d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall      break;
479d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall    case 5:
480d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall      if (!TypeID->isStr("Class"))
481d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall        break;
482d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall      Context.setObjCClassType(New);
483d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall      objc_types = true;
484d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall      return false;
485d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall    case 3:
486d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall      if (!TypeID->isStr("SEL"))
487d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall        break;
488d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall      Context.setObjCSelType(New);
489d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall      objc_types = true;
490d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall      return false;
491d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall    case 8:
492d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall      if (!TypeID->isStr("Protocol"))
4937c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar        break;
4947c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar      Context.setObjCProtoType(New->getUnderlyingType());
495abca5a1b3e74e644e297c7590b46ab73a6bb476aRafael Espindola      objc_types = true;
496abca5a1b3e74e644e297c7590b46ab73a6bb476aRafael Espindola      return false;
497abca5a1b3e74e644e297c7590b46ab73a6bb476aRafael Espindola    }
498d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall    // Fall through - the typedef name was not a builtin type.
4991eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  }
500af668b0e7d3581dea3b4f29a9262686e83887e5bDaniel Dunbar  // Verify the old decl was also a type.
5012873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman  TypeDecl *Old = dyn_cast<TypeDecl>(OldD);
5022873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman  if (!Old) {
503dd0cb22bd62e1e835327f478a2dbf0b8fa439713Daniel Dunbar    Diag(New->getLocation(), diag::err_redefinition_different_kind)
5042873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman      << New->getDeclName();
5052873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman    if (!objc_types)
506dd0cb22bd62e1e835327f478a2dbf0b8fa439713Daniel Dunbar      Diag(OldD->getLocation(), diag::note_previous_definition);
5071feade8e520be483293dbf55eb57a51720899589Mike Stump    return true;
50881ebbde0fb30a40df0f5e913d8a1f71c383d271aAnders Carlsson  }
509f55314dce992fd60816ba337ad151a2fb7c42239Mike Stump
5102873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman  // Determine the "old" type we'll use for checking and diagnostics.
5112873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman  QualType OldType;
5122873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman  if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
5132873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman    OldType = OldTypedef->getUnderlyingType();
5142873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman  else
515c5f657fe308f22243f674fc1dfbe24915944d8bfRafael Espindola    OldType = Context.getTypeDeclType(Old);
516c5f657fe308f22243f674fc1dfbe24915944d8bfRafael Espindola
517c5f657fe308f22243f674fc1dfbe24915944d8bfRafael Espindola  // If the typedef types are not identical, reject them in all languages and
518e289d81369914678db386f6aa86faf8f178e245dDouglas Gregor  // with any extensions enabled.
519fd015353a3c4f528216276f25df5b4d464d7a0cdAnders Carlsson
520e289d81369914678db386f6aa86faf8f178e245dDouglas Gregor  if (OldType != New->getUnderlyingType() &&
521fd015353a3c4f528216276f25df5b4d464d7a0cdAnders Carlsson      Context.getCanonicalType(OldType) !=
522fd015353a3c4f528216276f25df5b4d464d7a0cdAnders Carlsson      Context.getCanonicalType(New->getUnderlyingType())) {
523cf807c4dfdb23e8fa3f400e0b24ef5b79db7a530Sean Hunt    Diag(New->getLocation(), diag::err_redefinition_different_typedef)
524cf807c4dfdb23e8fa3f400e0b24ef5b79db7a530Sean Hunt      << New->getUnderlyingType() << OldType;
525cf807c4dfdb23e8fa3f400e0b24ef5b79db7a530Sean Hunt    if (!objc_types)
526cf807c4dfdb23e8fa3f400e0b24ef5b79db7a530Sean Hunt      Diag(Old->getLocation(), diag::note_previous_definition);
527fb51ddfafcd5f8536d0312b3daa3c0b74b90ab5bMike Stump    return true;
528bd6dbd19781cefd5b5ff9750c8bf86e6c341a68cMike Stump  }
529bd6dbd19781cefd5b5ff9750c8bf86e6c341a68cMike Stump  if (objc_types) return false;
530f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar  if (getLangOptions().Microsoft) return false;
531f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar
5321eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // C++ [dcl.typedef]p2:
5337c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  //   In a given non-class scope, a typedef specifier can be used to
534934176f27552141b5ad113cb3603ffb14906c570Anders Carlsson  //   redefine the name of any type declared in that scope to refer
535934176f27552141b5ad113cb3603ffb14906c570Anders Carlsson  //   to the type to which it already refers.
5361fb0caaa7bef765b85972274e3b434af2572c141John McCall  if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
5371fb0caaa7bef765b85972274e3b434af2572c141John McCall    return false;
5387c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
53940b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
5407c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
5417c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // *either* declaration is in a system header. The code below implements
54240b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  // this adhoc compatibility rule. FIXME: The following code will not
5437c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // work properly when compiling ".i" files (containing preprocessed output).
54482d0a418c8699fc6f4a9417457ffe93d43bba1c1Anton Korobeynikov  if (PP.getDiagnostics().getSuppressSystemWarnings()) {
54582d0a418c8699fc6f4a9417457ffe93d43bba1c1Anton Korobeynikov    SourceManager &SrcMgr = Context.getSourceManager();
5467c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    if (SrcMgr.isInSystemHeader(Old->getLocation()))
5477c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar      return false;
5480e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar    if (SrcMgr.isInSystemHeader(New->getLocation()))
5490e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar      return false;
5500e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar  }
5510e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar
5520e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar  Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
5537c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  Diag(Old->getLocation(), diag::note_previous_definition);
5547c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  return true;
5557c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar}
5560e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar
557f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar/// DeclhasAttr - returns true if decl Declaration already has the target
558f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar/// attribute.
559b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlssonstatic bool DeclHasAttr(const Decl *decl, const Attr *target) {
560c6c14d1cd68afcd90d097715296377f15be45210Eli Friedman  for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
561c6c14d1cd68afcd90d097715296377f15be45210Eli Friedman    if (attr->getKind() == target->getKind())
5620ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne      return true;
5630ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne
5640ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne  return false;
5650ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne}
5660ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne
5670ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne/// MergeAttributes - append attributes from the Old decl to the New one.
5680ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbournestatic void MergeAttributes(Decl *New, Decl *Old, ASTContext &C) {
569b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlsson  Attr *attr = const_cast<Attr*>(Old->getAttrs());
570b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlsson
571c6c14d1cd68afcd90d097715296377f15be45210Eli Friedman  while (attr) {
572b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlsson    Attr *tmp = attr;
5731eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    attr = attr->getNext();
5747c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
5757c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    if (!DeclHasAttr(New, tmp) && tmp->isMerged()) {
5761eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      tmp->setInherited(true);
57740b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis      New->addAttr(tmp);
5787c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    } else {
5791eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      tmp->setNext(0);
5800a0d2b179085a52c10402feebeb6db8b4d96a140Douglas Gregor      tmp->Destroy(C);
5817c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    }
5821eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  }
5837c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
5847c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  Old->invalidateAttrs();
5851eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump}
586af14603ca61757cf4361b583b45639a04c57e651John McCall
587af14603ca61757cf4361b583b45639a04c57e651John McCall/// Used in MergeFunctionDecl to keep track of function parameters in
588af14603ca61757cf4361b583b45639a04c57e651John McCall/// C.
589af14603ca61757cf4361b583b45639a04c57e651John McCallstruct GNUCompatibleParamWarning {
590af14603ca61757cf4361b583b45639a04c57e651John McCall  ParmVarDecl *OldParm;
5917c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  ParmVarDecl *NewParm;
5927c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  QualType PromotedType;
59340b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis};
5947c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
595219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar/// MergeFunctionDecl - We just parsed a function 'New' from
596219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar/// declarator D which has the same name and scope as a previous
5970269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar/// declaration 'Old'.  Figure out how to resolve this situation,
5981eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump/// merging decls or emitting diagnostics as appropriate.
5990269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar///
60035f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner/// In C++, New and Old must be declarations that are not
6010269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar/// overloaded. Use IsOverload to determine whether New and Old are
6020269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar/// overloaded, and to select the Old declaration that New should be
6030269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar/// merged with.
6040269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar///
605ad64e024bd18cf25dcfa44e049004371838decd8Chris Lattner/// Returns true if there was an error, false otherwise.
6060269871c9cba493f76237175ab60313406f3bafaDaniel Dunbarbool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
6070269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  assert(!isa<OverloadedFunctionDecl>(OldD) &&
6082acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner         "Cannot merge with an overloaded function declaration");
6091eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
61035f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  // Verify the old decl was also a function.
61135f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
61235f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  if (!Old) {
61335f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner    Diag(New->getLocation(), diag::err_redefinition_different_kind)
6141eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      << New->getDeclName();
6151eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    Diag(OldD->getLocation(), diag::note_previous_definition);
616a1cf15f4680e5cf39e72e28c5ea854fcba792e84Owen Anderson    return true;
61735f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  }
6181eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
619c38e9affd4519ea199af22419c8c794973cc4b23Fariborz Jahanian  // Determine whether the previous declaration was a definition,
620c38e9affd4519ea199af22419c8c794973cc4b23Fariborz Jahanian  // implicit declaration, or a declaration.
62196e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson  diag::kind PrevDiag;
6221eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  if (Old->isThisDeclarationADefinition())
6231eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    PrevDiag = diag::note_previous_definition;
6241eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  else if (Old->isImplicit())
6250269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar    PrevDiag = diag::note_previous_implicit_declaration;
6267db6d838aad4083fe86d7bf703a75fe6e8a17856Owen Anderson  else
6271c431b323d776362490bbf7cc796b74fedaf19f2Owen Anderson    PrevDiag = diag::note_previous_declaration;
6280269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
6290269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  QualType OldQType = Context.getCanonicalType(Old->getType());
6300269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  QualType NewQType = Context.getCanonicalType(New->getType());
6310269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
6320269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
63367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner      New->getStorageClass() == FunctionDecl::Static &&
63467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner      Old->getStorageClass() != FunctionDecl::Static) {
635dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky    Diag(New->getLocation(), diag::err_static_non_static)
636bbf58bb1b8dd8c5e0f07547a6c20ffd55385fcf6Rafael Espindola      << New;
637046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson    Diag(Old->getLocation(), PrevDiag);
638046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson    return true;
639046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson  }
640046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson
641046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson  if (getLangOptions().CPlusPlus) {
642bbf58bb1b8dd8c5e0f07547a6c20ffd55385fcf6Rafael Espindola    // (C++98 13.1p2):
643bbf58bb1b8dd8c5e0f07547a6c20ffd55385fcf6Rafael Espindola    //   Certain function declarations cannot be overloaded:
644bbf58bb1b8dd8c5e0f07547a6c20ffd55385fcf6Rafael Espindola    //     -- Function declarations that differ only in the return type
6452a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson    //        cannot be overloaded.
64667b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    QualType OldReturnType
64767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner      = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
648c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    QualType NewReturnType
649c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall      = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
650c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    if (OldReturnType != NewReturnType) {
651c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall      Diag(New->getLocation(), diag::err_ovl_diff_return_type);
652c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall      Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
653c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall      return true;
654c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    }
655c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall
6565f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
657f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
65867b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    if (OldMethod && NewMethod &&
6591eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        OldMethod->getLexicalDeclContext() ==
66067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner          NewMethod->getLexicalDeclContext()) {
66167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner      //    -- Member function declarations with the same name and the
6621eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      //       same parameter types cannot be overloaded if any of them
663c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall      //       is a static member function declaration.
664c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall      if (OldMethod->isStatic() || NewMethod->isStatic()) {
665c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall        Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
666c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall        Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
667c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall        return true;
66867b00520c8f5b48fad722b790d87fea6be764efeChris Lattner      }
66967b00520c8f5b48fad722b790d87fea6be764efeChris Lattner
67067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner      // C++ [class.mem]p1:
6715f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer      //   [...] A member shall not be declared twice in the
6725f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer      //   member-specification, except that a nested class or member
67377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge      //   class template can be declared and then later defined.
67477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge      unsigned NewDiag;
67577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge      if (isa<CXXConstructorDecl>(OldMethod))
67677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge        NewDiag = diag::err_constructor_redeclared;
67777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge      else if (isa<CXXDestructorDecl>(NewMethod))
67877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge        NewDiag = diag::err_destructor_redeclared;
67977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge      else if (isa<CXXConversionDecl>(NewMethod))
68077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge        NewDiag = diag::err_conv_function_redeclared;
68177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge      else
68277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge        NewDiag = diag::err_member_redeclared;
68377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
68477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge      Diag(New->getLocation(), NewDiag);
68577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge      Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
68677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    }
68777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
68877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    // (C++98 8.3.5p3):
68977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    //   All declarations for a function shall agree exactly in both the
69077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    //   return type and the parameter-type-list.
69177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    if (OldQType == NewQType)
69277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge      return MergeCompatibleFunctionDecls(New, Old);
69377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
69477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    // Fall through for conflicting redeclarations and redefinitions.
69577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  }
69677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
69777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  // C: Function types need to be compatible, not identical. This handles
69877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  // duplicate function decls like "void f(int); void f(enum X);" properly.
69977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  if (!getLangOptions().CPlusPlus &&
70077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge      Context.typesAreCompatible(OldQType, NewQType)) {
70177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    const FunctionType *OldFuncType = OldQType->getAsFunctionType();
70277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    const FunctionType *NewFuncType = NewQType->getAsFunctionType();
70377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    const FunctionProtoType *OldProto = 0;
70477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    if (isa<FunctionNoProtoType>(NewFuncType) &&
70577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge        (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
70677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge      // The old declaration provided a function prototype, but the
70777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge      // new declaration does not. Merge in the prototype.
70877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge      llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
70977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge                                                 OldProto->arg_type_end());
71077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge      NewQType = Context.getFunctionType(NewFuncType->getResultType(),
71177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge                                         &ParamTypes[0], ParamTypes.size(),
71277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge                                         OldProto->isVariadic(),
71377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge                                         OldProto->getTypeQuals());
71477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge      New->setType(NewQType);
71577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge      New->setInheritedPrototype();
71677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
7171eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      // Synthesize a parameter for each argument type.
7188bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman      llvm::SmallVector<ParmVarDecl*, 16> Params;
71977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge      for (FunctionProtoType::arg_type_iterator
72077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge             ParamType = OldProto->arg_type_begin(),
72177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge             ParamEnd = OldProto->arg_type_end();
72277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge           ParamType != ParamEnd; ++ParamType) {
72377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge        ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
7248bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman                                                 SourceLocation(), 0,
72557d5cee133495bc21d1abdbce45ab05a79274a23Daniel Dunbar                                                 *ParamType, VarDecl::None,
7268bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman                                                 0);
72777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge        Param->setImplicit();
72877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge        Params.push_back(Param);
72977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge      }
73077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
7318bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman      New->setParams(Context, &Params[0], Params.size());
732c5cbb909e8a27deb8f1a2b6b7bf56a96051af81aChris Lattner    }
7338bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
7348bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman    return MergeCompatibleFunctionDecls(New, Old);
73577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  }
73677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
73777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  // GNU C permits a K&R definition to follow a prototype declaration
73877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  // if the declared types of the parameters in the K&R definition
73977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  // match the types in the prototype declaration, even when the
74077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  // promoted types of the parameters from the K&R definition differ
74177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  // from the types in the prototype. GCC then keeps the types from
74277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  // the prototype.
74377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  if (!getLangOptions().CPlusPlus &&
74477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge      !getLangOptions().NoExtensions &&
745a6d6af308bfc9b72467b432a045a9fc6673e3821Argyrios Kyrtzidis      Old->hasPrototype() && !New->hasPrototype() &&
74690e99a84ddd020e8fda79643748243725a2ed071Argyrios Kyrtzidis      New->getType()->getAsFunctionProtoType() &&
74790e99a84ddd020e8fda79643748243725a2ed071Argyrios Kyrtzidis      Old->getNumParams() == New->getNumParams()) {
748a6d6af308bfc9b72467b432a045a9fc6673e3821Argyrios Kyrtzidis    llvm::SmallVector<QualType, 16> ArgTypes;
7490b6bc8bd7a1d2a7d7478d13d78cff94cacad61fcDouglas Gregor    llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings;
7504ac7c0bb39696e92fd220118fedc484c09a69870Argyrios Kyrtzidis    const FunctionProtoType *OldProto
75173241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar      = Old->getType()->getAsFunctionProtoType();
75273241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar    const FunctionProtoType *NewProto
7536a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      = New->getType()->getAsFunctionProtoType();
7546a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
7556a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    // Determine whether this is the GNU C extension.
7566a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    bool GNUCompatible =
7572acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner      Context.typesAreCompatible(OldProto->getResultType(),
7586a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola                                 NewProto->getResultType()) &&
7596a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      (OldProto->isVariadic() == NewProto->isVariadic());
760f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    for (unsigned Idx = 0, End = Old->getNumParams();
7616a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola         GNUCompatible && Idx != End; ++Idx) {
7626a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      ParmVarDecl *OldParm = Old->getParamDecl(Idx);
7636a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      ParmVarDecl *NewParm = New->getParamDecl(Idx);
7641faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson      if (Context.typesAreCompatible(OldParm->getType(),
7651faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson                                     NewProto->getArgType(Idx))) {
7666a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola        ArgTypes.push_back(NewParm->getType());
767f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall      } else if (Context.typesAreCompatible(OldParm->getType(),
7686a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola                                            NewParm->getType())) {
7696a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola        GNUCompatibleParamWarning Warn
7706a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola          = { OldParm, NewParm, NewProto->getArgType(Idx) };
7716a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola        Warnings.push_back(Warn);
7726a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola        ArgTypes.push_back(NewParm->getType());
7736a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      } else
7746a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola        GNUCompatible = false;
7756a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    }
7766a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
7776a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    if (GNUCompatible) {
778b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner      for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
7794a6835e650ff24e19ce08a3bd347c0ad186777fdAnders Carlsson        Diag(Warnings[Warn].NewParm->getLocation(),
7801eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump             diag::ext_param_promoted_not_compatible_with_prototype)
7816a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola          << Warnings[Warn].PromotedType
7826a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola          << Warnings[Warn].OldParm->getType();
7836a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola        Diag(Warnings[Warn].OldParm->getLocation(),
7846a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola             diag::note_previous_declaration);
785bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner      }
786bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
78740b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis      New->setType(Context.getFunctionType(NewProto->getResultType(),
788f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall                                           &ArgTypes[0], ArgTypes.size(),
789219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar                                           NewProto->isVariadic(),
790d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne                                           NewProto->getTypeQuals()));
791d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne      return MergeCompatibleFunctionDecls(New, Old);
792d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne    }
793d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne
794d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne    // Fall through to diagnose conflicting types.
795d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne  }
796d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne
797d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne  // A function that has already been declared has been redeclared or defined
798d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne  // with a different type- show appropriate diagnostic
799d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne  if (unsigned BuiltinID = Old->getBuiltinID(Context)) {
800d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne    // The user has declared a builtin function with an incompatible
801d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne    // signature.
802d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne    if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
803d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne      // The function the user is redeclaring is a library-defined
804d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne      // function like 'malloc' or 'printf'. Warn about the
805d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne      // redeclaration, then pretend that we don't know about this
806d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne      // library built-in.
80767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner      Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
8085e1e1f95c98b1add70c238093bbd5dc8d4f9c4e9Daniel Dunbar      Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
80973241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar        << Old << Old->getType();
810dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky      New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
811dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky      Old->setInvalidDecl();
812dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky      return false;
813dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky    }
814dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky
815dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky    PrevDiag = diag::note_previous_builtin_declaration;
816dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky  }
8175f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner
818dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
819dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky  Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
820dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky  return true;
821dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky}
822dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky
82373241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar/// \brief Completes the merge of two function declarations that are
824dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky/// known to be compatible.
8250269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar///
8260269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar/// This routine handles the merging of attributes and other
827bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar/// properties of function declarations form the old declaration to
828bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar/// the new declaration, once we know that New is in fact a
829a9a55c063e9e59c6ab0a6d7a21302660f7bde9f9Douglas Gregor/// redeclaration of Old.
83073241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar///
8314c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman/// \returns false
8324c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begemanbool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
83367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // Merge the attributes
83467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  MergeAttributes(New, Old, Context);
8354357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner
8364357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  // Merge the storage class.
8374357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  New->setStorageClass(Old->getStorageClass());
838bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
839bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  // FIXME: need to implement inline semantics
840bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall
841bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall  // Merge "pure" flag.
842bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall  if (Old->isPure())
843bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall    New->setPure();
844bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall
845bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall  // Merge the "deleted" flag.
846bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall  if (Old->isDeleted())
847bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall    New->setDeleted();
8484357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner
8494357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  if (getLangOptions().CPlusPlus)
8504357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    return MergeCXXFunctionDecl(New, Old);
8515f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner
8524357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  return false;
8534357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner}
8544357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner
8554357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner/// MergeVarDecl - We just parsed a variable 'New' which has the same name
8564357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
8574357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner/// situation, merging decls or emitting diagnostics as appropriate.
8584357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner///
8594357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner/// Tentative definition rules (C99 6.9.2p2) are checked by
8604c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
8614c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman/// definitions here, since the initializer hasn't been attached.
862a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola///
863a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindolabool Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
864a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  // Verify the old decl was also a variable.
865a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  VarDecl *Old = dyn_cast<VarDecl>(OldD);
866a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  if (!Old) {
867a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    Diag(New->getLocation(), diag::err_redefinition_different_kind)
868a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola      << New->getDeclName();
869a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    Diag(OldD->getLocation(), diag::note_previous_definition);
870a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    return true;
871a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  }
872a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola
873a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  MergeAttributes(New, Old, Context);
874a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola
875a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  // Merge the types
876a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  QualType MergedT = Context.mergeTypes(New->getType(), Old->getType());
877a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  if (MergedT.isNull()) {
878a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    Diag(New->getLocation(), diag::err_redefinition_different_type)
879a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola      << New->getDeclName();
880a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    Diag(Old->getLocation(), diag::note_previous_definition);
881a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    return true;
882a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  }
883a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  New->setType(MergedT);
884a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola
885a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
886a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  if (New->getStorageClass() == VarDecl::Static &&
887a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola      (Old->getStorageClass() == VarDecl::None || Old->hasExternalStorage())) {
888a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
889a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    Diag(Old->getLocation(), diag::note_previous_definition);
890a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    return true;
891a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  }
892a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  // C99 6.2.2p4:
893a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  //   For an identifier declared with the storage-class specifier
894a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  //   extern in a scope in which a prior declaration of that
895a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  //   identifier is visible,23) if the prior declaration specifies
896a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  //   internal or external linkage, the linkage of the identifier at
897a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  //   the later declaration is the same as the linkage specified at
898a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  //   the prior declaration. If no prior declaration is visible, or
899a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  //   if the prior declaration specifies no linkage, then the
900a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  //   identifier has external linkage.
901a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  if (New->hasExternalStorage() && Old->hasLinkage())
902a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    /* Okay */;
903a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  else if (New->getStorageClass() != VarDecl::Static &&
904cc4889f72ec68319969ba51e214d9940eb9327e5Rafael Espindola           Old->getStorageClass() == VarDecl::Static) {
905cc4889f72ec68319969ba51e214d9940eb9327e5Rafael Espindola    Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
906a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    Diag(Old->getLocation(), diag::note_previous_definition);
907a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    return true;
908a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  }
909a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola
910a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
911a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola
912cc4889f72ec68319969ba51e214d9940eb9327e5Rafael Espindola  // FIXME: The test for external storage here seems wrong? We still
913a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  // need to check for mismatches.
914a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
915b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner      // Don't complain about out-of-line definitions of static members.
9164a6835e650ff24e19ce08a3bd347c0ad186777fdAnders Carlsson      !(Old->getLexicalDeclContext()->isRecord() &&
9171eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        !New->getLexicalDeclContext()->isRecord())) {
918cb421fa690da545b58a720abe5f1c49b166dbde7Dan Gohman    Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
9198e2efcc267ed12dc435782288b7f9a4a1bc56c72Anders Carlsson    Diag(Old->getLocation(), diag::note_previous_definition);
9208e2efcc267ed12dc435782288b7f9a4a1bc56c72Anders Carlsson    return true;
9218e2efcc267ed12dc435782288b7f9a4a1bc56c72Anders Carlsson  }
92244eac33ae12df384f3f002102f919f603bee330fDouglas Gregor
92344eac33ae12df384f3f002102f919f603bee330fDouglas Gregor  // Keep a chain of previous declarations.
92444eac33ae12df384f3f002102f919f603bee330fDouglas Gregor  New->setPreviousDeclaration(Old);
925a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola
92644eac33ae12df384f3f002102f919f603bee330fDouglas Gregor  return false;
92744eac33ae12df384f3f002102f919f603bee330fDouglas Gregor}
92844eac33ae12df384f3f002102f919f603bee330fDouglas Gregor
9297dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman/// CheckParmsForFunctionDef - Check that the parameters of the given
9307dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman/// function are appropriate for the definition of a function. This
9317dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman/// takes care of any checks that cannot be performed on the
9327dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman/// declaration itself, e.g., that the types of each of the function
9337dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman/// parameters are complete.
9347dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedmanbool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
9357dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman  bool HasInvalidParm = false;
9367dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
9377dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman    ParmVarDecl *Param = FD->getParamDecl(p);
93844eac33ae12df384f3f002102f919f603bee330fDouglas Gregor
93944eac33ae12df384f3f002102f919f603bee330fDouglas Gregor    // C99 6.7.5.3p4: the parameters in a parameter type list in a
9407270ee4cd4794281c09dfb6931a98bbb2581ef02Anders Carlsson    // function declarator that is part of a function definition of
9417dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman    // that function shall not have incomplete type.
94244eac33ae12df384f3f002102f919f603bee330fDouglas Gregor    //
943b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner    // This is also C++ [dcl.fct]p6.
944b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner    if (!Param->isInvalidDecl() &&
94544eac33ae12df384f3f002102f919f603bee330fDouglas Gregor        RequireCompleteType(Param->getLocation(), Param->getType(),
946b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner                               diag::err_typecheck_decl_incomplete_type)) {
947b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner      Param->setInvalidDecl();
948b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner      HasInvalidParm = true;
9494357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    }
950b219cfc4d75f0a03630b7c4509ef791b7e97b2c8David Blaikie
951bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar    // C99 6.9.1p5: If the declarator includes a parameter type list, the
952bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar    // declaration of each parameter shall include an identifier.
95374391b48b4791cded373683a3baf67314f358d50Chris Lattner    if (Param->getIdentifier() == 0 &&
95474391b48b4791cded373683a3baf67314f358d50Chris Lattner        !Param->isImplicit() &&
95574391b48b4791cded373683a3baf67314f358d50Chris Lattner        !getLangOptions().CPlusPlus)
95674391b48b4791cded373683a3baf67314f358d50Chris Lattner      Diag(Param->getLocation(), diag::err_parameter_name_omitted);
95774391b48b4791cded373683a3baf67314f358d50Chris Lattner  }
95874391b48b4791cded373683a3baf67314f358d50Chris Lattner
95974391b48b4791cded373683a3baf67314f358d50Chris Lattner  return HasInvalidParm;
960f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall}
9615f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner
9622acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
963f85e193739c953358c865005855253af4f68a497John McCall/// no declarator (e.g. "struct foo;") is parsed.
964f85e193739c953358c865005855253af4f68a497John McCallSema::DeclPtrTy Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
9650558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  // FIXME: Error on auto/register at file scope
966f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  // FIXME: Error on inline/virtual/explicit
9670558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  // FIXME: Error on invalid restrict
9686a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  // FIXME: Warn on useless const/volatile
9696a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  // FIXME: Warn on useless static/extern/typedef/private_extern/mutable
9706a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  // FIXME: Warn on useless attributes
9717270ee4cd4794281c09dfb6931a98bbb2581ef02Anders Carlsson
9726a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  TagDecl *Tag = 0;
9736a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
9746a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      DS.getTypeSpecType() == DeclSpec::TST_struct ||
9756a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      DS.getTypeSpecType() == DeclSpec::TST_union ||
9760558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner      DS.getTypeSpecType() == DeclSpec::TST_enum)
9770558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    Tag = dyn_cast<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
9781eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
9790558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
9809cbe4f0ba01ec304e1e3d071c071f7bca33631c0Chris Lattner    if (!Record->getDeclName() && Record->isDefinition() &&
9810558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner        DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
9821eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      if (getLangOptions().CPlusPlus ||
983654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman          Record->getDeclContext()->isRecord())
984654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman        return BuildAnonymousStructOrUnion(S, DS, Record);
985654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman
986654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman      Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
987784f21121a6c9418ebd86baa6814e36e1176c410John McCall        << DS.getSourceRange();
9882acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner    }
989784f21121a6c9418ebd86baa6814e36e1176c410John McCall
990784f21121a6c9418ebd86baa6814e36e1176c410John McCall    // Microsoft allows unnamed struct/union fields. Don't complain
991784f21121a6c9418ebd86baa6814e36e1176c410John McCall    // about them.
9920774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall    // FIXME: Should we support Microsoft's extensions in this area?
993654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman    if (Record->getDeclName() && getLangOptions().Microsoft)
994654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman      return DeclPtrTy::make(Tag);
995bcaedaed309ce453a992fdeef4a4c908cc7d9dfbChris Lattner  }
996784f21121a6c9418ebd86baa6814e36e1176c410John McCall
997654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  if (!DS.isMissingDeclaratorOk() &&
998f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall      DS.getTypeSpecType() != DeclSpec::TST_error) {
999f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    // Warn about typedefs of enums without names, since this is an
1000654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman    // extension in both Microsoft an GNU.
1001b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlsson    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
1002f85e193739c953358c865005855253af4f68a497John McCall        Tag && isa<EnumDecl>(Tag)) {
1003f85e193739c953358c865005855253af4f68a497John McCall      Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
1004654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman        << DS.getSourceRange();
100567b00520c8f5b48fad722b790d87fea6be764efeChris Lattner      return DeclPtrTy::make(Tag);
100667b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    }
100767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner
1008f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
100967b00520c8f5b48fad722b790d87fea6be764efeChris Lattner      << DS.getSourceRange();
101067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    return DeclPtrTy();
101167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  }
101267b00520c8f5b48fad722b790d87fea6be764efeChris Lattner
101367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  return DeclPtrTy::make(Tag);
1014bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall}
1015bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall
1016bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall/// InjectAnonymousStructOrUnionMembers - Inject the members of the
1017bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall/// anonymous struct or union AnonRecord into the owning context Owner
1018bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall/// and scope S. This routine will be invoked just after we realize
1019bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall/// that an unnamed union or struct is actually an anonymous union or
1020bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall/// struct, e.g.,
1021bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall///
1022bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall/// @code
10231faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson/// union {
10241faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson///   int i;
10251faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson///   float f;
102601de7a44cea9f77cbcda65faad8edc8b48a3b617Rafael Espindola/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
1027bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall///    // f into the surrounding scope.x
1028bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall/// @endcode
1029bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall///
1030bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall/// This routine is recursive, injecting the names of nested anonymous
10311faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson/// structs/unions into the owning context and scope as well.
1032bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCallbool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
1033a29bf41b8f49578207ce36f6b21ff9bb7ee77babDouglas Gregor                                               RecordDecl *AnonRecord) {
1034bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  bool Invalid = false;
103510620eb5164e31208fcbf0437cd79ae535ed0559Sean Hunt  for (RecordDecl::field_iterator F = AnonRecord->field_begin(Context),
1036a29bf41b8f49578207ce36f6b21ff9bb7ee77babDouglas Gregor                               FEnd = AnonRecord->field_end(Context);
1037bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall       F != FEnd; ++F) {
1038bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall    if ((*F)->getDeclName()) {
10397b9a5aa7c0d76f577699d25ce6afe21ecccb60b7Rafael Espindola      NamedDecl *PrevDecl = LookupQualifiedName(Owner, (*F)->getDeclName(),
1040bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall                                                LookupOrdinaryName, true);
1041bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall      if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
104267b00520c8f5b48fad722b790d87fea6be764efeChris Lattner        // C++ [class.union]p2:
10431eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        //   The names of the members of an anonymous union shall be
1044784f21121a6c9418ebd86baa6814e36e1176c410John McCall        //   distinct from the names of any other entity in the
1045784f21121a6c9418ebd86baa6814e36e1176c410John McCall        //   scope in which the anonymous union is declared.
1046784f21121a6c9418ebd86baa6814e36e1176c410John McCall        unsigned diagKind
1047784f21121a6c9418ebd86baa6814e36e1176c410John McCall          = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
1048784f21121a6c9418ebd86baa6814e36e1176c410John McCall                                 : diag::err_anonymous_struct_member_redecl;
1049784f21121a6c9418ebd86baa6814e36e1176c410John McCall        Diag((*F)->getLocation(), diagKind)
10509cbe4f0ba01ec304e1e3d071c071f7bca33631c0Chris Lattner          << (*F)->getDeclName();
1051784f21121a6c9418ebd86baa6814e36e1176c410John McCall        Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
10520558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner        Invalid = true;
10530558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner      } else {
105474391b48b4791cded373683a3baf67314f358d50Chris Lattner        // C++ [class.union]p2:
105574391b48b4791cded373683a3baf67314f358d50Chris Lattner        //   For the purpose of name lookup, after the anonymous union
105674391b48b4791cded373683a3baf67314f358d50Chris Lattner        //   definition, the members of the anonymous union are
1057b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner        //   considered to have been defined in the scope in which the
10582acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner        //   anonymous union is declared.
10591faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson        Owner->makeDeclVisibleInContext(Context, *F);
106074391b48b4791cded373683a3baf67314f358d50Chris Lattner        S->AddDecl(DeclPtrTy::make(*F));
106174391b48b4791cded373683a3baf67314f358d50Chris Lattner        IdResolver.AddDecl(*F);
10624a6835e650ff24e19ce08a3bd347c0ad186777fdAnders Carlsson      }
1063bcaedaed309ce453a992fdeef4a4c908cc7d9dfbChris Lattner    } else if (const RecordType *InnerRecordType
10645f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner                 = (*F)->getType()->getAsRecordType()) {
10651faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson      RecordDecl *InnerRecord = InnerRecordType->getDecl();
106674391b48b4791cded373683a3baf67314f358d50Chris Lattner      if (InnerRecord->isAnonymousStructOrUnion())
106777ba708819285931932ecd33691a672bb59d221aEli Friedman        Invalid = Invalid ||
106874391b48b4791cded373683a3baf67314f358d50Chris Lattner          InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
106974391b48b4791cded373683a3baf67314f358d50Chris Lattner    }
107074391b48b4791cded373683a3baf67314f358d50Chris Lattner  }
10712acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner
10725f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  return Invalid;
1073f85e193739c953358c865005855253af4f68a497John McCall}
1074f85e193739c953358c865005855253af4f68a497John McCall
1075f85e193739c953358c865005855253af4f68a497John McCall/// ActOnAnonymousStructOrUnion - Handle the declaration of an
107674391b48b4791cded373683a3baf67314f358d50Chris Lattner/// anonymous structure or union. Anonymous unions are a C++ feature
1077bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar/// (C++ [class.union]) and a GNU C extension; anonymous structures
1078da55074866ca2fe7f718c5d3334648d6e340fb15Douglas Gregor/// are a GNU C and GNU C++ extension.
1079da55074866ca2fe7f718c5d3334648d6e340fb15Douglas GregorSema::DeclPtrTy Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
108088786862424cb2d478516d911709dc19c962af9cJohn McCall                                                  RecordDecl *Record) {
108120e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman  DeclContext *Owner = Record->getDeclContext();
1082da55074866ca2fe7f718c5d3334648d6e340fb15Douglas Gregor
1083da55074866ca2fe7f718c5d3334648d6e340fb15Douglas Gregor  // Diagnose whether this anonymous struct/union is an extension.
1084da55074866ca2fe7f718c5d3334648d6e340fb15Douglas Gregor  if (Record->isUnion() && !getLangOptions().CPlusPlus)
1085da55074866ca2fe7f718c5d3334648d6e340fb15Douglas Gregor    Diag(Record->getLocation(), diag::ext_anonymous_union);
10862bb110125e0e5adb7c1c65d12adfa34151ca1c47Douglas Gregor  else if (!Record->isUnion())
10872bb110125e0e5adb7c1c65d12adfa34151ca1c47Douglas Gregor    Diag(Record->getLocation(), diag::ext_anonymous_struct);
10882bb110125e0e5adb7c1c65d12adfa34151ca1c47Douglas Gregor
108920e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman  // C and C++ require different kinds of checks for anonymous
1090da55074866ca2fe7f718c5d3334648d6e340fb15Douglas Gregor  // structs/unions.
109120e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman  bool Invalid = false;
109220e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman  if (getLangOptions().CPlusPlus) {
109320e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman    const char* PrevSpec = 0;
109474391b48b4791cded373683a3baf67314f358d50Chris Lattner    // C++ [class.union]p3:
109574391b48b4791cded373683a3baf67314f358d50Chris Lattner    //   Anonymous unions declared in a named namespace or in the
109674391b48b4791cded373683a3baf67314f358d50Chris Lattner    //   global namespace shall be declared static.
109774391b48b4791cded373683a3baf67314f358d50Chris Lattner    if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
109874391b48b4791cded373683a3baf67314f358d50Chris Lattner        (isa<TranslationUnitDecl>(Owner) ||
109974391b48b4791cded373683a3baf67314f358d50Chris Lattner         (isa<NamespaceDecl>(Owner) &&
110074391b48b4791cded373683a3baf67314f358d50Chris Lattner          cast<NamespaceDecl>(Owner)->getDeclName()))) {
1101f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall      Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
11025f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner      Invalid = true;
11032acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner
1104c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola      // Recover by adding 'static'.
1105c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola      DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
11063c827a79cb7d04c255db8080e682ee2c6912373dDaniel Dunbar    }
1107f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    // C++ [class.union]p3:
110899b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner    //   A storage class is not allowed in a declaration of an
11096a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    //   anonymous union in a class scope.
11106a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
11117270ee4cd4794281c09dfb6931a98bbb2581ef02Anders Carlsson             isa<RecordDecl>(Owner)) {
11126a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      Diag(DS.getStorageClassSpecLoc(),
11136a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola           diag::err_anonymous_union_with_storage_spec);
11146a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      Invalid = true;
11156a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
1116c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola      // Recover by removing the storage specifier.
1117c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola      DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
1118c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola                             PrevSpec);
111974391b48b4791cded373683a3baf67314f358d50Chris Lattner    }
1120570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner
11211eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    // C++ [class.union]p2:
112299b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner    //   The member-specification of an anonymous union shall only
11233c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson    //   define non-static data members. [Note: nested types and
112499b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner    //   functions cannot be declared within an anonymous union. ]
11251eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    for (DeclContext::decl_iterator Mem = Record->decls_begin(Context),
112667b00520c8f5b48fad722b790d87fea6be764efeChris Lattner                                 MemEnd = Record->decls_end(Context);
112767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner         Mem != MemEnd; ++Mem) {
112867b00520c8f5b48fad722b790d87fea6be764efeChris Lattner      if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
1129f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall        // C++ [class.union]p3:
113067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner        //   An anonymous union shall not have private or protected
113167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner        //   members (clause 11).
113267b00520c8f5b48fad722b790d87fea6be764efeChris Lattner        if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
113367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner          Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
113467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner            << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
113567b00520c8f5b48fad722b790d87fea6be764efeChris Lattner          Invalid = true;
11361eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        }
11371eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      } else if ((*Mem)->isImplicit()) {
11381eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        // Any implicit members are fine.
113999b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner      } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
1140f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall        // This is a type that showed up in an
114156ebe5082da7411fb37479e230b52735f77cff35Eli Friedman        // elaborated-type-specifier inside the anonymous struct or
114249988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar        // union, but which actually declares a type outside of the
114399b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner        // anonymous struct or union. It's okay.
114474391b48b4791cded373683a3baf67314f358d50Chris Lattner      } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
1145f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump        if (!MemRecord->isAnonymousStructOrUnion() &&
1146f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump            MemRecord->getDeclName()) {
1147da55074866ca2fe7f718c5d3334648d6e340fb15Douglas Gregor          // This is a nested type declaration.
114849988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar          Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
1149110e8e56af30363072c140285961592b0107f789John McCall            << (int)Record->isUnion();
1150af14603ca61757cf4361b583b45639a04c57e651John McCall          Invalid = true;
1151af14603ca61757cf4361b583b45639a04c57e651John McCall        }
115215e310a3b970b64a84cb30f0005bc396b4d978cbJohn McCall      } else {
1153110e8e56af30363072c140285961592b0107f789John McCall        // We have something that isn't a non-static data
1154110e8e56af30363072c140285961592b0107f789John McCall        // member. Complain about it.
1155110e8e56af30363072c140285961592b0107f789John McCall        unsigned DK = diag::err_anonymous_record_bad_member;
11560a0d2b179085a52c10402feebeb6db8b4d96a140Douglas Gregor        if (isa<TypeDecl>(*Mem))
1157110e8e56af30363072c140285961592b0107f789John McCall          DK = diag::err_anonymous_record_with_type;
1158110e8e56af30363072c140285961592b0107f789John McCall        else if (isa<FunctionDecl>(*Mem))
1159af14603ca61757cf4361b583b45639a04c57e651John McCall          DK = diag::err_anonymous_record_with_function;
1160af14603ca61757cf4361b583b45639a04c57e651John McCall        else if (isa<VarDecl>(*Mem))
1161af14603ca61757cf4361b583b45639a04c57e651John McCall          DK = diag::err_anonymous_record_with_static;
1162110e8e56af30363072c140285961592b0107f789John McCall        Diag((*Mem)->getLocation(), DK)
116356ebe5082da7411fb37479e230b52735f77cff35Eli Friedman            << (int)Record->isUnion();
116456ebe5082da7411fb37479e230b52735f77cff35Eli Friedman          Invalid = true;
116574391b48b4791cded373683a3baf67314f358d50Chris Lattner      }
11661eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    }
1167f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  }
116874391b48b4791cded373683a3baf67314f358d50Chris Lattner
1169eda9a5ec380f172f4e0063744eb796144a125480Daniel Dunbar  if (!Record->isUnion() && !Owner->isRecord()) {
1170eda9a5ec380f172f4e0063744eb796144a125480Daniel Dunbar    Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
11713bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      << (int)getLangOptions().CPlusPlus;
11725f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    Invalid = true;
11732acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  }
11743bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
11753bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  // Create a declaration for this anonymous struct/union.
11763bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  NamedDecl *Anon = 0;
11773bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
11783bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
11793bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson                             /*IdentifierInfo=*/0,
11803bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson                             Context.getTypeDeclType(Record),
11813bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson                             /*BitWidth=*/0, /*Mutable=*/false);
11823bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    Anon->setAccess(AS_public);
11833bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    if (getLangOptions().CPlusPlus)
11843bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      FieldCollector->Add(cast<FieldDecl>(Anon));
11853bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  } else {
118696eaf2992b5955d1470fc9cce7a96e7e1e3b4ea7Anders Carlsson    VarDecl::StorageClass SC;
11873bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    switch (DS.getStorageClassSpec()) {
11883bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    default: assert(0 && "Unknown storage class!");
11893bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
11903bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
11913bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
11923bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
11933bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
11943bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
11953bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    case DeclSpec::SCS_mutable:
11963bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      // mutable can only appear on non-static class members, so it's always
11973bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      // an error here
11983bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      Diag(Record->getLocation(), diag::err_mutable_nonmember);
11993bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      Invalid = true;
12003bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      SC = VarDecl::None;
12013bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      break;
12023bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    }
12033bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
12043bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
12053bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson                           /*IdentifierInfo=*/0,
12063bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson                           Context.getTypeDeclType(Record),
12073bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson                           SC, DS.getSourceRange().getBegin());
12083bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  }
12093bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  Anon->setImplicit();
121074391b48b4791cded373683a3baf67314f358d50Chris Lattner
121174391b48b4791cded373683a3baf67314f358d50Chris Lattner  // Add the anonymous struct/union object to the current
121274391b48b4791cded373683a3baf67314f358d50Chris Lattner  // context. We'll be referencing this object when we refer to one of
121374391b48b4791cded373683a3baf67314f358d50Chris Lattner  // its members.
121474391b48b4791cded373683a3baf67314f358d50Chris Lattner  Owner->addDecl(Context, Anon);
12152acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner
121674391b48b4791cded373683a3baf67314f358d50Chris Lattner  // Inject the members of the anonymous struct/union into the owning
121774391b48b4791cded373683a3baf67314f358d50Chris Lattner  // context and into the identifier resolver chain for name lookup
121874391b48b4791cded373683a3baf67314f358d50Chris Lattner  // purposes.
121974391b48b4791cded373683a3baf67314f358d50Chris Lattner  if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
12201eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    Invalid = true;
12212acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner
1222207f4d8543529221932af82836016a2ef066c917Peter Collingbourne  // Mark this as an anonymous struct/union type. Note that we do not
1223f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  // do this until after we have already checked and injected the
12245f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  // members of this anonymous struct/union type, because otherwise
1225f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  // the members could be injected twice: once by DeclContext when it
122674391b48b4791cded373683a3baf67314f358d50Chris Lattner  // builds its lookup table, and once by
12273f75c43bd77e063342bc888ac276daf64ba0ce07Daniel Dunbar  // InjectAnonymousStructOrUnionMembers.
122874391b48b4791cded373683a3baf67314f358d50Chris Lattner  Record->setAnonymousStructOrUnion(true);
122974391b48b4791cded373683a3baf67314f358d50Chris Lattner
123074391b48b4791cded373683a3baf67314f358d50Chris Lattner  if (Invalid)
12312acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner    Anon->setInvalidDecl();
12325f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner
12331de4d4e8cb2e9c88809fea8092bc6e835a5473d2John McCall  return DeclPtrTy::make(Anon);
1234c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola}
1235bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
1236bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
123703f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar/// GetNameForDeclarator - Determine the full declaration name for the
123803f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar/// given Declarator.
123903f5ad9a7707e098f601921fcec17ed65eb355a7Daniel DunbarDeclarationName Sema::GetNameForDeclarator(Declarator &D) {
12407520bd1de12af10ea08c662440565adbdf589317Douglas Gregor  switch (D.getKind()) {
12417520bd1de12af10ea08c662440565adbdf589317Douglas Gregor  case Declarator::DK_Abstract:
12427520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    assert(D.getIdentifier() == 0 && "abstract declarators have no name");
12437520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    return DeclarationName();
12445f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner
1245f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  case Declarator::DK_Normal:
1246555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson    assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
124703f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    return DeclarationName(D.getIdentifier());
12487520bd1de12af10ea08c662440565adbdf589317Douglas Gregor
12497520bd1de12af10ea08c662440565adbdf589317Douglas Gregor  case Declarator::DK_Constructor: {
12507520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
12517520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    Ty = Context.getCanonicalType(Ty);
125203f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    return Context.DeclarationNames.getCXXConstructorName(Ty);
125303f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar  }
125403f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar
12556fb745bdf1ff1e32caf07e42093a7920726892c1Douglas Gregor  case Declarator::DK_Destructor: {
12566fb745bdf1ff1e32caf07e42093a7920726892c1Douglas Gregor    QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
12576fb745bdf1ff1e32caf07e42093a7920726892c1Douglas Gregor    Ty = Context.getCanonicalType(Ty);
12586fb745bdf1ff1e32caf07e42093a7920726892c1Douglas Gregor    return Context.DeclarationNames.getCXXDestructorName(Ty);
12596fb745bdf1ff1e32caf07e42093a7920726892c1Douglas Gregor  }
12604b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor
1261046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson  case Declarator::DK_Conversion: {
1262cb5d2d0647fdab2e36c85b417e03bf18916ce10cEli Friedman    // FIXME: We'd like to keep the non-canonical type for diagnostics!
1263dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1264dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    Ty = Context.getCanonicalType(Ty);
1265dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1266dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  }
1267dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor
1268dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  case Declarator::DK_Operator:
12694b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor    assert(D.getIdentifier() == 0 && "operator names have no identifier");
127006a54a38be5054c910ffc92db60edab23f9ea105Argyrios Kyrtzidis    return Context.DeclarationNames.getCXXOperatorName(
12714b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor                                                D.getOverloadedOperator());
1272dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  }
12734b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor
12744b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor  assert(false && "Unknown name kind");
12754b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor  return DeclarationName();
12766d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson}
12776d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson
12786d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson/// isNearlyMatchingFunction - Determine whether the C++ functions
12796d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson/// Declaration and Definition are "nearly" matching. This heuristic
12806d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson/// is used to improve diagnostics in the case where an out-of-line
12816d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson/// function definition doesn't match any declaration within
12824b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor/// the class or namespace.
1283142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanianstatic bool isNearlyMatchingFunction(ASTContext &Context,
1284142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                                     FunctionDecl *Declaration,
1285142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                                     FunctionDecl *Definition) {
12864b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor  if (Declaration->param_size() != Definition->param_size())
12874b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor    return false;
12884b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor  for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
12894b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor    QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1290142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian    QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1291142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian
1292142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian    DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1293f502d93b0ea970bfbd897e657f8d940a20984de2Anders Carlsson    DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
12944b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor    if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1295142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian      return false;
1296142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian  }
1297142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian
1298f502d93b0ea970bfbd897e657f8d940a20984de2Anders Carlsson  return true;
12994b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor}
13004b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor
13014b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas GregorSema::DeclPtrTy
13024b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas GregorSema::ActOnDeclarator(Scope *S, Declarator &D, bool IsFunctionDefinition) {
1303142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian  DeclarationName Name = GetNameForDeclarator(D);
1304142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian
1305142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian  // All of these full declarators require an identifier.  If it doesn't have
13064b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor  // one, the ParsedFreeStandingDeclSpec action should be used.
1307dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  if (!Name) {
1308dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    if (!D.getInvalidType())  // Reject this if we think it is valid.
130953bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian      Diag(D.getDeclSpec().getSourceRange().getBegin(),
131053bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian           diag::err_declarator_need_ident)
131153bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian        << D.getDeclSpec().getSourceRange() << D.getSourceRange();
1312dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    return DeclPtrTy();
1313dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  }
1314dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor
1315dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  // The scope passed in may not be a decl scope.  Zip up the scope tree until
1316dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  // we find one that is.
1317dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  while ((S->getFlags() & Scope::DeclScope) == 0 ||
1318dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor         (S->getFlags() & Scope::TemplateParamScope) != 0)
1319142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian    S = S->getParent();
132053bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian
1321142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian  DeclContext *DC;
1322142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian  NamedDecl *PrevDecl;
132353bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian  NamedDecl *New;
13244b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor  bool InvalidDecl = false;
13254b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor
13264b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor  QualType R = GetTypeForDeclarator(D, S);
132753bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian  if (R.isNull()) {
13284b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor    InvalidDecl = true;
13294b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor    R = Context.IntTy;
13302acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner    if (IsFunctionDefinition) // int(...)
133106f486ecd05bd6788da97c39164c1903a084c26dKen Dyck      R = Context.getFunctionType(R, 0, 0, true, 0);
133206f486ecd05bd6788da97c39164c1903a084c26dKen Dyck
1333687cc4a850b59116efee061018f0d8df50728b82Ken Dyck  }
1334687cc4a850b59116efee061018f0d8df50728b82Ken Dyck
1335bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  // See if this is a redefinition of a variable in the same scope.
13368f32f7189b12f67aa4a19bc7c3855b599980eca0Chris Lattner  if (D.getCXXScopeSpec().isInvalid()) {
133777ba708819285931932ecd33691a672bb59d221aEli Friedman    DC = CurContext;
13386c6bda3b0b1d8adaac2ba3f4da7056e9f1eef52eEli Friedman    PrevDecl = 0;
13391eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    InvalidDecl = true;
134031310a21fb2a9f13950f864f681c86080b05d5b2Sebastian Redl  } else if (!D.getCXXScopeSpec().isSet()) {
13413bb92693c3332c1e99870a4e45afff3892e1c6aeAnders Carlsson    LookupNameKind NameKind = LookupOrdinaryName;
13423bb92693c3332c1e99870a4e45afff3892e1c6aeAnders Carlsson
1343cd5f4aaf0c219189878126d556f35e38fdb8afa1Eli Friedman    // If the declaration we're planning to build will be a function
134403f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // or object with linkage, then look for another declaration with
134503f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
134603f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
134703f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar      /* Do nothing*/;
134803f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    else if (R->isFunctionType()) {
134903f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar      if (CurContext->isFunctionOrMethod())
135003f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar        NameKind = LookupRedeclarationWithLinkage;
135103f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
135203f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar      NameKind = LookupRedeclarationWithLinkage;
1353b0d0ea042116c1f451d3db8ceff9f1dd92bc36d2Anders Carlsson
135477ba708819285931932ecd33691a672bb59d221aEli Friedman    DC = CurContext;
1355c446d1816f46a4b6d2337102dfc001f55fc18211Douglas Gregor    PrevDecl = LookupName(S, Name, NameKind, true,
13566e656f45ae04b415ba7a4c0c25e55633e2d0ecd0Eli Friedman                          D.getDeclSpec().getStorageClassSpec() !=
13573bb92693c3332c1e99870a4e45afff3892e1c6aeAnders Carlsson                            DeclSpec::SCS_static,
1358c446d1816f46a4b6d2337102dfc001f55fc18211Douglas Gregor                          D.getIdentifierLoc());
1359c446d1816f46a4b6d2337102dfc001f55fc18211Douglas Gregor  } else { // Something like "int foo::x;"
1360c446d1816f46a4b6d2337102dfc001f55fc18211Douglas Gregor    DC = computeDeclContext(D.getCXXScopeSpec());
136189ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson    // FIXME: RequireCompleteDeclContext(D.getCXXScopeSpec()); ?
136289ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson    PrevDecl = LookupQualifiedName(DC, Name, LookupOrdinaryName, true);
13636c6bda3b0b1d8adaac2ba3f4da7056e9f1eef52eEli Friedman
136489ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson    // C++ 7.3.1.2p2:
136589ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson    // Members (including explicit specializations of templates) of a named
136689ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson    // namespace can also be defined outside that namespace by explicit
136789ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson    // qualification of the name being defined, provided that the entity being
1368bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall    // defined was already declared in the namespace and the definition appears
1369bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall    // after the point of declaration in a namespace that encloses the
1370bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall    // declarations namespace.
1371bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall    //
1372bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall    // Note that we only check the context at this point. We don't yet
13736e656f45ae04b415ba7a4c0c25e55633e2d0ecd0Eli Friedman    // have enough information to make sure that PrevDecl is actually
13748f32f7189b12f67aa4a19bc7c3855b599980eca0Chris Lattner    // the declaration we want to match. For example, given:
13758e53e720b3d7c962e91138a130dbd5d6c2def0e5Devang Patel    //
13762acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner    //   class X {
1377570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    //     void f();
13781eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    //     void f(float);
1379570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    //   };
1380570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    //
13819d4a15fd3b85434c43ea27562793de63a793321aChris Lattner    //   void X::f(int) { } // ill-formed
13829d4a15fd3b85434c43ea27562793de63a793321aChris Lattner    //
13839d4a15fd3b85434c43ea27562793de63a793321aChris Lattner    // In this case, PrevDecl will point to the overload set
1384570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    // containing the two f's declared in X, but neither of them
1385570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    // matches.
13861eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1387570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    // First check whether we named the global scope.
1388570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    if (isa<TranslationUnitDecl>(DC)) {
13891eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
1390570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner        << Name << D.getCXXScopeSpec().getRange();
1391570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    } else if (!CurContext->Encloses(DC)) {
1392570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner      // The qualifying scope doesn't enclose the original declaration.
1393570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner      // Emit diagnostic based on current scope.
1394570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner      SourceLocation L = D.getIdentifierLoc();
1395570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner      SourceRange R = D.getCXXScopeSpec().getRange();
1396570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner      if (isa<FunctionDecl>(CurContext))
1397570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner        Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
1398570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner      else
1399570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner        Diag(L, diag::err_invalid_declarator_scope)
1400570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner          << Name << cast<NamedDecl>(DC) << R;
1401207f4d8543529221932af82836016a2ef066c917Peter Collingbourne      InvalidDecl = true;
1402207f4d8543529221932af82836016a2ef066c917Peter Collingbourne    }
14031eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  }
1404f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall
14055f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  if (PrevDecl && PrevDecl->isTemplateParameter()) {
1406232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar    // Maybe we will complain about the shadowed template parameter.
1407570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    InvalidDecl = InvalidDecl
1408570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner      || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14090558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    // Just pretend that we didn't see the previous declaration.
141077ba708819285931932ecd33691a672bb59d221aEli Friedman    PrevDecl = 0;
14111eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  }
14123c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson
1413570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // In C++, the previous declaration we find might be a tag type
141477ba708819285931932ecd33691a672bb59d221aEli Friedman  // (class or enum). In this case, the new declaration will hide the
141577ba708819285931932ecd33691a672bb59d221aEli Friedman  // tag type. Note that this does does not apply if we're declaring a
1416570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // typedef (C++ [dcl.typedef]p4).
141777ba708819285931932ecd33691a672bb59d221aEli Friedman  if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag &&
141877ba708819285931932ecd33691a672bb59d221aEli Friedman      D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
141977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    PrevDecl = 0;
142077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
14218bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  bool Redeclaration = false;
142288a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
1423e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner    New = ActOnTypedefDeclarator(S, D, DC, R, PrevDecl,
1424e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner                                 InvalidDecl, Redeclaration);
1425e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner  } else if (R->isFunctionType()) {
1426da55074866ca2fe7f718c5d3334648d6e340fb15Douglas Gregor    New = ActOnFunctionDeclarator(S, D, DC, R, PrevDecl,
1427e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner                                  IsFunctionDefinition, InvalidDecl,
14281eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                  Redeclaration);
14298b752f10c394b140f9ef89e049cbad1a7676fc25Ken Dyck  } else {
1430354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    New = ActOnVariableDeclarator(S, D, DC, R, PrevDecl,
143188a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner                                  InvalidDecl, Redeclaration);
1432354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  }
1433354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian
1434354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  if (New == 0)
1435354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    return DeclPtrTy();
1436354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian
1437354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  // If this has an identifier and is not an invalid redeclaration,
1438354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  // add it to the scope stack.
1439354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  if (Name && !(Redeclaration && InvalidDecl))
1440354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    PushOnScopeChains(New, S);
14413030eb82593097502469a8b3fc26112c79c75605John McCall  // If any semantic error occurred, mark the decl as invalid.
14423030eb82593097502469a8b3fc26112c79c75605John McCall  if (D.getInvalidType() || InvalidDecl)
14433030eb82593097502469a8b3fc26112c79c75605John McCall    New->setInvalidDecl();
14443030eb82593097502469a8b3fc26112c79c75605John McCall
1445354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  return DeclPtrTy::make(New);
144673fb35003aad027492e661a3749e921b5d1ecaf9Eric Christopher}
1447354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian
1448354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
1449354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian/// types into constant array types in certain situations which would otherwise
1450354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian/// be errors (for GCC compatibility).
1451354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanianstatic QualType TryToFixInvalidVariablyModifiedType(QualType T,
1452354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian                                                    ASTContext &Context,
145390e99a84ddd020e8fda79643748243725a2ed071Argyrios Kyrtzidis                                                    bool &SizeIsNegative) {
1454a0f00a71fcb0f98298709d5e5318339acf7958acDouglas Gregor  // This method tries to turn a variable array into a constant
1455354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  // array even when the size isn't an ICE.  This is necessary
145640b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  // for compatibility with code that depends on gcc's buggy
1457354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  // constant expression folding, like struct {char x[(int)(char*)2];}
145840b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  SizeIsNegative = false;
1459354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian
1460e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner  if (const PointerType* PTy = dyn_cast<PointerType>(T)) {
1461e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner    QualType Pointee = PTy->getPointeeType();
1462354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    QualType FixedType =
1463e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner        TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative);
1464354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    if (FixedType.isNull()) return FixedType;
14658f51a4f2d00b0abda3cde7f3828fb2e2b9beafb5Douglas Gregor    FixedType = Context.getPointerType(FixedType);
14668f51a4f2d00b0abda3cde7f3828fb2e2b9beafb5Douglas Gregor    FixedType.setCVRQualifiers(T.getCVRQualifiers());
146799ace16bc6962f1fc3dc45bbbdf2eb74e555a8adJohn McCall    return FixedType;
1468a6cf1e709b96865210b81bd611d41e9a2d41500aEric Christopher  }
1469a6cf1e709b96865210b81bd611d41e9a2d41500aEric Christopher
1470a6cf1e709b96865210b81bd611d41e9a2d41500aEric Christopher  const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
1471309457d0f1b416c1b379c9f3e172848adffedb23Chris Lattner  if (!VLATy)
1472ab27d6ea7b4ce2762a16905281de796db32bb6f2Fariborz Jahanian    return QualType();
1473ab27d6ea7b4ce2762a16905281de796db32bb6f2Fariborz Jahanian  // FIXME: We should probably handle this case
147491f31dc234bbc98f3dd20e6741a7b0b98c7916bfEric Christopher  if (VLATy->getElementType()->isVariablyModifiedType())
1475354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    return QualType();
1476686226b538e72c5059ab7c9a8f87eb883193b645Sanjiv Gupta
1477354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  Expr::EvalResult EvalResult;
147888a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner  if (!VLATy->getSizeExpr() ||
14795f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer      !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) ||
1480bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      !EvalResult.Val.isInt())
1481bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    return QualType();
1482bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1483bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  llvm::APSInt &Res = EvalResult.Val.getInt();
1484bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
1485bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    return Context.getConstantArrayType(VLATy->getElementType(),
1486bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner                                        Res, ArrayType::Normal, 0);
1487bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1488bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  SizeIsNegative = true;
1489bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  return QualType();
1490bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner}
1491bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1492bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// \brief Register the given locally-scoped external C declaration so
1493bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// that it can be found later for redeclarations
14941eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpvoid
14952acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris LattnerSema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, NamedDecl *PrevDecl,
14965f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner                                       Scope *S) {
1497bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
1498bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner         "Decl is not a locally-scoped decl!");
1499dbf02bccc9fc1115cb7dd45c84df77252d68f220Benjamin Kramer  // Note that we have a locally-scoped external with this name.
1500bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  LocallyScopedExternalDecls[ND->getDeclName()] = ND;
1501dbf02bccc9fc1115cb7dd45c84df77252d68f220Benjamin Kramer
1502dbf02bccc9fc1115cb7dd45c84df77252d68f220Benjamin Kramer  if (!PrevDecl)
15038670cd3ea4dfbf86caacd270ec2441e9949bbb6aGabor Greif    return;
150435db3b9aad1829a1279b9e213ddee36395314a0bGabor Greif
1505dbf02bccc9fc1115cb7dd45c84df77252d68f220Benjamin Kramer  // If there was a previous declaration of this variable, it may be
15061eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // in our identifier chain. Update the identifier chain with the new
1507bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  // declaration.
1508bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
1509bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // The previous declaration was found on the identifer resolver
1510bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // chain, so remove it from its scope.
1511bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    while (S && !S->isDeclScope(DeclPtrTy::make(PrevDecl)))
151240f9c302f23a35611cd354f40b22b37f2c554a40John McCall      S = S->getParent();
151340f9c302f23a35611cd354f40b22b37f2c554a40John McCall
151440f9c302f23a35611cd354f40b22b37f2c554a40John McCall    if (S)
151540f9c302f23a35611cd354f40b22b37f2c554a40John McCall      S->RemoveDecl(DeclPtrTy::make(PrevDecl));
151640f9c302f23a35611cd354f40b22b37f2c554a40John McCall  }
151740f9c302f23a35611cd354f40b22b37f2c554a40John McCall}
151840f9c302f23a35611cd354f40b22b37f2c554a40John McCall
151940f9c302f23a35611cd354f40b22b37f2c554a40John McCall/// \brief Diagnose function specifiers on a declaration of an identifier that
152040f9c302f23a35611cd354f40b22b37f2c554a40John McCall/// does not identify a function.
152140f9c302f23a35611cd354f40b22b37f2c554a40John McCallvoid Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
152240f9c302f23a35611cd354f40b22b37f2c554a40John McCall  // FIXME: We should probably indicate the identifier in question to avoid
1523bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  // confusion for constructs like "inline int a(), b;"
1524bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  if (D.getDeclSpec().isInlineSpecified())
1525bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    Diag(D.getDeclSpec().getInlineSpecLoc(),
1526bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner         diag::err_inline_non_function);
1527bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1528bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  if (D.getDeclSpec().isVirtualSpecified())
1529bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    Diag(D.getDeclSpec().getVirtualSpecLoc(),
153035db3b9aad1829a1279b9e213ddee36395314a0bGabor Greif         diag::err_virtual_non_function);
153135db3b9aad1829a1279b9e213ddee36395314a0bGabor Greif
1532bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  if (D.getDeclSpec().isExplicitSpecified())
1533bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    Diag(D.getDeclSpec().getExplicitSpecLoc(),
1534bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner         diag::err_explicit_non_function);
153540f9c302f23a35611cd354f40b22b37f2c554a40John McCall}
153640f9c302f23a35611cd354f40b22b37f2c554a40John McCall
153740f9c302f23a35611cd354f40b22b37f2c554a40John McCallNamedDecl*
153840f9c302f23a35611cd354f40b22b37f2c554a40John McCallSema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1539bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner                             QualType R, Decl* PrevDecl, bool& InvalidDecl,
1540bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner                             bool &Redeclaration) {
1541bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
15421eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  if (D.getCXXScopeSpec().isSet()) {
154340f9c302f23a35611cd354f40b22b37f2c554a40John McCall    Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
154440f9c302f23a35611cd354f40b22b37f2c554a40John McCall      << D.getCXXScopeSpec().getRange();
154540f9c302f23a35611cd354f40b22b37f2c554a40John McCall    InvalidDecl = true;
1546bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // Pretend we didn't see the scope specifier.
1547bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    DC = 0;
15486ba728d9687b2617793f5afd410650a8d6c71080Gabor Greif  }
15494c7d9f1507d0f102bd4133bba63348636facd469Jay Foad
1550bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  if (getLangOptions().CPlusPlus) {
1551ffbb15e54a6dc120087003d1e42448b8705bd58aBenjamin Kramer    // Check that there are no default arguments (C++ only).
1552bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    CheckExtraCXXDefaultArguments(D);
155340f9c302f23a35611cd354f40b22b37f2c554a40John McCall  }
155440f9c302f23a35611cd354f40b22b37f2c554a40John McCall
1555ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar  DiagnoseFunctionSpecifiers(D);
1556bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1557bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  TypedefDecl *NewTD = ParseTypedefDecl(S, D, R);
155800549fcec0490b2daf27543e532f94adbb186063Chris Lattner  if (!NewTD) return 0;
155900549fcec0490b2daf27543e532f94adbb186063Chris Lattner
15603b122bc5f1203615e2128e0c1a63da438865b1ccDevang Patel  // Handle attributes prior to checking for duplicates in MergeVarDecl
1561c60346388d60b1756f3675dabb60dc58da0728ecChris Lattner  ProcessDeclAttributes(NewTD, D);
1562c60346388d60b1756f3675dabb60dc58da0728ecChris Lattner  // Merge the decl with the existing one if appropriate. If the decl is
1563c60346388d60b1756f3675dabb60dc58da0728ecChris Lattner  // in an outer scope, it isn't the same thing.
1564bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1565bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    Redeclaration = true;
1566bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    if (MergeTypeDefDecl(NewTD, PrevDecl))
1567bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      InvalidDecl = true;
1568bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  }
1569b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner
1570b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner  if (S->getFnParent() == 0) {
1571d26bc76c98006609002d9930f8840490e88ac5b5John McCall    QualType T = NewTD->getUnderlyingType();
15721f6f961293da9c2b1c23da2411c1b439a9502ed0John McCall    // C99 6.7.7p2: If a typedef name specifies a variably modified type
1573d26bc76c98006609002d9930f8840490e88ac5b5John McCall    // then it shall have block scope.
15741f6f961293da9c2b1c23da2411c1b439a9502ed0John McCall    if (T->isVariablyModifiedType()) {
15751f6f961293da9c2b1c23da2411c1b439a9502ed0John McCall      bool SizeIsNegative;
15761f6f961293da9c2b1c23da2411c1b439a9502ed0John McCall      QualType FixedTy =
15772acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner          TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
1578d26bc76c98006609002d9930f8840490e88ac5b5John McCall      if (!FixedTy.isNull()) {
15799fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner        Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size);
1580b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner        NewTD->setUnderlyingType(FixedTy);
15811eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      } else {
15820558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner        if (SizeIsNegative)
15830558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner          Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size);
15840558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner        else if (T->isVariableArrayType())
15850558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner          Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
15860558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner        else
15871eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump          Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
15881eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        InvalidDecl = true;
15890558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner      }
1590bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    }
15911eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  }
159242745815fa4e90bfb07e581d2e5152b2c2db08ffDaniel Dunbar  return NewTD;
1593bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner}
15940558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner
159534809507232bc4c3c4840c7d092c7440219fddafChris Lattner/// \brief Determines whether the given declaration is an out-of-scope
159662b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner/// previous declaration.
159762b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner///
159862b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner/// This routine should be invoked when name lookup has found a
159962b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner/// previous declaration (PrevDecl) that is not in the scope where a
160062b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner/// new declaration by the same name is being introduced. If the new
160162b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner/// declaration occurs in a local scope, previous declarations with
1602f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall/// linkage may still be considered previous declarations (C99
1603f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall/// 6.2.2p4-5, C++ [basic.link]p6).
16045f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner///
1605b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner/// \param PrevDecl the previous declaration found by name
16061eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump/// lookup
1607bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner///
1608bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// \param DC the context in which the new declaration is being
1609bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// declared.
16109fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner///
1611bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// \returns true if PrevDecl is an out-of-scope previous declaration
16129fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner/// for a new delcaration with the same name.
16139fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattnerstatic bool
16141eb4433ac451dc16f4133a88af2d002ac26c58efMike StumpisOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
161562b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner                                ASTContext &Context) {
1616bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  if (!PrevDecl)
16171eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    return 0;
16183c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson
1619bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  // FIXME: PrevDecl could be an OverloadedFunctionDecl, in which
1620bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  // case we need to check each of the overloaded functions.
16211eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  if (!PrevDecl->hasLinkage())
162262b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    return false;
1623bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
16241eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  if (Context.getLangOptions().CPlusPlus) {
16250558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    // C++ [basic.link]p6:
1626bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar    //   If there is a visible declaration of an entity with linkage
16271eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    //   having the same name and type, ignoring entities declared
1628112c967bd5c862a0f5d7913aa06700c048807db8John McCall    //   outside the innermost enclosing namespace scope, the block
1629112c967bd5c862a0f5d7913aa06700c048807db8John McCall    //   scope declaration declares that same entity and receives the
1630112c967bd5c862a0f5d7913aa06700c048807db8John McCall    //   linkage of the previous declaration.
1631112c967bd5c862a0f5d7913aa06700c048807db8John McCall    DeclContext *OuterContext = DC->getLookupContext();
16320558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    if (!OuterContext->isFunctionOrMethod())
16338b2423361648c39a7d8a3c5e8129e12006deac32John McCall      // This rule only applies to block-scope declarations.
1634bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar      return false;
1635112c967bd5c862a0f5d7913aa06700c048807db8John McCall    else {
16360ffeaad72cb335b926b064379be4c9886bbff004Anders Carlsson      DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
1637112c967bd5c862a0f5d7913aa06700c048807db8John McCall      if (PrevOuterContext->isRecord())
1638d26bc76c98006609002d9930f8840490e88ac5b5John McCall        // We found a member function: ignore it.
16396379a7a15335e0af543a942efe9cfd514a83dab8Daniel Dunbar        return false;
16407c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar      else {
16417c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar        // Find the innermost enclosing namespace for the new and
16421eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        // previous declarations.
164340b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis        while (!OuterContext->isFileContext())
1644219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar          OuterContext = OuterContext->getParent();
164540b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis        while (!PrevOuterContext->isFileContext())
1646219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar          PrevOuterContext = PrevOuterContext->getParent();
164777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
164877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge        // The previous declaration is in a different namespace, so it
1649bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar        // isn't the same function.
1650bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar        if (OuterContext->getPrimaryContext() !=
1651f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall            PrevOuterContext->getPrimaryContext())
1652f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall          return false;
165340b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis      }
1654bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    }
1655bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  }
16565f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner
1657f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  return true;
1658f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall}
1659f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall
1660f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCallNamedDecl*
1661f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCallSema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1662f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall                              QualType R,NamedDecl* PrevDecl, bool& InvalidDecl,
16631eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                              bool &Redeclaration) {
16642acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  DeclarationName Name = GetNameForDeclarator(D);
1665bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
1666bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // Check that there are no default arguments (C++ only).
1667bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  if (getLangOptions().CPlusPlus)
1668bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    CheckExtraCXXDefaultArguments(D);
1669bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
16701faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson  VarDecl *NewVD;
16711faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson  VarDecl::StorageClass SC;
1672bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  switch (D.getDeclSpec().getStorageClassSpec()) {
1673f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  default: assert(0 && "Unknown storage class!");
167496e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson  case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
1675bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
1676bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
16771eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
1678bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
1679bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1680bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  case DeclSpec::SCS_mutable:
16811eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    // mutable can only appear on non-static class members, so it's always
1682bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    // an error here
1683f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1684f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    InvalidDecl = true;
1685bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    SC = VarDecl::None;
1686bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    break;
1687bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  }
1688bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
1689bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  IdentifierInfo *II = Name.getAsIdentifierInfo();
1690bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  if (!II) {
1691bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1692f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall      << Name.getAsString();
16931eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    return 0;
16943c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson  }
1695bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
1696bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  DiagnoseFunctionSpecifiers(D);
1697f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall
16989a20d55807cc2f6534a9c51a46cc8143ed16786dAnders Carlsson  bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
1699bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  if (!DC->isRecord() && S->getFnParent() == 0) {
17001eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    // C99 6.9p2: The storage-class specifiers auto and register shall not
17017c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    // appear in the declaration specifiers in an external declaration.
17027c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    if (SC == VarDecl::Auto || SC == VarDecl::Register) {
17037c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar      Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
170440b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis      InvalidDecl = true;
17057c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    }
17067c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  }
170706a54a38be5054c910ffc92db60edab23f9ea105Argyrios Kyrtzidis  if (DC->isRecord() && !CurContext->isRecord()) {
17087c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    // This is an out-of-line definition of a static data member.
17097c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    if (SC == VarDecl::Static) {
17107c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
17117c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar           diag::err_static_out_of_line)
17121eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        << CodeModificationHint::CreateRemoval(
171311e8ce7380856abee188b237c2600272df2ed09dRafael Espindola                       SourceRange(D.getDeclSpec().getStorageClassSpecLoc()));
17140a0d2b179085a52c10402feebeb6db8b4d96a140Douglas Gregor    } else if (SC == VarDecl::None)
17157c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar      SC = VarDecl::Static;
17167c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  }
17177c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
17187c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // The variable can not
1719bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1720bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner                          II, R, SC,
17218dd55a3c3b28d195717c87bbc60e765951d408feBenjamin Kramer                          // FIXME: Move to DeclGroup...
17222d3ba4f5a923a90c3fc290ddfba5e36c2d0a9b46Chris Lattner                          D.getDeclSpec().getSourceRange().getBegin());
1723df983a8bcbbcea911b8dce283f044787df119d50Jay Foad  NewVD->setThreadSpecified(ThreadSpecified);
17248dd55a3c3b28d195717c87bbc60e765951d408feBenjamin Kramer
17257acda7c4a0e4aec6c003b3169ca45a5f3bc7e033Chris Lattner  // Set the lexical context. If the declarator has a C++ scope specifier, the
1726bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner  // lexical context will be different from the semantic context.
17271d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  NewVD->setLexicalDeclContext(CurContext);
17281d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar
17291d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  // Handle attributes prior to checking for duplicates in MergeVarDecl
173070ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  ProcessDeclAttributes(NewVD, D);
17311d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar
17321d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  // Handle GNU asm-label extension (encoded as an attribute).
17335f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  if (Expr *E = (Expr*) D.getAsmLabel()) {
17342f4eaef37476ae6891ede8ba215d0f6fd093629bBenjamin Kramer    // The parser guarantees this is a string.
17351d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar    StringLiteral *SE = cast<StringLiteral>(E);
1736f015b034159d40e7033309e50036804eb1971787Daniel Dunbar    NewVD->addAttr(::new (Context) AsmLabelAttr(std::string(SE->getStrData(),
1737f015b034159d40e7033309e50036804eb1971787Daniel Dunbar                                                        SE->getByteLength())));
1738f015b034159d40e7033309e50036804eb1971787Daniel Dunbar  }
17392f4eaef37476ae6891ede8ba215d0f6fd093629bBenjamin Kramer
1740f015b034159d40e7033309e50036804eb1971787Daniel Dunbar  // If name lookup finds a previous declaration that is not in the
1741f015b034159d40e7033309e50036804eb1971787Daniel Dunbar  // same scope as the new declaration, this may still be an
17421d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  // acceptable redeclaration.
17435f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  if (PrevDecl && !isDeclInScope(PrevDecl, DC, S) &&
17442f4eaef37476ae6891ede8ba215d0f6fd093629bBenjamin Kramer      !(NewVD->hasLinkage() &&
17451d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar        isOutOfScopePreviousDeclaration(PrevDecl, DC, Context)))
17461eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    PrevDecl = 0;
1747e7ddfb974884ec75ffd66953b79511ea457493baFariborz Jahanian
1748e7ddfb974884ec75ffd66953b79511ea457493baFariborz Jahanian  // Merge the decl with the existing one if appropriate.
1749e7ddfb974884ec75ffd66953b79511ea457493baFariborz Jahanian  if (PrevDecl) {
17501eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
175170ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar      // The user tried to define a non-static data member
17521d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar      // out-of-line (C++ [dcl.meaning]p1).
175370ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar      Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
175470ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar        << D.getCXXScopeSpec().getRange();
175570ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar      PrevDecl = 0;
175670ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar      InvalidDecl = true;
175770ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar    }
175870ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  } else if (D.getCXXScopeSpec().isSet()) {
175970ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar    // No previous declaration in the qualifying scope.
176070ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar    Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
176170ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar      << Name << D.getCXXScopeSpec().getRange();
176270ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar    InvalidDecl = true;
176370ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  }
176470ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar
176570ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  if (CheckVariableDeclaration(NewVD, PrevDecl, Redeclaration))
176670ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar    InvalidDecl = true;
176770ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar
176870ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  // If this is a locally-scoped extern C variable, update the map of
176970ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  // such variables.
1770434da48d0e35764f18b3fc96c75504746050b046Daniel Dunbar  if (CurContext->isFunctionOrMethod() && NewVD->isExternC(Context) &&
1771434da48d0e35764f18b3fc96c75504746050b046Daniel Dunbar      !InvalidDecl)
1772434da48d0e35764f18b3fc96c75504746050b046Daniel Dunbar    RegisterLocallyScopedExternCDecl(NewVD, PrevDecl, S);
177370ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar
17741d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  return NewVD;
17755f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner}
17761d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar
17771d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar/// \brief Perform semantic checking on a newly-created variable
1778cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian/// declaration.
1779cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian///
1780cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian/// This routine performs all of the type-checking required for a
1781cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian/// variable declaration once it has been build. It is used both to
1782cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian/// check variables after they have been parsed and their declarators
17835f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner/// have been translated into a declaration, and to check
1784cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian///
1785cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian/// \returns true if an error was encountered, false otherwise.
1786cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanianbool Sema::CheckVariableDeclaration(VarDecl *NewVD, NamedDecl *PrevDecl,
1787cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian                                    bool &Redeclaration) {
17881d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  bool Invalid = false;
17891d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar
17901d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  QualType T = NewVD->getType();
17911d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar
17921d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  if (T->isObjCInterfaceType()) {
17931eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    Diag(NewVD->getLocation(), diag::err_statically_allocated_object);
179470ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar    Invalid = true;
179570ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  }
17961eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
17971d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  // The variable can not have an abstract class type.
17981d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  if (RequireNonAbstractType(NewVD->getLocation(), T,
17991eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                             diag::err_abstract_type_in_decl,
18000032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson                             AbstractVariableType))
18010032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson    Invalid = true;
18023e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar
18031eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // Emit an error if an address space was applied to decl with local storage.
18049d4a15fd3b85434c43ea27562793de63a793321aChris Lattner  // This includes arrays of objects with address space qualifiers, but not
1805c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // automatic variables that point to other address spaces.
18062acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  // ISO/IEC TR 18037 S5.1.2
180796e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson  if (NewVD->hasLocalStorage() && (T.getAddressSpace() != 0)) {
18081eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
18099d4a15fd3b85434c43ea27562793de63a793321aChris Lattner    Invalid = true;
18103e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar  }
18113e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar
1812a5c04344fa70d6eec34344760c1fe511e16f2d76Jay Foad  if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
1813c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson      && !NewVD->hasAttr<BlocksAttr>())
18141eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
1815e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson
18163e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar  bool isIllegalVLA = T->isVariableArrayType() && NewVD->hasGlobalStorage();
18172acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  bool isIllegalVM = T->isVariablyModifiedType() && NewVD->hasLinkage();
1818e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  if (isIllegalVLA || isIllegalVM) {
1819e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson    bool SizeIsNegative;
18201d236ab930816f5da27bade92904914c44b73b4cBenjamin Kramer    QualType FixedTy =
182144b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor        TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
1822c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson    if (!FixedTy.isNull()) {
18235add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson      Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
18241eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      NewVD->setType(FixedTy);
1825c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson    } else if (T->isVariableArrayType()) {
18262acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner      Invalid = true;
18271eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
18285add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson      const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
18295add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson      // FIXME: This won't give the correct result for
1830c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson      // int a[10][n];
18310032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson      SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
1832a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar
183395b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner      if (NewVD->isFileVarDecl())
1834278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner        Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
1835a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar          << SizeRange;
1836278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner      else if (NewVD->getStorageClass() == VarDecl::Static)
183795b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner        Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
1838278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner          << SizeRange;
1839278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner      else
1840278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner        Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
1841a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar            << SizeRange;
1842584acf2ded2c18a18d6da0e1c01f5859a384d99fRafael Espindola    } else {
1843584acf2ded2c18a18d6da0e1c01f5859a384d99fRafael Espindola      Invalid = true;
1844584acf2ded2c18a18d6da0e1c01f5859a384d99fRafael Espindola
1845dc0f137295bc7ec5b231ff1842388f149f43c0c8Rafael Espindola      if (NewVD->isFileVarDecl())
1846278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner        Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
1847a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar      else
1848278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner        Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
18491eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    }
1850278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner  }
1851278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner
1852b266a1fce09ab4ee7033268199509aacfbef056aRafael Espindola  if (!PrevDecl && NewVD->isExternC(Context)) {
1853a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar    // Since we did not find anything by this name and we're declaring
18544da244c23d6093adbbbc41654aa5c5111b38f431Ken Dyck    // an extern "C" variable, look for a non-visible extern "C"
18554da244c23d6093adbbbc41654aa5c5111b38f431Ken Dyck    // declaration with the same name.
1856f7e903d7a30891083420c07ebeed281726a101d6Daniel Dunbar    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
1857f7e903d7a30891083420c07ebeed281726a101d6Daniel Dunbar      = LocallyScopedExternalDecls.find(NewVD->getDeclName());
1858f7e903d7a30891083420c07ebeed281726a101d6Daniel Dunbar    if (Pos != LocallyScopedExternalDecls.end())
1859a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar      PrevDecl = Pos->second;
1860a5c04344fa70d6eec34344760c1fe511e16f2d76Jay Foad  }
18615add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson
1862c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  if (!Invalid && T->isVoidType() && !NewVD->hasExternalStorage()) {
1863c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson    Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
18645add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson      << T;
18651eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    Invalid = true;
1866c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  }
186708e252425ca2cbdc44ba65d9a657ed5398014e36Owen Anderson
18681eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  if (PrevDecl) {
18691eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    Redeclaration = true;
187095b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner    if (MergeVarDecl(NewVD, PrevDecl))
1871bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor      Invalid = true;
18728e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  }
18731d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar
18741eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  return NewVD->isInvalidDecl() || Invalid;
18750c67829763b98bc670062b553897a851fab17401Anders Carlsson}
1876c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson
187745e8cbdce25c2e16c7aac2036a591f6190097ae6Chris LattnerNamedDecl*
187845c4ea75b235de94f44bf96843624e6a559e4c00Douglas GregorSema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
187945c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                              QualType R, NamedDecl* PrevDecl,
188045c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                              bool IsFunctionDefinition,
188145c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                              bool& InvalidDecl, bool &Redeclaration) {
188245c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  assert(R.getTypePtr()->isFunctionType());
188345c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
188445c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  DeclarationName Name = GetNameForDeclarator(D);
188545c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  FunctionDecl::StorageClass SC = FunctionDecl::None;
188645c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  switch (D.getDeclSpec().getStorageClassSpec()) {
188745c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  default: assert(0 && "Unknown storage class!");
188833e982bf782d851bfe5767acb1336fcf3419ac6bFariborz Jahanian  case DeclSpec::SCS_auto:
18894c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian  case DeclSpec::SCS_register:
18902bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  case DeclSpec::SCS_mutable:
18912bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    Diag(D.getDeclSpec().getStorageClassSpecLoc(),
1892cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian         diag::err_typecheck_sclass_func);
18932bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    InvalidDecl = true;
18942bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    break;
18952bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
18962bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  case DeclSpec::SCS_extern:      SC = FunctionDecl::Extern; break;
18972bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  case DeclSpec::SCS_static: {
18982bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    if (CurContext->getLookupContext()->isFunctionOrMethod()) {
18992bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian      // C99 6.7.1p5:
19002bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian      //   The declaration of an identifier for a function that has
1901ec951e0c2fc0db00c36bc60c900331dde32c1b43Fariborz Jahanian      //   block scope shall have no explicit storage-class specifier
19024c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian      //   other than extern
19034c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian      // See also (C++ [dcl.stc]p4).
19042acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
19054c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian           diag::err_static_block_func);
19066f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian      SC = FunctionDecl::None;
190725dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian    } else
190825dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian      SC = FunctionDecl::Static;
190925dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian    break;
19106f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian  }
19116f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian  case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
19122acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  }
19136f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian
19146f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian  bool isInline = D.getDeclSpec().isInlineSpecified();
19156f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
191625dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian  bool isExplicit = D.getDeclSpec().isExplicitSpecified();
191725dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian
191825dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian  // Check that the return type is not an abstract class type.
19192acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  // For record types, this is done by the AbstractClassUsageDiagnoser once
192025dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian  // the class has been completely parsed.
19216f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian  if (!DC->isRecord() &&
19226f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian      RequireNonAbstractType(D.getIdentifierLoc(),
1923a5c04344fa70d6eec34344760c1fe511e16f2d76Jay Foad                             R->getAsFunctionType()->getResultType(),
19244c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian                             diag::err_abstract_type_in_decl,
19252bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian                             AbstractReturnType))
192645c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    InvalidDecl = true;
192745c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
192845c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  // Do not allow returning a objc interface by-value.
192945c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  if (R->getAsFunctionType()->getResultType()->isObjCInterfaceType()) {
193045c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    Diag(D.getIdentifierLoc(),
193145c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor         diag::err_object_cannot_be_passed_returned_by_value) << 0
193245c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor      << R->getAsFunctionType()->getResultType();
193345c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    InvalidDecl = true;
193445c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  }
193545c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
193645c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  bool isVirtualOkay = false;
193745c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  FunctionDecl *NewFD;
193845c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  if (D.getKind() == Declarator::DK_Constructor) {
193945c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    // This is a C++ constructor declaration.
194045c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    assert(DC->isRecord() &&
194145c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor           "Constructors can only be declared in a member context");
194245c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
194345c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
194445c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
194545c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    // Create the new declaration
194645c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    NewFD = CXXConstructorDecl::Create(Context,
194745c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                       cast<CXXRecordDecl>(DC),
194845c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                       D.getIdentifierLoc(), Name, R,
194945c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                       isExplicit, isInline,
195045c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                       /*isImplicitlyDeclared=*/false);
195145c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
195245c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    if (InvalidDecl)
195345c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor      NewFD->setInvalidDecl();
195445c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  } else if (D.getKind() == Declarator::DK_Destructor) {
195545c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    // This is a C++ destructor declaration.
195645c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    if (DC->isRecord()) {
195745c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor      InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
195845c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
195945c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor      NewFD = CXXDestructorDecl::Create(Context,
19602bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian                                        cast<CXXRecordDecl>(DC),
19611d236ab930816f5da27bade92904914c44b73b4cBenjamin Kramer                                        D.getIdentifierLoc(), Name, R,
19622bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian                                        isInline,
19632bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian                                        /*isImplicitlyDeclared=*/false);
19644c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian
19652bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian      if (InvalidDecl)
19662bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian        NewFD->setInvalidDecl();
19672bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
19682bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian      isVirtualOkay = true;
19692bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    } else {
19702bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian      Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1971cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian
1972cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian      // Create a FunctionDecl to satisfy the function definition parsing
19732bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian      // code path.
19742bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian      NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
19752bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian                                   Name, R, SC, isInline,
19762bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian                                   /*hasPrototype=*/true,
1977803d307a5385059b1a84dfe9706ab158c80a20dcRafael Espindola                                   // FIXME: Move to DeclGroup...
1978cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian                                   D.getDeclSpec().getSourceRange().getBegin());
1979cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian      InvalidDecl = true;
1980a5c04344fa70d6eec34344760c1fe511e16f2d76Jay Foad      NewFD->setInvalidDecl();
19812bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    }
19822bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  } else if (D.getKind() == Declarator::DK_Conversion) {
19832acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner    if (!DC->isRecord()) {
19842bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian      Diag(D.getIdentifierLoc(),
19852bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian           diag::err_conv_function_not_member);
19862bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian      return 0;
198745c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    } else {
19882bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian      InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
19892bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
19902bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian      NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
19912bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian                                        D.getIdentifierLoc(), Name, R,
1992ec951e0c2fc0db00c36bc60c900331dde32c1b43Fariborz Jahanian                                        isInline, isExplicit);
1993ec951e0c2fc0db00c36bc60c900331dde32c1b43Fariborz Jahanian
1994bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor      if (InvalidDecl)
1995bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor        NewFD->setInvalidDecl();
19962bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
19972bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian      isVirtualOkay = true;
19982bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    }
19992bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  } else if (DC->isRecord()) {
200033e982bf782d851bfe5767acb1336fcf3419ac6bFariborz Jahanian    // This is a C++ method declaration.
200133e982bf782d851bfe5767acb1336fcf3419ac6bFariborz Jahanian    NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
20020815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                  D.getIdentifierLoc(), Name, R,
20030815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                  (SC == FunctionDecl::Static), isInline);
20040815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor
20050815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    isVirtualOkay = (SC != FunctionDecl::Static);
20060815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor  } else {
20070815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    // Determine whether the function was written with a
20080815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    // prototype. This true when:
20090815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    //   - we're in C++ (where every function has a prototype),
20100815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    //   - there is a prototype in the declarator, or
20110815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    //   - the type R of the function is some kind of typedef or other reference
20120815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    //     to a type name (which eventually refers to a function type).
20130815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    bool HasPrototype =
20140815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor       getLangOptions().CPlusPlus ||
20150815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor       (D.getNumTypeObjects() && D.getTypeObject(0).Fun.hasPrototype) ||
20160815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
20170815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor
20180815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    NewFD = FunctionDecl::Create(Context, DC,
20190815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                 D.getIdentifierLoc(),
20200815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                 Name, R, SC, isInline, HasPrototype,
20210815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                 // FIXME: Move to DeclGroup...
20220815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                 D.getDeclSpec().getSourceRange().getBegin());
20230815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor  }
20240815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor
20250815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor  // Set the lexical context. If the declarator has a C++
20260815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor  // scope specifier, the lexical context will be different
20270815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor  // from the semantic context.
20280815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor  NewFD->setLexicalDeclContext(CurContext);
20290815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor
20300815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor  // C++ [dcl.fct.spec]p5:
20310815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor  //   The virtual specifier shall only be used in declarations of
20320815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor  //   nonstatic class member functions that appear within a
20330815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor  //   member-specification of a class declaration; see 10.3.
20340815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor  //
20350815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor  // FIXME: Checking the 'virtual' specifier is not sufficient. A
20360815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor  // function is also virtual if it overrides an already virtual
20376143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  // function. This is important to do here because it's part of the
20381e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  // declaration.
20396143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  if (isVirtual && !InvalidDecl) {
204064f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman    if (!isVirtualOkay) {
204164f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman       Diag(D.getDeclSpec().getVirtualSpecLoc(),
20423b8037a8c6f462e51f75c82b3d7fe1b8dbcf06c0Ken Dyck           diag::err_virtual_non_function);
20431e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar    } else if (!CurContext->isRecord()) {
20443b8037a8c6f462e51f75c82b3d7fe1b8dbcf06c0Ken Dyck      // 'virtual' was specified outside of the class.
20451e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar      Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_out_of_class)
20461eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        << CodeModificationHint::CreateRemoval(
2047dbb1ecc32ca122b07b7c98fd0a8f6f53985adaccChris Lattner                             SourceRange(D.getDeclSpec().getVirtualSpecLoc()));
20481e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar    } else {
20491eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      // Okay: Add virtual to the method.
20502f4eaef37476ae6891ede8ba215d0f6fd093629bBenjamin Kramer      cast<CXXMethodDecl>(NewFD)->setVirtual();
20511e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar      CXXRecordDecl *CurClass = cast<CXXRecordDecl>(DC);
20521eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      CurClass->setAggregate(false);
20531e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar      CurClass->setPOD(false);
20541e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar      CurClass->setPolymorphic(true);
20551e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar      CurClass->setHasTrivialConstructor(false);
205664f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman    }
205764f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  }
205864f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman
205964f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  if (SC == FunctionDecl::Static && isa<CXXMethodDecl>(NewFD) &&
206064f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman      !CurContext->isRecord()) {
206164f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman    // C++ [class.static]p1:
206264f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman    //   A data or function member of a class may be declared static
206364f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman    //   in a class definition, in which case it is a static member of
206464f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman    //   the class.
206564f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman
206664f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman    // Complain about the 'static' specifier if it's on an out-of-line
206764f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman    // member function definition.
206864f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman    Diag(D.getDeclSpec().getStorageClassSpecLoc(),
206964f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman         diag::err_static_out_of_line)
207064f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman      << CodeModificationHint::CreateRemoval(
207164f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman                      SourceRange(D.getDeclSpec().getStorageClassSpecLoc()));
207264f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  }
207364f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman
207464f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  // Handle GNU asm-label extension (encoded as an attribute).
207564f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  if (Expr *E = (Expr*) D.getAsmLabel()) {
207664f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman    // The parser guarantees this is a string.
207764f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman    StringLiteral *SE = cast<StringLiteral>(E);
207864f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman    NewFD->addAttr(::new (Context) AsmLabelAttr(std::string(SE->getStrData(),
207964f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman                                                        SE->getByteLength())));
208064f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  }
208164f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman
208264f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  // Copy the parameter declarations from the declarator D to
208364f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  // the function declaration NewFD, if they are available.
208464f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  if (D.getNumTypeObjects() > 0) {
208564f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman    DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
208664f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman
208764f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman    // Create Decl objects for each parameter, adding them to the
20886143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar    // FunctionDecl.
20896143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar    llvm::SmallVector<ParmVarDecl*, 16> Params;
20906143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar
20916143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar    // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
20926143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar    // function that takes no arguments, not a function that takes a
20937eb79c1010c8d30b852768bec96e81cd3e6def2eEli Friedman    // single void argument.
2094a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall    // We let through "const void" here because Sema::GetTypeForDeclarator
209564f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman    // already checks for that case.
209664f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman    if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
209764f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman        FTI.ArgInfo[0].Param &&
209864f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman        FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()) {
20997eb79c1010c8d30b852768bec96e81cd3e6def2eEli Friedman      // empty arg list, don't push any params.
210064f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman      ParmVarDecl *Param = FTI.ArgInfo[0].Param.getAs<ParmVarDecl>();
210164f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman
210264f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman      // In C++, the empty parameter-type-list must be spelled "void"; a
210364f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman      // typedef of void is not permitted.
210464f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman      if (getLangOptions().CPlusPlus &&
210564f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman          Param->getType().getUnqualifiedType() != Context.VoidTy) {
210664f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman        Diag(Param->getLocation(), diag::err_param_typedef_of_void);
210764f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman      }
210864f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman    } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
210964f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman      for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
211064f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman        Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
211164f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman    }
21126143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar
21136143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar    NewFD->setParams(Context, &Params[0], Params.size());
2114eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner  } else if (R->getAsTypedefType()) {
2115eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner    // When we're declaring a function with a typedef, as in the
2116eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner    // following example, we'll need to synthesize (unnamed)
2117eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner    // parameters for use in the declaration.
2118eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner    //
2119eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner    // @code
2120a210f350fa78c263caa26e0f999cce85bb235309Eli Friedman    // typedef void fn(int);
2121a210f350fa78c263caa26e0f999cce85bb235309Eli Friedman    // fn f;
2122eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner    // @endcode
2123eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner    const FunctionProtoType *FT = R->getAsFunctionProtoType();
2124eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner    if (!FT) {
2125a7ad98ff0919d6a24ea7c46634ea29bea551c1a0Chris Lattner      // This is a typedef of a function with no prototype, so we
2126a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall      // don't need to do anything.
212745e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner    } else if ((FT->getNumArgs() == 0) ||
21285fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbar               (FT->getNumArgs() == 1 && !FT->isVariadic() &&
2129a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                FT->getArgType(0)->isVoidType())) {
2130a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall      // This is a zero-argument function. We don't need to do anything.
21316143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar    } else {
21320032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson      // Synthesize a parameter for each argument type.
21330032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson      llvm::SmallVector<ParmVarDecl*, 16> Params;
21341eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      for (FunctionProtoType::arg_type_iterator ArgType = FT->arg_type_begin();
213545e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner           ArgType != FT->arg_type_end(); ++ArgType) {
21361257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola        ParmVarDecl *Param = ParmVarDecl::Create(Context, DC,
21371257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola                                                 SourceLocation(), 0,
21381257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola                                                 *ArgType, VarDecl::None,
21391257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola                                                 0);
2140a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall        Param->setImplicit();
21411257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola        Params.push_back(Param);
21421257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola      }
214345e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
214445e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner      NewFD->setParams(Context, &Params[0], Params.size());
21456143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar    }
21466143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  }
21476143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar
21486143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  // If name lookup finds a previous declaration that is not in the
21496143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  // same scope as the new declaration, this may still be an
21506143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  // acceptable redeclaration.
21516143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  if (PrevDecl && !isDeclInScope(PrevDecl, DC, S) &&
21526143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar      !(NewFD->hasLinkage() &&
21535f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner        isOutOfScopePreviousDeclaration(PrevDecl, DC, Context)))
2154a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall    PrevDecl = 0;
2155a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall
21568e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  // Perform semantic checking on the function declaration.
21578e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  bool OverloadableAttrRequired = false; // FIXME: HACK!
21588e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  if (CheckFunctionDeclaration(NewFD, PrevDecl, Redeclaration,
21598e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar                               /*FIXME:*/OverloadableAttrRequired))
216095b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner    InvalidDecl = true;
21618e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar
21628e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  if (D.getCXXScopeSpec().isSet() && !InvalidDecl) {
21638e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar    // An out-of-line member function declaration must also be a
2164a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall    // definition (C++ [dcl.meaning]p1).
21651eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    if (!IsFunctionDefinition) {
2166a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall      Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
21679de4342ef79a18c706e46bc23f8f579f5add2375Benjamin Kramer        << D.getCXXScopeSpec().getRange();
216845e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner      InvalidDecl = true;
2169a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall    } else if (!Redeclaration) {
2170a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall      // The user tried to provide an out-of-line definition for a
2171a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall      // function that is a member of a class or namespace, but there
2172a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall      // was no such member function declared (C++ [class.mfct]p2,
2173a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall      // C++ [namespace.memdef]p2). For example:
2174a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall      //
217545e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner      // class X {
217645e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner      //   void f() const;
2177a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall      // };
2178a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall      //
2179a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall      // void X::f() { } // ill-formed
218045e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner      //
21816143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar      // Complain about this problem, and attempt to suggest close
21826143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar      // matches (e.g., those that differ only in cv-qualifiers and
21839de4342ef79a18c706e46bc23f8f579f5add2375Benjamin Kramer      // whether the parameter types are references).
21846143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar      Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
21859de4342ef79a18c706e46bc23f8f579f5add2375Benjamin Kramer        << cast<NamedDecl>(DC) << D.getCXXScopeSpec().getRange();
2186a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall      InvalidDecl = true;
2187a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall
21885f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner      LookupResult Prev = LookupQualifiedName(DC, Name, LookupOrdinaryName,
2189a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                              true);
21906143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar      assert(!Prev.isAmbiguous() &&
219141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar             "Cannot have an ambiguity in previous-declaration lookup");
2192af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
2193af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar           Func != FuncEnd; ++Func) {
21941eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        if (isa<FunctionDecl>(*Func) &&
2195af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar            isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD))
21961eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump          Diag((*Func)->getLocation(), diag::note_member_def_close_match);
219717945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis      }
2198af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar
21991eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      PrevDecl = 0;
2200af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    }
2201af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  }
2202af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar
2203af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  // Handle attributes. We need to have merged decls when handling attributes
2204af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  // (for example to check for conflicts, etc).
2205af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  // FIXME: This needs to happen before we merge declarations. Then,
2206af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  // let attribute merging cope with attribute conflicts.
2207af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  ProcessDeclAttributes(NewFD, D);
2208af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  AddKnownFunctionAttributes(NewFD);
220917945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis
2210fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian  if (OverloadableAttrRequired && !NewFD->getAttr<OverloadableAttr>()) {
2211fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian    // If a function name is overloadable in C, then every function
2212af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    // with that name must be marked "overloadable".
221317945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis    Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
2214fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian      << Redeclaration << NewFD;
2215fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian    if (PrevDecl)
2216af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      Diag(PrevDecl->getLocation(),
2217af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar           diag::note_attribute_overloadable_prev_overload);
2218af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    NewFD->addAttr(::new (Context) OverloadableAttr());
2219af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  }
2220e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall
2221db8264e4c5ffd7af6fbad4ca4306bd382bb02691Jordy Rose  // If this is a locally-scoped extern C function, update the
2222db8264e4c5ffd7af6fbad4ca4306bd382bb02691Jordy Rose  // map of such names.
2223e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  if (CurContext->isFunctionOrMethod() && NewFD->isExternC(Context)
2224e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall      && !InvalidDecl)
2225e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    RegisterLocallyScopedExternCDecl(NewFD, PrevDecl, S);
2226e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall
2227e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  return NewFD;
2228e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall}
2229e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall
2230109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian/// \brief Perform semantic checking of a new function declaration.
2231109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian///
2232109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian/// Performs semantic analysis of the new function declaration
2233e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall/// NewFD. This routine performs all semantic checking that does not
2234e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall/// require the actual declarator involved in the declaration, and is
2235e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall/// used both for the declaration of functions as they are parsed
2236e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall/// (called via ActOnDeclarator) and for the declaration of functions
2237e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall/// that have been instantiated via C++ template instantiation (called
2238e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall/// via InstantiateDecl).
223975cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis///
224075cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis/// \returns true if there was an error, false otherwise.
224175cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidisbool Sema::CheckFunctionDeclaration(FunctionDecl *NewFD, NamedDecl *&PrevDecl,
224275cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                                    bool &Redeclaration,
2243e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall                                    bool &OverloadableAttrRequired) {
2244e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  bool InvalidDecl = false;
2245f85e193739c953358c865005855253af4f68a497John McCall
2246e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  // Semantic checking for this function declaration (in isolation).
2247e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  if (getLangOptions().CPlusPlus) {
2248e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    // C++-specific checks.
2249e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
2250827bbcc8a9115782693b21030a45378abe5c1862David Chisnall      InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
2251109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian    else if (isa<CXXDestructorDecl>(NewFD)) {
2252109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian      CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
2253e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall      Record->setUserDeclaredDestructor(true);
2254e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall      // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
2255109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian      // user-defined destructor.
2256109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian      Record->setPOD(false);
2257109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian
225811d77169555480ee0a04c6e5bc390d8fde41175dArgyrios Kyrtzidis      // C++ [class.dtor]p3: A destructor is trivial if it is an implicitly-
225911d77169555480ee0a04c6e5bc390d8fde41175dArgyrios Kyrtzidis      // declared destructor.
2260109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian      Record->setHasTrivialDestructor(false);
226175cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis    } else if (CXXConversionDecl *Conversion
226275cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis               = dyn_cast<CXXConversionDecl>(NewFD))
226375cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis      ActOnConversionDeclarator(Conversion);
226475cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis
226575cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis    // Extra checking for C++ overloaded operators (C++ [over.oper]).
2266109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian    if (NewFD->isOverloadedOperator() &&
2267109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian        CheckOverloadedOperatorDeclaration(NewFD))
2268109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian      InvalidDecl = true;
2269f85e193739c953358c865005855253af4f68a497John McCall  }
2270109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian
2271109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian  // Check for a previous declaration of this name.
227291e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson  if (!PrevDecl && NewFD->isExternC(Context)) {
2273984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson    // Since we did not find anything by this name and we're declaring
227417945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis    // an extern "C" function, look for a non-visible extern "C"
2275984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson    // declaration with the same name.
2276984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
2277984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson      = LocallyScopedExternalDecls.find(NewFD->getDeclName());
2278984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson    if (Pos != LocallyScopedExternalDecls.end())
227991e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson      PrevDecl = Pos->second;
228091e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson  }
2281f976be8a63f9e0d3bd50e33dadef02c3c9921747Eli Friedman
2282f976be8a63f9e0d3bd50e33dadef02c3c9921747Eli Friedman  // Merge or overload the declaration with an existing declaration of
228391e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson  // the same name, if appropriate.
228491e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson  if (PrevDecl) {
228591e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    // Determine whether NewFD is an overload of PrevDecl or
228691e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    // a declaration that requires merging. If it's an overload,
228717945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis    // there's no more work to do here; we'll just add the new
228891e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    // function to the scope.
228991e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    OverloadedFunctionDecl::function_iterator MatchedDecl;
229091e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson
229191e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    if (!getLangOptions().CPlusPlus &&
229241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar        AllowOverloadingOfFunction(PrevDecl, Context)) {
229341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar      OverloadableAttrRequired = true;
229441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
229541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar      // Functions marked "overloadable" must have a prototype (that
229641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar      // we can't get through declaration merging).
229741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar      if (!NewFD->getType()->getAsFunctionProtoType()) {
229841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar        Diag(NewFD->getLocation(), diag::err_attribute_overloadable_no_prototype)
229941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar          << NewFD;
230016e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor        InvalidDecl = true;
230116e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor        Redeclaration = true;
230216e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor
23031eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        // Turn this into a variadic function with no parameters.
230441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar        QualType R = Context.getFunctionType(
2305293361afd4199c92aabff9267fddea890943c586Anders Carlsson                       NewFD->getType()->getAsFunctionType()->getResultType(),
23062b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson                       0, 0, true, 0);
230741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar        NewFD->setType(R);
230816e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor      }
23098387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet    }
23108387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet
231116e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor    if (PrevDecl &&
23121eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        (!AllowOverloadingOfFunction(PrevDecl, Context) ||
2313555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson         !IsOverload(NewFD, PrevDecl, MatchedDecl))) {
2314555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson      Redeclaration = true;
2315555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson      Decl *OldDecl = PrevDecl;
231641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
2317555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson      // If PrevDecl was an overloaded function, extract the
231841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar      // FunctionDecl that matched.
231941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar      if (isa<OverloadedFunctionDecl>(PrevDecl))
232026fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall        OldDecl = *MatchedDecl;
232126fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall
232226fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall      // NewFD and OldDecl represent declarations that need to be
232326fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall      // merged.
232426fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall      if (MergeFunctionDecl(NewFD, OldDecl))
232595d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson        InvalidDecl = true;
232641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
2327984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson      if (!InvalidDecl)
232841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar        NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
23299cfbe48a7a20a217fdb2920b29b67ae7941cb116Douglas Gregor    }
23309d0c6613ec040ad8d952556be909232a7f25dedeJohn McCall  }
23319cfbe48a7a20a217fdb2920b29b67ae7941cb116Douglas Gregor
2332dd9967a6374c9a44be4af02aaeee340ffb82848fDouglas Gregor  if (getLangOptions().CPlusPlus && !CurContext->isRecord()) {
2333127102b5196ffe04bdb70fd553fe62c265ab10a9Douglas Gregor    // In C++, check default arguments now that we have merged decls. Unless
2334127102b5196ffe04bdb70fd553fe62c265ab10a9Douglas Gregor    // the lexical context is the class, because in this case this is done
23353e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith    // during delayed parsing anyway.
2336018837b081bd1a725bae1c020eb1649975b04d67Anders Carlsson    CheckCXXDefaultArguments(NewFD);
23376a576ab708d3aa7d40e5d867ab1de5d3cb507553Douglas Gregor  }
233815de72cf580840c61e5704c2f8a2b56f9d0638e1Douglas Gregor
23399cfbe48a7a20a217fdb2920b29b67ae7941cb116Douglas Gregor  return InvalidDecl || NewFD->isInvalidDecl();
234095d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson}
23411fe598c026dc03fddbd65efb8119eb1afd9b1520Anders Carlsson
23428387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichetbool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
23438387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet  // FIXME: Need strict checking.  In C89, we need to check for
23441fe598c026dc03fddbd65efb8119eb1afd9b1520Anders Carlsson  // any assignment, increment, decrement, function-calls, or
23451fe598c026dc03fddbd65efb8119eb1afd9b1520Anders Carlsson  // commas outside of a sizeof.  In C99, it's the same list,
234695d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson  // except that the aforementioned are allowed in unevaluated
234795d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson  // expressions.  Everything else falls under the
234827ae53665f8b00fe4ba21da0fa79a4ce6e0b6cd5Anders Carlsson  // "may accept other forms of constant expressions" exception.
23498387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet  // (We never end up here for C++, so the constant expression
23508387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet  // rules there don't matter.)
235127ae53665f8b00fe4ba21da0fa79a4ce6e0b6cd5Anders Carlsson  if (Init->isConstantInitializer(Context))
235227ae53665f8b00fe4ba21da0fa79a4ce6e0b6cd5Anders Carlsson    return false;
235336674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson  Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
235436674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson    << Init->getSourceRange();
235536674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson  return true;
235636674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson}
235736674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson
235895d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlssonvoid Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init) {
23591eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
236038e24c782c17b6058bf61d635747bbde19fb1bc7Fariborz Jahanian}
236141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
236241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar/// AddInitializerToDecl - Adds the initializer Init to the
2363b31cb7f1752ea011fd06ac9574ce24667d11cbdbFariborz Jahanian/// declaration dcl. If DirectInit is true, this is C++ direct
236441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar/// initialization rather than copy initialization.
2365000835d0b04345c0014c603fe6339b3bc154050eFariborz Jahanianvoid Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init, bool DirectInit) {
2366baf101d1f96b4e41c9f2797875329840514f54f1Chris Lattner  Decl *RealDecl = dcl.getAs<Decl>();
2367baf101d1f96b4e41c9f2797875329840514f54f1Chris Lattner  // If there is no declaration, there was an error parsing it.  Just ignore
2368baf101d1f96b4e41c9f2797875329840514f54f1Chris Lattner  // the initializer.
2369baf101d1f96b4e41c9f2797875329840514f54f1Chris Lattner  if (RealDecl == 0)
2370baf101d1f96b4e41c9f2797875329840514f54f1Chris Lattner    return;
2371baf101d1f96b4e41c9f2797875329840514f54f1Chris Lattner
2372285d0dba947b7c9960eaa88e8c4fced0398d4319Chris Lattner  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
237341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    // With declarators parsed the way they are, the parser cannot
2374e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne    // distinguish between a normal initializer and a pure-specifier.
237541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    // Thus this grotesque test.
237641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    IntegerLiteral *IL;
237741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    Expr *Init = static_cast<Expr *>(init.get());
2378af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
2379af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar        Context.getCanonicalType(IL->getType()) == Context.IntTy) {
2380e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne      if (Method->isVirtual()) {
238141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar        Method->setPure();
238241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
2383af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar        // A class is abstract if at least one function is pure virtual.
2384af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar        cast<CXXRecordDecl>(CurContext)->setAbstract(true);
2385000835d0b04345c0014c603fe6339b3bc154050eFariborz Jahanian      } else if (!Method->isInvalidDecl()) {
2386000835d0b04345c0014c603fe6339b3bc154050eFariborz Jahanian        Diag(Method->getLocation(), diag::err_non_virtual_pure)
2387af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar          << Method->getDeclName() << Init->getSourceRange();
2388109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian        Method->setInvalidDecl();
2389e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne      }
239041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    } else {
23911eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      Diag(Method->getLocation(), diag::err_member_function_initialization)
239241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar        << Method->getDeclName() << Init->getSourceRange();
239341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar      Method->setInvalidDecl();
239441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    }
23956fb0aee4f9dc261bbec72e1283ad8dc0557a6d96Argyrios Kyrtzidis    return;
239641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  }
239741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
239841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
23991eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  if (!VDecl) {
2400305c658ebce84bb9833fc0e7675554656453b8e8Fariborz Jahanian    if (getLangOptions().CPlusPlus &&
240141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar        RealDecl->getLexicalDeclContext()->isRecord() &&
240241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar        isa<NamedDecl>(RealDecl))
240391e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson      Diag(RealDecl->getLocation(), diag::err_member_initialization)
240491e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson        << cast<NamedDecl>(RealDecl)->getDeclName();
240541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    else
240641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar      Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
240741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    RealDecl->setInvalidDecl();
240841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    return;
24095f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  }
24101eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
241141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  if (!VDecl->getType()->isArrayType() &&
241241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar      RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
241341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar                          diag::err_typecheck_decl_incomplete_type)) {
24149f5bff086cad25c15b4deb8a7763786097aadccdChris Lattner    RealDecl->setInvalidDecl();
24159f5bff086cad25c15b4deb8a7763786097aadccdChris Lattner    return;
241641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  }
24178d04258483be6583f0865464234d014807a3e1ccBenjamin Kramer
241841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  const VarDecl *Def = 0;
241941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  if (VDecl->getDefinition(Def)) {
24201eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    Diag(VDecl->getLocation(), diag::err_redefinition)
24211eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      << VDecl->getDeclName();
2422f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    Diag(Def->getLocation(), diag::note_previous_definition);
2423f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    VDecl->setInvalidDecl();
2424f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    return;
242541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  }
242641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
242741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  // Take ownership of the expression, now that we're sure we have somewhere
2428744016dde06fcffd50931e94a98c850f8b12cd87John McCall  // to put it.
2429744016dde06fcffd50931e94a98c850f8b12cd87John McCall  Expr *Init = static_cast<Expr *>(init.release());
2430744016dde06fcffd50931e94a98c850f8b12cd87John McCall  assert(Init && "missing initializer");
2431744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2432744016dde06fcffd50931e94a98c850f8b12cd87John McCall  // Get the decls type and save a reference for later, since
24332acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  // CheckInitializerTypes may change it.
2434744016dde06fcffd50931e94a98c850f8b12cd87John McCall  QualType DclT = VDecl->getType(), SavT = DclT;
2435744016dde06fcffd50931e94a98c850f8b12cd87John McCall  if (VDecl->isBlockVarDecl()) {
2436744016dde06fcffd50931e94a98c850f8b12cd87John McCall    if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
2437744016dde06fcffd50931e94a98c850f8b12cd87John McCall      Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
2438744016dde06fcffd50931e94a98c850f8b12cd87John McCall      VDecl->setInvalidDecl();
2439744016dde06fcffd50931e94a98c850f8b12cd87John McCall    } else if (!VDecl->isInvalidDecl()) {
2440744016dde06fcffd50931e94a98c850f8b12cd87John McCall      if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
2441744016dde06fcffd50931e94a98c850f8b12cd87John McCall                                VDecl->getDeclName(), DirectInit))
2442744016dde06fcffd50931e94a98c850f8b12cd87John McCall        VDecl->setInvalidDecl();
2443744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2444744016dde06fcffd50931e94a98c850f8b12cd87John McCall      // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2445744016dde06fcffd50931e94a98c850f8b12cd87John McCall      // Don't check invalid declarations to avoid emitting useless diagnostics.
2446744016dde06fcffd50931e94a98c850f8b12cd87John McCall      if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
2447744016dde06fcffd50931e94a98c850f8b12cd87John McCall        if (VDecl->getStorageClass() == VarDecl::Static) // C99 6.7.8p4.
2448744016dde06fcffd50931e94a98c850f8b12cd87John McCall          CheckForConstantInitializer(Init, DclT);
2449744016dde06fcffd50931e94a98c850f8b12cd87John McCall      }
24506f141659cab11109d9931d92d0988f8850778de3Jay Foad    }
2451744016dde06fcffd50931e94a98c850f8b12cd87John McCall  } else if (VDecl->isStaticDataMember() &&
2452744016dde06fcffd50931e94a98c850f8b12cd87John McCall             VDecl->getLexicalDeclContext()->isRecord()) {
2453744016dde06fcffd50931e94a98c850f8b12cd87John McCall    // This is an in-class initialization for a static data member, e.g.,
2454744016dde06fcffd50931e94a98c850f8b12cd87John McCall    //
2455744016dde06fcffd50931e94a98c850f8b12cd87John McCall    // struct S {
2456744016dde06fcffd50931e94a98c850f8b12cd87John McCall    //   static const int value = 17;
2457744016dde06fcffd50931e94a98c850f8b12cd87John McCall    // };
2458744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2459744016dde06fcffd50931e94a98c850f8b12cd87John McCall    // Attach the initializer
2460744016dde06fcffd50931e94a98c850f8b12cd87John McCall    VDecl->setInit(Init);
2461744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2462744016dde06fcffd50931e94a98c850f8b12cd87John McCall    // C++ [class.mem]p4:
2463744016dde06fcffd50931e94a98c850f8b12cd87John McCall    //   A member-declarator can contain a constant-initializer only
24645f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    //   if it declares a static member (9.4) of const integral or
2465744016dde06fcffd50931e94a98c850f8b12cd87John McCall    //   const enumeration type, see 9.4.2.
2466744016dde06fcffd50931e94a98c850f8b12cd87John McCall    QualType T = VDecl->getType();
2467744016dde06fcffd50931e94a98c850f8b12cd87John McCall    if (!T->isDependentType() &&
2468744016dde06fcffd50931e94a98c850f8b12cd87John McCall        (!Context.getCanonicalType(T).isConstQualified() ||
2469744016dde06fcffd50931e94a98c850f8b12cd87John McCall         !T->isIntegralType())) {
2470744016dde06fcffd50931e94a98c850f8b12cd87John McCall      Diag(VDecl->getLocation(), diag::err_member_initialization)
2471744016dde06fcffd50931e94a98c850f8b12cd87John McCall        << VDecl->getDeclName() << Init->getSourceRange();
2472744016dde06fcffd50931e94a98c850f8b12cd87John McCall      VDecl->setInvalidDecl();
2473744016dde06fcffd50931e94a98c850f8b12cd87John McCall    } else {
2474744016dde06fcffd50931e94a98c850f8b12cd87John McCall      // C++ [class.static.data]p4:
2475744016dde06fcffd50931e94a98c850f8b12cd87John McCall      //   If a static data member is of const integral or const
2476744016dde06fcffd50931e94a98c850f8b12cd87John McCall      //   enumeration type, its declaration in the class definition
2477744016dde06fcffd50931e94a98c850f8b12cd87John McCall      //   can specify a constant-initializer which shall be an
2478744016dde06fcffd50931e94a98c850f8b12cd87John McCall      //   integral constant expression (5.19).
2479744016dde06fcffd50931e94a98c850f8b12cd87John McCall      if (!Init->isTypeDependent() &&
2480744016dde06fcffd50931e94a98c850f8b12cd87John McCall          !Init->getType()->isIntegralType()) {
2481744016dde06fcffd50931e94a98c850f8b12cd87John McCall        // We have a non-dependent, non-integral or enumeration type.
2482744016dde06fcffd50931e94a98c850f8b12cd87John McCall        Diag(Init->getSourceRange().getBegin(),
2483744016dde06fcffd50931e94a98c850f8b12cd87John McCall             diag::err_in_class_initializer_non_integral_type)
2484744016dde06fcffd50931e94a98c850f8b12cd87John McCall          << Init->getType() << Init->getSourceRange();
2485744016dde06fcffd50931e94a98c850f8b12cd87John McCall        VDecl->setInvalidDecl();
2486744016dde06fcffd50931e94a98c850f8b12cd87John McCall      } else if (!Init->isTypeDependent() && !Init->isValueDependent()) {
2487744016dde06fcffd50931e94a98c850f8b12cd87John McCall        // Check whether the expression is a constant expression.
2488744016dde06fcffd50931e94a98c850f8b12cd87John McCall        llvm::APSInt Value;
2489744016dde06fcffd50931e94a98c850f8b12cd87John McCall        SourceLocation Loc;
2490744016dde06fcffd50931e94a98c850f8b12cd87John McCall        if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) {
24916f141659cab11109d9931d92d0988f8850778de3Jay Foad          Diag(Loc, diag::err_in_class_initializer_non_constant)
2492744016dde06fcffd50931e94a98c850f8b12cd87John McCall            << Init->getSourceRange();
2493744016dde06fcffd50931e94a98c850f8b12cd87John McCall          VDecl->setInvalidDecl();
2494744016dde06fcffd50931e94a98c850f8b12cd87John McCall        } else if (!VDecl->getType()->isDependentType())
2495744016dde06fcffd50931e94a98c850f8b12cd87John McCall          ImpCastExprToType(Init, VDecl->getType());
2496744016dde06fcffd50931e94a98c850f8b12cd87John McCall      }
2497744016dde06fcffd50931e94a98c850f8b12cd87John McCall    }
2498673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar  } else if (VDecl->isFileVarDecl()) {
24993dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky    if (VDecl->getStorageClass() == VarDecl::Extern)
25003dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky      Diag(VDecl->getLocation(), diag::warn_extern_init);
25015ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky    if (!VDecl->isInvalidDecl())
25025ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky      if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
25035ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky                                VDecl->getDeclName(), DirectInit))
25043dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky        VDecl->setInvalidDecl();
25053dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky
25065ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky    // C++ 3.6.2p2, allow dynamic initialization of static initializers.
25075ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky    // Don't check invalid declarations to avoid emitting useless diagnostics.
25083dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky    if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
25095ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky      // C99 6.7.8p4. All file scoped initializers need to be constant.
25105ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky      CheckForConstantInitializer(Init, DclT);
25115ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky    }
25125ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky  }
25135ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky  // If the type changed, it means we had an incomplete type that was
25145ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky  // completed by the initializer. For example:
2515  //   int ary[] = { 1, 3, 5 };
2516  // "ary" transitions from a VariableArrayType to a ConstantArrayType.
2517  if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
2518    VDecl->setType(DclT);
2519    Init->setType(DclT);
2520  }
2521
2522  // Attach the initializer to the decl.
2523  VDecl->setInit(Init);
2524  return;
2525}
2526
2527void Sema::ActOnUninitializedDecl(DeclPtrTy dcl) {
2528  Decl *RealDecl = dcl.getAs<Decl>();
2529
2530  // If there is no declaration, there was an error parsing it. Just ignore it.
2531  if (RealDecl == 0)
2532    return;
2533
2534  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2535    QualType Type = Var->getType();
2536    // C++ [dcl.init.ref]p3:
2537    //   The initializer can be omitted for a reference only in a
2538    //   parameter declaration (8.3.5), in the declaration of a
2539    //   function return type, in the declaration of a class member
2540    //   within its class declaration (9.2), and where the extern
2541    //   specifier is explicitly used.
2542    if (Type->isReferenceType() && !Var->hasExternalStorage()) {
2543      Diag(Var->getLocation(), diag::err_reference_var_requires_init)
2544        << Var->getDeclName()
2545        << SourceRange(Var->getLocation(), Var->getLocation());
2546      Var->setInvalidDecl();
2547      return;
2548    }
2549
2550    // C++ [dcl.init]p9:
2551    //
2552    //   If no initializer is specified for an object, and the object
2553    //   is of (possibly cv-qualified) non-POD class type (or array
2554    //   thereof), the object shall be default-initialized; if the
2555    //   object is of const-qualified type, the underlying class type
2556    //   shall have a user-declared default constructor.
2557    if (getLangOptions().CPlusPlus) {
2558      QualType InitType = Type;
2559      if (const ArrayType *Array = Context.getAsArrayType(Type))
2560        InitType = Array->getElementType();
2561      if (!Var->hasExternalStorage() && InitType->isRecordType()) {
2562        CXXRecordDecl *RD =
2563          cast<CXXRecordDecl>(InitType->getAsRecordType()->getDecl());
2564        CXXConstructorDecl *Constructor = 0;
2565        if (!RequireCompleteType(Var->getLocation(), InitType,
2566                                    diag::err_invalid_incomplete_type_use))
2567          Constructor
2568            = PerformInitializationByConstructor(InitType, 0, 0,
2569                                                 Var->getLocation(),
2570                                               SourceRange(Var->getLocation(),
2571                                                           Var->getLocation()),
2572                                                 Var->getDeclName(),
2573                                                 IK_Default);
2574        if (!Constructor)
2575          Var->setInvalidDecl();
2576        else if (!RD->hasTrivialConstructor())
2577          InitializeVarWithConstructor(Var, Constructor, InitType, 0, 0);
2578      }
2579    }
2580
2581#if 0
2582    // FIXME: Temporarily disabled because we are not properly parsing
2583    // linkage specifications on declarations, e.g.,
2584    //
2585    //   extern "C" const CGPoint CGPointerZero;
2586    //
2587    // C++ [dcl.init]p9:
2588    //
2589    //     If no initializer is specified for an object, and the
2590    //     object is of (possibly cv-qualified) non-POD class type (or
2591    //     array thereof), the object shall be default-initialized; if
2592    //     the object is of const-qualified type, the underlying class
2593    //     type shall have a user-declared default
2594    //     constructor. Otherwise, if no initializer is specified for
2595    //     an object, the object and its subobjects, if any, have an
2596    //     indeterminate initial value; if the object or any of its
2597    //     subobjects are of const-qualified type, the program is
2598    //     ill-formed.
2599    //
2600    // This isn't technically an error in C, so we don't diagnose it.
2601    //
2602    // FIXME: Actually perform the POD/user-defined default
2603    // constructor check.
2604    if (getLangOptions().CPlusPlus &&
2605        Context.getCanonicalType(Type).isConstQualified() &&
2606        !Var->hasExternalStorage())
2607      Diag(Var->getLocation(),  diag::err_const_var_requires_init)
2608        << Var->getName()
2609        << SourceRange(Var->getLocation(), Var->getLocation());
2610#endif
2611  }
2612}
2613
2614Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, DeclPtrTy *Group,
2615                                                   unsigned NumDecls) {
2616  llvm::SmallVector<Decl*, 8> Decls;
2617
2618  for (unsigned i = 0; i != NumDecls; ++i)
2619    if (Decl *D = Group[i].getAs<Decl>())
2620      Decls.push_back(D);
2621
2622  // Perform semantic analysis that depends on having fully processed both
2623  // the declarator and initializer.
2624  for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
2625    VarDecl *IDecl = dyn_cast<VarDecl>(Decls[i]);
2626    if (!IDecl)
2627      continue;
2628    QualType T = IDecl->getType();
2629
2630    // Block scope. C99 6.7p7: If an identifier for an object is declared with
2631    // no linkage (C99 6.2.2p6), the type for the object shall be complete...
2632    if (IDecl->isBlockVarDecl() && !IDecl->hasExternalStorage()) {
2633      if (!IDecl->isInvalidDecl() &&
2634          RequireCompleteType(IDecl->getLocation(), T,
2635                              diag::err_typecheck_decl_incomplete_type))
2636        IDecl->setInvalidDecl();
2637    }
2638    // File scope. C99 6.9.2p2: A declaration of an identifier for and
2639    // object that has file scope without an initializer, and without a
2640    // storage-class specifier or with the storage-class specifier "static",
2641    // constitutes a tentative definition. Note: A tentative definition with
2642    // external linkage is valid (C99 6.2.2p5).
2643    if (IDecl->isTentativeDefinition(Context)) {
2644      QualType CheckType = T;
2645      unsigned DiagID = diag::err_typecheck_decl_incomplete_type;
2646
2647      const IncompleteArrayType *ArrayT = Context.getAsIncompleteArrayType(T);
2648      if (ArrayT) {
2649        CheckType = ArrayT->getElementType();
2650        DiagID = diag::err_illegal_decl_array_incomplete_type;
2651      }
2652
2653      if (IDecl->isInvalidDecl()) {
2654        // Do nothing with invalid declarations
2655      } else if ((ArrayT || IDecl->getStorageClass() == VarDecl::Static) &&
2656                 RequireCompleteType(IDecl->getLocation(), CheckType, DiagID)) {
2657        // C99 6.9.2p3: If the declaration of an identifier for an object is
2658        // a tentative definition and has internal linkage (C99 6.2.2p3), the
2659        // declared type shall not be an incomplete type.
2660        IDecl->setInvalidDecl();
2661      }
2662    }
2663  }
2664  return DeclGroupPtrTy::make(DeclGroupRef::Create(Context,
2665                                                   &Decls[0], Decls.size()));
2666}
2667
2668
2669/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2670/// to introduce parameters into function prototype scope.
2671Sema::DeclPtrTy
2672Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
2673  const DeclSpec &DS = D.getDeclSpec();
2674
2675  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
2676  VarDecl::StorageClass StorageClass = VarDecl::None;
2677  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2678    StorageClass = VarDecl::Register;
2679  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
2680    Diag(DS.getStorageClassSpecLoc(),
2681         diag::err_invalid_storage_class_in_func_decl);
2682    D.getMutableDeclSpec().ClearStorageClassSpecs();
2683  }
2684  if (DS.isThreadSpecified()) {
2685    Diag(DS.getThreadSpecLoc(),
2686         diag::err_invalid_storage_class_in_func_decl);
2687    D.getMutableDeclSpec().ClearStorageClassSpecs();
2688  }
2689  DiagnoseFunctionSpecifiers(D);
2690
2691  // Check that there are no default arguments inside the type of this
2692  // parameter (C++ only).
2693  if (getLangOptions().CPlusPlus)
2694    CheckExtraCXXDefaultArguments(D);
2695
2696  // In this context, we *do not* check D.getInvalidType(). If the declarator
2697  // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2698  // though it will not reflect the user specified type.
2699  QualType parmDeclType = GetTypeForDeclarator(D, S);
2700  if (parmDeclType.isNull()) {
2701    D.setInvalidType(true);
2702    parmDeclType = Context.IntTy;
2703  }
2704
2705  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2706  // Can this happen for params?  We already checked that they don't conflict
2707  // among each other.  Here they can only shadow globals, which is ok.
2708  IdentifierInfo *II = D.getIdentifier();
2709  if (II) {
2710    if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
2711      if (PrevDecl->isTemplateParameter()) {
2712        // Maybe we will complain about the shadowed template parameter.
2713        DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2714        // Just pretend that we didn't see the previous declaration.
2715        PrevDecl = 0;
2716      } else if (S->isDeclScope(DeclPtrTy::make(PrevDecl))) {
2717        Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
2718
2719        // Recover by removing the name
2720        II = 0;
2721        D.SetIdentifier(0, D.getIdentifierLoc());
2722      }
2723    }
2724  }
2725
2726  // Parameters can not be abstract class types.
2727  // For record types, this is done by the AbstractClassUsageDiagnoser once
2728  // the class has been completely parsed.
2729  if (!CurContext->isRecord() &&
2730      RequireNonAbstractType(D.getIdentifierLoc(), parmDeclType,
2731                             diag::err_abstract_type_in_decl,
2732                             AbstractParamType))
2733    D.setInvalidType(true);
2734
2735  QualType T = adjustParameterType(parmDeclType);
2736
2737  ParmVarDecl *New;
2738  if (T == parmDeclType) // parameter type did not need adjustment
2739    New = ParmVarDecl::Create(Context, CurContext,
2740                              D.getIdentifierLoc(), II,
2741                              parmDeclType, StorageClass,
2742                              0);
2743  else // keep track of both the adjusted and unadjusted types
2744    New = OriginalParmVarDecl::Create(Context, CurContext,
2745                                      D.getIdentifierLoc(), II, T,
2746                                      parmDeclType, StorageClass, 0);
2747
2748  if (D.getInvalidType())
2749    New->setInvalidDecl();
2750
2751  // Parameter declarators cannot be interface types. All ObjC objects are
2752  // passed by reference.
2753  if (T->isObjCInterfaceType()) {
2754    Diag(D.getIdentifierLoc(),
2755         diag::err_object_cannot_be_passed_returned_by_value) << 1 << T;
2756    New->setInvalidDecl();
2757  }
2758
2759  // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2760  if (D.getCXXScopeSpec().isSet()) {
2761    Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2762      << D.getCXXScopeSpec().getRange();
2763    New->setInvalidDecl();
2764  }
2765
2766  // Add the parameter declaration into this scope.
2767  S->AddDecl(DeclPtrTy::make(New));
2768  if (II)
2769    IdResolver.AddDecl(New);
2770
2771  ProcessDeclAttributes(New, D);
2772  return DeclPtrTy::make(New);
2773}
2774
2775void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
2776                                           SourceLocation LocAfterDecls) {
2777  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2778         "Not a function declarator!");
2779  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2780
2781  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2782  // for a K&R function.
2783  if (!FTI.hasPrototype) {
2784    for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
2785      --i;
2786      if (FTI.ArgInfo[i].Param == 0) {
2787        std::string Code = "  int ";
2788        Code += FTI.ArgInfo[i].Ident->getName();
2789        Code += ";\n";
2790        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2791          << FTI.ArgInfo[i].Ident
2792          << CodeModificationHint::CreateInsertion(LocAfterDecls, Code);
2793
2794        // Implicitly declare the argument as type 'int' for lack of a better
2795        // type.
2796        DeclSpec DS;
2797        const char* PrevSpec; // unused
2798        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2799                           PrevSpec);
2800        Declarator ParamD(DS, Declarator::KNRTypeListContext);
2801        ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2802        FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
2803      }
2804    }
2805  }
2806}
2807
2808Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
2809                                              Declarator &D) {
2810  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2811  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2812         "Not a function declarator!");
2813  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2814
2815  if (FTI.hasPrototype) {
2816    // FIXME: Diagnose arguments without names in C.
2817  }
2818
2819  Scope *ParentScope = FnBodyScope->getParent();
2820
2821  DeclPtrTy DP = ActOnDeclarator(ParentScope, D, /*IsFunctionDefinition=*/true);
2822  return ActOnStartOfFunctionDef(FnBodyScope, DP);
2823}
2824
2825Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclPtrTy D) {
2826  FunctionDecl *FD = cast<FunctionDecl>(D.getAs<Decl>());
2827
2828  // See if this is a redefinition.
2829  const FunctionDecl *Definition;
2830  if (FD->getBody(Definition)) {
2831    Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
2832    Diag(Definition->getLocation(), diag::note_previous_definition);
2833  }
2834
2835  // Builtin functions cannot be defined.
2836  if (unsigned BuiltinID = FD->getBuiltinID(Context)) {
2837    if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2838      Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
2839      FD->setInvalidDecl();
2840    }
2841  }
2842
2843  // The return type of a function definition must be complete
2844  // (C99 6.9.1p3, C++ [dcl.fct]p6).
2845  QualType ResultType = FD->getResultType();
2846  if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
2847      RequireCompleteType(FD->getLocation(), ResultType,
2848                          diag::err_func_def_incomplete_result))
2849    FD->setInvalidDecl();
2850
2851  // GNU warning -Wmissing-prototypes:
2852  //   Warn if a global function is defined without a previous
2853  //   prototype declaration. This warning is issued even if the
2854  //   definition itself provides a prototype. The aim is to detect
2855  //   global functions that fail to be declared in header files.
2856  if (!FD->isInvalidDecl() && FD->isGlobal() && !isa<CXXMethodDecl>(FD) &&
2857      !FD->isMain()) {
2858    bool MissingPrototype = true;
2859    for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
2860         Prev; Prev = Prev->getPreviousDeclaration()) {
2861      // Ignore any declarations that occur in function or method
2862      // scope, because they aren't visible from the header.
2863      if (Prev->getDeclContext()->isFunctionOrMethod())
2864        continue;
2865
2866      MissingPrototype = !Prev->getType()->isFunctionProtoType();
2867      break;
2868    }
2869
2870    if (MissingPrototype)
2871      Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
2872  }
2873
2874  PushDeclContext(FnBodyScope, FD);
2875
2876  // Check the validity of our function parameters
2877  CheckParmsForFunctionDef(FD);
2878
2879  // Introduce our parameters into the function scope
2880  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2881    ParmVarDecl *Param = FD->getParamDecl(p);
2882    Param->setOwningFunction(FD);
2883
2884    // If this has an identifier, add it to the scope stack.
2885    if (Param->getIdentifier())
2886      PushOnScopeChains(Param, FnBodyScope);
2887  }
2888
2889  // Checking attributes of current function definition
2890  // dllimport attribute.
2891  if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2892    // dllimport attribute cannot be applied to definition.
2893    if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2894      Diag(FD->getLocation(),
2895           diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2896        << "dllimport";
2897      FD->setInvalidDecl();
2898      return DeclPtrTy::make(FD);
2899    } else {
2900      // If a symbol previously declared dllimport is later defined, the
2901      // attribute is ignored in subsequent references, and a warning is
2902      // emitted.
2903      Diag(FD->getLocation(),
2904           diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2905        << FD->getNameAsCString() << "dllimport";
2906    }
2907  }
2908  return DeclPtrTy::make(FD);
2909}
2910
2911static bool StatementCreatesScope(Stmt* S) {
2912
2913  if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
2914    for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
2915         I != E; ++I) {
2916      if (VarDecl *D = dyn_cast<VarDecl>(*I)) {
2917        if (D->getType()->isVariablyModifiedType() ||
2918            D->hasAttr<CleanupAttr>())
2919          return true;
2920      } else if (TypedefDecl *D = dyn_cast<TypedefDecl>(*I)) {
2921        if (D->getUnderlyingType()->isVariablyModifiedType())
2922          return true;
2923      }
2924    }
2925  }
2926  return false;
2927}
2928
2929
2930void Sema::RecursiveCalcLabelScopes(llvm::DenseMap<Stmt*, void*>& LabelScopeMap,
2931                                    llvm::DenseMap<void*, Stmt*>& PopScopeMap,
2932                                    std::vector<void*>& ScopeStack,
2933                                    Stmt* CurStmt,
2934                                    Stmt* ParentCompoundStmt) {
2935  for (Stmt::child_iterator i = CurStmt->child_begin();
2936       i != CurStmt->child_end(); ++i) {
2937    if (!*i) continue;
2938    if (StatementCreatesScope(*i))  {
2939      ScopeStack.push_back(*i);
2940      PopScopeMap[*i] = ParentCompoundStmt;
2941    } else if (ObjCAtTryStmt *AT = dyn_cast<ObjCAtTryStmt>(*i)) {
2942      ScopeStack.push_back(*i);
2943      PopScopeMap[*i] = AT->getTryBody();
2944    } else if (ObjCAtCatchStmt *AC = dyn_cast<ObjCAtCatchStmt>(*i)) {
2945      ScopeStack.push_back(*i);
2946      PopScopeMap[*i] = AC->getCatchBody();
2947    } else if (ObjCAtFinallyStmt *AF = dyn_cast<ObjCAtFinallyStmt>(*i)) {
2948      ScopeStack.push_back(*i);
2949      PopScopeMap[*i] = AF->getFinallyBody();
2950    } else if (isa<LabelStmt>(CurStmt)) {
2951      LabelScopeMap[CurStmt] = ScopeStack.size() ? ScopeStack.back() : 0;
2952    }
2953    if (isa<DeclStmt>(*i)) continue;
2954    Stmt* CurCompound = isa<CompoundStmt>(*i) ? *i : ParentCompoundStmt;
2955    RecursiveCalcLabelScopes(LabelScopeMap, PopScopeMap, ScopeStack,
2956                             *i, CurCompound);
2957  }
2958  while (ScopeStack.size() && PopScopeMap[ScopeStack.back()] == CurStmt) {
2959    ScopeStack.pop_back();
2960  }
2961}
2962
2963void Sema::RecursiveCalcJumpScopes(llvm::DenseMap<Stmt*, void*>& LabelScopeMap,
2964                                   llvm::DenseMap<void*, Stmt*>& PopScopeMap,
2965                                   llvm::DenseMap<Stmt*, void*>& GotoScopeMap,
2966                                   std::vector<void*>& ScopeStack,
2967                                   Stmt* CurStmt) {
2968  for (Stmt::child_iterator i = CurStmt->child_begin();
2969       i != CurStmt->child_end(); ++i) {
2970    if (!*i) continue;
2971    if (StatementCreatesScope(*i))  {
2972      ScopeStack.push_back(*i);
2973    } else if (GotoStmt* GS = dyn_cast<GotoStmt>(*i)) {
2974      void* LScope = LabelScopeMap[GS->getLabel()];
2975      if (LScope) {
2976        bool foundScopeInStack = false;
2977        for (unsigned i = ScopeStack.size(); i > 0; --i) {
2978          if (LScope == ScopeStack[i-1]) {
2979            foundScopeInStack = true;
2980            break;
2981          }
2982        }
2983        if (!foundScopeInStack) {
2984          Diag(GS->getSourceRange().getBegin(), diag::err_goto_into_scope);
2985        }
2986      }
2987    }
2988    if (isa<DeclStmt>(*i)) continue;
2989    RecursiveCalcJumpScopes(LabelScopeMap, PopScopeMap, GotoScopeMap,
2990                            ScopeStack, *i);
2991  }
2992  while (ScopeStack.size() && PopScopeMap[ScopeStack.back()] == CurStmt) {
2993    ScopeStack.pop_back();
2994  }
2995}
2996
2997Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg) {
2998  Decl *dcl = D.getAs<Decl>();
2999  Stmt *Body = static_cast<Stmt*>(BodyArg.release());
3000  if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
3001    FD->setBody(cast<CompoundStmt>(Body));
3002    assert(FD == getCurFunctionDecl() && "Function parsing confused");
3003  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
3004    assert(MD == getCurMethodDecl() && "Method parsing confused");
3005    MD->setBody(cast<CompoundStmt>(Body));
3006  } else {
3007    Body->Destroy(Context);
3008    return DeclPtrTy();
3009  }
3010  PopDeclContext();
3011  // Verify and clean out per-function state.
3012
3013  bool HaveLabels = !LabelMap.empty();
3014  // Check goto/label use.
3015  for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
3016       I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
3017    // Verify that we have no forward references left.  If so, there was a goto
3018    // or address of a label taken, but no definition of it.  Label fwd
3019    // definitions are indicated with a null substmt.
3020    if (I->second->getSubStmt() == 0) {
3021      LabelStmt *L = I->second;
3022      // Emit error.
3023      Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
3024
3025      // At this point, we have gotos that use the bogus label.  Stitch it into
3026      // the function body so that they aren't leaked and that the AST is well
3027      // formed.
3028      if (Body) {
3029#if 0
3030        // FIXME: Why do this?  Having a 'push_back' in CompoundStmt is ugly,
3031        // and the AST is malformed anyway.  We should just blow away 'L'.
3032        L->setSubStmt(new (Context) NullStmt(L->getIdentLoc()));
3033        cast<CompoundStmt>(Body)->push_back(L);
3034#else
3035        L->Destroy(Context);
3036#endif
3037      } else {
3038        // The whole function wasn't parsed correctly, just delete this.
3039        L->Destroy(Context);
3040      }
3041    }
3042  }
3043  LabelMap.clear();
3044
3045  if (!Body) return D;
3046
3047  if (HaveLabels) {
3048    llvm::DenseMap<Stmt*, void*> LabelScopeMap;
3049    llvm::DenseMap<void*, Stmt*> PopScopeMap;
3050    llvm::DenseMap<Stmt*, void*> GotoScopeMap;
3051    std::vector<void*> ScopeStack;
3052    RecursiveCalcLabelScopes(LabelScopeMap, PopScopeMap, ScopeStack, Body, Body);
3053    RecursiveCalcJumpScopes(LabelScopeMap, PopScopeMap, GotoScopeMap, ScopeStack, Body);
3054  }
3055
3056  return D;
3057}
3058
3059/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
3060/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
3061NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
3062                                          IdentifierInfo &II, Scope *S) {
3063  // Before we produce a declaration for an implicitly defined
3064  // function, see whether there was a locally-scoped declaration of
3065  // this name as a function or variable. If so, use that
3066  // (non-visible) declaration, and complain about it.
3067  llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
3068    = LocallyScopedExternalDecls.find(&II);
3069  if (Pos != LocallyScopedExternalDecls.end()) {
3070    Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
3071    Diag(Pos->second->getLocation(), diag::note_previous_declaration);
3072    return Pos->second;
3073  }
3074
3075  // Extension in C99.  Legal in C90, but warn about it.
3076  if (getLangOptions().C99)
3077    Diag(Loc, diag::ext_implicit_function_decl) << &II;
3078  else
3079    Diag(Loc, diag::warn_implicit_function_decl) << &II;
3080
3081  // FIXME: handle stuff like:
3082  // void foo() { extern float X(); }
3083  // void bar() { X(); }  <-- implicit decl for X in another scope.
3084
3085  // Set a Declarator for the implicit definition: int foo();
3086  const char *Dummy;
3087  DeclSpec DS;
3088  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
3089  Error = Error; // Silence warning.
3090  assert(!Error && "Error setting up implicit decl!");
3091  Declarator D(DS, Declarator::BlockContext);
3092  D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(),
3093                                             0, 0, 0, Loc, D),
3094                SourceLocation());
3095  D.SetIdentifier(&II, Loc);
3096
3097  // Insert this function into translation-unit scope.
3098
3099  DeclContext *PrevDC = CurContext;
3100  CurContext = Context.getTranslationUnitDecl();
3101
3102  FunctionDecl *FD =
3103 dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D, DeclPtrTy()).getAs<Decl>());
3104  FD->setImplicit();
3105
3106  CurContext = PrevDC;
3107
3108  AddKnownFunctionAttributes(FD);
3109
3110  return FD;
3111}
3112
3113/// \brief Adds any function attributes that we know a priori based on
3114/// the declaration of this function.
3115///
3116/// These attributes can apply both to implicitly-declared builtins
3117/// (like __builtin___printf_chk) or to library-declared functions
3118/// like NSLog or printf.
3119void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
3120  if (FD->isInvalidDecl())
3121    return;
3122
3123  // If this is a built-in function, map its builtin attributes to
3124  // actual attributes.
3125  if (unsigned BuiltinID = FD->getBuiltinID(Context)) {
3126    // Handle printf-formatting attributes.
3127    unsigned FormatIdx;
3128    bool HasVAListArg;
3129    if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
3130      if (!FD->getAttr<FormatAttr>())
3131        FD->addAttr(::new (Context) FormatAttr("printf", FormatIdx + 1,
3132                                               FormatIdx + 2));
3133    }
3134
3135    // Mark const if we don't care about errno and that is the only
3136    // thing preventing the function from being const. This allows
3137    // IRgen to use LLVM intrinsics for such functions.
3138    if (!getLangOptions().MathErrno &&
3139        Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
3140      if (!FD->getAttr<ConstAttr>())
3141        FD->addAttr(::new (Context) ConstAttr());
3142    }
3143  }
3144
3145  IdentifierInfo *Name = FD->getIdentifier();
3146  if (!Name)
3147    return;
3148  if ((!getLangOptions().CPlusPlus &&
3149       FD->getDeclContext()->isTranslationUnit()) ||
3150      (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
3151       cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
3152       LinkageSpecDecl::lang_c)) {
3153    // Okay: this could be a libc/libm/Objective-C function we know
3154    // about.
3155  } else
3156    return;
3157
3158  unsigned KnownID;
3159  for (KnownID = 0; KnownID != id_num_known_functions; ++KnownID)
3160    if (KnownFunctionIDs[KnownID] == Name)
3161      break;
3162
3163  switch (KnownID) {
3164  case id_NSLog:
3165  case id_NSLogv:
3166    if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
3167      // FIXME: We known better than our headers.
3168      const_cast<FormatAttr *>(Format)->setType("printf");
3169    } else
3170      FD->addAttr(::new (Context) FormatAttr("printf", 1, 2));
3171    break;
3172
3173  case id_asprintf:
3174  case id_vasprintf:
3175    if (!FD->getAttr<FormatAttr>())
3176      FD->addAttr(::new (Context) FormatAttr("printf", 2, 3));
3177    break;
3178
3179  default:
3180    // Unknown function or known function without any attributes to
3181    // add. Do nothing.
3182    break;
3183  }
3184}
3185
3186TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T) {
3187  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
3188  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3189
3190  // Scope manipulation handled by caller.
3191  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
3192                                           D.getIdentifierLoc(),
3193                                           D.getIdentifier(),
3194                                           T);
3195
3196  if (TagType *TT = dyn_cast<TagType>(T)) {
3197    TagDecl *TD = TT->getDecl();
3198
3199    // If the TagDecl that the TypedefDecl points to is an anonymous decl
3200    // keep track of the TypedefDecl.
3201    if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
3202      TD->setTypedefForAnonDecl(NewTD);
3203  }
3204
3205  if (D.getInvalidType())
3206    NewTD->setInvalidDecl();
3207  return NewTD;
3208}
3209
3210/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
3211/// former case, Name will be non-null.  In the later case, Name will be null.
3212/// TagSpec indicates what kind of tag this is. TK indicates whether this is a
3213/// reference/declaration/definition of a tag.
3214Sema::DeclPtrTy Sema::ActOnTag(Scope *S, unsigned TagSpec, TagKind TK,
3215                               SourceLocation KWLoc, const CXXScopeSpec &SS,
3216                               IdentifierInfo *Name, SourceLocation NameLoc,
3217                               AttributeList *Attr, AccessSpecifier AS) {
3218  // If this is not a definition, it must have a name.
3219  assert((Name != 0 || TK == TK_Definition) &&
3220         "Nameless record must be a definition!");
3221
3222  TagDecl::TagKind Kind;
3223  switch (TagSpec) {
3224  default: assert(0 && "Unknown tag type!");
3225  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3226  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
3227  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
3228  case DeclSpec::TST_enum:   Kind = TagDecl::TK_enum; break;
3229  }
3230
3231  DeclContext *SearchDC = CurContext;
3232  DeclContext *DC = CurContext;
3233  NamedDecl *PrevDecl = 0;
3234
3235  bool Invalid = false;
3236
3237  if (Name && SS.isNotEmpty()) {
3238    // We have a nested-name tag ('struct foo::bar').
3239
3240    // Check for invalid 'foo::'.
3241    if (SS.isInvalid()) {
3242      Name = 0;
3243      goto CreateNewDecl;
3244    }
3245
3246    // FIXME: RequireCompleteDeclContext(SS)?
3247    DC = computeDeclContext(SS);
3248    SearchDC = DC;
3249    // Look-up name inside 'foo::'.
3250    PrevDecl = dyn_cast_or_null<TagDecl>(
3251                 LookupQualifiedName(DC, Name, LookupTagName, true).getAsDecl());
3252
3253    // A tag 'foo::bar' must already exist.
3254    if (PrevDecl == 0) {
3255      Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
3256      Name = 0;
3257      goto CreateNewDecl;
3258    }
3259  } else if (Name) {
3260    // If this is a named struct, check to see if there was a previous forward
3261    // declaration or definition.
3262    // FIXME: We're looking into outer scopes here, even when we
3263    // shouldn't be. Doing so can result in ambiguities that we
3264    // shouldn't be diagnosing.
3265    LookupResult R = LookupName(S, Name, LookupTagName,
3266                                /*RedeclarationOnly=*/(TK != TK_Reference));
3267    if (R.isAmbiguous()) {
3268      DiagnoseAmbiguousLookup(R, Name, NameLoc);
3269      // FIXME: This is not best way to recover from case like:
3270      //
3271      // struct S s;
3272      //
3273      // causes needless "incomplete type" error later.
3274      Name = 0;
3275      PrevDecl = 0;
3276      Invalid = true;
3277    }
3278    else
3279      PrevDecl = R;
3280
3281    if (!getLangOptions().CPlusPlus && TK != TK_Reference) {
3282      // FIXME: This makes sure that we ignore the contexts associated
3283      // with C structs, unions, and enums when looking for a matching
3284      // tag declaration or definition. See the similar lookup tweak
3285      // in Sema::LookupName; is there a better way to deal with this?
3286      while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
3287        SearchDC = SearchDC->getParent();
3288    }
3289  }
3290
3291  if (PrevDecl && PrevDecl->isTemplateParameter()) {
3292    // Maybe we will complain about the shadowed template parameter.
3293    DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
3294    // Just pretend that we didn't see the previous declaration.
3295    PrevDecl = 0;
3296  }
3297
3298  if (PrevDecl) {
3299    // Check whether the previous declaration is usable.
3300    (void)DiagnoseUseOfDecl(PrevDecl, NameLoc);
3301
3302    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
3303      // If this is a use of a previous tag, or if the tag is already declared
3304      // in the same scope (so that the definition/declaration completes or
3305      // rementions the tag), reuse the decl.
3306      if (TK == TK_Reference || isDeclInScope(PrevDecl, SearchDC, S)) {
3307        // Make sure that this wasn't declared as an enum and now used as a
3308        // struct or something similar.
3309        if (PrevTagDecl->getTagKind() != Kind) {
3310          bool SafeToContinue
3311            = (PrevTagDecl->getTagKind() != TagDecl::TK_enum &&
3312               Kind != TagDecl::TK_enum);
3313          if (SafeToContinue)
3314            Diag(KWLoc, diag::err_use_with_wrong_tag)
3315              << Name
3316              << CodeModificationHint::CreateReplacement(SourceRange(KWLoc),
3317                                                  PrevTagDecl->getKindName());
3318          else
3319            Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
3320          Diag(PrevDecl->getLocation(), diag::note_previous_use);
3321
3322          if (SafeToContinue)
3323            Kind = PrevTagDecl->getTagKind();
3324          else {
3325            // Recover by making this an anonymous redefinition.
3326            Name = 0;
3327            PrevDecl = 0;
3328            Invalid = true;
3329          }
3330        }
3331
3332        if (!Invalid) {
3333          // If this is a use, just return the declaration we found.
3334
3335          // FIXME: In the future, return a variant or some other clue
3336          // for the consumer of this Decl to know it doesn't own it.
3337          // For our current ASTs this shouldn't be a problem, but will
3338          // need to be changed with DeclGroups.
3339          if (TK == TK_Reference)
3340            return DeclPtrTy::make(PrevDecl);
3341
3342          // Diagnose attempts to redefine a tag.
3343          if (TK == TK_Definition) {
3344            if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
3345              Diag(NameLoc, diag::err_redefinition) << Name;
3346              Diag(Def->getLocation(), diag::note_previous_definition);
3347              // If this is a redefinition, recover by making this
3348              // struct be anonymous, which will make any later
3349              // references get the previous definition.
3350              Name = 0;
3351              PrevDecl = 0;
3352              Invalid = true;
3353            } else {
3354              // If the type is currently being defined, complain
3355              // about a nested redefinition.
3356              TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
3357              if (Tag->isBeingDefined()) {
3358                Diag(NameLoc, diag::err_nested_redefinition) << Name;
3359                Diag(PrevTagDecl->getLocation(),
3360                     diag::note_previous_definition);
3361                Name = 0;
3362                PrevDecl = 0;
3363                Invalid = true;
3364              }
3365            }
3366
3367            // Okay, this is definition of a previously declared or referenced
3368            // tag PrevDecl. We're going to create a new Decl for it.
3369          }
3370        }
3371        // If we get here we have (another) forward declaration or we
3372        // have a definition.  Just create a new decl.
3373      } else {
3374        // If we get here, this is a definition of a new tag type in a nested
3375        // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
3376        // new decl/type.  We set PrevDecl to NULL so that the entities
3377        // have distinct types.
3378        PrevDecl = 0;
3379      }
3380      // If we get here, we're going to create a new Decl. If PrevDecl
3381      // is non-NULL, it's a definition of the tag declared by
3382      // PrevDecl. If it's NULL, we have a new definition.
3383    } else {
3384      // PrevDecl is a namespace, template, or anything else
3385      // that lives in the IDNS_Tag identifier namespace.
3386      if (isDeclInScope(PrevDecl, SearchDC, S)) {
3387        // The tag name clashes with a namespace name, issue an error and
3388        // recover by making this tag be anonymous.
3389        Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
3390        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3391        Name = 0;
3392        PrevDecl = 0;
3393        Invalid = true;
3394      } else {
3395        // The existing declaration isn't relevant to us; we're in a
3396        // new scope, so clear out the previous declaration.
3397        PrevDecl = 0;
3398      }
3399    }
3400  } else if (TK == TK_Reference && SS.isEmpty() && Name &&
3401             (Kind != TagDecl::TK_enum || !getLangOptions().CPlusPlus)) {
3402    // C.scope.pdecl]p5:
3403    //   -- for an elaborated-type-specifier of the form
3404    //
3405    //          class-key identifier
3406    //
3407    //      if the elaborated-type-specifier is used in the
3408    //      decl-specifier-seq or parameter-declaration-clause of a
3409    //      function defined in namespace scope, the identifier is
3410    //      declared as a class-name in the namespace that contains
3411    //      the declaration; otherwise, except as a friend
3412    //      declaration, the identifier is declared in the smallest
3413    //      non-class, non-function-prototype scope that contains the
3414    //      declaration.
3415    //
3416    // C99 6.7.2.3p8 has a similar (but not identical!) provision for
3417    // C structs and unions.
3418    //
3419    // GNU C also supports this behavior as part of its incomplete
3420    // enum types extension, while GNU C++ does not.
3421    //
3422    // Find the context where we'll be declaring the tag.
3423    // FIXME: We would like to maintain the current DeclContext as the
3424    // lexical context,
3425    while (SearchDC->isRecord())
3426      SearchDC = SearchDC->getParent();
3427
3428    // Find the scope where we'll be declaring the tag.
3429    while (S->isClassScope() ||
3430           (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
3431           ((S->getFlags() & Scope::DeclScope) == 0) ||
3432           (S->getEntity() &&
3433            ((DeclContext *)S->getEntity())->isTransparentContext()))
3434      S = S->getParent();
3435  }
3436
3437CreateNewDecl:
3438
3439  // If there is an identifier, use the location of the identifier as the
3440  // location of the decl, otherwise use the location of the struct/union
3441  // keyword.
3442  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
3443
3444  // Otherwise, create a new declaration. If there is a previous
3445  // declaration of the same entity, the two will be linked via
3446  // PrevDecl.
3447  TagDecl *New;
3448
3449  if (Kind == TagDecl::TK_enum) {
3450    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3451    // enum X { A, B, C } D;    D should chain to X.
3452    New = EnumDecl::Create(Context, SearchDC, Loc, Name,
3453                           cast_or_null<EnumDecl>(PrevDecl));
3454    // If this is an undefined enum, warn.
3455    if (TK != TK_Definition && !Invalid)  {
3456      unsigned DK = getLangOptions().CPlusPlus? diag::err_forward_ref_enum
3457                                              : diag::ext_forward_ref_enum;
3458      Diag(Loc, DK);
3459    }
3460  } else {
3461    // struct/union/class
3462
3463    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3464    // struct X { int A; } D;    D should chain to X.
3465    if (getLangOptions().CPlusPlus)
3466      // FIXME: Look for a way to use RecordDecl for simple structs.
3467      New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name,
3468                                  cast_or_null<CXXRecordDecl>(PrevDecl));
3469    else
3470      New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name,
3471                               cast_or_null<RecordDecl>(PrevDecl));
3472  }
3473
3474  if (Kind != TagDecl::TK_enum) {
3475    // Handle #pragma pack: if the #pragma pack stack has non-default
3476    // alignment, make up a packed attribute for this decl. These
3477    // attributes are checked when the ASTContext lays out the
3478    // structure.
3479    //
3480    // It is important for implementing the correct semantics that this
3481    // happen here (in act on tag decl). The #pragma pack stack is
3482    // maintained as a result of parser callbacks which can occur at
3483    // many points during the parsing of a struct declaration (because
3484    // the #pragma tokens are effectively skipped over during the
3485    // parsing of the struct).
3486    if (unsigned Alignment = getPragmaPackAlignment())
3487      New->addAttr(::new (Context) PackedAttr(Alignment * 8));
3488  }
3489
3490  if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) {
3491    // C++ [dcl.typedef]p3:
3492    //   [...] Similarly, in a given scope, a class or enumeration
3493    //   shall not be declared with the same name as a typedef-name
3494    //   that is declared in that scope and refers to a type other
3495    //   than the class or enumeration itself.
3496    LookupResult Lookup = LookupName(S, Name, LookupOrdinaryName, true);
3497    TypedefDecl *PrevTypedef = 0;
3498    if (Lookup.getKind() == LookupResult::Found)
3499      PrevTypedef = dyn_cast<TypedefDecl>(Lookup.getAsDecl());
3500
3501    if (PrevTypedef && isDeclInScope(PrevTypedef, SearchDC, S) &&
3502        Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) !=
3503          Context.getCanonicalType(Context.getTypeDeclType(New))) {
3504      Diag(Loc, diag::err_tag_definition_of_typedef)
3505        << Context.getTypeDeclType(New)
3506        << PrevTypedef->getUnderlyingType();
3507      Diag(PrevTypedef->getLocation(), diag::note_previous_definition);
3508      Invalid = true;
3509    }
3510  }
3511
3512  if (Invalid)
3513    New->setInvalidDecl();
3514
3515  if (Attr)
3516    ProcessDeclAttributeList(New, Attr);
3517
3518  // If we're declaring or defining a tag in function prototype scope
3519  // in C, note that this type can only be used within the function.
3520  if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
3521    Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
3522
3523  // Set the lexical context. If the tag has a C++ scope specifier, the
3524  // lexical context will be different from the semantic context.
3525  New->setLexicalDeclContext(CurContext);
3526
3527  // Set the access specifier.
3528  SetMemberAccessSpecifier(New, PrevDecl, AS);
3529
3530  if (TK == TK_Definition)
3531    New->startDefinition();
3532
3533  // If this has an identifier, add it to the scope stack.
3534  if (Name) {
3535    S = getNonFieldDeclScope(S);
3536    PushOnScopeChains(New, S);
3537  } else {
3538    CurContext->addDecl(Context, New);
3539  }
3540
3541  return DeclPtrTy::make(New);
3542}
3543
3544void Sema::ActOnTagStartDefinition(Scope *S, DeclPtrTy TagD) {
3545  AdjustDeclIfTemplate(TagD);
3546  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
3547
3548  // Enter the tag context.
3549  PushDeclContext(S, Tag);
3550
3551  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
3552    FieldCollector->StartClass();
3553
3554    if (Record->getIdentifier()) {
3555      // C++ [class]p2:
3556      //   [...] The class-name is also inserted into the scope of the
3557      //   class itself; this is known as the injected-class-name. For
3558      //   purposes of access checking, the injected-class-name is treated
3559      //   as if it were a public member name.
3560      CXXRecordDecl *InjectedClassName
3561        = CXXRecordDecl::Create(Context, Record->getTagKind(),
3562                                CurContext, Record->getLocation(),
3563                                Record->getIdentifier(), Record);
3564      InjectedClassName->setImplicit();
3565      InjectedClassName->setAccess(AS_public);
3566      if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
3567        InjectedClassName->setDescribedClassTemplate(Template);
3568      PushOnScopeChains(InjectedClassName, S);
3569      assert(InjectedClassName->isInjectedClassName() &&
3570             "Broken injected-class-name");
3571    }
3572  }
3573}
3574
3575void Sema::ActOnTagFinishDefinition(Scope *S, DeclPtrTy TagD) {
3576  AdjustDeclIfTemplate(TagD);
3577  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
3578
3579  if (isa<CXXRecordDecl>(Tag))
3580    FieldCollector->FinishClass();
3581
3582  // Exit this scope of this tag's definition.
3583  PopDeclContext();
3584
3585  // Notify the consumer that we've defined a tag.
3586  Consumer.HandleTagDeclDefinition(Tag);
3587}
3588
3589bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
3590                          QualType FieldTy, const Expr *BitWidth) {
3591  // C99 6.7.2.1p4 - verify the field type.
3592  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3593  if (!FieldTy->isDependentType() && !FieldTy->isIntegralType()) {
3594    // Handle incomplete types with specific error.
3595    if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
3596      return true;
3597    return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
3598      << FieldName << FieldTy << BitWidth->getSourceRange();
3599  }
3600
3601  // If the bit-width is type- or value-dependent, don't try to check
3602  // it now.
3603  if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
3604    return false;
3605
3606  llvm::APSInt Value;
3607  if (VerifyIntegerConstantExpression(BitWidth, &Value))
3608    return true;
3609
3610  // Zero-width bitfield is ok for anonymous field.
3611  if (Value == 0 && FieldName)
3612    return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3613
3614  if (Value.isSigned() && Value.isNegative())
3615    return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
3616             << FieldName << Value.toString(10);
3617
3618  if (!FieldTy->isDependentType()) {
3619    uint64_t TypeSize = Context.getTypeSize(FieldTy);
3620    // FIXME: We won't need the 0 size once we check that the field type is valid.
3621    if (TypeSize && Value.getZExtValue() > TypeSize)
3622      return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3623        << FieldName << (unsigned)TypeSize;
3624  }
3625
3626  return false;
3627}
3628
3629/// ActOnField - Each field of a struct/union/class is passed into this in order
3630/// to create a FieldDecl object for it.
3631Sema::DeclPtrTy Sema::ActOnField(Scope *S, DeclPtrTy TagD,
3632                                 SourceLocation DeclStart,
3633                                 Declarator &D, ExprTy *BitfieldWidth) {
3634  FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD.getAs<Decl>()),
3635                               DeclStart, D, static_cast<Expr*>(BitfieldWidth),
3636                               AS_public);
3637  return DeclPtrTy::make(Res);
3638}
3639
3640/// HandleField - Analyze a field of a C struct or a C++ data member.
3641///
3642FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
3643                             SourceLocation DeclStart,
3644                             Declarator &D, Expr *BitWidth,
3645                             AccessSpecifier AS) {
3646  IdentifierInfo *II = D.getIdentifier();
3647  SourceLocation Loc = DeclStart;
3648  if (II) Loc = D.getIdentifierLoc();
3649
3650  QualType T = GetTypeForDeclarator(D, S);
3651  if (getLangOptions().CPlusPlus)
3652    CheckExtraCXXDefaultArguments(D);
3653
3654  DiagnoseFunctionSpecifiers(D);
3655
3656  NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true);
3657  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
3658    PrevDecl = 0;
3659
3660  FieldDecl *NewFD
3661    = CheckFieldDecl(II, T, Record, Loc,
3662               D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable,
3663                     BitWidth, AS, PrevDecl, &D);
3664  if (NewFD->isInvalidDecl() && PrevDecl) {
3665    // Don't introduce NewFD into scope; there's already something
3666    // with the same name in the same scope.
3667  } else if (II) {
3668    PushOnScopeChains(NewFD, S);
3669  } else
3670    Record->addDecl(Context, NewFD);
3671
3672  return NewFD;
3673}
3674
3675/// \brief Build a new FieldDecl and check its well-formedness.
3676///
3677/// This routine builds a new FieldDecl given the fields name, type,
3678/// record, etc. \p PrevDecl should refer to any previous declaration
3679/// with the same name and in the same scope as the field to be
3680/// created.
3681///
3682/// \returns a new FieldDecl.
3683///
3684/// \todo The Declarator argument is a hack. It will be removed once
3685FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
3686                                RecordDecl *Record, SourceLocation Loc,
3687                                bool Mutable, Expr *BitWidth,
3688                                AccessSpecifier AS, NamedDecl *PrevDecl,
3689                                Declarator *D) {
3690  IdentifierInfo *II = Name.getAsIdentifierInfo();
3691  bool InvalidDecl = false;
3692
3693  // If we receive a broken type, recover by assuming 'int' and
3694  // marking this declaration as invalid.
3695  if (T.isNull()) {
3696    InvalidDecl = true;
3697    T = Context.IntTy;
3698  }
3699
3700  // C99 6.7.2.1p8: A member of a structure or union may have any type other
3701  // than a variably modified type.
3702  if (T->isVariablyModifiedType()) {
3703    bool SizeIsNegative;
3704    QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
3705                                                           SizeIsNegative);
3706    if (!FixedTy.isNull()) {
3707      Diag(Loc, diag::warn_illegal_constant_array_size);
3708      T = FixedTy;
3709    } else {
3710      if (SizeIsNegative)
3711        Diag(Loc, diag::err_typecheck_negative_array_size);
3712      else
3713        Diag(Loc, diag::err_typecheck_field_variable_size);
3714      T = Context.IntTy;
3715      InvalidDecl = true;
3716    }
3717  }
3718
3719  // Fields can not have abstract class types
3720  if (RequireNonAbstractType(Loc, T, diag::err_abstract_type_in_decl,
3721                             AbstractFieldType))
3722    InvalidDecl = true;
3723
3724  // If this is declared as a bit-field, check the bit-field.
3725  if (BitWidth && VerifyBitField(Loc, II, T, BitWidth)) {
3726    InvalidDecl = true;
3727    DeleteExpr(BitWidth);
3728    BitWidth = 0;
3729  }
3730
3731  FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, BitWidth,
3732                                       Mutable);
3733
3734  if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
3735    Diag(Loc, diag::err_duplicate_member) << II;
3736    Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3737    NewFD->setInvalidDecl();
3738    Record->setInvalidDecl();
3739  }
3740
3741  if (getLangOptions().CPlusPlus && !T->isPODType())
3742    cast<CXXRecordDecl>(Record)->setPOD(false);
3743
3744  // FIXME: We need to pass in the attributes given an AST
3745  // representation, not a parser representation.
3746  if (D)
3747    ProcessDeclAttributes(NewFD, *D);
3748
3749  if (T.isObjCGCWeak())
3750    Diag(Loc, diag::warn_attribute_weak_on_field);
3751
3752  if (InvalidDecl)
3753    NewFD->setInvalidDecl();
3754
3755  NewFD->setAccess(AS);
3756
3757  // C++ [dcl.init.aggr]p1:
3758  //   An aggregate is an array or a class (clause 9) with [...] no
3759  //   private or protected non-static data members (clause 11).
3760  // A POD must be an aggregate.
3761  if (getLangOptions().CPlusPlus &&
3762      (AS == AS_private || AS == AS_protected)) {
3763    CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
3764    CXXRecord->setAggregate(false);
3765    CXXRecord->setPOD(false);
3766  }
3767
3768  return NewFD;
3769}
3770
3771/// TranslateIvarVisibility - Translate visibility from a token ID to an
3772///  AST enum value.
3773static ObjCIvarDecl::AccessControl
3774TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
3775  switch (ivarVisibility) {
3776  default: assert(0 && "Unknown visitibility kind");
3777  case tok::objc_private: return ObjCIvarDecl::Private;
3778  case tok::objc_public: return ObjCIvarDecl::Public;
3779  case tok::objc_protected: return ObjCIvarDecl::Protected;
3780  case tok::objc_package: return ObjCIvarDecl::Package;
3781  }
3782}
3783
3784/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3785/// in order to create an IvarDecl object for it.
3786Sema::DeclPtrTy Sema::ActOnIvar(Scope *S,
3787                                SourceLocation DeclStart,
3788                                Declarator &D, ExprTy *BitfieldWidth,
3789                                tok::ObjCKeywordKind Visibility) {
3790
3791  IdentifierInfo *II = D.getIdentifier();
3792  Expr *BitWidth = (Expr*)BitfieldWidth;
3793  SourceLocation Loc = DeclStart;
3794  if (II) Loc = D.getIdentifierLoc();
3795
3796  // FIXME: Unnamed fields can be handled in various different ways, for
3797  // example, unnamed unions inject all members into the struct namespace!
3798
3799  QualType T = GetTypeForDeclarator(D, S);
3800  bool InvalidDecl = false;
3801  if (T.isNull()) {
3802    InvalidDecl = true;
3803    T = Context.IntTy;
3804  }
3805
3806  if (BitWidth) {
3807    // 6.7.2.1p3, 6.7.2.1p4
3808    if (VerifyBitField(Loc, II, T, BitWidth)) {
3809      InvalidDecl = true;
3810      DeleteExpr(BitWidth);
3811      BitWidth = 0;
3812    }
3813  } else {
3814    // Not a bitfield.
3815
3816    // validate II.
3817
3818  }
3819
3820  // C99 6.7.2.1p8: A member of a structure or union may have any type other
3821  // than a variably modified type.
3822  if (T->isVariablyModifiedType()) {
3823    Diag(Loc, diag::err_typecheck_ivar_variable_size);
3824    InvalidDecl = true;
3825  }
3826
3827  // Get the visibility (access control) for this ivar.
3828  ObjCIvarDecl::AccessControl ac =
3829    Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3830                                        : ObjCIvarDecl::None;
3831
3832  // Construct the decl.
3833  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, CurContext, Loc, II, T,ac,
3834                                             (Expr *)BitfieldWidth);
3835
3836  if (II) {
3837    NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true);
3838    if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3839        && !isa<TagDecl>(PrevDecl)) {
3840      Diag(Loc, diag::err_duplicate_member) << II;
3841      Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3842      NewID->setInvalidDecl();
3843    }
3844  }
3845
3846  // Process attributes attached to the ivar.
3847  ProcessDeclAttributes(NewID, D);
3848
3849  if (D.getInvalidType() || InvalidDecl)
3850    NewID->setInvalidDecl();
3851
3852  if (II) {
3853    // FIXME: When interfaces are DeclContexts, we'll need to add
3854    // these to the interface.
3855    S->AddDecl(DeclPtrTy::make(NewID));
3856    IdResolver.AddDecl(NewID);
3857  }
3858
3859  return DeclPtrTy::make(NewID);
3860}
3861
3862void Sema::ActOnFields(Scope* S,
3863                       SourceLocation RecLoc, DeclPtrTy RecDecl,
3864                       DeclPtrTy *Fields, unsigned NumFields,
3865                       SourceLocation LBrac, SourceLocation RBrac,
3866                       AttributeList *Attr) {
3867  Decl *EnclosingDecl = RecDecl.getAs<Decl>();
3868  assert(EnclosingDecl && "missing record or interface decl");
3869
3870  // If the decl this is being inserted into is invalid, then it may be a
3871  // redeclaration or some other bogus case.  Don't try to add fields to it.
3872  if (EnclosingDecl->isInvalidDecl()) {
3873    // FIXME: Deallocate fields?
3874    return;
3875  }
3876
3877
3878  // Verify that all the fields are okay.
3879  unsigned NumNamedMembers = 0;
3880  llvm::SmallVector<FieldDecl*, 32> RecFields;
3881
3882  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
3883  for (unsigned i = 0; i != NumFields; ++i) {
3884    FieldDecl *FD = cast<FieldDecl>(Fields[i].getAs<Decl>());
3885
3886    // Get the type for the field.
3887    Type *FDTy = FD->getType().getTypePtr();
3888
3889    if (!FD->isAnonymousStructOrUnion()) {
3890      // Remember all fields written by the user.
3891      RecFields.push_back(FD);
3892    }
3893
3894    // If the field is already invalid for some reason, don't emit more
3895    // diagnostics about it.
3896    if (FD->isInvalidDecl())
3897      continue;
3898
3899    // C99 6.7.2.1p2:
3900    //   A structure or union shall not contain a member with
3901    //   incomplete or function type (hence, a structure shall not
3902    //   contain an instance of itself, but may contain a pointer to
3903    //   an instance of itself), except that the last member of a
3904    //   structure with more than one named member may have incomplete
3905    //   array type; such a structure (and any union containing,
3906    //   possibly recursively, a member that is such a structure)
3907    //   shall not be a member of a structure or an element of an
3908    //   array.
3909    if (FDTy->isFunctionType()) {
3910      // Field declared as a function.
3911      Diag(FD->getLocation(), diag::err_field_declared_as_function)
3912        << FD->getDeclName();
3913      FD->setInvalidDecl();
3914      EnclosingDecl->setInvalidDecl();
3915      continue;
3916    } else if (FDTy->isIncompleteArrayType() && i == NumFields - 1 &&
3917               Record && Record->isStruct()) {
3918      // Flexible array member.
3919      if (NumNamedMembers < 1) {
3920        Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
3921          << FD->getDeclName();
3922        FD->setInvalidDecl();
3923        EnclosingDecl->setInvalidDecl();
3924        continue;
3925      }
3926      // Okay, we have a legal flexible array member at the end of the struct.
3927      if (Record)
3928        Record->setHasFlexibleArrayMember(true);
3929    } else if (!FDTy->isDependentType() &&
3930               RequireCompleteType(FD->getLocation(), FD->getType(),
3931                                   diag::err_field_incomplete)) {
3932      // Incomplete type
3933      FD->setInvalidDecl();
3934      EnclosingDecl->setInvalidDecl();
3935      continue;
3936    } else if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
3937      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3938        // If this is a member of a union, then entire union becomes "flexible".
3939        if (Record && Record->isUnion()) {
3940          Record->setHasFlexibleArrayMember(true);
3941        } else {
3942          // If this is a struct/class and this is not the last element, reject
3943          // it.  Note that GCC supports variable sized arrays in the middle of
3944          // structures.
3945          if (i != NumFields-1)
3946            Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
3947              << FD->getDeclName();
3948          else {
3949            // We support flexible arrays at the end of structs in
3950            // other structs as an extension.
3951            Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
3952              << FD->getDeclName();
3953            if (Record)
3954              Record->setHasFlexibleArrayMember(true);
3955          }
3956        }
3957      }
3958    } else if (FDTy->isObjCInterfaceType()) {
3959      /// A field cannot be an Objective-c object
3960      Diag(FD->getLocation(), diag::err_statically_allocated_object);
3961      FD->setInvalidDecl();
3962      EnclosingDecl->setInvalidDecl();
3963      continue;
3964    }
3965    // Keep track of the number of named members.
3966    if (FD->getIdentifier())
3967      ++NumNamedMembers;
3968  }
3969
3970  // Okay, we successfully defined 'Record'.
3971  if (Record) {
3972    Record->completeDefinition(Context);
3973  } else {
3974    ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
3975    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
3976      ID->setIVarList(ClsFields, RecFields.size(), Context);
3977      ID->setLocEnd(RBrac);
3978
3979      // Must enforce the rule that ivars in the base classes may not be
3980      // duplicates.
3981      if (ID->getSuperClass()) {
3982        for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3983             IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3984          ObjCIvarDecl* Ivar = (*IVI);
3985          IdentifierInfo *II = Ivar->getIdentifier();
3986          ObjCIvarDecl* prevIvar =
3987            ID->getSuperClass()->lookupInstanceVariable(Context, II);
3988          if (prevIvar) {
3989            Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3990            Diag(prevIvar->getLocation(), diag::note_previous_declaration);
3991          }
3992        }
3993      }
3994    } else if (ObjCImplementationDecl *IMPDecl =
3995                  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
3996      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3997      IMPDecl->setIVarList(ClsFields, RecFields.size(), Context);
3998      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
3999    }
4000  }
4001
4002  if (Attr)
4003    ProcessDeclAttributeList(Record, Attr);
4004}
4005
4006EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
4007                                          EnumConstantDecl *LastEnumConst,
4008                                          SourceLocation IdLoc,
4009                                          IdentifierInfo *Id,
4010                                          ExprArg val) {
4011  Expr *Val = (Expr *)val.get();
4012
4013  llvm::APSInt EnumVal(32);
4014  QualType EltTy;
4015  if (Val && !Val->isTypeDependent()) {
4016    // Make sure to promote the operand type to int.
4017    UsualUnaryConversions(Val);
4018    if (Val != val.get()) {
4019      val.release();
4020      val = Val;
4021    }
4022
4023    // C99 6.7.2.2p2: Make sure we have an integer constant expression.
4024    SourceLocation ExpLoc;
4025    if (!Val->isValueDependent() &&
4026        VerifyIntegerConstantExpression(Val, &EnumVal)) {
4027      Val = 0;
4028    } else {
4029      EltTy = Val->getType();
4030    }
4031  }
4032
4033  if (!Val) {
4034    if (LastEnumConst) {
4035      // Assign the last value + 1.
4036      EnumVal = LastEnumConst->getInitVal();
4037      ++EnumVal;
4038
4039      // Check for overflow on increment.
4040      if (EnumVal < LastEnumConst->getInitVal())
4041        Diag(IdLoc, diag::warn_enum_value_overflow);
4042
4043      EltTy = LastEnumConst->getType();
4044    } else {
4045      // First value, set to zero.
4046      EltTy = Context.IntTy;
4047      EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
4048    }
4049  }
4050
4051  val.release();
4052  return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
4053                                  Val, EnumVal);
4054}
4055
4056
4057Sema::DeclPtrTy Sema::ActOnEnumConstant(Scope *S, DeclPtrTy theEnumDecl,
4058                                        DeclPtrTy lastEnumConst,
4059                                        SourceLocation IdLoc,
4060                                        IdentifierInfo *Id,
4061                                        SourceLocation EqualLoc, ExprTy *val) {
4062  EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl.getAs<Decl>());
4063  EnumConstantDecl *LastEnumConst =
4064    cast_or_null<EnumConstantDecl>(lastEnumConst.getAs<Decl>());
4065  Expr *Val = static_cast<Expr*>(val);
4066
4067  // The scope passed in may not be a decl scope.  Zip up the scope tree until
4068  // we find one that is.
4069  S = getNonFieldDeclScope(S);
4070
4071  // Verify that there isn't already something declared with this name in this
4072  // scope.
4073  NamedDecl *PrevDecl = LookupName(S, Id, LookupOrdinaryName);
4074  if (PrevDecl && PrevDecl->isTemplateParameter()) {
4075    // Maybe we will complain about the shadowed template parameter.
4076    DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
4077    // Just pretend that we didn't see the previous declaration.
4078    PrevDecl = 0;
4079  }
4080
4081  if (PrevDecl) {
4082    // When in C++, we may get a TagDecl with the same name; in this case the
4083    // enum constant will 'hide' the tag.
4084    assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
4085           "Received TagDecl when not in C++!");
4086    if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
4087      if (isa<EnumConstantDecl>(PrevDecl))
4088        Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
4089      else
4090        Diag(IdLoc, diag::err_redefinition) << Id;
4091      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4092      if (Val) Val->Destroy(Context);
4093      return DeclPtrTy();
4094    }
4095  }
4096
4097  EnumConstantDecl *New = CheckEnumConstant(TheEnumDecl, LastEnumConst,
4098                                            IdLoc, Id, Owned(Val));
4099
4100  // Register this decl in the current scope stack.
4101  if (New)
4102    PushOnScopeChains(New, S);
4103
4104  return DeclPtrTy::make(New);
4105}
4106
4107// FIXME: For consistency with ActOnFields(), we should have the parser
4108// pass in the source location for the left/right braces.
4109void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclPtrTy EnumDeclX,
4110                         DeclPtrTy *Elements, unsigned NumElements) {
4111  EnumDecl *Enum = cast<EnumDecl>(EnumDeclX.getAs<Decl>());
4112  QualType EnumType = Context.getTypeDeclType(Enum);
4113
4114  // TODO: If the result value doesn't fit in an int, it must be a long or long
4115  // long value.  ISO C does not support this, but GCC does as an extension,
4116  // emit a warning.
4117  unsigned IntWidth = Context.Target.getIntWidth();
4118
4119  // Verify that all the values are okay, compute the size of the values, and
4120  // reverse the list.
4121  unsigned NumNegativeBits = 0;
4122  unsigned NumPositiveBits = 0;
4123
4124  // Keep track of whether all elements have type int.
4125  bool AllElementsInt = true;
4126
4127  for (unsigned i = 0; i != NumElements; ++i) {
4128    EnumConstantDecl *ECD =
4129      cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
4130    if (!ECD) continue;  // Already issued a diagnostic.
4131
4132    // If the enum value doesn't fit in an int, emit an extension warning.
4133    const llvm::APSInt &InitVal = ECD->getInitVal();
4134    assert(InitVal.getBitWidth() >= IntWidth &&
4135           "Should have promoted value to int");
4136    if (InitVal.getBitWidth() > IntWidth) {
4137      llvm::APSInt V(InitVal);
4138      V.trunc(IntWidth);
4139      V.extend(InitVal.getBitWidth());
4140      if (V != InitVal)
4141        Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
4142          << InitVal.toString(10);
4143    }
4144
4145    // Keep track of the size of positive and negative values.
4146    if (InitVal.isUnsigned() || InitVal.isNonNegative())
4147      NumPositiveBits = std::max(NumPositiveBits,
4148                                 (unsigned)InitVal.getActiveBits());
4149    else
4150      NumNegativeBits = std::max(NumNegativeBits,
4151                                 (unsigned)InitVal.getMinSignedBits());
4152
4153    // Keep track of whether every enum element has type int (very commmon).
4154    if (AllElementsInt)
4155      AllElementsInt = ECD->getType() == Context.IntTy;
4156  }
4157
4158  // Figure out the type that should be used for this enum.
4159  // FIXME: Support attribute(packed) on enums and -fshort-enums.
4160  QualType BestType;
4161  unsigned BestWidth;
4162
4163  if (NumNegativeBits) {
4164    // If there is a negative value, figure out the smallest integer type (of
4165    // int/long/longlong) that fits.
4166    if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
4167      BestType = Context.IntTy;
4168      BestWidth = IntWidth;
4169    } else {
4170      BestWidth = Context.Target.getLongWidth();
4171
4172      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
4173        BestType = Context.LongTy;
4174      else {
4175        BestWidth = Context.Target.getLongLongWidth();
4176
4177        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
4178          Diag(Enum->getLocation(), diag::warn_enum_too_large);
4179        BestType = Context.LongLongTy;
4180      }
4181    }
4182  } else {
4183    // If there is no negative value, figure out which of uint, ulong, ulonglong
4184    // fits.
4185    if (NumPositiveBits <= IntWidth) {
4186      BestType = Context.UnsignedIntTy;
4187      BestWidth = IntWidth;
4188    } else if (NumPositiveBits <=
4189               (BestWidth = Context.Target.getLongWidth())) {
4190      BestType = Context.UnsignedLongTy;
4191    } else {
4192      BestWidth = Context.Target.getLongLongWidth();
4193      assert(NumPositiveBits <= BestWidth &&
4194             "How could an initializer get larger than ULL?");
4195      BestType = Context.UnsignedLongLongTy;
4196    }
4197  }
4198
4199  // Loop over all of the enumerator constants, changing their types to match
4200  // the type of the enum if needed.
4201  for (unsigned i = 0; i != NumElements; ++i) {
4202    EnumConstantDecl *ECD =
4203      cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
4204    if (!ECD) continue;  // Already issued a diagnostic.
4205
4206    // Standard C says the enumerators have int type, but we allow, as an
4207    // extension, the enumerators to be larger than int size.  If each
4208    // enumerator value fits in an int, type it as an int, otherwise type it the
4209    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
4210    // that X has type 'int', not 'unsigned'.
4211    if (ECD->getType() == Context.IntTy) {
4212      // Make sure the init value is signed.
4213      llvm::APSInt IV = ECD->getInitVal();
4214      IV.setIsSigned(true);
4215      ECD->setInitVal(IV);
4216
4217      if (getLangOptions().CPlusPlus)
4218        // C++ [dcl.enum]p4: Following the closing brace of an
4219        // enum-specifier, each enumerator has the type of its
4220        // enumeration.
4221        ECD->setType(EnumType);
4222      continue;  // Already int type.
4223    }
4224
4225    // Determine whether the value fits into an int.
4226    llvm::APSInt InitVal = ECD->getInitVal();
4227    bool FitsInInt;
4228    if (InitVal.isUnsigned() || !InitVal.isNegative())
4229      FitsInInt = InitVal.getActiveBits() < IntWidth;
4230    else
4231      FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
4232
4233    // If it fits into an integer type, force it.  Otherwise force it to match
4234    // the enum decl type.
4235    QualType NewTy;
4236    unsigned NewWidth;
4237    bool NewSign;
4238    if (FitsInInt) {
4239      NewTy = Context.IntTy;
4240      NewWidth = IntWidth;
4241      NewSign = true;
4242    } else if (ECD->getType() == BestType) {
4243      // Already the right type!
4244      if (getLangOptions().CPlusPlus)
4245        // C++ [dcl.enum]p4: Following the closing brace of an
4246        // enum-specifier, each enumerator has the type of its
4247        // enumeration.
4248        ECD->setType(EnumType);
4249      continue;
4250    } else {
4251      NewTy = BestType;
4252      NewWidth = BestWidth;
4253      NewSign = BestType->isSignedIntegerType();
4254    }
4255
4256    // Adjust the APSInt value.
4257    InitVal.extOrTrunc(NewWidth);
4258    InitVal.setIsSigned(NewSign);
4259    ECD->setInitVal(InitVal);
4260
4261    // Adjust the Expr initializer and type.
4262    if (ECD->getInitExpr())
4263      ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy, ECD->getInitExpr(),
4264                                                      /*isLvalue=*/false));
4265    if (getLangOptions().CPlusPlus)
4266      // C++ [dcl.enum]p4: Following the closing brace of an
4267      // enum-specifier, each enumerator has the type of its
4268      // enumeration.
4269      ECD->setType(EnumType);
4270    else
4271      ECD->setType(NewTy);
4272  }
4273
4274  Enum->completeDefinition(Context, BestType);
4275}
4276
4277Sema::DeclPtrTy Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
4278                                            ExprArg expr) {
4279  StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
4280
4281  return DeclPtrTy::make(FileScopeAsmDecl::Create(Context, CurContext,
4282                                                  Loc, AsmString));
4283}
4284
4285