ASTContext.cpp revision 3e4c6c4c79a03f5cb0c4671d7c282d623c6dc35e
144d362409d5469aed47d19e7908d19bd194493aThomas Graf//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
244d362409d5469aed47d19e7908d19bd194493aThomas Graf//
344d362409d5469aed47d19e7908d19bd194493aThomas Graf//                     The LLVM Compiler Infrastructure
444d362409d5469aed47d19e7908d19bd194493aThomas Graf//
544d362409d5469aed47d19e7908d19bd194493aThomas Graf// This file is distributed under the University of Illinois Open Source
644d362409d5469aed47d19e7908d19bd194493aThomas Graf// License. See LICENSE.TXT for details.
744d362409d5469aed47d19e7908d19bd194493aThomas Graf//
844d362409d5469aed47d19e7908d19bd194493aThomas Graf//===----------------------------------------------------------------------===//
98a3efffa5b3fde252675239914118664d36a2c24Thomas Graf//
1044d362409d5469aed47d19e7908d19bd194493aThomas Graf//  This file implements the ASTContext interface.
1144d362409d5469aed47d19e7908d19bd194493aThomas Graf//
1244d362409d5469aed47d19e7908d19bd194493aThomas Graf//===----------------------------------------------------------------------===//
136782b6f709d03877a5661a4c8d8f8bd1b461f43fThomas Graf
1444d362409d5469aed47d19e7908d19bd194493aThomas Graf#include "clang/AST/ASTContext.h"
154fd5f7cb6627a22bd9f228b4259d5106ae39d535Thomas Graf#include "clang/AST/CharUnits.h"
1644d362409d5469aed47d19e7908d19bd194493aThomas Graf#include "clang/AST/DeclCXX.h"
1744d362409d5469aed47d19e7908d19bd194493aThomas Graf#include "clang/AST/DeclObjC.h"
1844d362409d5469aed47d19e7908d19bd194493aThomas Graf#include "clang/AST/DeclTemplate.h"
191155370f520cb64657e25153255cf7dc1424317fThomas Graf#include "clang/AST/TypeLoc.h"
2044d362409d5469aed47d19e7908d19bd194493aThomas Graf#include "clang/AST/Expr.h"
2144d362409d5469aed47d19e7908d19bd194493aThomas Graf#include "clang/AST/ExprCXX.h"
2244d362409d5469aed47d19e7908d19bd194493aThomas Graf#include "clang/AST/ExternalASTSource.h"
2344d362409d5469aed47d19e7908d19bd194493aThomas Graf#include "clang/AST/ASTMutationListener.h"
2444d362409d5469aed47d19e7908d19bd194493aThomas Graf#include "clang/AST/RecordLayout.h"
2544d362409d5469aed47d19e7908d19bd194493aThomas Graf#include "clang/AST/Mangle.h"
2644d362409d5469aed47d19e7908d19bd194493aThomas Graf#include "clang/Basic/Builtins.h"
2744d362409d5469aed47d19e7908d19bd194493aThomas Graf#include "clang/Basic/SourceManager.h"
281155370f520cb64657e25153255cf7dc1424317fThomas Graf#include "clang/Basic/TargetInfo.h"
2944d362409d5469aed47d19e7908d19bd194493aThomas Graf#include "llvm/ADT/SmallString.h"
3044d362409d5469aed47d19e7908d19bd194493aThomas Graf#include "llvm/ADT/StringExtras.h"
3144d362409d5469aed47d19e7908d19bd194493aThomas Graf#include "llvm/Support/MathExtras.h"
3244d362409d5469aed47d19e7908d19bd194493aThomas Graf#include "llvm/Support/raw_ostream.h"
331155370f520cb64657e25153255cf7dc1424317fThomas Graf#include "CXXABI.h"
3444d362409d5469aed47d19e7908d19bd194493aThomas Graf
3544d362409d5469aed47d19e7908d19bd194493aThomas Grafusing namespace clang;
3644d362409d5469aed47d19e7908d19bd194493aThomas Graf
3744d362409d5469aed47d19e7908d19bd194493aThomas Grafunsigned ASTContext::NumImplicitDefaultConstructors;
381155370f520cb64657e25153255cf7dc1424317fThomas Grafunsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
3944d362409d5469aed47d19e7908d19bd194493aThomas Grafunsigned ASTContext::NumImplicitCopyConstructors;
4044d362409d5469aed47d19e7908d19bd194493aThomas Grafunsigned ASTContext::NumImplicitCopyConstructorsDeclared;
4144d362409d5469aed47d19e7908d19bd194493aThomas Grafunsigned ASTContext::NumImplicitCopyAssignmentOperators;
4244d362409d5469aed47d19e7908d19bd194493aThomas Grafunsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
431155370f520cb64657e25153255cf7dc1424317fThomas Grafunsigned ASTContext::NumImplicitDestructors;
442bdee95a765457fe4206b89d51974ae56e75c588Thomas Grafunsigned ASTContext::NumImplicitDestructorsDeclared;
451155370f520cb64657e25153255cf7dc1424317fThomas Graf
4644d362409d5469aed47d19e7908d19bd194493aThomas Grafenum FloatingRank {
4744d362409d5469aed47d19e7908d19bd194493aThomas Graf  FloatRank, DoubleRank, LongDoubleRank
4844d362409d5469aed47d19e7908d19bd194493aThomas Graf};
4944d362409d5469aed47d19e7908d19bd194493aThomas Graf
501155370f520cb64657e25153255cf7dc1424317fThomas Grafvoid
5144d362409d5469aed47d19e7908d19bd194493aThomas GrafASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
5244d362409d5469aed47d19e7908d19bd194493aThomas Graf                                               TemplateTemplateParmDecl *Parm) {
5344d362409d5469aed47d19e7908d19bd194493aThomas Graf  ID.AddInteger(Parm->getDepth());
5444d362409d5469aed47d19e7908d19bd194493aThomas Graf  ID.AddInteger(Parm->getPosition());
5544d362409d5469aed47d19e7908d19bd194493aThomas Graf  ID.AddBoolean(Parm->isParameterPack());
5644d362409d5469aed47d19e7908d19bd194493aThomas Graf
5744d362409d5469aed47d19e7908d19bd194493aThomas Graf  TemplateParameterList *Params = Parm->getTemplateParameters();
5844d362409d5469aed47d19e7908d19bd194493aThomas Graf  ID.AddInteger(Params->size());
591155370f520cb64657e25153255cf7dc1424317fThomas Graf  for (TemplateParameterList::const_iterator P = Params->begin(),
6044d362409d5469aed47d19e7908d19bd194493aThomas Graf                                          PEnd = Params->end();
6144d362409d5469aed47d19e7908d19bd194493aThomas Graf       P != PEnd; ++P) {
6244d362409d5469aed47d19e7908d19bd194493aThomas Graf    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
6344d362409d5469aed47d19e7908d19bd194493aThomas Graf      ID.AddInteger(0);
641155370f520cb64657e25153255cf7dc1424317fThomas Graf      ID.AddBoolean(TTP->isParameterPack());
6544d362409d5469aed47d19e7908d19bd194493aThomas Graf      continue;
6644d362409d5469aed47d19e7908d19bd194493aThomas Graf    }
671155370f520cb64657e25153255cf7dc1424317fThomas Graf
681155370f520cb64657e25153255cf7dc1424317fThomas Graf    if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
6944d362409d5469aed47d19e7908d19bd194493aThomas Graf      ID.AddInteger(1);
7044d362409d5469aed47d19e7908d19bd194493aThomas Graf      ID.AddBoolean(NTTP->isParameterPack());
7144d362409d5469aed47d19e7908d19bd194493aThomas Graf      ID.AddPointer(NTTP->getType().getAsOpaquePtr());
721155370f520cb64657e25153255cf7dc1424317fThomas Graf      if (NTTP->isExpandedParameterPack()) {
7344d362409d5469aed47d19e7908d19bd194493aThomas Graf        ID.AddBoolean(true);
7444d362409d5469aed47d19e7908d19bd194493aThomas Graf        ID.AddInteger(NTTP->getNumExpansionTypes());
7544d362409d5469aed47d19e7908d19bd194493aThomas Graf        for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I)
7644d362409d5469aed47d19e7908d19bd194493aThomas Graf          ID.AddPointer(NTTP->getExpansionType(I).getAsOpaquePtr());
7744d362409d5469aed47d19e7908d19bd194493aThomas Graf      } else
781155370f520cb64657e25153255cf7dc1424317fThomas Graf        ID.AddBoolean(false);
7944d362409d5469aed47d19e7908d19bd194493aThomas Graf      continue;
8044d362409d5469aed47d19e7908d19bd194493aThomas Graf    }
8144d362409d5469aed47d19e7908d19bd194493aThomas Graf
8244d362409d5469aed47d19e7908d19bd194493aThomas Graf    TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
8344d362409d5469aed47d19e7908d19bd194493aThomas Graf    ID.AddInteger(2);
8444d362409d5469aed47d19e7908d19bd194493aThomas Graf    Profile(ID, TTP);
8544d362409d5469aed47d19e7908d19bd194493aThomas Graf  }
8644d362409d5469aed47d19e7908d19bd194493aThomas Graf}
8744d362409d5469aed47d19e7908d19bd194493aThomas Graf
8844d362409d5469aed47d19e7908d19bd194493aThomas GrafTemplateTemplateParmDecl *
8944d362409d5469aed47d19e7908d19bd194493aThomas GrafASTContext::getCanonicalTemplateTemplateParmDecl(
9044d362409d5469aed47d19e7908d19bd194493aThomas Graf                                          TemplateTemplateParmDecl *TTP) const {
9144d362409d5469aed47d19e7908d19bd194493aThomas Graf  // Check if we already have a canonical template template parameter.
9244d362409d5469aed47d19e7908d19bd194493aThomas Graf  llvm::FoldingSetNodeID ID;
9344d362409d5469aed47d19e7908d19bd194493aThomas Graf  CanonicalTemplateTemplateParm::Profile(ID, TTP);
9444d362409d5469aed47d19e7908d19bd194493aThomas Graf  void *InsertPos = 0;
9544d362409d5469aed47d19e7908d19bd194493aThomas Graf  CanonicalTemplateTemplateParm *Canonical
9644d362409d5469aed47d19e7908d19bd194493aThomas Graf    = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
9744d362409d5469aed47d19e7908d19bd194493aThomas Graf  if (Canonical)
981155370f520cb64657e25153255cf7dc1424317fThomas Graf    return Canonical->getParam();
9944d362409d5469aed47d19e7908d19bd194493aThomas Graf
10044d362409d5469aed47d19e7908d19bd194493aThomas Graf  // Build a canonical template parameter list.
10144d362409d5469aed47d19e7908d19bd194493aThomas Graf  TemplateParameterList *Params = TTP->getTemplateParameters();
10244d362409d5469aed47d19e7908d19bd194493aThomas Graf  llvm::SmallVector<NamedDecl *, 4> CanonParams;
10344d362409d5469aed47d19e7908d19bd194493aThomas Graf  CanonParams.reserve(Params->size());
10444d362409d5469aed47d19e7908d19bd194493aThomas Graf  for (TemplateParameterList::const_iterator P = Params->begin(),
10544d362409d5469aed47d19e7908d19bd194493aThomas Graf                                          PEnd = Params->end();
1061155370f520cb64657e25153255cf7dc1424317fThomas Graf       P != PEnd; ++P) {
10744d362409d5469aed47d19e7908d19bd194493aThomas Graf    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
10844d362409d5469aed47d19e7908d19bd194493aThomas Graf      CanonParams.push_back(
10944d362409d5469aed47d19e7908d19bd194493aThomas Graf                  TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
11044d362409d5469aed47d19e7908d19bd194493aThomas Graf                                               SourceLocation(),
1111155370f520cb64657e25153255cf7dc1424317fThomas Graf                                               SourceLocation(),
1121155370f520cb64657e25153255cf7dc1424317fThomas Graf                                               TTP->getDepth(),
1138a3efffa5b3fde252675239914118664d36a2c24Thomas Graf                                               TTP->getIndex(), 0, false,
11491c330aae51cd6cd44ad730e10dc82724998c810Thomas Graf                                               TTP->isParameterPack()));
11591c330aae51cd6cd44ad730e10dc82724998c810Thomas Graf    else if (NonTypeTemplateParmDecl *NTTP
11644d362409d5469aed47d19e7908d19bd194493aThomas Graf             = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
1171155370f520cb64657e25153255cf7dc1424317fThomas Graf      QualType T = getCanonicalType(NTTP->getType());
118664e1deaeb59ad9db0b2eeec613cf8a93551f567Thomas Graf      TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
11944d362409d5469aed47d19e7908d19bd194493aThomas Graf      NonTypeTemplateParmDecl *Param;
12091c330aae51cd6cd44ad730e10dc82724998c810Thomas Graf      if (NTTP->isExpandedParameterPack()) {
12144d362409d5469aed47d19e7908d19bd194493aThomas Graf        llvm::SmallVector<QualType, 2> ExpandedTypes;
12244d362409d5469aed47d19e7908d19bd194493aThomas Graf        llvm::SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
1231155370f520cb64657e25153255cf7dc1424317fThomas Graf        for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
1241155370f520cb64657e25153255cf7dc1424317fThomas Graf          ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
12591c330aae51cd6cd44ad730e10dc82724998c810Thomas Graf          ExpandedTInfos.push_back(
1268a3efffa5b3fde252675239914118664d36a2c24Thomas Graf                                getTrivialTypeSourceInfo(ExpandedTypes.back()));
12791c330aae51cd6cd44ad730e10dc82724998c810Thomas Graf        }
12891c330aae51cd6cd44ad730e10dc82724998c810Thomas Graf
12944d362409d5469aed47d19e7908d19bd194493aThomas Graf        Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
1301155370f520cb64657e25153255cf7dc1424317fThomas Graf                                                SourceLocation(),
1311155370f520cb64657e25153255cf7dc1424317fThomas Graf                                                SourceLocation(),
13244d362409d5469aed47d19e7908d19bd194493aThomas Graf                                                NTTP->getDepth(),
13391c330aae51cd6cd44ad730e10dc82724998c810Thomas Graf                                                NTTP->getPosition(), 0,
1348a3efffa5b3fde252675239914118664d36a2c24Thomas Graf                                                T,
13591c330aae51cd6cd44ad730e10dc82724998c810Thomas Graf                                                TInfo,
13691c330aae51cd6cd44ad730e10dc82724998c810Thomas Graf                                                ExpandedTypes.data(),
13744d362409d5469aed47d19e7908d19bd194493aThomas Graf                                                ExpandedTypes.size(),
1381155370f520cb64657e25153255cf7dc1424317fThomas Graf                                                ExpandedTInfos.data());
1398a3efffa5b3fde252675239914118664d36a2c24Thomas Graf      } else {
14091c330aae51cd6cd44ad730e10dc82724998c810Thomas Graf        Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
14191c330aae51cd6cd44ad730e10dc82724998c810Thomas Graf                                                SourceLocation(),
14244d362409d5469aed47d19e7908d19bd194493aThomas Graf                                                SourceLocation(),
1431155370f520cb64657e25153255cf7dc1424317fThomas Graf                                                NTTP->getDepth(),
1448a3efffa5b3fde252675239914118664d36a2c24Thomas Graf                                                NTTP->getPosition(), 0,
14591c330aae51cd6cd44ad730e10dc82724998c810Thomas Graf                                                T,
14691c330aae51cd6cd44ad730e10dc82724998c810Thomas Graf                                                NTTP->isParameterPack(),
14744d362409d5469aed47d19e7908d19bd194493aThomas Graf                                                TInfo);
1481155370f520cb64657e25153255cf7dc1424317fThomas Graf      }
14944d362409d5469aed47d19e7908d19bd194493aThomas Graf      CanonParams.push_back(Param);
15044d362409d5469aed47d19e7908d19bd194493aThomas Graf
15191c330aae51cd6cd44ad730e10dc82724998c810Thomas Graf    } else
1521155370f520cb64657e25153255cf7dc1424317fThomas Graf      CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
1531155370f520cb64657e25153255cf7dc1424317fThomas Graf                                           cast<TemplateTemplateParmDecl>(*P)));
15491c330aae51cd6cd44ad730e10dc82724998c810Thomas Graf  }
15591c330aae51cd6cd44ad730e10dc82724998c810Thomas Graf
15644d362409d5469aed47d19e7908d19bd194493aThomas Graf  TemplateTemplateParmDecl *CanonTTP
15744d362409d5469aed47d19e7908d19bd194493aThomas Graf    = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
15844d362409d5469aed47d19e7908d19bd194493aThomas Graf                                       SourceLocation(), TTP->getDepth(),
15944d362409d5469aed47d19e7908d19bd194493aThomas Graf                                       TTP->getPosition(),
1601155370f520cb64657e25153255cf7dc1424317fThomas Graf                                       TTP->isParameterPack(),
16144d362409d5469aed47d19e7908d19bd194493aThomas Graf                                       0,
1621155370f520cb64657e25153255cf7dc1424317fThomas Graf                         TemplateParameterList::Create(*this, SourceLocation(),
16344d362409d5469aed47d19e7908d19bd194493aThomas Graf                                                       SourceLocation(),
1641155370f520cb64657e25153255cf7dc1424317fThomas Graf                                                       CanonParams.data(),
1651155370f520cb64657e25153255cf7dc1424317fThomas Graf                                                       CanonParams.size(),
1661155370f520cb64657e25153255cf7dc1424317fThomas Graf                                                       SourceLocation()));
16744d362409d5469aed47d19e7908d19bd194493aThomas Graf
16844d362409d5469aed47d19e7908d19bd194493aThomas Graf  // Get the new insert position for the node we care about.
1691155370f520cb64657e25153255cf7dc1424317fThomas Graf  Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
17044d362409d5469aed47d19e7908d19bd194493aThomas Graf  assert(Canonical == 0 && "Shouldn't be in the map!");
17144d362409d5469aed47d19e7908d19bd194493aThomas Graf  (void)Canonical;
17244d362409d5469aed47d19e7908d19bd194493aThomas Graf
17344d362409d5469aed47d19e7908d19bd194493aThomas Graf  // Create the canonical template template parameter entry.
17444d362409d5469aed47d19e7908d19bd194493aThomas Graf  Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
17544d362409d5469aed47d19e7908d19bd194493aThomas Graf  CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
17644d362409d5469aed47d19e7908d19bd194493aThomas Graf  return CanonTTP;
17744d362409d5469aed47d19e7908d19bd194493aThomas Graf}
17844d362409d5469aed47d19e7908d19bd194493aThomas Graf
17944d362409d5469aed47d19e7908d19bd194493aThomas GrafCXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
18044d362409d5469aed47d19e7908d19bd194493aThomas Graf  if (!LangOpts.CPlusPlus) return 0;
1811155370f520cb64657e25153255cf7dc1424317fThomas Graf
18244d362409d5469aed47d19e7908d19bd194493aThomas Graf  switch (T.getCXXABI()) {
18344d362409d5469aed47d19e7908d19bd194493aThomas Graf  case CXXABI_ARM:
18444d362409d5469aed47d19e7908d19bd194493aThomas Graf    return CreateARMCXXABI(*this);
18544d362409d5469aed47d19e7908d19bd194493aThomas Graf  case CXXABI_Itanium:
1861155370f520cb64657e25153255cf7dc1424317fThomas Graf    return CreateItaniumCXXABI(*this);
18744d362409d5469aed47d19e7908d19bd194493aThomas Graf  case CXXABI_Microsoft:
18844d362409d5469aed47d19e7908d19bd194493aThomas Graf    return CreateMicrosoftCXXABI(*this);
18944d362409d5469aed47d19e7908d19bd194493aThomas Graf  }
1901155370f520cb64657e25153255cf7dc1424317fThomas Graf  return 0;
1911155370f520cb64657e25153255cf7dc1424317fThomas Graf}
19244d362409d5469aed47d19e7908d19bd194493aThomas Graf
1938a3efffa5b3fde252675239914118664d36a2c24Thomas Grafstatic const LangAS::Map &getAddressSpaceMap(const TargetInfo &T,
19444d362409d5469aed47d19e7908d19bd194493aThomas Graf                                             const LangOptions &LOpts) {
19544d362409d5469aed47d19e7908d19bd194493aThomas Graf  if (LOpts.FakeAddressSpaceMap) {
19644d362409d5469aed47d19e7908d19bd194493aThomas Graf    // The fake address space map must have a distinct entry for each
19744d362409d5469aed47d19e7908d19bd194493aThomas Graf    // language-specific address space.
19844d362409d5469aed47d19e7908d19bd194493aThomas Graf    static const unsigned FakeAddrSpaceMap[] = {
19944d362409d5469aed47d19e7908d19bd194493aThomas Graf      1, // opencl_global
2001155370f520cb64657e25153255cf7dc1424317fThomas Graf      2, // opencl_local
20144d362409d5469aed47d19e7908d19bd194493aThomas Graf      3  // opencl_constant
20244d362409d5469aed47d19e7908d19bd194493aThomas Graf    };
20344d362409d5469aed47d19e7908d19bd194493aThomas Graf    return FakeAddrSpaceMap;
20444d362409d5469aed47d19e7908d19bd194493aThomas Graf  } else {
2051155370f520cb64657e25153255cf7dc1424317fThomas Graf    return T.getAddressSpaceMap();
20644d362409d5469aed47d19e7908d19bd194493aThomas Graf  }
20744d362409d5469aed47d19e7908d19bd194493aThomas Graf}
20844d362409d5469aed47d19e7908d19bd194493aThomas Graf
20944d362409d5469aed47d19e7908d19bd194493aThomas GrafASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
2101155370f520cb64657e25153255cf7dc1424317fThomas Graf                       const TargetInfo &t,
21144d362409d5469aed47d19e7908d19bd194493aThomas Graf                       IdentifierTable &idents, SelectorTable &sels,
2121155370f520cb64657e25153255cf7dc1424317fThomas Graf                       Builtin::Context &builtins,
21344d362409d5469aed47d19e7908d19bd194493aThomas Graf                       unsigned size_reserve) :
21444d362409d5469aed47d19e7908d19bd194493aThomas Graf  FunctionProtoTypes(this_()),
21544d362409d5469aed47d19e7908d19bd194493aThomas Graf  TemplateSpecializationTypes(this_()),
21644d362409d5469aed47d19e7908d19bd194493aThomas Graf  DependentTemplateSpecializationTypes(this_()),
2171155370f520cb64657e25153255cf7dc1424317fThomas Graf  GlobalNestedNameSpecifier(0), IsInt128Installed(false),
21844d362409d5469aed47d19e7908d19bd194493aThomas Graf  CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
2198a3efffa5b3fde252675239914118664d36a2c24Thomas Graf  ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
22044d362409d5469aed47d19e7908d19bd194493aThomas Graf  sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
22127c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto  cudaConfigureCallDecl(0),
22244d362409d5469aed47d19e7908d19bd194493aThomas Graf  NullTypeSourceInfo(QualType()),
22344d362409d5469aed47d19e7908d19bd194493aThomas Graf  SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)),
22444d362409d5469aed47d19e7908d19bd194493aThomas Graf  AddrSpaceMap(getAddressSpaceMap(t, LOpts)), Target(t),
22544d362409d5469aed47d19e7908d19bd194493aThomas Graf  Idents(idents), Selectors(sels),
22644d362409d5469aed47d19e7908d19bd194493aThomas Graf  BuiltinInfo(builtins),
22744d362409d5469aed47d19e7908d19bd194493aThomas Graf  DeclarationNames(*this),
2281155370f520cb64657e25153255cf7dc1424317fThomas Graf  ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
22944d362409d5469aed47d19e7908d19bd194493aThomas Graf  LastSDM(0, 0),
23027c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto  UniqueBlockByRefTypeID(0) {
23127c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto  ObjCIdRedefinitionType = QualType();
23244d362409d5469aed47d19e7908d19bd194493aThomas Graf  ObjCClassRedefinitionType = QualType();
23344d362409d5469aed47d19e7908d19bd194493aThomas Graf  ObjCSelRedefinitionType = QualType();
23444d362409d5469aed47d19e7908d19bd194493aThomas Graf  if (size_reserve > 0) Types.reserve(size_reserve);
235256d7e723c0ff402422d3501866e9301b3f64c0fThomas Graf  TUDecl = TranslationUnitDecl::Create(*this);
23644d362409d5469aed47d19e7908d19bd194493aThomas Graf  InitBuiltinTypes();
23744d362409d5469aed47d19e7908d19bd194493aThomas Graf}
23844d362409d5469aed47d19e7908d19bd194493aThomas Graf
23944d362409d5469aed47d19e7908d19bd194493aThomas GrafASTContext::~ASTContext() {
2401155370f520cb64657e25153255cf7dc1424317fThomas Graf  // Release the DenseMaps associated with DeclContext objects.
24144d362409d5469aed47d19e7908d19bd194493aThomas Graf  // FIXME: Is this the ideal solution?
24227c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto  ReleaseDeclContextMaps();
24327c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto
24444d362409d5469aed47d19e7908d19bd194493aThomas Graf  // Call all of the deallocation functions.
24544d362409d5469aed47d19e7908d19bd194493aThomas Graf  for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
24644d362409d5469aed47d19e7908d19bd194493aThomas Graf    Deallocations[I].first(Deallocations[I].second);
2471155370f520cb64657e25153255cf7dc1424317fThomas Graf
24844d362409d5469aed47d19e7908d19bd194493aThomas Graf  // Release all of the memory associated with overridden C++ methods.
24944d362409d5469aed47d19e7908d19bd194493aThomas Graf  for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
25044d362409d5469aed47d19e7908d19bd194493aThomas Graf         OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
25144d362409d5469aed47d19e7908d19bd194493aThomas Graf       OM != OMEnd; ++OM)
25244d362409d5469aed47d19e7908d19bd194493aThomas Graf    OM->second.Destroy();
25344d362409d5469aed47d19e7908d19bd194493aThomas Graf
25444d362409d5469aed47d19e7908d19bd194493aThomas Graf  // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
25544d362409d5469aed47d19e7908d19bd194493aThomas Graf  // because they can contain DenseMaps.
25644d362409d5469aed47d19e7908d19bd194493aThomas Graf  for (llvm::DenseMap<const ObjCContainerDecl*,
25744d362409d5469aed47d19e7908d19bd194493aThomas Graf       const ASTRecordLayout*>::iterator
25844d362409d5469aed47d19e7908d19bd194493aThomas Graf       I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
25944d362409d5469aed47d19e7908d19bd194493aThomas Graf    // Increment in loop to prevent using deallocated memory.
26044d362409d5469aed47d19e7908d19bd194493aThomas Graf    if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
26144d362409d5469aed47d19e7908d19bd194493aThomas Graf      R->Destroy(*this);
26244d362409d5469aed47d19e7908d19bd194493aThomas Graf
26344d362409d5469aed47d19e7908d19bd194493aThomas Graf  for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
26444d362409d5469aed47d19e7908d19bd194493aThomas Graf       I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
26544d362409d5469aed47d19e7908d19bd194493aThomas Graf    // Increment in loop to prevent using deallocated memory.
26644d362409d5469aed47d19e7908d19bd194493aThomas Graf    if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
26744d362409d5469aed47d19e7908d19bd194493aThomas Graf      R->Destroy(*this);
26844d362409d5469aed47d19e7908d19bd194493aThomas Graf  }
2691155370f520cb64657e25153255cf7dc1424317fThomas Graf
27044d362409d5469aed47d19e7908d19bd194493aThomas Graf  for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
27144d362409d5469aed47d19e7908d19bd194493aThomas Graf                                                    AEnd = DeclAttrs.end();
27227c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto       A != AEnd; ++A)
27327c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto    A->second->~AttrVec();
27444d362409d5469aed47d19e7908d19bd194493aThomas Graf}
27527c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto
27627c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramotovoid ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
27727c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto  Deallocations.push_back(std::make_pair(Callback, Data));
27827c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto}
27927c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto
28027c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramotovoid
28127c505eb89f7a689416f822e26c0ccea0b351ba3Karl HiramotoASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
28227c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto  ExternalSource.reset(Source.take());
28327c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto}
28427c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto
28527c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramotovoid ASTContext::PrintStats() const {
28627c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto  fprintf(stderr, "*** AST Context Stats:\n");
28727c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto  fprintf(stderr, "  %d types total.\n", (int)Types.size());
28827c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto
28927c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto  unsigned counts[] = {
29027c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto#define TYPE(Name, Parent) 0,
29127c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto#define ABSTRACT_TYPE(Name, Parent)
29244d362409d5469aed47d19e7908d19bd194493aThomas Graf#include "clang/AST/TypeNodes.def"
29344d362409d5469aed47d19e7908d19bd194493aThomas Graf    0 // Extra
29444d362409d5469aed47d19e7908d19bd194493aThomas Graf  };
29544d362409d5469aed47d19e7908d19bd194493aThomas Graf
29644d362409d5469aed47d19e7908d19bd194493aThomas Graf  for (unsigned i = 0, e = Types.size(); i != e; ++i) {
2971155370f520cb64657e25153255cf7dc1424317fThomas Graf    Type *T = Types[i];
29844d362409d5469aed47d19e7908d19bd194493aThomas Graf    counts[(unsigned)T->getTypeClass()]++;
29944d362409d5469aed47d19e7908d19bd194493aThomas Graf  }
3001155370f520cb64657e25153255cf7dc1424317fThomas Graf
30144d362409d5469aed47d19e7908d19bd194493aThomas Graf  unsigned Idx = 0;
30244d362409d5469aed47d19e7908d19bd194493aThomas Graf  unsigned TotalBytes = 0;
3031155370f520cb64657e25153255cf7dc1424317fThomas Graf#define TYPE(Name, Parent)                                              \
30427c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto  if (counts[Idx])                                                      \
3052bdee95a765457fe4206b89d51974ae56e75c588Thomas Graf    fprintf(stderr, "    %d %s types\n", (int)counts[Idx], #Name);      \
3062bdee95a765457fe4206b89d51974ae56e75c588Thomas Graf  TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
3072bdee95a765457fe4206b89d51974ae56e75c588Thomas Graf  ++Idx;
3082bdee95a765457fe4206b89d51974ae56e75c588Thomas Graf#define ABSTRACT_TYPE(Name, Parent)
30927c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto#include "clang/AST/TypeNodes.def"
31027c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto
31127c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto  fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
31227c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto
31327c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto  // Implicit special member functions.
31427c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto  fprintf(stderr, "  %u/%u implicit default constructors created\n",
31527c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto          NumImplicitDefaultConstructorsDeclared,
31627c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto          NumImplicitDefaultConstructors);
31727c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto  fprintf(stderr, "  %u/%u implicit copy constructors created\n",
31827c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto          NumImplicitCopyConstructorsDeclared,
31927c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto          NumImplicitCopyConstructors);
32027c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto  fprintf(stderr, "  %u/%u implicit copy assignment operators created\n",
32127c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto          NumImplicitCopyAssignmentOperatorsDeclared,
32227c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto          NumImplicitCopyAssignmentOperators);
32327c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto  fprintf(stderr, "  %u/%u implicit destructors created\n",
32427c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto          NumImplicitDestructorsDeclared, NumImplicitDestructors);
32527c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto
32627c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto  if (ExternalSource.get()) {
32727c505eb89f7a689416f822e26c0ccea0b351ba3Karl Hiramoto    fprintf(stderr, "\n");
32844d362409d5469aed47d19e7908d19bd194493aThomas Graf    ExternalSource->PrintStats();
32944d362409d5469aed47d19e7908d19bd194493aThomas Graf  }
3301155370f520cb64657e25153255cf7dc1424317fThomas Graf
33144d362409d5469aed47d19e7908d19bd194493aThomas Graf  BumpAlloc.PrintStats();
3321155370f520cb64657e25153255cf7dc1424317fThomas Graf}
33344d362409d5469aed47d19e7908d19bd194493aThomas Graf
33444d362409d5469aed47d19e7908d19bd194493aThomas Graf
33544d362409d5469aed47d19e7908d19bd194493aThomas Grafvoid ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
33644d362409d5469aed47d19e7908d19bd194493aThomas Graf  BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
3371155370f520cb64657e25153255cf7dc1424317fThomas Graf  R = CanQualType::CreateUnsafe(QualType(Ty, 0));
33844d362409d5469aed47d19e7908d19bd194493aThomas Graf  Types.push_back(Ty);
33944d362409d5469aed47d19e7908d19bd194493aThomas Graf}
34044d362409d5469aed47d19e7908d19bd194493aThomas Graf
34144d362409d5469aed47d19e7908d19bd194493aThomas Grafvoid ASTContext::InitBuiltinTypes() {
34244d362409d5469aed47d19e7908d19bd194493aThomas Graf  assert(VoidTy.isNull() && "Context reinitialized?");
34344d362409d5469aed47d19e7908d19bd194493aThomas Graf
34444d362409d5469aed47d19e7908d19bd194493aThomas Graf  // C99 6.2.5p19.
34544d362409d5469aed47d19e7908d19bd194493aThomas Graf  InitBuiltinType(VoidTy,              BuiltinType::Void);
34644d362409d5469aed47d19e7908d19bd194493aThomas Graf
34744d362409d5469aed47d19e7908d19bd194493aThomas Graf  // C99 6.2.5p2.
34844d362409d5469aed47d19e7908d19bd194493aThomas Graf  InitBuiltinType(BoolTy,              BuiltinType::Bool);
3491155370f520cb64657e25153255cf7dc1424317fThomas Graf  // C99 6.2.5p3.
35044d362409d5469aed47d19e7908d19bd194493aThomas Graf  if (LangOpts.CharIsSigned)
35144d362409d5469aed47d19e7908d19bd194493aThomas Graf    InitBuiltinType(CharTy,            BuiltinType::Char_S);
35244d362409d5469aed47d19e7908d19bd194493aThomas Graf  else
35344d362409d5469aed47d19e7908d19bd194493aThomas Graf    InitBuiltinType(CharTy,            BuiltinType::Char_U);
35444d362409d5469aed47d19e7908d19bd194493aThomas Graf  // C99 6.2.5p4.
35544d362409d5469aed47d19e7908d19bd194493aThomas Graf  InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
35644d362409d5469aed47d19e7908d19bd194493aThomas Graf  InitBuiltinType(ShortTy,             BuiltinType::Short);
3578a3efffa5b3fde252675239914118664d36a2c24Thomas Graf  InitBuiltinType(IntTy,               BuiltinType::Int);
35844d362409d5469aed47d19e7908d19bd194493aThomas Graf  InitBuiltinType(LongTy,              BuiltinType::Long);
3596de17f3308cfd53ad922d144a1b28ddd962d6678Thomas Graf  InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
3606de17f3308cfd53ad922d144a1b28ddd962d6678Thomas Graf
3616de17f3308cfd53ad922d144a1b28ddd962d6678Thomas Graf  // C99 6.2.5p6.
3626de17f3308cfd53ad922d144a1b28ddd962d6678Thomas Graf  InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
3636de17f3308cfd53ad922d144a1b28ddd962d6678Thomas Graf  InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
3646de17f3308cfd53ad922d144a1b28ddd962d6678Thomas Graf  InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
36544d362409d5469aed47d19e7908d19bd194493aThomas Graf  InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
3661155370f520cb64657e25153255cf7dc1424317fThomas Graf  InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
3676de17f3308cfd53ad922d144a1b28ddd962d6678Thomas Graf
36844d362409d5469aed47d19e7908d19bd194493aThomas Graf  // C99 6.2.5p10.
36944d362409d5469aed47d19e7908d19bd194493aThomas Graf  InitBuiltinType(FloatTy,             BuiltinType::Float);
37044d362409d5469aed47d19e7908d19bd194493aThomas Graf  InitBuiltinType(DoubleTy,            BuiltinType::Double);
37144d362409d5469aed47d19e7908d19bd194493aThomas Graf  InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
37244d362409d5469aed47d19e7908d19bd194493aThomas Graf
37344d362409d5469aed47d19e7908d19bd194493aThomas Graf  // GNU extension, 128-bit integers.
37444d362409d5469aed47d19e7908d19bd194493aThomas Graf  InitBuiltinType(Int128Ty,            BuiltinType::Int128);
37544d362409d5469aed47d19e7908d19bd194493aThomas Graf  InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
37644d362409d5469aed47d19e7908d19bd194493aThomas Graf
37744d362409d5469aed47d19e7908d19bd194493aThomas Graf  if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
37844d362409d5469aed47d19e7908d19bd194493aThomas Graf    if (TargetInfo::isTypeSigned(Target.getWCharType()))
37944d362409d5469aed47d19e7908d19bd194493aThomas Graf      InitBuiltinType(WCharTy,           BuiltinType::WChar_S);
38044d362409d5469aed47d19e7908d19bd194493aThomas Graf    else  // -fshort-wchar makes wchar_t be unsigned.
38144d362409d5469aed47d19e7908d19bd194493aThomas Graf      InitBuiltinType(WCharTy,           BuiltinType::WChar_U);
3821155370f520cb64657e25153255cf7dc1424317fThomas Graf  } else // C99
38344d362409d5469aed47d19e7908d19bd194493aThomas Graf    WCharTy = getFromTargetType(Target.getWCharType());
38444d362409d5469aed47d19e7908d19bd194493aThomas Graf
38544d362409d5469aed47d19e7908d19bd194493aThomas Graf  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
38644d362409d5469aed47d19e7908d19bd194493aThomas Graf    InitBuiltinType(Char16Ty,           BuiltinType::Char16);
38744d362409d5469aed47d19e7908d19bd194493aThomas Graf  else // C99
38844d362409d5469aed47d19e7908d19bd194493aThomas Graf    Char16Ty = getFromTargetType(Target.getChar16Type());
38944d362409d5469aed47d19e7908d19bd194493aThomas Graf
39044d362409d5469aed47d19e7908d19bd194493aThomas Graf  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
39144d362409d5469aed47d19e7908d19bd194493aThomas Graf    InitBuiltinType(Char32Ty,           BuiltinType::Char32);
39244d362409d5469aed47d19e7908d19bd194493aThomas Graf  else // C99
39344d362409d5469aed47d19e7908d19bd194493aThomas Graf    Char32Ty = getFromTargetType(Target.getChar32Type());
39444d362409d5469aed47d19e7908d19bd194493aThomas Graf
39544d362409d5469aed47d19e7908d19bd194493aThomas Graf  // Placeholder type for type-dependent expressions whose type is
39644d362409d5469aed47d19e7908d19bd194493aThomas Graf  // completely unknown. No code should ever check a type against
39744d362409d5469aed47d19e7908d19bd194493aThomas Graf  // DependentTy and users should never see it; however, it is here to
39844d362409d5469aed47d19e7908d19bd194493aThomas Graf  // help diagnose failures to properly check for type-dependent
3991155370f520cb64657e25153255cf7dc1424317fThomas Graf  // expressions.
40044d362409d5469aed47d19e7908d19bd194493aThomas Graf  InitBuiltinType(DependentTy,         BuiltinType::Dependent);
40144d362409d5469aed47d19e7908d19bd194493aThomas Graf
40244d362409d5469aed47d19e7908d19bd194493aThomas Graf  // Placeholder type for functions.
40344d362409d5469aed47d19e7908d19bd194493aThomas Graf  InitBuiltinType(OverloadTy,          BuiltinType::Overload);
40444d362409d5469aed47d19e7908d19bd194493aThomas Graf
40544d362409d5469aed47d19e7908d19bd194493aThomas Graf  // Placeholder type for bound members.
40644d362409d5469aed47d19e7908d19bd194493aThomas Graf  InitBuiltinType(BoundMemberTy,       BuiltinType::BoundMember);
40744d362409d5469aed47d19e7908d19bd194493aThomas Graf
40844d362409d5469aed47d19e7908d19bd194493aThomas Graf  // "any" type; useful for debugger-like clients.
40944d362409d5469aed47d19e7908d19bd194493aThomas Graf  InitBuiltinType(UnknownAnyTy,        BuiltinType::UnknownAny);
41044d362409d5469aed47d19e7908d19bd194493aThomas Graf
41144d362409d5469aed47d19e7908d19bd194493aThomas Graf  // C99 6.2.5p11.
41244d362409d5469aed47d19e7908d19bd194493aThomas Graf  FloatComplexTy      = getComplexType(FloatTy);
41344d362409d5469aed47d19e7908d19bd194493aThomas Graf  DoubleComplexTy     = getComplexType(DoubleTy);
41444d362409d5469aed47d19e7908d19bd194493aThomas Graf  LongDoubleComplexTy = getComplexType(LongDoubleTy);
41544d362409d5469aed47d19e7908d19bd194493aThomas Graf
41644d362409d5469aed47d19e7908d19bd194493aThomas Graf  BuiltinVaListType = QualType();
4171155370f520cb64657e25153255cf7dc1424317fThomas Graf
41844d362409d5469aed47d19e7908d19bd194493aThomas Graf  // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
41944d362409d5469aed47d19e7908d19bd194493aThomas Graf  ObjCIdTypedefType = QualType();
42044d362409d5469aed47d19e7908d19bd194493aThomas Graf  ObjCClassTypedefType = QualType();
42144d362409d5469aed47d19e7908d19bd194493aThomas Graf  ObjCSelTypedefType = QualType();
42244d362409d5469aed47d19e7908d19bd194493aThomas Graf
42344d362409d5469aed47d19e7908d19bd194493aThomas Graf  // Builtin types for 'id', 'Class', and 'SEL'.
424b7c5bf98c4079304f78242d8b3c65451efc12b77Thomas Graf  InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
42544d362409d5469aed47d19e7908d19bd194493aThomas Graf  InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
4261155370f520cb64657e25153255cf7dc1424317fThomas Graf  InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
42744d362409d5469aed47d19e7908d19bd194493aThomas Graf
42844d362409d5469aed47d19e7908d19bd194493aThomas Graf  ObjCConstantStringType = QualType();
42944d362409d5469aed47d19e7908d19bd194493aThomas Graf
43044d362409d5469aed47d19e7908d19bd194493aThomas Graf  // void * type
43144d362409d5469aed47d19e7908d19bd194493aThomas Graf  VoidPtrTy = getPointerType(VoidTy);
4321155370f520cb64657e25153255cf7dc1424317fThomas Graf
43344d362409d5469aed47d19e7908d19bd194493aThomas Graf  // nullptr type (C++0x 2.14.7)
43444d362409d5469aed47d19e7908d19bd194493aThomas Graf  InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
43544d362409d5469aed47d19e7908d19bd194493aThomas Graf}
43644d362409d5469aed47d19e7908d19bd194493aThomas Graf
43744d362409d5469aed47d19e7908d19bd194493aThomas GrafDiagnostic &ASTContext::getDiagnostics() const {
43844d362409d5469aed47d19e7908d19bd194493aThomas Graf  return SourceMgr.getDiagnostics();
43944d362409d5469aed47d19e7908d19bd194493aThomas Graf}
44044d362409d5469aed47d19e7908d19bd194493aThomas Graf
44144d362409d5469aed47d19e7908d19bd194493aThomas GrafAttrVec& ASTContext::getDeclAttrs(const Decl *D) {
44244d362409d5469aed47d19e7908d19bd194493aThomas Graf  AttrVec *&Result = DeclAttrs[D];
44344d362409d5469aed47d19e7908d19bd194493aThomas Graf  if (!Result) {
44444d362409d5469aed47d19e7908d19bd194493aThomas Graf    void *Mem = Allocate(sizeof(AttrVec));
4458a3efffa5b3fde252675239914118664d36a2c24Thomas Graf    Result = new (Mem) AttrVec;
44644d362409d5469aed47d19e7908d19bd194493aThomas Graf  }
44744d362409d5469aed47d19e7908d19bd194493aThomas Graf
44844d362409d5469aed47d19e7908d19bd194493aThomas Graf  return *Result;
44944d362409d5469aed47d19e7908d19bd194493aThomas Graf}
45044d362409d5469aed47d19e7908d19bd194493aThomas Graf
45144d362409d5469aed47d19e7908d19bd194493aThomas Graf/// \brief Erase the attributes corresponding to the given declaration.
45244d362409d5469aed47d19e7908d19bd194493aThomas Grafvoid ASTContext::eraseDeclAttrs(const Decl *D) {
45344d362409d5469aed47d19e7908d19bd194493aThomas Graf  llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
45444d362409d5469aed47d19e7908d19bd194493aThomas Graf  if (Pos != DeclAttrs.end()) {
45544d362409d5469aed47d19e7908d19bd194493aThomas Graf    Pos->second->~AttrVec();
45644d362409d5469aed47d19e7908d19bd194493aThomas Graf    DeclAttrs.erase(Pos);
45744d362409d5469aed47d19e7908d19bd194493aThomas Graf  }
45844d362409d5469aed47d19e7908d19bd194493aThomas Graf}
45944d362409d5469aed47d19e7908d19bd194493aThomas Graf
46044d362409d5469aed47d19e7908d19bd194493aThomas GrafMemberSpecializationInfo *
46144d362409d5469aed47d19e7908d19bd194493aThomas GrafASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
46244d362409d5469aed47d19e7908d19bd194493aThomas Graf  assert(Var->isStaticDataMember() && "Not a static data member");
46344d362409d5469aed47d19e7908d19bd194493aThomas Graf  llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
46444d362409d5469aed47d19e7908d19bd194493aThomas Graf    = InstantiatedFromStaticDataMember.find(Var);
46544d362409d5469aed47d19e7908d19bd194493aThomas Graf  if (Pos == InstantiatedFromStaticDataMember.end())
46644d362409d5469aed47d19e7908d19bd194493aThomas Graf    return 0;
46744d362409d5469aed47d19e7908d19bd194493aThomas Graf
46844d362409d5469aed47d19e7908d19bd194493aThomas Graf  return Pos->second;
4698a3efffa5b3fde252675239914118664d36a2c24Thomas Graf}
47044d362409d5469aed47d19e7908d19bd194493aThomas Graf
47144d362409d5469aed47d19e7908d19bd194493aThomas Grafvoid
47244d362409d5469aed47d19e7908d19bd194493aThomas GrafASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
47344d362409d5469aed47d19e7908d19bd194493aThomas Graf                                                TemplateSpecializationKind TSK,
47444d362409d5469aed47d19e7908d19bd194493aThomas Graf                                          SourceLocation PointOfInstantiation) {
47544d362409d5469aed47d19e7908d19bd194493aThomas Graf  assert(Inst->isStaticDataMember() && "Not a static data member");
47644d362409d5469aed47d19e7908d19bd194493aThomas Graf  assert(Tmpl->isStaticDataMember() && "Not a static data member");
47744d362409d5469aed47d19e7908d19bd194493aThomas Graf  assert(!InstantiatedFromStaticDataMember[Inst] &&
47844d362409d5469aed47d19e7908d19bd194493aThomas Graf         "Already noted what static data member was instantiated from");
47944d362409d5469aed47d19e7908d19bd194493aThomas Graf  InstantiatedFromStaticDataMember[Inst]
48044d362409d5469aed47d19e7908d19bd194493aThomas Graf    = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
48144d362409d5469aed47d19e7908d19bd194493aThomas Graf}
48244d362409d5469aed47d19e7908d19bd194493aThomas Graf
48344d362409d5469aed47d19e7908d19bd194493aThomas GrafNamedDecl *
48444d362409d5469aed47d19e7908d19bd194493aThomas GrafASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
48544d362409d5469aed47d19e7908d19bd194493aThomas Graf  llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
48644d362409d5469aed47d19e7908d19bd194493aThomas Graf    = InstantiatedFromUsingDecl.find(UUD);
48744d362409d5469aed47d19e7908d19bd194493aThomas Graf  if (Pos == InstantiatedFromUsingDecl.end())
48844d362409d5469aed47d19e7908d19bd194493aThomas Graf    return 0;
48944d362409d5469aed47d19e7908d19bd194493aThomas Graf
49044d362409d5469aed47d19e7908d19bd194493aThomas Graf  return Pos->second;
49144d362409d5469aed47d19e7908d19bd194493aThomas Graf}
49244d362409d5469aed47d19e7908d19bd194493aThomas Graf
49344d362409d5469aed47d19e7908d19bd194493aThomas Grafvoid
49444d362409d5469aed47d19e7908d19bd194493aThomas GrafASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
49544d362409d5469aed47d19e7908d19bd194493aThomas Graf  assert((isa<UsingDecl>(Pattern) ||
49644d362409d5469aed47d19e7908d19bd194493aThomas Graf          isa<UnresolvedUsingValueDecl>(Pattern) ||
49744d362409d5469aed47d19e7908d19bd194493aThomas Graf          isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
49844d362409d5469aed47d19e7908d19bd194493aThomas Graf         "pattern decl is not a using decl");
49944d362409d5469aed47d19e7908d19bd194493aThomas Graf  assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
50044d362409d5469aed47d19e7908d19bd194493aThomas Graf  InstantiatedFromUsingDecl[Inst] = Pattern;
50144d362409d5469aed47d19e7908d19bd194493aThomas Graf}
50244d362409d5469aed47d19e7908d19bd194493aThomas Graf
50344d362409d5469aed47d19e7908d19bd194493aThomas GrafUsingShadowDecl *
50444d362409d5469aed47d19e7908d19bd194493aThomas GrafASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
50544d362409d5469aed47d19e7908d19bd194493aThomas Graf  llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
5061155370f520cb64657e25153255cf7dc1424317fThomas Graf    = InstantiatedFromUsingShadowDecl.find(Inst);
50744d362409d5469aed47d19e7908d19bd194493aThomas Graf  if (Pos == InstantiatedFromUsingShadowDecl.end())
50844d362409d5469aed47d19e7908d19bd194493aThomas Graf    return 0;
50923ee46ef7115c2e311c36e43a833e6c3deada18aThomas Graf
51044d362409d5469aed47d19e7908d19bd194493aThomas Graf  return Pos->second;
51144d362409d5469aed47d19e7908d19bd194493aThomas Graf}
51244d362409d5469aed47d19e7908d19bd194493aThomas Graf
51344d362409d5469aed47d19e7908d19bd194493aThomas Grafvoid
51444d362409d5469aed47d19e7908d19bd194493aThomas GrafASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
51544d362409d5469aed47d19e7908d19bd194493aThomas Graf                                               UsingShadowDecl *Pattern) {
5161155370f520cb64657e25153255cf7dc1424317fThomas Graf  assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
51744d362409d5469aed47d19e7908d19bd194493aThomas Graf  InstantiatedFromUsingShadowDecl[Inst] = Pattern;
5181155370f520cb64657e25153255cf7dc1424317fThomas Graf}
51944d362409d5469aed47d19e7908d19bd194493aThomas Graf
5201155370f520cb64657e25153255cf7dc1424317fThomas GrafFieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
52144d362409d5469aed47d19e7908d19bd194493aThomas Graf  llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
52244d362409d5469aed47d19e7908d19bd194493aThomas Graf    = InstantiatedFromUnnamedFieldDecl.find(Field);
52344d362409d5469aed47d19e7908d19bd194493aThomas Graf  if (Pos == InstantiatedFromUnnamedFieldDecl.end())
52444d362409d5469aed47d19e7908d19bd194493aThomas Graf    return 0;
5251155370f520cb64657e25153255cf7dc1424317fThomas Graf
52644d362409d5469aed47d19e7908d19bd194493aThomas Graf  return Pos->second;
52744d362409d5469aed47d19e7908d19bd194493aThomas Graf}
52844d362409d5469aed47d19e7908d19bd194493aThomas Graf
5291155370f520cb64657e25153255cf7dc1424317fThomas Grafvoid ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
53044d362409d5469aed47d19e7908d19bd194493aThomas Graf                                                     FieldDecl *Tmpl) {
53123ee46ef7115c2e311c36e43a833e6c3deada18aThomas Graf  assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
53244d362409d5469aed47d19e7908d19bd194493aThomas Graf  assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
53344d362409d5469aed47d19e7908d19bd194493aThomas Graf  assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
5348a3efffa5b3fde252675239914118664d36a2c24Thomas Graf         "Already noted what unnamed field was instantiated from");
53544d362409d5469aed47d19e7908d19bd194493aThomas Graf
53644d362409d5469aed47d19e7908d19bd194493aThomas Graf  InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
53744d362409d5469aed47d19e7908d19bd194493aThomas Graf}
5381155370f520cb64657e25153255cf7dc1424317fThomas Graf
53944d362409d5469aed47d19e7908d19bd194493aThomas Grafbool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
54044d362409d5469aed47d19e7908d19bd194493aThomas Graf                                    const FieldDecl *LastFD) const {
54144d362409d5469aed47d19e7908d19bd194493aThomas Graf  return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
54244d362409d5469aed47d19e7908d19bd194493aThomas Graf          FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() == 0);
54344d362409d5469aed47d19e7908d19bd194493aThomas Graf
54444d362409d5469aed47d19e7908d19bd194493aThomas Graf}
54544d362409d5469aed47d19e7908d19bd194493aThomas Graf
54644d362409d5469aed47d19e7908d19bd194493aThomas Grafbool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
54744d362409d5469aed47d19e7908d19bd194493aThomas Graf                                             const FieldDecl *LastFD) const {
54844d362409d5469aed47d19e7908d19bd194493aThomas Graf  return (FD->isBitField() && LastFD && LastFD->isBitField() &&
54944d362409d5469aed47d19e7908d19bd194493aThomas Graf          FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() == 0 &&
55044d362409d5469aed47d19e7908d19bd194493aThomas Graf          LastFD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() != 0);
55144d362409d5469aed47d19e7908d19bd194493aThomas Graf
55244d362409d5469aed47d19e7908d19bd194493aThomas Graf}
5531155370f520cb64657e25153255cf7dc1424317fThomas Graf
55444d362409d5469aed47d19e7908d19bd194493aThomas Grafbool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
55544d362409d5469aed47d19e7908d19bd194493aThomas Graf                                         const FieldDecl *LastFD) const {
55644d362409d5469aed47d19e7908d19bd194493aThomas Graf  return (FD->isBitField() && LastFD && LastFD->isBitField() &&
5578a3efffa5b3fde252675239914118664d36a2c24Thomas Graf          FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() &&
55844d362409d5469aed47d19e7908d19bd194493aThomas Graf          LastFD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue());
55944d362409d5469aed47d19e7908d19bd194493aThomas Graf}
56044d362409d5469aed47d19e7908d19bd194493aThomas Graf
56144d362409d5469aed47d19e7908d19bd194493aThomas GrafASTContext::overridden_cxx_method_iterator
56244d362409d5469aed47d19e7908d19bd194493aThomas GrafASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
56344d362409d5469aed47d19e7908d19bd194493aThomas Graf  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
56444d362409d5469aed47d19e7908d19bd194493aThomas Graf    = OverriddenMethods.find(Method);
56544d362409d5469aed47d19e7908d19bd194493aThomas Graf  if (Pos == OverriddenMethods.end())
56644d362409d5469aed47d19e7908d19bd194493aThomas Graf    return 0;
56744d362409d5469aed47d19e7908d19bd194493aThomas Graf
5681155370f520cb64657e25153255cf7dc1424317fThomas Graf  return Pos->second.begin();
56944d362409d5469aed47d19e7908d19bd194493aThomas Graf}
57044d362409d5469aed47d19e7908d19bd194493aThomas Graf
5711155370f520cb64657e25153255cf7dc1424317fThomas GrafASTContext::overridden_cxx_method_iterator
57244d362409d5469aed47d19e7908d19bd194493aThomas GrafASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
57344d362409d5469aed47d19e7908d19bd194493aThomas Graf  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
57444d362409d5469aed47d19e7908d19bd194493aThomas Graf    = OverriddenMethods.find(Method);
57544d362409d5469aed47d19e7908d19bd194493aThomas Graf  if (Pos == OverriddenMethods.end())
57644d362409d5469aed47d19e7908d19bd194493aThomas Graf    return 0;
57744d362409d5469aed47d19e7908d19bd194493aThomas Graf
57844d362409d5469aed47d19e7908d19bd194493aThomas Graf  return Pos->second.end();
57944d362409d5469aed47d19e7908d19bd194493aThomas Graf}
58044d362409d5469aed47d19e7908d19bd194493aThomas Graf
58144d362409d5469aed47d19e7908d19bd194493aThomas Grafunsigned
58244d362409d5469aed47d19e7908d19bd194493aThomas GrafASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
58344d362409d5469aed47d19e7908d19bd194493aThomas Graf  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
58444d362409d5469aed47d19e7908d19bd194493aThomas Graf    = OverriddenMethods.find(Method);
58544d362409d5469aed47d19e7908d19bd194493aThomas Graf  if (Pos == OverriddenMethods.end())
58644d362409d5469aed47d19e7908d19bd194493aThomas Graf    return 0;
58744d362409d5469aed47d19e7908d19bd194493aThomas Graf
58844d362409d5469aed47d19e7908d19bd194493aThomas Graf  return Pos->second.size();
58944d362409d5469aed47d19e7908d19bd194493aThomas Graf}
59044d362409d5469aed47d19e7908d19bd194493aThomas Graf
59144d362409d5469aed47d19e7908d19bd194493aThomas Grafvoid ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
59244d362409d5469aed47d19e7908d19bd194493aThomas Graf                                     const CXXMethodDecl *Overridden) {
59344d362409d5469aed47d19e7908d19bd194493aThomas Graf  OverriddenMethods[Method].push_back(Overridden);
59444d362409d5469aed47d19e7908d19bd194493aThomas Graf}
59544d362409d5469aed47d19e7908d19bd194493aThomas Graf
59644d362409d5469aed47d19e7908d19bd194493aThomas Graf//===----------------------------------------------------------------------===//
59744d362409d5469aed47d19e7908d19bd194493aThomas Graf//                         Type Sizing and Analysis
59844d362409d5469aed47d19e7908d19bd194493aThomas Graf//===----------------------------------------------------------------------===//
59944d362409d5469aed47d19e7908d19bd194493aThomas Graf
60044d362409d5469aed47d19e7908d19bd194493aThomas Graf/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
60144d362409d5469aed47d19e7908d19bd194493aThomas Graf/// scalar floating point type.
60244d362409d5469aed47d19e7908d19bd194493aThomas Grafconst llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
60344d362409d5469aed47d19e7908d19bd194493aThomas Graf  const BuiltinType *BT = T->getAs<BuiltinType>();
60444d362409d5469aed47d19e7908d19bd194493aThomas Graf  assert(BT && "Not a floating point type!");
60544d362409d5469aed47d19e7908d19bd194493aThomas Graf  switch (BT->getKind()) {
60644d362409d5469aed47d19e7908d19bd194493aThomas Graf  default: assert(0 && "Not a floating point type!");
60744d362409d5469aed47d19e7908d19bd194493aThomas Graf  case BuiltinType::Float:      return Target.getFloatFormat();
60844d362409d5469aed47d19e7908d19bd194493aThomas Graf  case BuiltinType::Double:     return Target.getDoubleFormat();
60944d362409d5469aed47d19e7908d19bd194493aThomas Graf  case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
61044d362409d5469aed47d19e7908d19bd194493aThomas Graf  }
61144d362409d5469aed47d19e7908d19bd194493aThomas Graf}
61244d362409d5469aed47d19e7908d19bd194493aThomas Graf
61344d362409d5469aed47d19e7908d19bd194493aThomas Graf/// getDeclAlign - Return a conservative estimate of the alignment of the
6148a3efffa5b3fde252675239914118664d36a2c24Thomas Graf/// specified decl.  Note that bitfields do not have a valid alignment, so
61544d362409d5469aed47d19e7908d19bd194493aThomas Graf/// this method will assert on them.
61644d362409d5469aed47d19e7908d19bd194493aThomas Graf/// If @p RefAsPointee, references are treated like their underlying type
61744d362409d5469aed47d19e7908d19bd194493aThomas Graf/// (for alignof), else they're treated like pointers (for CodeGen).
61844d362409d5469aed47d19e7908d19bd194493aThomas GrafCharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
61944d362409d5469aed47d19e7908d19bd194493aThomas Graf  unsigned Align = Target.getCharWidth();
62044d362409d5469aed47d19e7908d19bd194493aThomas Graf
62144d362409d5469aed47d19e7908d19bd194493aThomas Graf  bool UseAlignAttrOnly = false;
62244d362409d5469aed47d19e7908d19bd194493aThomas Graf  if (unsigned AlignFromAttr = D->getMaxAlignment()) {
62344d362409d5469aed47d19e7908d19bd194493aThomas Graf    Align = AlignFromAttr;
62444d362409d5469aed47d19e7908d19bd194493aThomas Graf
62544d362409d5469aed47d19e7908d19bd194493aThomas Graf    // __attribute__((aligned)) can increase or decrease alignment
62644d362409d5469aed47d19e7908d19bd194493aThomas Graf    // *except* on a struct or struct member, where it only increases
62744d362409d5469aed47d19e7908d19bd194493aThomas Graf    // alignment unless 'packed' is also specified.
62844d362409d5469aed47d19e7908d19bd194493aThomas Graf    //
62944d362409d5469aed47d19e7908d19bd194493aThomas Graf    // It is an error for [[align]] to decrease alignment, so we can
63044d362409d5469aed47d19e7908d19bd194493aThomas Graf    // ignore that possibility;  Sema should diagnose it.
6318a3efffa5b3fde252675239914118664d36a2c24Thomas Graf    if (isa<FieldDecl>(D)) {
63244d362409d5469aed47d19e7908d19bd194493aThomas Graf      UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
63344d362409d5469aed47d19e7908d19bd194493aThomas Graf        cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
63444d362409d5469aed47d19e7908d19bd194493aThomas Graf    } else {
63544d362409d5469aed47d19e7908d19bd194493aThomas Graf      UseAlignAttrOnly = true;
63644d362409d5469aed47d19e7908d19bd194493aThomas Graf    }
63744d362409d5469aed47d19e7908d19bd194493aThomas Graf  }
63844d362409d5469aed47d19e7908d19bd194493aThomas Graf  else if (isa<FieldDecl>(D))
63944d362409d5469aed47d19e7908d19bd194493aThomas Graf      UseAlignAttrOnly =
64044d362409d5469aed47d19e7908d19bd194493aThomas Graf        D->hasAttr<PackedAttr>() ||
64144d362409d5469aed47d19e7908d19bd194493aThomas Graf        cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
64244d362409d5469aed47d19e7908d19bd194493aThomas Graf
64344d362409d5469aed47d19e7908d19bd194493aThomas Graf  // If we're using the align attribute only, just ignore everything
6448a3efffa5b3fde252675239914118664d36a2c24Thomas Graf  // else about the declaration and its type.
64544d362409d5469aed47d19e7908d19bd194493aThomas Graf  if (UseAlignAttrOnly) {
64644d362409d5469aed47d19e7908d19bd194493aThomas Graf    // do nothing
64744d362409d5469aed47d19e7908d19bd194493aThomas Graf
6488a3efffa5b3fde252675239914118664d36a2c24Thomas Graf  } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
64944d362409d5469aed47d19e7908d19bd194493aThomas Graf    QualType T = VD->getType();
65044d362409d5469aed47d19e7908d19bd194493aThomas Graf    if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
65144d362409d5469aed47d19e7908d19bd194493aThomas Graf      if (RefAsPointee)
65244d362409d5469aed47d19e7908d19bd194493aThomas Graf        T = RT->getPointeeType();
65344d362409d5469aed47d19e7908d19bd194493aThomas Graf      else
65444d362409d5469aed47d19e7908d19bd194493aThomas Graf        T = getPointerType(RT->getPointeeType());
65544d362409d5469aed47d19e7908d19bd194493aThomas Graf    }
65644d362409d5469aed47d19e7908d19bd194493aThomas Graf    if (!T->isIncompleteType() && !T->isFunctionType()) {
65744d362409d5469aed47d19e7908d19bd194493aThomas Graf      // Adjust alignments of declarations with array type by the
65844d362409d5469aed47d19e7908d19bd194493aThomas Graf      // large-array alignment on the target.
65944d362409d5469aed47d19e7908d19bd194493aThomas Graf      unsigned MinWidth = Target.getLargeArrayMinWidth();
66044d362409d5469aed47d19e7908d19bd194493aThomas Graf      const ArrayType *arrayType;
66144d362409d5469aed47d19e7908d19bd194493aThomas Graf      if (MinWidth && (arrayType = getAsArrayType(T))) {
66244d362409d5469aed47d19e7908d19bd194493aThomas Graf        if (isa<VariableArrayType>(arrayType))
66344d362409d5469aed47d19e7908d19bd194493aThomas Graf          Align = std::max(Align, Target.getLargeArrayAlign());
66444d362409d5469aed47d19e7908d19bd194493aThomas Graf        else if (isa<ConstantArrayType>(arrayType) &&
66523ee46ef7115c2e311c36e43a833e6c3deada18aThomas Graf                 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
66644d362409d5469aed47d19e7908d19bd194493aThomas Graf          Align = std::max(Align, Target.getLargeArrayAlign());
66744d362409d5469aed47d19e7908d19bd194493aThomas Graf
66844d362409d5469aed47d19e7908d19bd194493aThomas Graf        // Walk through any array types while we're at it.
66944d362409d5469aed47d19e7908d19bd194493aThomas Graf        T = getBaseElementType(arrayType);
67044d362409d5469aed47d19e7908d19bd194493aThomas Graf      }
67144d362409d5469aed47d19e7908d19bd194493aThomas Graf      Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
67244d362409d5469aed47d19e7908d19bd194493aThomas Graf    }
67344d362409d5469aed47d19e7908d19bd194493aThomas Graf
67444d362409d5469aed47d19e7908d19bd194493aThomas Graf    // Fields can be subject to extra alignment constraints, like if
67544d362409d5469aed47d19e7908d19bd194493aThomas Graf    // the field is packed, the struct is packed, or the struct has a
67644d362409d5469aed47d19e7908d19bd194493aThomas Graf    // a max-field-alignment constraint (#pragma pack).  So calculate
67744d362409d5469aed47d19e7908d19bd194493aThomas Graf    // the actual alignment of the field within the struct, and then
67844d362409d5469aed47d19e7908d19bd194493aThomas Graf    // (as we're expected to) constrain that by the alignment of the type.
67944d362409d5469aed47d19e7908d19bd194493aThomas Graf    if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
68044d362409d5469aed47d19e7908d19bd194493aThomas Graf      // So calculate the alignment of the field.
68144d362409d5469aed47d19e7908d19bd194493aThomas Graf      const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
68244d362409d5469aed47d19e7908d19bd194493aThomas Graf
68344d362409d5469aed47d19e7908d19bd194493aThomas Graf      // Start with the record's overall alignment.
68444d362409d5469aed47d19e7908d19bd194493aThomas Graf      unsigned fieldAlign = toBits(layout.getAlignment());
68544d362409d5469aed47d19e7908d19bd194493aThomas Graf
68644d362409d5469aed47d19e7908d19bd194493aThomas Graf      // Use the GCD of that and the offset within the record.
68744d362409d5469aed47d19e7908d19bd194493aThomas Graf      uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
6881155370f520cb64657e25153255cf7dc1424317fThomas Graf      if (offset > 0) {
68944d362409d5469aed47d19e7908d19bd194493aThomas Graf        // Alignment is always a power of 2, so the GCD will be a power of 2,
69044d362409d5469aed47d19e7908d19bd194493aThomas Graf        // which means we get to do this crazy thing instead of Euclid's.
69144d362409d5469aed47d19e7908d19bd194493aThomas Graf        uint64_t lowBitOfOffset = offset & (~offset + 1);
69244d362409d5469aed47d19e7908d19bd194493aThomas Graf        if (lowBitOfOffset < fieldAlign)
69344d362409d5469aed47d19e7908d19bd194493aThomas Graf          fieldAlign = static_cast<unsigned>(lowBitOfOffset);
69444d362409d5469aed47d19e7908d19bd194493aThomas Graf      }
69544d362409d5469aed47d19e7908d19bd194493aThomas Graf
69644d362409d5469aed47d19e7908d19bd194493aThomas Graf      Align = std::min(Align, fieldAlign);
69744d362409d5469aed47d19e7908d19bd194493aThomas Graf    }
69844d362409d5469aed47d19e7908d19bd194493aThomas Graf  }
69944d362409d5469aed47d19e7908d19bd194493aThomas Graf
70044d362409d5469aed47d19e7908d19bd194493aThomas Graf  return toCharUnitsFromBits(Align);
7011155370f520cb64657e25153255cf7dc1424317fThomas Graf}
70244d362409d5469aed47d19e7908d19bd194493aThomas Graf
70344d362409d5469aed47d19e7908d19bd194493aThomas Grafstd::pair<CharUnits, CharUnits>
7041155370f520cb64657e25153255cf7dc1424317fThomas GrafASTContext::getTypeInfoInChars(const Type *T) const {
70544d362409d5469aed47d19e7908d19bd194493aThomas Graf  std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
7061155370f520cb64657e25153255cf7dc1424317fThomas Graf  return std::make_pair(toCharUnitsFromBits(Info.first),
70744d362409d5469aed47d19e7908d19bd194493aThomas Graf                        toCharUnitsFromBits(Info.second));
70844d362409d5469aed47d19e7908d19bd194493aThomas Graf}
70944d362409d5469aed47d19e7908d19bd194493aThomas Graf
7101155370f520cb64657e25153255cf7dc1424317fThomas Grafstd::pair<CharUnits, CharUnits>
7111155370f520cb64657e25153255cf7dc1424317fThomas GrafASTContext::getTypeInfoInChars(QualType T) const {
71244d362409d5469aed47d19e7908d19bd194493aThomas Graf  return getTypeInfoInChars(T.getTypePtr());
7131155370f520cb64657e25153255cf7dc1424317fThomas Graf}
71444d362409d5469aed47d19e7908d19bd194493aThomas Graf
7151155370f520cb64657e25153255cf7dc1424317fThomas Graf/// getTypeSize - Return the size of the specified type, in bits.  This method
71644d362409d5469aed47d19e7908d19bd194493aThomas Graf/// does not work on incomplete types.
7171155370f520cb64657e25153255cf7dc1424317fThomas Graf///
71844d362409d5469aed47d19e7908d19bd194493aThomas Graf/// FIXME: Pointers into different addr spaces could have different sizes and
71944d362409d5469aed47d19e7908d19bd194493aThomas Graf/// alignment requirements: getPointerInfo should take an AddrSpace, this
72044d362409d5469aed47d19e7908d19bd194493aThomas Graf/// should take a QualType, &c.
72144d362409d5469aed47d19e7908d19bd194493aThomas Grafstd::pair<uint64_t, unsigned>
72244d362409d5469aed47d19e7908d19bd194493aThomas GrafASTContext::getTypeInfo(const Type *T) const {
72344d362409d5469aed47d19e7908d19bd194493aThomas Graf  uint64_t Width=0;
72444d362409d5469aed47d19e7908d19bd194493aThomas Graf  unsigned Align=8;
72544d362409d5469aed47d19e7908d19bd194493aThomas Graf  switch (T->getTypeClass()) {
72644d362409d5469aed47d19e7908d19bd194493aThomas Graf#define TYPE(Class, Base)
72744d362409d5469aed47d19e7908d19bd194493aThomas Graf#define ABSTRACT_TYPE(Class, Base)
7281155370f520cb64657e25153255cf7dc1424317fThomas Graf#define NON_CANONICAL_TYPE(Class, Base)
72944d362409d5469aed47d19e7908d19bd194493aThomas Graf#define DEPENDENT_TYPE(Class, Base) case Type::Class:
73044d362409d5469aed47d19e7908d19bd194493aThomas Graf#include "clang/AST/TypeNodes.def"
73144d362409d5469aed47d19e7908d19bd194493aThomas Graf    assert(false && "Should not see dependent types");
73244d362409d5469aed47d19e7908d19bd194493aThomas Graf    break;
73344d362409d5469aed47d19e7908d19bd194493aThomas Graf
7341155370f520cb64657e25153255cf7dc1424317fThomas Graf  case Type::FunctionNoProto:
73544d362409d5469aed47d19e7908d19bd194493aThomas Graf  case Type::FunctionProto:
73644d362409d5469aed47d19e7908d19bd194493aThomas Graf    // GCC extension: alignof(function) = 32 bits
73744d362409d5469aed47d19e7908d19bd194493aThomas Graf    Width = 0;
73844d362409d5469aed47d19e7908d19bd194493aThomas Graf    Align = 32;
7391155370f520cb64657e25153255cf7dc1424317fThomas Graf    break;
74044d362409d5469aed47d19e7908d19bd194493aThomas Graf
7418a3efffa5b3fde252675239914118664d36a2c24Thomas Graf  case Type::IncompleteArray:
74244d362409d5469aed47d19e7908d19bd194493aThomas Graf  case Type::VariableArray:
74344d362409d5469aed47d19e7908d19bd194493aThomas Graf    Width = 0;
7441155370f520cb64657e25153255cf7dc1424317fThomas Graf    Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
74544d362409d5469aed47d19e7908d19bd194493aThomas Graf    break;
74644d362409d5469aed47d19e7908d19bd194493aThomas Graf
74744d362409d5469aed47d19e7908d19bd194493aThomas Graf  case Type::ConstantArray: {
74844d362409d5469aed47d19e7908d19bd194493aThomas Graf    const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
74944d362409d5469aed47d19e7908d19bd194493aThomas Graf
75044d362409d5469aed47d19e7908d19bd194493aThomas Graf    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
75144d362409d5469aed47d19e7908d19bd194493aThomas Graf    Width = EltInfo.first*CAT->getSize().getZExtValue();
75244d362409d5469aed47d19e7908d19bd194493aThomas Graf    Align = EltInfo.second;
753    Width = llvm::RoundUpToAlignment(Width, Align);
754    break;
755  }
756  case Type::ExtVector:
757  case Type::Vector: {
758    const VectorType *VT = cast<VectorType>(T);
759    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
760    Width = EltInfo.first*VT->getNumElements();
761    Align = Width;
762    // If the alignment is not a power of 2, round up to the next power of 2.
763    // This happens for non-power-of-2 length vectors.
764    if (Align & (Align-1)) {
765      Align = llvm::NextPowerOf2(Align);
766      Width = llvm::RoundUpToAlignment(Width, Align);
767    }
768    break;
769  }
770
771  case Type::Builtin:
772    switch (cast<BuiltinType>(T)->getKind()) {
773    default: assert(0 && "Unknown builtin type!");
774    case BuiltinType::Void:
775      // GCC extension: alignof(void) = 8 bits.
776      Width = 0;
777      Align = 8;
778      break;
779
780    case BuiltinType::Bool:
781      Width = Target.getBoolWidth();
782      Align = Target.getBoolAlign();
783      break;
784    case BuiltinType::Char_S:
785    case BuiltinType::Char_U:
786    case BuiltinType::UChar:
787    case BuiltinType::SChar:
788      Width = Target.getCharWidth();
789      Align = Target.getCharAlign();
790      break;
791    case BuiltinType::WChar_S:
792    case BuiltinType::WChar_U:
793      Width = Target.getWCharWidth();
794      Align = Target.getWCharAlign();
795      break;
796    case BuiltinType::Char16:
797      Width = Target.getChar16Width();
798      Align = Target.getChar16Align();
799      break;
800    case BuiltinType::Char32:
801      Width = Target.getChar32Width();
802      Align = Target.getChar32Align();
803      break;
804    case BuiltinType::UShort:
805    case BuiltinType::Short:
806      Width = Target.getShortWidth();
807      Align = Target.getShortAlign();
808      break;
809    case BuiltinType::UInt:
810    case BuiltinType::Int:
811      Width = Target.getIntWidth();
812      Align = Target.getIntAlign();
813      break;
814    case BuiltinType::ULong:
815    case BuiltinType::Long:
816      Width = Target.getLongWidth();
817      Align = Target.getLongAlign();
818      break;
819    case BuiltinType::ULongLong:
820    case BuiltinType::LongLong:
821      Width = Target.getLongLongWidth();
822      Align = Target.getLongLongAlign();
823      break;
824    case BuiltinType::Int128:
825    case BuiltinType::UInt128:
826      Width = 128;
827      Align = 128; // int128_t is 128-bit aligned on all targets.
828      break;
829    case BuiltinType::Float:
830      Width = Target.getFloatWidth();
831      Align = Target.getFloatAlign();
832      break;
833    case BuiltinType::Double:
834      Width = Target.getDoubleWidth();
835      Align = Target.getDoubleAlign();
836      break;
837    case BuiltinType::LongDouble:
838      Width = Target.getLongDoubleWidth();
839      Align = Target.getLongDoubleAlign();
840      break;
841    case BuiltinType::NullPtr:
842      Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
843      Align = Target.getPointerAlign(0); //   == sizeof(void*)
844      break;
845    case BuiltinType::ObjCId:
846    case BuiltinType::ObjCClass:
847    case BuiltinType::ObjCSel:
848      Width = Target.getPointerWidth(0);
849      Align = Target.getPointerAlign(0);
850      break;
851    }
852    break;
853  case Type::ObjCObjectPointer:
854    Width = Target.getPointerWidth(0);
855    Align = Target.getPointerAlign(0);
856    break;
857  case Type::BlockPointer: {
858    unsigned AS = getTargetAddressSpace(
859        cast<BlockPointerType>(T)->getPointeeType());
860    Width = Target.getPointerWidth(AS);
861    Align = Target.getPointerAlign(AS);
862    break;
863  }
864  case Type::LValueReference:
865  case Type::RValueReference: {
866    // alignof and sizeof should never enter this code path here, so we go
867    // the pointer route.
868    unsigned AS = getTargetAddressSpace(
869        cast<ReferenceType>(T)->getPointeeType());
870    Width = Target.getPointerWidth(AS);
871    Align = Target.getPointerAlign(AS);
872    break;
873  }
874  case Type::Pointer: {
875    unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
876    Width = Target.getPointerWidth(AS);
877    Align = Target.getPointerAlign(AS);
878    break;
879  }
880  case Type::MemberPointer: {
881    const MemberPointerType *MPT = cast<MemberPointerType>(T);
882    std::pair<uint64_t, unsigned> PtrDiffInfo =
883      getTypeInfo(getPointerDiffType());
884    Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
885    Align = PtrDiffInfo.second;
886    break;
887  }
888  case Type::Complex: {
889    // Complex types have the same alignment as their elements, but twice the
890    // size.
891    std::pair<uint64_t, unsigned> EltInfo =
892      getTypeInfo(cast<ComplexType>(T)->getElementType());
893    Width = EltInfo.first*2;
894    Align = EltInfo.second;
895    break;
896  }
897  case Type::ObjCObject:
898    return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
899  case Type::ObjCInterface: {
900    const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
901    const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
902    Width = toBits(Layout.getSize());
903    Align = toBits(Layout.getAlignment());
904    break;
905  }
906  case Type::Record:
907  case Type::Enum: {
908    const TagType *TT = cast<TagType>(T);
909
910    if (TT->getDecl()->isInvalidDecl()) {
911      Width = 8;
912      Align = 8;
913      break;
914    }
915
916    if (const EnumType *ET = dyn_cast<EnumType>(TT))
917      return getTypeInfo(ET->getDecl()->getIntegerType());
918
919    const RecordType *RT = cast<RecordType>(TT);
920    const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
921    Width = toBits(Layout.getSize());
922    Align = toBits(Layout.getAlignment());
923    break;
924  }
925
926  case Type::SubstTemplateTypeParm:
927    return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
928                       getReplacementType().getTypePtr());
929
930  case Type::Auto: {
931    const AutoType *A = cast<AutoType>(T);
932    assert(A->isDeduced() && "Cannot request the size of a dependent type");
933    return getTypeInfo(A->getDeducedType().getTypePtr());
934  }
935
936  case Type::Paren:
937    return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
938
939  case Type::Typedef: {
940    const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
941    std::pair<uint64_t, unsigned> Info
942      = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
943    // If the typedef has an aligned attribute on it, it overrides any computed
944    // alignment we have.  This violates the GCC documentation (which says that
945    // attribute(aligned) can only round up) but matches its implementation.
946    if (unsigned AttrAlign = Typedef->getMaxAlignment())
947      Align = AttrAlign;
948    else
949      Align = Info.second;
950    Width = Info.first;
951    break;
952  }
953
954  case Type::TypeOfExpr:
955    return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
956                         .getTypePtr());
957
958  case Type::TypeOf:
959    return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
960
961  case Type::Decltype:
962    return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
963                        .getTypePtr());
964
965  case Type::Elaborated:
966    return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
967
968  case Type::Attributed:
969    return getTypeInfo(
970                  cast<AttributedType>(T)->getEquivalentType().getTypePtr());
971
972  case Type::TemplateSpecialization: {
973    assert(getCanonicalType(T) != T &&
974           "Cannot request the size of a dependent type");
975    const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
976    // A type alias template specialization may refer to a typedef with the
977    // aligned attribute on it.
978    if (TST->isTypeAlias())
979      return getTypeInfo(TST->getAliasedType().getTypePtr());
980    else
981      return getTypeInfo(getCanonicalType(T));
982  }
983
984  }
985
986  assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
987  return std::make_pair(Width, Align);
988}
989
990/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
991CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
992  return CharUnits::fromQuantity(BitSize / getCharWidth());
993}
994
995/// toBits - Convert a size in characters to a size in characters.
996int64_t ASTContext::toBits(CharUnits CharSize) const {
997  return CharSize.getQuantity() * getCharWidth();
998}
999
1000/// getTypeSizeInChars - Return the size of the specified type, in characters.
1001/// This method does not work on incomplete types.
1002CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
1003  return toCharUnitsFromBits(getTypeSize(T));
1004}
1005CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
1006  return toCharUnitsFromBits(getTypeSize(T));
1007}
1008
1009/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1010/// characters. This method does not work on incomplete types.
1011CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
1012  return toCharUnitsFromBits(getTypeAlign(T));
1013}
1014CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
1015  return toCharUnitsFromBits(getTypeAlign(T));
1016}
1017
1018/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1019/// type for the current target in bits.  This can be different than the ABI
1020/// alignment in cases where it is beneficial for performance to overalign
1021/// a data type.
1022unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
1023  unsigned ABIAlign = getTypeAlign(T);
1024
1025  // Double and long long should be naturally aligned if possible.
1026  if (const ComplexType* CT = T->getAs<ComplexType>())
1027    T = CT->getElementType().getTypePtr();
1028  if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1029      T->isSpecificBuiltinType(BuiltinType::LongLong))
1030    return std::max(ABIAlign, (unsigned)getTypeSize(T));
1031
1032  return ABIAlign;
1033}
1034
1035/// ShallowCollectObjCIvars -
1036/// Collect all ivars, including those synthesized, in the current class.
1037///
1038void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
1039                            llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
1040  // FIXME. This need be removed but there are two many places which
1041  // assume const-ness of ObjCInterfaceDecl
1042  ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1043  for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1044        Iv= Iv->getNextIvar())
1045    Ivars.push_back(Iv);
1046}
1047
1048/// DeepCollectObjCIvars -
1049/// This routine first collects all declared, but not synthesized, ivars in
1050/// super class and then collects all ivars, including those synthesized for
1051/// current class. This routine is used for implementation of current class
1052/// when all ivars, declared and synthesized are known.
1053///
1054void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1055                                      bool leafClass,
1056                            llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
1057  if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1058    DeepCollectObjCIvars(SuperClass, false, Ivars);
1059  if (!leafClass) {
1060    for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1061         E = OI->ivar_end(); I != E; ++I)
1062      Ivars.push_back(*I);
1063  }
1064  else
1065    ShallowCollectObjCIvars(OI, Ivars);
1066}
1067
1068/// CollectInheritedProtocols - Collect all protocols in current class and
1069/// those inherited by it.
1070void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
1071                          llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
1072  if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1073    // We can use protocol_iterator here instead of
1074    // all_referenced_protocol_iterator since we are walking all categories.
1075    for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1076         PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
1077      ObjCProtocolDecl *Proto = (*P);
1078      Protocols.insert(Proto);
1079      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1080           PE = Proto->protocol_end(); P != PE; ++P) {
1081        Protocols.insert(*P);
1082        CollectInheritedProtocols(*P, Protocols);
1083      }
1084    }
1085
1086    // Categories of this Interface.
1087    for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1088         CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1089      CollectInheritedProtocols(CDeclChain, Protocols);
1090    if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1091      while (SD) {
1092        CollectInheritedProtocols(SD, Protocols);
1093        SD = SD->getSuperClass();
1094      }
1095  } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1096    for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
1097         PE = OC->protocol_end(); P != PE; ++P) {
1098      ObjCProtocolDecl *Proto = (*P);
1099      Protocols.insert(Proto);
1100      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1101           PE = Proto->protocol_end(); P != PE; ++P)
1102        CollectInheritedProtocols(*P, Protocols);
1103    }
1104  } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1105    for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1106         PE = OP->protocol_end(); P != PE; ++P) {
1107      ObjCProtocolDecl *Proto = (*P);
1108      Protocols.insert(Proto);
1109      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1110           PE = Proto->protocol_end(); P != PE; ++P)
1111        CollectInheritedProtocols(*P, Protocols);
1112    }
1113  }
1114}
1115
1116unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
1117  unsigned count = 0;
1118  // Count ivars declared in class extension.
1119  for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1120       CDecl = CDecl->getNextClassExtension())
1121    count += CDecl->ivar_size();
1122
1123  // Count ivar defined in this class's implementation.  This
1124  // includes synthesized ivars.
1125  if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
1126    count += ImplDecl->ivar_size();
1127
1128  return count;
1129}
1130
1131/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1132ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1133  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1134    I = ObjCImpls.find(D);
1135  if (I != ObjCImpls.end())
1136    return cast<ObjCImplementationDecl>(I->second);
1137  return 0;
1138}
1139/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1140ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1141  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1142    I = ObjCImpls.find(D);
1143  if (I != ObjCImpls.end())
1144    return cast<ObjCCategoryImplDecl>(I->second);
1145  return 0;
1146}
1147
1148/// \brief Set the implementation of ObjCInterfaceDecl.
1149void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1150                           ObjCImplementationDecl *ImplD) {
1151  assert(IFaceD && ImplD && "Passed null params");
1152  ObjCImpls[IFaceD] = ImplD;
1153}
1154/// \brief Set the implementation of ObjCCategoryDecl.
1155void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1156                           ObjCCategoryImplDecl *ImplD) {
1157  assert(CatD && ImplD && "Passed null params");
1158  ObjCImpls[CatD] = ImplD;
1159}
1160
1161/// \brief Get the copy initialization expression of VarDecl,or NULL if
1162/// none exists.
1163Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
1164  assert(VD && "Passed null params");
1165  assert(VD->hasAttr<BlocksAttr>() &&
1166         "getBlockVarCopyInits - not __block var");
1167  llvm::DenseMap<const VarDecl*, Expr*>::iterator
1168    I = BlockVarCopyInits.find(VD);
1169  return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1170}
1171
1172/// \brief Set the copy inialization expression of a block var decl.
1173void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1174  assert(VD && Init && "Passed null params");
1175  assert(VD->hasAttr<BlocksAttr>() &&
1176         "setBlockVarCopyInits - not __block var");
1177  BlockVarCopyInits[VD] = Init;
1178}
1179
1180/// \brief Allocate an uninitialized TypeSourceInfo.
1181///
1182/// The caller should initialize the memory held by TypeSourceInfo using
1183/// the TypeLoc wrappers.
1184///
1185/// \param T the type that will be the basis for type source info. This type
1186/// should refer to how the declarator was written in source code, not to
1187/// what type semantic analysis resolved the declarator to.
1188TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
1189                                                 unsigned DataSize) const {
1190  if (!DataSize)
1191    DataSize = TypeLoc::getFullDataSizeForType(T);
1192  else
1193    assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
1194           "incorrect data size provided to CreateTypeSourceInfo!");
1195
1196  TypeSourceInfo *TInfo =
1197    (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1198  new (TInfo) TypeSourceInfo(T);
1199  return TInfo;
1200}
1201
1202TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
1203                                                     SourceLocation L) const {
1204  TypeSourceInfo *DI = CreateTypeSourceInfo(T);
1205  DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
1206  return DI;
1207}
1208
1209const ASTRecordLayout &
1210ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
1211  return getObjCLayout(D, 0);
1212}
1213
1214const ASTRecordLayout &
1215ASTContext::getASTObjCImplementationLayout(
1216                                        const ObjCImplementationDecl *D) const {
1217  return getObjCLayout(D->getClassInterface(), D);
1218}
1219
1220//===----------------------------------------------------------------------===//
1221//                   Type creation/memoization methods
1222//===----------------------------------------------------------------------===//
1223
1224QualType
1225ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1226  unsigned fastQuals = quals.getFastQualifiers();
1227  quals.removeFastQualifiers();
1228
1229  // Check if we've already instantiated this type.
1230  llvm::FoldingSetNodeID ID;
1231  ExtQuals::Profile(ID, baseType, quals);
1232  void *insertPos = 0;
1233  if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1234    assert(eq->getQualifiers() == quals);
1235    return QualType(eq, fastQuals);
1236  }
1237
1238  // If the base type is not canonical, make the appropriate canonical type.
1239  QualType canon;
1240  if (!baseType->isCanonicalUnqualified()) {
1241    SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1242    canonSplit.second.addConsistentQualifiers(quals);
1243    canon = getExtQualType(canonSplit.first, canonSplit.second);
1244
1245    // Re-find the insert position.
1246    (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1247  }
1248
1249  ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1250  ExtQualNodes.InsertNode(eq, insertPos);
1251  return QualType(eq, fastQuals);
1252}
1253
1254QualType
1255ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
1256  QualType CanT = getCanonicalType(T);
1257  if (CanT.getAddressSpace() == AddressSpace)
1258    return T;
1259
1260  // If we are composing extended qualifiers together, merge together
1261  // into one ExtQuals node.
1262  QualifierCollector Quals;
1263  const Type *TypeNode = Quals.strip(T);
1264
1265  // If this type already has an address space specified, it cannot get
1266  // another one.
1267  assert(!Quals.hasAddressSpace() &&
1268         "Type cannot be in multiple addr spaces!");
1269  Quals.addAddressSpace(AddressSpace);
1270
1271  return getExtQualType(TypeNode, Quals);
1272}
1273
1274QualType ASTContext::getObjCGCQualType(QualType T,
1275                                       Qualifiers::GC GCAttr) const {
1276  QualType CanT = getCanonicalType(T);
1277  if (CanT.getObjCGCAttr() == GCAttr)
1278    return T;
1279
1280  if (const PointerType *ptr = T->getAs<PointerType>()) {
1281    QualType Pointee = ptr->getPointeeType();
1282    if (Pointee->isAnyPointerType()) {
1283      QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1284      return getPointerType(ResultType);
1285    }
1286  }
1287
1288  // If we are composing extended qualifiers together, merge together
1289  // into one ExtQuals node.
1290  QualifierCollector Quals;
1291  const Type *TypeNode = Quals.strip(T);
1292
1293  // If this type already has an ObjCGC specified, it cannot get
1294  // another one.
1295  assert(!Quals.hasObjCGCAttr() &&
1296         "Type cannot have multiple ObjCGCs!");
1297  Quals.addObjCGCAttr(GCAttr);
1298
1299  return getExtQualType(TypeNode, Quals);
1300}
1301
1302const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1303                                                   FunctionType::ExtInfo Info) {
1304  if (T->getExtInfo() == Info)
1305    return T;
1306
1307  QualType Result;
1308  if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1309    Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1310  } else {
1311    const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1312    FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1313    EPI.ExtInfo = Info;
1314    Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1315                             FPT->getNumArgs(), EPI);
1316  }
1317
1318  return cast<FunctionType>(Result.getTypePtr());
1319}
1320
1321/// getComplexType - Return the uniqued reference to the type for a complex
1322/// number with the specified element type.
1323QualType ASTContext::getComplexType(QualType T) const {
1324  // Unique pointers, to guarantee there is only one pointer of a particular
1325  // structure.
1326  llvm::FoldingSetNodeID ID;
1327  ComplexType::Profile(ID, T);
1328
1329  void *InsertPos = 0;
1330  if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1331    return QualType(CT, 0);
1332
1333  // If the pointee type isn't canonical, this won't be a canonical type either,
1334  // so fill in the canonical type field.
1335  QualType Canonical;
1336  if (!T.isCanonical()) {
1337    Canonical = getComplexType(getCanonicalType(T));
1338
1339    // Get the new insert position for the node we care about.
1340    ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
1341    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1342  }
1343  ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
1344  Types.push_back(New);
1345  ComplexTypes.InsertNode(New, InsertPos);
1346  return QualType(New, 0);
1347}
1348
1349/// getPointerType - Return the uniqued reference to the type for a pointer to
1350/// the specified type.
1351QualType ASTContext::getPointerType(QualType T) const {
1352  // Unique pointers, to guarantee there is only one pointer of a particular
1353  // structure.
1354  llvm::FoldingSetNodeID ID;
1355  PointerType::Profile(ID, T);
1356
1357  void *InsertPos = 0;
1358  if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1359    return QualType(PT, 0);
1360
1361  // If the pointee type isn't canonical, this won't be a canonical type either,
1362  // so fill in the canonical type field.
1363  QualType Canonical;
1364  if (!T.isCanonical()) {
1365    Canonical = getPointerType(getCanonicalType(T));
1366
1367    // Get the new insert position for the node we care about.
1368    PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1369    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1370  }
1371  PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
1372  Types.push_back(New);
1373  PointerTypes.InsertNode(New, InsertPos);
1374  return QualType(New, 0);
1375}
1376
1377/// getBlockPointerType - Return the uniqued reference to the type for
1378/// a pointer to the specified block.
1379QualType ASTContext::getBlockPointerType(QualType T) const {
1380  assert(T->isFunctionType() && "block of function types only");
1381  // Unique pointers, to guarantee there is only one block of a particular
1382  // structure.
1383  llvm::FoldingSetNodeID ID;
1384  BlockPointerType::Profile(ID, T);
1385
1386  void *InsertPos = 0;
1387  if (BlockPointerType *PT =
1388        BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1389    return QualType(PT, 0);
1390
1391  // If the block pointee type isn't canonical, this won't be a canonical
1392  // type either so fill in the canonical type field.
1393  QualType Canonical;
1394  if (!T.isCanonical()) {
1395    Canonical = getBlockPointerType(getCanonicalType(T));
1396
1397    // Get the new insert position for the node we care about.
1398    BlockPointerType *NewIP =
1399      BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1400    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1401  }
1402  BlockPointerType *New
1403    = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
1404  Types.push_back(New);
1405  BlockPointerTypes.InsertNode(New, InsertPos);
1406  return QualType(New, 0);
1407}
1408
1409/// getLValueReferenceType - Return the uniqued reference to the type for an
1410/// lvalue reference to the specified type.
1411QualType
1412ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
1413  // Unique pointers, to guarantee there is only one pointer of a particular
1414  // structure.
1415  llvm::FoldingSetNodeID ID;
1416  ReferenceType::Profile(ID, T, SpelledAsLValue);
1417
1418  void *InsertPos = 0;
1419  if (LValueReferenceType *RT =
1420        LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1421    return QualType(RT, 0);
1422
1423  const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1424
1425  // If the referencee type isn't canonical, this won't be a canonical type
1426  // either, so fill in the canonical type field.
1427  QualType Canonical;
1428  if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1429    QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1430    Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
1431
1432    // Get the new insert position for the node we care about.
1433    LValueReferenceType *NewIP =
1434      LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1435    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1436  }
1437
1438  LValueReferenceType *New
1439    = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1440                                                     SpelledAsLValue);
1441  Types.push_back(New);
1442  LValueReferenceTypes.InsertNode(New, InsertPos);
1443
1444  return QualType(New, 0);
1445}
1446
1447/// getRValueReferenceType - Return the uniqued reference to the type for an
1448/// rvalue reference to the specified type.
1449QualType ASTContext::getRValueReferenceType(QualType T) const {
1450  // Unique pointers, to guarantee there is only one pointer of a particular
1451  // structure.
1452  llvm::FoldingSetNodeID ID;
1453  ReferenceType::Profile(ID, T, false);
1454
1455  void *InsertPos = 0;
1456  if (RValueReferenceType *RT =
1457        RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1458    return QualType(RT, 0);
1459
1460  const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1461
1462  // If the referencee type isn't canonical, this won't be a canonical type
1463  // either, so fill in the canonical type field.
1464  QualType Canonical;
1465  if (InnerRef || !T.isCanonical()) {
1466    QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1467    Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
1468
1469    // Get the new insert position for the node we care about.
1470    RValueReferenceType *NewIP =
1471      RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1472    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1473  }
1474
1475  RValueReferenceType *New
1476    = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
1477  Types.push_back(New);
1478  RValueReferenceTypes.InsertNode(New, InsertPos);
1479  return QualType(New, 0);
1480}
1481
1482/// getMemberPointerType - Return the uniqued reference to the type for a
1483/// member pointer to the specified type, in the specified class.
1484QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
1485  // Unique pointers, to guarantee there is only one pointer of a particular
1486  // structure.
1487  llvm::FoldingSetNodeID ID;
1488  MemberPointerType::Profile(ID, T, Cls);
1489
1490  void *InsertPos = 0;
1491  if (MemberPointerType *PT =
1492      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1493    return QualType(PT, 0);
1494
1495  // If the pointee or class type isn't canonical, this won't be a canonical
1496  // type either, so fill in the canonical type field.
1497  QualType Canonical;
1498  if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
1499    Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1500
1501    // Get the new insert position for the node we care about.
1502    MemberPointerType *NewIP =
1503      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1504    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1505  }
1506  MemberPointerType *New
1507    = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
1508  Types.push_back(New);
1509  MemberPointerTypes.InsertNode(New, InsertPos);
1510  return QualType(New, 0);
1511}
1512
1513/// getConstantArrayType - Return the unique reference to the type for an
1514/// array of the specified element type.
1515QualType ASTContext::getConstantArrayType(QualType EltTy,
1516                                          const llvm::APInt &ArySizeIn,
1517                                          ArrayType::ArraySizeModifier ASM,
1518                                          unsigned IndexTypeQuals) const {
1519  assert((EltTy->isDependentType() ||
1520          EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
1521         "Constant array of VLAs is illegal!");
1522
1523  // Convert the array size into a canonical width matching the pointer size for
1524  // the target.
1525  llvm::APInt ArySize(ArySizeIn);
1526  ArySize =
1527    ArySize.zextOrTrunc(Target.getPointerWidth(getTargetAddressSpace(EltTy)));
1528
1529  llvm::FoldingSetNodeID ID;
1530  ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
1531
1532  void *InsertPos = 0;
1533  if (ConstantArrayType *ATP =
1534      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1535    return QualType(ATP, 0);
1536
1537  // If the element type isn't canonical or has qualifiers, this won't
1538  // be a canonical type either, so fill in the canonical type field.
1539  QualType Canon;
1540  if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1541    SplitQualType canonSplit = getCanonicalType(EltTy).split();
1542    Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
1543                                 ASM, IndexTypeQuals);
1544    Canon = getQualifiedType(Canon, canonSplit.second);
1545
1546    // Get the new insert position for the node we care about.
1547    ConstantArrayType *NewIP =
1548      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1549    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1550  }
1551
1552  ConstantArrayType *New = new(*this,TypeAlignment)
1553    ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
1554  ConstantArrayTypes.InsertNode(New, InsertPos);
1555  Types.push_back(New);
1556  return QualType(New, 0);
1557}
1558
1559/// getVariableArrayDecayedType - Turns the given type, which may be
1560/// variably-modified, into the corresponding type with all the known
1561/// sizes replaced with [*].
1562QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1563  // Vastly most common case.
1564  if (!type->isVariablyModifiedType()) return type;
1565
1566  QualType result;
1567
1568  SplitQualType split = type.getSplitDesugaredType();
1569  const Type *ty = split.first;
1570  switch (ty->getTypeClass()) {
1571#define TYPE(Class, Base)
1572#define ABSTRACT_TYPE(Class, Base)
1573#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1574#include "clang/AST/TypeNodes.def"
1575    llvm_unreachable("didn't desugar past all non-canonical types?");
1576
1577  // These types should never be variably-modified.
1578  case Type::Builtin:
1579  case Type::Complex:
1580  case Type::Vector:
1581  case Type::ExtVector:
1582  case Type::DependentSizedExtVector:
1583  case Type::ObjCObject:
1584  case Type::ObjCInterface:
1585  case Type::ObjCObjectPointer:
1586  case Type::Record:
1587  case Type::Enum:
1588  case Type::UnresolvedUsing:
1589  case Type::TypeOfExpr:
1590  case Type::TypeOf:
1591  case Type::Decltype:
1592  case Type::DependentName:
1593  case Type::InjectedClassName:
1594  case Type::TemplateSpecialization:
1595  case Type::DependentTemplateSpecialization:
1596  case Type::TemplateTypeParm:
1597  case Type::SubstTemplateTypeParmPack:
1598  case Type::Auto:
1599  case Type::PackExpansion:
1600    llvm_unreachable("type should never be variably-modified");
1601
1602  // These types can be variably-modified but should never need to
1603  // further decay.
1604  case Type::FunctionNoProto:
1605  case Type::FunctionProto:
1606  case Type::BlockPointer:
1607  case Type::MemberPointer:
1608    return type;
1609
1610  // These types can be variably-modified.  All these modifications
1611  // preserve structure except as noted by comments.
1612  // TODO: if we ever care about optimizing VLAs, there are no-op
1613  // optimizations available here.
1614  case Type::Pointer:
1615    result = getPointerType(getVariableArrayDecayedType(
1616                              cast<PointerType>(ty)->getPointeeType()));
1617    break;
1618
1619  case Type::LValueReference: {
1620    const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1621    result = getLValueReferenceType(
1622                 getVariableArrayDecayedType(lv->getPointeeType()),
1623                                    lv->isSpelledAsLValue());
1624    break;
1625  }
1626
1627  case Type::RValueReference: {
1628    const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1629    result = getRValueReferenceType(
1630                 getVariableArrayDecayedType(lv->getPointeeType()));
1631    break;
1632  }
1633
1634  case Type::ConstantArray: {
1635    const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1636    result = getConstantArrayType(
1637                 getVariableArrayDecayedType(cat->getElementType()),
1638                                  cat->getSize(),
1639                                  cat->getSizeModifier(),
1640                                  cat->getIndexTypeCVRQualifiers());
1641    break;
1642  }
1643
1644  case Type::DependentSizedArray: {
1645    const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1646    result = getDependentSizedArrayType(
1647                 getVariableArrayDecayedType(dat->getElementType()),
1648                                        dat->getSizeExpr(),
1649                                        dat->getSizeModifier(),
1650                                        dat->getIndexTypeCVRQualifiers(),
1651                                        dat->getBracketsRange());
1652    break;
1653  }
1654
1655  // Turn incomplete types into [*] types.
1656  case Type::IncompleteArray: {
1657    const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1658    result = getVariableArrayType(
1659                 getVariableArrayDecayedType(iat->getElementType()),
1660                                  /*size*/ 0,
1661                                  ArrayType::Normal,
1662                                  iat->getIndexTypeCVRQualifiers(),
1663                                  SourceRange());
1664    break;
1665  }
1666
1667  // Turn VLA types into [*] types.
1668  case Type::VariableArray: {
1669    const VariableArrayType *vat = cast<VariableArrayType>(ty);
1670    result = getVariableArrayType(
1671                 getVariableArrayDecayedType(vat->getElementType()),
1672                                  /*size*/ 0,
1673                                  ArrayType::Star,
1674                                  vat->getIndexTypeCVRQualifiers(),
1675                                  vat->getBracketsRange());
1676    break;
1677  }
1678  }
1679
1680  // Apply the top-level qualifiers from the original.
1681  return getQualifiedType(result, split.second);
1682}
1683
1684/// getVariableArrayType - Returns a non-unique reference to the type for a
1685/// variable array of the specified element type.
1686QualType ASTContext::getVariableArrayType(QualType EltTy,
1687                                          Expr *NumElts,
1688                                          ArrayType::ArraySizeModifier ASM,
1689                                          unsigned IndexTypeQuals,
1690                                          SourceRange Brackets) const {
1691  // Since we don't unique expressions, it isn't possible to unique VLA's
1692  // that have an expression provided for their size.
1693  QualType Canon;
1694
1695  // Be sure to pull qualifiers off the element type.
1696  if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1697    SplitQualType canonSplit = getCanonicalType(EltTy).split();
1698    Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
1699                                 IndexTypeQuals, Brackets);
1700    Canon = getQualifiedType(Canon, canonSplit.second);
1701  }
1702
1703  VariableArrayType *New = new(*this, TypeAlignment)
1704    VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
1705
1706  VariableArrayTypes.push_back(New);
1707  Types.push_back(New);
1708  return QualType(New, 0);
1709}
1710
1711/// getDependentSizedArrayType - Returns a non-unique reference to
1712/// the type for a dependently-sized array of the specified element
1713/// type.
1714QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1715                                                Expr *numElements,
1716                                                ArrayType::ArraySizeModifier ASM,
1717                                                unsigned elementTypeQuals,
1718                                                SourceRange brackets) const {
1719  assert((!numElements || numElements->isTypeDependent() ||
1720          numElements->isValueDependent()) &&
1721         "Size must be type- or value-dependent!");
1722
1723  // Dependently-sized array types that do not have a specified number
1724  // of elements will have their sizes deduced from a dependent
1725  // initializer.  We do no canonicalization here at all, which is okay
1726  // because they can't be used in most locations.
1727  if (!numElements) {
1728    DependentSizedArrayType *newType
1729      = new (*this, TypeAlignment)
1730          DependentSizedArrayType(*this, elementType, QualType(),
1731                                  numElements, ASM, elementTypeQuals,
1732                                  brackets);
1733    Types.push_back(newType);
1734    return QualType(newType, 0);
1735  }
1736
1737  // Otherwise, we actually build a new type every time, but we
1738  // also build a canonical type.
1739
1740  SplitQualType canonElementType = getCanonicalType(elementType).split();
1741
1742  void *insertPos = 0;
1743  llvm::FoldingSetNodeID ID;
1744  DependentSizedArrayType::Profile(ID, *this,
1745                                   QualType(canonElementType.first, 0),
1746                                   ASM, elementTypeQuals, numElements);
1747
1748  // Look for an existing type with these properties.
1749  DependentSizedArrayType *canonTy =
1750    DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1751
1752  // If we don't have one, build one.
1753  if (!canonTy) {
1754    canonTy = new (*this, TypeAlignment)
1755      DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1756                              QualType(), numElements, ASM, elementTypeQuals,
1757                              brackets);
1758    DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1759    Types.push_back(canonTy);
1760  }
1761
1762  // Apply qualifiers from the element type to the array.
1763  QualType canon = getQualifiedType(QualType(canonTy,0),
1764                                    canonElementType.second);
1765
1766  // If we didn't need extra canonicalization for the element type,
1767  // then just use that as our result.
1768  if (QualType(canonElementType.first, 0) == elementType)
1769    return canon;
1770
1771  // Otherwise, we need to build a type which follows the spelling
1772  // of the element type.
1773  DependentSizedArrayType *sugaredType
1774    = new (*this, TypeAlignment)
1775        DependentSizedArrayType(*this, elementType, canon, numElements,
1776                                ASM, elementTypeQuals, brackets);
1777  Types.push_back(sugaredType);
1778  return QualType(sugaredType, 0);
1779}
1780
1781QualType ASTContext::getIncompleteArrayType(QualType elementType,
1782                                            ArrayType::ArraySizeModifier ASM,
1783                                            unsigned elementTypeQuals) const {
1784  llvm::FoldingSetNodeID ID;
1785  IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
1786
1787  void *insertPos = 0;
1788  if (IncompleteArrayType *iat =
1789       IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1790    return QualType(iat, 0);
1791
1792  // If the element type isn't canonical, this won't be a canonical type
1793  // either, so fill in the canonical type field.  We also have to pull
1794  // qualifiers off the element type.
1795  QualType canon;
1796
1797  if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1798    SplitQualType canonSplit = getCanonicalType(elementType).split();
1799    canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1800                                   ASM, elementTypeQuals);
1801    canon = getQualifiedType(canon, canonSplit.second);
1802
1803    // Get the new insert position for the node we care about.
1804    IncompleteArrayType *existing =
1805      IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1806    assert(!existing && "Shouldn't be in the map!"); (void) existing;
1807  }
1808
1809  IncompleteArrayType *newType = new (*this, TypeAlignment)
1810    IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
1811
1812  IncompleteArrayTypes.InsertNode(newType, insertPos);
1813  Types.push_back(newType);
1814  return QualType(newType, 0);
1815}
1816
1817/// getVectorType - Return the unique reference to a vector type of
1818/// the specified element type and size. VectorType must be a built-in type.
1819QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1820                                   VectorType::VectorKind VecKind) const {
1821  assert(vecType->isBuiltinType());
1822
1823  // Check if we've already instantiated a vector of this type.
1824  llvm::FoldingSetNodeID ID;
1825  VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
1826
1827  void *InsertPos = 0;
1828  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1829    return QualType(VTP, 0);
1830
1831  // If the element type isn't canonical, this won't be a canonical type either,
1832  // so fill in the canonical type field.
1833  QualType Canonical;
1834  if (!vecType.isCanonical()) {
1835    Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
1836
1837    // Get the new insert position for the node we care about.
1838    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1839    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1840  }
1841  VectorType *New = new (*this, TypeAlignment)
1842    VectorType(vecType, NumElts, Canonical, VecKind);
1843  VectorTypes.InsertNode(New, InsertPos);
1844  Types.push_back(New);
1845  return QualType(New, 0);
1846}
1847
1848/// getExtVectorType - Return the unique reference to an extended vector type of
1849/// the specified element type and size. VectorType must be a built-in type.
1850QualType
1851ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
1852  assert(vecType->isBuiltinType());
1853
1854  // Check if we've already instantiated a vector of this type.
1855  llvm::FoldingSetNodeID ID;
1856  VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
1857                      VectorType::GenericVector);
1858  void *InsertPos = 0;
1859  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1860    return QualType(VTP, 0);
1861
1862  // If the element type isn't canonical, this won't be a canonical type either,
1863  // so fill in the canonical type field.
1864  QualType Canonical;
1865  if (!vecType.isCanonical()) {
1866    Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
1867
1868    // Get the new insert position for the node we care about.
1869    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1870    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1871  }
1872  ExtVectorType *New = new (*this, TypeAlignment)
1873    ExtVectorType(vecType, NumElts, Canonical);
1874  VectorTypes.InsertNode(New, InsertPos);
1875  Types.push_back(New);
1876  return QualType(New, 0);
1877}
1878
1879QualType
1880ASTContext::getDependentSizedExtVectorType(QualType vecType,
1881                                           Expr *SizeExpr,
1882                                           SourceLocation AttrLoc) const {
1883  llvm::FoldingSetNodeID ID;
1884  DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
1885                                       SizeExpr);
1886
1887  void *InsertPos = 0;
1888  DependentSizedExtVectorType *Canon
1889    = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1890  DependentSizedExtVectorType *New;
1891  if (Canon) {
1892    // We already have a canonical version of this array type; use it as
1893    // the canonical type for a newly-built type.
1894    New = new (*this, TypeAlignment)
1895      DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1896                                  SizeExpr, AttrLoc);
1897  } else {
1898    QualType CanonVecTy = getCanonicalType(vecType);
1899    if (CanonVecTy == vecType) {
1900      New = new (*this, TypeAlignment)
1901        DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1902                                    AttrLoc);
1903
1904      DependentSizedExtVectorType *CanonCheck
1905        = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1906      assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1907      (void)CanonCheck;
1908      DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1909    } else {
1910      QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1911                                                      SourceLocation());
1912      New = new (*this, TypeAlignment)
1913        DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
1914    }
1915  }
1916
1917  Types.push_back(New);
1918  return QualType(New, 0);
1919}
1920
1921/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
1922///
1923QualType
1924ASTContext::getFunctionNoProtoType(QualType ResultTy,
1925                                   const FunctionType::ExtInfo &Info) const {
1926  const CallingConv DefaultCC = Info.getCC();
1927  const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1928                               CC_X86StdCall : DefaultCC;
1929  // Unique functions, to guarantee there is only one function of a particular
1930  // structure.
1931  llvm::FoldingSetNodeID ID;
1932  FunctionNoProtoType::Profile(ID, ResultTy, Info);
1933
1934  void *InsertPos = 0;
1935  if (FunctionNoProtoType *FT =
1936        FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1937    return QualType(FT, 0);
1938
1939  QualType Canonical;
1940  if (!ResultTy.isCanonical() ||
1941      getCanonicalCallConv(CallConv) != CallConv) {
1942    Canonical =
1943      getFunctionNoProtoType(getCanonicalType(ResultTy),
1944                     Info.withCallingConv(getCanonicalCallConv(CallConv)));
1945
1946    // Get the new insert position for the node we care about.
1947    FunctionNoProtoType *NewIP =
1948      FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1949    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1950  }
1951
1952  FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
1953  FunctionNoProtoType *New = new (*this, TypeAlignment)
1954    FunctionNoProtoType(ResultTy, Canonical, newInfo);
1955  Types.push_back(New);
1956  FunctionNoProtoTypes.InsertNode(New, InsertPos);
1957  return QualType(New, 0);
1958}
1959
1960/// getFunctionType - Return a normal function type with a typed argument
1961/// list.  isVariadic indicates whether the argument list includes '...'.
1962QualType
1963ASTContext::getFunctionType(QualType ResultTy,
1964                            const QualType *ArgArray, unsigned NumArgs,
1965                            const FunctionProtoType::ExtProtoInfo &EPI) const {
1966  // Unique functions, to guarantee there is only one function of a particular
1967  // structure.
1968  llvm::FoldingSetNodeID ID;
1969  FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
1970
1971  void *InsertPos = 0;
1972  if (FunctionProtoType *FTP =
1973        FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1974    return QualType(FTP, 0);
1975
1976  // Determine whether the type being created is already canonical or not.
1977  bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
1978  for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1979    if (!ArgArray[i].isCanonicalAsParam())
1980      isCanonical = false;
1981
1982  const CallingConv DefaultCC = EPI.ExtInfo.getCC();
1983  const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1984                               CC_X86StdCall : DefaultCC;
1985
1986  // If this type isn't canonical, get the canonical version of it.
1987  // The exception spec is not part of the canonical type.
1988  QualType Canonical;
1989  if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
1990    llvm::SmallVector<QualType, 16> CanonicalArgs;
1991    CanonicalArgs.reserve(NumArgs);
1992    for (unsigned i = 0; i != NumArgs; ++i)
1993      CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
1994
1995    FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
1996    CanonicalEPI.ExceptionSpecType = EST_None;
1997    CanonicalEPI.NumExceptions = 0;
1998    CanonicalEPI.ExtInfo
1999      = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2000
2001    Canonical = getFunctionType(getCanonicalType(ResultTy),
2002                                CanonicalArgs.data(), NumArgs,
2003                                CanonicalEPI);
2004
2005    // Get the new insert position for the node we care about.
2006    FunctionProtoType *NewIP =
2007      FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2008    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2009  }
2010
2011  // FunctionProtoType objects are allocated with extra bytes after them
2012  // for two variable size arrays (for parameter and exception types) at the
2013  // end of them. Instead of the exception types, there could be a noexcept
2014  // expression and a context pointer.
2015  size_t Size = sizeof(FunctionProtoType) +
2016                NumArgs * sizeof(QualType);
2017  if (EPI.ExceptionSpecType == EST_Dynamic)
2018    Size += EPI.NumExceptions * sizeof(QualType);
2019  else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
2020    Size += sizeof(Expr*);
2021  }
2022  FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
2023  FunctionProtoType::ExtProtoInfo newEPI = EPI;
2024  newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
2025  new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
2026  Types.push_back(FTP);
2027  FunctionProtoTypes.InsertNode(FTP, InsertPos);
2028  return QualType(FTP, 0);
2029}
2030
2031#ifndef NDEBUG
2032static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2033  if (!isa<CXXRecordDecl>(D)) return false;
2034  const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2035  if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2036    return true;
2037  if (RD->getDescribedClassTemplate() &&
2038      !isa<ClassTemplateSpecializationDecl>(RD))
2039    return true;
2040  return false;
2041}
2042#endif
2043
2044/// getInjectedClassNameType - Return the unique reference to the
2045/// injected class name type for the specified templated declaration.
2046QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
2047                                              QualType TST) const {
2048  assert(NeedsInjectedClassNameType(Decl));
2049  if (Decl->TypeForDecl) {
2050    assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2051  } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
2052    assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2053    Decl->TypeForDecl = PrevDecl->TypeForDecl;
2054    assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2055  } else {
2056    Type *newType =
2057      new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
2058    Decl->TypeForDecl = newType;
2059    Types.push_back(newType);
2060  }
2061  return QualType(Decl->TypeForDecl, 0);
2062}
2063
2064/// getTypeDeclType - Return the unique reference to the type for the
2065/// specified type declaration.
2066QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
2067  assert(Decl && "Passed null for Decl param");
2068  assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
2069
2070  if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
2071    return getTypedefType(Typedef);
2072
2073  assert(!isa<TemplateTypeParmDecl>(Decl) &&
2074         "Template type parameter types are always available.");
2075
2076  if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
2077    assert(!Record->getPreviousDeclaration() &&
2078           "struct/union has previous declaration");
2079    assert(!NeedsInjectedClassNameType(Record));
2080    return getRecordType(Record);
2081  } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
2082    assert(!Enum->getPreviousDeclaration() &&
2083           "enum has previous declaration");
2084    return getEnumType(Enum);
2085  } else if (const UnresolvedUsingTypenameDecl *Using =
2086               dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
2087    Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2088    Decl->TypeForDecl = newType;
2089    Types.push_back(newType);
2090  } else
2091    llvm_unreachable("TypeDecl without a type?");
2092
2093  return QualType(Decl->TypeForDecl, 0);
2094}
2095
2096/// getTypedefType - Return the unique reference to the type for the
2097/// specified typedef name decl.
2098QualType
2099ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2100                           QualType Canonical) const {
2101  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2102
2103  if (Canonical.isNull())
2104    Canonical = getCanonicalType(Decl->getUnderlyingType());
2105  TypedefType *newType = new(*this, TypeAlignment)
2106    TypedefType(Type::Typedef, Decl, Canonical);
2107  Decl->TypeForDecl = newType;
2108  Types.push_back(newType);
2109  return QualType(newType, 0);
2110}
2111
2112QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
2113  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2114
2115  if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2116    if (PrevDecl->TypeForDecl)
2117      return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2118
2119  RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2120  Decl->TypeForDecl = newType;
2121  Types.push_back(newType);
2122  return QualType(newType, 0);
2123}
2124
2125QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
2126  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2127
2128  if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2129    if (PrevDecl->TypeForDecl)
2130      return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2131
2132  EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2133  Decl->TypeForDecl = newType;
2134  Types.push_back(newType);
2135  return QualType(newType, 0);
2136}
2137
2138QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2139                                       QualType modifiedType,
2140                                       QualType equivalentType) {
2141  llvm::FoldingSetNodeID id;
2142  AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2143
2144  void *insertPos = 0;
2145  AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2146  if (type) return QualType(type, 0);
2147
2148  QualType canon = getCanonicalType(equivalentType);
2149  type = new (*this, TypeAlignment)
2150           AttributedType(canon, attrKind, modifiedType, equivalentType);
2151
2152  Types.push_back(type);
2153  AttributedTypes.InsertNode(type, insertPos);
2154
2155  return QualType(type, 0);
2156}
2157
2158
2159/// \brief Retrieve a substitution-result type.
2160QualType
2161ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
2162                                         QualType Replacement) const {
2163  assert(Replacement.isCanonical()
2164         && "replacement types must always be canonical");
2165
2166  llvm::FoldingSetNodeID ID;
2167  SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2168  void *InsertPos = 0;
2169  SubstTemplateTypeParmType *SubstParm
2170    = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2171
2172  if (!SubstParm) {
2173    SubstParm = new (*this, TypeAlignment)
2174      SubstTemplateTypeParmType(Parm, Replacement);
2175    Types.push_back(SubstParm);
2176    SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2177  }
2178
2179  return QualType(SubstParm, 0);
2180}
2181
2182/// \brief Retrieve a
2183QualType ASTContext::getSubstTemplateTypeParmPackType(
2184                                          const TemplateTypeParmType *Parm,
2185                                              const TemplateArgument &ArgPack) {
2186#ifndef NDEBUG
2187  for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2188                                    PEnd = ArgPack.pack_end();
2189       P != PEnd; ++P) {
2190    assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2191    assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2192  }
2193#endif
2194
2195  llvm::FoldingSetNodeID ID;
2196  SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2197  void *InsertPos = 0;
2198  if (SubstTemplateTypeParmPackType *SubstParm
2199        = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2200    return QualType(SubstParm, 0);
2201
2202  QualType Canon;
2203  if (!Parm->isCanonicalUnqualified()) {
2204    Canon = getCanonicalType(QualType(Parm, 0));
2205    Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2206                                             ArgPack);
2207    SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2208  }
2209
2210  SubstTemplateTypeParmPackType *SubstParm
2211    = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2212                                                               ArgPack);
2213  Types.push_back(SubstParm);
2214  SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2215  return QualType(SubstParm, 0);
2216}
2217
2218/// \brief Retrieve the template type parameter type for a template
2219/// parameter or parameter pack with the given depth, index, and (optionally)
2220/// name.
2221QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
2222                                             bool ParameterPack,
2223                                             TemplateTypeParmDecl *TTPDecl) const {
2224  llvm::FoldingSetNodeID ID;
2225  TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
2226  void *InsertPos = 0;
2227  TemplateTypeParmType *TypeParm
2228    = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2229
2230  if (TypeParm)
2231    return QualType(TypeParm, 0);
2232
2233  if (TTPDecl) {
2234    QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
2235    TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
2236
2237    TemplateTypeParmType *TypeCheck
2238      = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2239    assert(!TypeCheck && "Template type parameter canonical type broken");
2240    (void)TypeCheck;
2241  } else
2242    TypeParm = new (*this, TypeAlignment)
2243      TemplateTypeParmType(Depth, Index, ParameterPack);
2244
2245  Types.push_back(TypeParm);
2246  TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2247
2248  return QualType(TypeParm, 0);
2249}
2250
2251TypeSourceInfo *
2252ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2253                                              SourceLocation NameLoc,
2254                                        const TemplateArgumentListInfo &Args,
2255                                              QualType Underlying) const {
2256  assert(!Name.getAsDependentTemplateName() &&
2257         "No dependent template names here!");
2258  QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
2259
2260  TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2261  TemplateSpecializationTypeLoc TL
2262    = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2263  TL.setTemplateNameLoc(NameLoc);
2264  TL.setLAngleLoc(Args.getLAngleLoc());
2265  TL.setRAngleLoc(Args.getRAngleLoc());
2266  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2267    TL.setArgLocInfo(i, Args[i].getLocInfo());
2268  return DI;
2269}
2270
2271QualType
2272ASTContext::getTemplateSpecializationType(TemplateName Template,
2273                                          const TemplateArgumentListInfo &Args,
2274                                          QualType Underlying) const {
2275  assert(!Template.getAsDependentTemplateName() &&
2276         "No dependent template names here!");
2277
2278  unsigned NumArgs = Args.size();
2279
2280  llvm::SmallVector<TemplateArgument, 4> ArgVec;
2281  ArgVec.reserve(NumArgs);
2282  for (unsigned i = 0; i != NumArgs; ++i)
2283    ArgVec.push_back(Args[i].getArgument());
2284
2285  return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
2286                                       Underlying);
2287}
2288
2289QualType
2290ASTContext::getTemplateSpecializationType(TemplateName Template,
2291                                          const TemplateArgument *Args,
2292                                          unsigned NumArgs,
2293                                          QualType Underlying) const {
2294  assert(!Template.getAsDependentTemplateName() &&
2295         "No dependent template names here!");
2296  // Look through qualified template names.
2297  if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2298    Template = TemplateName(QTN->getTemplateDecl());
2299
2300  bool isTypeAlias =
2301    Template.getAsTemplateDecl() &&
2302    isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2303
2304  QualType CanonType;
2305  if (!Underlying.isNull())
2306    CanonType = getCanonicalType(Underlying);
2307  else {
2308    assert(!isTypeAlias &&
2309           "Underlying type for template alias must be computed by caller");
2310    CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2311                                                       NumArgs);
2312  }
2313
2314  // Allocate the (non-canonical) template specialization type, but don't
2315  // try to unique it: these types typically have location information that
2316  // we don't unique and don't want to lose.
2317  void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2318                       sizeof(TemplateArgument) * NumArgs +
2319                       (isTypeAlias ? sizeof(QualType) : 0),
2320                       TypeAlignment);
2321  TemplateSpecializationType *Spec
2322    = new (Mem) TemplateSpecializationType(Template,
2323                                           Args, NumArgs,
2324                                           CanonType,
2325                                         isTypeAlias ? Underlying : QualType());
2326
2327  Types.push_back(Spec);
2328  return QualType(Spec, 0);
2329}
2330
2331QualType
2332ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2333                                                   const TemplateArgument *Args,
2334                                                   unsigned NumArgs) const {
2335  assert(!Template.getAsDependentTemplateName() &&
2336         "No dependent template names here!");
2337  assert((!Template.getAsTemplateDecl() ||
2338          !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
2339         "Underlying type for template alias must be computed by caller");
2340
2341  // Look through qualified template names.
2342  if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2343    Template = TemplateName(QTN->getTemplateDecl());
2344
2345  // Build the canonical template specialization type.
2346  TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2347  llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2348  CanonArgs.reserve(NumArgs);
2349  for (unsigned I = 0; I != NumArgs; ++I)
2350    CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2351
2352  // Determine whether this canonical template specialization type already
2353  // exists.
2354  llvm::FoldingSetNodeID ID;
2355  TemplateSpecializationType::Profile(ID, CanonTemplate,
2356                                      CanonArgs.data(), NumArgs, *this);
2357
2358  void *InsertPos = 0;
2359  TemplateSpecializationType *Spec
2360    = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2361
2362  if (!Spec) {
2363    // Allocate a new canonical template specialization type.
2364    void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2365                          sizeof(TemplateArgument) * NumArgs),
2366                         TypeAlignment);
2367    Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2368                                                CanonArgs.data(), NumArgs,
2369                                                QualType(), QualType());
2370    Types.push_back(Spec);
2371    TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2372  }
2373
2374  assert(Spec->isDependentType() &&
2375         "Non-dependent template-id type must have a canonical type");
2376  return QualType(Spec, 0);
2377}
2378
2379QualType
2380ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2381                              NestedNameSpecifier *NNS,
2382                              QualType NamedType) const {
2383  llvm::FoldingSetNodeID ID;
2384  ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
2385
2386  void *InsertPos = 0;
2387  ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2388  if (T)
2389    return QualType(T, 0);
2390
2391  QualType Canon = NamedType;
2392  if (!Canon.isCanonical()) {
2393    Canon = getCanonicalType(NamedType);
2394    ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2395    assert(!CheckT && "Elaborated canonical type broken");
2396    (void)CheckT;
2397  }
2398
2399  T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
2400  Types.push_back(T);
2401  ElaboratedTypes.InsertNode(T, InsertPos);
2402  return QualType(T, 0);
2403}
2404
2405QualType
2406ASTContext::getParenType(QualType InnerType) const {
2407  llvm::FoldingSetNodeID ID;
2408  ParenType::Profile(ID, InnerType);
2409
2410  void *InsertPos = 0;
2411  ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2412  if (T)
2413    return QualType(T, 0);
2414
2415  QualType Canon = InnerType;
2416  if (!Canon.isCanonical()) {
2417    Canon = getCanonicalType(InnerType);
2418    ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2419    assert(!CheckT && "Paren canonical type broken");
2420    (void)CheckT;
2421  }
2422
2423  T = new (*this) ParenType(InnerType, Canon);
2424  Types.push_back(T);
2425  ParenTypes.InsertNode(T, InsertPos);
2426  return QualType(T, 0);
2427}
2428
2429QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2430                                          NestedNameSpecifier *NNS,
2431                                          const IdentifierInfo *Name,
2432                                          QualType Canon) const {
2433  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2434
2435  if (Canon.isNull()) {
2436    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2437    ElaboratedTypeKeyword CanonKeyword = Keyword;
2438    if (Keyword == ETK_None)
2439      CanonKeyword = ETK_Typename;
2440
2441    if (CanonNNS != NNS || CanonKeyword != Keyword)
2442      Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
2443  }
2444
2445  llvm::FoldingSetNodeID ID;
2446  DependentNameType::Profile(ID, Keyword, NNS, Name);
2447
2448  void *InsertPos = 0;
2449  DependentNameType *T
2450    = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2451  if (T)
2452    return QualType(T, 0);
2453
2454  T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
2455  Types.push_back(T);
2456  DependentNameTypes.InsertNode(T, InsertPos);
2457  return QualType(T, 0);
2458}
2459
2460QualType
2461ASTContext::getDependentTemplateSpecializationType(
2462                                 ElaboratedTypeKeyword Keyword,
2463                                 NestedNameSpecifier *NNS,
2464                                 const IdentifierInfo *Name,
2465                                 const TemplateArgumentListInfo &Args) const {
2466  // TODO: avoid this copy
2467  llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2468  for (unsigned I = 0, E = Args.size(); I != E; ++I)
2469    ArgCopy.push_back(Args[I].getArgument());
2470  return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2471                                                ArgCopy.size(),
2472                                                ArgCopy.data());
2473}
2474
2475QualType
2476ASTContext::getDependentTemplateSpecializationType(
2477                                 ElaboratedTypeKeyword Keyword,
2478                                 NestedNameSpecifier *NNS,
2479                                 const IdentifierInfo *Name,
2480                                 unsigned NumArgs,
2481                                 const TemplateArgument *Args) const {
2482  assert((!NNS || NNS->isDependent()) &&
2483         "nested-name-specifier must be dependent");
2484
2485  llvm::FoldingSetNodeID ID;
2486  DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2487                                               Name, NumArgs, Args);
2488
2489  void *InsertPos = 0;
2490  DependentTemplateSpecializationType *T
2491    = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2492  if (T)
2493    return QualType(T, 0);
2494
2495  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2496
2497  ElaboratedTypeKeyword CanonKeyword = Keyword;
2498  if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2499
2500  bool AnyNonCanonArgs = false;
2501  llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2502  for (unsigned I = 0; I != NumArgs; ++I) {
2503    CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2504    if (!CanonArgs[I].structurallyEquals(Args[I]))
2505      AnyNonCanonArgs = true;
2506  }
2507
2508  QualType Canon;
2509  if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2510    Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2511                                                   Name, NumArgs,
2512                                                   CanonArgs.data());
2513
2514    // Find the insert position again.
2515    DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2516  }
2517
2518  void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2519                        sizeof(TemplateArgument) * NumArgs),
2520                       TypeAlignment);
2521  T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
2522                                                    Name, NumArgs, Args, Canon);
2523  Types.push_back(T);
2524  DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
2525  return QualType(T, 0);
2526}
2527
2528QualType ASTContext::getPackExpansionType(QualType Pattern,
2529                                      llvm::Optional<unsigned> NumExpansions) {
2530  llvm::FoldingSetNodeID ID;
2531  PackExpansionType::Profile(ID, Pattern, NumExpansions);
2532
2533  assert(Pattern->containsUnexpandedParameterPack() &&
2534         "Pack expansions must expand one or more parameter packs");
2535  void *InsertPos = 0;
2536  PackExpansionType *T
2537    = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2538  if (T)
2539    return QualType(T, 0);
2540
2541  QualType Canon;
2542  if (!Pattern.isCanonical()) {
2543    Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
2544
2545    // Find the insert position again.
2546    PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2547  }
2548
2549  T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
2550  Types.push_back(T);
2551  PackExpansionTypes.InsertNode(T, InsertPos);
2552  return QualType(T, 0);
2553}
2554
2555/// CmpProtocolNames - Comparison predicate for sorting protocols
2556/// alphabetically.
2557static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2558                            const ObjCProtocolDecl *RHS) {
2559  return LHS->getDeclName() < RHS->getDeclName();
2560}
2561
2562static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
2563                                unsigned NumProtocols) {
2564  if (NumProtocols == 0) return true;
2565
2566  for (unsigned i = 1; i != NumProtocols; ++i)
2567    if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2568      return false;
2569  return true;
2570}
2571
2572static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
2573                                   unsigned &NumProtocols) {
2574  ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
2575
2576  // Sort protocols, keyed by name.
2577  std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2578
2579  // Remove duplicates.
2580  ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2581  NumProtocols = ProtocolsEnd-Protocols;
2582}
2583
2584QualType ASTContext::getObjCObjectType(QualType BaseType,
2585                                       ObjCProtocolDecl * const *Protocols,
2586                                       unsigned NumProtocols) const {
2587  // If the base type is an interface and there aren't any protocols
2588  // to add, then the interface type will do just fine.
2589  if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2590    return BaseType;
2591
2592  // Look in the folding set for an existing type.
2593  llvm::FoldingSetNodeID ID;
2594  ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
2595  void *InsertPos = 0;
2596  if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2597    return QualType(QT, 0);
2598
2599  // Build the canonical type, which has the canonical base type and
2600  // a sorted-and-uniqued list of protocols.
2601  QualType Canonical;
2602  bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2603  if (!ProtocolsSorted || !BaseType.isCanonical()) {
2604    if (!ProtocolsSorted) {
2605      llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2606                                                     Protocols + NumProtocols);
2607      unsigned UniqueCount = NumProtocols;
2608
2609      SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2610      Canonical = getObjCObjectType(getCanonicalType(BaseType),
2611                                    &Sorted[0], UniqueCount);
2612    } else {
2613      Canonical = getObjCObjectType(getCanonicalType(BaseType),
2614                                    Protocols, NumProtocols);
2615    }
2616
2617    // Regenerate InsertPos.
2618    ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2619  }
2620
2621  unsigned Size = sizeof(ObjCObjectTypeImpl);
2622  Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2623  void *Mem = Allocate(Size, TypeAlignment);
2624  ObjCObjectTypeImpl *T =
2625    new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2626
2627  Types.push_back(T);
2628  ObjCObjectTypes.InsertNode(T, InsertPos);
2629  return QualType(T, 0);
2630}
2631
2632/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2633/// the given object type.
2634QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
2635  llvm::FoldingSetNodeID ID;
2636  ObjCObjectPointerType::Profile(ID, ObjectT);
2637
2638  void *InsertPos = 0;
2639  if (ObjCObjectPointerType *QT =
2640              ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2641    return QualType(QT, 0);
2642
2643  // Find the canonical object type.
2644  QualType Canonical;
2645  if (!ObjectT.isCanonical()) {
2646    Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2647
2648    // Regenerate InsertPos.
2649    ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2650  }
2651
2652  // No match.
2653  void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2654  ObjCObjectPointerType *QType =
2655    new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
2656
2657  Types.push_back(QType);
2658  ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2659  return QualType(QType, 0);
2660}
2661
2662/// getObjCInterfaceType - Return the unique reference to the type for the
2663/// specified ObjC interface decl. The list of protocols is optional.
2664QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
2665  if (Decl->TypeForDecl)
2666    return QualType(Decl->TypeForDecl, 0);
2667
2668  // FIXME: redeclarations?
2669  void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2670  ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2671  Decl->TypeForDecl = T;
2672  Types.push_back(T);
2673  return QualType(T, 0);
2674}
2675
2676/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2677/// TypeOfExprType AST's (since expression's are never shared). For example,
2678/// multiple declarations that refer to "typeof(x)" all contain different
2679/// DeclRefExpr's. This doesn't effect the type checker, since it operates
2680/// on canonical type's (which are always unique).
2681QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
2682  TypeOfExprType *toe;
2683  if (tofExpr->isTypeDependent()) {
2684    llvm::FoldingSetNodeID ID;
2685    DependentTypeOfExprType::Profile(ID, *this, tofExpr);
2686
2687    void *InsertPos = 0;
2688    DependentTypeOfExprType *Canon
2689      = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2690    if (Canon) {
2691      // We already have a "canonical" version of an identical, dependent
2692      // typeof(expr) type. Use that as our canonical type.
2693      toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
2694                                          QualType((TypeOfExprType*)Canon, 0));
2695    }
2696    else {
2697      // Build a new, canonical typeof(expr) type.
2698      Canon
2699        = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
2700      DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2701      toe = Canon;
2702    }
2703  } else {
2704    QualType Canonical = getCanonicalType(tofExpr->getType());
2705    toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
2706  }
2707  Types.push_back(toe);
2708  return QualType(toe, 0);
2709}
2710
2711/// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
2712/// TypeOfType AST's. The only motivation to unique these nodes would be
2713/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
2714/// an issue. This doesn't effect the type checker, since it operates
2715/// on canonical type's (which are always unique).
2716QualType ASTContext::getTypeOfType(QualType tofType) const {
2717  QualType Canonical = getCanonicalType(tofType);
2718  TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
2719  Types.push_back(tot);
2720  return QualType(tot, 0);
2721}
2722
2723/// getDecltypeForExpr - Given an expr, will return the decltype for that
2724/// expression, according to the rules in C++0x [dcl.type.simple]p4
2725static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
2726  if (e->isTypeDependent())
2727    return Context.DependentTy;
2728
2729  // If e is an id expression or a class member access, decltype(e) is defined
2730  // as the type of the entity named by e.
2731  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2732    if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2733      return VD->getType();
2734  }
2735  if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2736    if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2737      return FD->getType();
2738  }
2739  // If e is a function call or an invocation of an overloaded operator,
2740  // (parentheses around e are ignored), decltype(e) is defined as the
2741  // return type of that function.
2742  if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2743    return CE->getCallReturnType();
2744
2745  QualType T = e->getType();
2746
2747  // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
2748  // defined as T&, otherwise decltype(e) is defined as T.
2749  if (e->isLValue())
2750    T = Context.getLValueReferenceType(T);
2751
2752  return T;
2753}
2754
2755/// getDecltypeType -  Unlike many "get<Type>" functions, we don't unique
2756/// DecltypeType AST's. The only motivation to unique these nodes would be
2757/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
2758/// an issue. This doesn't effect the type checker, since it operates
2759/// on canonical type's (which are always unique).
2760QualType ASTContext::getDecltypeType(Expr *e) const {
2761  DecltypeType *dt;
2762  if (e->isTypeDependent()) {
2763    llvm::FoldingSetNodeID ID;
2764    DependentDecltypeType::Profile(ID, *this, e);
2765
2766    void *InsertPos = 0;
2767    DependentDecltypeType *Canon
2768      = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2769    if (Canon) {
2770      // We already have a "canonical" version of an equivalent, dependent
2771      // decltype type. Use that as our canonical type.
2772      dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
2773                                       QualType((DecltypeType*)Canon, 0));
2774    }
2775    else {
2776      // Build a new, canonical typeof(expr) type.
2777      Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
2778      DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2779      dt = Canon;
2780    }
2781  } else {
2782    QualType T = getDecltypeForExpr(e, *this);
2783    dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
2784  }
2785  Types.push_back(dt);
2786  return QualType(dt, 0);
2787}
2788
2789/// getAutoType - We only unique auto types after they've been deduced.
2790QualType ASTContext::getAutoType(QualType DeducedType) const {
2791  void *InsertPos = 0;
2792  if (!DeducedType.isNull()) {
2793    // Look in the folding set for an existing type.
2794    llvm::FoldingSetNodeID ID;
2795    AutoType::Profile(ID, DeducedType);
2796    if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2797      return QualType(AT, 0);
2798  }
2799
2800  AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2801  Types.push_back(AT);
2802  if (InsertPos)
2803    AutoTypes.InsertNode(AT, InsertPos);
2804  return QualType(AT, 0);
2805}
2806
2807/// getAutoDeductType - Get type pattern for deducing against 'auto'.
2808QualType ASTContext::getAutoDeductType() const {
2809  if (AutoDeductTy.isNull())
2810    AutoDeductTy = getAutoType(QualType());
2811  assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
2812  return AutoDeductTy;
2813}
2814
2815/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
2816QualType ASTContext::getAutoRRefDeductType() const {
2817  if (AutoRRefDeductTy.isNull())
2818    AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
2819  assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
2820  return AutoRRefDeductTy;
2821}
2822
2823/// getTagDeclType - Return the unique reference to the type for the
2824/// specified TagDecl (struct/union/class/enum) decl.
2825QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
2826  assert (Decl);
2827  // FIXME: What is the design on getTagDeclType when it requires casting
2828  // away const?  mutable?
2829  return getTypeDeclType(const_cast<TagDecl*>(Decl));
2830}
2831
2832/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2833/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2834/// needs to agree with the definition in <stddef.h>.
2835CanQualType ASTContext::getSizeType() const {
2836  return getFromTargetType(Target.getSizeType());
2837}
2838
2839/// getSignedWCharType - Return the type of "signed wchar_t".
2840/// Used when in C++, as a GCC extension.
2841QualType ASTContext::getSignedWCharType() const {
2842  // FIXME: derive from "Target" ?
2843  return WCharTy;
2844}
2845
2846/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2847/// Used when in C++, as a GCC extension.
2848QualType ASTContext::getUnsignedWCharType() const {
2849  // FIXME: derive from "Target" ?
2850  return UnsignedIntTy;
2851}
2852
2853/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2854/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2855QualType ASTContext::getPointerDiffType() const {
2856  return getFromTargetType(Target.getPtrDiffType(0));
2857}
2858
2859//===----------------------------------------------------------------------===//
2860//                              Type Operators
2861//===----------------------------------------------------------------------===//
2862
2863CanQualType ASTContext::getCanonicalParamType(QualType T) const {
2864  // Push qualifiers into arrays, and then discard any remaining
2865  // qualifiers.
2866  T = getCanonicalType(T);
2867  T = getVariableArrayDecayedType(T);
2868  const Type *Ty = T.getTypePtr();
2869  QualType Result;
2870  if (isa<ArrayType>(Ty)) {
2871    Result = getArrayDecayedType(QualType(Ty,0));
2872  } else if (isa<FunctionType>(Ty)) {
2873    Result = getPointerType(QualType(Ty, 0));
2874  } else {
2875    Result = QualType(Ty, 0);
2876  }
2877
2878  return CanQualType::CreateUnsafe(Result);
2879}
2880
2881
2882QualType ASTContext::getUnqualifiedArrayType(QualType type,
2883                                             Qualifiers &quals) {
2884  SplitQualType splitType = type.getSplitUnqualifiedType();
2885
2886  // FIXME: getSplitUnqualifiedType() actually walks all the way to
2887  // the unqualified desugared type and then drops it on the floor.
2888  // We then have to strip that sugar back off with
2889  // getUnqualifiedDesugaredType(), which is silly.
2890  const ArrayType *AT =
2891    dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2892
2893  // If we don't have an array, just use the results in splitType.
2894  if (!AT) {
2895    quals = splitType.second;
2896    return QualType(splitType.first, 0);
2897  }
2898
2899  // Otherwise, recurse on the array's element type.
2900  QualType elementType = AT->getElementType();
2901  QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2902
2903  // If that didn't change the element type, AT has no qualifiers, so we
2904  // can just use the results in splitType.
2905  if (elementType == unqualElementType) {
2906    assert(quals.empty()); // from the recursive call
2907    quals = splitType.second;
2908    return QualType(splitType.first, 0);
2909  }
2910
2911  // Otherwise, add in the qualifiers from the outermost type, then
2912  // build the type back up.
2913  quals.addConsistentQualifiers(splitType.second);
2914
2915  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
2916    return getConstantArrayType(unqualElementType, CAT->getSize(),
2917                                CAT->getSizeModifier(), 0);
2918  }
2919
2920  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
2921    return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
2922  }
2923
2924  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2925    return getVariableArrayType(unqualElementType,
2926                                VAT->getSizeExpr(),
2927                                VAT->getSizeModifier(),
2928                                VAT->getIndexTypeCVRQualifiers(),
2929                                VAT->getBracketsRange());
2930  }
2931
2932  const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
2933  return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
2934                                    DSAT->getSizeModifier(), 0,
2935                                    SourceRange());
2936}
2937
2938/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types  that
2939/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2940/// they point to and return true. If T1 and T2 aren't pointer types
2941/// or pointer-to-member types, or if they are not similar at this
2942/// level, returns false and leaves T1 and T2 unchanged. Top-level
2943/// qualifiers on T1 and T2 are ignored. This function will typically
2944/// be called in a loop that successively "unwraps" pointer and
2945/// pointer-to-member types to compare them at each level.
2946bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2947  const PointerType *T1PtrType = T1->getAs<PointerType>(),
2948                    *T2PtrType = T2->getAs<PointerType>();
2949  if (T1PtrType && T2PtrType) {
2950    T1 = T1PtrType->getPointeeType();
2951    T2 = T2PtrType->getPointeeType();
2952    return true;
2953  }
2954
2955  const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2956                          *T2MPType = T2->getAs<MemberPointerType>();
2957  if (T1MPType && T2MPType &&
2958      hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2959                             QualType(T2MPType->getClass(), 0))) {
2960    T1 = T1MPType->getPointeeType();
2961    T2 = T2MPType->getPointeeType();
2962    return true;
2963  }
2964
2965  if (getLangOptions().ObjC1) {
2966    const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2967                                *T2OPType = T2->getAs<ObjCObjectPointerType>();
2968    if (T1OPType && T2OPType) {
2969      T1 = T1OPType->getPointeeType();
2970      T2 = T2OPType->getPointeeType();
2971      return true;
2972    }
2973  }
2974
2975  // FIXME: Block pointers, too?
2976
2977  return false;
2978}
2979
2980DeclarationNameInfo
2981ASTContext::getNameForTemplate(TemplateName Name,
2982                               SourceLocation NameLoc) const {
2983  if (TemplateDecl *TD = Name.getAsTemplateDecl())
2984    // DNInfo work in progress: CHECKME: what about DNLoc?
2985    return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2986
2987  if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2988    DeclarationName DName;
2989    if (DTN->isIdentifier()) {
2990      DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2991      return DeclarationNameInfo(DName, NameLoc);
2992    } else {
2993      DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2994      // DNInfo work in progress: FIXME: source locations?
2995      DeclarationNameLoc DNLoc;
2996      DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2997      DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2998      return DeclarationNameInfo(DName, NameLoc, DNLoc);
2999    }
3000  }
3001
3002  OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3003  assert(Storage);
3004  // DNInfo work in progress: CHECKME: what about DNLoc?
3005  return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3006}
3007
3008TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
3009  if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3010    if (TemplateTemplateParmDecl *TTP
3011                              = dyn_cast<TemplateTemplateParmDecl>(Template))
3012      Template = getCanonicalTemplateTemplateParmDecl(TTP);
3013
3014    // The canonical template name is the canonical template declaration.
3015    return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
3016  }
3017
3018  if (SubstTemplateTemplateParmPackStorage *SubstPack
3019                                  = Name.getAsSubstTemplateTemplateParmPack()) {
3020    TemplateTemplateParmDecl *CanonParam
3021      = getCanonicalTemplateTemplateParmDecl(SubstPack->getParameterPack());
3022    TemplateArgument CanonArgPack
3023      = getCanonicalTemplateArgument(SubstPack->getArgumentPack());
3024    return getSubstTemplateTemplateParmPack(CanonParam, CanonArgPack);
3025  }
3026
3027  assert(!Name.getAsOverloadedTemplate());
3028
3029  DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3030  assert(DTN && "Non-dependent template names must refer to template decls.");
3031  return DTN->CanonicalTemplateName;
3032}
3033
3034bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3035  X = getCanonicalTemplateName(X);
3036  Y = getCanonicalTemplateName(Y);
3037  return X.getAsVoidPointer() == Y.getAsVoidPointer();
3038}
3039
3040TemplateArgument
3041ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
3042  switch (Arg.getKind()) {
3043    case TemplateArgument::Null:
3044      return Arg;
3045
3046    case TemplateArgument::Expression:
3047      return Arg;
3048
3049    case TemplateArgument::Declaration:
3050      return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
3051
3052    case TemplateArgument::Template:
3053      return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
3054
3055    case TemplateArgument::TemplateExpansion:
3056      return TemplateArgument(getCanonicalTemplateName(
3057                                         Arg.getAsTemplateOrTemplatePattern()),
3058                              Arg.getNumTemplateExpansions());
3059
3060    case TemplateArgument::Integral:
3061      return TemplateArgument(*Arg.getAsIntegral(),
3062                              getCanonicalType(Arg.getIntegralType()));
3063
3064    case TemplateArgument::Type:
3065      return TemplateArgument(getCanonicalType(Arg.getAsType()));
3066
3067    case TemplateArgument::Pack: {
3068      if (Arg.pack_size() == 0)
3069        return Arg;
3070
3071      TemplateArgument *CanonArgs
3072        = new (*this) TemplateArgument[Arg.pack_size()];
3073      unsigned Idx = 0;
3074      for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
3075                                        AEnd = Arg.pack_end();
3076           A != AEnd; (void)++A, ++Idx)
3077        CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
3078
3079      return TemplateArgument(CanonArgs, Arg.pack_size());
3080    }
3081  }
3082
3083  // Silence GCC warning
3084  assert(false && "Unhandled template argument kind");
3085  return TemplateArgument();
3086}
3087
3088NestedNameSpecifier *
3089ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
3090  if (!NNS)
3091    return 0;
3092
3093  switch (NNS->getKind()) {
3094  case NestedNameSpecifier::Identifier:
3095    // Canonicalize the prefix but keep the identifier the same.
3096    return NestedNameSpecifier::Create(*this,
3097                         getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3098                                       NNS->getAsIdentifier());
3099
3100  case NestedNameSpecifier::Namespace:
3101    // A namespace is canonical; build a nested-name-specifier with
3102    // this namespace and no prefix.
3103    return NestedNameSpecifier::Create(*this, 0,
3104                                 NNS->getAsNamespace()->getOriginalNamespace());
3105
3106  case NestedNameSpecifier::NamespaceAlias:
3107    // A namespace is canonical; build a nested-name-specifier with
3108    // this namespace and no prefix.
3109    return NestedNameSpecifier::Create(*this, 0,
3110                                    NNS->getAsNamespaceAlias()->getNamespace()
3111                                                      ->getOriginalNamespace());
3112
3113  case NestedNameSpecifier::TypeSpec:
3114  case NestedNameSpecifier::TypeSpecWithTemplate: {
3115    QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
3116
3117    // If we have some kind of dependent-named type (e.g., "typename T::type"),
3118    // break it apart into its prefix and identifier, then reconsititute those
3119    // as the canonical nested-name-specifier. This is required to canonicalize
3120    // a dependent nested-name-specifier involving typedefs of dependent-name
3121    // types, e.g.,
3122    //   typedef typename T::type T1;
3123    //   typedef typename T1::type T2;
3124    if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3125      NestedNameSpecifier *Prefix
3126        = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3127      return NestedNameSpecifier::Create(*this, Prefix,
3128                           const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3129    }
3130
3131    // Do the same thing as above, but with dependent-named specializations.
3132    if (const DependentTemplateSpecializationType *DTST
3133          = T->getAs<DependentTemplateSpecializationType>()) {
3134      NestedNameSpecifier *Prefix
3135        = getCanonicalNestedNameSpecifier(DTST->getQualifier());
3136
3137      T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3138                                                 Prefix, DTST->getIdentifier(),
3139                                                 DTST->getNumArgs(),
3140                                                 DTST->getArgs());
3141      T = getCanonicalType(T);
3142    }
3143
3144    return NestedNameSpecifier::Create(*this, 0, false,
3145                                       const_cast<Type*>(T.getTypePtr()));
3146  }
3147
3148  case NestedNameSpecifier::Global:
3149    // The global specifier is canonical and unique.
3150    return NNS;
3151  }
3152
3153  // Required to silence a GCC warning
3154  return 0;
3155}
3156
3157
3158const ArrayType *ASTContext::getAsArrayType(QualType T) const {
3159  // Handle the non-qualified case efficiently.
3160  if (!T.hasLocalQualifiers()) {
3161    // Handle the common positive case fast.
3162    if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3163      return AT;
3164  }
3165
3166  // Handle the common negative case fast.
3167  if (!isa<ArrayType>(T.getCanonicalType()))
3168    return 0;
3169
3170  // Apply any qualifiers from the array type to the element type.  This
3171  // implements C99 6.7.3p8: "If the specification of an array type includes
3172  // any type qualifiers, the element type is so qualified, not the array type."
3173
3174  // If we get here, we either have type qualifiers on the type, or we have
3175  // sugar such as a typedef in the way.  If we have type qualifiers on the type
3176  // we must propagate them down into the element type.
3177
3178  SplitQualType split = T.getSplitDesugaredType();
3179  Qualifiers qs = split.second;
3180
3181  // If we have a simple case, just return now.
3182  const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3183  if (ATy == 0 || qs.empty())
3184    return ATy;
3185
3186  // Otherwise, we have an array and we have qualifiers on it.  Push the
3187  // qualifiers into the array element type and return a new array type.
3188  QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
3189
3190  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3191    return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3192                                                CAT->getSizeModifier(),
3193                                           CAT->getIndexTypeCVRQualifiers()));
3194  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3195    return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3196                                                  IAT->getSizeModifier(),
3197                                           IAT->getIndexTypeCVRQualifiers()));
3198
3199  if (const DependentSizedArrayType *DSAT
3200        = dyn_cast<DependentSizedArrayType>(ATy))
3201    return cast<ArrayType>(
3202                     getDependentSizedArrayType(NewEltTy,
3203                                                DSAT->getSizeExpr(),
3204                                                DSAT->getSizeModifier(),
3205                                              DSAT->getIndexTypeCVRQualifiers(),
3206                                                DSAT->getBracketsRange()));
3207
3208  const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
3209  return cast<ArrayType>(getVariableArrayType(NewEltTy,
3210                                              VAT->getSizeExpr(),
3211                                              VAT->getSizeModifier(),
3212                                              VAT->getIndexTypeCVRQualifiers(),
3213                                              VAT->getBracketsRange()));
3214}
3215
3216/// getArrayDecayedType - Return the properly qualified result of decaying the
3217/// specified array type to a pointer.  This operation is non-trivial when
3218/// handling typedefs etc.  The canonical type of "T" must be an array type,
3219/// this returns a pointer to a properly qualified element of the array.
3220///
3221/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
3222QualType ASTContext::getArrayDecayedType(QualType Ty) const {
3223  // Get the element type with 'getAsArrayType' so that we don't lose any
3224  // typedefs in the element type of the array.  This also handles propagation
3225  // of type qualifiers from the array type into the element type if present
3226  // (C99 6.7.3p8).
3227  const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3228  assert(PrettyArrayType && "Not an array type!");
3229
3230  QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
3231
3232  // int x[restrict 4] ->  int *restrict
3233  return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
3234}
3235
3236QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3237  return getBaseElementType(array->getElementType());
3238}
3239
3240QualType ASTContext::getBaseElementType(QualType type) const {
3241  Qualifiers qs;
3242  while (true) {
3243    SplitQualType split = type.getSplitDesugaredType();
3244    const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3245    if (!array) break;
3246
3247    type = array->getElementType();
3248    qs.addConsistentQualifiers(split.second);
3249  }
3250
3251  return getQualifiedType(type, qs);
3252}
3253
3254/// getConstantArrayElementCount - Returns number of constant array elements.
3255uint64_t
3256ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
3257  uint64_t ElementCount = 1;
3258  do {
3259    ElementCount *= CA->getSize().getZExtValue();
3260    CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3261  } while (CA);
3262  return ElementCount;
3263}
3264
3265/// getFloatingRank - Return a relative rank for floating point types.
3266/// This routine will assert if passed a built-in type that isn't a float.
3267static FloatingRank getFloatingRank(QualType T) {
3268  if (const ComplexType *CT = T->getAs<ComplexType>())
3269    return getFloatingRank(CT->getElementType());
3270
3271  assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3272  switch (T->getAs<BuiltinType>()->getKind()) {
3273  default: assert(0 && "getFloatingRank(): not a floating type");
3274  case BuiltinType::Float:      return FloatRank;
3275  case BuiltinType::Double:     return DoubleRank;
3276  case BuiltinType::LongDouble: return LongDoubleRank;
3277  }
3278}
3279
3280/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3281/// point or a complex type (based on typeDomain/typeSize).
3282/// 'typeDomain' is a real floating point or complex type.
3283/// 'typeSize' is a real floating point or complex type.
3284QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3285                                                       QualType Domain) const {
3286  FloatingRank EltRank = getFloatingRank(Size);
3287  if (Domain->isComplexType()) {
3288    switch (EltRank) {
3289    default: assert(0 && "getFloatingRank(): illegal value for rank");
3290    case FloatRank:      return FloatComplexTy;
3291    case DoubleRank:     return DoubleComplexTy;
3292    case LongDoubleRank: return LongDoubleComplexTy;
3293    }
3294  }
3295
3296  assert(Domain->isRealFloatingType() && "Unknown domain!");
3297  switch (EltRank) {
3298  default: assert(0 && "getFloatingRank(): illegal value for rank");
3299  case FloatRank:      return FloatTy;
3300  case DoubleRank:     return DoubleTy;
3301  case LongDoubleRank: return LongDoubleTy;
3302  }
3303}
3304
3305/// getFloatingTypeOrder - Compare the rank of the two specified floating
3306/// point types, ignoring the domain of the type (i.e. 'double' ==
3307/// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
3308/// LHS < RHS, return -1.
3309int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
3310  FloatingRank LHSR = getFloatingRank(LHS);
3311  FloatingRank RHSR = getFloatingRank(RHS);
3312
3313  if (LHSR == RHSR)
3314    return 0;
3315  if (LHSR > RHSR)
3316    return 1;
3317  return -1;
3318}
3319
3320/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3321/// routine will assert if passed a built-in type that isn't an integer or enum,
3322/// or if it is not canonicalized.
3323unsigned ASTContext::getIntegerRank(const Type *T) const {
3324  assert(T->isCanonicalUnqualified() && "T should be canonicalized");
3325  if (const EnumType* ET = dyn_cast<EnumType>(T))
3326    T = ET->getDecl()->getPromotionType().getTypePtr();
3327
3328  if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3329      T->isSpecificBuiltinType(BuiltinType::WChar_U))
3330    T = getFromTargetType(Target.getWCharType()).getTypePtr();
3331
3332  if (T->isSpecificBuiltinType(BuiltinType::Char16))
3333    T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3334
3335  if (T->isSpecificBuiltinType(BuiltinType::Char32))
3336    T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3337
3338  switch (cast<BuiltinType>(T)->getKind()) {
3339  default: assert(0 && "getIntegerRank(): not a built-in integer");
3340  case BuiltinType::Bool:
3341    return 1 + (getIntWidth(BoolTy) << 3);
3342  case BuiltinType::Char_S:
3343  case BuiltinType::Char_U:
3344  case BuiltinType::SChar:
3345  case BuiltinType::UChar:
3346    return 2 + (getIntWidth(CharTy) << 3);
3347  case BuiltinType::Short:
3348  case BuiltinType::UShort:
3349    return 3 + (getIntWidth(ShortTy) << 3);
3350  case BuiltinType::Int:
3351  case BuiltinType::UInt:
3352    return 4 + (getIntWidth(IntTy) << 3);
3353  case BuiltinType::Long:
3354  case BuiltinType::ULong:
3355    return 5 + (getIntWidth(LongTy) << 3);
3356  case BuiltinType::LongLong:
3357  case BuiltinType::ULongLong:
3358    return 6 + (getIntWidth(LongLongTy) << 3);
3359  case BuiltinType::Int128:
3360  case BuiltinType::UInt128:
3361    return 7 + (getIntWidth(Int128Ty) << 3);
3362  }
3363}
3364
3365/// \brief Whether this is a promotable bitfield reference according
3366/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3367///
3368/// \returns the type this bit-field will promote to, or NULL if no
3369/// promotion occurs.
3370QualType ASTContext::isPromotableBitField(Expr *E) const {
3371  if (E->isTypeDependent() || E->isValueDependent())
3372    return QualType();
3373
3374  FieldDecl *Field = E->getBitField();
3375  if (!Field)
3376    return QualType();
3377
3378  QualType FT = Field->getType();
3379
3380  llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3381  uint64_t BitWidth = BitWidthAP.getZExtValue();
3382  uint64_t IntSize = getTypeSize(IntTy);
3383  // GCC extension compatibility: if the bit-field size is less than or equal
3384  // to the size of int, it gets promoted no matter what its type is.
3385  // For instance, unsigned long bf : 4 gets promoted to signed int.
3386  if (BitWidth < IntSize)
3387    return IntTy;
3388
3389  if (BitWidth == IntSize)
3390    return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3391
3392  // Types bigger than int are not subject to promotions, and therefore act
3393  // like the base type.
3394  // FIXME: This doesn't quite match what gcc does, but what gcc does here
3395  // is ridiculous.
3396  return QualType();
3397}
3398
3399/// getPromotedIntegerType - Returns the type that Promotable will
3400/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3401/// integer type.
3402QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
3403  assert(!Promotable.isNull());
3404  assert(Promotable->isPromotableIntegerType());
3405  if (const EnumType *ET = Promotable->getAs<EnumType>())
3406    return ET->getDecl()->getPromotionType();
3407  if (Promotable->isSignedIntegerType())
3408    return IntTy;
3409  uint64_t PromotableSize = getTypeSize(Promotable);
3410  uint64_t IntSize = getTypeSize(IntTy);
3411  assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3412  return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3413}
3414
3415/// getIntegerTypeOrder - Returns the highest ranked integer type:
3416/// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
3417/// LHS < RHS, return -1.
3418int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
3419  const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3420  const Type *RHSC = getCanonicalType(RHS).getTypePtr();
3421  if (LHSC == RHSC) return 0;
3422
3423  bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3424  bool RHSUnsigned = RHSC->isUnsignedIntegerType();
3425
3426  unsigned LHSRank = getIntegerRank(LHSC);
3427  unsigned RHSRank = getIntegerRank(RHSC);
3428
3429  if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
3430    if (LHSRank == RHSRank) return 0;
3431    return LHSRank > RHSRank ? 1 : -1;
3432  }
3433
3434  // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3435  if (LHSUnsigned) {
3436    // If the unsigned [LHS] type is larger, return it.
3437    if (LHSRank >= RHSRank)
3438      return 1;
3439
3440    // If the signed type can represent all values of the unsigned type, it
3441    // wins.  Because we are dealing with 2's complement and types that are
3442    // powers of two larger than each other, this is always safe.
3443    return -1;
3444  }
3445
3446  // If the unsigned [RHS] type is larger, return it.
3447  if (RHSRank >= LHSRank)
3448    return -1;
3449
3450  // If the signed type can represent all values of the unsigned type, it
3451  // wins.  Because we are dealing with 2's complement and types that are
3452  // powers of two larger than each other, this is always safe.
3453  return 1;
3454}
3455
3456static RecordDecl *
3457CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3458                 DeclContext *DC, IdentifierInfo *Id) {
3459  SourceLocation Loc;
3460  if (Ctx.getLangOptions().CPlusPlus)
3461    return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
3462  else
3463    return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
3464}
3465
3466// getCFConstantStringType - Return the type used for constant CFStrings.
3467QualType ASTContext::getCFConstantStringType() const {
3468  if (!CFConstantStringTypeDecl) {
3469    CFConstantStringTypeDecl =
3470      CreateRecordDecl(*this, TTK_Struct, TUDecl,
3471                       &Idents.get("NSConstantString"));
3472    CFConstantStringTypeDecl->startDefinition();
3473
3474    QualType FieldTypes[4];
3475
3476    // const int *isa;
3477    FieldTypes[0] = getPointerType(IntTy.withConst());
3478    // int flags;
3479    FieldTypes[1] = IntTy;
3480    // const char *str;
3481    FieldTypes[2] = getPointerType(CharTy.withConst());
3482    // long length;
3483    FieldTypes[3] = LongTy;
3484
3485    // Create fields
3486    for (unsigned i = 0; i < 4; ++i) {
3487      FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
3488                                           SourceLocation(),
3489                                           SourceLocation(), 0,
3490                                           FieldTypes[i], /*TInfo=*/0,
3491                                           /*BitWidth=*/0,
3492                                           /*Mutable=*/false);
3493      Field->setAccess(AS_public);
3494      CFConstantStringTypeDecl->addDecl(Field);
3495    }
3496
3497    CFConstantStringTypeDecl->completeDefinition();
3498  }
3499
3500  return getTagDeclType(CFConstantStringTypeDecl);
3501}
3502
3503void ASTContext::setCFConstantStringType(QualType T) {
3504  const RecordType *Rec = T->getAs<RecordType>();
3505  assert(Rec && "Invalid CFConstantStringType");
3506  CFConstantStringTypeDecl = Rec->getDecl();
3507}
3508
3509// getNSConstantStringType - Return the type used for constant NSStrings.
3510QualType ASTContext::getNSConstantStringType() const {
3511  if (!NSConstantStringTypeDecl) {
3512    NSConstantStringTypeDecl =
3513    CreateRecordDecl(*this, TTK_Struct, TUDecl,
3514                     &Idents.get("__builtin_NSString"));
3515    NSConstantStringTypeDecl->startDefinition();
3516
3517    QualType FieldTypes[3];
3518
3519    // const int *isa;
3520    FieldTypes[0] = getPointerType(IntTy.withConst());
3521    // const char *str;
3522    FieldTypes[1] = getPointerType(CharTy.withConst());
3523    // unsigned int length;
3524    FieldTypes[2] = UnsignedIntTy;
3525
3526    // Create fields
3527    for (unsigned i = 0; i < 3; ++i) {
3528      FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3529                                           SourceLocation(),
3530                                           SourceLocation(), 0,
3531                                           FieldTypes[i], /*TInfo=*/0,
3532                                           /*BitWidth=*/0,
3533                                           /*Mutable=*/false);
3534      Field->setAccess(AS_public);
3535      NSConstantStringTypeDecl->addDecl(Field);
3536    }
3537
3538    NSConstantStringTypeDecl->completeDefinition();
3539  }
3540
3541  return getTagDeclType(NSConstantStringTypeDecl);
3542}
3543
3544void ASTContext::setNSConstantStringType(QualType T) {
3545  const RecordType *Rec = T->getAs<RecordType>();
3546  assert(Rec && "Invalid NSConstantStringType");
3547  NSConstantStringTypeDecl = Rec->getDecl();
3548}
3549
3550QualType ASTContext::getObjCFastEnumerationStateType() const {
3551  if (!ObjCFastEnumerationStateTypeDecl) {
3552    ObjCFastEnumerationStateTypeDecl =
3553      CreateRecordDecl(*this, TTK_Struct, TUDecl,
3554                       &Idents.get("__objcFastEnumerationState"));
3555    ObjCFastEnumerationStateTypeDecl->startDefinition();
3556
3557    QualType FieldTypes[] = {
3558      UnsignedLongTy,
3559      getPointerType(ObjCIdTypedefType),
3560      getPointerType(UnsignedLongTy),
3561      getConstantArrayType(UnsignedLongTy,
3562                           llvm::APInt(32, 5), ArrayType::Normal, 0)
3563    };
3564
3565    for (size_t i = 0; i < 4; ++i) {
3566      FieldDecl *Field = FieldDecl::Create(*this,
3567                                           ObjCFastEnumerationStateTypeDecl,
3568                                           SourceLocation(),
3569                                           SourceLocation(), 0,
3570                                           FieldTypes[i], /*TInfo=*/0,
3571                                           /*BitWidth=*/0,
3572                                           /*Mutable=*/false);
3573      Field->setAccess(AS_public);
3574      ObjCFastEnumerationStateTypeDecl->addDecl(Field);
3575    }
3576
3577    ObjCFastEnumerationStateTypeDecl->completeDefinition();
3578  }
3579
3580  return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3581}
3582
3583QualType ASTContext::getBlockDescriptorType() const {
3584  if (BlockDescriptorType)
3585    return getTagDeclType(BlockDescriptorType);
3586
3587  RecordDecl *T;
3588  // FIXME: Needs the FlagAppleBlock bit.
3589  T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
3590                       &Idents.get("__block_descriptor"));
3591  T->startDefinition();
3592
3593  QualType FieldTypes[] = {
3594    UnsignedLongTy,
3595    UnsignedLongTy,
3596  };
3597
3598  const char *FieldNames[] = {
3599    "reserved",
3600    "Size"
3601  };
3602
3603  for (size_t i = 0; i < 2; ++i) {
3604    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3605                                         SourceLocation(),
3606                                         &Idents.get(FieldNames[i]),
3607                                         FieldTypes[i], /*TInfo=*/0,
3608                                         /*BitWidth=*/0,
3609                                         /*Mutable=*/false);
3610    Field->setAccess(AS_public);
3611    T->addDecl(Field);
3612  }
3613
3614  T->completeDefinition();
3615
3616  BlockDescriptorType = T;
3617
3618  return getTagDeclType(BlockDescriptorType);
3619}
3620
3621void ASTContext::setBlockDescriptorType(QualType T) {
3622  const RecordType *Rec = T->getAs<RecordType>();
3623  assert(Rec && "Invalid BlockDescriptorType");
3624  BlockDescriptorType = Rec->getDecl();
3625}
3626
3627QualType ASTContext::getBlockDescriptorExtendedType() const {
3628  if (BlockDescriptorExtendedType)
3629    return getTagDeclType(BlockDescriptorExtendedType);
3630
3631  RecordDecl *T;
3632  // FIXME: Needs the FlagAppleBlock bit.
3633  T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
3634                       &Idents.get("__block_descriptor_withcopydispose"));
3635  T->startDefinition();
3636
3637  QualType FieldTypes[] = {
3638    UnsignedLongTy,
3639    UnsignedLongTy,
3640    getPointerType(VoidPtrTy),
3641    getPointerType(VoidPtrTy)
3642  };
3643
3644  const char *FieldNames[] = {
3645    "reserved",
3646    "Size",
3647    "CopyFuncPtr",
3648    "DestroyFuncPtr"
3649  };
3650
3651  for (size_t i = 0; i < 4; ++i) {
3652    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3653                                         SourceLocation(),
3654                                         &Idents.get(FieldNames[i]),
3655                                         FieldTypes[i], /*TInfo=*/0,
3656                                         /*BitWidth=*/0,
3657                                         /*Mutable=*/false);
3658    Field->setAccess(AS_public);
3659    T->addDecl(Field);
3660  }
3661
3662  T->completeDefinition();
3663
3664  BlockDescriptorExtendedType = T;
3665
3666  return getTagDeclType(BlockDescriptorExtendedType);
3667}
3668
3669void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3670  const RecordType *Rec = T->getAs<RecordType>();
3671  assert(Rec && "Invalid BlockDescriptorType");
3672  BlockDescriptorExtendedType = Rec->getDecl();
3673}
3674
3675bool ASTContext::BlockRequiresCopying(QualType Ty) const {
3676  if (Ty->isBlockPointerType())
3677    return true;
3678  if (isObjCNSObjectType(Ty))
3679    return true;
3680  if (Ty->isObjCObjectPointerType())
3681    return true;
3682  if (getLangOptions().CPlusPlus) {
3683    if (const RecordType *RT = Ty->getAs<RecordType>()) {
3684      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3685      return RD->hasConstCopyConstructor(*this);
3686
3687    }
3688  }
3689  return false;
3690}
3691
3692QualType
3693ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) const {
3694  //  type = struct __Block_byref_1_X {
3695  //    void *__isa;
3696  //    struct __Block_byref_1_X *__forwarding;
3697  //    unsigned int __flags;
3698  //    unsigned int __size;
3699  //    void *__copy_helper;            // as needed
3700  //    void *__destroy_help            // as needed
3701  //    int X;
3702  //  } *
3703
3704  bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3705
3706  // FIXME: Move up
3707  llvm::SmallString<36> Name;
3708  llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3709                                  ++UniqueBlockByRefTypeID << '_' << DeclName;
3710  RecordDecl *T;
3711  T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
3712  T->startDefinition();
3713  QualType Int32Ty = IntTy;
3714  assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3715  QualType FieldTypes[] = {
3716    getPointerType(VoidPtrTy),
3717    getPointerType(getTagDeclType(T)),
3718    Int32Ty,
3719    Int32Ty,
3720    getPointerType(VoidPtrTy),
3721    getPointerType(VoidPtrTy),
3722    Ty
3723  };
3724
3725  llvm::StringRef FieldNames[] = {
3726    "__isa",
3727    "__forwarding",
3728    "__flags",
3729    "__size",
3730    "__copy_helper",
3731    "__destroy_helper",
3732    DeclName,
3733  };
3734
3735  for (size_t i = 0; i < 7; ++i) {
3736    if (!HasCopyAndDispose && i >=4 && i <= 5)
3737      continue;
3738    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3739                                         SourceLocation(),
3740                                         &Idents.get(FieldNames[i]),
3741                                         FieldTypes[i], /*TInfo=*/0,
3742                                         /*BitWidth=*/0, /*Mutable=*/false);
3743    Field->setAccess(AS_public);
3744    T->addDecl(Field);
3745  }
3746
3747  T->completeDefinition();
3748
3749  return getPointerType(getTagDeclType(T));
3750}
3751
3752void ASTContext::setObjCFastEnumerationStateType(QualType T) {
3753  const RecordType *Rec = T->getAs<RecordType>();
3754  assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3755  ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3756}
3757
3758// This returns true if a type has been typedefed to BOOL:
3759// typedef <type> BOOL;
3760static bool isTypeTypedefedAsBOOL(QualType T) {
3761  if (const TypedefType *TT = dyn_cast<TypedefType>(T))
3762    if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3763      return II->isStr("BOOL");
3764
3765  return false;
3766}
3767
3768/// getObjCEncodingTypeSize returns size of type for objective-c encoding
3769/// purpose.
3770CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
3771  CharUnits sz = getTypeSizeInChars(type);
3772
3773  // Make all integer and enum types at least as large as an int
3774  if (sz.isPositive() && type->isIntegralOrEnumerationType())
3775    sz = std::max(sz, getTypeSizeInChars(IntTy));
3776  // Treat arrays as pointers, since that's how they're passed in.
3777  else if (type->isArrayType())
3778    sz = getTypeSizeInChars(VoidPtrTy);
3779  return sz;
3780}
3781
3782static inline
3783std::string charUnitsToString(const CharUnits &CU) {
3784  return llvm::itostr(CU.getQuantity());
3785}
3786
3787/// getObjCEncodingForBlock - Return the encoded type for this block
3788/// declaration.
3789std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3790  std::string S;
3791
3792  const BlockDecl *Decl = Expr->getBlockDecl();
3793  QualType BlockTy =
3794      Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3795  // Encode result type.
3796  getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
3797  // Compute size of all parameters.
3798  // Start with computing size of a pointer in number of bytes.
3799  // FIXME: There might(should) be a better way of doing this computation!
3800  SourceLocation Loc;
3801  CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3802  CharUnits ParmOffset = PtrSize;
3803  for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
3804       E = Decl->param_end(); PI != E; ++PI) {
3805    QualType PType = (*PI)->getType();
3806    CharUnits sz = getObjCEncodingTypeSize(PType);
3807    assert (sz.isPositive() && "BlockExpr - Incomplete param type");
3808    ParmOffset += sz;
3809  }
3810  // Size of the argument frame
3811  S += charUnitsToString(ParmOffset);
3812  // Block pointer and offset.
3813  S += "@?0";
3814  ParmOffset = PtrSize;
3815
3816  // Argument types.
3817  ParmOffset = PtrSize;
3818  for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3819       Decl->param_end(); PI != E; ++PI) {
3820    ParmVarDecl *PVDecl = *PI;
3821    QualType PType = PVDecl->getOriginalType();
3822    if (const ArrayType *AT =
3823          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3824      // Use array's original type only if it has known number of
3825      // elements.
3826      if (!isa<ConstantArrayType>(AT))
3827        PType = PVDecl->getType();
3828    } else if (PType->isFunctionType())
3829      PType = PVDecl->getType();
3830    getObjCEncodingForType(PType, S);
3831    S += charUnitsToString(ParmOffset);
3832    ParmOffset += getObjCEncodingTypeSize(PType);
3833  }
3834
3835  return S;
3836}
3837
3838void ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
3839                                                std::string& S) {
3840  // Encode result type.
3841  getObjCEncodingForType(Decl->getResultType(), S);
3842  CharUnits ParmOffset;
3843  // Compute size of all parameters.
3844  for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3845       E = Decl->param_end(); PI != E; ++PI) {
3846    QualType PType = (*PI)->getType();
3847    CharUnits sz = getObjCEncodingTypeSize(PType);
3848    assert (sz.isPositive() &&
3849        "getObjCEncodingForMethodDecl - Incomplete param type");
3850    ParmOffset += sz;
3851  }
3852  S += charUnitsToString(ParmOffset);
3853  ParmOffset = CharUnits::Zero();
3854
3855  // Argument types.
3856  for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3857       E = Decl->param_end(); PI != E; ++PI) {
3858    ParmVarDecl *PVDecl = *PI;
3859    QualType PType = PVDecl->getOriginalType();
3860    if (const ArrayType *AT =
3861          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3862      // Use array's original type only if it has known number of
3863      // elements.
3864      if (!isa<ConstantArrayType>(AT))
3865        PType = PVDecl->getType();
3866    } else if (PType->isFunctionType())
3867      PType = PVDecl->getType();
3868    getObjCEncodingForType(PType, S);
3869    S += charUnitsToString(ParmOffset);
3870    ParmOffset += getObjCEncodingTypeSize(PType);
3871  }
3872}
3873
3874/// getObjCEncodingForMethodDecl - Return the encoded type for this method
3875/// declaration.
3876void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
3877                                              std::string& S) const {
3878  // FIXME: This is not very efficient.
3879  // Encode type qualifer, 'in', 'inout', etc. for the return type.
3880  getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
3881  // Encode result type.
3882  getObjCEncodingForType(Decl->getResultType(), S);
3883  // Compute size of all parameters.
3884  // Start with computing size of a pointer in number of bytes.
3885  // FIXME: There might(should) be a better way of doing this computation!
3886  SourceLocation Loc;
3887  CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3888  // The first two arguments (self and _cmd) are pointers; account for
3889  // their size.
3890  CharUnits ParmOffset = 2 * PtrSize;
3891  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3892       E = Decl->sel_param_end(); PI != E; ++PI) {
3893    QualType PType = (*PI)->getType();
3894    CharUnits sz = getObjCEncodingTypeSize(PType);
3895    assert (sz.isPositive() &&
3896        "getObjCEncodingForMethodDecl - Incomplete param type");
3897    ParmOffset += sz;
3898  }
3899  S += charUnitsToString(ParmOffset);
3900  S += "@0:";
3901  S += charUnitsToString(PtrSize);
3902
3903  // Argument types.
3904  ParmOffset = 2 * PtrSize;
3905  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3906       E = Decl->sel_param_end(); PI != E; ++PI) {
3907    ParmVarDecl *PVDecl = *PI;
3908    QualType PType = PVDecl->getOriginalType();
3909    if (const ArrayType *AT =
3910          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3911      // Use array's original type only if it has known number of
3912      // elements.
3913      if (!isa<ConstantArrayType>(AT))
3914        PType = PVDecl->getType();
3915    } else if (PType->isFunctionType())
3916      PType = PVDecl->getType();
3917    // Process argument qualifiers for user supplied arguments; such as,
3918    // 'in', 'inout', etc.
3919    getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
3920    getObjCEncodingForType(PType, S);
3921    S += charUnitsToString(ParmOffset);
3922    ParmOffset += getObjCEncodingTypeSize(PType);
3923  }
3924}
3925
3926/// getObjCEncodingForPropertyDecl - Return the encoded type for this
3927/// property declaration. If non-NULL, Container must be either an
3928/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3929/// NULL when getting encodings for protocol properties.
3930/// Property attributes are stored as a comma-delimited C string. The simple
3931/// attributes readonly and bycopy are encoded as single characters. The
3932/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3933/// encoded as single characters, followed by an identifier. Property types
3934/// are also encoded as a parametrized attribute. The characters used to encode
3935/// these attributes are defined by the following enumeration:
3936/// @code
3937/// enum PropertyAttributes {
3938/// kPropertyReadOnly = 'R',   // property is read-only.
3939/// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
3940/// kPropertyByref = '&',  // property is a reference to the value last assigned
3941/// kPropertyDynamic = 'D',    // property is dynamic
3942/// kPropertyGetter = 'G',     // followed by getter selector name
3943/// kPropertySetter = 'S',     // followed by setter selector name
3944/// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
3945/// kPropertyType = 't'              // followed by old-style type encoding.
3946/// kPropertyWeak = 'W'              // 'weak' property
3947/// kPropertyStrong = 'P'            // property GC'able
3948/// kPropertyNonAtomic = 'N'         // property non-atomic
3949/// };
3950/// @endcode
3951void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
3952                                                const Decl *Container,
3953                                                std::string& S) const {
3954  // Collect information from the property implementation decl(s).
3955  bool Dynamic = false;
3956  ObjCPropertyImplDecl *SynthesizePID = 0;
3957
3958  // FIXME: Duplicated code due to poor abstraction.
3959  if (Container) {
3960    if (const ObjCCategoryImplDecl *CID =
3961        dyn_cast<ObjCCategoryImplDecl>(Container)) {
3962      for (ObjCCategoryImplDecl::propimpl_iterator
3963             i = CID->propimpl_begin(), e = CID->propimpl_end();
3964           i != e; ++i) {
3965        ObjCPropertyImplDecl *PID = *i;
3966        if (PID->getPropertyDecl() == PD) {
3967          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3968            Dynamic = true;
3969          } else {
3970            SynthesizePID = PID;
3971          }
3972        }
3973      }
3974    } else {
3975      const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
3976      for (ObjCCategoryImplDecl::propimpl_iterator
3977             i = OID->propimpl_begin(), e = OID->propimpl_end();
3978           i != e; ++i) {
3979        ObjCPropertyImplDecl *PID = *i;
3980        if (PID->getPropertyDecl() == PD) {
3981          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3982            Dynamic = true;
3983          } else {
3984            SynthesizePID = PID;
3985          }
3986        }
3987      }
3988    }
3989  }
3990
3991  // FIXME: This is not very efficient.
3992  S = "T";
3993
3994  // Encode result type.
3995  // GCC has some special rules regarding encoding of properties which
3996  // closely resembles encoding of ivars.
3997  getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
3998                             true /* outermost type */,
3999                             true /* encoding for property */);
4000
4001  if (PD->isReadOnly()) {
4002    S += ",R";
4003  } else {
4004    switch (PD->getSetterKind()) {
4005    case ObjCPropertyDecl::Assign: break;
4006    case ObjCPropertyDecl::Copy:   S += ",C"; break;
4007    case ObjCPropertyDecl::Retain: S += ",&"; break;
4008    }
4009  }
4010
4011  // It really isn't clear at all what this means, since properties
4012  // are "dynamic by default".
4013  if (Dynamic)
4014    S += ",D";
4015
4016  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4017    S += ",N";
4018
4019  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4020    S += ",G";
4021    S += PD->getGetterName().getAsString();
4022  }
4023
4024  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4025    S += ",S";
4026    S += PD->getSetterName().getAsString();
4027  }
4028
4029  if (SynthesizePID) {
4030    const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4031    S += ",V";
4032    S += OID->getNameAsString();
4033  }
4034
4035  // FIXME: OBJCGC: weak & strong
4036}
4037
4038/// getLegacyIntegralTypeEncoding -
4039/// Another legacy compatibility encoding: 32-bit longs are encoded as
4040/// 'l' or 'L' , but not always.  For typedefs, we need to use
4041/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4042///
4043void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
4044  if (isa<TypedefType>(PointeeTy.getTypePtr())) {
4045    if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
4046      if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
4047        PointeeTy = UnsignedIntTy;
4048      else
4049        if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
4050          PointeeTy = IntTy;
4051    }
4052  }
4053}
4054
4055void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
4056                                        const FieldDecl *Field) const {
4057  // We follow the behavior of gcc, expanding structures which are
4058  // directly pointed to, and expanding embedded structures. Note that
4059  // these rules are sufficient to prevent recursive encoding of the
4060  // same type.
4061  getObjCEncodingForTypeImpl(T, S, true, true, Field,
4062                             true /* outermost type */);
4063}
4064
4065static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4066    switch (T->getAs<BuiltinType>()->getKind()) {
4067    default: assert(0 && "Unhandled builtin type kind");
4068    case BuiltinType::Void:       return 'v';
4069    case BuiltinType::Bool:       return 'B';
4070    case BuiltinType::Char_U:
4071    case BuiltinType::UChar:      return 'C';
4072    case BuiltinType::UShort:     return 'S';
4073    case BuiltinType::UInt:       return 'I';
4074    case BuiltinType::ULong:
4075        return C->getIntWidth(T) == 32 ? 'L' : 'Q';
4076    case BuiltinType::UInt128:    return 'T';
4077    case BuiltinType::ULongLong:  return 'Q';
4078    case BuiltinType::Char_S:
4079    case BuiltinType::SChar:      return 'c';
4080    case BuiltinType::Short:      return 's';
4081    case BuiltinType::WChar_S:
4082    case BuiltinType::WChar_U:
4083    case BuiltinType::Int:        return 'i';
4084    case BuiltinType::Long:
4085      return C->getIntWidth(T) == 32 ? 'l' : 'q';
4086    case BuiltinType::LongLong:   return 'q';
4087    case BuiltinType::Int128:     return 't';
4088    case BuiltinType::Float:      return 'f';
4089    case BuiltinType::Double:     return 'd';
4090    case BuiltinType::LongDouble: return 'D';
4091    }
4092}
4093
4094static void EncodeBitField(const ASTContext *Ctx, std::string& S,
4095                           QualType T, const FieldDecl *FD) {
4096  const Expr *E = FD->getBitWidth();
4097  assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
4098  S += 'b';
4099  // The NeXT runtime encodes bit fields as b followed by the number of bits.
4100  // The GNU runtime requires more information; bitfields are encoded as b,
4101  // then the offset (in bits) of the first element, then the type of the
4102  // bitfield, then the size in bits.  For example, in this structure:
4103  //
4104  // struct
4105  // {
4106  //    int integer;
4107  //    int flags:2;
4108  // };
4109  // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4110  // runtime, but b32i2 for the GNU runtime.  The reason for this extra
4111  // information is not especially sensible, but we're stuck with it for
4112  // compatibility with GCC, although providing it breaks anything that
4113  // actually uses runtime introspection and wants to work on both runtimes...
4114  if (!Ctx->getLangOptions().NeXTRuntime) {
4115    const RecordDecl *RD = FD->getParent();
4116    const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
4117    // FIXME: This same linear search is also used in ExprConstant - it might
4118    // be better if the FieldDecl stored its offset.  We'd be increasing the
4119    // size of the object slightly, but saving some time every time it is used.
4120    unsigned i = 0;
4121    for (RecordDecl::field_iterator Field = RD->field_begin(),
4122                                 FieldEnd = RD->field_end();
4123         Field != FieldEnd; (void)++Field, ++i) {
4124      if (*Field == FD)
4125        break;
4126    }
4127    S += llvm::utostr(RL.getFieldOffset(i));
4128    if (T->isEnumeralType())
4129      S += 'i';
4130    else
4131      S += ObjCEncodingForPrimitiveKind(Ctx, T);
4132  }
4133  unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
4134  S += llvm::utostr(N);
4135}
4136
4137// FIXME: Use SmallString for accumulating string.
4138void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4139                                            bool ExpandPointedToStructures,
4140                                            bool ExpandStructures,
4141                                            const FieldDecl *FD,
4142                                            bool OutermostType,
4143                                            bool EncodingProperty) const {
4144  if (T->getAs<BuiltinType>()) {
4145    if (FD && FD->isBitField())
4146      return EncodeBitField(this, S, T, FD);
4147    S += ObjCEncodingForPrimitiveKind(this, T);
4148    return;
4149  }
4150
4151  if (const ComplexType *CT = T->getAs<ComplexType>()) {
4152    S += 'j';
4153    getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
4154                               false);
4155    return;
4156  }
4157
4158  // encoding for pointer or r3eference types.
4159  QualType PointeeTy;
4160  if (const PointerType *PT = T->getAs<PointerType>()) {
4161    if (PT->isObjCSelType()) {
4162      S += ':';
4163      return;
4164    }
4165    PointeeTy = PT->getPointeeType();
4166  }
4167  else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4168    PointeeTy = RT->getPointeeType();
4169  if (!PointeeTy.isNull()) {
4170    bool isReadOnly = false;
4171    // For historical/compatibility reasons, the read-only qualifier of the
4172    // pointee gets emitted _before_ the '^'.  The read-only qualifier of
4173    // the pointer itself gets ignored, _unless_ we are looking at a typedef!
4174    // Also, do not emit the 'r' for anything but the outermost type!
4175    if (isa<TypedefType>(T.getTypePtr())) {
4176      if (OutermostType && T.isConstQualified()) {
4177        isReadOnly = true;
4178        S += 'r';
4179      }
4180    } else if (OutermostType) {
4181      QualType P = PointeeTy;
4182      while (P->getAs<PointerType>())
4183        P = P->getAs<PointerType>()->getPointeeType();
4184      if (P.isConstQualified()) {
4185        isReadOnly = true;
4186        S += 'r';
4187      }
4188    }
4189    if (isReadOnly) {
4190      // Another legacy compatibility encoding. Some ObjC qualifier and type
4191      // combinations need to be rearranged.
4192      // Rewrite "in const" from "nr" to "rn"
4193      if (llvm::StringRef(S).endswith("nr"))
4194        S.replace(S.end()-2, S.end(), "rn");
4195    }
4196
4197    if (PointeeTy->isCharType()) {
4198      // char pointer types should be encoded as '*' unless it is a
4199      // type that has been typedef'd to 'BOOL'.
4200      if (!isTypeTypedefedAsBOOL(PointeeTy)) {
4201        S += '*';
4202        return;
4203      }
4204    } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
4205      // GCC binary compat: Need to convert "struct objc_class *" to "#".
4206      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4207        S += '#';
4208        return;
4209      }
4210      // GCC binary compat: Need to convert "struct objc_object *" to "@".
4211      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4212        S += '@';
4213        return;
4214      }
4215      // fall through...
4216    }
4217    S += '^';
4218    getLegacyIntegralTypeEncoding(PointeeTy);
4219
4220    getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
4221                               NULL);
4222    return;
4223  }
4224
4225  if (const ArrayType *AT =
4226      // Ignore type qualifiers etc.
4227        dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
4228    if (isa<IncompleteArrayType>(AT)) {
4229      // Incomplete arrays are encoded as a pointer to the array element.
4230      S += '^';
4231
4232      getObjCEncodingForTypeImpl(AT->getElementType(), S,
4233                                 false, ExpandStructures, FD);
4234    } else {
4235      S += '[';
4236
4237      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
4238        S += llvm::utostr(CAT->getSize().getZExtValue());
4239      else {
4240        //Variable length arrays are encoded as a regular array with 0 elements.
4241        assert(isa<VariableArrayType>(AT) && "Unknown array type!");
4242        S += '0';
4243      }
4244
4245      getObjCEncodingForTypeImpl(AT->getElementType(), S,
4246                                 false, ExpandStructures, FD);
4247      S += ']';
4248    }
4249    return;
4250  }
4251
4252  if (T->getAs<FunctionType>()) {
4253    S += '?';
4254    return;
4255  }
4256
4257  if (const RecordType *RTy = T->getAs<RecordType>()) {
4258    RecordDecl *RDecl = RTy->getDecl();
4259    S += RDecl->isUnion() ? '(' : '{';
4260    // Anonymous structures print as '?'
4261    if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4262      S += II->getName();
4263      if (ClassTemplateSpecializationDecl *Spec
4264          = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4265        const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4266        std::string TemplateArgsStr
4267          = TemplateSpecializationType::PrintTemplateArgumentList(
4268                                            TemplateArgs.data(),
4269                                            TemplateArgs.size(),
4270                                            (*this).PrintingPolicy);
4271
4272        S += TemplateArgsStr;
4273      }
4274    } else {
4275      S += '?';
4276    }
4277    if (ExpandStructures) {
4278      S += '=';
4279      for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4280                                   FieldEnd = RDecl->field_end();
4281           Field != FieldEnd; ++Field) {
4282        if (FD) {
4283          S += '"';
4284          S += Field->getNameAsString();
4285          S += '"';
4286        }
4287
4288        // Special case bit-fields.
4289        if (Field->isBitField()) {
4290          getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4291                                     (*Field));
4292        } else {
4293          QualType qt = Field->getType();
4294          getLegacyIntegralTypeEncoding(qt);
4295          getObjCEncodingForTypeImpl(qt, S, false, true,
4296                                     FD);
4297        }
4298      }
4299    }
4300    S += RDecl->isUnion() ? ')' : '}';
4301    return;
4302  }
4303
4304  if (T->isEnumeralType()) {
4305    if (FD && FD->isBitField())
4306      EncodeBitField(this, S, T, FD);
4307    else
4308      S += 'i';
4309    return;
4310  }
4311
4312  if (T->isBlockPointerType()) {
4313    S += "@?"; // Unlike a pointer-to-function, which is "^?".
4314    return;
4315  }
4316
4317  // Ignore protocol qualifiers when mangling at this level.
4318  if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4319    T = OT->getBaseType();
4320
4321  if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
4322    // @encode(class_name)
4323    ObjCInterfaceDecl *OI = OIT->getDecl();
4324    S += '{';
4325    const IdentifierInfo *II = OI->getIdentifier();
4326    S += II->getName();
4327    S += '=';
4328    llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
4329    DeepCollectObjCIvars(OI, true, Ivars);
4330    for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4331      FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4332      if (Field->isBitField())
4333        getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
4334      else
4335        getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
4336    }
4337    S += '}';
4338    return;
4339  }
4340
4341  if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
4342    if (OPT->isObjCIdType()) {
4343      S += '@';
4344      return;
4345    }
4346
4347    if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4348      // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4349      // Since this is a binary compatibility issue, need to consult with runtime
4350      // folks. Fortunately, this is a *very* obsure construct.
4351      S += '#';
4352      return;
4353    }
4354
4355    if (OPT->isObjCQualifiedIdType()) {
4356      getObjCEncodingForTypeImpl(getObjCIdType(), S,
4357                                 ExpandPointedToStructures,
4358                                 ExpandStructures, FD);
4359      if (FD || EncodingProperty) {
4360        // Note that we do extended encoding of protocol qualifer list
4361        // Only when doing ivar or property encoding.
4362        S += '"';
4363        for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4364             E = OPT->qual_end(); I != E; ++I) {
4365          S += '<';
4366          S += (*I)->getNameAsString();
4367          S += '>';
4368        }
4369        S += '"';
4370      }
4371      return;
4372    }
4373
4374    QualType PointeeTy = OPT->getPointeeType();
4375    if (!EncodingProperty &&
4376        isa<TypedefType>(PointeeTy.getTypePtr())) {
4377      // Another historical/compatibility reason.
4378      // We encode the underlying type which comes out as
4379      // {...};
4380      S += '^';
4381      getObjCEncodingForTypeImpl(PointeeTy, S,
4382                                 false, ExpandPointedToStructures,
4383                                 NULL);
4384      return;
4385    }
4386
4387    S += '@';
4388    if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
4389      S += '"';
4390      S += OPT->getInterfaceDecl()->getIdentifier()->getName();
4391      for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4392           E = OPT->qual_end(); I != E; ++I) {
4393        S += '<';
4394        S += (*I)->getNameAsString();
4395        S += '>';
4396      }
4397      S += '"';
4398    }
4399    return;
4400  }
4401
4402  // gcc just blithely ignores member pointers.
4403  // TODO: maybe there should be a mangling for these
4404  if (T->getAs<MemberPointerType>())
4405    return;
4406
4407  if (T->isVectorType()) {
4408    // This matches gcc's encoding, even though technically it is
4409    // insufficient.
4410    // FIXME. We should do a better job than gcc.
4411    return;
4412  }
4413
4414  assert(0 && "@encode for type not implemented!");
4415}
4416
4417void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
4418                                                 std::string& S) const {
4419  if (QT & Decl::OBJC_TQ_In)
4420    S += 'n';
4421  if (QT & Decl::OBJC_TQ_Inout)
4422    S += 'N';
4423  if (QT & Decl::OBJC_TQ_Out)
4424    S += 'o';
4425  if (QT & Decl::OBJC_TQ_Bycopy)
4426    S += 'O';
4427  if (QT & Decl::OBJC_TQ_Byref)
4428    S += 'R';
4429  if (QT & Decl::OBJC_TQ_Oneway)
4430    S += 'V';
4431}
4432
4433void ASTContext::setBuiltinVaListType(QualType T) {
4434  assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
4435
4436  BuiltinVaListType = T;
4437}
4438
4439void ASTContext::setObjCIdType(QualType T) {
4440  ObjCIdTypedefType = T;
4441}
4442
4443void ASTContext::setObjCSelType(QualType T) {
4444  ObjCSelTypedefType = T;
4445}
4446
4447void ASTContext::setObjCProtoType(QualType QT) {
4448  ObjCProtoType = QT;
4449}
4450
4451void ASTContext::setObjCClassType(QualType T) {
4452  ObjCClassTypedefType = T;
4453}
4454
4455void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
4456  assert(ObjCConstantStringType.isNull() &&
4457         "'NSConstantString' type already set!");
4458
4459  ObjCConstantStringType = getObjCInterfaceType(Decl);
4460}
4461
4462/// \brief Retrieve the template name that corresponds to a non-empty
4463/// lookup.
4464TemplateName
4465ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4466                                      UnresolvedSetIterator End) const {
4467  unsigned size = End - Begin;
4468  assert(size > 1 && "set is not overloaded!");
4469
4470  void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4471                          size * sizeof(FunctionTemplateDecl*));
4472  OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4473
4474  NamedDecl **Storage = OT->getStorage();
4475  for (UnresolvedSetIterator I = Begin; I != End; ++I) {
4476    NamedDecl *D = *I;
4477    assert(isa<FunctionTemplateDecl>(D) ||
4478           (isa<UsingShadowDecl>(D) &&
4479            isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4480    *Storage++ = D;
4481  }
4482
4483  return TemplateName(OT);
4484}
4485
4486/// \brief Retrieve the template name that represents a qualified
4487/// template name such as \c std::vector.
4488TemplateName
4489ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4490                                     bool TemplateKeyword,
4491                                     TemplateDecl *Template) const {
4492  assert(NNS && "Missing nested-name-specifier in qualified template name");
4493
4494  // FIXME: Canonicalization?
4495  llvm::FoldingSetNodeID ID;
4496  QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4497
4498  void *InsertPos = 0;
4499  QualifiedTemplateName *QTN =
4500    QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4501  if (!QTN) {
4502    QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4503    QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4504  }
4505
4506  return TemplateName(QTN);
4507}
4508
4509/// \brief Retrieve the template name that represents a dependent
4510/// template name such as \c MetaFun::template apply.
4511TemplateName
4512ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4513                                     const IdentifierInfo *Name) const {
4514  assert((!NNS || NNS->isDependent()) &&
4515         "Nested name specifier must be dependent");
4516
4517  llvm::FoldingSetNodeID ID;
4518  DependentTemplateName::Profile(ID, NNS, Name);
4519
4520  void *InsertPos = 0;
4521  DependentTemplateName *QTN =
4522    DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4523
4524  if (QTN)
4525    return TemplateName(QTN);
4526
4527  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4528  if (CanonNNS == NNS) {
4529    QTN = new (*this,4) DependentTemplateName(NNS, Name);
4530  } else {
4531    TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4532    QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
4533    DependentTemplateName *CheckQTN =
4534      DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4535    assert(!CheckQTN && "Dependent type name canonicalization broken");
4536    (void)CheckQTN;
4537  }
4538
4539  DependentTemplateNames.InsertNode(QTN, InsertPos);
4540  return TemplateName(QTN);
4541}
4542
4543/// \brief Retrieve the template name that represents a dependent
4544/// template name such as \c MetaFun::template operator+.
4545TemplateName
4546ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4547                                     OverloadedOperatorKind Operator) const {
4548  assert((!NNS || NNS->isDependent()) &&
4549         "Nested name specifier must be dependent");
4550
4551  llvm::FoldingSetNodeID ID;
4552  DependentTemplateName::Profile(ID, NNS, Operator);
4553
4554  void *InsertPos = 0;
4555  DependentTemplateName *QTN
4556    = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4557
4558  if (QTN)
4559    return TemplateName(QTN);
4560
4561  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4562  if (CanonNNS == NNS) {
4563    QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4564  } else {
4565    TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4566    QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
4567
4568    DependentTemplateName *CheckQTN
4569      = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4570    assert(!CheckQTN && "Dependent template name canonicalization broken");
4571    (void)CheckQTN;
4572  }
4573
4574  DependentTemplateNames.InsertNode(QTN, InsertPos);
4575  return TemplateName(QTN);
4576}
4577
4578TemplateName
4579ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4580                                       const TemplateArgument &ArgPack) const {
4581  ASTContext &Self = const_cast<ASTContext &>(*this);
4582  llvm::FoldingSetNodeID ID;
4583  SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4584
4585  void *InsertPos = 0;
4586  SubstTemplateTemplateParmPackStorage *Subst
4587    = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4588
4589  if (!Subst) {
4590    Subst = new (*this) SubstTemplateTemplateParmPackStorage(Self, Param,
4591                                                           ArgPack.pack_size(),
4592                                                         ArgPack.pack_begin());
4593    SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4594  }
4595
4596  return TemplateName(Subst);
4597}
4598
4599/// getFromTargetType - Given one of the integer types provided by
4600/// TargetInfo, produce the corresponding type. The unsigned @p Type
4601/// is actually a value of type @c TargetInfo::IntType.
4602CanQualType ASTContext::getFromTargetType(unsigned Type) const {
4603  switch (Type) {
4604  case TargetInfo::NoInt: return CanQualType();
4605  case TargetInfo::SignedShort: return ShortTy;
4606  case TargetInfo::UnsignedShort: return UnsignedShortTy;
4607  case TargetInfo::SignedInt: return IntTy;
4608  case TargetInfo::UnsignedInt: return UnsignedIntTy;
4609  case TargetInfo::SignedLong: return LongTy;
4610  case TargetInfo::UnsignedLong: return UnsignedLongTy;
4611  case TargetInfo::SignedLongLong: return LongLongTy;
4612  case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4613  }
4614
4615  assert(false && "Unhandled TargetInfo::IntType value");
4616  return CanQualType();
4617}
4618
4619//===----------------------------------------------------------------------===//
4620//                        Type Predicates.
4621//===----------------------------------------------------------------------===//
4622
4623/// isObjCNSObjectType - Return true if this is an NSObject object using
4624/// NSObject attribute on a c-style pointer type.
4625/// FIXME - Make it work directly on types.
4626/// FIXME: Move to Type.
4627///
4628bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4629  if (const TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4630    if (TypedefNameDecl *TD = TDT->getDecl())
4631      if (TD->getAttr<ObjCNSObjectAttr>())
4632        return true;
4633  }
4634  return false;
4635}
4636
4637/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4638/// garbage collection attribute.
4639///
4640Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4641  if (getLangOptions().getGCMode() == LangOptions::NonGC)
4642    return Qualifiers::GCNone;
4643
4644  assert(getLangOptions().ObjC1);
4645  Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4646
4647  // Default behaviour under objective-C's gc is for ObjC pointers
4648  // (or pointers to them) be treated as though they were declared
4649  // as __strong.
4650  if (GCAttrs == Qualifiers::GCNone) {
4651    if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4652      return Qualifiers::Strong;
4653    else if (Ty->isPointerType())
4654      return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4655  } else {
4656    // It's not valid to set GC attributes on anything that isn't a
4657    // pointer.
4658#ifndef NDEBUG
4659    QualType CT = Ty->getCanonicalTypeInternal();
4660    while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4661      CT = AT->getElementType();
4662    assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4663#endif
4664  }
4665  return GCAttrs;
4666}
4667
4668//===----------------------------------------------------------------------===//
4669//                        Type Compatibility Testing
4670//===----------------------------------------------------------------------===//
4671
4672/// areCompatVectorTypes - Return true if the two specified vector types are
4673/// compatible.
4674static bool areCompatVectorTypes(const VectorType *LHS,
4675                                 const VectorType *RHS) {
4676  assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
4677  return LHS->getElementType() == RHS->getElementType() &&
4678         LHS->getNumElements() == RHS->getNumElements();
4679}
4680
4681bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4682                                          QualType SecondVec) {
4683  assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4684  assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4685
4686  if (hasSameUnqualifiedType(FirstVec, SecondVec))
4687    return true;
4688
4689  // Treat Neon vector types and most AltiVec vector types as if they are the
4690  // equivalent GCC vector types.
4691  const VectorType *First = FirstVec->getAs<VectorType>();
4692  const VectorType *Second = SecondVec->getAs<VectorType>();
4693  if (First->getNumElements() == Second->getNumElements() &&
4694      hasSameType(First->getElementType(), Second->getElementType()) &&
4695      First->getVectorKind() != VectorType::AltiVecPixel &&
4696      First->getVectorKind() != VectorType::AltiVecBool &&
4697      Second->getVectorKind() != VectorType::AltiVecPixel &&
4698      Second->getVectorKind() != VectorType::AltiVecBool)
4699    return true;
4700
4701  return false;
4702}
4703
4704//===----------------------------------------------------------------------===//
4705// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4706//===----------------------------------------------------------------------===//
4707
4708/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4709/// inheritance hierarchy of 'rProto'.
4710bool
4711ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4712                                           ObjCProtocolDecl *rProto) const {
4713  if (lProto == rProto)
4714    return true;
4715  for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4716       E = rProto->protocol_end(); PI != E; ++PI)
4717    if (ProtocolCompatibleWithProtocol(lProto, *PI))
4718      return true;
4719  return false;
4720}
4721
4722/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4723/// return true if lhs's protocols conform to rhs's protocol; false
4724/// otherwise.
4725bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4726  if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4727    return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4728  return false;
4729}
4730
4731/// ObjCQualifiedClassTypesAreCompatible - compare  Class<p,...> and
4732/// Class<p1, ...>.
4733bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4734                                                      QualType rhs) {
4735  const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4736  const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4737  assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4738
4739  for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4740       E = lhsQID->qual_end(); I != E; ++I) {
4741    bool match = false;
4742    ObjCProtocolDecl *lhsProto = *I;
4743    for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4744         E = rhsOPT->qual_end(); J != E; ++J) {
4745      ObjCProtocolDecl *rhsProto = *J;
4746      if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4747        match = true;
4748        break;
4749      }
4750    }
4751    if (!match)
4752      return false;
4753  }
4754  return true;
4755}
4756
4757/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4758/// ObjCQualifiedIDType.
4759bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4760                                                   bool compare) {
4761  // Allow id<P..> and an 'id' or void* type in all cases.
4762  if (lhs->isVoidPointerType() ||
4763      lhs->isObjCIdType() || lhs->isObjCClassType())
4764    return true;
4765  else if (rhs->isVoidPointerType() ||
4766           rhs->isObjCIdType() || rhs->isObjCClassType())
4767    return true;
4768
4769  if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
4770    const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4771
4772    if (!rhsOPT) return false;
4773
4774    if (rhsOPT->qual_empty()) {
4775      // If the RHS is a unqualified interface pointer "NSString*",
4776      // make sure we check the class hierarchy.
4777      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4778        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4779             E = lhsQID->qual_end(); I != E; ++I) {
4780          // when comparing an id<P> on lhs with a static type on rhs,
4781          // see if static class implements all of id's protocols, directly or
4782          // through its super class and categories.
4783          if (!rhsID->ClassImplementsProtocol(*I, true))
4784            return false;
4785        }
4786      }
4787      // If there are no qualifiers and no interface, we have an 'id'.
4788      return true;
4789    }
4790    // Both the right and left sides have qualifiers.
4791    for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4792         E = lhsQID->qual_end(); I != E; ++I) {
4793      ObjCProtocolDecl *lhsProto = *I;
4794      bool match = false;
4795
4796      // when comparing an id<P> on lhs with a static type on rhs,
4797      // see if static class implements all of id's protocols, directly or
4798      // through its super class and categories.
4799      for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4800           E = rhsOPT->qual_end(); J != E; ++J) {
4801        ObjCProtocolDecl *rhsProto = *J;
4802        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4803            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4804          match = true;
4805          break;
4806        }
4807      }
4808      // If the RHS is a qualified interface pointer "NSString<P>*",
4809      // make sure we check the class hierarchy.
4810      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4811        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4812             E = lhsQID->qual_end(); I != E; ++I) {
4813          // when comparing an id<P> on lhs with a static type on rhs,
4814          // see if static class implements all of id's protocols, directly or
4815          // through its super class and categories.
4816          if (rhsID->ClassImplementsProtocol(*I, true)) {
4817            match = true;
4818            break;
4819          }
4820        }
4821      }
4822      if (!match)
4823        return false;
4824    }
4825
4826    return true;
4827  }
4828
4829  const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4830  assert(rhsQID && "One of the LHS/RHS should be id<x>");
4831
4832  if (const ObjCObjectPointerType *lhsOPT =
4833        lhs->getAsObjCInterfacePointerType()) {
4834    // If both the right and left sides have qualifiers.
4835    for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4836         E = lhsOPT->qual_end(); I != E; ++I) {
4837      ObjCProtocolDecl *lhsProto = *I;
4838      bool match = false;
4839
4840      // when comparing an id<P> on rhs with a static type on lhs,
4841      // see if static class implements all of id's protocols, directly or
4842      // through its super class and categories.
4843      // First, lhs protocols in the qualifier list must be found, direct
4844      // or indirect in rhs's qualifier list or it is a mismatch.
4845      for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4846           E = rhsQID->qual_end(); J != E; ++J) {
4847        ObjCProtocolDecl *rhsProto = *J;
4848        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4849            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4850          match = true;
4851          break;
4852        }
4853      }
4854      if (!match)
4855        return false;
4856    }
4857
4858    // Static class's protocols, or its super class or category protocols
4859    // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
4860    if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4861      llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4862      CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
4863      // This is rather dubious but matches gcc's behavior. If lhs has
4864      // no type qualifier and its class has no static protocol(s)
4865      // assume that it is mismatch.
4866      if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
4867        return false;
4868      for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4869           LHSInheritedProtocols.begin(),
4870           E = LHSInheritedProtocols.end(); I != E; ++I) {
4871        bool match = false;
4872        ObjCProtocolDecl *lhsProto = (*I);
4873        for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4874             E = rhsQID->qual_end(); J != E; ++J) {
4875          ObjCProtocolDecl *rhsProto = *J;
4876          if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4877              (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4878            match = true;
4879            break;
4880          }
4881        }
4882        if (!match)
4883          return false;
4884      }
4885    }
4886    return true;
4887  }
4888  return false;
4889}
4890
4891/// canAssignObjCInterfaces - Return true if the two interface types are
4892/// compatible for assignment from RHS to LHS.  This handles validation of any
4893/// protocol qualifiers on the LHS or RHS.
4894///
4895bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4896                                         const ObjCObjectPointerType *RHSOPT) {
4897  const ObjCObjectType* LHS = LHSOPT->getObjectType();
4898  const ObjCObjectType* RHS = RHSOPT->getObjectType();
4899
4900  // If either type represents the built-in 'id' or 'Class' types, return true.
4901  if (LHS->isObjCUnqualifiedIdOrClass() ||
4902      RHS->isObjCUnqualifiedIdOrClass())
4903    return true;
4904
4905  if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
4906    return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4907                                             QualType(RHSOPT,0),
4908                                             false);
4909
4910  if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4911    return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4912                                                QualType(RHSOPT,0));
4913
4914  // If we have 2 user-defined types, fall into that path.
4915  if (LHS->getInterface() && RHS->getInterface())
4916    return canAssignObjCInterfaces(LHS, RHS);
4917
4918  return false;
4919}
4920
4921/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4922/// for providing type-safety for objective-c pointers used to pass/return
4923/// arguments in block literals. When passed as arguments, passing 'A*' where
4924/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4925/// not OK. For the return type, the opposite is not OK.
4926bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4927                                         const ObjCObjectPointerType *LHSOPT,
4928                                         const ObjCObjectPointerType *RHSOPT,
4929                                         bool BlockReturnType) {
4930  if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
4931    return true;
4932
4933  if (LHSOPT->isObjCBuiltinType()) {
4934    return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4935  }
4936
4937  if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
4938    return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4939                                             QualType(RHSOPT,0),
4940                                             false);
4941
4942  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4943  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4944  if (LHS && RHS)  { // We have 2 user-defined types.
4945    if (LHS != RHS) {
4946      if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4947        return BlockReturnType;
4948      if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4949        return !BlockReturnType;
4950    }
4951    else
4952      return true;
4953  }
4954  return false;
4955}
4956
4957/// getIntersectionOfProtocols - This routine finds the intersection of set
4958/// of protocols inherited from two distinct objective-c pointer objects.
4959/// It is used to build composite qualifier list of the composite type of
4960/// the conditional expression involving two objective-c pointer objects.
4961static
4962void getIntersectionOfProtocols(ASTContext &Context,
4963                                const ObjCObjectPointerType *LHSOPT,
4964                                const ObjCObjectPointerType *RHSOPT,
4965      llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4966
4967  const ObjCObjectType* LHS = LHSOPT->getObjectType();
4968  const ObjCObjectType* RHS = RHSOPT->getObjectType();
4969  assert(LHS->getInterface() && "LHS must have an interface base");
4970  assert(RHS->getInterface() && "RHS must have an interface base");
4971
4972  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4973  unsigned LHSNumProtocols = LHS->getNumProtocols();
4974  if (LHSNumProtocols > 0)
4975    InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4976  else {
4977    llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4978    Context.CollectInheritedProtocols(LHS->getInterface(),
4979                                      LHSInheritedProtocols);
4980    InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4981                                LHSInheritedProtocols.end());
4982  }
4983
4984  unsigned RHSNumProtocols = RHS->getNumProtocols();
4985  if (RHSNumProtocols > 0) {
4986    ObjCProtocolDecl **RHSProtocols =
4987      const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
4988    for (unsigned i = 0; i < RHSNumProtocols; ++i)
4989      if (InheritedProtocolSet.count(RHSProtocols[i]))
4990        IntersectionOfProtocols.push_back(RHSProtocols[i]);
4991  }
4992  else {
4993    llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
4994    Context.CollectInheritedProtocols(RHS->getInterface(),
4995                                      RHSInheritedProtocols);
4996    for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4997         RHSInheritedProtocols.begin(),
4998         E = RHSInheritedProtocols.end(); I != E; ++I)
4999      if (InheritedProtocolSet.count((*I)))
5000        IntersectionOfProtocols.push_back((*I));
5001  }
5002}
5003
5004/// areCommonBaseCompatible - Returns common base class of the two classes if
5005/// one found. Note that this is O'2 algorithm. But it will be called as the
5006/// last type comparison in a ?-exp of ObjC pointer types before a
5007/// warning is issued. So, its invokation is extremely rare.
5008QualType ASTContext::areCommonBaseCompatible(
5009                                          const ObjCObjectPointerType *Lptr,
5010                                          const ObjCObjectPointerType *Rptr) {
5011  const ObjCObjectType *LHS = Lptr->getObjectType();
5012  const ObjCObjectType *RHS = Rptr->getObjectType();
5013  const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5014  const ObjCInterfaceDecl* RDecl = RHS->getInterface();
5015  if (!LDecl || !RDecl || (LDecl == RDecl))
5016    return QualType();
5017
5018  do {
5019    LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
5020    if (canAssignObjCInterfaces(LHS, RHS)) {
5021      llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
5022      getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5023
5024      QualType Result = QualType(LHS, 0);
5025      if (!Protocols.empty())
5026        Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5027      Result = getObjCObjectPointerType(Result);
5028      return Result;
5029    }
5030  } while ((LDecl = LDecl->getSuperClass()));
5031
5032  return QualType();
5033}
5034
5035bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5036                                         const ObjCObjectType *RHS) {
5037  assert(LHS->getInterface() && "LHS is not an interface type");
5038  assert(RHS->getInterface() && "RHS is not an interface type");
5039
5040  // Verify that the base decls are compatible: the RHS must be a subclass of
5041  // the LHS.
5042  if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
5043    return false;
5044
5045  // RHS must have a superset of the protocols in the LHS.  If the LHS is not
5046  // protocol qualified at all, then we are good.
5047  if (LHS->getNumProtocols() == 0)
5048    return true;
5049
5050  // Okay, we know the LHS has protocol qualifiers.  If the RHS doesn't,
5051  // more detailed analysis is required.
5052  if (RHS->getNumProtocols() == 0) {
5053    // OK, if LHS is a superclass of RHS *and*
5054    // this superclass is assignment compatible with LHS.
5055    // false otherwise.
5056    bool IsSuperClass =
5057      LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5058    if (IsSuperClass) {
5059      // OK if conversion of LHS to SuperClass results in narrowing of types
5060      // ; i.e., SuperClass may implement at least one of the protocols
5061      // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5062      // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5063      llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
5064      CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
5065      // If super class has no protocols, it is not a match.
5066      if (SuperClassInheritedProtocols.empty())
5067        return false;
5068
5069      for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5070           LHSPE = LHS->qual_end();
5071           LHSPI != LHSPE; LHSPI++) {
5072        bool SuperImplementsProtocol = false;
5073        ObjCProtocolDecl *LHSProto = (*LHSPI);
5074
5075        for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5076             SuperClassInheritedProtocols.begin(),
5077             E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5078          ObjCProtocolDecl *SuperClassProto = (*I);
5079          if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5080            SuperImplementsProtocol = true;
5081            break;
5082          }
5083        }
5084        if (!SuperImplementsProtocol)
5085          return false;
5086      }
5087      return true;
5088    }
5089    return false;
5090  }
5091
5092  for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5093                                     LHSPE = LHS->qual_end();
5094       LHSPI != LHSPE; LHSPI++) {
5095    bool RHSImplementsProtocol = false;
5096
5097    // If the RHS doesn't implement the protocol on the left, the types
5098    // are incompatible.
5099    for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5100                                       RHSPE = RHS->qual_end();
5101         RHSPI != RHSPE; RHSPI++) {
5102      if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
5103        RHSImplementsProtocol = true;
5104        break;
5105      }
5106    }
5107    // FIXME: For better diagnostics, consider passing back the protocol name.
5108    if (!RHSImplementsProtocol)
5109      return false;
5110  }
5111  // The RHS implements all protocols listed on the LHS.
5112  return true;
5113}
5114
5115bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5116  // get the "pointed to" types
5117  const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5118  const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
5119
5120  if (!LHSOPT || !RHSOPT)
5121    return false;
5122
5123  return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5124         canAssignObjCInterfaces(RHSOPT, LHSOPT);
5125}
5126
5127bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5128  return canAssignObjCInterfaces(
5129                getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5130                getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5131}
5132
5133/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
5134/// both shall have the identically qualified version of a compatible type.
5135/// C99 6.2.7p1: Two types have compatible types if their types are the
5136/// same. See 6.7.[2,3,5] for additional rules.
5137bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5138                                    bool CompareUnqualified) {
5139  if (getLangOptions().CPlusPlus)
5140    return hasSameType(LHS, RHS);
5141
5142  return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
5143}
5144
5145bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5146  return !mergeTypes(LHS, RHS, true).isNull();
5147}
5148
5149/// mergeTransparentUnionType - if T is a transparent union type and a member
5150/// of T is compatible with SubType, return the merged type, else return
5151/// QualType()
5152QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5153                                               bool OfBlockPointer,
5154                                               bool Unqualified) {
5155  if (const RecordType *UT = T->getAsUnionType()) {
5156    RecordDecl *UD = UT->getDecl();
5157    if (UD->hasAttr<TransparentUnionAttr>()) {
5158      for (RecordDecl::field_iterator it = UD->field_begin(),
5159           itend = UD->field_end(); it != itend; ++it) {
5160        QualType ET = it->getType().getUnqualifiedType();
5161        QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5162        if (!MT.isNull())
5163          return MT;
5164      }
5165    }
5166  }
5167
5168  return QualType();
5169}
5170
5171/// mergeFunctionArgumentTypes - merge two types which appear as function
5172/// argument types
5173QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5174                                                bool OfBlockPointer,
5175                                                bool Unqualified) {
5176  // GNU extension: two types are compatible if they appear as a function
5177  // argument, one of the types is a transparent union type and the other
5178  // type is compatible with a union member
5179  QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5180                                              Unqualified);
5181  if (!lmerge.isNull())
5182    return lmerge;
5183
5184  QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5185                                              Unqualified);
5186  if (!rmerge.isNull())
5187    return rmerge;
5188
5189  return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5190}
5191
5192QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
5193                                        bool OfBlockPointer,
5194                                        bool Unqualified) {
5195  const FunctionType *lbase = lhs->getAs<FunctionType>();
5196  const FunctionType *rbase = rhs->getAs<FunctionType>();
5197  const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5198  const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
5199  bool allLTypes = true;
5200  bool allRTypes = true;
5201
5202  // Check return type
5203  QualType retType;
5204  if (OfBlockPointer) {
5205    QualType RHS = rbase->getResultType();
5206    QualType LHS = lbase->getResultType();
5207    bool UnqualifiedResult = Unqualified;
5208    if (!UnqualifiedResult)
5209      UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
5210    retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
5211  }
5212  else
5213    retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5214                         Unqualified);
5215  if (retType.isNull()) return QualType();
5216
5217  if (Unqualified)
5218    retType = retType.getUnqualifiedType();
5219
5220  CanQualType LRetType = getCanonicalType(lbase->getResultType());
5221  CanQualType RRetType = getCanonicalType(rbase->getResultType());
5222  if (Unqualified) {
5223    LRetType = LRetType.getUnqualifiedType();
5224    RRetType = RRetType.getUnqualifiedType();
5225  }
5226
5227  if (getCanonicalType(retType) != LRetType)
5228    allLTypes = false;
5229  if (getCanonicalType(retType) != RRetType)
5230    allRTypes = false;
5231
5232  // FIXME: double check this
5233  // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5234  //                           rbase->getRegParmAttr() != 0 &&
5235  //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
5236  FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5237  FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
5238
5239  // Compatible functions must have compatible calling conventions
5240  if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
5241    return QualType();
5242
5243  // Regparm is part of the calling convention.
5244  if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5245    return QualType();
5246  if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5247    return QualType();
5248
5249  // It's noreturn if either type is.
5250  // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5251  bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5252  if (NoReturn != lbaseInfo.getNoReturn())
5253    allLTypes = false;
5254  if (NoReturn != rbaseInfo.getNoReturn())
5255    allRTypes = false;
5256
5257  FunctionType::ExtInfo einfo(NoReturn,
5258                              lbaseInfo.getHasRegParm(),
5259                              lbaseInfo.getRegParm(),
5260                              lbaseInfo.getCC());
5261
5262  if (lproto && rproto) { // two C99 style function prototypes
5263    assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5264           "C++ shouldn't be here");
5265    unsigned lproto_nargs = lproto->getNumArgs();
5266    unsigned rproto_nargs = rproto->getNumArgs();
5267
5268    // Compatible functions must have the same number of arguments
5269    if (lproto_nargs != rproto_nargs)
5270      return QualType();
5271
5272    // Variadic and non-variadic functions aren't compatible
5273    if (lproto->isVariadic() != rproto->isVariadic())
5274      return QualType();
5275
5276    if (lproto->getTypeQuals() != rproto->getTypeQuals())
5277      return QualType();
5278
5279    // Check argument compatibility
5280    llvm::SmallVector<QualType, 10> types;
5281    for (unsigned i = 0; i < lproto_nargs; i++) {
5282      QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5283      QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
5284      QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5285                                                    OfBlockPointer,
5286                                                    Unqualified);
5287      if (argtype.isNull()) return QualType();
5288
5289      if (Unqualified)
5290        argtype = argtype.getUnqualifiedType();
5291
5292      types.push_back(argtype);
5293      if (Unqualified) {
5294        largtype = largtype.getUnqualifiedType();
5295        rargtype = rargtype.getUnqualifiedType();
5296      }
5297
5298      if (getCanonicalType(argtype) != getCanonicalType(largtype))
5299        allLTypes = false;
5300      if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5301        allRTypes = false;
5302    }
5303    if (allLTypes) return lhs;
5304    if (allRTypes) return rhs;
5305
5306    FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5307    EPI.ExtInfo = einfo;
5308    return getFunctionType(retType, types.begin(), types.size(), EPI);
5309  }
5310
5311  if (lproto) allRTypes = false;
5312  if (rproto) allLTypes = false;
5313
5314  const FunctionProtoType *proto = lproto ? lproto : rproto;
5315  if (proto) {
5316    assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
5317    if (proto->isVariadic()) return QualType();
5318    // Check that the types are compatible with the types that
5319    // would result from default argument promotions (C99 6.7.5.3p15).
5320    // The only types actually affected are promotable integer
5321    // types and floats, which would be passed as a different
5322    // type depending on whether the prototype is visible.
5323    unsigned proto_nargs = proto->getNumArgs();
5324    for (unsigned i = 0; i < proto_nargs; ++i) {
5325      QualType argTy = proto->getArgType(i);
5326
5327      // Look at the promotion type of enum types, since that is the type used
5328      // to pass enum values.
5329      if (const EnumType *Enum = argTy->getAs<EnumType>())
5330        argTy = Enum->getDecl()->getPromotionType();
5331
5332      if (argTy->isPromotableIntegerType() ||
5333          getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5334        return QualType();
5335    }
5336
5337    if (allLTypes) return lhs;
5338    if (allRTypes) return rhs;
5339
5340    FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5341    EPI.ExtInfo = einfo;
5342    return getFunctionType(retType, proto->arg_type_begin(),
5343                           proto->getNumArgs(), EPI);
5344  }
5345
5346  if (allLTypes) return lhs;
5347  if (allRTypes) return rhs;
5348  return getFunctionNoProtoType(retType, einfo);
5349}
5350
5351QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
5352                                bool OfBlockPointer,
5353                                bool Unqualified, bool BlockReturnType) {
5354  // C++ [expr]: If an expression initially has the type "reference to T", the
5355  // type is adjusted to "T" prior to any further analysis, the expression
5356  // designates the object or function denoted by the reference, and the
5357  // expression is an lvalue unless the reference is an rvalue reference and
5358  // the expression is a function call (possibly inside parentheses).
5359  assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5360  assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
5361
5362  if (Unqualified) {
5363    LHS = LHS.getUnqualifiedType();
5364    RHS = RHS.getUnqualifiedType();
5365  }
5366
5367  QualType LHSCan = getCanonicalType(LHS),
5368           RHSCan = getCanonicalType(RHS);
5369
5370  // If two types are identical, they are compatible.
5371  if (LHSCan == RHSCan)
5372    return LHS;
5373
5374  // If the qualifiers are different, the types aren't compatible... mostly.
5375  Qualifiers LQuals = LHSCan.getLocalQualifiers();
5376  Qualifiers RQuals = RHSCan.getLocalQualifiers();
5377  if (LQuals != RQuals) {
5378    // If any of these qualifiers are different, we have a type
5379    // mismatch.
5380    if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5381        LQuals.getAddressSpace() != RQuals.getAddressSpace())
5382      return QualType();
5383
5384    // Exactly one GC qualifier difference is allowed: __strong is
5385    // okay if the other type has no GC qualifier but is an Objective
5386    // C object pointer (i.e. implicitly strong by default).  We fix
5387    // this by pretending that the unqualified type was actually
5388    // qualified __strong.
5389    Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5390    Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5391    assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5392
5393    if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5394      return QualType();
5395
5396    if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5397      return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5398    }
5399    if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5400      return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5401    }
5402    return QualType();
5403  }
5404
5405  // Okay, qualifiers are equal.
5406
5407  Type::TypeClass LHSClass = LHSCan->getTypeClass();
5408  Type::TypeClass RHSClass = RHSCan->getTypeClass();
5409
5410  // We want to consider the two function types to be the same for these
5411  // comparisons, just force one to the other.
5412  if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5413  if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
5414
5415  // Same as above for arrays
5416  if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5417    LHSClass = Type::ConstantArray;
5418  if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5419    RHSClass = Type::ConstantArray;
5420
5421  // ObjCInterfaces are just specialized ObjCObjects.
5422  if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5423  if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5424
5425  // Canonicalize ExtVector -> Vector.
5426  if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5427  if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
5428
5429  // If the canonical type classes don't match.
5430  if (LHSClass != RHSClass) {
5431    // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
5432    // a signed integer type, or an unsigned integer type.
5433    // Compatibility is based on the underlying type, not the promotion
5434    // type.
5435    if (const EnumType* ETy = LHS->getAs<EnumType>()) {
5436      if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5437        return RHS;
5438    }
5439    if (const EnumType* ETy = RHS->getAs<EnumType>()) {
5440      if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5441        return LHS;
5442    }
5443
5444    return QualType();
5445  }
5446
5447  // The canonical type classes match.
5448  switch (LHSClass) {
5449#define TYPE(Class, Base)
5450#define ABSTRACT_TYPE(Class, Base)
5451#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
5452#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5453#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5454#include "clang/AST/TypeNodes.def"
5455    assert(false && "Non-canonical and dependent types shouldn't get here");
5456    return QualType();
5457
5458  case Type::LValueReference:
5459  case Type::RValueReference:
5460  case Type::MemberPointer:
5461    assert(false && "C++ should never be in mergeTypes");
5462    return QualType();
5463
5464  case Type::ObjCInterface:
5465  case Type::IncompleteArray:
5466  case Type::VariableArray:
5467  case Type::FunctionProto:
5468  case Type::ExtVector:
5469    assert(false && "Types are eliminated above");
5470    return QualType();
5471
5472  case Type::Pointer:
5473  {
5474    // Merge two pointer types, while trying to preserve typedef info
5475    QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5476    QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
5477    if (Unqualified) {
5478      LHSPointee = LHSPointee.getUnqualifiedType();
5479      RHSPointee = RHSPointee.getUnqualifiedType();
5480    }
5481    QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5482                                     Unqualified);
5483    if (ResultType.isNull()) return QualType();
5484    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5485      return LHS;
5486    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5487      return RHS;
5488    return getPointerType(ResultType);
5489  }
5490  case Type::BlockPointer:
5491  {
5492    // Merge two block pointer types, while trying to preserve typedef info
5493    QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5494    QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
5495    if (Unqualified) {
5496      LHSPointee = LHSPointee.getUnqualifiedType();
5497      RHSPointee = RHSPointee.getUnqualifiedType();
5498    }
5499    QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5500                                     Unqualified);
5501    if (ResultType.isNull()) return QualType();
5502    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5503      return LHS;
5504    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5505      return RHS;
5506    return getBlockPointerType(ResultType);
5507  }
5508  case Type::ConstantArray:
5509  {
5510    const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5511    const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5512    if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5513      return QualType();
5514
5515    QualType LHSElem = getAsArrayType(LHS)->getElementType();
5516    QualType RHSElem = getAsArrayType(RHS)->getElementType();
5517    if (Unqualified) {
5518      LHSElem = LHSElem.getUnqualifiedType();
5519      RHSElem = RHSElem.getUnqualifiedType();
5520    }
5521
5522    QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
5523    if (ResultType.isNull()) return QualType();
5524    if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5525      return LHS;
5526    if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5527      return RHS;
5528    if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5529                                          ArrayType::ArraySizeModifier(), 0);
5530    if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5531                                          ArrayType::ArraySizeModifier(), 0);
5532    const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5533    const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
5534    if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5535      return LHS;
5536    if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5537      return RHS;
5538    if (LVAT) {
5539      // FIXME: This isn't correct! But tricky to implement because
5540      // the array's size has to be the size of LHS, but the type
5541      // has to be different.
5542      return LHS;
5543    }
5544    if (RVAT) {
5545      // FIXME: This isn't correct! But tricky to implement because
5546      // the array's size has to be the size of RHS, but the type
5547      // has to be different.
5548      return RHS;
5549    }
5550    if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5551    if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
5552    return getIncompleteArrayType(ResultType,
5553                                  ArrayType::ArraySizeModifier(), 0);
5554  }
5555  case Type::FunctionNoProto:
5556    return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
5557  case Type::Record:
5558  case Type::Enum:
5559    return QualType();
5560  case Type::Builtin:
5561    // Only exactly equal builtin types are compatible, which is tested above.
5562    return QualType();
5563  case Type::Complex:
5564    // Distinct complex types are incompatible.
5565    return QualType();
5566  case Type::Vector:
5567    // FIXME: The merged type should be an ExtVector!
5568    if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5569                             RHSCan->getAs<VectorType>()))
5570      return LHS;
5571    return QualType();
5572  case Type::ObjCObject: {
5573    // Check if the types are assignment compatible.
5574    // FIXME: This should be type compatibility, e.g. whether
5575    // "LHS x; RHS x;" at global scope is legal.
5576    const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5577    const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5578    if (canAssignObjCInterfaces(LHSIface, RHSIface))
5579      return LHS;
5580
5581    return QualType();
5582  }
5583  case Type::ObjCObjectPointer: {
5584    if (OfBlockPointer) {
5585      if (canAssignObjCInterfacesInBlockPointer(
5586                                          LHS->getAs<ObjCObjectPointerType>(),
5587                                          RHS->getAs<ObjCObjectPointerType>(),
5588                                          BlockReturnType))
5589      return LHS;
5590      return QualType();
5591    }
5592    if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5593                                RHS->getAs<ObjCObjectPointerType>()))
5594      return LHS;
5595
5596    return QualType();
5597    }
5598  }
5599
5600  return QualType();
5601}
5602
5603/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5604/// 'RHS' attributes and returns the merged version; including for function
5605/// return types.
5606QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5607  QualType LHSCan = getCanonicalType(LHS),
5608  RHSCan = getCanonicalType(RHS);
5609  // If two types are identical, they are compatible.
5610  if (LHSCan == RHSCan)
5611    return LHS;
5612  if (RHSCan->isFunctionType()) {
5613    if (!LHSCan->isFunctionType())
5614      return QualType();
5615    QualType OldReturnType =
5616      cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5617    QualType NewReturnType =
5618      cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5619    QualType ResReturnType =
5620      mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5621    if (ResReturnType.isNull())
5622      return QualType();
5623    if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5624      // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5625      // In either case, use OldReturnType to build the new function type.
5626      const FunctionType *F = LHS->getAs<FunctionType>();
5627      if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
5628        FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5629        EPI.ExtInfo = getFunctionExtInfo(LHS);
5630        QualType ResultType
5631          = getFunctionType(OldReturnType, FPT->arg_type_begin(),
5632                            FPT->getNumArgs(), EPI);
5633        return ResultType;
5634      }
5635    }
5636    return QualType();
5637  }
5638
5639  // If the qualifiers are different, the types can still be merged.
5640  Qualifiers LQuals = LHSCan.getLocalQualifiers();
5641  Qualifiers RQuals = RHSCan.getLocalQualifiers();
5642  if (LQuals != RQuals) {
5643    // If any of these qualifiers are different, we have a type mismatch.
5644    if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5645        LQuals.getAddressSpace() != RQuals.getAddressSpace())
5646      return QualType();
5647
5648    // Exactly one GC qualifier difference is allowed: __strong is
5649    // okay if the other type has no GC qualifier but is an Objective
5650    // C object pointer (i.e. implicitly strong by default).  We fix
5651    // this by pretending that the unqualified type was actually
5652    // qualified __strong.
5653    Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5654    Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5655    assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5656
5657    if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5658      return QualType();
5659
5660    if (GC_L == Qualifiers::Strong)
5661      return LHS;
5662    if (GC_R == Qualifiers::Strong)
5663      return RHS;
5664    return QualType();
5665  }
5666
5667  if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5668    QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5669    QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5670    QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5671    if (ResQT == LHSBaseQT)
5672      return LHS;
5673    if (ResQT == RHSBaseQT)
5674      return RHS;
5675  }
5676  return QualType();
5677}
5678
5679//===----------------------------------------------------------------------===//
5680//                         Integer Predicates
5681//===----------------------------------------------------------------------===//
5682
5683unsigned ASTContext::getIntWidth(QualType T) const {
5684  if (const EnumType *ET = dyn_cast<EnumType>(T))
5685    T = ET->getDecl()->getIntegerType();
5686  if (T->isBooleanType())
5687    return 1;
5688  // For builtin types, just use the standard type sizing method
5689  return (unsigned)getTypeSize(T);
5690}
5691
5692QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
5693  assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
5694
5695  // Turn <4 x signed int> -> <4 x unsigned int>
5696  if (const VectorType *VTy = T->getAs<VectorType>())
5697    return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
5698                         VTy->getNumElements(), VTy->getVectorKind());
5699
5700  // For enums, we return the unsigned version of the base type.
5701  if (const EnumType *ETy = T->getAs<EnumType>())
5702    T = ETy->getDecl()->getIntegerType();
5703
5704  const BuiltinType *BTy = T->getAs<BuiltinType>();
5705  assert(BTy && "Unexpected signed integer type");
5706  switch (BTy->getKind()) {
5707  case BuiltinType::Char_S:
5708  case BuiltinType::SChar:
5709    return UnsignedCharTy;
5710  case BuiltinType::Short:
5711    return UnsignedShortTy;
5712  case BuiltinType::Int:
5713    return UnsignedIntTy;
5714  case BuiltinType::Long:
5715    return UnsignedLongTy;
5716  case BuiltinType::LongLong:
5717    return UnsignedLongLongTy;
5718  case BuiltinType::Int128:
5719    return UnsignedInt128Ty;
5720  default:
5721    assert(0 && "Unexpected signed integer type");
5722    return QualType();
5723  }
5724}
5725
5726ASTMutationListener::~ASTMutationListener() { }
5727
5728
5729//===----------------------------------------------------------------------===//
5730//                          Builtin Type Computation
5731//===----------------------------------------------------------------------===//
5732
5733/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
5734/// pointer over the consumed characters.  This returns the resultant type.  If
5735/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5736/// types.  This allows "v2i*" to be parsed as a pointer to a v2i instead of
5737/// a vector of "i*".
5738///
5739/// RequiresICE is filled in on return to indicate whether the value is required
5740/// to be an Integer Constant Expression.
5741static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
5742                                  ASTContext::GetBuiltinTypeError &Error,
5743                                  bool &RequiresICE,
5744                                  bool AllowTypeModifiers) {
5745  // Modifiers.
5746  int HowLong = 0;
5747  bool Signed = false, Unsigned = false;
5748  RequiresICE = false;
5749
5750  // Read the prefixed modifiers first.
5751  bool Done = false;
5752  while (!Done) {
5753    switch (*Str++) {
5754    default: Done = true; --Str; break;
5755    case 'I':
5756      RequiresICE = true;
5757      break;
5758    case 'S':
5759      assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5760      assert(!Signed && "Can't use 'S' modifier multiple times!");
5761      Signed = true;
5762      break;
5763    case 'U':
5764      assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5765      assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5766      Unsigned = true;
5767      break;
5768    case 'L':
5769      assert(HowLong <= 2 && "Can't have LLLL modifier");
5770      ++HowLong;
5771      break;
5772    }
5773  }
5774
5775  QualType Type;
5776
5777  // Read the base type.
5778  switch (*Str++) {
5779  default: assert(0 && "Unknown builtin type letter!");
5780  case 'v':
5781    assert(HowLong == 0 && !Signed && !Unsigned &&
5782           "Bad modifiers used with 'v'!");
5783    Type = Context.VoidTy;
5784    break;
5785  case 'f':
5786    assert(HowLong == 0 && !Signed && !Unsigned &&
5787           "Bad modifiers used with 'f'!");
5788    Type = Context.FloatTy;
5789    break;
5790  case 'd':
5791    assert(HowLong < 2 && !Signed && !Unsigned &&
5792           "Bad modifiers used with 'd'!");
5793    if (HowLong)
5794      Type = Context.LongDoubleTy;
5795    else
5796      Type = Context.DoubleTy;
5797    break;
5798  case 's':
5799    assert(HowLong == 0 && "Bad modifiers used with 's'!");
5800    if (Unsigned)
5801      Type = Context.UnsignedShortTy;
5802    else
5803      Type = Context.ShortTy;
5804    break;
5805  case 'i':
5806    if (HowLong == 3)
5807      Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5808    else if (HowLong == 2)
5809      Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5810    else if (HowLong == 1)
5811      Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5812    else
5813      Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5814    break;
5815  case 'c':
5816    assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5817    if (Signed)
5818      Type = Context.SignedCharTy;
5819    else if (Unsigned)
5820      Type = Context.UnsignedCharTy;
5821    else
5822      Type = Context.CharTy;
5823    break;
5824  case 'b': // boolean
5825    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5826    Type = Context.BoolTy;
5827    break;
5828  case 'z':  // size_t.
5829    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5830    Type = Context.getSizeType();
5831    break;
5832  case 'F':
5833    Type = Context.getCFConstantStringType();
5834    break;
5835  case 'G':
5836    Type = Context.getObjCIdType();
5837    break;
5838  case 'H':
5839    Type = Context.getObjCSelType();
5840    break;
5841  case 'a':
5842    Type = Context.getBuiltinVaListType();
5843    assert(!Type.isNull() && "builtin va list type not initialized!");
5844    break;
5845  case 'A':
5846    // This is a "reference" to a va_list; however, what exactly
5847    // this means depends on how va_list is defined. There are two
5848    // different kinds of va_list: ones passed by value, and ones
5849    // passed by reference.  An example of a by-value va_list is
5850    // x86, where va_list is a char*. An example of by-ref va_list
5851    // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5852    // we want this argument to be a char*&; for x86-64, we want
5853    // it to be a __va_list_tag*.
5854    Type = Context.getBuiltinVaListType();
5855    assert(!Type.isNull() && "builtin va list type not initialized!");
5856    if (Type->isArrayType())
5857      Type = Context.getArrayDecayedType(Type);
5858    else
5859      Type = Context.getLValueReferenceType(Type);
5860    break;
5861  case 'V': {
5862    char *End;
5863    unsigned NumElements = strtoul(Str, &End, 10);
5864    assert(End != Str && "Missing vector size");
5865    Str = End;
5866
5867    QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
5868                                             RequiresICE, false);
5869    assert(!RequiresICE && "Can't require vector ICE");
5870
5871    // TODO: No way to make AltiVec vectors in builtins yet.
5872    Type = Context.getVectorType(ElementType, NumElements,
5873                                 VectorType::GenericVector);
5874    break;
5875  }
5876  case 'X': {
5877    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
5878                                             false);
5879    assert(!RequiresICE && "Can't require complex ICE");
5880    Type = Context.getComplexType(ElementType);
5881    break;
5882  }
5883  case 'P':
5884    Type = Context.getFILEType();
5885    if (Type.isNull()) {
5886      Error = ASTContext::GE_Missing_stdio;
5887      return QualType();
5888    }
5889    break;
5890  case 'J':
5891    if (Signed)
5892      Type = Context.getsigjmp_bufType();
5893    else
5894      Type = Context.getjmp_bufType();
5895
5896    if (Type.isNull()) {
5897      Error = ASTContext::GE_Missing_setjmp;
5898      return QualType();
5899    }
5900    break;
5901  }
5902
5903  // If there are modifiers and if we're allowed to parse them, go for it.
5904  Done = !AllowTypeModifiers;
5905  while (!Done) {
5906    switch (char c = *Str++) {
5907    default: Done = true; --Str; break;
5908    case '*':
5909    case '&': {
5910      // Both pointers and references can have their pointee types
5911      // qualified with an address space.
5912      char *End;
5913      unsigned AddrSpace = strtoul(Str, &End, 10);
5914      if (End != Str && AddrSpace != 0) {
5915        Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5916        Str = End;
5917      }
5918      if (c == '*')
5919        Type = Context.getPointerType(Type);
5920      else
5921        Type = Context.getLValueReferenceType(Type);
5922      break;
5923    }
5924    // FIXME: There's no way to have a built-in with an rvalue ref arg.
5925    case 'C':
5926      Type = Type.withConst();
5927      break;
5928    case 'D':
5929      Type = Context.getVolatileType(Type);
5930      break;
5931    }
5932  }
5933
5934  assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
5935         "Integer constant 'I' type must be an integer");
5936
5937  return Type;
5938}
5939
5940/// GetBuiltinType - Return the type for the specified builtin.
5941QualType ASTContext::GetBuiltinType(unsigned Id,
5942                                    GetBuiltinTypeError &Error,
5943                                    unsigned *IntegerConstantArgs) const {
5944  const char *TypeStr = BuiltinInfo.GetTypeString(Id);
5945
5946  llvm::SmallVector<QualType, 8> ArgTypes;
5947
5948  bool RequiresICE = false;
5949  Error = GE_None;
5950  QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
5951                                       RequiresICE, true);
5952  if (Error != GE_None)
5953    return QualType();
5954
5955  assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
5956
5957  while (TypeStr[0] && TypeStr[0] != '.') {
5958    QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
5959    if (Error != GE_None)
5960      return QualType();
5961
5962    // If this argument is required to be an IntegerConstantExpression and the
5963    // caller cares, fill in the bitmask we return.
5964    if (RequiresICE && IntegerConstantArgs)
5965      *IntegerConstantArgs |= 1 << ArgTypes.size();
5966
5967    // Do array -> pointer decay.  The builtin should use the decayed type.
5968    if (Ty->isArrayType())
5969      Ty = getArrayDecayedType(Ty);
5970
5971    ArgTypes.push_back(Ty);
5972  }
5973
5974  assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5975         "'.' should only occur at end of builtin type list!");
5976
5977  FunctionType::ExtInfo EI;
5978  if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
5979
5980  bool Variadic = (TypeStr[0] == '.');
5981
5982  // We really shouldn't be making a no-proto type here, especially in C++.
5983  if (ArgTypes.empty() && Variadic)
5984    return getFunctionNoProtoType(ResType, EI);
5985
5986  FunctionProtoType::ExtProtoInfo EPI;
5987  EPI.ExtInfo = EI;
5988  EPI.Variadic = Variadic;
5989
5990  return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
5991}
5992
5993GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5994  GVALinkage External = GVA_StrongExternal;
5995
5996  Linkage L = FD->getLinkage();
5997  switch (L) {
5998  case NoLinkage:
5999  case InternalLinkage:
6000  case UniqueExternalLinkage:
6001    return GVA_Internal;
6002
6003  case ExternalLinkage:
6004    switch (FD->getTemplateSpecializationKind()) {
6005    case TSK_Undeclared:
6006    case TSK_ExplicitSpecialization:
6007      External = GVA_StrongExternal;
6008      break;
6009
6010    case TSK_ExplicitInstantiationDefinition:
6011      return GVA_ExplicitTemplateInstantiation;
6012
6013    case TSK_ExplicitInstantiationDeclaration:
6014    case TSK_ImplicitInstantiation:
6015      External = GVA_TemplateInstantiation;
6016      break;
6017    }
6018  }
6019
6020  if (!FD->isInlined())
6021    return External;
6022
6023  if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6024    // GNU or C99 inline semantics. Determine whether this symbol should be
6025    // externally visible.
6026    if (FD->isInlineDefinitionExternallyVisible())
6027      return External;
6028
6029    // C99 inline semantics, where the symbol is not externally visible.
6030    return GVA_C99Inline;
6031  }
6032
6033  // C++0x [temp.explicit]p9:
6034  //   [ Note: The intent is that an inline function that is the subject of
6035  //   an explicit instantiation declaration will still be implicitly
6036  //   instantiated when used so that the body can be considered for
6037  //   inlining, but that no out-of-line copy of the inline function would be
6038  //   generated in the translation unit. -- end note ]
6039  if (FD->getTemplateSpecializationKind()
6040                                       == TSK_ExplicitInstantiationDeclaration)
6041    return GVA_C99Inline;
6042
6043  return GVA_CXXInline;
6044}
6045
6046GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6047  // If this is a static data member, compute the kind of template
6048  // specialization. Otherwise, this variable is not part of a
6049  // template.
6050  TemplateSpecializationKind TSK = TSK_Undeclared;
6051  if (VD->isStaticDataMember())
6052    TSK = VD->getTemplateSpecializationKind();
6053
6054  Linkage L = VD->getLinkage();
6055  if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6056      VD->getType()->getLinkage() == UniqueExternalLinkage)
6057    L = UniqueExternalLinkage;
6058
6059  switch (L) {
6060  case NoLinkage:
6061  case InternalLinkage:
6062  case UniqueExternalLinkage:
6063    return GVA_Internal;
6064
6065  case ExternalLinkage:
6066    switch (TSK) {
6067    case TSK_Undeclared:
6068    case TSK_ExplicitSpecialization:
6069      return GVA_StrongExternal;
6070
6071    case TSK_ExplicitInstantiationDeclaration:
6072      llvm_unreachable("Variable should not be instantiated");
6073      // Fall through to treat this like any other instantiation.
6074
6075    case TSK_ExplicitInstantiationDefinition:
6076      return GVA_ExplicitTemplateInstantiation;
6077
6078    case TSK_ImplicitInstantiation:
6079      return GVA_TemplateInstantiation;
6080    }
6081  }
6082
6083  return GVA_StrongExternal;
6084}
6085
6086bool ASTContext::DeclMustBeEmitted(const Decl *D) {
6087  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6088    if (!VD->isFileVarDecl())
6089      return false;
6090  } else if (!isa<FunctionDecl>(D))
6091    return false;
6092
6093  // Weak references don't produce any output by themselves.
6094  if (D->hasAttr<WeakRefAttr>())
6095    return false;
6096
6097  // Aliases and used decls are required.
6098  if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6099    return true;
6100
6101  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6102    // Forward declarations aren't required.
6103    if (!FD->isThisDeclarationADefinition())
6104      return false;
6105
6106    // Constructors and destructors are required.
6107    if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6108      return true;
6109
6110    // The key function for a class is required.
6111    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6112      const CXXRecordDecl *RD = MD->getParent();
6113      if (MD->isOutOfLine() && RD->isDynamicClass()) {
6114        const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6115        if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6116          return true;
6117      }
6118    }
6119
6120    GVALinkage Linkage = GetGVALinkageForFunction(FD);
6121
6122    // static, static inline, always_inline, and extern inline functions can
6123    // always be deferred.  Normal inline functions can be deferred in C99/C++.
6124    // Implicit template instantiations can also be deferred in C++.
6125    if (Linkage == GVA_Internal  || Linkage == GVA_C99Inline ||
6126        Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6127      return false;
6128    return true;
6129  }
6130
6131  const VarDecl *VD = cast<VarDecl>(D);
6132  assert(VD->isFileVarDecl() && "Expected file scoped var");
6133
6134  if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6135    return false;
6136
6137  // Structs that have non-trivial constructors or destructors are required.
6138
6139  // FIXME: Handle references.
6140  if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6141    if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
6142      if (RD->hasDefinition() &&
6143          (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
6144        return true;
6145    }
6146  }
6147
6148  GVALinkage L = GetGVALinkageForVariable(VD);
6149  if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6150    if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6151      return false;
6152  }
6153
6154  return true;
6155}
6156
6157CallingConv ASTContext::getDefaultMethodCallConv() {
6158  // Pass through to the C++ ABI object
6159  return ABI->getDefaultMethodCallConv();
6160}
6161
6162bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
6163  // Pass through to the C++ ABI object
6164  return ABI->isNearlyEmpty(RD);
6165}
6166
6167MangleContext *ASTContext::createMangleContext() {
6168  switch (Target.getCXXABI()) {
6169  case CXXABI_ARM:
6170  case CXXABI_Itanium:
6171    return createItaniumMangleContext(*this, getDiagnostics());
6172  case CXXABI_Microsoft:
6173    return createMicrosoftMangleContext(*this, getDiagnostics());
6174  }
6175  assert(0 && "Unsupported ABI");
6176  return 0;
6177}
6178
6179CXXABI::~CXXABI() {}
6180
6181size_t ASTContext::getSideTableAllocatedMemory() const {
6182  size_t bytes = 0;
6183  bytes += ASTRecordLayouts.getMemorySize();
6184  bytes += ObjCLayouts.getMemorySize();
6185  bytes += KeyFunctions.getMemorySize();
6186  bytes += ObjCImpls.getMemorySize();
6187  bytes += BlockVarCopyInits.getMemorySize();
6188  bytes += DeclAttrs.getMemorySize();
6189  bytes += InstantiatedFromStaticDataMember.getMemorySize();
6190  bytes += InstantiatedFromUsingDecl.getMemorySize();
6191  bytes += InstantiatedFromUsingShadowDecl.getMemorySize();
6192  bytes += InstantiatedFromUnnamedFieldDecl.getMemorySize();
6193  return bytes;
6194}
6195
6196