ASTContext.cpp revision 8cc246c9a68c783a5b90d2e8b8927521cb3a49b7
1a9aa5fa8ae2a2b43a94e6462ded2cd51445e9ee3ager@chromium.org//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
23484964a86451e86dcf04be9bd8c0d76ee04f081rossberg@chromium.org//
33484964a86451e86dcf04be9bd8c0d76ee04f081rossberg@chromium.org//                     The LLVM Compiler Infrastructure
443d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen//
5b26c50a70863498de657ad44be2cffa49ccdcbeaager@chromium.org// This file is distributed under the University of Illinois Open Source
64b0feeef5d01dbc2948080b4f69daa37e1083461machenbach@chromium.org// License. See LICENSE.TXT for details.
777ca49ac05d25684c89442029c22f5b2bce94395ulan@chromium.org//
843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen//===----------------------------------------------------------------------===//
9196eb601290dc49c3754da728dc58700dff2de1bmachenbach@chromium.org//
10196eb601290dc49c3754da728dc58700dff2de1bmachenbach@chromium.org//  This file implements the ASTContext interface.
11196eb601290dc49c3754da728dc58700dff2de1bmachenbach@chromium.org//
12196eb601290dc49c3754da728dc58700dff2de1bmachenbach@chromium.org//===----------------------------------------------------------------------===//
134b0feeef5d01dbc2948080b4f69daa37e1083461machenbach@chromium.org
14196eb601290dc49c3754da728dc58700dff2de1bmachenbach@chromium.org#include "clang/AST/ASTContext.h"
15196eb601290dc49c3754da728dc58700dff2de1bmachenbach@chromium.org#include "clang/AST/CharUnits.h"
16196eb601290dc49c3754da728dc58700dff2de1bmachenbach@chromium.org#include "clang/AST/DeclCXX.h"
17196eb601290dc49c3754da728dc58700dff2de1bmachenbach@chromium.org#include "clang/AST/DeclObjC.h"
18196eb601290dc49c3754da728dc58700dff2de1bmachenbach@chromium.org#include "clang/AST/DeclTemplate.h"
1943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen#include "clang/AST/TypeLoc.h"
2077ca49ac05d25684c89442029c22f5b2bce94395ulan@chromium.org#include "clang/AST/Expr.h"
2177ca49ac05d25684c89442029c22f5b2bce94395ulan@chromium.org#include "clang/AST/ExprCXX.h"
2277ca49ac05d25684c89442029c22f5b2bce94395ulan@chromium.org#include "clang/AST/ExternalASTSource.h"
2377ca49ac05d25684c89442029c22f5b2bce94395ulan@chromium.org#include "clang/AST/ASTMutationListener.h"
2477ca49ac05d25684c89442029c22f5b2bce94395ulan@chromium.org#include "clang/AST/RecordLayout.h"
2571affb54842da76b24f0bb3184e9f0960523f89dkasperl@chromium.org#include "clang/Basic/Builtins.h"
2671affb54842da76b24f0bb3184e9f0960523f89dkasperl@chromium.org#include "clang/Basic/SourceManager.h"
2743d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen#include "clang/Basic/TargetInfo.h"
2825156ded31ef771a2d799ed902483d83b3ebcbdclrn@chromium.org#include "llvm/ADT/SmallString.h"
29a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org#include "llvm/ADT/StringExtras.h"
30a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org#include "llvm/Support/MathExtras.h"
31a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org#include "llvm/Support/raw_ostream.h"
32a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org#include "CXXABI.h"
33a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org
34a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.orgusing namespace clang;
35a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org
36a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.orgunsigned ASTContext::NumImplicitDefaultConstructors;
37a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.orgunsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
38a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.orgunsigned ASTContext::NumImplicitCopyConstructors;
39a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.orgunsigned ASTContext::NumImplicitCopyConstructorsDeclared;
40a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.orgunsigned ASTContext::NumImplicitCopyAssignmentOperators;
41a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.orgunsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
42a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.orgunsigned ASTContext::NumImplicitDestructors;
43a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.orgunsigned ASTContext::NumImplicitDestructorsDeclared;
44a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org
45a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.orgenum FloatingRank {
46a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org  FloatRank, DoubleRank, LongDoubleRank
47a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org};
48a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org
49a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.orgvoid
50a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.orgASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
51a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org                                               TemplateTemplateParmDecl *Parm) {
52a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org  ID.AddInteger(Parm->getDepth());
53a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org  ID.AddInteger(Parm->getPosition());
54a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org  // FIXME: Parameter pack
55a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org
56a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org  TemplateParameterList *Params = Parm->getTemplateParameters();
57a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org  ID.AddInteger(Params->size());
58a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org  for (TemplateParameterList::const_iterator P = Params->begin(),
59a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org                                          PEnd = Params->end();
60a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org       P != PEnd; ++P) {
61a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
62a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org      ID.AddInteger(0);
63a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org      ID.AddBoolean(TTP->isParameterPack());
64a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org      continue;
65a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org    }
66a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org
67a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org    if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
68a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org      ID.AddInteger(1);
69a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org      // FIXME: Parameter pack
70a9aa5fa8ae2a2b43a94e6462ded2cd51445e9ee3ager@chromium.org      ID.AddPointer(NTTP->getType().getAsOpaquePtr());
71a9aa5fa8ae2a2b43a94e6462ded2cd51445e9ee3ager@chromium.org      continue;
72ef33a5482a35a9a25f702f8e3f02bb6b49f3854cjkummerow@chromium.org    }
73ef33a5482a35a9a25f702f8e3f02bb6b49f3854cjkummerow@chromium.org
74ef33a5482a35a9a25f702f8e3f02bb6b49f3854cjkummerow@chromium.org    TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
75ef33a5482a35a9a25f702f8e3f02bb6b49f3854cjkummerow@chromium.org    ID.AddInteger(2);
76ef33a5482a35a9a25f702f8e3f02bb6b49f3854cjkummerow@chromium.org    Profile(ID, TTP);
77ea88ce93dcb41a9200ec8747ae7642a5db1f4ce7sgjesse@chromium.org  }
7843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen}
7943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
8043d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansenTemplateTemplateParmDecl *
81a9aa5fa8ae2a2b43a94e6462ded2cd51445e9ee3ager@chromium.orgASTContext::getCanonicalTemplateTemplateParmDecl(
822ebef182c49d59eba907b120c3c2a50808bd1f12machenbach@chromium.org                                                 TemplateTemplateParmDecl *TTP) {
8365fae84840520e9ce49a78bf542abf073b49ac3fricow@chromium.org  // Check if we already have a canonical template template parameter.
8465fae84840520e9ce49a78bf542abf073b49ac3fricow@chromium.org  llvm::FoldingSetNodeID ID;
85ef33a5482a35a9a25f702f8e3f02bb6b49f3854cjkummerow@chromium.org  CanonicalTemplateTemplateParm::Profile(ID, TTP);
86ef33a5482a35a9a25f702f8e3f02bb6b49f3854cjkummerow@chromium.org  void *InsertPos = 0;
87ef33a5482a35a9a25f702f8e3f02bb6b49f3854cjkummerow@chromium.org  CanonicalTemplateTemplateParm *Canonical
88ef33a5482a35a9a25f702f8e3f02bb6b49f3854cjkummerow@chromium.org    = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
89ef33a5482a35a9a25f702f8e3f02bb6b49f3854cjkummerow@chromium.org  if (Canonical)
90ea88ce93dcb41a9200ec8747ae7642a5db1f4ce7sgjesse@chromium.org    return Canonical->getParam();
9165fae84840520e9ce49a78bf542abf073b49ac3fricow@chromium.org
9265fae84840520e9ce49a78bf542abf073b49ac3fricow@chromium.org  // Build a canonical template parameter list.
93ef33a5482a35a9a25f702f8e3f02bb6b49f3854cjkummerow@chromium.org  TemplateParameterList *Params = TTP->getTemplateParameters();
9440cb878ef373bea9bdf7998829891e4096751dd0danno@chromium.org  llvm::SmallVector<NamedDecl *, 4> CanonParams;
9540cb878ef373bea9bdf7998829891e4096751dd0danno@chromium.org  CanonParams.reserve(Params->size());
9640cb878ef373bea9bdf7998829891e4096751dd0danno@chromium.org  for (TemplateParameterList::const_iterator P = Params->begin(),
9740cb878ef373bea9bdf7998829891e4096751dd0danno@chromium.org                                          PEnd = Params->end();
9840cb878ef373bea9bdf7998829891e4096751dd0danno@chromium.org       P != PEnd; ++P) {
9940cb878ef373bea9bdf7998829891e4096751dd0danno@chromium.org    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
10040cb878ef373bea9bdf7998829891e4096751dd0danno@chromium.org      CanonParams.push_back(
10140cb878ef373bea9bdf7998829891e4096751dd0danno@chromium.org                  TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
10240cb878ef373bea9bdf7998829891e4096751dd0danno@chromium.org                                               SourceLocation(), TTP->getDepth(),
10365fae84840520e9ce49a78bf542abf073b49ac3fricow@chromium.org                                               TTP->getIndex(), 0, false,
1042ebef182c49d59eba907b120c3c2a50808bd1f12machenbach@chromium.org                                               TTP->isParameterPack()));
1052ebef182c49d59eba907b120c3c2a50808bd1f12machenbach@chromium.org    else if (NonTypeTemplateParmDecl *NTTP
1062ebef182c49d59eba907b120c3c2a50808bd1f12machenbach@chromium.org             = dyn_cast<NonTypeTemplateParmDecl>(*P))
1072ebef182c49d59eba907b120c3c2a50808bd1f12machenbach@chromium.org      CanonParams.push_back(
1082ebef182c49d59eba907b120c3c2a50808bd1f12machenbach@chromium.org            NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
1092ebef182c49d59eba907b120c3c2a50808bd1f12machenbach@chromium.org                                            SourceLocation(), NTTP->getDepth(),
1102ebef182c49d59eba907b120c3c2a50808bd1f12machenbach@chromium.org                                            NTTP->getPosition(), 0,
1112ebef182c49d59eba907b120c3c2a50808bd1f12machenbach@chromium.org                                            getCanonicalType(NTTP->getType()),
1122ebef182c49d59eba907b120c3c2a50808bd1f12machenbach@chromium.org                                            0));
1132ebef182c49d59eba907b120c3c2a50808bd1f12machenbach@chromium.org    else
1142ebef182c49d59eba907b120c3c2a50808bd1f12machenbach@chromium.org      CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
1152ebef182c49d59eba907b120c3c2a50808bd1f12machenbach@chromium.org                                           cast<TemplateTemplateParmDecl>(*P)));
1162ebef182c49d59eba907b120c3c2a50808bd1f12machenbach@chromium.org  }
1172ebef182c49d59eba907b120c3c2a50808bd1f12machenbach@chromium.org
1182ebef182c49d59eba907b120c3c2a50808bd1f12machenbach@chromium.org  TemplateTemplateParmDecl *CanonTTP
1192ebef182c49d59eba907b120c3c2a50808bd1f12machenbach@chromium.org    = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
1202ebef182c49d59eba907b120c3c2a50808bd1f12machenbach@chromium.org                                       SourceLocation(), TTP->getDepth(),
12143d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen                                       TTP->getPosition(), 0,
12243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen                         TemplateParameterList::Create(*this, SourceLocation(),
12383aa54905e559090bea7771b83f188762cfcf082ricow@chromium.org                                                       SourceLocation(),
12483aa54905e559090bea7771b83f188762cfcf082ricow@chromium.org                                                       CanonParams.data(),
12583aa54905e559090bea7771b83f188762cfcf082ricow@chromium.org                                                       CanonParams.size(),
12643d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen                                                       SourceLocation()));
127ddda9e81d3175130f2029c0e1205d265a00c32edjkummerow@chromium.org
12843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  // Get the new insert position for the node we care about.
12943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
130720dc0bc17114e33b9b2177fcb6726bda9cabd62sgjesse@chromium.org  assert(Canonical == 0 && "Shouldn't be in the map!");
1314a6c3279070e8f133607a74c08d8c08ac394ab98erik.corry@gmail.com  (void)Canonical;
132cec079d8ed1f0920a0ea3dc9a3e81966013287c1whesse@chromium.org
133720dc0bc17114e33b9b2177fcb6726bda9cabd62sgjesse@chromium.org  // Create the canonical template template parameter entry.
1344a6c3279070e8f133607a74c08d8c08ac394ab98erik.corry@gmail.com  Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
1354a6c3279070e8f133607a74c08d8c08ac394ab98erik.corry@gmail.com  CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
1364a6c3279070e8f133607a74c08d8c08ac394ab98erik.corry@gmail.com  return CanonTTP;
13743d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen}
13843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
13943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansenCXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
14043d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  if (!LangOpts.CPlusPlus) return 0;
14143d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
14243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  switch (T.getCXXABI()) {
14343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  case CXXABI_ARM:
14443d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen    return CreateARMCXXABI(*this);
14543d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  case CXXABI_Itanium:
14643d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen    return CreateItaniumCXXABI(*this);
14743d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  case CXXABI_Microsoft:
14843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen    return CreateMicrosoftCXXABI(*this);
14943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  }
15043d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  return 0;
15143d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen}
15243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
15343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansenASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
15443d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen                       const TargetInfo &t,
15543d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen                       IdentifierTable &idents, SelectorTable &sels,
15643d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen                       Builtin::Context &builtins,
15743d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen                       unsigned size_reserve) :
15843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  TemplateSpecializationTypes(this_()),
15943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  DependentTemplateSpecializationTypes(this_()),
16043d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  GlobalNestedNameSpecifier(0), IsInt128Installed(false),
16143d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
16243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
16343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
16443d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  NullTypeSourceInfo(QualType()),
16543d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)), Target(t),
16643d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  Idents(idents), Selectors(sels),
16743d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  BuiltinInfo(builtins),
168ddda9e81d3175130f2029c0e1205d265a00c32edjkummerow@chromium.org  DeclarationNames(*this),
16943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
17083aa54905e559090bea7771b83f188762cfcf082ricow@chromium.org  LastSDM(0, 0),
17143d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
17243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  ObjCIdRedefinitionType = QualType();
17343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  ObjCClassRedefinitionType = QualType();
17443d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  ObjCSelRedefinitionType = QualType();
17543d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  if (size_reserve > 0) Types.reserve(size_reserve);
17643d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  TUDecl = TranslationUnitDecl::Create(*this);
17743d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  InitBuiltinTypes();
17843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen}
17943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
18043d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansenASTContext::~ASTContext() {
18143d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  // Release the DenseMaps associated with DeclContext objects.
18243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  // FIXME: Is this the ideal solution?
18343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  ReleaseDeclContextMaps();
18443d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
18543d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  // Call all of the deallocation functions.
18643d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
18743d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen    Deallocations[I].first(Deallocations[I].second);
18843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
18943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  // Release all of the memory associated with overridden C++ methods.
19043d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
19143d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen         OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
19243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen       OM != OMEnd; ++OM)
19343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen    OM->second.Destroy();
19443d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
19543d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
19643d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  // because they can contain DenseMaps.
197f0ac72dfa39ec827de605aafc57d4834237aa7f3whesse@chromium.org  for (llvm::DenseMap<const ObjCContainerDecl*,
198720dc0bc17114e33b9b2177fcb6726bda9cabd62sgjesse@chromium.org       const ASTRecordLayout*>::iterator
199720dc0bc17114e33b9b2177fcb6726bda9cabd62sgjesse@chromium.org       I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
200e3c177a423baa3c30225c4e422b6f6c76d38b951machenbach@chromium.org    // Increment in loop to prevent using deallocated memory.
201e3c177a423baa3c30225c4e422b6f6c76d38b951machenbach@chromium.org    if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
20243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen      R->Destroy(*this);
20343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
20443d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
20543d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen       I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
20643d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen    // Increment in loop to prevent using deallocated memory.
20743d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen    if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
20843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen      R->Destroy(*this);
20943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  }
210720dc0bc17114e33b9b2177fcb6726bda9cabd62sgjesse@chromium.org
211720dc0bc17114e33b9b2177fcb6726bda9cabd62sgjesse@chromium.org  for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
212720dc0bc17114e33b9b2177fcb6726bda9cabd62sgjesse@chromium.org                                                    AEnd = DeclAttrs.end();
21343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen       A != AEnd; ++A)
214fa7f914e3bacba481b13da5cf2bc4c935567ebc4machenbach@chromium.org    A->second->~AttrVec();
21543d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen}
21643d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
21743d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansenvoid ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
21843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  Deallocations.push_back(std::make_pair(Callback, Data));
21943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen}
22043d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
221f0ac72dfa39ec827de605aafc57d4834237aa7f3whesse@chromium.orgvoid
222720dc0bc17114e33b9b2177fcb6726bda9cabd62sgjesse@chromium.orgASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
223f0ac72dfa39ec827de605aafc57d4834237aa7f3whesse@chromium.org  ExternalSource.reset(Source.take());
224720dc0bc17114e33b9b2177fcb6726bda9cabd62sgjesse@chromium.org}
225720dc0bc17114e33b9b2177fcb6726bda9cabd62sgjesse@chromium.org
2264a6c3279070e8f133607a74c08d8c08ac394ab98erik.corry@gmail.comvoid ASTContext::PrintStats() const {
2274a6c3279070e8f133607a74c08d8c08ac394ab98erik.corry@gmail.com  fprintf(stderr, "*** AST Context Stats:\n");
2284a6c3279070e8f133607a74c08d8c08ac394ab98erik.corry@gmail.com  fprintf(stderr, "  %d types total.\n", (int)Types.size());
22943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
23043d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  unsigned counts[] = {
23143d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen#define TYPE(Name, Parent) 0,
23243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen#define ABSTRACT_TYPE(Name, Parent)
23343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen#include "clang/AST/TypeNodes.def"
23443d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen    0 // Extra
23543d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  };
23643d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
23743d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  for (unsigned i = 0, e = Types.size(); i != e; ++i) {
23843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen    Type *T = Types[i];
23943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen    counts[(unsigned)T->getTypeClass()]++;
24043d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  }
24143d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
24243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  unsigned Idx = 0;
24343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  unsigned TotalBytes = 0;
24443d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen#define TYPE(Name, Parent)                                              \
24543d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  if (counts[Idx])                                                      \
246ddda9e81d3175130f2029c0e1205d265a00c32edjkummerow@chromium.org    fprintf(stderr, "    %d %s types\n", (int)counts[Idx], #Name);      \
24743d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
24843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  ++Idx;
24943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen#define ABSTRACT_TYPE(Name, Parent)
25043d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen#include "clang/AST/TypeNodes.def"
25143d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
25243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
25343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
25443d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  // Implicit special member functions.
255ddda9e81d3175130f2029c0e1205d265a00c32edjkummerow@chromium.org  fprintf(stderr, "  %u/%u implicit default constructors created\n",
25643d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen          NumImplicitDefaultConstructorsDeclared,
25743d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen          NumImplicitDefaultConstructors);
25843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  fprintf(stderr, "  %u/%u implicit copy constructors created\n",
25943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen          NumImplicitCopyConstructorsDeclared,
26043d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen          NumImplicitCopyConstructors);
26143d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  fprintf(stderr, "  %u/%u implicit copy assignment operators created\n",
26243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen          NumImplicitCopyAssignmentOperatorsDeclared,
26343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen          NumImplicitCopyAssignmentOperators);
26443d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  fprintf(stderr, "  %u/%u implicit destructors created\n",
26543d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen          NumImplicitDestructorsDeclared, NumImplicitDestructors);
26643d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
26743d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  if (ExternalSource.get()) {
26843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen    fprintf(stderr, "\n");
26943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen    ExternalSource->PrintStats();
27043d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  }
27143d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
27243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  BumpAlloc.PrintStats();
27343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen}
27443d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
27543d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
27643d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansenvoid ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
27743d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
27843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  R = CanQualType::CreateUnsafe(QualType(Ty, 0));
27943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  Types.push_back(Ty);
28043d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen}
281ddda9e81d3175130f2029c0e1205d265a00c32edjkummerow@chromium.org
28243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansenvoid ASTContext::InitBuiltinTypes() {
28343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  assert(VoidTy.isNull() && "Context reinitialized?");
28443d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
28543d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  // C99 6.2.5p19.
28643d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  InitBuiltinType(VoidTy,              BuiltinType::Void);
28743d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
288c4c927273ae2b690c4a015b4640a2a469c9a1a69ager@chromium.org  // C99 6.2.5p2.
289c4c927273ae2b690c4a015b4640a2a469c9a1a69ager@chromium.org  InitBuiltinType(BoolTy,              BuiltinType::Bool);
29043d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  // C99 6.2.5p3.
29143d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  if (LangOpts.CharIsSigned)
29243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen    InitBuiltinType(CharTy,            BuiltinType::Char_S);
29343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  else
294ddda9e81d3175130f2029c0e1205d265a00c32edjkummerow@chromium.org    InitBuiltinType(CharTy,            BuiltinType::Char_U);
29543d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  // C99 6.2.5p4.
29643d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
29743d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  InitBuiltinType(ShortTy,             BuiltinType::Short);
29843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  InitBuiltinType(IntTy,               BuiltinType::Int);
29943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  InitBuiltinType(LongTy,              BuiltinType::Long);
300c20610af4f0ca150977ca140a1174f98ee46f5aafschneider@chromium.org  InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
30143d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
302e3c177a423baa3c30225c4e422b6f6c76d38b951machenbach@chromium.org  // C99 6.2.5p6.
30343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
30443d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
30543d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
30643d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
30743d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
30843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
30943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  // C99 6.2.5p10.
31043d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  InitBuiltinType(FloatTy,             BuiltinType::Float);
31143d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  InitBuiltinType(DoubleTy,            BuiltinType::Double);
31243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
313c20610af4f0ca150977ca140a1174f98ee46f5aafschneider@chromium.org
314c20610af4f0ca150977ca140a1174f98ee46f5aafschneider@chromium.org  // GNU extension, 128-bit integers.
315c20610af4f0ca150977ca140a1174f98ee46f5aafschneider@chromium.org  InitBuiltinType(Int128Ty,            BuiltinType::Int128);
316c20610af4f0ca150977ca140a1174f98ee46f5aafschneider@chromium.org  InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
317c20610af4f0ca150977ca140a1174f98ee46f5aafschneider@chromium.org
318c20610af4f0ca150977ca140a1174f98ee46f5aafschneider@chromium.org  if (LangOpts.CPlusPlus) // C++ 3.9.1p5
319e3c177a423baa3c30225c4e422b6f6c76d38b951machenbach@chromium.org    InitBuiltinType(WCharTy,           BuiltinType::WChar);
3204a6c3279070e8f133607a74c08d8c08ac394ab98erik.corry@gmail.com  else // C99
321c20610af4f0ca150977ca140a1174f98ee46f5aafschneider@chromium.org    WCharTy = getFromTargetType(Target.getWCharType());
322c20610af4f0ca150977ca140a1174f98ee46f5aafschneider@chromium.org
32343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
3244a6c3279070e8f133607a74c08d8c08ac394ab98erik.corry@gmail.com    InitBuiltinType(Char16Ty,           BuiltinType::Char16);
3254a6c3279070e8f133607a74c08d8c08ac394ab98erik.corry@gmail.com  else // C99
3264a6c3279070e8f133607a74c08d8c08ac394ab98erik.corry@gmail.com    Char16Ty = getFromTargetType(Target.getChar16Type());
3274a6c3279070e8f133607a74c08d8c08ac394ab98erik.corry@gmail.com
32843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
3294a6c3279070e8f133607a74c08d8c08ac394ab98erik.corry@gmail.com    InitBuiltinType(Char32Ty,           BuiltinType::Char32);
3304a6c3279070e8f133607a74c08d8c08ac394ab98erik.corry@gmail.com  else // C99
3314a6c3279070e8f133607a74c08d8c08ac394ab98erik.corry@gmail.com    Char32Ty = getFromTargetType(Target.getChar32Type());
33243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
333e3c177a423baa3c30225c4e422b6f6c76d38b951machenbach@chromium.org  // Placeholder type for type-dependent expressions whose type is
334e3c177a423baa3c30225c4e422b6f6c76d38b951machenbach@chromium.org  // completely unknown. No code should ever check a type against
33543d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  // DependentTy and users should never see it; however, it is here to
33643d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  // help diagnose failures to properly check for type-dependent
33743d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  // expressions.
33843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  InitBuiltinType(DependentTy,         BuiltinType::Dependent);
33943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
34043d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  // Placeholder type for functions.
34143d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  InitBuiltinType(OverloadTy,          BuiltinType::Overload);
34243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
34343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  // Placeholder type for C++0x auto declarations whose real type has
34443d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  // not yet been deduced.
345c20610af4f0ca150977ca140a1174f98ee46f5aafschneider@chromium.org  InitBuiltinType(UndeducedAutoTy,     BuiltinType::UndeducedAuto);
346c20610af4f0ca150977ca140a1174f98ee46f5aafschneider@chromium.org
347e3c177a423baa3c30225c4e422b6f6c76d38b951machenbach@chromium.org  // C99 6.2.5p11.
348c20610af4f0ca150977ca140a1174f98ee46f5aafschneider@chromium.org  FloatComplexTy      = getComplexType(FloatTy);
34943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  DoubleComplexTy     = getComplexType(DoubleTy);
35043d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  LongDoubleComplexTy = getComplexType(LongDoubleTy);
35143d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
35243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  BuiltinVaListType = QualType();
35343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
35443d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
35543d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  ObjCIdTypedefType = QualType();
35643d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  ObjCClassTypedefType = QualType();
35743d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  ObjCSelTypedefType = QualType();
35843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
359c20610af4f0ca150977ca140a1174f98ee46f5aafschneider@chromium.org  // Builtin types for 'id', 'Class', and 'SEL'.
360c20610af4f0ca150977ca140a1174f98ee46f5aafschneider@chromium.org  InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
3614a6c3279070e8f133607a74c08d8c08ac394ab98erik.corry@gmail.com  InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
362c20610af4f0ca150977ca140a1174f98ee46f5aafschneider@chromium.org  InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
363c20610af4f0ca150977ca140a1174f98ee46f5aafschneider@chromium.org
3644a6c3279070e8f133607a74c08d8c08ac394ab98erik.corry@gmail.com  ObjCConstantStringType = QualType();
3654a6c3279070e8f133607a74c08d8c08ac394ab98erik.corry@gmail.com
3664a6c3279070e8f133607a74c08d8c08ac394ab98erik.corry@gmail.com  // void * type
367e3c177a423baa3c30225c4e422b6f6c76d38b951machenbach@chromium.org  VoidPtrTy = getPointerType(VoidTy);
36843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
36943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  // nullptr type (C++0x 2.14.7)
37043d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
37143d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen}
37243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
37343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansenDiagnostic &ASTContext::getDiagnostics() const {
37443d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  return SourceMgr.getDiagnostics();
37543d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen}
37643d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
37743d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansenAttrVec& ASTContext::getDeclAttrs(const Decl *D) {
37843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  AttrVec *&Result = DeclAttrs[D];
37943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  if (!Result) {
38043d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen    void *Mem = Allocate(sizeof(AttrVec));
38143d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen    Result = new (Mem) AttrVec;
38243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  }
38343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
38443d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  return *Result;
385ddda9e81d3175130f2029c0e1205d265a00c32edjkummerow@chromium.org}
38643d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
38743d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen/// \brief Erase the attributes corresponding to the given declaration.
38843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansenvoid ASTContext::eraseDeclAttrs(const Decl *D) {
38943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
39043d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  if (Pos != DeclAttrs.end()) {
39143d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen    Pos->second->~AttrVec();
39243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen    DeclAttrs.erase(Pos);
39343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  }
39443d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen}
39543d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
39643d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
39743d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansenMemberSpecializationInfo *
39843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansenASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
39943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  assert(Var->isStaticDataMember() && "Not a static data member");
400c4c927273ae2b690c4a015b4640a2a469c9a1a69ager@chromium.org  llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
40143d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen    = InstantiatedFromStaticDataMember.find(Var);
40243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  if (Pos == InstantiatedFromStaticDataMember.end())
40343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen    return 0;
40443d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
40543d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  return Pos->second;
40643d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen}
40743d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
40843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansenvoid
40943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansenASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
41043d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen                                                TemplateSpecializationKind TSK,
41143d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen                                          SourceLocation PointOfInstantiation) {
41243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  assert(Inst->isStaticDataMember() && "Not a static data member");
41343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  assert(Tmpl->isStaticDataMember() && "Not a static data member");
41443d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  assert(!InstantiatedFromStaticDataMember[Inst] &&
415e3c177a423baa3c30225c4e422b6f6c76d38b951machenbach@chromium.org         "Already noted what static data member was instantiated from");
41643d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  InstantiatedFromStaticDataMember[Inst]
41743d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen    = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
41843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen}
41943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
42043d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansenNamedDecl *
42143d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansenASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
42243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
42343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen    = InstantiatedFromUsingDecl.find(UUD);
42443d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  if (Pos == InstantiatedFromUsingDecl.end())
42543d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen    return 0;
42643d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
42743d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  return Pos->second;
42843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen}
42943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
43043d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansenvoid
43143d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansenASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
43243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  assert((isa<UsingDecl>(Pattern) ||
43343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen          isa<UnresolvedUsingValueDecl>(Pattern) ||
43443d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen          isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
43543d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen         "pattern decl is not a using decl");
436e31286d471eb2e656a1809383fa16b76053dd673machenbach@chromium.org  assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
43743d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  InstantiatedFromUsingDecl[Inst] = Pattern;
43843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen}
43943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
44043d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansenUsingShadowDecl *
44143d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansenASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
44243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
443e31286d471eb2e656a1809383fa16b76053dd673machenbach@chromium.org    = InstantiatedFromUsingShadowDecl.find(Inst);
444c86e8c29eea534916f0d6a2a285b65a86d1b3b67machenbach@chromium.org  if (Pos == InstantiatedFromUsingShadowDecl.end())
445c86e8c29eea534916f0d6a2a285b65a86d1b3b67machenbach@chromium.org    return 0;
44643d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
44743d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  return Pos->second;
44843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen}
449e3c177a423baa3c30225c4e422b6f6c76d38b951machenbach@chromium.org
45043d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansenvoid
45143d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansenASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
45243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen                                               UsingShadowDecl *Pattern) {
45343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
45443d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  InstantiatedFromUsingShadowDecl[Inst] = Pattern;
45543d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen}
45643d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
45743d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansenFieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
45843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
45943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen    = InstantiatedFromUnnamedFieldDecl.find(Field);
46043d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  if (Pos == InstantiatedFromUnnamedFieldDecl.end())
46143d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen    return 0;
46243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
46343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  return Pos->second;
46443d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen}
46543d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
466e31286d471eb2e656a1809383fa16b76053dd673machenbach@chromium.orgvoid ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
467e31286d471eb2e656a1809383fa16b76053dd673machenbach@chromium.org                                                     FieldDecl *Tmpl) {
46843d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
46943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
47043d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
47143d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen         "Already noted what unnamed field was instantiated from");
47243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
47343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
47443d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen}
47543d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
47643d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansenASTContext::overridden_cxx_method_iterator
47743d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansenASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
478ddda9e81d3175130f2029c0e1205d265a00c32edjkummerow@chromium.org  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
47943d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen    = OverriddenMethods.find(Method);
48043d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  if (Pos == OverriddenMethods.end())
48143d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen    return 0;
48243d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen
48343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  return Pos->second.begin();
48443d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen}
485a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org
486a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.orgASTContext::overridden_cxx_method_iterator
487a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.orgASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
488a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
489a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org    = OverriddenMethods.find(Method);
490a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org  if (Pos == OverriddenMethods.end())
491a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org    return 0;
492a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org
4932c81ceb7f1e1ccf5f304be0646f4c1375941a7f2machenbach@chromium.org  return Pos->second.end();
494a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org}
495a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org
496a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.orgunsigned
497a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.orgASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
498a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
499a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org    = OverriddenMethods.find(Method);
500a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org  if (Pos == OverriddenMethods.end())
501a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org    return 0;
502a70700b91bc28abeed6373b856017f7f9cc8273bmachenbach@chromium.org
50343d26ecc3563a46f62a0224030667c8f8f3f6cebchristian.plesner.hansen  return Pos->second.size();
504}
505
506void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
507                                     const CXXMethodDecl *Overridden) {
508  OverriddenMethods[Method].push_back(Overridden);
509}
510
511//===----------------------------------------------------------------------===//
512//                         Type Sizing and Analysis
513//===----------------------------------------------------------------------===//
514
515/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
516/// scalar floating point type.
517const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
518  const BuiltinType *BT = T->getAs<BuiltinType>();
519  assert(BT && "Not a floating point type!");
520  switch (BT->getKind()) {
521  default: assert(0 && "Not a floating point type!");
522  case BuiltinType::Float:      return Target.getFloatFormat();
523  case BuiltinType::Double:     return Target.getDoubleFormat();
524  case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
525  }
526}
527
528/// getDeclAlign - Return a conservative estimate of the alignment of the
529/// specified decl.  Note that bitfields do not have a valid alignment, so
530/// this method will assert on them.
531/// If @p RefAsPointee, references are treated like their underlying type
532/// (for alignof), else they're treated like pointers (for CodeGen).
533CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
534  unsigned Align = Target.getCharWidth();
535
536  bool UseAlignAttrOnly = false;
537  if (unsigned AlignFromAttr = D->getMaxAlignment()) {
538    Align = AlignFromAttr;
539
540    // __attribute__((aligned)) can increase or decrease alignment
541    // *except* on a struct or struct member, where it only increases
542    // alignment unless 'packed' is also specified.
543    //
544    // It is an error for [[align]] to decrease alignment, so we can
545    // ignore that possibility;  Sema should diagnose it.
546    if (isa<FieldDecl>(D)) {
547      UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
548        cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
549    } else {
550      UseAlignAttrOnly = true;
551    }
552  }
553
554  if (UseAlignAttrOnly) {
555    // ignore type of value
556  } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
557    QualType T = VD->getType();
558    if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
559      if (RefAsPointee)
560        T = RT->getPointeeType();
561      else
562        T = getPointerType(RT->getPointeeType());
563    }
564    if (!T->isIncompleteType() && !T->isFunctionType()) {
565      unsigned MinWidth = Target.getLargeArrayMinWidth();
566      unsigned ArrayAlign = Target.getLargeArrayAlign();
567      if (isa<VariableArrayType>(T) && MinWidth != 0)
568        Align = std::max(Align, ArrayAlign);
569      if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
570        unsigned Size = getTypeSize(CT);
571        if (MinWidth != 0 && MinWidth <= Size)
572          Align = std::max(Align, ArrayAlign);
573      }
574      // Incomplete or function types default to 1.
575      while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
576        T = cast<ArrayType>(T)->getElementType();
577
578      Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
579    }
580    if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
581      // In the case of a field in a packed struct, we want the minimum
582      // of the alignment of the field and the alignment of the struct.
583      Align = std::min(Align,
584        getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
585    }
586  }
587
588  return CharUnits::fromQuantity(Align / Target.getCharWidth());
589}
590
591std::pair<CharUnits, CharUnits>
592ASTContext::getTypeInfoInChars(const Type *T) {
593  std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
594  return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
595                        CharUnits::fromQuantity(Info.second / getCharWidth()));
596}
597
598std::pair<CharUnits, CharUnits>
599ASTContext::getTypeInfoInChars(QualType T) {
600  return getTypeInfoInChars(T.getTypePtr());
601}
602
603/// getTypeSize - Return the size of the specified type, in bits.  This method
604/// does not work on incomplete types.
605///
606/// FIXME: Pointers into different addr spaces could have different sizes and
607/// alignment requirements: getPointerInfo should take an AddrSpace, this
608/// should take a QualType, &c.
609std::pair<uint64_t, unsigned>
610ASTContext::getTypeInfo(const Type *T) {
611  uint64_t Width=0;
612  unsigned Align=8;
613  switch (T->getTypeClass()) {
614#define TYPE(Class, Base)
615#define ABSTRACT_TYPE(Class, Base)
616#define NON_CANONICAL_TYPE(Class, Base)
617#define DEPENDENT_TYPE(Class, Base) case Type::Class:
618#include "clang/AST/TypeNodes.def"
619    assert(false && "Should not see dependent types");
620    break;
621
622  case Type::FunctionNoProto:
623  case Type::FunctionProto:
624    // GCC extension: alignof(function) = 32 bits
625    Width = 0;
626    Align = 32;
627    break;
628
629  case Type::IncompleteArray:
630  case Type::VariableArray:
631    Width = 0;
632    Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
633    break;
634
635  case Type::ConstantArray: {
636    const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
637
638    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
639    Width = EltInfo.first*CAT->getSize().getZExtValue();
640    Align = EltInfo.second;
641    break;
642  }
643  case Type::ExtVector:
644  case Type::Vector: {
645    const VectorType *VT = cast<VectorType>(T);
646    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
647    Width = EltInfo.first*VT->getNumElements();
648    Align = Width;
649    // If the alignment is not a power of 2, round up to the next power of 2.
650    // This happens for non-power-of-2 length vectors.
651    if (Align & (Align-1)) {
652      Align = llvm::NextPowerOf2(Align);
653      Width = llvm::RoundUpToAlignment(Width, Align);
654    }
655    break;
656  }
657
658  case Type::Builtin:
659    switch (cast<BuiltinType>(T)->getKind()) {
660    default: assert(0 && "Unknown builtin type!");
661    case BuiltinType::Void:
662      // GCC extension: alignof(void) = 8 bits.
663      Width = 0;
664      Align = 8;
665      break;
666
667    case BuiltinType::Bool:
668      Width = Target.getBoolWidth();
669      Align = Target.getBoolAlign();
670      break;
671    case BuiltinType::Char_S:
672    case BuiltinType::Char_U:
673    case BuiltinType::UChar:
674    case BuiltinType::SChar:
675      Width = Target.getCharWidth();
676      Align = Target.getCharAlign();
677      break;
678    case BuiltinType::WChar:
679      Width = Target.getWCharWidth();
680      Align = Target.getWCharAlign();
681      break;
682    case BuiltinType::Char16:
683      Width = Target.getChar16Width();
684      Align = Target.getChar16Align();
685      break;
686    case BuiltinType::Char32:
687      Width = Target.getChar32Width();
688      Align = Target.getChar32Align();
689      break;
690    case BuiltinType::UShort:
691    case BuiltinType::Short:
692      Width = Target.getShortWidth();
693      Align = Target.getShortAlign();
694      break;
695    case BuiltinType::UInt:
696    case BuiltinType::Int:
697      Width = Target.getIntWidth();
698      Align = Target.getIntAlign();
699      break;
700    case BuiltinType::ULong:
701    case BuiltinType::Long:
702      Width = Target.getLongWidth();
703      Align = Target.getLongAlign();
704      break;
705    case BuiltinType::ULongLong:
706    case BuiltinType::LongLong:
707      Width = Target.getLongLongWidth();
708      Align = Target.getLongLongAlign();
709      break;
710    case BuiltinType::Int128:
711    case BuiltinType::UInt128:
712      Width = 128;
713      Align = 128; // int128_t is 128-bit aligned on all targets.
714      break;
715    case BuiltinType::Float:
716      Width = Target.getFloatWidth();
717      Align = Target.getFloatAlign();
718      break;
719    case BuiltinType::Double:
720      Width = Target.getDoubleWidth();
721      Align = Target.getDoubleAlign();
722      break;
723    case BuiltinType::LongDouble:
724      Width = Target.getLongDoubleWidth();
725      Align = Target.getLongDoubleAlign();
726      break;
727    case BuiltinType::NullPtr:
728      Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
729      Align = Target.getPointerAlign(0); //   == sizeof(void*)
730      break;
731    case BuiltinType::ObjCId:
732    case BuiltinType::ObjCClass:
733    case BuiltinType::ObjCSel:
734      Width = Target.getPointerWidth(0);
735      Align = Target.getPointerAlign(0);
736      break;
737    }
738    break;
739  case Type::ObjCObjectPointer:
740    Width = Target.getPointerWidth(0);
741    Align = Target.getPointerAlign(0);
742    break;
743  case Type::BlockPointer: {
744    unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
745    Width = Target.getPointerWidth(AS);
746    Align = Target.getPointerAlign(AS);
747    break;
748  }
749  case Type::LValueReference:
750  case Type::RValueReference: {
751    // alignof and sizeof should never enter this code path here, so we go
752    // the pointer route.
753    unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
754    Width = Target.getPointerWidth(AS);
755    Align = Target.getPointerAlign(AS);
756    break;
757  }
758  case Type::Pointer: {
759    unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
760    Width = Target.getPointerWidth(AS);
761    Align = Target.getPointerAlign(AS);
762    break;
763  }
764  case Type::MemberPointer: {
765    const MemberPointerType *MPT = cast<MemberPointerType>(T);
766    std::pair<uint64_t, unsigned> PtrDiffInfo =
767      getTypeInfo(getPointerDiffType());
768    Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
769    Align = PtrDiffInfo.second;
770    break;
771  }
772  case Type::Complex: {
773    // Complex types have the same alignment as their elements, but twice the
774    // size.
775    std::pair<uint64_t, unsigned> EltInfo =
776      getTypeInfo(cast<ComplexType>(T)->getElementType());
777    Width = EltInfo.first*2;
778    Align = EltInfo.second;
779    break;
780  }
781  case Type::ObjCObject:
782    return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
783  case Type::ObjCInterface: {
784    const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
785    const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
786    Width = Layout.getSize();
787    Align = Layout.getAlignment();
788    break;
789  }
790  case Type::Record:
791  case Type::Enum: {
792    const TagType *TT = cast<TagType>(T);
793
794    if (TT->getDecl()->isInvalidDecl()) {
795      Width = 1;
796      Align = 1;
797      break;
798    }
799
800    if (const EnumType *ET = dyn_cast<EnumType>(TT))
801      return getTypeInfo(ET->getDecl()->getIntegerType());
802
803    const RecordType *RT = cast<RecordType>(TT);
804    const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
805    Width = Layout.getSize();
806    Align = Layout.getAlignment();
807    break;
808  }
809
810  case Type::SubstTemplateTypeParm:
811    return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
812                       getReplacementType().getTypePtr());
813
814  case Type::Paren:
815    return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
816
817  case Type::Typedef: {
818    const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
819    std::pair<uint64_t, unsigned> Info
820      = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
821    Align = std::max(Typedef->getMaxAlignment(), Info.second);
822    Width = Info.first;
823    break;
824  }
825
826  case Type::TypeOfExpr:
827    return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
828                         .getTypePtr());
829
830  case Type::TypeOf:
831    return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
832
833  case Type::Decltype:
834    return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
835                        .getTypePtr());
836
837  case Type::Elaborated:
838    return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
839
840  case Type::TemplateSpecialization:
841    assert(getCanonicalType(T) != T &&
842           "Cannot request the size of a dependent type");
843    // FIXME: this is likely to be wrong once we support template
844    // aliases, since a template alias could refer to a typedef that
845    // has an __aligned__ attribute on it.
846    return getTypeInfo(getCanonicalType(T));
847  }
848
849  assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
850  return std::make_pair(Width, Align);
851}
852
853/// getTypeSizeInChars - Return the size of the specified type, in characters.
854/// This method does not work on incomplete types.
855CharUnits ASTContext::getTypeSizeInChars(QualType T) {
856  return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
857}
858CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
859  return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
860}
861
862/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
863/// characters. This method does not work on incomplete types.
864CharUnits ASTContext::getTypeAlignInChars(QualType T) {
865  return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
866}
867CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
868  return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
869}
870
871/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
872/// type for the current target in bits.  This can be different than the ABI
873/// alignment in cases where it is beneficial for performance to overalign
874/// a data type.
875unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
876  unsigned ABIAlign = getTypeAlign(T);
877
878  // Double and long long should be naturally aligned if possible.
879  if (const ComplexType* CT = T->getAs<ComplexType>())
880    T = CT->getElementType().getTypePtr();
881  if (T->isSpecificBuiltinType(BuiltinType::Double) ||
882      T->isSpecificBuiltinType(BuiltinType::LongLong))
883    return std::max(ABIAlign, (unsigned)getTypeSize(T));
884
885  return ABIAlign;
886}
887
888/// ShallowCollectObjCIvars -
889/// Collect all ivars, including those synthesized, in the current class.
890///
891void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
892                                 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
893  // FIXME. This need be removed but there are two many places which
894  // assume const-ness of ObjCInterfaceDecl
895  ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
896  for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
897        Iv= Iv->getNextIvar())
898    Ivars.push_back(Iv);
899}
900
901/// DeepCollectObjCIvars -
902/// This routine first collects all declared, but not synthesized, ivars in
903/// super class and then collects all ivars, including those synthesized for
904/// current class. This routine is used for implementation of current class
905/// when all ivars, declared and synthesized are known.
906///
907void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
908                                      bool leafClass,
909                                llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
910  if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
911    DeepCollectObjCIvars(SuperClass, false, Ivars);
912  if (!leafClass) {
913    for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
914         E = OI->ivar_end(); I != E; ++I)
915      Ivars.push_back(*I);
916  }
917  else
918    ShallowCollectObjCIvars(OI, Ivars);
919}
920
921/// CollectInheritedProtocols - Collect all protocols in current class and
922/// those inherited by it.
923void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
924                          llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
925  if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
926    // We can use protocol_iterator here instead of
927    // all_referenced_protocol_iterator since we are walking all categories.
928    for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
929         PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
930      ObjCProtocolDecl *Proto = (*P);
931      Protocols.insert(Proto);
932      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
933           PE = Proto->protocol_end(); P != PE; ++P) {
934        Protocols.insert(*P);
935        CollectInheritedProtocols(*P, Protocols);
936      }
937    }
938
939    // Categories of this Interface.
940    for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
941         CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
942      CollectInheritedProtocols(CDeclChain, Protocols);
943    if (ObjCInterfaceDecl *SD = OI->getSuperClass())
944      while (SD) {
945        CollectInheritedProtocols(SD, Protocols);
946        SD = SD->getSuperClass();
947      }
948  } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
949    for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
950         PE = OC->protocol_end(); P != PE; ++P) {
951      ObjCProtocolDecl *Proto = (*P);
952      Protocols.insert(Proto);
953      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
954           PE = Proto->protocol_end(); P != PE; ++P)
955        CollectInheritedProtocols(*P, Protocols);
956    }
957  } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
958    for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
959         PE = OP->protocol_end(); P != PE; ++P) {
960      ObjCProtocolDecl *Proto = (*P);
961      Protocols.insert(Proto);
962      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
963           PE = Proto->protocol_end(); P != PE; ++P)
964        CollectInheritedProtocols(*P, Protocols);
965    }
966  }
967}
968
969unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
970  unsigned count = 0;
971  // Count ivars declared in class extension.
972  for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
973       CDecl = CDecl->getNextClassExtension())
974    count += CDecl->ivar_size();
975
976  // Count ivar defined in this class's implementation.  This
977  // includes synthesized ivars.
978  if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
979    count += ImplDecl->ivar_size();
980
981  return count;
982}
983
984/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
985ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
986  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
987    I = ObjCImpls.find(D);
988  if (I != ObjCImpls.end())
989    return cast<ObjCImplementationDecl>(I->second);
990  return 0;
991}
992/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
993ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
994  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
995    I = ObjCImpls.find(D);
996  if (I != ObjCImpls.end())
997    return cast<ObjCCategoryImplDecl>(I->second);
998  return 0;
999}
1000
1001/// \brief Set the implementation of ObjCInterfaceDecl.
1002void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1003                           ObjCImplementationDecl *ImplD) {
1004  assert(IFaceD && ImplD && "Passed null params");
1005  ObjCImpls[IFaceD] = ImplD;
1006}
1007/// \brief Set the implementation of ObjCCategoryDecl.
1008void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1009                           ObjCCategoryImplDecl *ImplD) {
1010  assert(CatD && ImplD && "Passed null params");
1011  ObjCImpls[CatD] = ImplD;
1012}
1013
1014/// \brief Get the copy initialization expression of VarDecl,or NULL if
1015/// none exists.
1016Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
1017  assert(VD && "Passed null params");
1018  assert(VD->hasAttr<BlocksAttr>() &&
1019         "getBlockVarCopyInits - not __block var");
1020  llvm::DenseMap<const VarDecl*, Expr*>::iterator
1021    I = BlockVarCopyInits.find(VD);
1022  return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1023}
1024
1025/// \brief Set the copy inialization expression of a block var decl.
1026void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1027  assert(VD && Init && "Passed null params");
1028  assert(VD->hasAttr<BlocksAttr>() &&
1029         "setBlockVarCopyInits - not __block var");
1030  BlockVarCopyInits[VD] = Init;
1031}
1032
1033/// \brief Allocate an uninitialized TypeSourceInfo.
1034///
1035/// The caller should initialize the memory held by TypeSourceInfo using
1036/// the TypeLoc wrappers.
1037///
1038/// \param T the type that will be the basis for type source info. This type
1039/// should refer to how the declarator was written in source code, not to
1040/// what type semantic analysis resolved the declarator to.
1041TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
1042                                                 unsigned DataSize) {
1043  if (!DataSize)
1044    DataSize = TypeLoc::getFullDataSizeForType(T);
1045  else
1046    assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
1047           "incorrect data size provided to CreateTypeSourceInfo!");
1048
1049  TypeSourceInfo *TInfo =
1050    (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1051  new (TInfo) TypeSourceInfo(T);
1052  return TInfo;
1053}
1054
1055TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
1056                                                     SourceLocation L) {
1057  TypeSourceInfo *DI = CreateTypeSourceInfo(T);
1058  DI->getTypeLoc().initialize(L);
1059  return DI;
1060}
1061
1062const ASTRecordLayout &
1063ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1064  return getObjCLayout(D, 0);
1065}
1066
1067const ASTRecordLayout &
1068ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1069  return getObjCLayout(D->getClassInterface(), D);
1070}
1071
1072//===----------------------------------------------------------------------===//
1073//                   Type creation/memoization methods
1074//===----------------------------------------------------------------------===//
1075
1076QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1077  unsigned Fast = Quals.getFastQualifiers();
1078  Quals.removeFastQualifiers();
1079
1080  // Check if we've already instantiated this type.
1081  llvm::FoldingSetNodeID ID;
1082  ExtQuals::Profile(ID, TypeNode, Quals);
1083  void *InsertPos = 0;
1084  if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1085    assert(EQ->getQualifiers() == Quals);
1086    QualType T = QualType(EQ, Fast);
1087    return T;
1088  }
1089
1090  ExtQuals *New = new (*this, TypeAlignment) ExtQuals(TypeNode, Quals);
1091  ExtQualNodes.InsertNode(New, InsertPos);
1092  QualType T = QualType(New, Fast);
1093  return T;
1094}
1095
1096QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
1097  QualType CanT = getCanonicalType(T);
1098  if (CanT.getAddressSpace() == AddressSpace)
1099    return T;
1100
1101  // If we are composing extended qualifiers together, merge together
1102  // into one ExtQuals node.
1103  QualifierCollector Quals;
1104  const Type *TypeNode = Quals.strip(T);
1105
1106  // If this type already has an address space specified, it cannot get
1107  // another one.
1108  assert(!Quals.hasAddressSpace() &&
1109         "Type cannot be in multiple addr spaces!");
1110  Quals.addAddressSpace(AddressSpace);
1111
1112  return getExtQualType(TypeNode, Quals);
1113}
1114
1115QualType ASTContext::getObjCGCQualType(QualType T,
1116                                       Qualifiers::GC GCAttr) {
1117  QualType CanT = getCanonicalType(T);
1118  if (CanT.getObjCGCAttr() == GCAttr)
1119    return T;
1120
1121  if (T->isPointerType()) {
1122    QualType Pointee = T->getAs<PointerType>()->getPointeeType();
1123    if (Pointee->isAnyPointerType()) {
1124      QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1125      return getPointerType(ResultType);
1126    }
1127  }
1128
1129  // If we are composing extended qualifiers together, merge together
1130  // into one ExtQuals node.
1131  QualifierCollector Quals;
1132  const Type *TypeNode = Quals.strip(T);
1133
1134  // If this type already has an ObjCGC specified, it cannot get
1135  // another one.
1136  assert(!Quals.hasObjCGCAttr() &&
1137         "Type cannot have multiple ObjCGCs!");
1138  Quals.addObjCGCAttr(GCAttr);
1139
1140  return getExtQualType(TypeNode, Quals);
1141}
1142
1143static QualType getExtFunctionType(ASTContext& Context, QualType T,
1144                                   const FunctionType::ExtInfo &Info) {
1145  QualType ResultType;
1146  if (const PointerType *Pointer = T->getAs<PointerType>()) {
1147    QualType Pointee = Pointer->getPointeeType();
1148    ResultType = getExtFunctionType(Context, Pointee, Info);
1149    if (ResultType == Pointee)
1150      return T;
1151
1152    ResultType = Context.getPointerType(ResultType);
1153  } else if (const ParenType *Paren = T->getAs<ParenType>()) {
1154    QualType Inner = Paren->getInnerType();
1155    ResultType = getExtFunctionType(Context, Inner, Info);
1156    if (ResultType == Inner)
1157      return T;
1158
1159    ResultType = Context.getParenType(ResultType);
1160  } else if (const BlockPointerType *BlockPointer
1161                                              = T->getAs<BlockPointerType>()) {
1162    QualType Pointee = BlockPointer->getPointeeType();
1163    ResultType = getExtFunctionType(Context, Pointee, Info);
1164    if (ResultType == Pointee)
1165      return T;
1166
1167    ResultType = Context.getBlockPointerType(ResultType);
1168  } else if (const MemberPointerType *MemberPointer
1169                                            = T->getAs<MemberPointerType>()) {
1170    QualType Pointee = MemberPointer->getPointeeType();
1171    ResultType = getExtFunctionType(Context, Pointee, Info);
1172    if (ResultType == Pointee)
1173      return T;
1174
1175    ResultType = Context.getMemberPointerType(ResultType,
1176                                              MemberPointer->getClass());
1177   } else if (const FunctionType *F = T->getAs<FunctionType>()) {
1178    if (F->getExtInfo() == Info)
1179      return T;
1180
1181    if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
1182      ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
1183                                                  Info);
1184    } else {
1185      const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
1186      FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1187      EPI.ExtInfo = Info;
1188      ResultType = Context.getFunctionType(FPT->getResultType(),
1189                                           FPT->arg_type_begin(),
1190                                           FPT->getNumArgs(), EPI);
1191    }
1192  } else
1193    return T;
1194
1195  return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1196}
1197
1198QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
1199  FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1200  return getExtFunctionType(*this, T, Info.withNoReturn(AddNoReturn));
1201}
1202
1203QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
1204  FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1205  return getExtFunctionType(*this, T, Info.withCallingConv(CallConv));
1206}
1207
1208QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) {
1209  FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1210  return getExtFunctionType(*this, T, Info.withRegParm(RegParm));
1211}
1212
1213/// getComplexType - Return the uniqued reference to the type for a complex
1214/// number with the specified element type.
1215QualType ASTContext::getComplexType(QualType T) {
1216  // Unique pointers, to guarantee there is only one pointer of a particular
1217  // structure.
1218  llvm::FoldingSetNodeID ID;
1219  ComplexType::Profile(ID, T);
1220
1221  void *InsertPos = 0;
1222  if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1223    return QualType(CT, 0);
1224
1225  // If the pointee type isn't canonical, this won't be a canonical type either,
1226  // so fill in the canonical type field.
1227  QualType Canonical;
1228  if (!T.isCanonical()) {
1229    Canonical = getComplexType(getCanonicalType(T));
1230
1231    // Get the new insert position for the node we care about.
1232    ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
1233    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1234  }
1235  ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
1236  Types.push_back(New);
1237  ComplexTypes.InsertNode(New, InsertPos);
1238  return QualType(New, 0);
1239}
1240
1241/// getPointerType - Return the uniqued reference to the type for a pointer to
1242/// the specified type.
1243QualType ASTContext::getPointerType(QualType T) {
1244  // Unique pointers, to guarantee there is only one pointer of a particular
1245  // structure.
1246  llvm::FoldingSetNodeID ID;
1247  PointerType::Profile(ID, T);
1248
1249  void *InsertPos = 0;
1250  if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1251    return QualType(PT, 0);
1252
1253  // If the pointee type isn't canonical, this won't be a canonical type either,
1254  // so fill in the canonical type field.
1255  QualType Canonical;
1256  if (!T.isCanonical()) {
1257    Canonical = getPointerType(getCanonicalType(T));
1258
1259    // Get the new insert position for the node we care about.
1260    PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1261    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1262  }
1263  PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
1264  Types.push_back(New);
1265  PointerTypes.InsertNode(New, InsertPos);
1266  return QualType(New, 0);
1267}
1268
1269/// getBlockPointerType - Return the uniqued reference to the type for
1270/// a pointer to the specified block.
1271QualType ASTContext::getBlockPointerType(QualType T) {
1272  assert(T->isFunctionType() && "block of function types only");
1273  // Unique pointers, to guarantee there is only one block of a particular
1274  // structure.
1275  llvm::FoldingSetNodeID ID;
1276  BlockPointerType::Profile(ID, T);
1277
1278  void *InsertPos = 0;
1279  if (BlockPointerType *PT =
1280        BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1281    return QualType(PT, 0);
1282
1283  // If the block pointee type isn't canonical, this won't be a canonical
1284  // type either so fill in the canonical type field.
1285  QualType Canonical;
1286  if (!T.isCanonical()) {
1287    Canonical = getBlockPointerType(getCanonicalType(T));
1288
1289    // Get the new insert position for the node we care about.
1290    BlockPointerType *NewIP =
1291      BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1292    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1293  }
1294  BlockPointerType *New
1295    = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
1296  Types.push_back(New);
1297  BlockPointerTypes.InsertNode(New, InsertPos);
1298  return QualType(New, 0);
1299}
1300
1301/// getLValueReferenceType - Return the uniqued reference to the type for an
1302/// lvalue reference to the specified type.
1303QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
1304  // Unique pointers, to guarantee there is only one pointer of a particular
1305  // structure.
1306  llvm::FoldingSetNodeID ID;
1307  ReferenceType::Profile(ID, T, SpelledAsLValue);
1308
1309  void *InsertPos = 0;
1310  if (LValueReferenceType *RT =
1311        LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1312    return QualType(RT, 0);
1313
1314  const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1315
1316  // If the referencee type isn't canonical, this won't be a canonical type
1317  // either, so fill in the canonical type field.
1318  QualType Canonical;
1319  if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1320    QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1321    Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
1322
1323    // Get the new insert position for the node we care about.
1324    LValueReferenceType *NewIP =
1325      LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1326    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1327  }
1328
1329  LValueReferenceType *New
1330    = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1331                                                     SpelledAsLValue);
1332  Types.push_back(New);
1333  LValueReferenceTypes.InsertNode(New, InsertPos);
1334
1335  return QualType(New, 0);
1336}
1337
1338/// getRValueReferenceType - Return the uniqued reference to the type for an
1339/// rvalue reference to the specified type.
1340QualType ASTContext::getRValueReferenceType(QualType T) {
1341  // Unique pointers, to guarantee there is only one pointer of a particular
1342  // structure.
1343  llvm::FoldingSetNodeID ID;
1344  ReferenceType::Profile(ID, T, false);
1345
1346  void *InsertPos = 0;
1347  if (RValueReferenceType *RT =
1348        RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1349    return QualType(RT, 0);
1350
1351  const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1352
1353  // If the referencee type isn't canonical, this won't be a canonical type
1354  // either, so fill in the canonical type field.
1355  QualType Canonical;
1356  if (InnerRef || !T.isCanonical()) {
1357    QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1358    Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
1359
1360    // Get the new insert position for the node we care about.
1361    RValueReferenceType *NewIP =
1362      RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1363    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1364  }
1365
1366  RValueReferenceType *New
1367    = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
1368  Types.push_back(New);
1369  RValueReferenceTypes.InsertNode(New, InsertPos);
1370  return QualType(New, 0);
1371}
1372
1373/// getMemberPointerType - Return the uniqued reference to the type for a
1374/// member pointer to the specified type, in the specified class.
1375QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
1376  // Unique pointers, to guarantee there is only one pointer of a particular
1377  // structure.
1378  llvm::FoldingSetNodeID ID;
1379  MemberPointerType::Profile(ID, T, Cls);
1380
1381  void *InsertPos = 0;
1382  if (MemberPointerType *PT =
1383      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1384    return QualType(PT, 0);
1385
1386  // If the pointee or class type isn't canonical, this won't be a canonical
1387  // type either, so fill in the canonical type field.
1388  QualType Canonical;
1389  if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
1390    Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1391
1392    // Get the new insert position for the node we care about.
1393    MemberPointerType *NewIP =
1394      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1395    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1396  }
1397  MemberPointerType *New
1398    = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
1399  Types.push_back(New);
1400  MemberPointerTypes.InsertNode(New, InsertPos);
1401  return QualType(New, 0);
1402}
1403
1404/// getConstantArrayType - Return the unique reference to the type for an
1405/// array of the specified element type.
1406QualType ASTContext::getConstantArrayType(QualType EltTy,
1407                                          const llvm::APInt &ArySizeIn,
1408                                          ArrayType::ArraySizeModifier ASM,
1409                                          unsigned EltTypeQuals) {
1410  assert((EltTy->isDependentType() ||
1411          EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
1412         "Constant array of VLAs is illegal!");
1413
1414  // Convert the array size into a canonical width matching the pointer size for
1415  // the target.
1416  llvm::APInt ArySize(ArySizeIn);
1417  ArySize =
1418    ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1419
1420  llvm::FoldingSetNodeID ID;
1421  ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
1422
1423  void *InsertPos = 0;
1424  if (ConstantArrayType *ATP =
1425      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1426    return QualType(ATP, 0);
1427
1428  // If the element type isn't canonical, this won't be a canonical type either,
1429  // so fill in the canonical type field.
1430  QualType Canonical;
1431  if (!EltTy.isCanonical()) {
1432    Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
1433                                     ASM, EltTypeQuals);
1434    // Get the new insert position for the node we care about.
1435    ConstantArrayType *NewIP =
1436      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1437    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1438  }
1439
1440  ConstantArrayType *New = new(*this,TypeAlignment)
1441    ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
1442  ConstantArrayTypes.InsertNode(New, InsertPos);
1443  Types.push_back(New);
1444  return QualType(New, 0);
1445}
1446
1447/// getIncompleteArrayType - Returns a unique reference to the type for a
1448/// incomplete array of the specified element type.
1449QualType ASTContext::getUnknownSizeVariableArrayType(QualType Ty) {
1450  QualType ElemTy = getBaseElementType(Ty);
1451  DeclarationName Name;
1452  llvm::SmallVector<QualType, 8> ATypes;
1453  QualType ATy = Ty;
1454  while (const ArrayType *AT = getAsArrayType(ATy)) {
1455    ATypes.push_back(ATy);
1456    ATy = AT->getElementType();
1457  }
1458  for (int i = ATypes.size() - 1; i >= 0; i--) {
1459    if (const VariableArrayType *VAT = getAsVariableArrayType(ATypes[i])) {
1460      ElemTy = getVariableArrayType(ElemTy, /*ArraySize*/0, ArrayType::Star,
1461                                    0, VAT->getBracketsRange());
1462    }
1463    else if (const ConstantArrayType *CAT = getAsConstantArrayType(ATypes[i])) {
1464      llvm::APSInt ConstVal(CAT->getSize());
1465      ElemTy = getConstantArrayType(ElemTy, ConstVal, ArrayType::Normal, 0);
1466    }
1467    else if (getAsIncompleteArrayType(ATypes[i])) {
1468      ElemTy = getVariableArrayType(ElemTy, /*ArraySize*/0, ArrayType::Normal,
1469                                    0, SourceRange());
1470    }
1471    else
1472      assert(false && "DependentArrayType is seen");
1473  }
1474  return ElemTy;
1475}
1476
1477/// getVariableArrayDecayedType - Returns a vla type where known sizes
1478/// are replaced with [*]
1479QualType ASTContext::getVariableArrayDecayedType(QualType Ty) {
1480  if (Ty->isPointerType()) {
1481    QualType BaseType = Ty->getAs<PointerType>()->getPointeeType();
1482    if (isa<VariableArrayType>(BaseType)) {
1483      ArrayType *AT = dyn_cast<ArrayType>(BaseType);
1484      VariableArrayType *VAT = cast<VariableArrayType>(AT);
1485      if (VAT->getSizeExpr()) {
1486        Ty = getUnknownSizeVariableArrayType(BaseType);
1487        Ty = getPointerType(Ty);
1488      }
1489    }
1490  }
1491  return Ty;
1492}
1493
1494
1495/// getVariableArrayType - Returns a non-unique reference to the type for a
1496/// variable array of the specified element type.
1497QualType ASTContext::getVariableArrayType(QualType EltTy,
1498                                          Expr *NumElts,
1499                                          ArrayType::ArraySizeModifier ASM,
1500                                          unsigned EltTypeQuals,
1501                                          SourceRange Brackets) {
1502  // Since we don't unique expressions, it isn't possible to unique VLA's
1503  // that have an expression provided for their size.
1504  QualType CanonType;
1505
1506  if (!EltTy.isCanonical()) {
1507    CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1508                                     EltTypeQuals, Brackets);
1509  }
1510
1511  VariableArrayType *New = new(*this, TypeAlignment)
1512    VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
1513
1514  VariableArrayTypes.push_back(New);
1515  Types.push_back(New);
1516  return QualType(New, 0);
1517}
1518
1519/// getDependentSizedArrayType - Returns a non-unique reference to
1520/// the type for a dependently-sized array of the specified element
1521/// type.
1522QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1523                                                Expr *NumElts,
1524                                                ArrayType::ArraySizeModifier ASM,
1525                                                unsigned EltTypeQuals,
1526                                                SourceRange Brackets) {
1527  assert((!NumElts || NumElts->isTypeDependent() ||
1528          NumElts->isValueDependent()) &&
1529         "Size must be type- or value-dependent!");
1530
1531  void *InsertPos = 0;
1532  DependentSizedArrayType *Canon = 0;
1533  llvm::FoldingSetNodeID ID;
1534
1535  QualType CanonicalEltTy = getCanonicalType(EltTy);
1536  if (NumElts) {
1537    // Dependently-sized array types that do not have a specified
1538    // number of elements will have their sizes deduced from an
1539    // initializer.
1540    DependentSizedArrayType::Profile(ID, *this, CanonicalEltTy, ASM,
1541                                     EltTypeQuals, NumElts);
1542
1543    Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1544  }
1545
1546  DependentSizedArrayType *New;
1547  if (Canon) {
1548    // We already have a canonical version of this array type; use it as
1549    // the canonical type for a newly-built type.
1550    New = new (*this, TypeAlignment)
1551      DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1552                              NumElts, ASM, EltTypeQuals, Brackets);
1553  } else if (CanonicalEltTy == EltTy) {
1554    // This is a canonical type. Record it.
1555    New = new (*this, TypeAlignment)
1556      DependentSizedArrayType(*this, EltTy, QualType(),
1557                              NumElts, ASM, EltTypeQuals, Brackets);
1558
1559    if (NumElts) {
1560#ifndef NDEBUG
1561      DependentSizedArrayType *CanonCheck
1562        = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1563      assert(!CanonCheck && "Dependent-sized canonical array type broken");
1564      (void)CanonCheck;
1565#endif
1566      DependentSizedArrayTypes.InsertNode(New, InsertPos);
1567    }
1568  } else {
1569    QualType Canon = getDependentSizedArrayType(CanonicalEltTy, NumElts,
1570                                                ASM, EltTypeQuals,
1571                                                SourceRange());
1572    New = new (*this, TypeAlignment)
1573      DependentSizedArrayType(*this, EltTy, Canon,
1574                              NumElts, ASM, EltTypeQuals, Brackets);
1575  }
1576
1577  Types.push_back(New);
1578  return QualType(New, 0);
1579}
1580
1581QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1582                                            ArrayType::ArraySizeModifier ASM,
1583                                            unsigned EltTypeQuals) {
1584  llvm::FoldingSetNodeID ID;
1585  IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
1586
1587  void *InsertPos = 0;
1588  if (IncompleteArrayType *ATP =
1589       IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1590    return QualType(ATP, 0);
1591
1592  // If the element type isn't canonical, this won't be a canonical type
1593  // either, so fill in the canonical type field.
1594  QualType Canonical;
1595
1596  if (!EltTy.isCanonical()) {
1597    Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
1598                                       ASM, EltTypeQuals);
1599
1600    // Get the new insert position for the node we care about.
1601    IncompleteArrayType *NewIP =
1602      IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1603    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1604  }
1605
1606  IncompleteArrayType *New = new (*this, TypeAlignment)
1607    IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
1608
1609  IncompleteArrayTypes.InsertNode(New, InsertPos);
1610  Types.push_back(New);
1611  return QualType(New, 0);
1612}
1613
1614/// getVectorType - Return the unique reference to a vector type of
1615/// the specified element type and size. VectorType must be a built-in type.
1616QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1617                                   VectorType::VectorKind VecKind) {
1618  BuiltinType *BaseType;
1619
1620  BaseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1621  assert(BaseType != 0 && "getVectorType(): Expecting a built-in type");
1622
1623  // Check if we've already instantiated a vector of this type.
1624  llvm::FoldingSetNodeID ID;
1625  VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
1626
1627  void *InsertPos = 0;
1628  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1629    return QualType(VTP, 0);
1630
1631  // If the element type isn't canonical, this won't be a canonical type either,
1632  // so fill in the canonical type field.
1633  QualType Canonical;
1634  if (!vecType.isCanonical()) {
1635    Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
1636
1637    // Get the new insert position for the node we care about.
1638    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1639    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1640  }
1641  VectorType *New = new (*this, TypeAlignment)
1642    VectorType(vecType, NumElts, Canonical, VecKind);
1643  VectorTypes.InsertNode(New, InsertPos);
1644  Types.push_back(New);
1645  return QualType(New, 0);
1646}
1647
1648/// getExtVectorType - Return the unique reference to an extended vector type of
1649/// the specified element type and size. VectorType must be a built-in type.
1650QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
1651  BuiltinType *baseType;
1652
1653  baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1654  assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
1655
1656  // Check if we've already instantiated a vector of this type.
1657  llvm::FoldingSetNodeID ID;
1658  VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
1659                      VectorType::GenericVector);
1660  void *InsertPos = 0;
1661  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1662    return QualType(VTP, 0);
1663
1664  // If the element type isn't canonical, this won't be a canonical type either,
1665  // so fill in the canonical type field.
1666  QualType Canonical;
1667  if (!vecType.isCanonical()) {
1668    Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
1669
1670    // Get the new insert position for the node we care about.
1671    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1672    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1673  }
1674  ExtVectorType *New = new (*this, TypeAlignment)
1675    ExtVectorType(vecType, NumElts, Canonical);
1676  VectorTypes.InsertNode(New, InsertPos);
1677  Types.push_back(New);
1678  return QualType(New, 0);
1679}
1680
1681QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1682                                                    Expr *SizeExpr,
1683                                                    SourceLocation AttrLoc) {
1684  llvm::FoldingSetNodeID ID;
1685  DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
1686                                       SizeExpr);
1687
1688  void *InsertPos = 0;
1689  DependentSizedExtVectorType *Canon
1690    = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1691  DependentSizedExtVectorType *New;
1692  if (Canon) {
1693    // We already have a canonical version of this array type; use it as
1694    // the canonical type for a newly-built type.
1695    New = new (*this, TypeAlignment)
1696      DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1697                                  SizeExpr, AttrLoc);
1698  } else {
1699    QualType CanonVecTy = getCanonicalType(vecType);
1700    if (CanonVecTy == vecType) {
1701      New = new (*this, TypeAlignment)
1702        DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1703                                    AttrLoc);
1704
1705      DependentSizedExtVectorType *CanonCheck
1706        = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1707      assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1708      (void)CanonCheck;
1709      DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1710    } else {
1711      QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1712                                                      SourceLocation());
1713      New = new (*this, TypeAlignment)
1714        DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
1715    }
1716  }
1717
1718  Types.push_back(New);
1719  return QualType(New, 0);
1720}
1721
1722/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
1723///
1724QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1725                                            const FunctionType::ExtInfo &Info) {
1726  const CallingConv CallConv = Info.getCC();
1727  // Unique functions, to guarantee there is only one function of a particular
1728  // structure.
1729  llvm::FoldingSetNodeID ID;
1730  FunctionNoProtoType::Profile(ID, ResultTy, Info);
1731
1732  void *InsertPos = 0;
1733  if (FunctionNoProtoType *FT =
1734        FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1735    return QualType(FT, 0);
1736
1737  QualType Canonical;
1738  if (!ResultTy.isCanonical() ||
1739      getCanonicalCallConv(CallConv) != CallConv) {
1740    Canonical =
1741      getFunctionNoProtoType(getCanonicalType(ResultTy),
1742                     Info.withCallingConv(getCanonicalCallConv(CallConv)));
1743
1744    // Get the new insert position for the node we care about.
1745    FunctionNoProtoType *NewIP =
1746      FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1747    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1748  }
1749
1750  FunctionNoProtoType *New = new (*this, TypeAlignment)
1751    FunctionNoProtoType(ResultTy, Canonical, Info);
1752  Types.push_back(New);
1753  FunctionNoProtoTypes.InsertNode(New, InsertPos);
1754  return QualType(New, 0);
1755}
1756
1757/// getFunctionType - Return a normal function type with a typed argument
1758/// list.  isVariadic indicates whether the argument list includes '...'.
1759QualType ASTContext::getFunctionType(QualType ResultTy,
1760                                     const QualType *ArgArray, unsigned NumArgs,
1761                                   const FunctionProtoType::ExtProtoInfo &EPI) {
1762  // Unique functions, to guarantee there is only one function of a particular
1763  // structure.
1764  llvm::FoldingSetNodeID ID;
1765  FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI);
1766
1767  void *InsertPos = 0;
1768  if (FunctionProtoType *FTP =
1769        FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1770    return QualType(FTP, 0);
1771
1772  // Determine whether the type being created is already canonical or not.
1773  bool isCanonical = !EPI.HasExceptionSpec && ResultTy.isCanonical();
1774  for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1775    if (!ArgArray[i].isCanonicalAsParam())
1776      isCanonical = false;
1777
1778  const CallingConv CallConv = EPI.ExtInfo.getCC();
1779
1780  // If this type isn't canonical, get the canonical version of it.
1781  // The exception spec is not part of the canonical type.
1782  QualType Canonical;
1783  if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
1784    llvm::SmallVector<QualType, 16> CanonicalArgs;
1785    CanonicalArgs.reserve(NumArgs);
1786    for (unsigned i = 0; i != NumArgs; ++i)
1787      CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
1788
1789    FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
1790    if (CanonicalEPI.HasExceptionSpec) {
1791      CanonicalEPI.HasExceptionSpec = false;
1792      CanonicalEPI.HasAnyExceptionSpec = false;
1793      CanonicalEPI.NumExceptions = 0;
1794    }
1795    CanonicalEPI.ExtInfo
1796      = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
1797
1798    Canonical = getFunctionType(getCanonicalType(ResultTy),
1799                                CanonicalArgs.data(), NumArgs,
1800                                CanonicalEPI);
1801
1802    // Get the new insert position for the node we care about.
1803    FunctionProtoType *NewIP =
1804      FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1805    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1806  }
1807
1808  // FunctionProtoType objects are allocated with extra bytes after them
1809  // for two variable size arrays (for parameter and exception types) at the
1810  // end of them.
1811  size_t Size = sizeof(FunctionProtoType) +
1812                NumArgs * sizeof(QualType) +
1813                EPI.NumExceptions * sizeof(QualType);
1814  FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
1815  new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, EPI);
1816  Types.push_back(FTP);
1817  FunctionProtoTypes.InsertNode(FTP, InsertPos);
1818  return QualType(FTP, 0);
1819}
1820
1821#ifndef NDEBUG
1822static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1823  if (!isa<CXXRecordDecl>(D)) return false;
1824  const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1825  if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1826    return true;
1827  if (RD->getDescribedClassTemplate() &&
1828      !isa<ClassTemplateSpecializationDecl>(RD))
1829    return true;
1830  return false;
1831}
1832#endif
1833
1834/// getInjectedClassNameType - Return the unique reference to the
1835/// injected class name type for the specified templated declaration.
1836QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1837                                              QualType TST) {
1838  assert(NeedsInjectedClassNameType(Decl));
1839  if (Decl->TypeForDecl) {
1840    assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1841  } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
1842    assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1843    Decl->TypeForDecl = PrevDecl->TypeForDecl;
1844    assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1845  } else {
1846    Decl->TypeForDecl =
1847      new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
1848    Types.push_back(Decl->TypeForDecl);
1849  }
1850  return QualType(Decl->TypeForDecl, 0);
1851}
1852
1853/// getTypeDeclType - Return the unique reference to the type for the
1854/// specified type declaration.
1855QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
1856  assert(Decl && "Passed null for Decl param");
1857  assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
1858
1859  if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
1860    return getTypedefType(Typedef);
1861
1862  assert(!isa<TemplateTypeParmDecl>(Decl) &&
1863         "Template type parameter types are always available.");
1864
1865  if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
1866    assert(!Record->getPreviousDeclaration() &&
1867           "struct/union has previous declaration");
1868    assert(!NeedsInjectedClassNameType(Record));
1869    return getRecordType(Record);
1870  } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1871    assert(!Enum->getPreviousDeclaration() &&
1872           "enum has previous declaration");
1873    return getEnumType(Enum);
1874  } else if (const UnresolvedUsingTypenameDecl *Using =
1875               dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1876    Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
1877  } else
1878    llvm_unreachable("TypeDecl without a type?");
1879
1880  Types.push_back(Decl->TypeForDecl);
1881  return QualType(Decl->TypeForDecl, 0);
1882}
1883
1884/// getTypedefType - Return the unique reference to the type for the
1885/// specified typename decl.
1886QualType
1887ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) {
1888  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1889
1890  if (Canonical.isNull())
1891    Canonical = getCanonicalType(Decl->getUnderlyingType());
1892  Decl->TypeForDecl = new(*this, TypeAlignment)
1893    TypedefType(Type::Typedef, Decl, Canonical);
1894  Types.push_back(Decl->TypeForDecl);
1895  return QualType(Decl->TypeForDecl, 0);
1896}
1897
1898QualType ASTContext::getRecordType(const RecordDecl *Decl) {
1899  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1900
1901  if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
1902    if (PrevDecl->TypeForDecl)
1903      return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1904
1905  Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Decl);
1906  Types.push_back(Decl->TypeForDecl);
1907  return QualType(Decl->TypeForDecl, 0);
1908}
1909
1910QualType ASTContext::getEnumType(const EnumDecl *Decl) {
1911  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1912
1913  if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
1914    if (PrevDecl->TypeForDecl)
1915      return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1916
1917  Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Decl);
1918  Types.push_back(Decl->TypeForDecl);
1919  return QualType(Decl->TypeForDecl, 0);
1920}
1921
1922/// \brief Retrieve a substitution-result type.
1923QualType
1924ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1925                                         QualType Replacement) {
1926  assert(Replacement.isCanonical()
1927         && "replacement types must always be canonical");
1928
1929  llvm::FoldingSetNodeID ID;
1930  SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1931  void *InsertPos = 0;
1932  SubstTemplateTypeParmType *SubstParm
1933    = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1934
1935  if (!SubstParm) {
1936    SubstParm = new (*this, TypeAlignment)
1937      SubstTemplateTypeParmType(Parm, Replacement);
1938    Types.push_back(SubstParm);
1939    SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1940  }
1941
1942  return QualType(SubstParm, 0);
1943}
1944
1945/// \brief Retrieve the template type parameter type for a template
1946/// parameter or parameter pack with the given depth, index, and (optionally)
1947/// name.
1948QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
1949                                             bool ParameterPack,
1950                                             IdentifierInfo *Name) {
1951  llvm::FoldingSetNodeID ID;
1952  TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
1953  void *InsertPos = 0;
1954  TemplateTypeParmType *TypeParm
1955    = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1956
1957  if (TypeParm)
1958    return QualType(TypeParm, 0);
1959
1960  if (Name) {
1961    QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1962    TypeParm = new (*this, TypeAlignment)
1963      TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
1964
1965    TemplateTypeParmType *TypeCheck
1966      = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1967    assert(!TypeCheck && "Template type parameter canonical type broken");
1968    (void)TypeCheck;
1969  } else
1970    TypeParm = new (*this, TypeAlignment)
1971      TemplateTypeParmType(Depth, Index, ParameterPack);
1972
1973  Types.push_back(TypeParm);
1974  TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1975
1976  return QualType(TypeParm, 0);
1977}
1978
1979TypeSourceInfo *
1980ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1981                                              SourceLocation NameLoc,
1982                                        const TemplateArgumentListInfo &Args,
1983                                              QualType CanonType) {
1984  QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1985
1986  TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1987  TemplateSpecializationTypeLoc TL
1988    = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1989  TL.setTemplateNameLoc(NameLoc);
1990  TL.setLAngleLoc(Args.getLAngleLoc());
1991  TL.setRAngleLoc(Args.getRAngleLoc());
1992  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1993    TL.setArgLocInfo(i, Args[i].getLocInfo());
1994  return DI;
1995}
1996
1997QualType
1998ASTContext::getTemplateSpecializationType(TemplateName Template,
1999                                          const TemplateArgumentListInfo &Args,
2000                                          QualType Canon) {
2001  unsigned NumArgs = Args.size();
2002
2003  llvm::SmallVector<TemplateArgument, 4> ArgVec;
2004  ArgVec.reserve(NumArgs);
2005  for (unsigned i = 0; i != NumArgs; ++i)
2006    ArgVec.push_back(Args[i].getArgument());
2007
2008  return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
2009                                       Canon);
2010}
2011
2012QualType
2013ASTContext::getTemplateSpecializationType(TemplateName Template,
2014                                          const TemplateArgument *Args,
2015                                          unsigned NumArgs,
2016                                          QualType Canon) {
2017  if (!Canon.isNull())
2018    Canon = getCanonicalType(Canon);
2019  else
2020    Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
2021
2022  // Allocate the (non-canonical) template specialization type, but don't
2023  // try to unique it: these types typically have location information that
2024  // we don't unique and don't want to lose.
2025  void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2026                        sizeof(TemplateArgument) * NumArgs),
2027                       TypeAlignment);
2028  TemplateSpecializationType *Spec
2029    = new (Mem) TemplateSpecializationType(Template,
2030                                           Args, NumArgs,
2031                                           Canon);
2032
2033  Types.push_back(Spec);
2034  return QualType(Spec, 0);
2035}
2036
2037QualType
2038ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2039                                                   const TemplateArgument *Args,
2040                                                   unsigned NumArgs) {
2041  // Build the canonical template specialization type.
2042  TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2043  llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2044  CanonArgs.reserve(NumArgs);
2045  for (unsigned I = 0; I != NumArgs; ++I)
2046    CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2047
2048  // Determine whether this canonical template specialization type already
2049  // exists.
2050  llvm::FoldingSetNodeID ID;
2051  TemplateSpecializationType::Profile(ID, CanonTemplate,
2052                                      CanonArgs.data(), NumArgs, *this);
2053
2054  void *InsertPos = 0;
2055  TemplateSpecializationType *Spec
2056    = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2057
2058  if (!Spec) {
2059    // Allocate a new canonical template specialization type.
2060    void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2061                          sizeof(TemplateArgument) * NumArgs),
2062                         TypeAlignment);
2063    Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2064                                                CanonArgs.data(), NumArgs,
2065                                                QualType());
2066    Types.push_back(Spec);
2067    TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2068  }
2069
2070  assert(Spec->isDependentType() &&
2071         "Non-dependent template-id type must have a canonical type");
2072  return QualType(Spec, 0);
2073}
2074
2075QualType
2076ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2077                              NestedNameSpecifier *NNS,
2078                              QualType NamedType) {
2079  llvm::FoldingSetNodeID ID;
2080  ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
2081
2082  void *InsertPos = 0;
2083  ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2084  if (T)
2085    return QualType(T, 0);
2086
2087  QualType Canon = NamedType;
2088  if (!Canon.isCanonical()) {
2089    Canon = getCanonicalType(NamedType);
2090    ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2091    assert(!CheckT && "Elaborated canonical type broken");
2092    (void)CheckT;
2093  }
2094
2095  T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
2096  Types.push_back(T);
2097  ElaboratedTypes.InsertNode(T, InsertPos);
2098  return QualType(T, 0);
2099}
2100
2101QualType
2102ASTContext::getParenType(QualType InnerType) {
2103  llvm::FoldingSetNodeID ID;
2104  ParenType::Profile(ID, InnerType);
2105
2106  void *InsertPos = 0;
2107  ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2108  if (T)
2109    return QualType(T, 0);
2110
2111  QualType Canon = InnerType;
2112  if (!Canon.isCanonical()) {
2113    Canon = getCanonicalType(InnerType);
2114    ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2115    assert(!CheckT && "Paren canonical type broken");
2116    (void)CheckT;
2117  }
2118
2119  T = new (*this) ParenType(InnerType, Canon);
2120  Types.push_back(T);
2121  ParenTypes.InsertNode(T, InsertPos);
2122  return QualType(T, 0);
2123}
2124
2125QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2126                                          NestedNameSpecifier *NNS,
2127                                          const IdentifierInfo *Name,
2128                                          QualType Canon) {
2129  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2130
2131  if (Canon.isNull()) {
2132    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2133    ElaboratedTypeKeyword CanonKeyword = Keyword;
2134    if (Keyword == ETK_None)
2135      CanonKeyword = ETK_Typename;
2136
2137    if (CanonNNS != NNS || CanonKeyword != Keyword)
2138      Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
2139  }
2140
2141  llvm::FoldingSetNodeID ID;
2142  DependentNameType::Profile(ID, Keyword, NNS, Name);
2143
2144  void *InsertPos = 0;
2145  DependentNameType *T
2146    = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2147  if (T)
2148    return QualType(T, 0);
2149
2150  T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
2151  Types.push_back(T);
2152  DependentNameTypes.InsertNode(T, InsertPos);
2153  return QualType(T, 0);
2154}
2155
2156QualType
2157ASTContext::getDependentTemplateSpecializationType(
2158                                 ElaboratedTypeKeyword Keyword,
2159                                 NestedNameSpecifier *NNS,
2160                                 const IdentifierInfo *Name,
2161                                 const TemplateArgumentListInfo &Args) {
2162  // TODO: avoid this copy
2163  llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2164  for (unsigned I = 0, E = Args.size(); I != E; ++I)
2165    ArgCopy.push_back(Args[I].getArgument());
2166  return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2167                                                ArgCopy.size(),
2168                                                ArgCopy.data());
2169}
2170
2171QualType
2172ASTContext::getDependentTemplateSpecializationType(
2173                                 ElaboratedTypeKeyword Keyword,
2174                                 NestedNameSpecifier *NNS,
2175                                 const IdentifierInfo *Name,
2176                                 unsigned NumArgs,
2177                                 const TemplateArgument *Args) {
2178  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2179
2180  llvm::FoldingSetNodeID ID;
2181  DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2182                                               Name, NumArgs, Args);
2183
2184  void *InsertPos = 0;
2185  DependentTemplateSpecializationType *T
2186    = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2187  if (T)
2188    return QualType(T, 0);
2189
2190  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2191
2192  ElaboratedTypeKeyword CanonKeyword = Keyword;
2193  if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2194
2195  bool AnyNonCanonArgs = false;
2196  llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2197  for (unsigned I = 0; I != NumArgs; ++I) {
2198    CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2199    if (!CanonArgs[I].structurallyEquals(Args[I]))
2200      AnyNonCanonArgs = true;
2201  }
2202
2203  QualType Canon;
2204  if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2205    Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2206                                                   Name, NumArgs,
2207                                                   CanonArgs.data());
2208
2209    // Find the insert position again.
2210    DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2211  }
2212
2213  void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2214                        sizeof(TemplateArgument) * NumArgs),
2215                       TypeAlignment);
2216  T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
2217                                                    Name, NumArgs, Args, Canon);
2218  Types.push_back(T);
2219  DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
2220  return QualType(T, 0);
2221}
2222
2223/// CmpProtocolNames - Comparison predicate for sorting protocols
2224/// alphabetically.
2225static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2226                            const ObjCProtocolDecl *RHS) {
2227  return LHS->getDeclName() < RHS->getDeclName();
2228}
2229
2230static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
2231                                unsigned NumProtocols) {
2232  if (NumProtocols == 0) return true;
2233
2234  for (unsigned i = 1; i != NumProtocols; ++i)
2235    if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2236      return false;
2237  return true;
2238}
2239
2240static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
2241                                   unsigned &NumProtocols) {
2242  ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
2243
2244  // Sort protocols, keyed by name.
2245  std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2246
2247  // Remove duplicates.
2248  ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2249  NumProtocols = ProtocolsEnd-Protocols;
2250}
2251
2252QualType ASTContext::getObjCObjectType(QualType BaseType,
2253                                       ObjCProtocolDecl * const *Protocols,
2254                                       unsigned NumProtocols) {
2255  // If the base type is an interface and there aren't any protocols
2256  // to add, then the interface type will do just fine.
2257  if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2258    return BaseType;
2259
2260  // Look in the folding set for an existing type.
2261  llvm::FoldingSetNodeID ID;
2262  ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
2263  void *InsertPos = 0;
2264  if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2265    return QualType(QT, 0);
2266
2267  // Build the canonical type, which has the canonical base type and
2268  // a sorted-and-uniqued list of protocols.
2269  QualType Canonical;
2270  bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2271  if (!ProtocolsSorted || !BaseType.isCanonical()) {
2272    if (!ProtocolsSorted) {
2273      llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2274                                                     Protocols + NumProtocols);
2275      unsigned UniqueCount = NumProtocols;
2276
2277      SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2278      Canonical = getObjCObjectType(getCanonicalType(BaseType),
2279                                    &Sorted[0], UniqueCount);
2280    } else {
2281      Canonical = getObjCObjectType(getCanonicalType(BaseType),
2282                                    Protocols, NumProtocols);
2283    }
2284
2285    // Regenerate InsertPos.
2286    ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2287  }
2288
2289  unsigned Size = sizeof(ObjCObjectTypeImpl);
2290  Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2291  void *Mem = Allocate(Size, TypeAlignment);
2292  ObjCObjectTypeImpl *T =
2293    new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2294
2295  Types.push_back(T);
2296  ObjCObjectTypes.InsertNode(T, InsertPos);
2297  return QualType(T, 0);
2298}
2299
2300/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2301/// the given object type.
2302QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2303  llvm::FoldingSetNodeID ID;
2304  ObjCObjectPointerType::Profile(ID, ObjectT);
2305
2306  void *InsertPos = 0;
2307  if (ObjCObjectPointerType *QT =
2308              ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2309    return QualType(QT, 0);
2310
2311  // Find the canonical object type.
2312  QualType Canonical;
2313  if (!ObjectT.isCanonical()) {
2314    Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2315
2316    // Regenerate InsertPos.
2317    ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2318  }
2319
2320  // No match.
2321  void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2322  ObjCObjectPointerType *QType =
2323    new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
2324
2325  Types.push_back(QType);
2326  ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2327  return QualType(QType, 0);
2328}
2329
2330/// getObjCInterfaceType - Return the unique reference to the type for the
2331/// specified ObjC interface decl. The list of protocols is optional.
2332QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2333  if (Decl->TypeForDecl)
2334    return QualType(Decl->TypeForDecl, 0);
2335
2336  // FIXME: redeclarations?
2337  void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2338  ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2339  Decl->TypeForDecl = T;
2340  Types.push_back(T);
2341  return QualType(T, 0);
2342}
2343
2344/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2345/// TypeOfExprType AST's (since expression's are never shared). For example,
2346/// multiple declarations that refer to "typeof(x)" all contain different
2347/// DeclRefExpr's. This doesn't effect the type checker, since it operates
2348/// on canonical type's (which are always unique).
2349QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
2350  TypeOfExprType *toe;
2351  if (tofExpr->isTypeDependent()) {
2352    llvm::FoldingSetNodeID ID;
2353    DependentTypeOfExprType::Profile(ID, *this, tofExpr);
2354
2355    void *InsertPos = 0;
2356    DependentTypeOfExprType *Canon
2357      = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2358    if (Canon) {
2359      // We already have a "canonical" version of an identical, dependent
2360      // typeof(expr) type. Use that as our canonical type.
2361      toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
2362                                          QualType((TypeOfExprType*)Canon, 0));
2363    }
2364    else {
2365      // Build a new, canonical typeof(expr) type.
2366      Canon
2367        = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
2368      DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2369      toe = Canon;
2370    }
2371  } else {
2372    QualType Canonical = getCanonicalType(tofExpr->getType());
2373    toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
2374  }
2375  Types.push_back(toe);
2376  return QualType(toe, 0);
2377}
2378
2379/// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
2380/// TypeOfType AST's. The only motivation to unique these nodes would be
2381/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
2382/// an issue. This doesn't effect the type checker, since it operates
2383/// on canonical type's (which are always unique).
2384QualType ASTContext::getTypeOfType(QualType tofType) {
2385  QualType Canonical = getCanonicalType(tofType);
2386  TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
2387  Types.push_back(tot);
2388  return QualType(tot, 0);
2389}
2390
2391/// getDecltypeForExpr - Given an expr, will return the decltype for that
2392/// expression, according to the rules in C++0x [dcl.type.simple]p4
2393static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
2394  if (e->isTypeDependent())
2395    return Context.DependentTy;
2396
2397  // If e is an id expression or a class member access, decltype(e) is defined
2398  // as the type of the entity named by e.
2399  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2400    if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2401      return VD->getType();
2402  }
2403  if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2404    if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2405      return FD->getType();
2406  }
2407  // If e is a function call or an invocation of an overloaded operator,
2408  // (parentheses around e are ignored), decltype(e) is defined as the
2409  // return type of that function.
2410  if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2411    return CE->getCallReturnType();
2412
2413  QualType T = e->getType();
2414
2415  // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
2416  // defined as T&, otherwise decltype(e) is defined as T.
2417  if (e->isLValue())
2418    T = Context.getLValueReferenceType(T);
2419
2420  return T;
2421}
2422
2423/// getDecltypeType -  Unlike many "get<Type>" functions, we don't unique
2424/// DecltypeType AST's. The only motivation to unique these nodes would be
2425/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
2426/// an issue. This doesn't effect the type checker, since it operates
2427/// on canonical type's (which are always unique).
2428QualType ASTContext::getDecltypeType(Expr *e) {
2429  DecltypeType *dt;
2430  if (e->isTypeDependent()) {
2431    llvm::FoldingSetNodeID ID;
2432    DependentDecltypeType::Profile(ID, *this, e);
2433
2434    void *InsertPos = 0;
2435    DependentDecltypeType *Canon
2436      = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2437    if (Canon) {
2438      // We already have a "canonical" version of an equivalent, dependent
2439      // decltype type. Use that as our canonical type.
2440      dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
2441                                       QualType((DecltypeType*)Canon, 0));
2442    }
2443    else {
2444      // Build a new, canonical typeof(expr) type.
2445      Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
2446      DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2447      dt = Canon;
2448    }
2449  } else {
2450    QualType T = getDecltypeForExpr(e, *this);
2451    dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
2452  }
2453  Types.push_back(dt);
2454  return QualType(dt, 0);
2455}
2456
2457/// getTagDeclType - Return the unique reference to the type for the
2458/// specified TagDecl (struct/union/class/enum) decl.
2459QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
2460  assert (Decl);
2461  // FIXME: What is the design on getTagDeclType when it requires casting
2462  // away const?  mutable?
2463  return getTypeDeclType(const_cast<TagDecl*>(Decl));
2464}
2465
2466/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2467/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2468/// needs to agree with the definition in <stddef.h>.
2469CanQualType ASTContext::getSizeType() const {
2470  return getFromTargetType(Target.getSizeType());
2471}
2472
2473/// getSignedWCharType - Return the type of "signed wchar_t".
2474/// Used when in C++, as a GCC extension.
2475QualType ASTContext::getSignedWCharType() const {
2476  // FIXME: derive from "Target" ?
2477  return WCharTy;
2478}
2479
2480/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2481/// Used when in C++, as a GCC extension.
2482QualType ASTContext::getUnsignedWCharType() const {
2483  // FIXME: derive from "Target" ?
2484  return UnsignedIntTy;
2485}
2486
2487/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2488/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2489QualType ASTContext::getPointerDiffType() const {
2490  return getFromTargetType(Target.getPtrDiffType(0));
2491}
2492
2493//===----------------------------------------------------------------------===//
2494//                              Type Operators
2495//===----------------------------------------------------------------------===//
2496
2497CanQualType ASTContext::getCanonicalParamType(QualType T) {
2498  // Push qualifiers into arrays, and then discard any remaining
2499  // qualifiers.
2500  T = getCanonicalType(T);
2501  T = getVariableArrayDecayedType(T);
2502  const Type *Ty = T.getTypePtr();
2503  QualType Result;
2504  if (isa<ArrayType>(Ty)) {
2505    Result = getArrayDecayedType(QualType(Ty,0));
2506  } else if (isa<FunctionType>(Ty)) {
2507    Result = getPointerType(QualType(Ty, 0));
2508  } else {
2509    Result = QualType(Ty, 0);
2510  }
2511
2512  return CanQualType::CreateUnsafe(Result);
2513}
2514
2515/// getCanonicalType - Return the canonical (structural) type corresponding to
2516/// the specified potentially non-canonical type.  The non-canonical version
2517/// of a type may have many "decorated" versions of types.  Decorators can
2518/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2519/// to be free of any of these, allowing two canonical types to be compared
2520/// for exact equality with a simple pointer comparison.
2521CanQualType ASTContext::getCanonicalType(QualType T) {
2522  QualifierCollector Quals;
2523  const Type *Ptr = Quals.strip(T);
2524  QualType CanType = Ptr->getCanonicalTypeInternal();
2525
2526  // The canonical internal type will be the canonical type *except*
2527  // that we push type qualifiers down through array types.
2528
2529  // If there are no new qualifiers to push down, stop here.
2530  if (!Quals.hasQualifiers())
2531    return CanQualType::CreateUnsafe(CanType);
2532
2533  // If the type qualifiers are on an array type, get the canonical
2534  // type of the array with the qualifiers applied to the element
2535  // type.
2536  ArrayType *AT = dyn_cast<ArrayType>(CanType);
2537  if (!AT)
2538    return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
2539
2540  // Get the canonical version of the element with the extra qualifiers on it.
2541  // This can recursively sink qualifiers through multiple levels of arrays.
2542  QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
2543  NewEltTy = getCanonicalType(NewEltTy);
2544
2545  if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2546    return CanQualType::CreateUnsafe(
2547             getConstantArrayType(NewEltTy, CAT->getSize(),
2548                                  CAT->getSizeModifier(),
2549                                  CAT->getIndexTypeCVRQualifiers()));
2550  if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
2551    return CanQualType::CreateUnsafe(
2552             getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
2553                                    IAT->getIndexTypeCVRQualifiers()));
2554
2555  if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
2556    return CanQualType::CreateUnsafe(
2557             getDependentSizedArrayType(NewEltTy,
2558                                        DSAT->getSizeExpr(),
2559                                        DSAT->getSizeModifier(),
2560                                        DSAT->getIndexTypeCVRQualifiers(),
2561                        DSAT->getBracketsRange())->getCanonicalTypeInternal());
2562
2563  VariableArrayType *VAT = cast<VariableArrayType>(AT);
2564  return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
2565                                                        VAT->getSizeExpr(),
2566                                                        VAT->getSizeModifier(),
2567                                              VAT->getIndexTypeCVRQualifiers(),
2568                                                     VAT->getBracketsRange()));
2569}
2570
2571QualType ASTContext::getUnqualifiedArrayType(QualType T,
2572                                             Qualifiers &Quals) {
2573  Quals = T.getQualifiers();
2574  const ArrayType *AT = getAsArrayType(T);
2575  if (!AT) {
2576    return T.getUnqualifiedType();
2577  }
2578
2579  QualType Elt = AT->getElementType();
2580  QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
2581  if (Elt == UnqualElt)
2582    return T;
2583
2584  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
2585    return getConstantArrayType(UnqualElt, CAT->getSize(),
2586                                CAT->getSizeModifier(), 0);
2587  }
2588
2589  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
2590    return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2591  }
2592
2593  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2594    return getVariableArrayType(UnqualElt,
2595                                VAT->getSizeExpr(),
2596                                VAT->getSizeModifier(),
2597                                VAT->getIndexTypeCVRQualifiers(),
2598                                VAT->getBracketsRange());
2599  }
2600
2601  const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
2602  return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr(),
2603                                    DSAT->getSizeModifier(), 0,
2604                                    SourceRange());
2605}
2606
2607/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types  that
2608/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2609/// they point to and return true. If T1 and T2 aren't pointer types
2610/// or pointer-to-member types, or if they are not similar at this
2611/// level, returns false and leaves T1 and T2 unchanged. Top-level
2612/// qualifiers on T1 and T2 are ignored. This function will typically
2613/// be called in a loop that successively "unwraps" pointer and
2614/// pointer-to-member types to compare them at each level.
2615bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2616  const PointerType *T1PtrType = T1->getAs<PointerType>(),
2617                    *T2PtrType = T2->getAs<PointerType>();
2618  if (T1PtrType && T2PtrType) {
2619    T1 = T1PtrType->getPointeeType();
2620    T2 = T2PtrType->getPointeeType();
2621    return true;
2622  }
2623
2624  const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2625                          *T2MPType = T2->getAs<MemberPointerType>();
2626  if (T1MPType && T2MPType &&
2627      hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2628                             QualType(T2MPType->getClass(), 0))) {
2629    T1 = T1MPType->getPointeeType();
2630    T2 = T2MPType->getPointeeType();
2631    return true;
2632  }
2633
2634  if (getLangOptions().ObjC1) {
2635    const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2636                                *T2OPType = T2->getAs<ObjCObjectPointerType>();
2637    if (T1OPType && T2OPType) {
2638      T1 = T1OPType->getPointeeType();
2639      T2 = T2OPType->getPointeeType();
2640      return true;
2641    }
2642  }
2643
2644  // FIXME: Block pointers, too?
2645
2646  return false;
2647}
2648
2649DeclarationNameInfo ASTContext::getNameForTemplate(TemplateName Name,
2650                                                   SourceLocation NameLoc) {
2651  if (TemplateDecl *TD = Name.getAsTemplateDecl())
2652    // DNInfo work in progress: CHECKME: what about DNLoc?
2653    return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2654
2655  if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2656    DeclarationName DName;
2657    if (DTN->isIdentifier()) {
2658      DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2659      return DeclarationNameInfo(DName, NameLoc);
2660    } else {
2661      DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2662      // DNInfo work in progress: FIXME: source locations?
2663      DeclarationNameLoc DNLoc;
2664      DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2665      DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2666      return DeclarationNameInfo(DName, NameLoc, DNLoc);
2667    }
2668  }
2669
2670  OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2671  assert(Storage);
2672  // DNInfo work in progress: CHECKME: what about DNLoc?
2673  return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
2674}
2675
2676TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2677  if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2678    if (TemplateTemplateParmDecl *TTP
2679                              = dyn_cast<TemplateTemplateParmDecl>(Template))
2680      Template = getCanonicalTemplateTemplateParmDecl(TTP);
2681
2682    // The canonical template name is the canonical template declaration.
2683    return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
2684  }
2685
2686  assert(!Name.getAsOverloadedTemplate());
2687
2688  DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2689  assert(DTN && "Non-dependent template names must refer to template decls.");
2690  return DTN->CanonicalTemplateName;
2691}
2692
2693bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2694  X = getCanonicalTemplateName(X);
2695  Y = getCanonicalTemplateName(Y);
2696  return X.getAsVoidPointer() == Y.getAsVoidPointer();
2697}
2698
2699TemplateArgument
2700ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2701  switch (Arg.getKind()) {
2702    case TemplateArgument::Null:
2703      return Arg;
2704
2705    case TemplateArgument::Expression:
2706      return Arg;
2707
2708    case TemplateArgument::Declaration:
2709      return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
2710
2711    case TemplateArgument::Template:
2712      return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2713
2714    case TemplateArgument::Integral:
2715      return TemplateArgument(*Arg.getAsIntegral(),
2716                              getCanonicalType(Arg.getIntegralType()));
2717
2718    case TemplateArgument::Type:
2719      return TemplateArgument(getCanonicalType(Arg.getAsType()));
2720
2721    case TemplateArgument::Pack: {
2722      TemplateArgument *CanonArgs
2723        = new (*this) TemplateArgument[Arg.pack_size()];
2724      unsigned Idx = 0;
2725      for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
2726                                        AEnd = Arg.pack_end();
2727           A != AEnd; (void)++A, ++Idx)
2728        CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
2729
2730      return TemplateArgument(CanonArgs, Arg.pack_size());
2731    }
2732  }
2733
2734  // Silence GCC warning
2735  assert(false && "Unhandled template argument kind");
2736  return TemplateArgument();
2737}
2738
2739NestedNameSpecifier *
2740ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
2741  if (!NNS)
2742    return 0;
2743
2744  switch (NNS->getKind()) {
2745  case NestedNameSpecifier::Identifier:
2746    // Canonicalize the prefix but keep the identifier the same.
2747    return NestedNameSpecifier::Create(*this,
2748                         getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2749                                       NNS->getAsIdentifier());
2750
2751  case NestedNameSpecifier::Namespace:
2752    // A namespace is canonical; build a nested-name-specifier with
2753    // this namespace and no prefix.
2754    return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2755
2756  case NestedNameSpecifier::TypeSpec:
2757  case NestedNameSpecifier::TypeSpecWithTemplate: {
2758    QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
2759
2760    // If we have some kind of dependent-named type (e.g., "typename T::type"),
2761    // break it apart into its prefix and identifier, then reconsititute those
2762    // as the canonical nested-name-specifier. This is required to canonicalize
2763    // a dependent nested-name-specifier involving typedefs of dependent-name
2764    // types, e.g.,
2765    //   typedef typename T::type T1;
2766    //   typedef typename T1::type T2;
2767    if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
2768      NestedNameSpecifier *Prefix
2769        = getCanonicalNestedNameSpecifier(DNT->getQualifier());
2770      return NestedNameSpecifier::Create(*this, Prefix,
2771                           const_cast<IdentifierInfo *>(DNT->getIdentifier()));
2772    }
2773
2774    // Do the same thing as above, but with dependent-named specializations.
2775    if (const DependentTemplateSpecializationType *DTST
2776          = T->getAs<DependentTemplateSpecializationType>()) {
2777      NestedNameSpecifier *Prefix
2778        = getCanonicalNestedNameSpecifier(DTST->getQualifier());
2779      TemplateName Name
2780        = getDependentTemplateName(Prefix, DTST->getIdentifier());
2781      T = getTemplateSpecializationType(Name,
2782                                        DTST->getArgs(), DTST->getNumArgs());
2783      T = getCanonicalType(T);
2784    }
2785
2786    return NestedNameSpecifier::Create(*this, 0, false, T.getTypePtr());
2787  }
2788
2789  case NestedNameSpecifier::Global:
2790    // The global specifier is canonical and unique.
2791    return NNS;
2792  }
2793
2794  // Required to silence a GCC warning
2795  return 0;
2796}
2797
2798
2799const ArrayType *ASTContext::getAsArrayType(QualType T) {
2800  // Handle the non-qualified case efficiently.
2801  if (!T.hasLocalQualifiers()) {
2802    // Handle the common positive case fast.
2803    if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2804      return AT;
2805  }
2806
2807  // Handle the common negative case fast.
2808  QualType CType = T->getCanonicalTypeInternal();
2809  if (!isa<ArrayType>(CType))
2810    return 0;
2811
2812  // Apply any qualifiers from the array type to the element type.  This
2813  // implements C99 6.7.3p8: "If the specification of an array type includes
2814  // any type qualifiers, the element type is so qualified, not the array type."
2815
2816  // If we get here, we either have type qualifiers on the type, or we have
2817  // sugar such as a typedef in the way.  If we have type qualifiers on the type
2818  // we must propagate them down into the element type.
2819
2820  QualifierCollector Qs;
2821  const Type *Ty = Qs.strip(T.getDesugaredType(*this));
2822
2823  // If we have a simple case, just return now.
2824  const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2825  if (ATy == 0 || Qs.empty())
2826    return ATy;
2827
2828  // Otherwise, we have an array and we have qualifiers on it.  Push the
2829  // qualifiers into the array element type and return a new array type.
2830  // Get the canonical version of the element with the extra qualifiers on it.
2831  // This can recursively sink qualifiers through multiple levels of arrays.
2832  QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
2833
2834  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2835    return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2836                                                CAT->getSizeModifier(),
2837                                           CAT->getIndexTypeCVRQualifiers()));
2838  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2839    return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2840                                                  IAT->getSizeModifier(),
2841                                           IAT->getIndexTypeCVRQualifiers()));
2842
2843  if (const DependentSizedArrayType *DSAT
2844        = dyn_cast<DependentSizedArrayType>(ATy))
2845    return cast<ArrayType>(
2846                     getDependentSizedArrayType(NewEltTy,
2847                                                DSAT->getSizeExpr(),
2848                                                DSAT->getSizeModifier(),
2849                                              DSAT->getIndexTypeCVRQualifiers(),
2850                                                DSAT->getBracketsRange()));
2851
2852  const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
2853  return cast<ArrayType>(getVariableArrayType(NewEltTy,
2854                                              VAT->getSizeExpr(),
2855                                              VAT->getSizeModifier(),
2856                                              VAT->getIndexTypeCVRQualifiers(),
2857                                              VAT->getBracketsRange()));
2858}
2859
2860/// getArrayDecayedType - Return the properly qualified result of decaying the
2861/// specified array type to a pointer.  This operation is non-trivial when
2862/// handling typedefs etc.  The canonical type of "T" must be an array type,
2863/// this returns a pointer to a properly qualified element of the array.
2864///
2865/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2866QualType ASTContext::getArrayDecayedType(QualType Ty) {
2867  // Get the element type with 'getAsArrayType' so that we don't lose any
2868  // typedefs in the element type of the array.  This also handles propagation
2869  // of type qualifiers from the array type into the element type if present
2870  // (C99 6.7.3p8).
2871  const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2872  assert(PrettyArrayType && "Not an array type!");
2873
2874  QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
2875
2876  // int x[restrict 4] ->  int *restrict
2877  return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
2878}
2879
2880QualType ASTContext::getBaseElementType(QualType QT) {
2881  QualifierCollector Qs;
2882  while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2883    QT = AT->getElementType();
2884  return Qs.apply(*this, QT);
2885}
2886
2887QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2888  QualType ElemTy = AT->getElementType();
2889
2890  if (const ArrayType *AT = getAsArrayType(ElemTy))
2891    return getBaseElementType(AT);
2892
2893  return ElemTy;
2894}
2895
2896/// getConstantArrayElementCount - Returns number of constant array elements.
2897uint64_t
2898ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
2899  uint64_t ElementCount = 1;
2900  do {
2901    ElementCount *= CA->getSize().getZExtValue();
2902    CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2903  } while (CA);
2904  return ElementCount;
2905}
2906
2907/// getFloatingRank - Return a relative rank for floating point types.
2908/// This routine will assert if passed a built-in type that isn't a float.
2909static FloatingRank getFloatingRank(QualType T) {
2910  if (const ComplexType *CT = T->getAs<ComplexType>())
2911    return getFloatingRank(CT->getElementType());
2912
2913  assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2914  switch (T->getAs<BuiltinType>()->getKind()) {
2915  default: assert(0 && "getFloatingRank(): not a floating type");
2916  case BuiltinType::Float:      return FloatRank;
2917  case BuiltinType::Double:     return DoubleRank;
2918  case BuiltinType::LongDouble: return LongDoubleRank;
2919  }
2920}
2921
2922/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2923/// point or a complex type (based on typeDomain/typeSize).
2924/// 'typeDomain' is a real floating point or complex type.
2925/// 'typeSize' is a real floating point or complex type.
2926QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2927                                                       QualType Domain) const {
2928  FloatingRank EltRank = getFloatingRank(Size);
2929  if (Domain->isComplexType()) {
2930    switch (EltRank) {
2931    default: assert(0 && "getFloatingRank(): illegal value for rank");
2932    case FloatRank:      return FloatComplexTy;
2933    case DoubleRank:     return DoubleComplexTy;
2934    case LongDoubleRank: return LongDoubleComplexTy;
2935    }
2936  }
2937
2938  assert(Domain->isRealFloatingType() && "Unknown domain!");
2939  switch (EltRank) {
2940  default: assert(0 && "getFloatingRank(): illegal value for rank");
2941  case FloatRank:      return FloatTy;
2942  case DoubleRank:     return DoubleTy;
2943  case LongDoubleRank: return LongDoubleTy;
2944  }
2945}
2946
2947/// getFloatingTypeOrder - Compare the rank of the two specified floating
2948/// point types, ignoring the domain of the type (i.e. 'double' ==
2949/// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
2950/// LHS < RHS, return -1.
2951int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2952  FloatingRank LHSR = getFloatingRank(LHS);
2953  FloatingRank RHSR = getFloatingRank(RHS);
2954
2955  if (LHSR == RHSR)
2956    return 0;
2957  if (LHSR > RHSR)
2958    return 1;
2959  return -1;
2960}
2961
2962/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2963/// routine will assert if passed a built-in type that isn't an integer or enum,
2964/// or if it is not canonicalized.
2965unsigned ASTContext::getIntegerRank(Type *T) {
2966  assert(T->isCanonicalUnqualified() && "T should be canonicalized");
2967  if (EnumType* ET = dyn_cast<EnumType>(T))
2968    T = ET->getDecl()->getPromotionType().getTypePtr();
2969
2970  if (T->isSpecificBuiltinType(BuiltinType::WChar))
2971    T = getFromTargetType(Target.getWCharType()).getTypePtr();
2972
2973  if (T->isSpecificBuiltinType(BuiltinType::Char16))
2974    T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2975
2976  if (T->isSpecificBuiltinType(BuiltinType::Char32))
2977    T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2978
2979  switch (cast<BuiltinType>(T)->getKind()) {
2980  default: assert(0 && "getIntegerRank(): not a built-in integer");
2981  case BuiltinType::Bool:
2982    return 1 + (getIntWidth(BoolTy) << 3);
2983  case BuiltinType::Char_S:
2984  case BuiltinType::Char_U:
2985  case BuiltinType::SChar:
2986  case BuiltinType::UChar:
2987    return 2 + (getIntWidth(CharTy) << 3);
2988  case BuiltinType::Short:
2989  case BuiltinType::UShort:
2990    return 3 + (getIntWidth(ShortTy) << 3);
2991  case BuiltinType::Int:
2992  case BuiltinType::UInt:
2993    return 4 + (getIntWidth(IntTy) << 3);
2994  case BuiltinType::Long:
2995  case BuiltinType::ULong:
2996    return 5 + (getIntWidth(LongTy) << 3);
2997  case BuiltinType::LongLong:
2998  case BuiltinType::ULongLong:
2999    return 6 + (getIntWidth(LongLongTy) << 3);
3000  case BuiltinType::Int128:
3001  case BuiltinType::UInt128:
3002    return 7 + (getIntWidth(Int128Ty) << 3);
3003  }
3004}
3005
3006/// \brief Whether this is a promotable bitfield reference according
3007/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3008///
3009/// \returns the type this bit-field will promote to, or NULL if no
3010/// promotion occurs.
3011QualType ASTContext::isPromotableBitField(Expr *E) {
3012  if (E->isTypeDependent() || E->isValueDependent())
3013    return QualType();
3014
3015  FieldDecl *Field = E->getBitField();
3016  if (!Field)
3017    return QualType();
3018
3019  QualType FT = Field->getType();
3020
3021  llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3022  uint64_t BitWidth = BitWidthAP.getZExtValue();
3023  uint64_t IntSize = getTypeSize(IntTy);
3024  // GCC extension compatibility: if the bit-field size is less than or equal
3025  // to the size of int, it gets promoted no matter what its type is.
3026  // For instance, unsigned long bf : 4 gets promoted to signed int.
3027  if (BitWidth < IntSize)
3028    return IntTy;
3029
3030  if (BitWidth == IntSize)
3031    return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3032
3033  // Types bigger than int are not subject to promotions, and therefore act
3034  // like the base type.
3035  // FIXME: This doesn't quite match what gcc does, but what gcc does here
3036  // is ridiculous.
3037  return QualType();
3038}
3039
3040/// getPromotedIntegerType - Returns the type that Promotable will
3041/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3042/// integer type.
3043QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
3044  assert(!Promotable.isNull());
3045  assert(Promotable->isPromotableIntegerType());
3046  if (const EnumType *ET = Promotable->getAs<EnumType>())
3047    return ET->getDecl()->getPromotionType();
3048  if (Promotable->isSignedIntegerType())
3049    return IntTy;
3050  uint64_t PromotableSize = getTypeSize(Promotable);
3051  uint64_t IntSize = getTypeSize(IntTy);
3052  assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3053  return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3054}
3055
3056/// getIntegerTypeOrder - Returns the highest ranked integer type:
3057/// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
3058/// LHS < RHS, return -1.
3059int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
3060  Type *LHSC = getCanonicalType(LHS).getTypePtr();
3061  Type *RHSC = getCanonicalType(RHS).getTypePtr();
3062  if (LHSC == RHSC) return 0;
3063
3064  bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3065  bool RHSUnsigned = RHSC->isUnsignedIntegerType();
3066
3067  unsigned LHSRank = getIntegerRank(LHSC);
3068  unsigned RHSRank = getIntegerRank(RHSC);
3069
3070  if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
3071    if (LHSRank == RHSRank) return 0;
3072    return LHSRank > RHSRank ? 1 : -1;
3073  }
3074
3075  // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3076  if (LHSUnsigned) {
3077    // If the unsigned [LHS] type is larger, return it.
3078    if (LHSRank >= RHSRank)
3079      return 1;
3080
3081    // If the signed type can represent all values of the unsigned type, it
3082    // wins.  Because we are dealing with 2's complement and types that are
3083    // powers of two larger than each other, this is always safe.
3084    return -1;
3085  }
3086
3087  // If the unsigned [RHS] type is larger, return it.
3088  if (RHSRank >= LHSRank)
3089    return -1;
3090
3091  // If the signed type can represent all values of the unsigned type, it
3092  // wins.  Because we are dealing with 2's complement and types that are
3093  // powers of two larger than each other, this is always safe.
3094  return 1;
3095}
3096
3097static RecordDecl *
3098CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
3099                 SourceLocation L, IdentifierInfo *Id) {
3100  if (Ctx.getLangOptions().CPlusPlus)
3101    return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
3102  else
3103    return RecordDecl::Create(Ctx, TK, DC, L, Id);
3104}
3105
3106// getCFConstantStringType - Return the type used for constant CFStrings.
3107QualType ASTContext::getCFConstantStringType() {
3108  if (!CFConstantStringTypeDecl) {
3109    CFConstantStringTypeDecl =
3110      CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
3111                       &Idents.get("NSConstantString"));
3112    CFConstantStringTypeDecl->startDefinition();
3113
3114    QualType FieldTypes[4];
3115
3116    // const int *isa;
3117    FieldTypes[0] = getPointerType(IntTy.withConst());
3118    // int flags;
3119    FieldTypes[1] = IntTy;
3120    // const char *str;
3121    FieldTypes[2] = getPointerType(CharTy.withConst());
3122    // long length;
3123    FieldTypes[3] = LongTy;
3124
3125    // Create fields
3126    for (unsigned i = 0; i < 4; ++i) {
3127      FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
3128                                           SourceLocation(), 0,
3129                                           FieldTypes[i], /*TInfo=*/0,
3130                                           /*BitWidth=*/0,
3131                                           /*Mutable=*/false);
3132      Field->setAccess(AS_public);
3133      CFConstantStringTypeDecl->addDecl(Field);
3134    }
3135
3136    CFConstantStringTypeDecl->completeDefinition();
3137  }
3138
3139  return getTagDeclType(CFConstantStringTypeDecl);
3140}
3141
3142void ASTContext::setCFConstantStringType(QualType T) {
3143  const RecordType *Rec = T->getAs<RecordType>();
3144  assert(Rec && "Invalid CFConstantStringType");
3145  CFConstantStringTypeDecl = Rec->getDecl();
3146}
3147
3148// getNSConstantStringType - Return the type used for constant NSStrings.
3149QualType ASTContext::getNSConstantStringType() {
3150  if (!NSConstantStringTypeDecl) {
3151    NSConstantStringTypeDecl =
3152    CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
3153                     &Idents.get("__builtin_NSString"));
3154    NSConstantStringTypeDecl->startDefinition();
3155
3156    QualType FieldTypes[3];
3157
3158    // const int *isa;
3159    FieldTypes[0] = getPointerType(IntTy.withConst());
3160    // const char *str;
3161    FieldTypes[1] = getPointerType(CharTy.withConst());
3162    // unsigned int length;
3163    FieldTypes[2] = UnsignedIntTy;
3164
3165    // Create fields
3166    for (unsigned i = 0; i < 3; ++i) {
3167      FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3168                                           SourceLocation(), 0,
3169                                           FieldTypes[i], /*TInfo=*/0,
3170                                           /*BitWidth=*/0,
3171                                           /*Mutable=*/false);
3172      Field->setAccess(AS_public);
3173      NSConstantStringTypeDecl->addDecl(Field);
3174    }
3175
3176    NSConstantStringTypeDecl->completeDefinition();
3177  }
3178
3179  return getTagDeclType(NSConstantStringTypeDecl);
3180}
3181
3182void ASTContext::setNSConstantStringType(QualType T) {
3183  const RecordType *Rec = T->getAs<RecordType>();
3184  assert(Rec && "Invalid NSConstantStringType");
3185  NSConstantStringTypeDecl = Rec->getDecl();
3186}
3187
3188QualType ASTContext::getObjCFastEnumerationStateType() {
3189  if (!ObjCFastEnumerationStateTypeDecl) {
3190    ObjCFastEnumerationStateTypeDecl =
3191      CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
3192                       &Idents.get("__objcFastEnumerationState"));
3193    ObjCFastEnumerationStateTypeDecl->startDefinition();
3194
3195    QualType FieldTypes[] = {
3196      UnsignedLongTy,
3197      getPointerType(ObjCIdTypedefType),
3198      getPointerType(UnsignedLongTy),
3199      getConstantArrayType(UnsignedLongTy,
3200                           llvm::APInt(32, 5), ArrayType::Normal, 0)
3201    };
3202
3203    for (size_t i = 0; i < 4; ++i) {
3204      FieldDecl *Field = FieldDecl::Create(*this,
3205                                           ObjCFastEnumerationStateTypeDecl,
3206                                           SourceLocation(), 0,
3207                                           FieldTypes[i], /*TInfo=*/0,
3208                                           /*BitWidth=*/0,
3209                                           /*Mutable=*/false);
3210      Field->setAccess(AS_public);
3211      ObjCFastEnumerationStateTypeDecl->addDecl(Field);
3212    }
3213
3214    ObjCFastEnumerationStateTypeDecl->completeDefinition();
3215  }
3216
3217  return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3218}
3219
3220QualType ASTContext::getBlockDescriptorType() {
3221  if (BlockDescriptorType)
3222    return getTagDeclType(BlockDescriptorType);
3223
3224  RecordDecl *T;
3225  // FIXME: Needs the FlagAppleBlock bit.
3226  T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
3227                       &Idents.get("__block_descriptor"));
3228  T->startDefinition();
3229
3230  QualType FieldTypes[] = {
3231    UnsignedLongTy,
3232    UnsignedLongTy,
3233  };
3234
3235  const char *FieldNames[] = {
3236    "reserved",
3237    "Size"
3238  };
3239
3240  for (size_t i = 0; i < 2; ++i) {
3241    FieldDecl *Field = FieldDecl::Create(*this,
3242                                         T,
3243                                         SourceLocation(),
3244                                         &Idents.get(FieldNames[i]),
3245                                         FieldTypes[i], /*TInfo=*/0,
3246                                         /*BitWidth=*/0,
3247                                         /*Mutable=*/false);
3248    Field->setAccess(AS_public);
3249    T->addDecl(Field);
3250  }
3251
3252  T->completeDefinition();
3253
3254  BlockDescriptorType = T;
3255
3256  return getTagDeclType(BlockDescriptorType);
3257}
3258
3259void ASTContext::setBlockDescriptorType(QualType T) {
3260  const RecordType *Rec = T->getAs<RecordType>();
3261  assert(Rec && "Invalid BlockDescriptorType");
3262  BlockDescriptorType = Rec->getDecl();
3263}
3264
3265QualType ASTContext::getBlockDescriptorExtendedType() {
3266  if (BlockDescriptorExtendedType)
3267    return getTagDeclType(BlockDescriptorExtendedType);
3268
3269  RecordDecl *T;
3270  // FIXME: Needs the FlagAppleBlock bit.
3271  T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
3272                       &Idents.get("__block_descriptor_withcopydispose"));
3273  T->startDefinition();
3274
3275  QualType FieldTypes[] = {
3276    UnsignedLongTy,
3277    UnsignedLongTy,
3278    getPointerType(VoidPtrTy),
3279    getPointerType(VoidPtrTy)
3280  };
3281
3282  const char *FieldNames[] = {
3283    "reserved",
3284    "Size",
3285    "CopyFuncPtr",
3286    "DestroyFuncPtr"
3287  };
3288
3289  for (size_t i = 0; i < 4; ++i) {
3290    FieldDecl *Field = FieldDecl::Create(*this,
3291                                         T,
3292                                         SourceLocation(),
3293                                         &Idents.get(FieldNames[i]),
3294                                         FieldTypes[i], /*TInfo=*/0,
3295                                         /*BitWidth=*/0,
3296                                         /*Mutable=*/false);
3297    Field->setAccess(AS_public);
3298    T->addDecl(Field);
3299  }
3300
3301  T->completeDefinition();
3302
3303  BlockDescriptorExtendedType = T;
3304
3305  return getTagDeclType(BlockDescriptorExtendedType);
3306}
3307
3308void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3309  const RecordType *Rec = T->getAs<RecordType>();
3310  assert(Rec && "Invalid BlockDescriptorType");
3311  BlockDescriptorExtendedType = Rec->getDecl();
3312}
3313
3314bool ASTContext::BlockRequiresCopying(QualType Ty) {
3315  if (Ty->isBlockPointerType())
3316    return true;
3317  if (isObjCNSObjectType(Ty))
3318    return true;
3319  if (Ty->isObjCObjectPointerType())
3320    return true;
3321  if (getLangOptions().CPlusPlus) {
3322    if (const RecordType *RT = Ty->getAs<RecordType>()) {
3323      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3324      return RD->hasConstCopyConstructor(*this);
3325
3326    }
3327  }
3328  return false;
3329}
3330
3331QualType ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) {
3332  //  type = struct __Block_byref_1_X {
3333  //    void *__isa;
3334  //    struct __Block_byref_1_X *__forwarding;
3335  //    unsigned int __flags;
3336  //    unsigned int __size;
3337  //    void *__copy_helper;            // as needed
3338  //    void *__destroy_help            // as needed
3339  //    int X;
3340  //  } *
3341
3342  bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3343
3344  // FIXME: Move up
3345  llvm::SmallString<36> Name;
3346  llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3347                                  ++UniqueBlockByRefTypeID << '_' << DeclName;
3348  RecordDecl *T;
3349  T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
3350                       &Idents.get(Name.str()));
3351  T->startDefinition();
3352  QualType Int32Ty = IntTy;
3353  assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3354  QualType FieldTypes[] = {
3355    getPointerType(VoidPtrTy),
3356    getPointerType(getTagDeclType(T)),
3357    Int32Ty,
3358    Int32Ty,
3359    getPointerType(VoidPtrTy),
3360    getPointerType(VoidPtrTy),
3361    Ty
3362  };
3363
3364  llvm::StringRef FieldNames[] = {
3365    "__isa",
3366    "__forwarding",
3367    "__flags",
3368    "__size",
3369    "__copy_helper",
3370    "__destroy_helper",
3371    DeclName,
3372  };
3373
3374  for (size_t i = 0; i < 7; ++i) {
3375    if (!HasCopyAndDispose && i >=4 && i <= 5)
3376      continue;
3377    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3378                                         &Idents.get(FieldNames[i]),
3379                                         FieldTypes[i], /*TInfo=*/0,
3380                                         /*BitWidth=*/0, /*Mutable=*/false);
3381    Field->setAccess(AS_public);
3382    T->addDecl(Field);
3383  }
3384
3385  T->completeDefinition();
3386
3387  return getPointerType(getTagDeclType(T));
3388}
3389
3390
3391QualType ASTContext::getBlockParmType(
3392  bool BlockHasCopyDispose,
3393  llvm::SmallVectorImpl<const Expr *> &Layout) {
3394
3395  // FIXME: Move up
3396  llvm::SmallString<36> Name;
3397  llvm::raw_svector_ostream(Name) << "__block_literal_"
3398                                  << ++UniqueBlockParmTypeID;
3399  RecordDecl *T;
3400  T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
3401                       &Idents.get(Name.str()));
3402  T->startDefinition();
3403  QualType FieldTypes[] = {
3404    getPointerType(VoidPtrTy),
3405    IntTy,
3406    IntTy,
3407    getPointerType(VoidPtrTy),
3408    (BlockHasCopyDispose ?
3409     getPointerType(getBlockDescriptorExtendedType()) :
3410     getPointerType(getBlockDescriptorType()))
3411  };
3412
3413  const char *FieldNames[] = {
3414    "__isa",
3415    "__flags",
3416    "__reserved",
3417    "__FuncPtr",
3418    "__descriptor"
3419  };
3420
3421  for (size_t i = 0; i < 5; ++i) {
3422    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3423                                         &Idents.get(FieldNames[i]),
3424                                         FieldTypes[i], /*TInfo=*/0,
3425                                         /*BitWidth=*/0, /*Mutable=*/false);
3426    Field->setAccess(AS_public);
3427    T->addDecl(Field);
3428  }
3429
3430  for (unsigned i = 0; i < Layout.size(); ++i) {
3431    const Expr *E = Layout[i];
3432
3433    QualType FieldType = E->getType();
3434    IdentifierInfo *FieldName = 0;
3435    if (isa<CXXThisExpr>(E)) {
3436      FieldName = &Idents.get("this");
3437    } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3438      const ValueDecl *D = BDRE->getDecl();
3439      FieldName = D->getIdentifier();
3440      if (BDRE->isByRef())
3441        FieldType = BuildByRefType(D->getName(), FieldType);
3442    } else {
3443      // Padding.
3444      assert(isa<ConstantArrayType>(FieldType) &&
3445             isa<DeclRefExpr>(E) &&
3446             !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3447             "doesn't match characteristics of padding decl");
3448    }
3449
3450    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3451                                         FieldName, FieldType, /*TInfo=*/0,
3452                                         /*BitWidth=*/0, /*Mutable=*/false);
3453    Field->setAccess(AS_public);
3454    T->addDecl(Field);
3455  }
3456
3457  T->completeDefinition();
3458
3459  return getPointerType(getTagDeclType(T));
3460}
3461
3462void ASTContext::setObjCFastEnumerationStateType(QualType T) {
3463  const RecordType *Rec = T->getAs<RecordType>();
3464  assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3465  ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3466}
3467
3468// This returns true if a type has been typedefed to BOOL:
3469// typedef <type> BOOL;
3470static bool isTypeTypedefedAsBOOL(QualType T) {
3471  if (const TypedefType *TT = dyn_cast<TypedefType>(T))
3472    if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3473      return II->isStr("BOOL");
3474
3475  return false;
3476}
3477
3478/// getObjCEncodingTypeSize returns size of type for objective-c encoding
3479/// purpose.
3480CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
3481  CharUnits sz = getTypeSizeInChars(type);
3482
3483  // Make all integer and enum types at least as large as an int
3484  if (sz.isPositive() && type->isIntegralOrEnumerationType())
3485    sz = std::max(sz, getTypeSizeInChars(IntTy));
3486  // Treat arrays as pointers, since that's how they're passed in.
3487  else if (type->isArrayType())
3488    sz = getTypeSizeInChars(VoidPtrTy);
3489  return sz;
3490}
3491
3492static inline
3493std::string charUnitsToString(const CharUnits &CU) {
3494  return llvm::itostr(CU.getQuantity());
3495}
3496
3497/// getObjCEncodingForBlockDecl - Return the encoded type for this block
3498/// declaration.
3499void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3500                                             std::string& S) {
3501  const BlockDecl *Decl = Expr->getBlockDecl();
3502  QualType BlockTy =
3503      Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3504  // Encode result type.
3505  getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
3506  // Compute size of all parameters.
3507  // Start with computing size of a pointer in number of bytes.
3508  // FIXME: There might(should) be a better way of doing this computation!
3509  SourceLocation Loc;
3510  CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3511  CharUnits ParmOffset = PtrSize;
3512  for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
3513       E = Decl->param_end(); PI != E; ++PI) {
3514    QualType PType = (*PI)->getType();
3515    CharUnits sz = getObjCEncodingTypeSize(PType);
3516    assert (sz.isPositive() && "BlockExpr - Incomplete param type");
3517    ParmOffset += sz;
3518  }
3519  // Size of the argument frame
3520  S += charUnitsToString(ParmOffset);
3521  // Block pointer and offset.
3522  S += "@?0";
3523  ParmOffset = PtrSize;
3524
3525  // Argument types.
3526  ParmOffset = PtrSize;
3527  for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3528       Decl->param_end(); PI != E; ++PI) {
3529    ParmVarDecl *PVDecl = *PI;
3530    QualType PType = PVDecl->getOriginalType();
3531    if (const ArrayType *AT =
3532          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3533      // Use array's original type only if it has known number of
3534      // elements.
3535      if (!isa<ConstantArrayType>(AT))
3536        PType = PVDecl->getType();
3537    } else if (PType->isFunctionType())
3538      PType = PVDecl->getType();
3539    getObjCEncodingForType(PType, S);
3540    S += charUnitsToString(ParmOffset);
3541    ParmOffset += getObjCEncodingTypeSize(PType);
3542  }
3543}
3544
3545/// getObjCEncodingForMethodDecl - Return the encoded type for this method
3546/// declaration.
3547void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
3548                                              std::string& S) {
3549  // FIXME: This is not very efficient.
3550  // Encode type qualifer, 'in', 'inout', etc. for the return type.
3551  getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
3552  // Encode result type.
3553  getObjCEncodingForType(Decl->getResultType(), S);
3554  // Compute size of all parameters.
3555  // Start with computing size of a pointer in number of bytes.
3556  // FIXME: There might(should) be a better way of doing this computation!
3557  SourceLocation Loc;
3558  CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3559  // The first two arguments (self and _cmd) are pointers; account for
3560  // their size.
3561  CharUnits ParmOffset = 2 * PtrSize;
3562  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3563       E = Decl->sel_param_end(); PI != E; ++PI) {
3564    QualType PType = (*PI)->getType();
3565    CharUnits sz = getObjCEncodingTypeSize(PType);
3566    assert (sz.isPositive() &&
3567        "getObjCEncodingForMethodDecl - Incomplete param type");
3568    ParmOffset += sz;
3569  }
3570  S += charUnitsToString(ParmOffset);
3571  S += "@0:";
3572  S += charUnitsToString(PtrSize);
3573
3574  // Argument types.
3575  ParmOffset = 2 * PtrSize;
3576  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3577       E = Decl->sel_param_end(); PI != E; ++PI) {
3578    ParmVarDecl *PVDecl = *PI;
3579    QualType PType = PVDecl->getOriginalType();
3580    if (const ArrayType *AT =
3581          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3582      // Use array's original type only if it has known number of
3583      // elements.
3584      if (!isa<ConstantArrayType>(AT))
3585        PType = PVDecl->getType();
3586    } else if (PType->isFunctionType())
3587      PType = PVDecl->getType();
3588    // Process argument qualifiers for user supplied arguments; such as,
3589    // 'in', 'inout', etc.
3590    getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
3591    getObjCEncodingForType(PType, S);
3592    S += charUnitsToString(ParmOffset);
3593    ParmOffset += getObjCEncodingTypeSize(PType);
3594  }
3595}
3596
3597/// getObjCEncodingForPropertyDecl - Return the encoded type for this
3598/// property declaration. If non-NULL, Container must be either an
3599/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3600/// NULL when getting encodings for protocol properties.
3601/// Property attributes are stored as a comma-delimited C string. The simple
3602/// attributes readonly and bycopy are encoded as single characters. The
3603/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3604/// encoded as single characters, followed by an identifier. Property types
3605/// are also encoded as a parametrized attribute. The characters used to encode
3606/// these attributes are defined by the following enumeration:
3607/// @code
3608/// enum PropertyAttributes {
3609/// kPropertyReadOnly = 'R',   // property is read-only.
3610/// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
3611/// kPropertyByref = '&',  // property is a reference to the value last assigned
3612/// kPropertyDynamic = 'D',    // property is dynamic
3613/// kPropertyGetter = 'G',     // followed by getter selector name
3614/// kPropertySetter = 'S',     // followed by setter selector name
3615/// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
3616/// kPropertyType = 't'              // followed by old-style type encoding.
3617/// kPropertyWeak = 'W'              // 'weak' property
3618/// kPropertyStrong = 'P'            // property GC'able
3619/// kPropertyNonAtomic = 'N'         // property non-atomic
3620/// };
3621/// @endcode
3622void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
3623                                                const Decl *Container,
3624                                                std::string& S) {
3625  // Collect information from the property implementation decl(s).
3626  bool Dynamic = false;
3627  ObjCPropertyImplDecl *SynthesizePID = 0;
3628
3629  // FIXME: Duplicated code due to poor abstraction.
3630  if (Container) {
3631    if (const ObjCCategoryImplDecl *CID =
3632        dyn_cast<ObjCCategoryImplDecl>(Container)) {
3633      for (ObjCCategoryImplDecl::propimpl_iterator
3634             i = CID->propimpl_begin(), e = CID->propimpl_end();
3635           i != e; ++i) {
3636        ObjCPropertyImplDecl *PID = *i;
3637        if (PID->getPropertyDecl() == PD) {
3638          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3639            Dynamic = true;
3640          } else {
3641            SynthesizePID = PID;
3642          }
3643        }
3644      }
3645    } else {
3646      const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
3647      for (ObjCCategoryImplDecl::propimpl_iterator
3648             i = OID->propimpl_begin(), e = OID->propimpl_end();
3649           i != e; ++i) {
3650        ObjCPropertyImplDecl *PID = *i;
3651        if (PID->getPropertyDecl() == PD) {
3652          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3653            Dynamic = true;
3654          } else {
3655            SynthesizePID = PID;
3656          }
3657        }
3658      }
3659    }
3660  }
3661
3662  // FIXME: This is not very efficient.
3663  S = "T";
3664
3665  // Encode result type.
3666  // GCC has some special rules regarding encoding of properties which
3667  // closely resembles encoding of ivars.
3668  getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
3669                             true /* outermost type */,
3670                             true /* encoding for property */);
3671
3672  if (PD->isReadOnly()) {
3673    S += ",R";
3674  } else {
3675    switch (PD->getSetterKind()) {
3676    case ObjCPropertyDecl::Assign: break;
3677    case ObjCPropertyDecl::Copy:   S += ",C"; break;
3678    case ObjCPropertyDecl::Retain: S += ",&"; break;
3679    }
3680  }
3681
3682  // It really isn't clear at all what this means, since properties
3683  // are "dynamic by default".
3684  if (Dynamic)
3685    S += ",D";
3686
3687  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3688    S += ",N";
3689
3690  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3691    S += ",G";
3692    S += PD->getGetterName().getAsString();
3693  }
3694
3695  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3696    S += ",S";
3697    S += PD->getSetterName().getAsString();
3698  }
3699
3700  if (SynthesizePID) {
3701    const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3702    S += ",V";
3703    S += OID->getNameAsString();
3704  }
3705
3706  // FIXME: OBJCGC: weak & strong
3707}
3708
3709/// getLegacyIntegralTypeEncoding -
3710/// Another legacy compatibility encoding: 32-bit longs are encoded as
3711/// 'l' or 'L' , but not always.  For typedefs, we need to use
3712/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3713///
3714void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
3715  if (isa<TypedefType>(PointeeTy.getTypePtr())) {
3716    if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
3717      if (BT->getKind() == BuiltinType::ULong &&
3718          ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
3719        PointeeTy = UnsignedIntTy;
3720      else
3721        if (BT->getKind() == BuiltinType::Long &&
3722            ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
3723          PointeeTy = IntTy;
3724    }
3725  }
3726}
3727
3728void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
3729                                        const FieldDecl *Field) {
3730  // We follow the behavior of gcc, expanding structures which are
3731  // directly pointed to, and expanding embedded structures. Note that
3732  // these rules are sufficient to prevent recursive encoding of the
3733  // same type.
3734  getObjCEncodingForTypeImpl(T, S, true, true, Field,
3735                             true /* outermost type */);
3736}
3737
3738static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3739    switch (T->getAs<BuiltinType>()->getKind()) {
3740    default: assert(0 && "Unhandled builtin type kind");
3741    case BuiltinType::Void:       return 'v';
3742    case BuiltinType::Bool:       return 'B';
3743    case BuiltinType::Char_U:
3744    case BuiltinType::UChar:      return 'C';
3745    case BuiltinType::UShort:     return 'S';
3746    case BuiltinType::UInt:       return 'I';
3747    case BuiltinType::ULong:
3748        return
3749          (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3750    case BuiltinType::UInt128:    return 'T';
3751    case BuiltinType::ULongLong:  return 'Q';
3752    case BuiltinType::Char_S:
3753    case BuiltinType::SChar:      return 'c';
3754    case BuiltinType::Short:      return 's';
3755    case BuiltinType::WChar:
3756    case BuiltinType::Int:        return 'i';
3757    case BuiltinType::Long:
3758      return
3759        (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3760    case BuiltinType::LongLong:   return 'q';
3761    case BuiltinType::Int128:     return 't';
3762    case BuiltinType::Float:      return 'f';
3763    case BuiltinType::Double:     return 'd';
3764    case BuiltinType::LongDouble: return 'D';
3765    }
3766}
3767
3768static void EncodeBitField(const ASTContext *Context, std::string& S,
3769                           QualType T, const FieldDecl *FD) {
3770  const Expr *E = FD->getBitWidth();
3771  assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3772  ASTContext *Ctx = const_cast<ASTContext*>(Context);
3773  S += 'b';
3774  // The NeXT runtime encodes bit fields as b followed by the number of bits.
3775  // The GNU runtime requires more information; bitfields are encoded as b,
3776  // then the offset (in bits) of the first element, then the type of the
3777  // bitfield, then the size in bits.  For example, in this structure:
3778  //
3779  // struct
3780  // {
3781  //    int integer;
3782  //    int flags:2;
3783  // };
3784  // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3785  // runtime, but b32i2 for the GNU runtime.  The reason for this extra
3786  // information is not especially sensible, but we're stuck with it for
3787  // compatibility with GCC, although providing it breaks anything that
3788  // actually uses runtime introspection and wants to work on both runtimes...
3789  if (!Ctx->getLangOptions().NeXTRuntime) {
3790    const RecordDecl *RD = FD->getParent();
3791    const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3792    // FIXME: This same linear search is also used in ExprConstant - it might
3793    // be better if the FieldDecl stored its offset.  We'd be increasing the
3794    // size of the object slightly, but saving some time every time it is used.
3795    unsigned i = 0;
3796    for (RecordDecl::field_iterator Field = RD->field_begin(),
3797                                 FieldEnd = RD->field_end();
3798         Field != FieldEnd; (void)++Field, ++i) {
3799      if (*Field == FD)
3800        break;
3801    }
3802    S += llvm::utostr(RL.getFieldOffset(i));
3803    S += ObjCEncodingForPrimitiveKind(Context, T);
3804  }
3805  unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
3806  S += llvm::utostr(N);
3807}
3808
3809// FIXME: Use SmallString for accumulating string.
3810void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3811                                            bool ExpandPointedToStructures,
3812                                            bool ExpandStructures,
3813                                            const FieldDecl *FD,
3814                                            bool OutermostType,
3815                                            bool EncodingProperty) {
3816  if (T->getAs<BuiltinType>()) {
3817    if (FD && FD->isBitField())
3818      return EncodeBitField(this, S, T, FD);
3819    S += ObjCEncodingForPrimitiveKind(this, T);
3820    return;
3821  }
3822
3823  if (const ComplexType *CT = T->getAs<ComplexType>()) {
3824    S += 'j';
3825    getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
3826                               false);
3827    return;
3828  }
3829
3830  // encoding for pointer or r3eference types.
3831  QualType PointeeTy;
3832  if (const PointerType *PT = T->getAs<PointerType>()) {
3833    if (PT->isObjCSelType()) {
3834      S += ':';
3835      return;
3836    }
3837    PointeeTy = PT->getPointeeType();
3838  }
3839  else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3840    PointeeTy = RT->getPointeeType();
3841  if (!PointeeTy.isNull()) {
3842    bool isReadOnly = false;
3843    // For historical/compatibility reasons, the read-only qualifier of the
3844    // pointee gets emitted _before_ the '^'.  The read-only qualifier of
3845    // the pointer itself gets ignored, _unless_ we are looking at a typedef!
3846    // Also, do not emit the 'r' for anything but the outermost type!
3847    if (isa<TypedefType>(T.getTypePtr())) {
3848      if (OutermostType && T.isConstQualified()) {
3849        isReadOnly = true;
3850        S += 'r';
3851      }
3852    } else if (OutermostType) {
3853      QualType P = PointeeTy;
3854      while (P->getAs<PointerType>())
3855        P = P->getAs<PointerType>()->getPointeeType();
3856      if (P.isConstQualified()) {
3857        isReadOnly = true;
3858        S += 'r';
3859      }
3860    }
3861    if (isReadOnly) {
3862      // Another legacy compatibility encoding. Some ObjC qualifier and type
3863      // combinations need to be rearranged.
3864      // Rewrite "in const" from "nr" to "rn"
3865      if (llvm::StringRef(S).endswith("nr"))
3866        S.replace(S.end()-2, S.end(), "rn");
3867    }
3868
3869    if (PointeeTy->isCharType()) {
3870      // char pointer types should be encoded as '*' unless it is a
3871      // type that has been typedef'd to 'BOOL'.
3872      if (!isTypeTypedefedAsBOOL(PointeeTy)) {
3873        S += '*';
3874        return;
3875      }
3876    } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
3877      // GCC binary compat: Need to convert "struct objc_class *" to "#".
3878      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3879        S += '#';
3880        return;
3881      }
3882      // GCC binary compat: Need to convert "struct objc_object *" to "@".
3883      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3884        S += '@';
3885        return;
3886      }
3887      // fall through...
3888    }
3889    S += '^';
3890    getLegacyIntegralTypeEncoding(PointeeTy);
3891
3892    getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
3893                               NULL);
3894    return;
3895  }
3896
3897  if (const ArrayType *AT =
3898      // Ignore type qualifiers etc.
3899        dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
3900    if (isa<IncompleteArrayType>(AT)) {
3901      // Incomplete arrays are encoded as a pointer to the array element.
3902      S += '^';
3903
3904      getObjCEncodingForTypeImpl(AT->getElementType(), S,
3905                                 false, ExpandStructures, FD);
3906    } else {
3907      S += '[';
3908
3909      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3910        S += llvm::utostr(CAT->getSize().getZExtValue());
3911      else {
3912        //Variable length arrays are encoded as a regular array with 0 elements.
3913        assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3914        S += '0';
3915      }
3916
3917      getObjCEncodingForTypeImpl(AT->getElementType(), S,
3918                                 false, ExpandStructures, FD);
3919      S += ']';
3920    }
3921    return;
3922  }
3923
3924  if (T->getAs<FunctionType>()) {
3925    S += '?';
3926    return;
3927  }
3928
3929  if (const RecordType *RTy = T->getAs<RecordType>()) {
3930    RecordDecl *RDecl = RTy->getDecl();
3931    S += RDecl->isUnion() ? '(' : '{';
3932    // Anonymous structures print as '?'
3933    if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3934      S += II->getName();
3935      if (ClassTemplateSpecializationDecl *Spec
3936          = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3937        const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3938        std::string TemplateArgsStr
3939          = TemplateSpecializationType::PrintTemplateArgumentList(
3940                                            TemplateArgs.data(),
3941                                            TemplateArgs.size(),
3942                                            (*this).PrintingPolicy);
3943
3944        S += TemplateArgsStr;
3945      }
3946    } else {
3947      S += '?';
3948    }
3949    if (ExpandStructures) {
3950      S += '=';
3951      for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3952                                   FieldEnd = RDecl->field_end();
3953           Field != FieldEnd; ++Field) {
3954        if (FD) {
3955          S += '"';
3956          S += Field->getNameAsString();
3957          S += '"';
3958        }
3959
3960        // Special case bit-fields.
3961        if (Field->isBitField()) {
3962          getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
3963                                     (*Field));
3964        } else {
3965          QualType qt = Field->getType();
3966          getLegacyIntegralTypeEncoding(qt);
3967          getObjCEncodingForTypeImpl(qt, S, false, true,
3968                                     FD);
3969        }
3970      }
3971    }
3972    S += RDecl->isUnion() ? ')' : '}';
3973    return;
3974  }
3975
3976  if (T->isEnumeralType()) {
3977    if (FD && FD->isBitField())
3978      EncodeBitField(this, S, T, FD);
3979    else
3980      S += 'i';
3981    return;
3982  }
3983
3984  if (T->isBlockPointerType()) {
3985    S += "@?"; // Unlike a pointer-to-function, which is "^?".
3986    return;
3987  }
3988
3989  // Ignore protocol qualifiers when mangling at this level.
3990  if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3991    T = OT->getBaseType();
3992
3993  if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
3994    // @encode(class_name)
3995    ObjCInterfaceDecl *OI = OIT->getDecl();
3996    S += '{';
3997    const IdentifierInfo *II = OI->getIdentifier();
3998    S += II->getName();
3999    S += '=';
4000    llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
4001    DeepCollectObjCIvars(OI, true, Ivars);
4002    for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4003      FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4004      if (Field->isBitField())
4005        getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
4006      else
4007        getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
4008    }
4009    S += '}';
4010    return;
4011  }
4012
4013  if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
4014    if (OPT->isObjCIdType()) {
4015      S += '@';
4016      return;
4017    }
4018
4019    if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4020      // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4021      // Since this is a binary compatibility issue, need to consult with runtime
4022      // folks. Fortunately, this is a *very* obsure construct.
4023      S += '#';
4024      return;
4025    }
4026
4027    if (OPT->isObjCQualifiedIdType()) {
4028      getObjCEncodingForTypeImpl(getObjCIdType(), S,
4029                                 ExpandPointedToStructures,
4030                                 ExpandStructures, FD);
4031      if (FD || EncodingProperty) {
4032        // Note that we do extended encoding of protocol qualifer list
4033        // Only when doing ivar or property encoding.
4034        S += '"';
4035        for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4036             E = OPT->qual_end(); I != E; ++I) {
4037          S += '<';
4038          S += (*I)->getNameAsString();
4039          S += '>';
4040        }
4041        S += '"';
4042      }
4043      return;
4044    }
4045
4046    QualType PointeeTy = OPT->getPointeeType();
4047    if (!EncodingProperty &&
4048        isa<TypedefType>(PointeeTy.getTypePtr())) {
4049      // Another historical/compatibility reason.
4050      // We encode the underlying type which comes out as
4051      // {...};
4052      S += '^';
4053      getObjCEncodingForTypeImpl(PointeeTy, S,
4054                                 false, ExpandPointedToStructures,
4055                                 NULL);
4056      return;
4057    }
4058
4059    S += '@';
4060    if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
4061      S += '"';
4062      S += OPT->getInterfaceDecl()->getIdentifier()->getName();
4063      for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4064           E = OPT->qual_end(); I != E; ++I) {
4065        S += '<';
4066        S += (*I)->getNameAsString();
4067        S += '>';
4068      }
4069      S += '"';
4070    }
4071    return;
4072  }
4073
4074  // gcc just blithely ignores member pointers.
4075  // TODO: maybe there should be a mangling for these
4076  if (T->getAs<MemberPointerType>())
4077    return;
4078
4079  if (T->isVectorType()) {
4080    // This matches gcc's encoding, even though technically it is
4081    // insufficient.
4082    // FIXME. We should do a better job than gcc.
4083    return;
4084  }
4085
4086  assert(0 && "@encode for type not implemented!");
4087}
4088
4089void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
4090                                                 std::string& S) const {
4091  if (QT & Decl::OBJC_TQ_In)
4092    S += 'n';
4093  if (QT & Decl::OBJC_TQ_Inout)
4094    S += 'N';
4095  if (QT & Decl::OBJC_TQ_Out)
4096    S += 'o';
4097  if (QT & Decl::OBJC_TQ_Bycopy)
4098    S += 'O';
4099  if (QT & Decl::OBJC_TQ_Byref)
4100    S += 'R';
4101  if (QT & Decl::OBJC_TQ_Oneway)
4102    S += 'V';
4103}
4104
4105void ASTContext::setBuiltinVaListType(QualType T) {
4106  assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
4107
4108  BuiltinVaListType = T;
4109}
4110
4111void ASTContext::setObjCIdType(QualType T) {
4112  ObjCIdTypedefType = T;
4113}
4114
4115void ASTContext::setObjCSelType(QualType T) {
4116  ObjCSelTypedefType = T;
4117}
4118
4119void ASTContext::setObjCProtoType(QualType QT) {
4120  ObjCProtoType = QT;
4121}
4122
4123void ASTContext::setObjCClassType(QualType T) {
4124  ObjCClassTypedefType = T;
4125}
4126
4127void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
4128  assert(ObjCConstantStringType.isNull() &&
4129         "'NSConstantString' type already set!");
4130
4131  ObjCConstantStringType = getObjCInterfaceType(Decl);
4132}
4133
4134/// \brief Retrieve the template name that corresponds to a non-empty
4135/// lookup.
4136TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4137                                                   UnresolvedSetIterator End) {
4138  unsigned size = End - Begin;
4139  assert(size > 1 && "set is not overloaded!");
4140
4141  void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4142                          size * sizeof(FunctionTemplateDecl*));
4143  OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4144
4145  NamedDecl **Storage = OT->getStorage();
4146  for (UnresolvedSetIterator I = Begin; I != End; ++I) {
4147    NamedDecl *D = *I;
4148    assert(isa<FunctionTemplateDecl>(D) ||
4149           (isa<UsingShadowDecl>(D) &&
4150            isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4151    *Storage++ = D;
4152  }
4153
4154  return TemplateName(OT);
4155}
4156
4157/// \brief Retrieve the template name that represents a qualified
4158/// template name such as \c std::vector.
4159TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4160                                                  bool TemplateKeyword,
4161                                                  TemplateDecl *Template) {
4162  // FIXME: Canonicalization?
4163  llvm::FoldingSetNodeID ID;
4164  QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4165
4166  void *InsertPos = 0;
4167  QualifiedTemplateName *QTN =
4168    QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4169  if (!QTN) {
4170    QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4171    QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4172  }
4173
4174  return TemplateName(QTN);
4175}
4176
4177/// \brief Retrieve the template name that represents a dependent
4178/// template name such as \c MetaFun::template apply.
4179TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4180                                                  const IdentifierInfo *Name) {
4181  assert((!NNS || NNS->isDependent()) &&
4182         "Nested name specifier must be dependent");
4183
4184  llvm::FoldingSetNodeID ID;
4185  DependentTemplateName::Profile(ID, NNS, Name);
4186
4187  void *InsertPos = 0;
4188  DependentTemplateName *QTN =
4189    DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4190
4191  if (QTN)
4192    return TemplateName(QTN);
4193
4194  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4195  if (CanonNNS == NNS) {
4196    QTN = new (*this,4) DependentTemplateName(NNS, Name);
4197  } else {
4198    TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4199    QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
4200    DependentTemplateName *CheckQTN =
4201      DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4202    assert(!CheckQTN && "Dependent type name canonicalization broken");
4203    (void)CheckQTN;
4204  }
4205
4206  DependentTemplateNames.InsertNode(QTN, InsertPos);
4207  return TemplateName(QTN);
4208}
4209
4210/// \brief Retrieve the template name that represents a dependent
4211/// template name such as \c MetaFun::template operator+.
4212TemplateName
4213ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4214                                     OverloadedOperatorKind Operator) {
4215  assert((!NNS || NNS->isDependent()) &&
4216         "Nested name specifier must be dependent");
4217
4218  llvm::FoldingSetNodeID ID;
4219  DependentTemplateName::Profile(ID, NNS, Operator);
4220
4221  void *InsertPos = 0;
4222  DependentTemplateName *QTN
4223    = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4224
4225  if (QTN)
4226    return TemplateName(QTN);
4227
4228  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4229  if (CanonNNS == NNS) {
4230    QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4231  } else {
4232    TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4233    QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
4234
4235    DependentTemplateName *CheckQTN
4236      = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4237    assert(!CheckQTN && "Dependent template name canonicalization broken");
4238    (void)CheckQTN;
4239  }
4240
4241  DependentTemplateNames.InsertNode(QTN, InsertPos);
4242  return TemplateName(QTN);
4243}
4244
4245/// getFromTargetType - Given one of the integer types provided by
4246/// TargetInfo, produce the corresponding type. The unsigned @p Type
4247/// is actually a value of type @c TargetInfo::IntType.
4248CanQualType ASTContext::getFromTargetType(unsigned Type) const {
4249  switch (Type) {
4250  case TargetInfo::NoInt: return CanQualType();
4251  case TargetInfo::SignedShort: return ShortTy;
4252  case TargetInfo::UnsignedShort: return UnsignedShortTy;
4253  case TargetInfo::SignedInt: return IntTy;
4254  case TargetInfo::UnsignedInt: return UnsignedIntTy;
4255  case TargetInfo::SignedLong: return LongTy;
4256  case TargetInfo::UnsignedLong: return UnsignedLongTy;
4257  case TargetInfo::SignedLongLong: return LongLongTy;
4258  case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4259  }
4260
4261  assert(false && "Unhandled TargetInfo::IntType value");
4262  return CanQualType();
4263}
4264
4265//===----------------------------------------------------------------------===//
4266//                        Type Predicates.
4267//===----------------------------------------------------------------------===//
4268
4269/// isObjCNSObjectType - Return true if this is an NSObject object using
4270/// NSObject attribute on a c-style pointer type.
4271/// FIXME - Make it work directly on types.
4272/// FIXME: Move to Type.
4273///
4274bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4275  if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4276    if (TypedefDecl *TD = TDT->getDecl())
4277      if (TD->getAttr<ObjCNSObjectAttr>())
4278        return true;
4279  }
4280  return false;
4281}
4282
4283/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4284/// garbage collection attribute.
4285///
4286Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4287  Qualifiers::GC GCAttrs = Qualifiers::GCNone;
4288  if (getLangOptions().ObjC1 &&
4289      getLangOptions().getGCMode() != LangOptions::NonGC) {
4290    GCAttrs = Ty.getObjCGCAttr();
4291    // Default behavious under objective-c's gc is for objective-c pointers
4292    // (or pointers to them) be treated as though they were declared
4293    // as __strong.
4294    if (GCAttrs == Qualifiers::GCNone) {
4295      if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4296        GCAttrs = Qualifiers::Strong;
4297      else if (Ty->isPointerType())
4298        return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4299    }
4300    // Non-pointers have none gc'able attribute regardless of the attribute
4301    // set on them.
4302    else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
4303      return Qualifiers::GCNone;
4304  }
4305  return GCAttrs;
4306}
4307
4308//===----------------------------------------------------------------------===//
4309//                        Type Compatibility Testing
4310//===----------------------------------------------------------------------===//
4311
4312/// areCompatVectorTypes - Return true if the two specified vector types are
4313/// compatible.
4314static bool areCompatVectorTypes(const VectorType *LHS,
4315                                 const VectorType *RHS) {
4316  assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
4317  return LHS->getElementType() == RHS->getElementType() &&
4318         LHS->getNumElements() == RHS->getNumElements();
4319}
4320
4321bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4322                                          QualType SecondVec) {
4323  assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4324  assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4325
4326  if (hasSameUnqualifiedType(FirstVec, SecondVec))
4327    return true;
4328
4329  // Treat Neon vector types and most AltiVec vector types as if they are the
4330  // equivalent GCC vector types.
4331  const VectorType *First = FirstVec->getAs<VectorType>();
4332  const VectorType *Second = SecondVec->getAs<VectorType>();
4333  if (First->getNumElements() == Second->getNumElements() &&
4334      hasSameType(First->getElementType(), Second->getElementType()) &&
4335      First->getVectorKind() != VectorType::AltiVecPixel &&
4336      First->getVectorKind() != VectorType::AltiVecBool &&
4337      Second->getVectorKind() != VectorType::AltiVecPixel &&
4338      Second->getVectorKind() != VectorType::AltiVecBool)
4339    return true;
4340
4341  return false;
4342}
4343
4344//===----------------------------------------------------------------------===//
4345// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4346//===----------------------------------------------------------------------===//
4347
4348/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4349/// inheritance hierarchy of 'rProto'.
4350bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4351                                                ObjCProtocolDecl *rProto) {
4352  if (lProto == rProto)
4353    return true;
4354  for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4355       E = rProto->protocol_end(); PI != E; ++PI)
4356    if (ProtocolCompatibleWithProtocol(lProto, *PI))
4357      return true;
4358  return false;
4359}
4360
4361/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4362/// return true if lhs's protocols conform to rhs's protocol; false
4363/// otherwise.
4364bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4365  if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4366    return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4367  return false;
4368}
4369
4370/// ObjCQualifiedClassTypesAreCompatible - compare  Class<p,...> and
4371/// Class<p1, ...>.
4372bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4373                                                      QualType rhs) {
4374  const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4375  const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4376  assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4377
4378  for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4379       E = lhsQID->qual_end(); I != E; ++I) {
4380    bool match = false;
4381    ObjCProtocolDecl *lhsProto = *I;
4382    for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4383         E = rhsOPT->qual_end(); J != E; ++J) {
4384      ObjCProtocolDecl *rhsProto = *J;
4385      if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4386        match = true;
4387        break;
4388      }
4389    }
4390    if (!match)
4391      return false;
4392  }
4393  return true;
4394}
4395
4396/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4397/// ObjCQualifiedIDType.
4398bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4399                                                   bool compare) {
4400  // Allow id<P..> and an 'id' or void* type in all cases.
4401  if (lhs->isVoidPointerType() ||
4402      lhs->isObjCIdType() || lhs->isObjCClassType())
4403    return true;
4404  else if (rhs->isVoidPointerType() ||
4405           rhs->isObjCIdType() || rhs->isObjCClassType())
4406    return true;
4407
4408  if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
4409    const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4410
4411    if (!rhsOPT) return false;
4412
4413    if (rhsOPT->qual_empty()) {
4414      // If the RHS is a unqualified interface pointer "NSString*",
4415      // make sure we check the class hierarchy.
4416      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4417        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4418             E = lhsQID->qual_end(); I != E; ++I) {
4419          // when comparing an id<P> on lhs with a static type on rhs,
4420          // see if static class implements all of id's protocols, directly or
4421          // through its super class and categories.
4422          if (!rhsID->ClassImplementsProtocol(*I, true))
4423            return false;
4424        }
4425      }
4426      // If there are no qualifiers and no interface, we have an 'id'.
4427      return true;
4428    }
4429    // Both the right and left sides have qualifiers.
4430    for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4431         E = lhsQID->qual_end(); I != E; ++I) {
4432      ObjCProtocolDecl *lhsProto = *I;
4433      bool match = false;
4434
4435      // when comparing an id<P> on lhs with a static type on rhs,
4436      // see if static class implements all of id's protocols, directly or
4437      // through its super class and categories.
4438      for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4439           E = rhsOPT->qual_end(); J != E; ++J) {
4440        ObjCProtocolDecl *rhsProto = *J;
4441        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4442            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4443          match = true;
4444          break;
4445        }
4446      }
4447      // If the RHS is a qualified interface pointer "NSString<P>*",
4448      // make sure we check the class hierarchy.
4449      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4450        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4451             E = lhsQID->qual_end(); I != E; ++I) {
4452          // when comparing an id<P> on lhs with a static type on rhs,
4453          // see if static class implements all of id's protocols, directly or
4454          // through its super class and categories.
4455          if (rhsID->ClassImplementsProtocol(*I, true)) {
4456            match = true;
4457            break;
4458          }
4459        }
4460      }
4461      if (!match)
4462        return false;
4463    }
4464
4465    return true;
4466  }
4467
4468  const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4469  assert(rhsQID && "One of the LHS/RHS should be id<x>");
4470
4471  if (const ObjCObjectPointerType *lhsOPT =
4472        lhs->getAsObjCInterfacePointerType()) {
4473    // If both the right and left sides have qualifiers.
4474    for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4475         E = lhsOPT->qual_end(); I != E; ++I) {
4476      ObjCProtocolDecl *lhsProto = *I;
4477      bool match = false;
4478
4479      // when comparing an id<P> on rhs with a static type on lhs,
4480      // see if static class implements all of id's protocols, directly or
4481      // through its super class and categories.
4482      // First, lhs protocols in the qualifier list must be found, direct
4483      // or indirect in rhs's qualifier list or it is a mismatch.
4484      for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4485           E = rhsQID->qual_end(); J != E; ++J) {
4486        ObjCProtocolDecl *rhsProto = *J;
4487        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4488            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4489          match = true;
4490          break;
4491        }
4492      }
4493      if (!match)
4494        return false;
4495    }
4496
4497    // Static class's protocols, or its super class or category protocols
4498    // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
4499    if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4500      llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4501      CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
4502      // This is rather dubious but matches gcc's behavior. If lhs has
4503      // no type qualifier and its class has no static protocol(s)
4504      // assume that it is mismatch.
4505      if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
4506        return false;
4507      for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4508           LHSInheritedProtocols.begin(),
4509           E = LHSInheritedProtocols.end(); I != E; ++I) {
4510        bool match = false;
4511        ObjCProtocolDecl *lhsProto = (*I);
4512        for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4513             E = rhsQID->qual_end(); J != E; ++J) {
4514          ObjCProtocolDecl *rhsProto = *J;
4515          if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4516              (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4517            match = true;
4518            break;
4519          }
4520        }
4521        if (!match)
4522          return false;
4523      }
4524    }
4525    return true;
4526  }
4527  return false;
4528}
4529
4530/// canAssignObjCInterfaces - Return true if the two interface types are
4531/// compatible for assignment from RHS to LHS.  This handles validation of any
4532/// protocol qualifiers on the LHS or RHS.
4533///
4534bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4535                                         const ObjCObjectPointerType *RHSOPT) {
4536  const ObjCObjectType* LHS = LHSOPT->getObjectType();
4537  const ObjCObjectType* RHS = RHSOPT->getObjectType();
4538
4539  // If either type represents the built-in 'id' or 'Class' types, return true.
4540  if (LHS->isObjCUnqualifiedIdOrClass() ||
4541      RHS->isObjCUnqualifiedIdOrClass())
4542    return true;
4543
4544  if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
4545    return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4546                                             QualType(RHSOPT,0),
4547                                             false);
4548
4549  if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4550    return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4551                                                QualType(RHSOPT,0));
4552
4553  // If we have 2 user-defined types, fall into that path.
4554  if (LHS->getInterface() && RHS->getInterface())
4555    return canAssignObjCInterfaces(LHS, RHS);
4556
4557  return false;
4558}
4559
4560/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4561/// for providing type-safty for objective-c pointers used to pass/return
4562/// arguments in block literals. When passed as arguments, passing 'A*' where
4563/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4564/// not OK. For the return type, the opposite is not OK.
4565bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4566                                         const ObjCObjectPointerType *LHSOPT,
4567                                         const ObjCObjectPointerType *RHSOPT) {
4568  if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
4569    return true;
4570
4571  if (LHSOPT->isObjCBuiltinType()) {
4572    return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4573  }
4574
4575  if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
4576    return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4577                                             QualType(RHSOPT,0),
4578                                             false);
4579
4580  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4581  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4582  if (LHS && RHS)  { // We have 2 user-defined types.
4583    if (LHS != RHS) {
4584      if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4585        return false;
4586      if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4587        return true;
4588    }
4589    else
4590      return true;
4591  }
4592  return false;
4593}
4594
4595/// getIntersectionOfProtocols - This routine finds the intersection of set
4596/// of protocols inherited from two distinct objective-c pointer objects.
4597/// It is used to build composite qualifier list of the composite type of
4598/// the conditional expression involving two objective-c pointer objects.
4599static
4600void getIntersectionOfProtocols(ASTContext &Context,
4601                                const ObjCObjectPointerType *LHSOPT,
4602                                const ObjCObjectPointerType *RHSOPT,
4603      llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4604
4605  const ObjCObjectType* LHS = LHSOPT->getObjectType();
4606  const ObjCObjectType* RHS = RHSOPT->getObjectType();
4607  assert(LHS->getInterface() && "LHS must have an interface base");
4608  assert(RHS->getInterface() && "RHS must have an interface base");
4609
4610  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4611  unsigned LHSNumProtocols = LHS->getNumProtocols();
4612  if (LHSNumProtocols > 0)
4613    InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4614  else {
4615    llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4616    Context.CollectInheritedProtocols(LHS->getInterface(),
4617                                      LHSInheritedProtocols);
4618    InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4619                                LHSInheritedProtocols.end());
4620  }
4621
4622  unsigned RHSNumProtocols = RHS->getNumProtocols();
4623  if (RHSNumProtocols > 0) {
4624    ObjCProtocolDecl **RHSProtocols =
4625      const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
4626    for (unsigned i = 0; i < RHSNumProtocols; ++i)
4627      if (InheritedProtocolSet.count(RHSProtocols[i]))
4628        IntersectionOfProtocols.push_back(RHSProtocols[i]);
4629  }
4630  else {
4631    llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
4632    Context.CollectInheritedProtocols(RHS->getInterface(),
4633                                      RHSInheritedProtocols);
4634    for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4635         RHSInheritedProtocols.begin(),
4636         E = RHSInheritedProtocols.end(); I != E; ++I)
4637      if (InheritedProtocolSet.count((*I)))
4638        IntersectionOfProtocols.push_back((*I));
4639  }
4640}
4641
4642/// areCommonBaseCompatible - Returns common base class of the two classes if
4643/// one found. Note that this is O'2 algorithm. But it will be called as the
4644/// last type comparison in a ?-exp of ObjC pointer types before a
4645/// warning is issued. So, its invokation is extremely rare.
4646QualType ASTContext::areCommonBaseCompatible(
4647                                          const ObjCObjectPointerType *Lptr,
4648                                          const ObjCObjectPointerType *Rptr) {
4649  const ObjCObjectType *LHS = Lptr->getObjectType();
4650  const ObjCObjectType *RHS = Rptr->getObjectType();
4651  const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4652  const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4653  if (!LDecl || !RDecl)
4654    return QualType();
4655
4656  while ((LDecl = LDecl->getSuperClass())) {
4657    LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
4658    if (canAssignObjCInterfaces(LHS, RHS)) {
4659      llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4660      getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4661
4662      QualType Result = QualType(LHS, 0);
4663      if (!Protocols.empty())
4664        Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4665      Result = getObjCObjectPointerType(Result);
4666      return Result;
4667    }
4668  }
4669
4670  return QualType();
4671}
4672
4673bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4674                                         const ObjCObjectType *RHS) {
4675  assert(LHS->getInterface() && "LHS is not an interface type");
4676  assert(RHS->getInterface() && "RHS is not an interface type");
4677
4678  // Verify that the base decls are compatible: the RHS must be a subclass of
4679  // the LHS.
4680  if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
4681    return false;
4682
4683  // RHS must have a superset of the protocols in the LHS.  If the LHS is not
4684  // protocol qualified at all, then we are good.
4685  if (LHS->getNumProtocols() == 0)
4686    return true;
4687
4688  // Okay, we know the LHS has protocol qualifiers.  If the RHS doesn't, then it
4689  // isn't a superset.
4690  if (RHS->getNumProtocols() == 0)
4691    return true;  // FIXME: should return false!
4692
4693  for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4694                                     LHSPE = LHS->qual_end();
4695       LHSPI != LHSPE; LHSPI++) {
4696    bool RHSImplementsProtocol = false;
4697
4698    // If the RHS doesn't implement the protocol on the left, the types
4699    // are incompatible.
4700    for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4701                                       RHSPE = RHS->qual_end();
4702         RHSPI != RHSPE; RHSPI++) {
4703      if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
4704        RHSImplementsProtocol = true;
4705        break;
4706      }
4707    }
4708    // FIXME: For better diagnostics, consider passing back the protocol name.
4709    if (!RHSImplementsProtocol)
4710      return false;
4711  }
4712  // The RHS implements all protocols listed on the LHS.
4713  return true;
4714}
4715
4716bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4717  // get the "pointed to" types
4718  const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4719  const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
4720
4721  if (!LHSOPT || !RHSOPT)
4722    return false;
4723
4724  return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4725         canAssignObjCInterfaces(RHSOPT, LHSOPT);
4726}
4727
4728bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
4729  return canAssignObjCInterfaces(
4730                getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
4731                getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
4732}
4733
4734/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
4735/// both shall have the identically qualified version of a compatible type.
4736/// C99 6.2.7p1: Two types have compatible types if their types are the
4737/// same. See 6.7.[2,3,5] for additional rules.
4738bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
4739                                    bool CompareUnqualified) {
4740  if (getLangOptions().CPlusPlus)
4741    return hasSameType(LHS, RHS);
4742
4743  return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
4744}
4745
4746bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4747  return !mergeTypes(LHS, RHS, true).isNull();
4748}
4749
4750/// mergeTransparentUnionType - if T is a transparent union type and a member
4751/// of T is compatible with SubType, return the merged type, else return
4752/// QualType()
4753QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
4754                                               bool OfBlockPointer,
4755                                               bool Unqualified) {
4756  if (const RecordType *UT = T->getAsUnionType()) {
4757    RecordDecl *UD = UT->getDecl();
4758    if (UD->hasAttr<TransparentUnionAttr>()) {
4759      for (RecordDecl::field_iterator it = UD->field_begin(),
4760           itend = UD->field_end(); it != itend; ++it) {
4761        QualType ET = it->getType().getUnqualifiedType();
4762        QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
4763        if (!MT.isNull())
4764          return MT;
4765      }
4766    }
4767  }
4768
4769  return QualType();
4770}
4771
4772/// mergeFunctionArgumentTypes - merge two types which appear as function
4773/// argument types
4774QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
4775                                                bool OfBlockPointer,
4776                                                bool Unqualified) {
4777  // GNU extension: two types are compatible if they appear as a function
4778  // argument, one of the types is a transparent union type and the other
4779  // type is compatible with a union member
4780  QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
4781                                              Unqualified);
4782  if (!lmerge.isNull())
4783    return lmerge;
4784
4785  QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
4786                                              Unqualified);
4787  if (!rmerge.isNull())
4788    return rmerge;
4789
4790  return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
4791}
4792
4793QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
4794                                        bool OfBlockPointer,
4795                                        bool Unqualified) {
4796  const FunctionType *lbase = lhs->getAs<FunctionType>();
4797  const FunctionType *rbase = rhs->getAs<FunctionType>();
4798  const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4799  const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
4800  bool allLTypes = true;
4801  bool allRTypes = true;
4802
4803  // Check return type
4804  QualType retType;
4805  if (OfBlockPointer)
4806    retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true,
4807                         Unqualified);
4808  else
4809    retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
4810                         Unqualified);
4811  if (retType.isNull()) return QualType();
4812
4813  if (Unqualified)
4814    retType = retType.getUnqualifiedType();
4815
4816  CanQualType LRetType = getCanonicalType(lbase->getResultType());
4817  CanQualType RRetType = getCanonicalType(rbase->getResultType());
4818  if (Unqualified) {
4819    LRetType = LRetType.getUnqualifiedType();
4820    RRetType = RRetType.getUnqualifiedType();
4821  }
4822
4823  if (getCanonicalType(retType) != LRetType)
4824    allLTypes = false;
4825  if (getCanonicalType(retType) != RRetType)
4826    allRTypes = false;
4827
4828  // FIXME: double check this
4829  // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4830  //                           rbase->getRegParmAttr() != 0 &&
4831  //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
4832  FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4833  FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
4834
4835  // Compatible functions must have compatible calling conventions
4836  if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
4837    return QualType();
4838
4839  // Regparm is part of the calling convention.
4840  if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
4841    return QualType();
4842
4843  // It's noreturn if either type is.
4844  // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
4845  bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4846  if (NoReturn != lbaseInfo.getNoReturn())
4847    allLTypes = false;
4848  if (NoReturn != rbaseInfo.getNoReturn())
4849    allRTypes = false;
4850
4851  FunctionType::ExtInfo einfo(NoReturn,
4852                              lbaseInfo.getRegParm(),
4853                              lbaseInfo.getCC());
4854
4855  if (lproto && rproto) { // two C99 style function prototypes
4856    assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4857           "C++ shouldn't be here");
4858    unsigned lproto_nargs = lproto->getNumArgs();
4859    unsigned rproto_nargs = rproto->getNumArgs();
4860
4861    // Compatible functions must have the same number of arguments
4862    if (lproto_nargs != rproto_nargs)
4863      return QualType();
4864
4865    // Variadic and non-variadic functions aren't compatible
4866    if (lproto->isVariadic() != rproto->isVariadic())
4867      return QualType();
4868
4869    if (lproto->getTypeQuals() != rproto->getTypeQuals())
4870      return QualType();
4871
4872    // Check argument compatibility
4873    llvm::SmallVector<QualType, 10> types;
4874    for (unsigned i = 0; i < lproto_nargs; i++) {
4875      QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4876      QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4877      QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
4878                                                    OfBlockPointer,
4879                                                    Unqualified);
4880      if (argtype.isNull()) return QualType();
4881
4882      if (Unqualified)
4883        argtype = argtype.getUnqualifiedType();
4884
4885      types.push_back(argtype);
4886      if (Unqualified) {
4887        largtype = largtype.getUnqualifiedType();
4888        rargtype = rargtype.getUnqualifiedType();
4889      }
4890
4891      if (getCanonicalType(argtype) != getCanonicalType(largtype))
4892        allLTypes = false;
4893      if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4894        allRTypes = false;
4895    }
4896    if (allLTypes) return lhs;
4897    if (allRTypes) return rhs;
4898
4899    FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
4900    EPI.ExtInfo = einfo;
4901    return getFunctionType(retType, types.begin(), types.size(), EPI);
4902  }
4903
4904  if (lproto) allRTypes = false;
4905  if (rproto) allLTypes = false;
4906
4907  const FunctionProtoType *proto = lproto ? lproto : rproto;
4908  if (proto) {
4909    assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
4910    if (proto->isVariadic()) return QualType();
4911    // Check that the types are compatible with the types that
4912    // would result from default argument promotions (C99 6.7.5.3p15).
4913    // The only types actually affected are promotable integer
4914    // types and floats, which would be passed as a different
4915    // type depending on whether the prototype is visible.
4916    unsigned proto_nargs = proto->getNumArgs();
4917    for (unsigned i = 0; i < proto_nargs; ++i) {
4918      QualType argTy = proto->getArgType(i);
4919
4920      // Look at the promotion type of enum types, since that is the type used
4921      // to pass enum values.
4922      if (const EnumType *Enum = argTy->getAs<EnumType>())
4923        argTy = Enum->getDecl()->getPromotionType();
4924
4925      if (argTy->isPromotableIntegerType() ||
4926          getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4927        return QualType();
4928    }
4929
4930    if (allLTypes) return lhs;
4931    if (allRTypes) return rhs;
4932
4933    FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
4934    EPI.ExtInfo = einfo;
4935    return getFunctionType(retType, proto->arg_type_begin(),
4936                           proto->getNumArgs(), EPI);
4937  }
4938
4939  if (allLTypes) return lhs;
4940  if (allRTypes) return rhs;
4941  return getFunctionNoProtoType(retType, einfo);
4942}
4943
4944QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
4945                                bool OfBlockPointer,
4946                                bool Unqualified) {
4947  // C++ [expr]: If an expression initially has the type "reference to T", the
4948  // type is adjusted to "T" prior to any further analysis, the expression
4949  // designates the object or function denoted by the reference, and the
4950  // expression is an lvalue unless the reference is an rvalue reference and
4951  // the expression is a function call (possibly inside parentheses).
4952  assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4953  assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4954
4955  if (Unqualified) {
4956    LHS = LHS.getUnqualifiedType();
4957    RHS = RHS.getUnqualifiedType();
4958  }
4959
4960  QualType LHSCan = getCanonicalType(LHS),
4961           RHSCan = getCanonicalType(RHS);
4962
4963  // If two types are identical, they are compatible.
4964  if (LHSCan == RHSCan)
4965    return LHS;
4966
4967  // If the qualifiers are different, the types aren't compatible... mostly.
4968  Qualifiers LQuals = LHSCan.getLocalQualifiers();
4969  Qualifiers RQuals = RHSCan.getLocalQualifiers();
4970  if (LQuals != RQuals) {
4971    // If any of these qualifiers are different, we have a type
4972    // mismatch.
4973    if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4974        LQuals.getAddressSpace() != RQuals.getAddressSpace())
4975      return QualType();
4976
4977    // Exactly one GC qualifier difference is allowed: __strong is
4978    // okay if the other type has no GC qualifier but is an Objective
4979    // C object pointer (i.e. implicitly strong by default).  We fix
4980    // this by pretending that the unqualified type was actually
4981    // qualified __strong.
4982    Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4983    Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4984    assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4985
4986    if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4987      return QualType();
4988
4989    if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4990      return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4991    }
4992    if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4993      return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4994    }
4995    return QualType();
4996  }
4997
4998  // Okay, qualifiers are equal.
4999
5000  Type::TypeClass LHSClass = LHSCan->getTypeClass();
5001  Type::TypeClass RHSClass = RHSCan->getTypeClass();
5002
5003  // We want to consider the two function types to be the same for these
5004  // comparisons, just force one to the other.
5005  if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5006  if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
5007
5008  // Same as above for arrays
5009  if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5010    LHSClass = Type::ConstantArray;
5011  if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5012    RHSClass = Type::ConstantArray;
5013
5014  // ObjCInterfaces are just specialized ObjCObjects.
5015  if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5016  if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5017
5018  // Canonicalize ExtVector -> Vector.
5019  if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5020  if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
5021
5022  // If the canonical type classes don't match.
5023  if (LHSClass != RHSClass) {
5024    // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
5025    // a signed integer type, or an unsigned integer type.
5026    // Compatibility is based on the underlying type, not the promotion
5027    // type.
5028    if (const EnumType* ETy = LHS->getAs<EnumType>()) {
5029      if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5030        return RHS;
5031    }
5032    if (const EnumType* ETy = RHS->getAs<EnumType>()) {
5033      if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5034        return LHS;
5035    }
5036
5037    return QualType();
5038  }
5039
5040  // The canonical type classes match.
5041  switch (LHSClass) {
5042#define TYPE(Class, Base)
5043#define ABSTRACT_TYPE(Class, Base)
5044#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
5045#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5046#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5047#include "clang/AST/TypeNodes.def"
5048    assert(false && "Non-canonical and dependent types shouldn't get here");
5049    return QualType();
5050
5051  case Type::LValueReference:
5052  case Type::RValueReference:
5053  case Type::MemberPointer:
5054    assert(false && "C++ should never be in mergeTypes");
5055    return QualType();
5056
5057  case Type::ObjCInterface:
5058  case Type::IncompleteArray:
5059  case Type::VariableArray:
5060  case Type::FunctionProto:
5061  case Type::ExtVector:
5062    assert(false && "Types are eliminated above");
5063    return QualType();
5064
5065  case Type::Pointer:
5066  {
5067    // Merge two pointer types, while trying to preserve typedef info
5068    QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5069    QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
5070    if (Unqualified) {
5071      LHSPointee = LHSPointee.getUnqualifiedType();
5072      RHSPointee = RHSPointee.getUnqualifiedType();
5073    }
5074    QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5075                                     Unqualified);
5076    if (ResultType.isNull()) return QualType();
5077    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5078      return LHS;
5079    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5080      return RHS;
5081    return getPointerType(ResultType);
5082  }
5083  case Type::BlockPointer:
5084  {
5085    // Merge two block pointer types, while trying to preserve typedef info
5086    QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5087    QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
5088    if (Unqualified) {
5089      LHSPointee = LHSPointee.getUnqualifiedType();
5090      RHSPointee = RHSPointee.getUnqualifiedType();
5091    }
5092    QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5093                                     Unqualified);
5094    if (ResultType.isNull()) return QualType();
5095    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5096      return LHS;
5097    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5098      return RHS;
5099    return getBlockPointerType(ResultType);
5100  }
5101  case Type::ConstantArray:
5102  {
5103    const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5104    const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5105    if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5106      return QualType();
5107
5108    QualType LHSElem = getAsArrayType(LHS)->getElementType();
5109    QualType RHSElem = getAsArrayType(RHS)->getElementType();
5110    if (Unqualified) {
5111      LHSElem = LHSElem.getUnqualifiedType();
5112      RHSElem = RHSElem.getUnqualifiedType();
5113    }
5114
5115    QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
5116    if (ResultType.isNull()) return QualType();
5117    if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5118      return LHS;
5119    if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5120      return RHS;
5121    if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5122                                          ArrayType::ArraySizeModifier(), 0);
5123    if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5124                                          ArrayType::ArraySizeModifier(), 0);
5125    const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5126    const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
5127    if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5128      return LHS;
5129    if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5130      return RHS;
5131    if (LVAT) {
5132      // FIXME: This isn't correct! But tricky to implement because
5133      // the array's size has to be the size of LHS, but the type
5134      // has to be different.
5135      return LHS;
5136    }
5137    if (RVAT) {
5138      // FIXME: This isn't correct! But tricky to implement because
5139      // the array's size has to be the size of RHS, but the type
5140      // has to be different.
5141      return RHS;
5142    }
5143    if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5144    if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
5145    return getIncompleteArrayType(ResultType,
5146                                  ArrayType::ArraySizeModifier(), 0);
5147  }
5148  case Type::FunctionNoProto:
5149    return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
5150  case Type::Record:
5151  case Type::Enum:
5152    return QualType();
5153  case Type::Builtin:
5154    // Only exactly equal builtin types are compatible, which is tested above.
5155    return QualType();
5156  case Type::Complex:
5157    // Distinct complex types are incompatible.
5158    return QualType();
5159  case Type::Vector:
5160    // FIXME: The merged type should be an ExtVector!
5161    if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5162                             RHSCan->getAs<VectorType>()))
5163      return LHS;
5164    return QualType();
5165  case Type::ObjCObject: {
5166    // Check if the types are assignment compatible.
5167    // FIXME: This should be type compatibility, e.g. whether
5168    // "LHS x; RHS x;" at global scope is legal.
5169    const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5170    const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5171    if (canAssignObjCInterfaces(LHSIface, RHSIface))
5172      return LHS;
5173
5174    return QualType();
5175  }
5176  case Type::ObjCObjectPointer: {
5177    if (OfBlockPointer) {
5178      if (canAssignObjCInterfacesInBlockPointer(
5179                                          LHS->getAs<ObjCObjectPointerType>(),
5180                                          RHS->getAs<ObjCObjectPointerType>()))
5181      return LHS;
5182      return QualType();
5183    }
5184    if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5185                                RHS->getAs<ObjCObjectPointerType>()))
5186      return LHS;
5187
5188    return QualType();
5189    }
5190  }
5191
5192  return QualType();
5193}
5194
5195/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5196/// 'RHS' attributes and returns the merged version; including for function
5197/// return types.
5198QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5199  QualType LHSCan = getCanonicalType(LHS),
5200  RHSCan = getCanonicalType(RHS);
5201  // If two types are identical, they are compatible.
5202  if (LHSCan == RHSCan)
5203    return LHS;
5204  if (RHSCan->isFunctionType()) {
5205    if (!LHSCan->isFunctionType())
5206      return QualType();
5207    QualType OldReturnType =
5208      cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5209    QualType NewReturnType =
5210      cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5211    QualType ResReturnType =
5212      mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5213    if (ResReturnType.isNull())
5214      return QualType();
5215    if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5216      // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5217      // In either case, use OldReturnType to build the new function type.
5218      const FunctionType *F = LHS->getAs<FunctionType>();
5219      if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
5220        FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5221        EPI.ExtInfo = getFunctionExtInfo(LHS);
5222        QualType ResultType
5223          = getFunctionType(OldReturnType, FPT->arg_type_begin(),
5224                            FPT->getNumArgs(), EPI);
5225        return ResultType;
5226      }
5227    }
5228    return QualType();
5229  }
5230
5231  // If the qualifiers are different, the types can still be merged.
5232  Qualifiers LQuals = LHSCan.getLocalQualifiers();
5233  Qualifiers RQuals = RHSCan.getLocalQualifiers();
5234  if (LQuals != RQuals) {
5235    // If any of these qualifiers are different, we have a type mismatch.
5236    if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5237        LQuals.getAddressSpace() != RQuals.getAddressSpace())
5238      return QualType();
5239
5240    // Exactly one GC qualifier difference is allowed: __strong is
5241    // okay if the other type has no GC qualifier but is an Objective
5242    // C object pointer (i.e. implicitly strong by default).  We fix
5243    // this by pretending that the unqualified type was actually
5244    // qualified __strong.
5245    Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5246    Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5247    assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5248
5249    if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5250      return QualType();
5251
5252    if (GC_L == Qualifiers::Strong)
5253      return LHS;
5254    if (GC_R == Qualifiers::Strong)
5255      return RHS;
5256    return QualType();
5257  }
5258
5259  if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5260    QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5261    QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5262    QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5263    if (ResQT == LHSBaseQT)
5264      return LHS;
5265    if (ResQT == RHSBaseQT)
5266      return RHS;
5267  }
5268  return QualType();
5269}
5270
5271//===----------------------------------------------------------------------===//
5272//                         Integer Predicates
5273//===----------------------------------------------------------------------===//
5274
5275unsigned ASTContext::getIntWidth(QualType T) {
5276  if (EnumType *ET = dyn_cast<EnumType>(T))
5277    T = ET->getDecl()->getIntegerType();
5278  if (T->isBooleanType())
5279    return 1;
5280  // For builtin types, just use the standard type sizing method
5281  return (unsigned)getTypeSize(T);
5282}
5283
5284QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
5285  assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
5286
5287  // Turn <4 x signed int> -> <4 x unsigned int>
5288  if (const VectorType *VTy = T->getAs<VectorType>())
5289    return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
5290                         VTy->getNumElements(), VTy->getVectorKind());
5291
5292  // For enums, we return the unsigned version of the base type.
5293  if (const EnumType *ETy = T->getAs<EnumType>())
5294    T = ETy->getDecl()->getIntegerType();
5295
5296  const BuiltinType *BTy = T->getAs<BuiltinType>();
5297  assert(BTy && "Unexpected signed integer type");
5298  switch (BTy->getKind()) {
5299  case BuiltinType::Char_S:
5300  case BuiltinType::SChar:
5301    return UnsignedCharTy;
5302  case BuiltinType::Short:
5303    return UnsignedShortTy;
5304  case BuiltinType::Int:
5305    return UnsignedIntTy;
5306  case BuiltinType::Long:
5307    return UnsignedLongTy;
5308  case BuiltinType::LongLong:
5309    return UnsignedLongLongTy;
5310  case BuiltinType::Int128:
5311    return UnsignedInt128Ty;
5312  default:
5313    assert(0 && "Unexpected signed integer type");
5314    return QualType();
5315  }
5316}
5317
5318ExternalASTSource::~ExternalASTSource() { }
5319
5320void ExternalASTSource::PrintStats() { }
5321
5322ASTMutationListener::~ASTMutationListener() { }
5323
5324
5325//===----------------------------------------------------------------------===//
5326//                          Builtin Type Computation
5327//===----------------------------------------------------------------------===//
5328
5329/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
5330/// pointer over the consumed characters.  This returns the resultant type.  If
5331/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5332/// types.  This allows "v2i*" to be parsed as a pointer to a v2i instead of
5333/// a vector of "i*".
5334///
5335/// RequiresICE is filled in on return to indicate whether the value is required
5336/// to be an Integer Constant Expression.
5337static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
5338                                  ASTContext::GetBuiltinTypeError &Error,
5339                                  bool &RequiresICE,
5340                                  bool AllowTypeModifiers) {
5341  // Modifiers.
5342  int HowLong = 0;
5343  bool Signed = false, Unsigned = false;
5344  RequiresICE = false;
5345
5346  // Read the prefixed modifiers first.
5347  bool Done = false;
5348  while (!Done) {
5349    switch (*Str++) {
5350    default: Done = true; --Str; break;
5351    case 'I':
5352      RequiresICE = true;
5353      break;
5354    case 'S':
5355      assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5356      assert(!Signed && "Can't use 'S' modifier multiple times!");
5357      Signed = true;
5358      break;
5359    case 'U':
5360      assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5361      assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5362      Unsigned = true;
5363      break;
5364    case 'L':
5365      assert(HowLong <= 2 && "Can't have LLLL modifier");
5366      ++HowLong;
5367      break;
5368    }
5369  }
5370
5371  QualType Type;
5372
5373  // Read the base type.
5374  switch (*Str++) {
5375  default: assert(0 && "Unknown builtin type letter!");
5376  case 'v':
5377    assert(HowLong == 0 && !Signed && !Unsigned &&
5378           "Bad modifiers used with 'v'!");
5379    Type = Context.VoidTy;
5380    break;
5381  case 'f':
5382    assert(HowLong == 0 && !Signed && !Unsigned &&
5383           "Bad modifiers used with 'f'!");
5384    Type = Context.FloatTy;
5385    break;
5386  case 'd':
5387    assert(HowLong < 2 && !Signed && !Unsigned &&
5388           "Bad modifiers used with 'd'!");
5389    if (HowLong)
5390      Type = Context.LongDoubleTy;
5391    else
5392      Type = Context.DoubleTy;
5393    break;
5394  case 's':
5395    assert(HowLong == 0 && "Bad modifiers used with 's'!");
5396    if (Unsigned)
5397      Type = Context.UnsignedShortTy;
5398    else
5399      Type = Context.ShortTy;
5400    break;
5401  case 'i':
5402    if (HowLong == 3)
5403      Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5404    else if (HowLong == 2)
5405      Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5406    else if (HowLong == 1)
5407      Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5408    else
5409      Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5410    break;
5411  case 'c':
5412    assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5413    if (Signed)
5414      Type = Context.SignedCharTy;
5415    else if (Unsigned)
5416      Type = Context.UnsignedCharTy;
5417    else
5418      Type = Context.CharTy;
5419    break;
5420  case 'b': // boolean
5421    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5422    Type = Context.BoolTy;
5423    break;
5424  case 'z':  // size_t.
5425    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5426    Type = Context.getSizeType();
5427    break;
5428  case 'F':
5429    Type = Context.getCFConstantStringType();
5430    break;
5431  case 'G':
5432    Type = Context.getObjCIdType();
5433    break;
5434  case 'H':
5435    Type = Context.getObjCSelType();
5436    break;
5437  case 'a':
5438    Type = Context.getBuiltinVaListType();
5439    assert(!Type.isNull() && "builtin va list type not initialized!");
5440    break;
5441  case 'A':
5442    // This is a "reference" to a va_list; however, what exactly
5443    // this means depends on how va_list is defined. There are two
5444    // different kinds of va_list: ones passed by value, and ones
5445    // passed by reference.  An example of a by-value va_list is
5446    // x86, where va_list is a char*. An example of by-ref va_list
5447    // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5448    // we want this argument to be a char*&; for x86-64, we want
5449    // it to be a __va_list_tag*.
5450    Type = Context.getBuiltinVaListType();
5451    assert(!Type.isNull() && "builtin va list type not initialized!");
5452    if (Type->isArrayType())
5453      Type = Context.getArrayDecayedType(Type);
5454    else
5455      Type = Context.getLValueReferenceType(Type);
5456    break;
5457  case 'V': {
5458    char *End;
5459    unsigned NumElements = strtoul(Str, &End, 10);
5460    assert(End != Str && "Missing vector size");
5461    Str = End;
5462
5463    QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
5464                                             RequiresICE, false);
5465    assert(!RequiresICE && "Can't require vector ICE");
5466
5467    // TODO: No way to make AltiVec vectors in builtins yet.
5468    Type = Context.getVectorType(ElementType, NumElements,
5469                                 VectorType::GenericVector);
5470    break;
5471  }
5472  case 'X': {
5473    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
5474                                             false);
5475    assert(!RequiresICE && "Can't require complex ICE");
5476    Type = Context.getComplexType(ElementType);
5477    break;
5478  }
5479  case 'P':
5480    Type = Context.getFILEType();
5481    if (Type.isNull()) {
5482      Error = ASTContext::GE_Missing_stdio;
5483      return QualType();
5484    }
5485    break;
5486  case 'J':
5487    if (Signed)
5488      Type = Context.getsigjmp_bufType();
5489    else
5490      Type = Context.getjmp_bufType();
5491
5492    if (Type.isNull()) {
5493      Error = ASTContext::GE_Missing_setjmp;
5494      return QualType();
5495    }
5496    break;
5497  }
5498
5499  // If there are modifiers and if we're allowed to parse them, go for it.
5500  Done = !AllowTypeModifiers;
5501  while (!Done) {
5502    switch (char c = *Str++) {
5503    default: Done = true; --Str; break;
5504    case '*':
5505    case '&': {
5506      // Both pointers and references can have their pointee types
5507      // qualified with an address space.
5508      char *End;
5509      unsigned AddrSpace = strtoul(Str, &End, 10);
5510      if (End != Str && AddrSpace != 0) {
5511        Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5512        Str = End;
5513      }
5514      if (c == '*')
5515        Type = Context.getPointerType(Type);
5516      else
5517        Type = Context.getLValueReferenceType(Type);
5518      break;
5519    }
5520    // FIXME: There's no way to have a built-in with an rvalue ref arg.
5521    case 'C':
5522      Type = Type.withConst();
5523      break;
5524    case 'D':
5525      Type = Context.getVolatileType(Type);
5526      break;
5527    }
5528  }
5529
5530  assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
5531         "Integer constant 'I' type must be an integer");
5532
5533  return Type;
5534}
5535
5536/// GetBuiltinType - Return the type for the specified builtin.
5537QualType ASTContext::GetBuiltinType(unsigned Id,
5538                                    GetBuiltinTypeError &Error,
5539                                    unsigned *IntegerConstantArgs) {
5540  const char *TypeStr = BuiltinInfo.GetTypeString(Id);
5541
5542  llvm::SmallVector<QualType, 8> ArgTypes;
5543
5544  bool RequiresICE = false;
5545  Error = GE_None;
5546  QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
5547                                       RequiresICE, true);
5548  if (Error != GE_None)
5549    return QualType();
5550
5551  assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
5552
5553  while (TypeStr[0] && TypeStr[0] != '.') {
5554    QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
5555    if (Error != GE_None)
5556      return QualType();
5557
5558    // If this argument is required to be an IntegerConstantExpression and the
5559    // caller cares, fill in the bitmask we return.
5560    if (RequiresICE && IntegerConstantArgs)
5561      *IntegerConstantArgs |= 1 << ArgTypes.size();
5562
5563    // Do array -> pointer decay.  The builtin should use the decayed type.
5564    if (Ty->isArrayType())
5565      Ty = getArrayDecayedType(Ty);
5566
5567    ArgTypes.push_back(Ty);
5568  }
5569
5570  assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5571         "'.' should only occur at end of builtin type list!");
5572
5573  // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5574  if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5575    return getFunctionNoProtoType(ResType);
5576
5577  FunctionProtoType::ExtProtoInfo EPI;
5578  EPI.Variadic = (TypeStr[0] == '.');
5579  // FIXME: Should we create noreturn types?
5580
5581  return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
5582}
5583
5584GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5585  GVALinkage External = GVA_StrongExternal;
5586
5587  Linkage L = FD->getLinkage();
5588  if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5589      FD->getType()->getLinkage() == UniqueExternalLinkage)
5590    L = UniqueExternalLinkage;
5591
5592  switch (L) {
5593  case NoLinkage:
5594  case InternalLinkage:
5595  case UniqueExternalLinkage:
5596    return GVA_Internal;
5597
5598  case ExternalLinkage:
5599    switch (FD->getTemplateSpecializationKind()) {
5600    case TSK_Undeclared:
5601    case TSK_ExplicitSpecialization:
5602      External = GVA_StrongExternal;
5603      break;
5604
5605    case TSK_ExplicitInstantiationDefinition:
5606      return GVA_ExplicitTemplateInstantiation;
5607
5608    case TSK_ExplicitInstantiationDeclaration:
5609    case TSK_ImplicitInstantiation:
5610      External = GVA_TemplateInstantiation;
5611      break;
5612    }
5613  }
5614
5615  if (!FD->isInlined())
5616    return External;
5617
5618  if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5619    // GNU or C99 inline semantics. Determine whether this symbol should be
5620    // externally visible.
5621    if (FD->isInlineDefinitionExternallyVisible())
5622      return External;
5623
5624    // C99 inline semantics, where the symbol is not externally visible.
5625    return GVA_C99Inline;
5626  }
5627
5628  // C++0x [temp.explicit]p9:
5629  //   [ Note: The intent is that an inline function that is the subject of
5630  //   an explicit instantiation declaration will still be implicitly
5631  //   instantiated when used so that the body can be considered for
5632  //   inlining, but that no out-of-line copy of the inline function would be
5633  //   generated in the translation unit. -- end note ]
5634  if (FD->getTemplateSpecializationKind()
5635                                       == TSK_ExplicitInstantiationDeclaration)
5636    return GVA_C99Inline;
5637
5638  return GVA_CXXInline;
5639}
5640
5641GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5642  // If this is a static data member, compute the kind of template
5643  // specialization. Otherwise, this variable is not part of a
5644  // template.
5645  TemplateSpecializationKind TSK = TSK_Undeclared;
5646  if (VD->isStaticDataMember())
5647    TSK = VD->getTemplateSpecializationKind();
5648
5649  Linkage L = VD->getLinkage();
5650  if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5651      VD->getType()->getLinkage() == UniqueExternalLinkage)
5652    L = UniqueExternalLinkage;
5653
5654  switch (L) {
5655  case NoLinkage:
5656  case InternalLinkage:
5657  case UniqueExternalLinkage:
5658    return GVA_Internal;
5659
5660  case ExternalLinkage:
5661    switch (TSK) {
5662    case TSK_Undeclared:
5663    case TSK_ExplicitSpecialization:
5664      return GVA_StrongExternal;
5665
5666    case TSK_ExplicitInstantiationDeclaration:
5667      llvm_unreachable("Variable should not be instantiated");
5668      // Fall through to treat this like any other instantiation.
5669
5670    case TSK_ExplicitInstantiationDefinition:
5671      return GVA_ExplicitTemplateInstantiation;
5672
5673    case TSK_ImplicitInstantiation:
5674      return GVA_TemplateInstantiation;
5675    }
5676  }
5677
5678  return GVA_StrongExternal;
5679}
5680
5681bool ASTContext::DeclMustBeEmitted(const Decl *D) {
5682  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5683    if (!VD->isFileVarDecl())
5684      return false;
5685  } else if (!isa<FunctionDecl>(D))
5686    return false;
5687
5688  // Weak references don't produce any output by themselves.
5689  if (D->hasAttr<WeakRefAttr>())
5690    return false;
5691
5692  // Aliases and used decls are required.
5693  if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5694    return true;
5695
5696  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5697    // Forward declarations aren't required.
5698    if (!FD->isThisDeclarationADefinition())
5699      return false;
5700
5701    // Constructors and destructors are required.
5702    if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5703      return true;
5704
5705    // The key function for a class is required.
5706    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5707      const CXXRecordDecl *RD = MD->getParent();
5708      if (MD->isOutOfLine() && RD->isDynamicClass()) {
5709        const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5710        if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5711          return true;
5712      }
5713    }
5714
5715    GVALinkage Linkage = GetGVALinkageForFunction(FD);
5716
5717    // static, static inline, always_inline, and extern inline functions can
5718    // always be deferred.  Normal inline functions can be deferred in C99/C++.
5719    // Implicit template instantiations can also be deferred in C++.
5720    if (Linkage == GVA_Internal  || Linkage == GVA_C99Inline ||
5721        Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
5722      return false;
5723    return true;
5724  }
5725
5726  const VarDecl *VD = cast<VarDecl>(D);
5727  assert(VD->isFileVarDecl() && "Expected file scoped var");
5728
5729  if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
5730    return false;
5731
5732  // Structs that have non-trivial constructors or destructors are required.
5733
5734  // FIXME: Handle references.
5735  if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
5736    if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
5737      if (RD->hasDefinition() &&
5738          (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
5739        return true;
5740    }
5741  }
5742
5743  GVALinkage L = GetGVALinkageForVariable(VD);
5744  if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
5745    if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
5746      return false;
5747  }
5748
5749  return true;
5750}
5751
5752CallingConv ASTContext::getDefaultMethodCallConv() {
5753  // Pass through to the C++ ABI object
5754  return ABI->getDefaultMethodCallConv();
5755}
5756
5757bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) {
5758  // Pass through to the C++ ABI object
5759  return ABI->isNearlyEmpty(RD);
5760}
5761
5762CXXABI::~CXXABI() {}
5763