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