ASTContext.cpp revision ed8abf18329df67b0abcbb3a10458bd8c1d2a595
19f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
29f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson//
39f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson//                     The LLVM Compiler Infrastructure
49f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson//
59f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson// This file is distributed under the University of Illinois Open Source
69f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson// License. See LICENSE.TXT for details.
79f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson//
89f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson//===----------------------------------------------------------------------===//
99f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson//
109f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson//  This file implements the ASTContext interface.
119f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson//
129f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson//===----------------------------------------------------------------------===//
139f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
149f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "clang/AST/ASTContext.h"
159f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "clang/AST/CharUnits.h"
169f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "clang/AST/DeclCXX.h"
179f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "clang/AST/DeclObjC.h"
189f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "clang/AST/DeclTemplate.h"
199f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "clang/AST/TypeLoc.h"
209f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "clang/AST/Expr.h"
219f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "clang/AST/ExprCXX.h"
229f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "clang/AST/ExternalASTSource.h"
239f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "clang/AST/RecordLayout.h"
249f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "clang/Basic/Builtins.h"
259f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "clang/Basic/SourceManager.h"
269f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "clang/Basic/TargetInfo.h"
279f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "llvm/ADT/SmallString.h"
289f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "llvm/ADT/StringExtras.h"
299f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "llvm/Support/MathExtras.h"
309f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "llvm/Support/raw_ostream.h"
319f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
329f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonusing namespace clang;
339f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
349f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonunsigned ASTContext::NumImplicitDefaultConstructors;
359f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonunsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
369f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonunsigned ASTContext::NumImplicitCopyConstructors;
379f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonunsigned ASTContext::NumImplicitCopyConstructorsDeclared;
389f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonunsigned ASTContext::NumImplicitCopyAssignmentOperators;
399f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonunsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
409f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonunsigned ASTContext::NumImplicitDestructors;
419f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonunsigned ASTContext::NumImplicitDestructorsDeclared;
429f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
439f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonenum FloatingRank {
449f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  FloatRank, DoubleRank, LongDoubleRank
459f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson};
469f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
479f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonvoid
489f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
499f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                               TemplateTemplateParmDecl *Parm) {
509f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ID.AddInteger(Parm->getDepth());
519f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ID.AddInteger(Parm->getPosition());
529f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // FIXME: Parameter pack
539f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
549f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  TemplateParameterList *Params = Parm->getTemplateParameters();
559f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ID.AddInteger(Params->size());
569f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  for (TemplateParameterList::const_iterator P = Params->begin(),
579f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                          PEnd = Params->end();
589f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson       P != PEnd; ++P) {
599f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
609f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      ID.AddInteger(0);
619f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      ID.AddBoolean(TTP->isParameterPack());
629f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      continue;
639f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    }
649f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
659f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
669f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      ID.AddInteger(1);
679f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      // FIXME: Parameter pack
689f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      ID.AddPointer(NTTP->getType().getAsOpaquePtr());
699f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      continue;
709f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    }
719f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
729f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
739f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    ID.AddInteger(2);
749f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Profile(ID, TTP);
759f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
769f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
779f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
789f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonTemplateTemplateParmDecl *
799f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonASTContext::getCanonicalTemplateTemplateParmDecl(
809f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                                 TemplateTemplateParmDecl *TTP) {
819f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Check if we already have a canonical template template parameter.
829f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  llvm::FoldingSetNodeID ID;
839f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  CanonicalTemplateTemplateParm::Profile(ID, TTP);
849f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  void *InsertPos = 0;
859f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  CanonicalTemplateTemplateParm *Canonical
869f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
879f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (Canonical)
889f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return Canonical->getParam();
899f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
909f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Build a canonical template parameter list.
919f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  TemplateParameterList *Params = TTP->getTemplateParameters();
929f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  llvm::SmallVector<NamedDecl *, 4> CanonParams;
939f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  CanonParams.reserve(Params->size());
949f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  for (TemplateParameterList::const_iterator P = Params->begin(),
959f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                          PEnd = Params->end();
969f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson       P != PEnd; ++P) {
979f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
989f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      CanonParams.push_back(
999f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                  TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
1009f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                               SourceLocation(), TTP->getDepth(),
1019f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                               TTP->getIndex(), 0, false,
1029f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                               TTP->isParameterPack()));
1039f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    else if (NonTypeTemplateParmDecl *NTTP
1049f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson             = dyn_cast<NonTypeTemplateParmDecl>(*P))
1059f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      CanonParams.push_back(
1069f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson            NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
1079f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                            SourceLocation(), NTTP->getDepth(),
1089f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                            NTTP->getPosition(), 0,
1099f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                            getCanonicalType(NTTP->getType()),
1109f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                            0));
1119f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    else
1129f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
1139f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                           cast<TemplateTemplateParmDecl>(*P)));
1149f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
1159f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
1169f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  TemplateTemplateParmDecl *CanonTTP
1179f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
1189f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                       SourceLocation(), TTP->getDepth(),
1199f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                       TTP->getPosition(), 0,
1209f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                         TemplateParameterList::Create(*this, SourceLocation(),
1219f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                                       SourceLocation(),
1229f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                                       CanonParams.data(),
1239f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                                       CanonParams.size(),
1249f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                                       SourceLocation()));
1259f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
1269f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Get the new insert position for the node we care about.
1279f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
1289f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert(Canonical == 0 && "Shouldn't be in the map!");
1299f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  (void)Canonical;
1309f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
1319f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Create the canonical template template parameter entry.
1329f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
1339f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
1349f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return CanonTTP;
1359f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
1369f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
1379f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
1389f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                       const TargetInfo &t,
1399f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                       IdentifierTable &idents, SelectorTable &sels,
1409f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                       Builtin::Context &builtins,
1419f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                       bool FreeMem, unsigned size_reserve) :
1429f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  TemplateSpecializationTypes(this_()),
1439f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  DependentTemplateSpecializationTypes(this_()),
1449f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  GlobalNestedNameSpecifier(0), IsInt128Installed(false),
1459f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
1469f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
1479f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
1489f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  NullTypeSourceInfo(QualType()),
1499f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  SourceMgr(SM), LangOpts(LOpts), FreeMemory(FreeMem), Target(t),
1509f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  Idents(idents), Selectors(sels),
1519f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  BuiltinInfo(builtins),
1529f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  DeclarationNames(*this),
1539f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ExternalSource(0), PrintingPolicy(LOpts),
1549f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  LastSDM(0, 0),
1559f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
1569f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ObjCIdRedefinitionType = QualType();
1579f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ObjCClassRedefinitionType = QualType();
1589f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ObjCSelRedefinitionType = QualType();
1599f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (size_reserve > 0) Types.reserve(size_reserve);
1609f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  TUDecl = TranslationUnitDecl::Create(*this);
1619f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinTypes();
1629f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
1639f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
1649f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonASTContext::~ASTContext() {
1659f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Release the DenseMaps associated with DeclContext objects.
1669f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // FIXME: Is this the ideal solution?
1679f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ReleaseDeclContextMaps();
1689f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
1699f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (!FreeMemory) {
1709f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // Call all of the deallocation functions.
1719f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
1729f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Deallocations[I].first(Deallocations[I].second);
1739f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
1749f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
1759f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Release all of the memory associated with overridden C++ methods.
1769f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
1779f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson         OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
1789f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson       OM != OMEnd; ++OM)
1799f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    OM->second.Destroy();
1809f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
1819f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (FreeMemory) {
1829f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // Deallocate all the types.
1839f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    while (!Types.empty()) {
1849f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Types.back()->Destroy(*this);
1859f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Types.pop_back();
1869f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    }
1879f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
1889f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    for (llvm::FoldingSet<ExtQuals>::iterator
1899f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson         I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) {
1909f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      // Increment in loop to prevent using deallocated memory.
1919f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Deallocate(&*I++);
1929f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    }
1939f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
1949f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    for (llvm::DenseMap<const ObjCContainerDecl*,
1959f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson         const ASTRecordLayout*>::iterator
1969f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson         I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
1979f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      // Increment in loop to prevent using deallocated memory.
1989f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
1999f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson        R->Destroy(*this);
2009f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    }
2019f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
2029f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2039f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
2049f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // even when using the BumpPtrAllocator because they can contain
2059f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // DenseMaps.
2069f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
2079f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson       I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
2089f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // Increment in loop to prevent using deallocated memory.
2099f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
2109f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      R->Destroy(*this);
2119f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
2129f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2139f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Destroy nested-name-specifiers.
2149f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  for (llvm::FoldingSet<NestedNameSpecifier>::iterator
2159f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson         NNS = NestedNameSpecifiers.begin(),
2169f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson         NNSEnd = NestedNameSpecifiers.end();
2179f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson       NNS != NNSEnd; ) {
2189f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // Increment in loop to prevent using deallocated memory.
2199f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    (*NNS++).Destroy(*this);
2209f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
2219f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2229f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (GlobalNestedNameSpecifier)
2239f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    GlobalNestedNameSpecifier->Destroy(*this);
2249f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2259f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  TUDecl->Destroy(*this);
2269f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
2279f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2289f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonvoid ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
2299f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  Deallocations.push_back(std::make_pair(Callback, Data));
2309f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
2319f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2329f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonvoid
2339f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
2349f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ExternalSource.reset(Source.take());
2359f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
2369f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2379f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonvoid ASTContext::PrintStats() const {
2389f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  fprintf(stderr, "*** AST Context Stats:\n");
2399f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  fprintf(stderr, "  %d types total.\n", (int)Types.size());
2409f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2419f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  unsigned counts[] = {
2429f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#define TYPE(Name, Parent) 0,
2439f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#define ABSTRACT_TYPE(Name, Parent)
2449f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "clang/AST/TypeNodes.def"
2459f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    0 // Extra
2469f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  };
2479f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2489f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  for (unsigned i = 0, e = Types.size(); i != e; ++i) {
2499f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Type *T = Types[i];
2509f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    counts[(unsigned)T->getTypeClass()]++;
2519f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
2529f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2539f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  unsigned Idx = 0;
2549f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  unsigned TotalBytes = 0;
2559f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#define TYPE(Name, Parent)                                              \
2569f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (counts[Idx])                                                      \
2579f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    fprintf(stderr, "    %d %s types\n", (int)counts[Idx], #Name);      \
2589f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
2599f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ++Idx;
2609f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#define ABSTRACT_TYPE(Name, Parent)
2619f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "clang/AST/TypeNodes.def"
2629f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2639f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
2649f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2659f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Implicit special member functions.
2669f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  fprintf(stderr, "  %u/%u implicit default constructors created\n",
2679f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson          NumImplicitDefaultConstructorsDeclared,
2689f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson          NumImplicitDefaultConstructors);
2699f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  fprintf(stderr, "  %u/%u implicit copy constructors created\n",
2709f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson          NumImplicitCopyConstructorsDeclared,
2719f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson          NumImplicitCopyConstructors);
2729f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  fprintf(stderr, "  %u/%u implicit copy assignment operators created\n",
2739f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson          NumImplicitCopyAssignmentOperatorsDeclared,
2749f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson          NumImplicitCopyAssignmentOperators);
2759f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  fprintf(stderr, "  %u/%u implicit destructors created\n",
2769f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson          NumImplicitDestructorsDeclared, NumImplicitDestructors);
2779f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2789f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (!FreeMemory)
2799f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    BumpAlloc.PrintStats();
2809f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2819f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (ExternalSource.get()) {
2829f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    fprintf(stderr, "\n");
2839f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    ExternalSource->PrintStats();
2849f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
2859f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2869f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (!FreeMemory)
2879f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    BumpAlloc.PrintStats();
2889f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
2899f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2909f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2919f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonvoid ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
2929f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
2939f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  R = CanQualType::CreateUnsafe(QualType(Ty, 0));
2949f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  Types.push_back(Ty);
2959f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
2969f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2979f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonvoid ASTContext::InitBuiltinTypes() {
2989f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert(VoidTy.isNull() && "Context reinitialized?");
2999f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3009f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // C99 6.2.5p19.
3019f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(VoidTy,              BuiltinType::Void);
3029f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3039f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // C99 6.2.5p2.
3049f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(BoolTy,              BuiltinType::Bool);
3059f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // C99 6.2.5p3.
3069f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (LangOpts.CharIsSigned)
3079f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    InitBuiltinType(CharTy,            BuiltinType::Char_S);
3089f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  else
3099f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    InitBuiltinType(CharTy,            BuiltinType::Char_U);
3109f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // C99 6.2.5p4.
3119f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
3129f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(ShortTy,             BuiltinType::Short);
3139f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(IntTy,               BuiltinType::Int);
3149f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(LongTy,              BuiltinType::Long);
3159f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
3169f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3179f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // C99 6.2.5p6.
3189f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
3199f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
3209f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
3219f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
3229f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
3239f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3249f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // C99 6.2.5p10.
3259f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(FloatTy,             BuiltinType::Float);
3269f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(DoubleTy,            BuiltinType::Double);
3279f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
3289f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3299f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // GNU extension, 128-bit integers.
3309f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(Int128Ty,            BuiltinType::Int128);
3319f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
3329f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3339f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (LangOpts.CPlusPlus) // C++ 3.9.1p5
3349f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    InitBuiltinType(WCharTy,           BuiltinType::WChar);
3359f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  else // C99
3369f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    WCharTy = getFromTargetType(Target.getWCharType());
3379f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3389f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
3399f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    InitBuiltinType(Char16Ty,           BuiltinType::Char16);
3409f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  else // C99
3419f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Char16Ty = getFromTargetType(Target.getChar16Type());
3429f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3439f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
3449f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    InitBuiltinType(Char32Ty,           BuiltinType::Char32);
3459f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  else // C99
3469f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Char32Ty = getFromTargetType(Target.getChar32Type());
3479f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3489f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Placeholder type for functions.
3499f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(OverloadTy,          BuiltinType::Overload);
3509f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3519f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Placeholder type for type-dependent expressions whose type is
3529f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // completely unknown. No code should ever check a type against
3539f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // DependentTy and users should never see it; however, it is here to
3549f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // help diagnose failures to properly check for type-dependent
3559f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // expressions.
3569f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(DependentTy,         BuiltinType::Dependent);
3579f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3589f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Placeholder type for C++0x auto declarations whose real type has
3599f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // not yet been deduced.
3609f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
3619f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3629f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // C99 6.2.5p11.
3639f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  FloatComplexTy      = getComplexType(FloatTy);
3649f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  DoubleComplexTy     = getComplexType(DoubleTy);
3659f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  LongDoubleComplexTy = getComplexType(LongDoubleTy);
3669f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3679f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  BuiltinVaListType = QualType();
3689f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3699f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
3709f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ObjCIdTypedefType = QualType();
3719f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ObjCClassTypedefType = QualType();
3729f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ObjCSelTypedefType = QualType();
3739f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3749f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Builtin types for 'id', 'Class', and 'SEL'.
3759f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
3769f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
3779f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
3789f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3799f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ObjCConstantStringType = QualType();
3809f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3819f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // void * type
3829f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  VoidPtrTy = getPointerType(VoidTy);
3839f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3849f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // nullptr type (C++0x 2.14.7)
3859f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
3869f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
3879f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3889f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonMemberSpecializationInfo *
3899f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
3909f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert(Var->isStaticDataMember() && "Not a static data member");
3919f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
3929f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    = InstantiatedFromStaticDataMember.find(Var);
3939f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (Pos == InstantiatedFromStaticDataMember.end())
3949f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return 0;
3959f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3969f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return Pos->second;
3979f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
3989f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3999f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonvoid
4009f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
4019f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                                TemplateSpecializationKind TSK,
4029f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                          SourceLocation PointOfInstantiation) {
4039f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert(Inst->isStaticDataMember() && "Not a static data member");
4049f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert(Tmpl->isStaticDataMember() && "Not a static data member");
4059f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert(!InstantiatedFromStaticDataMember[Inst] &&
4069f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson         "Already noted what static data member was instantiated from");
4079f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InstantiatedFromStaticDataMember[Inst]
4089f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
4099f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
4109f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
4119f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonNamedDecl *
4129f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
4139f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
4149f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    = InstantiatedFromUsingDecl.find(UUD);
4159f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (Pos == InstantiatedFromUsingDecl.end())
4169f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return 0;
4179f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
4189f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return Pos->second;
4199f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
4209f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
4219f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonvoid
4229f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
4239f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert((isa<UsingDecl>(Pattern) ||
4249f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson          isa<UnresolvedUsingValueDecl>(Pattern) ||
4259f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson          isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
4269f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson         "pattern decl is not a using decl");
4279f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
4289f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InstantiatedFromUsingDecl[Inst] = Pattern;
4299f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
4309f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
4319f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonUsingShadowDecl *
4329f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
4339f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
4349f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    = InstantiatedFromUsingShadowDecl.find(Inst);
4359f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (Pos == InstantiatedFromUsingShadowDecl.end())
4369f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return 0;
4379f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
4389f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return Pos->second;
4399f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
4409f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
4419f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonvoid
4429f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
4439f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                               UsingShadowDecl *Pattern) {
4449f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
4459f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InstantiatedFromUsingShadowDecl[Inst] = Pattern;
4469f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
4479f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
4489f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonFieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
4499f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
4509f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    = InstantiatedFromUnnamedFieldDecl.find(Field);
4519f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (Pos == InstantiatedFromUnnamedFieldDecl.end())
4529f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return 0;
4539f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
4549f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return Pos->second;
4559f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
4569f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
4579f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonvoid ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
4589f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                                     FieldDecl *Tmpl) {
4599f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
4609f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
4619f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
4629f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson         "Already noted what unnamed field was instantiated from");
4639f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
4649f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
4659f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
4669f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
4679f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonASTContext::overridden_cxx_method_iterator
4689f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
4699f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
4709f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    = OverriddenMethods.find(Method);
4719f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (Pos == OverriddenMethods.end())
4729f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return 0;
4739f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
4749f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return Pos->second.begin();
4759f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
4769f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
4779f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonASTContext::overridden_cxx_method_iterator
4789f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
4799f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
4809f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    = OverriddenMethods.find(Method);
4819f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (Pos == OverriddenMethods.end())
4829f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return 0;
4839f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
4849f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return Pos->second.end();
4859f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
4869f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
4879f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonunsigned
4889f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
4899f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
4909f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    = OverriddenMethods.find(Method);
4919f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (Pos == OverriddenMethods.end())
4929f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return 0;
4939f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
4949f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return Pos->second.size();
4959f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
4969f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
4979f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonvoid ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
4989f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                     const CXXMethodDecl *Overridden) {
4999f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  OverriddenMethods[Method].push_back(Overridden);
5009f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
5019f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
5029f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonnamespace {
5039f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  class BeforeInTranslationUnit
5049f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    : std::binary_function<SourceRange, SourceRange, bool> {
5059f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    SourceManager *SourceMgr;
5069f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
5079f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  public:
5089f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
5099f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
5109f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    bool operator()(SourceRange X, SourceRange Y) {
5119f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
5129f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    }
5139f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  };
5149f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
5159f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
5169f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson//===----------------------------------------------------------------------===//
5179f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson//                         Type Sizing and Analysis
5189f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson//===----------------------------------------------------------------------===//
5199f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
5209f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
5219f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// scalar floating point type.
5229f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonconst llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
5239f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  const BuiltinType *BT = T->getAs<BuiltinType>();
5249f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert(BT && "Not a floating point type!");
5259f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  switch (BT->getKind()) {
5269f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  default: assert(0 && "Not a floating point type!");
5279f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  case BuiltinType::Float:      return Target.getFloatFormat();
5289f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  case BuiltinType::Double:     return Target.getDoubleFormat();
5299f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
5309f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
5319f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
5329f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
5339f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// getDeclAlign - Return a conservative estimate of the alignment of the
5349f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// specified decl.  Note that bitfields do not have a valid alignment, so
5359f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// this method will assert on them.
5369f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// If @p RefAsPointee, references are treated like their underlying type
5379f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// (for alignof), else they're treated like pointers (for CodeGen).
5389f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonCharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
5399f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  unsigned Align = Target.getCharWidth();
5409f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
5419f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
5429f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Align = std::max(Align, AA->getMaxAlignment());
5439f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
5449f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
5459f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    QualType T = VD->getType();
5469f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
5479f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      if (RefAsPointee)
5489f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson        T = RT->getPointeeType();
5499f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      else
5509f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson        T = getPointerType(RT->getPointeeType());
5519f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    }
5529f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    if (!T->isIncompleteType() && !T->isFunctionType()) {
5539f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      unsigned MinWidth = Target.getLargeArrayMinWidth();
5549f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      unsigned ArrayAlign = Target.getLargeArrayAlign();
5559f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      if (isa<VariableArrayType>(T) && MinWidth != 0)
5569f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson        Align = std::max(Align, ArrayAlign);
5579f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
5589f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson        unsigned Size = getTypeSize(CT);
5599f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson        if (MinWidth != 0 && MinWidth <= Size)
5609f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson          Align = std::max(Align, ArrayAlign);
5619f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      }
5629f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      // Incomplete or function types default to 1.
5639f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
5649f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson        T = cast<ArrayType>(T)->getElementType();
5659f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
5669f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
5679f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    }
5689f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
5699f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      // In the case of a field in a packed struct, we want the minimum
5709f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      // of the alignment of the field and the alignment of the struct.
5719f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Align = std::min(Align,
5729f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson        getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
5739f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    }
5749f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
5759f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
5769f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return CharUnits::fromQuantity(Align / Target.getCharWidth());
5779f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
5789f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
5799f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonstd::pair<CharUnits, CharUnits>
5809f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonASTContext::getTypeInfoInChars(const Type *T) {
5819f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
5829f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
5839f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                        CharUnits::fromQuantity(Info.second / getCharWidth()));
5849f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
5859f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
5869f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonstd::pair<CharUnits, CharUnits>
5879f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonASTContext::getTypeInfoInChars(QualType T) {
5889f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return getTypeInfoInChars(T.getTypePtr());
5899f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
5909f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
5919f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// getTypeSize - Return the size of the specified type, in bits.  This method
5929f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// does not work on incomplete types.
5939f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson///
5949f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// FIXME: Pointers into different addr spaces could have different sizes and
5959f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// alignment requirements: getPointerInfo should take an AddrSpace, this
5969f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// should take a QualType, &c.
5979f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonstd::pair<uint64_t, unsigned>
5989f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonASTContext::getTypeInfo(const Type *T) {
5999f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  uint64_t Width=0;
6009f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  unsigned Align=8;
6019f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  switch (T->getTypeClass()) {
6029f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#define TYPE(Class, Base)
6039f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#define ABSTRACT_TYPE(Class, Base)
6049f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#define NON_CANONICAL_TYPE(Class, Base)
6059f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6069f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "clang/AST/TypeNodes.def"
6079f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    assert(false && "Should not see dependent types");
6089f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    break;
6099f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
6109f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  case Type::FunctionNoProto:
6119f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  case Type::FunctionProto:
6129f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // GCC extension: alignof(function) = 32 bits
6139f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Width = 0;
6149f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Align = 32;
6159f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    break;
6169f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
6179f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  case Type::IncompleteArray:
6189f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  case Type::VariableArray:
6199f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Width = 0;
6209f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
6219f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    break;
6229f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
6239f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  case Type::ConstantArray: {
6249f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
6259f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
6269f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
6279f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Width = EltInfo.first*CAT->getSize().getZExtValue();
6289f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Align = EltInfo.second;
6299f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    break;
6309f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
6319f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  case Type::ExtVector:
6329f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  case Type::Vector: {
6339f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    const VectorType *VT = cast<VectorType>(T);
6349f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
6359f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Width = EltInfo.first*VT->getNumElements();
6369f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Align = Width;
6379f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // If the alignment is not a power of 2, round up to the next power of 2.
6389f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // This happens for non-power-of-2 length vectors.
6399f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    if (Align & (Align-1)) {
6409f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Align = llvm::NextPowerOf2(Align);
6419f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Width = llvm::RoundUpToAlignment(Width, Align);
6429f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    }
6439f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    break;
6449f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
6459f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
6469f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  case Type::Builtin:
6479f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    switch (cast<BuiltinType>(T)->getKind()) {
6489f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    default: assert(0 && "Unknown builtin type!");
6499f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    case BuiltinType::Void:
6509f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      // GCC extension: alignof(void) = 8 bits.
6519f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Width = 0;
6529f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Align = 8;
6539f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      break;
6549f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
6559f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    case BuiltinType::Bool:
6569f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Width = Target.getBoolWidth();
6579f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Align = Target.getBoolAlign();
6589f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      break;
6599f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    case BuiltinType::Char_S:
6609f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    case BuiltinType::Char_U:
6619f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    case BuiltinType::UChar:
6629f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    case BuiltinType::SChar:
6639f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Width = Target.getCharWidth();
6649f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Align = Target.getCharAlign();
6659f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      break;
6669f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    case BuiltinType::WChar:
6679f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Width = Target.getWCharWidth();
6689f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Align = Target.getWCharAlign();
6699f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      break;
6709f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    case BuiltinType::Char16:
6719f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Width = Target.getChar16Width();
6729f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Align = Target.getChar16Align();
6739f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      break;
6749f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    case BuiltinType::Char32:
6759f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Width = Target.getChar32Width();
6769f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Align = Target.getChar32Align();
6779f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      break;
6789f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    case BuiltinType::UShort:
6799f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    case BuiltinType::Short:
6809f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Width = Target.getShortWidth();
6819f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Align = Target.getShortAlign();
6829f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      break;
6839f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    case BuiltinType::UInt:
6849f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    case BuiltinType::Int:
6859f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Width = Target.getIntWidth();
6869f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Align = Target.getIntAlign();
6879f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      break;
6889f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    case BuiltinType::ULong:
6899f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    case BuiltinType::Long:
6909f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Width = Target.getLongWidth();
6919f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Align = Target.getLongAlign();
6929f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      break;
6939f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    case BuiltinType::ULongLong:
6949f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    case BuiltinType::LongLong:
6959f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Width = Target.getLongLongWidth();
6969f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Align = Target.getLongLongAlign();
6979f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      break;
6989f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    case BuiltinType::Int128:
6999f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    case BuiltinType::UInt128:
7009f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Width = 128;
7019f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Align = 128; // int128_t is 128-bit aligned on all targets.
7029f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      break;
7039f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    case BuiltinType::Float:
7049f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Width = Target.getFloatWidth();
7059f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Align = Target.getFloatAlign();
7069f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      break;
7079f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    case BuiltinType::Double:
7089f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Width = Target.getDoubleWidth();
7099f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Align = Target.getDoubleAlign();
7109f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      break;
7119f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    case BuiltinType::LongDouble:
7129f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Width = Target.getLongDoubleWidth();
7139f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Align = Target.getLongDoubleAlign();
7149f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      break;
7159f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    case BuiltinType::NullPtr:
7169f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
7179f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Align = Target.getPointerAlign(0); //   == sizeof(void*)
7189f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      break;
7199f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    }
7209f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    break;
7219f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  case Type::ObjCObjectPointer:
7229f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Width = Target.getPointerWidth(0);
7239f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Align = Target.getPointerAlign(0);
7249f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    break;
7259f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  case Type::BlockPointer: {
7269f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
7279f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Width = Target.getPointerWidth(AS);
7289f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Align = Target.getPointerAlign(AS);
7299f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    break;
7309f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
7319f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  case Type::LValueReference:
7329f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  case Type::RValueReference: {
7339f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // alignof and sizeof should never enter this code path here, so we go
7349f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // the pointer route.
7359f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
7369f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Width = Target.getPointerWidth(AS);
7379f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Align = Target.getPointerAlign(AS);
7389f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    break;
7399f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
7409f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  case Type::Pointer: {
7419f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
7429f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Width = Target.getPointerWidth(AS);
7439f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Align = Target.getPointerAlign(AS);
7449f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    break;
7459f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
7469f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  case Type::MemberPointer: {
7479f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
7489f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    std::pair<uint64_t, unsigned> PtrDiffInfo =
7499f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      getTypeInfo(getPointerDiffType());
7509f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Width = PtrDiffInfo.first;
7519f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    if (Pointee->isFunctionType())
7529f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Width *= 2;
7539f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Align = PtrDiffInfo.second;
7549f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    break;
7559f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
7569f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  case Type::Complex: {
7579f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // Complex types have the same alignment as their elements, but twice the
7589f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // size.
7599f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    std::pair<uint64_t, unsigned> EltInfo =
7609f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      getTypeInfo(cast<ComplexType>(T)->getElementType());
7619f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Width = EltInfo.first*2;
7629f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Align = EltInfo.second;
7639f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    break;
7649f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
7659f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  case Type::ObjCObject:
7669f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
7679f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  case Type::ObjCInterface: {
7689f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
7699f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
7709f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Width = Layout.getSize();
7719f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Align = Layout.getAlignment();
7729f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    break;
7739f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
7749f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  case Type::Record:
7759f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  case Type::Enum: {
7769f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    const TagType *TT = cast<TagType>(T);
7779f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
7789f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    if (TT->getDecl()->isInvalidDecl()) {
7799f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Width = 1;
7809f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Align = 1;
7819f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      break;
7829f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    }
7839f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
7849f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    if (const EnumType *ET = dyn_cast<EnumType>(TT))
7859f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      return getTypeInfo(ET->getDecl()->getIntegerType());
7869f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
7879f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    const RecordType *RT = cast<RecordType>(TT);
7889f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
7899f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Width = Layout.getSize();
7909f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Align = Layout.getAlignment();
7919f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    break;
7929f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
7939f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
7949f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  case Type::SubstTemplateTypeParm:
7959f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
7969f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                       getReplacementType().getTypePtr());
7979f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
7989f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  case Type::Typedef: {
7999f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
8009f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
8019f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Align = std::max(Aligned->getMaxAlignment(),
8029f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                       getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
8039f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
8049f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    } else
8059f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
8069f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    break;
8079f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
8089f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
8099f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  case Type::TypeOfExpr:
8109f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
8119f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                         .getTypePtr());
8129f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
8139f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  case Type::TypeOf:
8149f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
8159f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
8169f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  case Type::Decltype:
8179f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
8189f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                        .getTypePtr());
8199f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
8209f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  case Type::Elaborated:
8219f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
8229f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
8239f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  case Type::TemplateSpecialization:
8249f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    assert(getCanonicalType(T) != T &&
8259f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson           "Cannot request the size of a dependent type");
8269f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // FIXME: this is likely to be wrong once we support template
8279f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // aliases, since a template alias could refer to a typedef that
8289f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // has an __aligned__ attribute on it.
8299f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return getTypeInfo(getCanonicalType(T));
8309f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
8319f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
8329f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
8339f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return std::make_pair(Width, Align);
8349f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
8359f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
8369f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// getTypeSizeInChars - Return the size of the specified type, in characters.
8379f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// This method does not work on incomplete types.
8389f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonCharUnits ASTContext::getTypeSizeInChars(QualType T) {
8399f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
8409f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
8419f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonCharUnits ASTContext::getTypeSizeInChars(const Type *T) {
8429f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
8439f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
8449f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
8459f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
8469f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// characters. This method does not work on incomplete types.
8479f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonCharUnits ASTContext::getTypeAlignInChars(QualType T) {
8489f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
8499f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
8509f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonCharUnits ASTContext::getTypeAlignInChars(const Type *T) {
8519f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
8529f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
8539f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
8549f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
8559f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// type for the current target in bits.  This can be different than the ABI
8569f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// alignment in cases where it is beneficial for performance to overalign
8579f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// a data type.
8589f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonunsigned ASTContext::getPreferredTypeAlign(const Type *T) {
8599f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  unsigned ABIAlign = getTypeAlign(T);
8609f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
8619f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Double and long long should be naturally aligned if possible.
8629f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (const ComplexType* CT = T->getAs<ComplexType>())
8639f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    T = CT->getElementType().getTypePtr();
8649f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (T->isSpecificBuiltinType(BuiltinType::Double) ||
8659f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      T->isSpecificBuiltinType(BuiltinType::LongLong))
8669f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return std::max(ABIAlign, (unsigned)getTypeSize(T));
8679f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
8689f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return ABIAlign;
8699f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
8709f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
8719f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonstatic void CollectLocalObjCIvars(ASTContext *Ctx,
8729f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                  const ObjCInterfaceDecl *OI,
8739f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                  llvm::SmallVectorImpl<FieldDecl*> &Fields) {
8749f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
8759f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson       E = OI->ivar_end(); I != E; ++I) {
8769f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    ObjCIvarDecl *IVDecl = *I;
8779f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    if (!IVDecl->isInvalidDecl())
8789f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Fields.push_back(cast<FieldDecl>(IVDecl));
8799f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
8809f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
8819f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
8829f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonvoid ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
8839f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                             llvm::SmallVectorImpl<FieldDecl*> &Fields) {
8849f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
8859f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    CollectObjCIvars(SuperClass, Fields);
8869f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  CollectLocalObjCIvars(this, OI, Fields);
8879f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
8889f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
8899f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// ShallowCollectObjCIvars -
8909f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// Collect all ivars, including those synthesized, in the current class.
8919f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson///
8929f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonvoid ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
8939f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
8949f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
8959f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson         E = OI->ivar_end(); I != E; ++I) {
8969f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson     Ivars.push_back(*I);
8979f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
8989f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
8999f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  CollectNonClassIvars(OI, Ivars);
9009f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
9019f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
9029f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// CollectNonClassIvars -
9039f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// This routine collects all other ivars which are not declared in the class.
9049f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// This includes synthesized ivars (via @synthesize) and those in
9059f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson//  class's @implementation.
9069f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson///
9079f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonvoid ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
9089f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
9099f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Find ivars declared in class extension.
9109f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
9119f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson       CDecl = CDecl->getNextClassExtension()) {
9129f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
9139f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson         E = CDecl->ivar_end(); I != E; ++I) {
9149f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Ivars.push_back(*I);
9159f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    }
9169f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
9179f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
9189f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Also add any ivar defined in this class's implementation.  This
9199f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // includes synthesized ivars.
9209f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
9219f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
9229f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson         E = ImplDecl->ivar_end(); I != E; ++I)
9239f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Ivars.push_back(*I);
9249f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
9259f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
9269f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
9279f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// CollectInheritedProtocols - Collect all protocols in current class and
9289f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// those inherited by it.
9299f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonvoid ASTContext::CollectInheritedProtocols(const Decl *CDecl,
9309f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                          llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
9319f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
9329f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
9339f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson         PE = OI->protocol_end(); P != PE; ++P) {
9349f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      ObjCProtocolDecl *Proto = (*P);
9359f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Protocols.insert(Proto);
9369f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
9379f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson           PE = Proto->protocol_end(); P != PE; ++P) {
9389f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson        Protocols.insert(*P);
9399f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson        CollectInheritedProtocols(*P, Protocols);
9409f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      }
9419f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    }
9429f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
9439f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // Categories of this Interface.
9449f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
9459f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson         CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
9469f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      CollectInheritedProtocols(CDeclChain, Protocols);
9479f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    if (ObjCInterfaceDecl *SD = OI->getSuperClass())
9489f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      while (SD) {
9499f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson        CollectInheritedProtocols(SD, Protocols);
9509f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson        SD = SD->getSuperClass();
9519f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      }
9529f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
9539f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
9549f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson         PE = OC->protocol_end(); P != PE; ++P) {
9559f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      ObjCProtocolDecl *Proto = (*P);
9569f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Protocols.insert(Proto);
9579f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
9589f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson           PE = Proto->protocol_end(); P != PE; ++P)
9599f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson        CollectInheritedProtocols(*P, Protocols);
9609f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    }
9619f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
9629f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
9639f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson         PE = OP->protocol_end(); P != PE; ++P) {
9649f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      ObjCProtocolDecl *Proto = (*P);
9659f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Protocols.insert(Proto);
9669f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
9679f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson           PE = Proto->protocol_end(); P != PE; ++P)
9689f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson        CollectInheritedProtocols(*P, Protocols);
9699f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    }
9709f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
9719f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
9729f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
9739f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonunsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
9749f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  unsigned count = 0;
9759f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Count ivars declared in class extension.
9769f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
9779f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson       CDecl = CDecl->getNextClassExtension())
9789f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    count += CDecl->ivar_size();
9799f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
9809f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Count ivar defined in this class's implementation.  This
9819f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // includes synthesized ivars.
9829f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
9839f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    count += ImplDecl->ivar_size();
9849f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
9859f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return count;
9869f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
9879f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
9889f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
9899f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
9909f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
9919f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    I = ObjCImpls.find(D);
9929f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (I != ObjCImpls.end())
9939f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return cast<ObjCImplementationDecl>(I->second);
9949f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return 0;
9959f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
9969f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
9979f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
9989f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
9999f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    I = ObjCImpls.find(D);
10009f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (I != ObjCImpls.end())
10019f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return cast<ObjCCategoryImplDecl>(I->second);
10029f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return 0;
10039f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
10049f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
10059f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// \brief Set the implementation of ObjCInterfaceDecl.
10069f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonvoid ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
10079f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                           ObjCImplementationDecl *ImplD) {
10089f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert(IFaceD && ImplD && "Passed null params");
10099f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ObjCImpls[IFaceD] = ImplD;
10109f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
10119f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// \brief Set the implementation of ObjCCategoryDecl.
10129f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonvoid ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
10139f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                           ObjCCategoryImplDecl *ImplD) {
10149f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert(CatD && ImplD && "Passed null params");
10159f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ObjCImpls[CatD] = ImplD;
10169f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
10179f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
10189f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// \brief Allocate an uninitialized TypeSourceInfo.
10199f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson///
10209f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// The caller should initialize the memory held by TypeSourceInfo using
10219f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// the TypeLoc wrappers.
10229f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson///
10239f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// \param T the type that will be the basis for type source info. This type
10249f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// should refer to how the declarator was written in source code, not to
10259f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// what type semantic analysis resolved the declarator to.
10269f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonTypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
10279f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                                 unsigned DataSize) {
10289f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (!DataSize)
10299f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    DataSize = TypeLoc::getFullDataSizeForType(T);
10309f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  else
10319f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
10329f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson           "incorrect data size provided to CreateTypeSourceInfo!");
10339f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
10349f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  TypeSourceInfo *TInfo =
10359f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
10369f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  new (TInfo) TypeSourceInfo(T);
10379f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return TInfo;
10389f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
10399f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
10409f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonTypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
10419f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                                     SourceLocation L) {
10429f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  TypeSourceInfo *DI = CreateTypeSourceInfo(T);
10439f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  DI->getTypeLoc().initialize(L);
10449f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return DI;
10459f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
10469f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
10479f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonconst ASTRecordLayout &
10489f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
10499f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return getObjCLayout(D, 0);
10509f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
10519f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
10529f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonconst ASTRecordLayout &
10539f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
10549f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return getObjCLayout(D->getClassInterface(), D);
10559f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
10569f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
10579f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson//===----------------------------------------------------------------------===//
10589f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson//                   Type creation/memoization methods
10599f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson//===----------------------------------------------------------------------===//
10609f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
10619f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonQualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
10629f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  unsigned Fast = Quals.getFastQualifiers();
10639f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  Quals.removeFastQualifiers();
10649f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
10659f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Check if we've already instantiated this type.
10669f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  llvm::FoldingSetNodeID ID;
10679f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ExtQuals::Profile(ID, TypeNode, Quals);
10689f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  void *InsertPos = 0;
10699f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
10709f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    assert(EQ->getQualifiers() == Quals);
10719f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    QualType T = QualType(EQ, Fast);
10729f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return T;
10739f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
10749f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
10759f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
10769f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ExtQualNodes.InsertNode(New, InsertPos);
10779f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  QualType T = QualType(New, Fast);
10789f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return T;
10799f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
10809f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
10819f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonQualType ASTContext::getVolatileType(QualType T) {
10829f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  QualType CanT = getCanonicalType(T);
10839f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (CanT.isVolatileQualified()) return T;
10849f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
10859f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  QualifierCollector Quals;
10869f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  const Type *TypeNode = Quals.strip(T);
10879f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  Quals.addVolatile();
10889f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
10899f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return getExtQualType(TypeNode, Quals);
10909f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
10919f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
10929f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonQualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
10939f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  QualType CanT = getCanonicalType(T);
10949f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (CanT.getAddressSpace() == AddressSpace)
10959f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return T;
10969f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
10979f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // If we are composing extended qualifiers together, merge together
10989f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // into one ExtQuals node.
10999f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  QualifierCollector Quals;
11009f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  const Type *TypeNode = Quals.strip(T);
11019f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
11029f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // If this type already has an address space specified, it cannot get
11039f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // another one.
11049f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert(!Quals.hasAddressSpace() &&
11059f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson         "Type cannot be in multiple addr spaces!");
11069f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  Quals.addAddressSpace(AddressSpace);
11079f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
11089f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return getExtQualType(TypeNode, Quals);
11099f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
11109f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
11119f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonQualType ASTContext::getObjCGCQualType(QualType T,
11129f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                       Qualifiers::GC GCAttr) {
11139f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  QualType CanT = getCanonicalType(T);
11149f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (CanT.getObjCGCAttr() == GCAttr)
11159f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return T;
11169f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
11179f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (T->isPointerType()) {
11189f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    QualType Pointee = T->getAs<PointerType>()->getPointeeType();
11199f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    if (Pointee->isAnyPointerType()) {
11209f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
11219f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      return getPointerType(ResultType);
11229f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    }
11239f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
11249f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
11259f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // If we are composing extended qualifiers together, merge together
11269f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // into one ExtQuals node.
11279f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  QualifierCollector Quals;
11289f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  const Type *TypeNode = Quals.strip(T);
11299f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
11309f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // If this type already has an ObjCGC specified, it cannot get
11319f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // another one.
11329f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert(!Quals.hasObjCGCAttr() &&
11339f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson         "Type cannot have multiple ObjCGCs!");
11349f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  Quals.addObjCGCAttr(GCAttr);
11359f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
11369f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return getExtQualType(TypeNode, Quals);
11379f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
11389f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
11399f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonstatic QualType getExtFunctionType(ASTContext& Context, QualType T,
11409f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                        const FunctionType::ExtInfo &Info) {
11419f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  QualType ResultType;
11429f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (const PointerType *Pointer = T->getAs<PointerType>()) {
11439f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    QualType Pointee = Pointer->getPointeeType();
11449f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    ResultType = getExtFunctionType(Context, Pointee, Info);
11459f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    if (ResultType == Pointee)
11469f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      return T;
11479f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
11489f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    ResultType = Context.getPointerType(ResultType);
11499f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  } else if (const BlockPointerType *BlockPointer
11509f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                              = T->getAs<BlockPointerType>()) {
11519f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    QualType Pointee = BlockPointer->getPointeeType();
11529f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    ResultType = getExtFunctionType(Context, Pointee, Info);
11539f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    if (ResultType == Pointee)
11549f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      return T;
11559f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
11569f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    ResultType = Context.getBlockPointerType(ResultType);
11579f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson   } else if (const FunctionType *F = T->getAs<FunctionType>()) {
11589f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    if (F->getExtInfo() == Info)
11599f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      return T;
11609f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
11619f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
11629f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
11639f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                                  Info);
11649f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    } else {
11659f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
11669f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      ResultType
11679f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson        = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
11689f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                  FPT->getNumArgs(), FPT->isVariadic(),
11699f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                  FPT->getTypeQuals(),
11709f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                  FPT->hasExceptionSpec(),
11719f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                  FPT->hasAnyExceptionSpec(),
11729f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                  FPT->getNumExceptions(),
11739f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                  FPT->exception_begin(),
11749f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                  Info);
11759f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    }
11769f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  } else
11779f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return T;
11789f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
11799f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
11809f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
11819f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
11829f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonQualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
11839f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  FunctionType::ExtInfo Info = getFunctionExtInfo(T);
11849f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return getExtFunctionType(*this, T,
11859f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                 Info.withNoReturn(AddNoReturn));
11869f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
11879f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
11889f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonQualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
11899f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  FunctionType::ExtInfo Info = getFunctionExtInfo(T);
11909f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return getExtFunctionType(*this, T,
11919f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                            Info.withCallingConv(CallConv));
11929f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
11939f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
11949f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonQualType ASTContext::getRegParmType(QualType T, unsigned RegParm) {
11959f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  FunctionType::ExtInfo Info = getFunctionExtInfo(T);
11969f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return getExtFunctionType(*this, T,
11979f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                 Info.withRegParm(RegParm));
11989f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
11999f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
12009f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// getComplexType - Return the uniqued reference to the type for a complex
12019f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// number with the specified element type.
12029f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonQualType ASTContext::getComplexType(QualType T) {
12039f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Unique pointers, to guarantee there is only one pointer of a particular
12049f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // structure.
12059f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  llvm::FoldingSetNodeID ID;
12069f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ComplexType::Profile(ID, T);
12079f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
12089f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  void *InsertPos = 0;
12099f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
12109f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return QualType(CT, 0);
12119f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
12129f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // If the pointee type isn't canonical, this won't be a canonical type either,
12139f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // so fill in the canonical type field.
12149f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  QualType Canonical;
12159f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (!T.isCanonical()) {
12169f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Canonical = getComplexType(getCanonicalType(T));
12179f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
12189f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // Get the new insert position for the node we care about.
12199f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
12209f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
12219f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
12229f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
12239f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  Types.push_back(New);
12249f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ComplexTypes.InsertNode(New, InsertPos);
12259f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return QualType(New, 0);
12269f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
12279f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
12289f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// getPointerType - Return the uniqued reference to the type for a pointer to
12299f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// the specified type.
12309f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonQualType ASTContext::getPointerType(QualType T) {
12319f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Unique pointers, to guarantee there is only one pointer of a particular
12329f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // structure.
12339f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  llvm::FoldingSetNodeID ID;
12349f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  PointerType::Profile(ID, T);
12359f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
12369f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  void *InsertPos = 0;
12379f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
12389f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return QualType(PT, 0);
12399f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
12409f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // If the pointee type isn't canonical, this won't be a canonical type either,
12419f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // so fill in the canonical type field.
12429f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  QualType Canonical;
12439f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (!T.isCanonical()) {
12449f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Canonical = getPointerType(getCanonicalType(T));
12459f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
12469f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // Get the new insert position for the node we care about.
12479f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
12489f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
12499f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
12509f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
12519f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  Types.push_back(New);
12529f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  PointerTypes.InsertNode(New, InsertPos);
12539f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return QualType(New, 0);
12549f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
12559f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
12569f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// getBlockPointerType - Return the uniqued reference to the type for
12579f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// a pointer to the specified block.
12589f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonQualType ASTContext::getBlockPointerType(QualType T) {
12599f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert(T->isFunctionType() && "block of function types only");
12609f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Unique pointers, to guarantee there is only one block of a particular
12619f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // structure.
12629f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  llvm::FoldingSetNodeID ID;
12639f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  BlockPointerType::Profile(ID, T);
12649f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
12659f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  void *InsertPos = 0;
12669f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (BlockPointerType *PT =
12679f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson        BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
12689f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return QualType(PT, 0);
12699f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
12709f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // If the block pointee type isn't canonical, this won't be a canonical
12719f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // type either so fill in the canonical type field.
12729f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  QualType Canonical;
12739f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (!T.isCanonical()) {
12749f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Canonical = getBlockPointerType(getCanonicalType(T));
12759f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
12769f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // Get the new insert position for the node we care about.
12779f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    BlockPointerType *NewIP =
12789f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
12799f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
12809f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
12819f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  BlockPointerType *New
12829f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
12839f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  Types.push_back(New);
12849f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  BlockPointerTypes.InsertNode(New, InsertPos);
12859f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return QualType(New, 0);
12869f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
12879f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
12889f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// getLValueReferenceType - Return the uniqued reference to the type for an
12899f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// lvalue reference to the specified type.
12909f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonQualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
12919f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Unique pointers, to guarantee there is only one pointer of a particular
12929f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // structure.
12939f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  llvm::FoldingSetNodeID ID;
12949f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ReferenceType::Profile(ID, T, SpelledAsLValue);
12959f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
12969f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  void *InsertPos = 0;
12979f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (LValueReferenceType *RT =
12989f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson        LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
12999f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return QualType(RT, 0);
13009f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
13019f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  const ReferenceType *InnerRef = T->getAs<ReferenceType>();
13029f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
13039f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // If the referencee type isn't canonical, this won't be a canonical type
13049f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // either, so fill in the canonical type field.
13059f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  QualType Canonical;
13069f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
13079f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
13089f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
13099f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
13109f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // Get the new insert position for the node we care about.
13119f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    LValueReferenceType *NewIP =
13129f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
13139f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
13149f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
13159f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
13169f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  LValueReferenceType *New
13179f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
13189f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                                     SpelledAsLValue);
13199f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  Types.push_back(New);
13209f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  LValueReferenceTypes.InsertNode(New, InsertPos);
13219f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
13229f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return QualType(New, 0);
13239f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
13249f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
13259f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// getRValueReferenceType - Return the uniqued reference to the type for an
13269f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// rvalue reference to the specified type.
13279f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonQualType ASTContext::getRValueReferenceType(QualType T) {
13289f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Unique pointers, to guarantee there is only one pointer of a particular
13299f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // structure.
13309f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  llvm::FoldingSetNodeID ID;
13319f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ReferenceType::Profile(ID, T, false);
13329f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
13339f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  void *InsertPos = 0;
13349f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (RValueReferenceType *RT =
13359f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson        RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
13369f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return QualType(RT, 0);
13379f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
13389f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  const ReferenceType *InnerRef = T->getAs<ReferenceType>();
13399f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
13409f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // If the referencee type isn't canonical, this won't be a canonical type
13419f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // either, so fill in the canonical type field.
13429f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  QualType Canonical;
13439f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (InnerRef || !T.isCanonical()) {
13449f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
13459f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
13469f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
13479f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // Get the new insert position for the node we care about.
13489f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    RValueReferenceType *NewIP =
13499f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
13509f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
13519f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
13529f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
13539f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  RValueReferenceType *New
13549f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
13559f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  Types.push_back(New);
13569f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  RValueReferenceTypes.InsertNode(New, InsertPos);
13579f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return QualType(New, 0);
13589f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
13599f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
13609f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// getMemberPointerType - Return the uniqued reference to the type for a
13619f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// member pointer to the specified type, in the specified class.
13629f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonQualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
13639f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Unique pointers, to guarantee there is only one pointer of a particular
13649f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // structure.
13659f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  llvm::FoldingSetNodeID ID;
13669f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  MemberPointerType::Profile(ID, T, Cls);
13679f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
13689f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  void *InsertPos = 0;
13699f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (MemberPointerType *PT =
13709f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
13719f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return QualType(PT, 0);
13729f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
13739f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // If the pointee or class type isn't canonical, this won't be a canonical
13749f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // type either, so fill in the canonical type field.
13759f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  QualType Canonical;
13769f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
13779f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
13789f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
13799f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // Get the new insert position for the node we care about.
13809f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    MemberPointerType *NewIP =
13819f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
13829f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
13839f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
13849f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  MemberPointerType *New
13859f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
13869f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  Types.push_back(New);
13879f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  MemberPointerTypes.InsertNode(New, InsertPos);
13889f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return QualType(New, 0);
13899f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
13909f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
13919f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// getConstantArrayType - Return the unique reference to the type for an
13929f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// array of the specified element type.
13939f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonQualType ASTContext::getConstantArrayType(QualType EltTy,
13949f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                          const llvm::APInt &ArySizeIn,
13959f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                          ArrayType::ArraySizeModifier ASM,
13969f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                          unsigned EltTypeQuals) {
13979f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert((EltTy->isDependentType() ||
13989f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson          EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
13999f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson         "Constant array of VLAs is illegal!");
14009f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
14019f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Convert the array size into a canonical width matching the pointer size for
14029f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // the target.
14039f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  llvm::APInt ArySize(ArySizeIn);
14049f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
14059f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
14069f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  llvm::FoldingSetNodeID ID;
14079f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
14089f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
14099f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  void *InsertPos = 0;
14109f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (ConstantArrayType *ATP =
14119f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
14129f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return QualType(ATP, 0);
14139f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
14149f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // If the element type isn't canonical, this won't be a canonical type either,
14159f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // so fill in the canonical type field.
14169f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  QualType Canonical;
14179f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (!EltTy.isCanonical()) {
14189f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
14199f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                     ASM, EltTypeQuals);
14209f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // Get the new insert position for the node we care about.
14219f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    ConstantArrayType *NewIP =
14229f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
14239f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
14249f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
14259f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
14269f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ConstantArrayType *New = new(*this,TypeAlignment)
14279f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
14289f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ConstantArrayTypes.InsertNode(New, InsertPos);
14299f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  Types.push_back(New);
14309f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return QualType(New, 0);
14319f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
14329f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
14339f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// getVariableArrayType - Returns a non-unique reference to the type for a
14349f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// variable array of the specified element type.
14359f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonQualType ASTContext::getVariableArrayType(QualType EltTy,
14369f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                          Expr *NumElts,
14379f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                          ArrayType::ArraySizeModifier ASM,
14389f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                          unsigned EltTypeQuals,
14399f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                          SourceRange Brackets) {
14409f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Since we don't unique expressions, it isn't possible to unique VLA's
14419f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // that have an expression provided for their size.
14429f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  QualType CanonType;
14439f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
14449f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (!EltTy.isCanonical()) {
14459f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    if (NumElts)
14469f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      NumElts->Retain();
14479f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
14489f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                     EltTypeQuals, Brackets);
14499f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
14509f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
14519f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  VariableArrayType *New = new(*this, TypeAlignment)
14529f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
14539f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
14549f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  VariableArrayTypes.push_back(New);
14559f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  Types.push_back(New);
14569f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return QualType(New, 0);
14579f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
14589f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
14599f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// getDependentSizedArrayType - Returns a non-unique reference to
14609f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// the type for a dependently-sized array of the specified element
14619f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// type.
14629f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonQualType ASTContext::getDependentSizedArrayType(QualType EltTy,
14639f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                                Expr *NumElts,
14649f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                                ArrayType::ArraySizeModifier ASM,
14659f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                                unsigned EltTypeQuals,
14669f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                                SourceRange Brackets) {
14679f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert((!NumElts || NumElts->isTypeDependent() ||
14689f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson          NumElts->isValueDependent()) &&
14699f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson         "Size must be type- or value-dependent!");
14709f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
14719f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  void *InsertPos = 0;
14729f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  DependentSizedArrayType *Canon = 0;
14739f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  llvm::FoldingSetNodeID ID;
14749f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
14759f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (NumElts) {
14769f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // Dependently-sized array types that do not have a specified
14779f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // number of elements will have their sizes deduced from an
14789f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // initializer.
14799f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
14809f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                     EltTypeQuals, NumElts);
14819f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
14829f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
14839f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
14849f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
14859f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  DependentSizedArrayType *New;
14869f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (Canon) {
14879f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // We already have a canonical version of this array type; use it as
14889f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // the canonical type for a newly-built type.
14899f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    New = new (*this, TypeAlignment)
14909f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
14919f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                              NumElts, ASM, EltTypeQuals, Brackets);
14929f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  } else {
14939f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    QualType CanonEltTy = getCanonicalType(EltTy);
14949f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    if (CanonEltTy == EltTy) {
14959f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      New = new (*this, TypeAlignment)
14969f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson        DependentSizedArrayType(*this, EltTy, QualType(),
14979f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                NumElts, ASM, EltTypeQuals, Brackets);
14989f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
14999f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      if (NumElts) {
15009f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson        DependentSizedArrayType *CanonCheck
15019f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson          = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
15029f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson        assert(!CanonCheck && "Dependent-sized canonical array type broken");
15039f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson        (void)CanonCheck;
15049f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson        DependentSizedArrayTypes.InsertNode(New, InsertPos);
15059f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      }
15069f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    } else {
15079f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
15089f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                                  ASM, EltTypeQuals,
15099f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                                  SourceRange());
15109f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      New = new (*this, TypeAlignment)
15119f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson        DependentSizedArrayType(*this, EltTy, Canon,
15129f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                NumElts, ASM, EltTypeQuals, Brackets);
15139f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    }
15149f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
15159f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
15169f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  Types.push_back(New);
15179f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return QualType(New, 0);
15189f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
15199f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
15209f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonQualType ASTContext::getIncompleteArrayType(QualType EltTy,
15219f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                            ArrayType::ArraySizeModifier ASM,
15229f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                            unsigned EltTypeQuals) {
15239f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  llvm::FoldingSetNodeID ID;
15249f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
15259f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
15269f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  void *InsertPos = 0;
15279f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (IncompleteArrayType *ATP =
15289f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson       IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
15299f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return QualType(ATP, 0);
15309f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
15319f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // If the element type isn't canonical, this won't be a canonical type
15329f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // either, so fill in the canonical type field.
15339f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  QualType Canonical;
15349f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
15359f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (!EltTy.isCanonical()) {
15369f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
15379f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                       ASM, EltTypeQuals);
15389f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
15399f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // Get the new insert position for the node we care about.
15409f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    IncompleteArrayType *NewIP =
15419f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
15429f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
15439f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
15449f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
15459f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  IncompleteArrayType *New = new (*this, TypeAlignment)
15469f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
15479f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
15489f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  IncompleteArrayTypes.InsertNode(New, InsertPos);
15499f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  Types.push_back(New);
15509f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return QualType(New, 0);
15519f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
15529f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
15539f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// getVectorType - Return the unique reference to a vector type of
15549f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// the specified element type and size. VectorType must be a built-in type.
15559f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonQualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
15569f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    VectorType::AltiVecSpecific AltiVecSpec) {
15579f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  BuiltinType *baseType;
15589f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
15599f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
15609f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
15619f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
15629f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Check if we've already instantiated a vector of this type.
15639f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  llvm::FoldingSetNodeID ID;
15649f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  VectorType::Profile(ID, vecType, NumElts, Type::Vector, AltiVecSpec);
15659f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
15669f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  void *InsertPos = 0;
15679f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
15689f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return QualType(VTP, 0);
15699f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
15709f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // If the element type isn't canonical, this won't be a canonical type either,
15719f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // so fill in the canonical type field.
15729f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  QualType Canonical;
15739f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (!vecType.isCanonical() || (AltiVecSpec == VectorType::AltiVec)) {
15749f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // pass VectorType::NotAltiVec for AltiVecSpec to make AltiVec canonical
15759f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // vector type (except 'vector bool ...' and 'vector Pixel') the same as
15769f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // the equivalent GCC vector types
15779f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Canonical = getVectorType(getCanonicalType(vecType), NumElts,
15789f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      VectorType::NotAltiVec);
15799f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
15809f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // Get the new insert position for the node we care about.
15819f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
15829f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
15839f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
15849f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  VectorType *New = new (*this, TypeAlignment)
15859f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    VectorType(vecType, NumElts, Canonical, AltiVecSpec);
15869f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  VectorTypes.InsertNode(New, InsertPos);
15879f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  Types.push_back(New);
15889f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return QualType(New, 0);
15899f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
15909f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
15919f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// getExtVectorType - Return the unique reference to an extended vector type of
15929f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// the specified element type and size. VectorType must be a built-in type.
15939f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonQualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
15949f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  BuiltinType *baseType;
15959f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
15969f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
15979f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
15989f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
15999f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Check if we've already instantiated a vector of this type.
16009f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  llvm::FoldingSetNodeID ID;
16019f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
16029f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                      VectorType::NotAltiVec);
16039f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  void *InsertPos = 0;
16049f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
16059f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return QualType(VTP, 0);
16069f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
16079f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // If the element type isn't canonical, this won't be a canonical type either,
16089f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // so fill in the canonical type field.
16099f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  QualType Canonical;
16109f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (!vecType.isCanonical()) {
16119f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
16129f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
16139f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // Get the new insert position for the node we care about.
16149f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
16159f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
16169f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
16179f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ExtVectorType *New = new (*this, TypeAlignment)
16189f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    ExtVectorType(vecType, NumElts, Canonical);
16199f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  VectorTypes.InsertNode(New, InsertPos);
16209f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  Types.push_back(New);
16219f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return QualType(New, 0);
16229f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
16239f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
16249f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonQualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
16259f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                                    Expr *SizeExpr,
16269f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                                    SourceLocation AttrLoc) {
16279f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  llvm::FoldingSetNodeID ID;
16289f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
16299f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                       SizeExpr);
16309f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
16319f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  void *InsertPos = 0;
16329f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  DependentSizedExtVectorType *Canon
16339f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
16349f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  DependentSizedExtVectorType *New;
16359f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (Canon) {
16369f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // We already have a canonical version of this array type; use it as
16379f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    // the canonical type for a newly-built type.
16389f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    New = new (*this, TypeAlignment)
16399f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
16409f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                  SizeExpr, AttrLoc);
16419f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  } else {
16429f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    QualType CanonVecTy = getCanonicalType(vecType);
16439f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    if (CanonVecTy == vecType) {
16449f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      New = new (*this, TypeAlignment)
16459f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson        DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
16469f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                    AttrLoc);
16479f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
16489f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      DependentSizedExtVectorType *CanonCheck
16499f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson        = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
16509f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
16519f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      (void)CanonCheck;
16529f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
16539f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    } else {
16549f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
16559f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                                      SourceLocation());
16569f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      New = new (*this, TypeAlignment)
16579f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson        DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
16589f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    }
16599f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
16609f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
16619f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  Types.push_back(New);
16629f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return QualType(New, 0);
16639f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
16649f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
16659f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
16669f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson///
16679f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonQualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
16689f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                            const FunctionType::ExtInfo &Info) {
16699f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  const CallingConv CallConv = Info.getCC();
16709f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Unique functions, to guarantee there is only one function of a particular
16719f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // structure.
16729f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  llvm::FoldingSetNodeID ID;
16739f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  FunctionNoProtoType::Profile(ID, ResultTy, Info);
1674
1675  void *InsertPos = 0;
1676  if (FunctionNoProtoType *FT =
1677        FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1678    return QualType(FT, 0);
1679
1680  QualType Canonical;
1681  if (!ResultTy.isCanonical() ||
1682      getCanonicalCallConv(CallConv) != CallConv) {
1683    Canonical =
1684      getFunctionNoProtoType(getCanonicalType(ResultTy),
1685                     Info.withCallingConv(getCanonicalCallConv(CallConv)));
1686
1687    // Get the new insert position for the node we care about.
1688    FunctionNoProtoType *NewIP =
1689      FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1690    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1691  }
1692
1693  FunctionNoProtoType *New = new (*this, TypeAlignment)
1694    FunctionNoProtoType(ResultTy, Canonical, Info);
1695  Types.push_back(New);
1696  FunctionNoProtoTypes.InsertNode(New, InsertPos);
1697  return QualType(New, 0);
1698}
1699
1700/// getFunctionType - Return a normal function type with a typed argument
1701/// list.  isVariadic indicates whether the argument list includes '...'.
1702QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
1703                                     unsigned NumArgs, bool isVariadic,
1704                                     unsigned TypeQuals, bool hasExceptionSpec,
1705                                     bool hasAnyExceptionSpec, unsigned NumExs,
1706                                     const QualType *ExArray,
1707                                     const FunctionType::ExtInfo &Info) {
1708  const CallingConv CallConv= Info.getCC();
1709  // Unique functions, to guarantee there is only one function of a particular
1710  // structure.
1711  llvm::FoldingSetNodeID ID;
1712  FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
1713                             TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1714                             NumExs, ExArray, Info);
1715
1716  void *InsertPos = 0;
1717  if (FunctionProtoType *FTP =
1718        FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1719    return QualType(FTP, 0);
1720
1721  // Determine whether the type being created is already canonical or not.
1722  bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
1723  for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1724    if (!ArgArray[i].isCanonicalAsParam())
1725      isCanonical = false;
1726
1727  // If this type isn't canonical, get the canonical version of it.
1728  // The exception spec is not part of the canonical type.
1729  QualType Canonical;
1730  if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
1731    llvm::SmallVector<QualType, 16> CanonicalArgs;
1732    CanonicalArgs.reserve(NumArgs);
1733    for (unsigned i = 0; i != NumArgs; ++i)
1734      CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
1735
1736    Canonical = getFunctionType(getCanonicalType(ResultTy),
1737                                CanonicalArgs.data(), NumArgs,
1738                                isVariadic, TypeQuals, false,
1739                                false, 0, 0,
1740                     Info.withCallingConv(getCanonicalCallConv(CallConv)));
1741
1742    // Get the new insert position for the node we care about.
1743    FunctionProtoType *NewIP =
1744      FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1745    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1746  }
1747
1748  // FunctionProtoType objects are allocated with extra bytes after them
1749  // for two variable size arrays (for parameter and exception types) at the
1750  // end of them.
1751  FunctionProtoType *FTP =
1752    (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1753                                 NumArgs*sizeof(QualType) +
1754                                 NumExs*sizeof(QualType), TypeAlignment);
1755  new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
1756                              TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1757                              ExArray, NumExs, Canonical, Info);
1758  Types.push_back(FTP);
1759  FunctionProtoTypes.InsertNode(FTP, InsertPos);
1760  return QualType(FTP, 0);
1761}
1762
1763#ifndef NDEBUG
1764static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1765  if (!isa<CXXRecordDecl>(D)) return false;
1766  const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1767  if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1768    return true;
1769  if (RD->getDescribedClassTemplate() &&
1770      !isa<ClassTemplateSpecializationDecl>(RD))
1771    return true;
1772  return false;
1773}
1774#endif
1775
1776/// getInjectedClassNameType - Return the unique reference to the
1777/// injected class name type for the specified templated declaration.
1778QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1779                                              QualType TST) {
1780  assert(NeedsInjectedClassNameType(Decl));
1781  if (Decl->TypeForDecl) {
1782    assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1783  } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
1784    assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1785    Decl->TypeForDecl = PrevDecl->TypeForDecl;
1786    assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1787  } else {
1788    Decl->TypeForDecl =
1789      new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
1790    Types.push_back(Decl->TypeForDecl);
1791  }
1792  return QualType(Decl->TypeForDecl, 0);
1793}
1794
1795/// getTypeDeclType - Return the unique reference to the type for the
1796/// specified type declaration.
1797QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
1798  assert(Decl && "Passed null for Decl param");
1799  assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
1800
1801  if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
1802    return getTypedefType(Typedef);
1803
1804  assert(!isa<TemplateTypeParmDecl>(Decl) &&
1805         "Template type parameter types are always available.");
1806
1807  if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
1808    assert(!Record->getPreviousDeclaration() &&
1809           "struct/union has previous declaration");
1810    assert(!NeedsInjectedClassNameType(Record));
1811    return getRecordType(Record);
1812  } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1813    assert(!Enum->getPreviousDeclaration() &&
1814           "enum has previous declaration");
1815    return getEnumType(Enum);
1816  } else if (const UnresolvedUsingTypenameDecl *Using =
1817               dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1818    Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
1819  } else
1820    llvm_unreachable("TypeDecl without a type?");
1821
1822  Types.push_back(Decl->TypeForDecl);
1823  return QualType(Decl->TypeForDecl, 0);
1824}
1825
1826/// getTypedefType - Return the unique reference to the type for the
1827/// specified typename decl.
1828QualType
1829ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) {
1830  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1831
1832  if (Canonical.isNull())
1833    Canonical = getCanonicalType(Decl->getUnderlyingType());
1834  Decl->TypeForDecl = new(*this, TypeAlignment)
1835    TypedefType(Type::Typedef, Decl, Canonical);
1836  Types.push_back(Decl->TypeForDecl);
1837  return QualType(Decl->TypeForDecl, 0);
1838}
1839
1840QualType ASTContext::getRecordType(const RecordDecl *Decl) {
1841  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1842
1843  if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
1844    if (PrevDecl->TypeForDecl)
1845      return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1846
1847  Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Decl);
1848  Types.push_back(Decl->TypeForDecl);
1849  return QualType(Decl->TypeForDecl, 0);
1850}
1851
1852QualType ASTContext::getEnumType(const EnumDecl *Decl) {
1853  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1854
1855  if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
1856    if (PrevDecl->TypeForDecl)
1857      return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1858
1859  Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Decl);
1860  Types.push_back(Decl->TypeForDecl);
1861  return QualType(Decl->TypeForDecl, 0);
1862}
1863
1864/// \brief Retrieve a substitution-result type.
1865QualType
1866ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1867                                         QualType Replacement) {
1868  assert(Replacement.isCanonical()
1869         && "replacement types must always be canonical");
1870
1871  llvm::FoldingSetNodeID ID;
1872  SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1873  void *InsertPos = 0;
1874  SubstTemplateTypeParmType *SubstParm
1875    = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1876
1877  if (!SubstParm) {
1878    SubstParm = new (*this, TypeAlignment)
1879      SubstTemplateTypeParmType(Parm, Replacement);
1880    Types.push_back(SubstParm);
1881    SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1882  }
1883
1884  return QualType(SubstParm, 0);
1885}
1886
1887/// \brief Retrieve the template type parameter type for a template
1888/// parameter or parameter pack with the given depth, index, and (optionally)
1889/// name.
1890QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
1891                                             bool ParameterPack,
1892                                             IdentifierInfo *Name) {
1893  llvm::FoldingSetNodeID ID;
1894  TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
1895  void *InsertPos = 0;
1896  TemplateTypeParmType *TypeParm
1897    = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1898
1899  if (TypeParm)
1900    return QualType(TypeParm, 0);
1901
1902  if (Name) {
1903    QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1904    TypeParm = new (*this, TypeAlignment)
1905      TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
1906
1907    TemplateTypeParmType *TypeCheck
1908      = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1909    assert(!TypeCheck && "Template type parameter canonical type broken");
1910    (void)TypeCheck;
1911  } else
1912    TypeParm = new (*this, TypeAlignment)
1913      TemplateTypeParmType(Depth, Index, ParameterPack);
1914
1915  Types.push_back(TypeParm);
1916  TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1917
1918  return QualType(TypeParm, 0);
1919}
1920
1921TypeSourceInfo *
1922ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1923                                              SourceLocation NameLoc,
1924                                        const TemplateArgumentListInfo &Args,
1925                                              QualType CanonType) {
1926  QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1927
1928  TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1929  TemplateSpecializationTypeLoc TL
1930    = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1931  TL.setTemplateNameLoc(NameLoc);
1932  TL.setLAngleLoc(Args.getLAngleLoc());
1933  TL.setRAngleLoc(Args.getRAngleLoc());
1934  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1935    TL.setArgLocInfo(i, Args[i].getLocInfo());
1936  return DI;
1937}
1938
1939QualType
1940ASTContext::getTemplateSpecializationType(TemplateName Template,
1941                                          const TemplateArgumentListInfo &Args,
1942                                          QualType Canon) {
1943  unsigned NumArgs = Args.size();
1944
1945  llvm::SmallVector<TemplateArgument, 4> ArgVec;
1946  ArgVec.reserve(NumArgs);
1947  for (unsigned i = 0; i != NumArgs; ++i)
1948    ArgVec.push_back(Args[i].getArgument());
1949
1950  return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
1951                                       Canon);
1952}
1953
1954QualType
1955ASTContext::getTemplateSpecializationType(TemplateName Template,
1956                                          const TemplateArgument *Args,
1957                                          unsigned NumArgs,
1958                                          QualType Canon) {
1959  if (!Canon.isNull())
1960    Canon = getCanonicalType(Canon);
1961  else
1962    Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
1963
1964  // Allocate the (non-canonical) template specialization type, but don't
1965  // try to unique it: these types typically have location information that
1966  // we don't unique and don't want to lose.
1967  void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1968                        sizeof(TemplateArgument) * NumArgs),
1969                       TypeAlignment);
1970  TemplateSpecializationType *Spec
1971    = new (Mem) TemplateSpecializationType(Template,
1972                                           Args, NumArgs,
1973                                           Canon);
1974
1975  Types.push_back(Spec);
1976  return QualType(Spec, 0);
1977}
1978
1979QualType
1980ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
1981                                                   const TemplateArgument *Args,
1982                                                   unsigned NumArgs) {
1983  // Build the canonical template specialization type.
1984  TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1985  llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1986  CanonArgs.reserve(NumArgs);
1987  for (unsigned I = 0; I != NumArgs; ++I)
1988    CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1989
1990  // Determine whether this canonical template specialization type already
1991  // exists.
1992  llvm::FoldingSetNodeID ID;
1993  TemplateSpecializationType::Profile(ID, CanonTemplate,
1994                                      CanonArgs.data(), NumArgs, *this);
1995
1996  void *InsertPos = 0;
1997  TemplateSpecializationType *Spec
1998    = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1999
2000  if (!Spec) {
2001    // Allocate a new canonical template specialization type.
2002    void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2003                          sizeof(TemplateArgument) * NumArgs),
2004                         TypeAlignment);
2005    Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2006                                                CanonArgs.data(), NumArgs,
2007                                                QualType());
2008    Types.push_back(Spec);
2009    TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2010  }
2011
2012  assert(Spec->isDependentType() &&
2013         "Non-dependent template-id type must have a canonical type");
2014  return QualType(Spec, 0);
2015}
2016
2017QualType
2018ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2019                              NestedNameSpecifier *NNS,
2020                              QualType NamedType) {
2021  llvm::FoldingSetNodeID ID;
2022  ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
2023
2024  void *InsertPos = 0;
2025  ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2026  if (T)
2027    return QualType(T, 0);
2028
2029  QualType Canon = NamedType;
2030  if (!Canon.isCanonical()) {
2031    Canon = getCanonicalType(NamedType);
2032    ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2033    assert(!CheckT && "Elaborated canonical type broken");
2034    (void)CheckT;
2035  }
2036
2037  T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
2038  Types.push_back(T);
2039  ElaboratedTypes.InsertNode(T, InsertPos);
2040  return QualType(T, 0);
2041}
2042
2043QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2044                                          NestedNameSpecifier *NNS,
2045                                          const IdentifierInfo *Name,
2046                                          QualType Canon) {
2047  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2048
2049  if (Canon.isNull()) {
2050    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2051    ElaboratedTypeKeyword CanonKeyword = Keyword;
2052    if (Keyword == ETK_None)
2053      CanonKeyword = ETK_Typename;
2054
2055    if (CanonNNS != NNS || CanonKeyword != Keyword)
2056      Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
2057  }
2058
2059  llvm::FoldingSetNodeID ID;
2060  DependentNameType::Profile(ID, Keyword, NNS, Name);
2061
2062  void *InsertPos = 0;
2063  DependentNameType *T
2064    = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2065  if (T)
2066    return QualType(T, 0);
2067
2068  T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
2069  Types.push_back(T);
2070  DependentNameTypes.InsertNode(T, InsertPos);
2071  return QualType(T, 0);
2072}
2073
2074QualType
2075ASTContext::getDependentTemplateSpecializationType(
2076                                 ElaboratedTypeKeyword Keyword,
2077                                 NestedNameSpecifier *NNS,
2078                                 const IdentifierInfo *Name,
2079                                 const TemplateArgumentListInfo &Args) {
2080  // TODO: avoid this copy
2081  llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2082  for (unsigned I = 0, E = Args.size(); I != E; ++I)
2083    ArgCopy.push_back(Args[I].getArgument());
2084  return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2085                                                ArgCopy.size(),
2086                                                ArgCopy.data());
2087}
2088
2089QualType
2090ASTContext::getDependentTemplateSpecializationType(
2091                                 ElaboratedTypeKeyword Keyword,
2092                                 NestedNameSpecifier *NNS,
2093                                 const IdentifierInfo *Name,
2094                                 unsigned NumArgs,
2095                                 const TemplateArgument *Args) {
2096  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2097
2098  llvm::FoldingSetNodeID ID;
2099  DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2100                                               Name, NumArgs, Args);
2101
2102  void *InsertPos = 0;
2103  DependentTemplateSpecializationType *T
2104    = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2105  if (T)
2106    return QualType(T, 0);
2107
2108  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2109
2110  ElaboratedTypeKeyword CanonKeyword = Keyword;
2111  if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2112
2113  bool AnyNonCanonArgs = false;
2114  llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2115  for (unsigned I = 0; I != NumArgs; ++I) {
2116    CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2117    if (!CanonArgs[I].structurallyEquals(Args[I]))
2118      AnyNonCanonArgs = true;
2119  }
2120
2121  QualType Canon;
2122  if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2123    Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2124                                                   Name, NumArgs,
2125                                                   CanonArgs.data());
2126
2127    // Find the insert position again.
2128    DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2129  }
2130
2131  void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2132                        sizeof(TemplateArgument) * NumArgs),
2133                       TypeAlignment);
2134  T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
2135                                                    Name, NumArgs, Args, Canon);
2136  Types.push_back(T);
2137  DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
2138  return QualType(T, 0);
2139}
2140
2141/// CmpProtocolNames - Comparison predicate for sorting protocols
2142/// alphabetically.
2143static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2144                            const ObjCProtocolDecl *RHS) {
2145  return LHS->getDeclName() < RHS->getDeclName();
2146}
2147
2148static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
2149                                unsigned NumProtocols) {
2150  if (NumProtocols == 0) return true;
2151
2152  for (unsigned i = 1; i != NumProtocols; ++i)
2153    if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2154      return false;
2155  return true;
2156}
2157
2158static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
2159                                   unsigned &NumProtocols) {
2160  ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
2161
2162  // Sort protocols, keyed by name.
2163  std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2164
2165  // Remove duplicates.
2166  ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2167  NumProtocols = ProtocolsEnd-Protocols;
2168}
2169
2170QualType ASTContext::getObjCObjectType(QualType BaseType,
2171                                       ObjCProtocolDecl * const *Protocols,
2172                                       unsigned NumProtocols) {
2173  // If the base type is an interface and there aren't any protocols
2174  // to add, then the interface type will do just fine.
2175  if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2176    return BaseType;
2177
2178  // Look in the folding set for an existing type.
2179  llvm::FoldingSetNodeID ID;
2180  ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
2181  void *InsertPos = 0;
2182  if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2183    return QualType(QT, 0);
2184
2185  // Build the canonical type, which has the canonical base type and
2186  // a sorted-and-uniqued list of protocols.
2187  QualType Canonical;
2188  bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2189  if (!ProtocolsSorted || !BaseType.isCanonical()) {
2190    if (!ProtocolsSorted) {
2191      llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2192                                                     Protocols + NumProtocols);
2193      unsigned UniqueCount = NumProtocols;
2194
2195      SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2196      Canonical = getObjCObjectType(getCanonicalType(BaseType),
2197                                    &Sorted[0], UniqueCount);
2198    } else {
2199      Canonical = getObjCObjectType(getCanonicalType(BaseType),
2200                                    Protocols, NumProtocols);
2201    }
2202
2203    // Regenerate InsertPos.
2204    ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2205  }
2206
2207  unsigned Size = sizeof(ObjCObjectTypeImpl);
2208  Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2209  void *Mem = Allocate(Size, TypeAlignment);
2210  ObjCObjectTypeImpl *T =
2211    new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2212
2213  Types.push_back(T);
2214  ObjCObjectTypes.InsertNode(T, InsertPos);
2215  return QualType(T, 0);
2216}
2217
2218/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2219/// the given object type.
2220QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2221  llvm::FoldingSetNodeID ID;
2222  ObjCObjectPointerType::Profile(ID, ObjectT);
2223
2224  void *InsertPos = 0;
2225  if (ObjCObjectPointerType *QT =
2226              ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2227    return QualType(QT, 0);
2228
2229  // Find the canonical object type.
2230  QualType Canonical;
2231  if (!ObjectT.isCanonical()) {
2232    Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2233
2234    // Regenerate InsertPos.
2235    ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2236  }
2237
2238  // No match.
2239  void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2240  ObjCObjectPointerType *QType =
2241    new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
2242
2243  Types.push_back(QType);
2244  ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2245  return QualType(QType, 0);
2246}
2247
2248/// getObjCInterfaceType - Return the unique reference to the type for the
2249/// specified ObjC interface decl. The list of protocols is optional.
2250QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2251  if (Decl->TypeForDecl)
2252    return QualType(Decl->TypeForDecl, 0);
2253
2254  // FIXME: redeclarations?
2255  void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2256  ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2257  Decl->TypeForDecl = T;
2258  Types.push_back(T);
2259  return QualType(T, 0);
2260}
2261
2262/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2263/// TypeOfExprType AST's (since expression's are never shared). For example,
2264/// multiple declarations that refer to "typeof(x)" all contain different
2265/// DeclRefExpr's. This doesn't effect the type checker, since it operates
2266/// on canonical type's (which are always unique).
2267QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
2268  TypeOfExprType *toe;
2269  if (tofExpr->isTypeDependent()) {
2270    llvm::FoldingSetNodeID ID;
2271    DependentTypeOfExprType::Profile(ID, *this, tofExpr);
2272
2273    void *InsertPos = 0;
2274    DependentTypeOfExprType *Canon
2275      = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2276    if (Canon) {
2277      // We already have a "canonical" version of an identical, dependent
2278      // typeof(expr) type. Use that as our canonical type.
2279      toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
2280                                          QualType((TypeOfExprType*)Canon, 0));
2281    }
2282    else {
2283      // Build a new, canonical typeof(expr) type.
2284      Canon
2285        = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
2286      DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2287      toe = Canon;
2288    }
2289  } else {
2290    QualType Canonical = getCanonicalType(tofExpr->getType());
2291    toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
2292  }
2293  Types.push_back(toe);
2294  return QualType(toe, 0);
2295}
2296
2297/// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
2298/// TypeOfType AST's. The only motivation to unique these nodes would be
2299/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
2300/// an issue. This doesn't effect the type checker, since it operates
2301/// on canonical type's (which are always unique).
2302QualType ASTContext::getTypeOfType(QualType tofType) {
2303  QualType Canonical = getCanonicalType(tofType);
2304  TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
2305  Types.push_back(tot);
2306  return QualType(tot, 0);
2307}
2308
2309/// getDecltypeForExpr - Given an expr, will return the decltype for that
2310/// expression, according to the rules in C++0x [dcl.type.simple]p4
2311static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
2312  if (e->isTypeDependent())
2313    return Context.DependentTy;
2314
2315  // If e is an id expression or a class member access, decltype(e) is defined
2316  // as the type of the entity named by e.
2317  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2318    if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2319      return VD->getType();
2320  }
2321  if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2322    if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2323      return FD->getType();
2324  }
2325  // If e is a function call or an invocation of an overloaded operator,
2326  // (parentheses around e are ignored), decltype(e) is defined as the
2327  // return type of that function.
2328  if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2329    return CE->getCallReturnType();
2330
2331  QualType T = e->getType();
2332
2333  // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
2334  // defined as T&, otherwise decltype(e) is defined as T.
2335  if (e->isLvalue(Context) == Expr::LV_Valid)
2336    T = Context.getLValueReferenceType(T);
2337
2338  return T;
2339}
2340
2341/// getDecltypeType -  Unlike many "get<Type>" functions, we don't unique
2342/// DecltypeType AST's. The only motivation to unique these nodes would be
2343/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
2344/// an issue. This doesn't effect the type checker, since it operates
2345/// on canonical type's (which are always unique).
2346QualType ASTContext::getDecltypeType(Expr *e) {
2347  DecltypeType *dt;
2348  if (e->isTypeDependent()) {
2349    llvm::FoldingSetNodeID ID;
2350    DependentDecltypeType::Profile(ID, *this, e);
2351
2352    void *InsertPos = 0;
2353    DependentDecltypeType *Canon
2354      = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2355    if (Canon) {
2356      // We already have a "canonical" version of an equivalent, dependent
2357      // decltype type. Use that as our canonical type.
2358      dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
2359                                       QualType((DecltypeType*)Canon, 0));
2360    }
2361    else {
2362      // Build a new, canonical typeof(expr) type.
2363      Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
2364      DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2365      dt = Canon;
2366    }
2367  } else {
2368    QualType T = getDecltypeForExpr(e, *this);
2369    dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
2370  }
2371  Types.push_back(dt);
2372  return QualType(dt, 0);
2373}
2374
2375/// getTagDeclType - Return the unique reference to the type for the
2376/// specified TagDecl (struct/union/class/enum) decl.
2377QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
2378  assert (Decl);
2379  // FIXME: What is the design on getTagDeclType when it requires casting
2380  // away const?  mutable?
2381  return getTypeDeclType(const_cast<TagDecl*>(Decl));
2382}
2383
2384/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2385/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2386/// needs to agree with the definition in <stddef.h>.
2387CanQualType ASTContext::getSizeType() const {
2388  return getFromTargetType(Target.getSizeType());
2389}
2390
2391/// getSignedWCharType - Return the type of "signed wchar_t".
2392/// Used when in C++, as a GCC extension.
2393QualType ASTContext::getSignedWCharType() const {
2394  // FIXME: derive from "Target" ?
2395  return WCharTy;
2396}
2397
2398/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2399/// Used when in C++, as a GCC extension.
2400QualType ASTContext::getUnsignedWCharType() const {
2401  // FIXME: derive from "Target" ?
2402  return UnsignedIntTy;
2403}
2404
2405/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2406/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2407QualType ASTContext::getPointerDiffType() const {
2408  return getFromTargetType(Target.getPtrDiffType(0));
2409}
2410
2411//===----------------------------------------------------------------------===//
2412//                              Type Operators
2413//===----------------------------------------------------------------------===//
2414
2415CanQualType ASTContext::getCanonicalParamType(QualType T) {
2416  // Push qualifiers into arrays, and then discard any remaining
2417  // qualifiers.
2418  T = getCanonicalType(T);
2419  const Type *Ty = T.getTypePtr();
2420
2421  QualType Result;
2422  if (isa<ArrayType>(Ty)) {
2423    Result = getArrayDecayedType(QualType(Ty,0));
2424  } else if (isa<FunctionType>(Ty)) {
2425    Result = getPointerType(QualType(Ty, 0));
2426  } else {
2427    Result = QualType(Ty, 0);
2428  }
2429
2430  return CanQualType::CreateUnsafe(Result);
2431}
2432
2433/// getCanonicalType - Return the canonical (structural) type corresponding to
2434/// the specified potentially non-canonical type.  The non-canonical version
2435/// of a type may have many "decorated" versions of types.  Decorators can
2436/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2437/// to be free of any of these, allowing two canonical types to be compared
2438/// for exact equality with a simple pointer comparison.
2439CanQualType ASTContext::getCanonicalType(QualType T) {
2440  QualifierCollector Quals;
2441  const Type *Ptr = Quals.strip(T);
2442  QualType CanType = Ptr->getCanonicalTypeInternal();
2443
2444  // The canonical internal type will be the canonical type *except*
2445  // that we push type qualifiers down through array types.
2446
2447  // If there are no new qualifiers to push down, stop here.
2448  if (!Quals.hasQualifiers())
2449    return CanQualType::CreateUnsafe(CanType);
2450
2451  // If the type qualifiers are on an array type, get the canonical
2452  // type of the array with the qualifiers applied to the element
2453  // type.
2454  ArrayType *AT = dyn_cast<ArrayType>(CanType);
2455  if (!AT)
2456    return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
2457
2458  // Get the canonical version of the element with the extra qualifiers on it.
2459  // This can recursively sink qualifiers through multiple levels of arrays.
2460  QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
2461  NewEltTy = getCanonicalType(NewEltTy);
2462
2463  if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2464    return CanQualType::CreateUnsafe(
2465             getConstantArrayType(NewEltTy, CAT->getSize(),
2466                                  CAT->getSizeModifier(),
2467                                  CAT->getIndexTypeCVRQualifiers()));
2468  if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
2469    return CanQualType::CreateUnsafe(
2470             getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
2471                                    IAT->getIndexTypeCVRQualifiers()));
2472
2473  if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
2474    return CanQualType::CreateUnsafe(
2475             getDependentSizedArrayType(NewEltTy,
2476                                        DSAT->getSizeExpr() ?
2477                                          DSAT->getSizeExpr()->Retain() : 0,
2478                                        DSAT->getSizeModifier(),
2479                                        DSAT->getIndexTypeCVRQualifiers(),
2480                        DSAT->getBracketsRange())->getCanonicalTypeInternal());
2481
2482  VariableArrayType *VAT = cast<VariableArrayType>(AT);
2483  return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
2484                                                        VAT->getSizeExpr() ?
2485                                              VAT->getSizeExpr()->Retain() : 0,
2486                                                        VAT->getSizeModifier(),
2487                                              VAT->getIndexTypeCVRQualifiers(),
2488                                                     VAT->getBracketsRange()));
2489}
2490
2491QualType ASTContext::getUnqualifiedArrayType(QualType T,
2492                                             Qualifiers &Quals) {
2493  Quals = T.getQualifiers();
2494  const ArrayType *AT = getAsArrayType(T);
2495  if (!AT) {
2496    return T.getUnqualifiedType();
2497  }
2498
2499  QualType Elt = AT->getElementType();
2500  QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
2501  if (Elt == UnqualElt)
2502    return T;
2503
2504  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
2505    return getConstantArrayType(UnqualElt, CAT->getSize(),
2506                                CAT->getSizeModifier(), 0);
2507  }
2508
2509  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
2510    return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2511  }
2512
2513  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2514    return getVariableArrayType(UnqualElt,
2515                                VAT->getSizeExpr() ?
2516                                VAT->getSizeExpr()->Retain() : 0,
2517                                VAT->getSizeModifier(),
2518                                VAT->getIndexTypeCVRQualifiers(),
2519                                VAT->getBracketsRange());
2520  }
2521
2522  const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
2523  return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2524                                    DSAT->getSizeModifier(), 0,
2525                                    SourceRange());
2526}
2527
2528/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types  that
2529/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2530/// they point to and return true. If T1 and T2 aren't pointer types
2531/// or pointer-to-member types, or if they are not similar at this
2532/// level, returns false and leaves T1 and T2 unchanged. Top-level
2533/// qualifiers on T1 and T2 are ignored. This function will typically
2534/// be called in a loop that successively "unwraps" pointer and
2535/// pointer-to-member types to compare them at each level.
2536bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2537  const PointerType *T1PtrType = T1->getAs<PointerType>(),
2538                    *T2PtrType = T2->getAs<PointerType>();
2539  if (T1PtrType && T2PtrType) {
2540    T1 = T1PtrType->getPointeeType();
2541    T2 = T2PtrType->getPointeeType();
2542    return true;
2543  }
2544
2545  const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2546                          *T2MPType = T2->getAs<MemberPointerType>();
2547  if (T1MPType && T2MPType &&
2548      hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2549                             QualType(T2MPType->getClass(), 0))) {
2550    T1 = T1MPType->getPointeeType();
2551    T2 = T2MPType->getPointeeType();
2552    return true;
2553  }
2554
2555  if (getLangOptions().ObjC1) {
2556    const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2557                                *T2OPType = T2->getAs<ObjCObjectPointerType>();
2558    if (T1OPType && T2OPType) {
2559      T1 = T1OPType->getPointeeType();
2560      T2 = T2OPType->getPointeeType();
2561      return true;
2562    }
2563  }
2564
2565  // FIXME: Block pointers, too?
2566
2567  return false;
2568}
2569
2570DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2571  if (TemplateDecl *TD = Name.getAsTemplateDecl())
2572    return TD->getDeclName();
2573
2574  if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2575    if (DTN->isIdentifier()) {
2576      return DeclarationNames.getIdentifier(DTN->getIdentifier());
2577    } else {
2578      return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2579    }
2580  }
2581
2582  OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2583  assert(Storage);
2584  return (*Storage->begin())->getDeclName();
2585}
2586
2587TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2588  if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2589    if (TemplateTemplateParmDecl *TTP
2590                              = dyn_cast<TemplateTemplateParmDecl>(Template))
2591      Template = getCanonicalTemplateTemplateParmDecl(TTP);
2592
2593    // The canonical template name is the canonical template declaration.
2594    return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
2595  }
2596
2597  assert(!Name.getAsOverloadedTemplate());
2598
2599  DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2600  assert(DTN && "Non-dependent template names must refer to template decls.");
2601  return DTN->CanonicalTemplateName;
2602}
2603
2604bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2605  X = getCanonicalTemplateName(X);
2606  Y = getCanonicalTemplateName(Y);
2607  return X.getAsVoidPointer() == Y.getAsVoidPointer();
2608}
2609
2610TemplateArgument
2611ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2612  switch (Arg.getKind()) {
2613    case TemplateArgument::Null:
2614      return Arg;
2615
2616    case TemplateArgument::Expression:
2617      return Arg;
2618
2619    case TemplateArgument::Declaration:
2620      return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
2621
2622    case TemplateArgument::Template:
2623      return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2624
2625    case TemplateArgument::Integral:
2626      return TemplateArgument(*Arg.getAsIntegral(),
2627                              getCanonicalType(Arg.getIntegralType()));
2628
2629    case TemplateArgument::Type:
2630      return TemplateArgument(getCanonicalType(Arg.getAsType()));
2631
2632    case TemplateArgument::Pack: {
2633      // FIXME: Allocate in ASTContext
2634      TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2635      unsigned Idx = 0;
2636      for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
2637                                        AEnd = Arg.pack_end();
2638           A != AEnd; (void)++A, ++Idx)
2639        CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
2640
2641      TemplateArgument Result;
2642      Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2643      return Result;
2644    }
2645  }
2646
2647  // Silence GCC warning
2648  assert(false && "Unhandled template argument kind");
2649  return TemplateArgument();
2650}
2651
2652NestedNameSpecifier *
2653ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
2654  if (!NNS)
2655    return 0;
2656
2657  switch (NNS->getKind()) {
2658  case NestedNameSpecifier::Identifier:
2659    // Canonicalize the prefix but keep the identifier the same.
2660    return NestedNameSpecifier::Create(*this,
2661                         getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2662                                       NNS->getAsIdentifier());
2663
2664  case NestedNameSpecifier::Namespace:
2665    // A namespace is canonical; build a nested-name-specifier with
2666    // this namespace and no prefix.
2667    return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2668
2669  case NestedNameSpecifier::TypeSpec:
2670  case NestedNameSpecifier::TypeSpecWithTemplate: {
2671    QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
2672    return NestedNameSpecifier::Create(*this, 0,
2673                 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
2674                                       T.getTypePtr());
2675  }
2676
2677  case NestedNameSpecifier::Global:
2678    // The global specifier is canonical and unique.
2679    return NNS;
2680  }
2681
2682  // Required to silence a GCC warning
2683  return 0;
2684}
2685
2686
2687const ArrayType *ASTContext::getAsArrayType(QualType T) {
2688  // Handle the non-qualified case efficiently.
2689  if (!T.hasLocalQualifiers()) {
2690    // Handle the common positive case fast.
2691    if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2692      return AT;
2693  }
2694
2695  // Handle the common negative case fast.
2696  QualType CType = T->getCanonicalTypeInternal();
2697  if (!isa<ArrayType>(CType))
2698    return 0;
2699
2700  // Apply any qualifiers from the array type to the element type.  This
2701  // implements C99 6.7.3p8: "If the specification of an array type includes
2702  // any type qualifiers, the element type is so qualified, not the array type."
2703
2704  // If we get here, we either have type qualifiers on the type, or we have
2705  // sugar such as a typedef in the way.  If we have type qualifiers on the type
2706  // we must propagate them down into the element type.
2707
2708  QualifierCollector Qs;
2709  const Type *Ty = Qs.strip(T.getDesugaredType());
2710
2711  // If we have a simple case, just return now.
2712  const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2713  if (ATy == 0 || Qs.empty())
2714    return ATy;
2715
2716  // Otherwise, we have an array and we have qualifiers on it.  Push the
2717  // qualifiers into the array element type and return a new array type.
2718  // Get the canonical version of the element with the extra qualifiers on it.
2719  // This can recursively sink qualifiers through multiple levels of arrays.
2720  QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
2721
2722  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2723    return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2724                                                CAT->getSizeModifier(),
2725                                           CAT->getIndexTypeCVRQualifiers()));
2726  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2727    return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2728                                                  IAT->getSizeModifier(),
2729                                           IAT->getIndexTypeCVRQualifiers()));
2730
2731  if (const DependentSizedArrayType *DSAT
2732        = dyn_cast<DependentSizedArrayType>(ATy))
2733    return cast<ArrayType>(
2734                     getDependentSizedArrayType(NewEltTy,
2735                                                DSAT->getSizeExpr() ?
2736                                              DSAT->getSizeExpr()->Retain() : 0,
2737                                                DSAT->getSizeModifier(),
2738                                              DSAT->getIndexTypeCVRQualifiers(),
2739                                                DSAT->getBracketsRange()));
2740
2741  const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
2742  return cast<ArrayType>(getVariableArrayType(NewEltTy,
2743                                              VAT->getSizeExpr() ?
2744                                              VAT->getSizeExpr()->Retain() : 0,
2745                                              VAT->getSizeModifier(),
2746                                              VAT->getIndexTypeCVRQualifiers(),
2747                                              VAT->getBracketsRange()));
2748}
2749
2750
2751/// getArrayDecayedType - Return the properly qualified result of decaying the
2752/// specified array type to a pointer.  This operation is non-trivial when
2753/// handling typedefs etc.  The canonical type of "T" must be an array type,
2754/// this returns a pointer to a properly qualified element of the array.
2755///
2756/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2757QualType ASTContext::getArrayDecayedType(QualType Ty) {
2758  // Get the element type with 'getAsArrayType' so that we don't lose any
2759  // typedefs in the element type of the array.  This also handles propagation
2760  // of type qualifiers from the array type into the element type if present
2761  // (C99 6.7.3p8).
2762  const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2763  assert(PrettyArrayType && "Not an array type!");
2764
2765  QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
2766
2767  // int x[restrict 4] ->  int *restrict
2768  return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
2769}
2770
2771QualType ASTContext::getBaseElementType(QualType QT) {
2772  QualifierCollector Qs;
2773  while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2774    QT = AT->getElementType();
2775  return Qs.apply(QT);
2776}
2777
2778QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2779  QualType ElemTy = AT->getElementType();
2780
2781  if (const ArrayType *AT = getAsArrayType(ElemTy))
2782    return getBaseElementType(AT);
2783
2784  return ElemTy;
2785}
2786
2787/// getConstantArrayElementCount - Returns number of constant array elements.
2788uint64_t
2789ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
2790  uint64_t ElementCount = 1;
2791  do {
2792    ElementCount *= CA->getSize().getZExtValue();
2793    CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2794  } while (CA);
2795  return ElementCount;
2796}
2797
2798/// getFloatingRank - Return a relative rank for floating point types.
2799/// This routine will assert if passed a built-in type that isn't a float.
2800static FloatingRank getFloatingRank(QualType T) {
2801  if (const ComplexType *CT = T->getAs<ComplexType>())
2802    return getFloatingRank(CT->getElementType());
2803
2804  assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2805  switch (T->getAs<BuiltinType>()->getKind()) {
2806  default: assert(0 && "getFloatingRank(): not a floating type");
2807  case BuiltinType::Float:      return FloatRank;
2808  case BuiltinType::Double:     return DoubleRank;
2809  case BuiltinType::LongDouble: return LongDoubleRank;
2810  }
2811}
2812
2813/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2814/// point or a complex type (based on typeDomain/typeSize).
2815/// 'typeDomain' is a real floating point or complex type.
2816/// 'typeSize' is a real floating point or complex type.
2817QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2818                                                       QualType Domain) const {
2819  FloatingRank EltRank = getFloatingRank(Size);
2820  if (Domain->isComplexType()) {
2821    switch (EltRank) {
2822    default: assert(0 && "getFloatingRank(): illegal value for rank");
2823    case FloatRank:      return FloatComplexTy;
2824    case DoubleRank:     return DoubleComplexTy;
2825    case LongDoubleRank: return LongDoubleComplexTy;
2826    }
2827  }
2828
2829  assert(Domain->isRealFloatingType() && "Unknown domain!");
2830  switch (EltRank) {
2831  default: assert(0 && "getFloatingRank(): illegal value for rank");
2832  case FloatRank:      return FloatTy;
2833  case DoubleRank:     return DoubleTy;
2834  case LongDoubleRank: return LongDoubleTy;
2835  }
2836}
2837
2838/// getFloatingTypeOrder - Compare the rank of the two specified floating
2839/// point types, ignoring the domain of the type (i.e. 'double' ==
2840/// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
2841/// LHS < RHS, return -1.
2842int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2843  FloatingRank LHSR = getFloatingRank(LHS);
2844  FloatingRank RHSR = getFloatingRank(RHS);
2845
2846  if (LHSR == RHSR)
2847    return 0;
2848  if (LHSR > RHSR)
2849    return 1;
2850  return -1;
2851}
2852
2853/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2854/// routine will assert if passed a built-in type that isn't an integer or enum,
2855/// or if it is not canonicalized.
2856unsigned ASTContext::getIntegerRank(Type *T) {
2857  assert(T->isCanonicalUnqualified() && "T should be canonicalized");
2858  if (EnumType* ET = dyn_cast<EnumType>(T))
2859    T = ET->getDecl()->getPromotionType().getTypePtr();
2860
2861  if (T->isSpecificBuiltinType(BuiltinType::WChar))
2862    T = getFromTargetType(Target.getWCharType()).getTypePtr();
2863
2864  if (T->isSpecificBuiltinType(BuiltinType::Char16))
2865    T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2866
2867  if (T->isSpecificBuiltinType(BuiltinType::Char32))
2868    T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2869
2870  switch (cast<BuiltinType>(T)->getKind()) {
2871  default: assert(0 && "getIntegerRank(): not a built-in integer");
2872  case BuiltinType::Bool:
2873    return 1 + (getIntWidth(BoolTy) << 3);
2874  case BuiltinType::Char_S:
2875  case BuiltinType::Char_U:
2876  case BuiltinType::SChar:
2877  case BuiltinType::UChar:
2878    return 2 + (getIntWidth(CharTy) << 3);
2879  case BuiltinType::Short:
2880  case BuiltinType::UShort:
2881    return 3 + (getIntWidth(ShortTy) << 3);
2882  case BuiltinType::Int:
2883  case BuiltinType::UInt:
2884    return 4 + (getIntWidth(IntTy) << 3);
2885  case BuiltinType::Long:
2886  case BuiltinType::ULong:
2887    return 5 + (getIntWidth(LongTy) << 3);
2888  case BuiltinType::LongLong:
2889  case BuiltinType::ULongLong:
2890    return 6 + (getIntWidth(LongLongTy) << 3);
2891  case BuiltinType::Int128:
2892  case BuiltinType::UInt128:
2893    return 7 + (getIntWidth(Int128Ty) << 3);
2894  }
2895}
2896
2897/// \brief Whether this is a promotable bitfield reference according
2898/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2899///
2900/// \returns the type this bit-field will promote to, or NULL if no
2901/// promotion occurs.
2902QualType ASTContext::isPromotableBitField(Expr *E) {
2903  if (E->isTypeDependent() || E->isValueDependent())
2904    return QualType();
2905
2906  FieldDecl *Field = E->getBitField();
2907  if (!Field)
2908    return QualType();
2909
2910  QualType FT = Field->getType();
2911
2912  llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2913  uint64_t BitWidth = BitWidthAP.getZExtValue();
2914  uint64_t IntSize = getTypeSize(IntTy);
2915  // GCC extension compatibility: if the bit-field size is less than or equal
2916  // to the size of int, it gets promoted no matter what its type is.
2917  // For instance, unsigned long bf : 4 gets promoted to signed int.
2918  if (BitWidth < IntSize)
2919    return IntTy;
2920
2921  if (BitWidth == IntSize)
2922    return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2923
2924  // Types bigger than int are not subject to promotions, and therefore act
2925  // like the base type.
2926  // FIXME: This doesn't quite match what gcc does, but what gcc does here
2927  // is ridiculous.
2928  return QualType();
2929}
2930
2931/// getPromotedIntegerType - Returns the type that Promotable will
2932/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2933/// integer type.
2934QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2935  assert(!Promotable.isNull());
2936  assert(Promotable->isPromotableIntegerType());
2937  if (const EnumType *ET = Promotable->getAs<EnumType>())
2938    return ET->getDecl()->getPromotionType();
2939  if (Promotable->isSignedIntegerType())
2940    return IntTy;
2941  uint64_t PromotableSize = getTypeSize(Promotable);
2942  uint64_t IntSize = getTypeSize(IntTy);
2943  assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2944  return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2945}
2946
2947/// getIntegerTypeOrder - Returns the highest ranked integer type:
2948/// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
2949/// LHS < RHS, return -1.
2950int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
2951  Type *LHSC = getCanonicalType(LHS).getTypePtr();
2952  Type *RHSC = getCanonicalType(RHS).getTypePtr();
2953  if (LHSC == RHSC) return 0;
2954
2955  bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2956  bool RHSUnsigned = RHSC->isUnsignedIntegerType();
2957
2958  unsigned LHSRank = getIntegerRank(LHSC);
2959  unsigned RHSRank = getIntegerRank(RHSC);
2960
2961  if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
2962    if (LHSRank == RHSRank) return 0;
2963    return LHSRank > RHSRank ? 1 : -1;
2964  }
2965
2966  // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2967  if (LHSUnsigned) {
2968    // If the unsigned [LHS] type is larger, return it.
2969    if (LHSRank >= RHSRank)
2970      return 1;
2971
2972    // If the signed type can represent all values of the unsigned type, it
2973    // wins.  Because we are dealing with 2's complement and types that are
2974    // powers of two larger than each other, this is always safe.
2975    return -1;
2976  }
2977
2978  // If the unsigned [RHS] type is larger, return it.
2979  if (RHSRank >= LHSRank)
2980    return -1;
2981
2982  // If the signed type can represent all values of the unsigned type, it
2983  // wins.  Because we are dealing with 2's complement and types that are
2984  // powers of two larger than each other, this is always safe.
2985  return 1;
2986}
2987
2988static RecordDecl *
2989CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2990                 SourceLocation L, IdentifierInfo *Id) {
2991  if (Ctx.getLangOptions().CPlusPlus)
2992    return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2993  else
2994    return RecordDecl::Create(Ctx, TK, DC, L, Id);
2995}
2996
2997// getCFConstantStringType - Return the type used for constant CFStrings.
2998QualType ASTContext::getCFConstantStringType() {
2999  if (!CFConstantStringTypeDecl) {
3000    CFConstantStringTypeDecl =
3001      CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
3002                       &Idents.get("NSConstantString"));
3003    CFConstantStringTypeDecl->startDefinition();
3004
3005    QualType FieldTypes[4];
3006
3007    // const int *isa;
3008    FieldTypes[0] = getPointerType(IntTy.withConst());
3009    // int flags;
3010    FieldTypes[1] = IntTy;
3011    // const char *str;
3012    FieldTypes[2] = getPointerType(CharTy.withConst());
3013    // long length;
3014    FieldTypes[3] = LongTy;
3015
3016    // Create fields
3017    for (unsigned i = 0; i < 4; ++i) {
3018      FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
3019                                           SourceLocation(), 0,
3020                                           FieldTypes[i], /*TInfo=*/0,
3021                                           /*BitWidth=*/0,
3022                                           /*Mutable=*/false);
3023      Field->setAccess(AS_public);
3024      CFConstantStringTypeDecl->addDecl(Field);
3025    }
3026
3027    CFConstantStringTypeDecl->completeDefinition();
3028  }
3029
3030  return getTagDeclType(CFConstantStringTypeDecl);
3031}
3032
3033void ASTContext::setCFConstantStringType(QualType T) {
3034  const RecordType *Rec = T->getAs<RecordType>();
3035  assert(Rec && "Invalid CFConstantStringType");
3036  CFConstantStringTypeDecl = Rec->getDecl();
3037}
3038
3039// getNSConstantStringType - Return the type used for constant NSStrings.
3040QualType ASTContext::getNSConstantStringType() {
3041  if (!NSConstantStringTypeDecl) {
3042    NSConstantStringTypeDecl =
3043    CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
3044                     &Idents.get("__builtin_NSString"));
3045    NSConstantStringTypeDecl->startDefinition();
3046
3047    QualType FieldTypes[3];
3048
3049    // const int *isa;
3050    FieldTypes[0] = getPointerType(IntTy.withConst());
3051    // const char *str;
3052    FieldTypes[1] = getPointerType(CharTy.withConst());
3053    // unsigned int length;
3054    FieldTypes[2] = UnsignedIntTy;
3055
3056    // Create fields
3057    for (unsigned i = 0; i < 3; ++i) {
3058      FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3059                                           SourceLocation(), 0,
3060                                           FieldTypes[i], /*TInfo=*/0,
3061                                           /*BitWidth=*/0,
3062                                           /*Mutable=*/false);
3063      Field->setAccess(AS_public);
3064      NSConstantStringTypeDecl->addDecl(Field);
3065    }
3066
3067    NSConstantStringTypeDecl->completeDefinition();
3068  }
3069
3070  return getTagDeclType(NSConstantStringTypeDecl);
3071}
3072
3073void ASTContext::setNSConstantStringType(QualType T) {
3074  const RecordType *Rec = T->getAs<RecordType>();
3075  assert(Rec && "Invalid NSConstantStringType");
3076  NSConstantStringTypeDecl = Rec->getDecl();
3077}
3078
3079QualType ASTContext::getObjCFastEnumerationStateType() {
3080  if (!ObjCFastEnumerationStateTypeDecl) {
3081    ObjCFastEnumerationStateTypeDecl =
3082      CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
3083                       &Idents.get("__objcFastEnumerationState"));
3084    ObjCFastEnumerationStateTypeDecl->startDefinition();
3085
3086    QualType FieldTypes[] = {
3087      UnsignedLongTy,
3088      getPointerType(ObjCIdTypedefType),
3089      getPointerType(UnsignedLongTy),
3090      getConstantArrayType(UnsignedLongTy,
3091                           llvm::APInt(32, 5), ArrayType::Normal, 0)
3092    };
3093
3094    for (size_t i = 0; i < 4; ++i) {
3095      FieldDecl *Field = FieldDecl::Create(*this,
3096                                           ObjCFastEnumerationStateTypeDecl,
3097                                           SourceLocation(), 0,
3098                                           FieldTypes[i], /*TInfo=*/0,
3099                                           /*BitWidth=*/0,
3100                                           /*Mutable=*/false);
3101      Field->setAccess(AS_public);
3102      ObjCFastEnumerationStateTypeDecl->addDecl(Field);
3103    }
3104    if (getLangOptions().CPlusPlus)
3105      if (CXXRecordDecl *CXXRD =
3106            dyn_cast<CXXRecordDecl>(ObjCFastEnumerationStateTypeDecl))
3107        CXXRD->setEmpty(false);
3108
3109    ObjCFastEnumerationStateTypeDecl->completeDefinition();
3110  }
3111
3112  return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3113}
3114
3115QualType ASTContext::getBlockDescriptorType() {
3116  if (BlockDescriptorType)
3117    return getTagDeclType(BlockDescriptorType);
3118
3119  RecordDecl *T;
3120  // FIXME: Needs the FlagAppleBlock bit.
3121  T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
3122                       &Idents.get("__block_descriptor"));
3123  T->startDefinition();
3124
3125  QualType FieldTypes[] = {
3126    UnsignedLongTy,
3127    UnsignedLongTy,
3128  };
3129
3130  const char *FieldNames[] = {
3131    "reserved",
3132    "Size"
3133  };
3134
3135  for (size_t i = 0; i < 2; ++i) {
3136    FieldDecl *Field = FieldDecl::Create(*this,
3137                                         T,
3138                                         SourceLocation(),
3139                                         &Idents.get(FieldNames[i]),
3140                                         FieldTypes[i], /*TInfo=*/0,
3141                                         /*BitWidth=*/0,
3142                                         /*Mutable=*/false);
3143    Field->setAccess(AS_public);
3144    T->addDecl(Field);
3145  }
3146
3147  T->completeDefinition();
3148
3149  BlockDescriptorType = T;
3150
3151  return getTagDeclType(BlockDescriptorType);
3152}
3153
3154void ASTContext::setBlockDescriptorType(QualType T) {
3155  const RecordType *Rec = T->getAs<RecordType>();
3156  assert(Rec && "Invalid BlockDescriptorType");
3157  BlockDescriptorType = Rec->getDecl();
3158}
3159
3160QualType ASTContext::getBlockDescriptorExtendedType() {
3161  if (BlockDescriptorExtendedType)
3162    return getTagDeclType(BlockDescriptorExtendedType);
3163
3164  RecordDecl *T;
3165  // FIXME: Needs the FlagAppleBlock bit.
3166  T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
3167                       &Idents.get("__block_descriptor_withcopydispose"));
3168  T->startDefinition();
3169
3170  QualType FieldTypes[] = {
3171    UnsignedLongTy,
3172    UnsignedLongTy,
3173    getPointerType(VoidPtrTy),
3174    getPointerType(VoidPtrTy)
3175  };
3176
3177  const char *FieldNames[] = {
3178    "reserved",
3179    "Size",
3180    "CopyFuncPtr",
3181    "DestroyFuncPtr"
3182  };
3183
3184  for (size_t i = 0; i < 4; ++i) {
3185    FieldDecl *Field = FieldDecl::Create(*this,
3186                                         T,
3187                                         SourceLocation(),
3188                                         &Idents.get(FieldNames[i]),
3189                                         FieldTypes[i], /*TInfo=*/0,
3190                                         /*BitWidth=*/0,
3191                                         /*Mutable=*/false);
3192    Field->setAccess(AS_public);
3193    T->addDecl(Field);
3194  }
3195
3196  T->completeDefinition();
3197
3198  BlockDescriptorExtendedType = T;
3199
3200  return getTagDeclType(BlockDescriptorExtendedType);
3201}
3202
3203void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3204  const RecordType *Rec = T->getAs<RecordType>();
3205  assert(Rec && "Invalid BlockDescriptorType");
3206  BlockDescriptorExtendedType = Rec->getDecl();
3207}
3208
3209bool ASTContext::BlockRequiresCopying(QualType Ty) {
3210  if (Ty->isBlockPointerType())
3211    return true;
3212  if (isObjCNSObjectType(Ty))
3213    return true;
3214  if (Ty->isObjCObjectPointerType())
3215    return true;
3216  return false;
3217}
3218
3219QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3220  //  type = struct __Block_byref_1_X {
3221  //    void *__isa;
3222  //    struct __Block_byref_1_X *__forwarding;
3223  //    unsigned int __flags;
3224  //    unsigned int __size;
3225  //    void *__copy_helper;		// as needed
3226  //    void *__destroy_help		// as needed
3227  //    int X;
3228  //  } *
3229
3230  bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3231
3232  // FIXME: Move up
3233  llvm::SmallString<36> Name;
3234  llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3235                                  ++UniqueBlockByRefTypeID << '_' << DeclName;
3236  RecordDecl *T;
3237  T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
3238                       &Idents.get(Name.str()));
3239  T->startDefinition();
3240  QualType Int32Ty = IntTy;
3241  assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3242  QualType FieldTypes[] = {
3243    getPointerType(VoidPtrTy),
3244    getPointerType(getTagDeclType(T)),
3245    Int32Ty,
3246    Int32Ty,
3247    getPointerType(VoidPtrTy),
3248    getPointerType(VoidPtrTy),
3249    Ty
3250  };
3251
3252  const char *FieldNames[] = {
3253    "__isa",
3254    "__forwarding",
3255    "__flags",
3256    "__size",
3257    "__copy_helper",
3258    "__destroy_helper",
3259    DeclName,
3260  };
3261
3262  for (size_t i = 0; i < 7; ++i) {
3263    if (!HasCopyAndDispose && i >=4 && i <= 5)
3264      continue;
3265    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3266                                         &Idents.get(FieldNames[i]),
3267                                         FieldTypes[i], /*TInfo=*/0,
3268                                         /*BitWidth=*/0, /*Mutable=*/false);
3269    Field->setAccess(AS_public);
3270    T->addDecl(Field);
3271  }
3272
3273  T->completeDefinition();
3274
3275  return getPointerType(getTagDeclType(T));
3276}
3277
3278
3279QualType ASTContext::getBlockParmType(
3280  bool BlockHasCopyDispose,
3281  llvm::SmallVectorImpl<const Expr *> &Layout) {
3282
3283  // FIXME: Move up
3284  llvm::SmallString<36> Name;
3285  llvm::raw_svector_ostream(Name) << "__block_literal_"
3286                                  << ++UniqueBlockParmTypeID;
3287  RecordDecl *T;
3288  T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
3289                       &Idents.get(Name.str()));
3290  T->startDefinition();
3291  QualType FieldTypes[] = {
3292    getPointerType(VoidPtrTy),
3293    IntTy,
3294    IntTy,
3295    getPointerType(VoidPtrTy),
3296    (BlockHasCopyDispose ?
3297     getPointerType(getBlockDescriptorExtendedType()) :
3298     getPointerType(getBlockDescriptorType()))
3299  };
3300
3301  const char *FieldNames[] = {
3302    "__isa",
3303    "__flags",
3304    "__reserved",
3305    "__FuncPtr",
3306    "__descriptor"
3307  };
3308
3309  for (size_t i = 0; i < 5; ++i) {
3310    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3311                                         &Idents.get(FieldNames[i]),
3312                                         FieldTypes[i], /*TInfo=*/0,
3313                                         /*BitWidth=*/0, /*Mutable=*/false);
3314    Field->setAccess(AS_public);
3315    T->addDecl(Field);
3316  }
3317
3318  for (unsigned i = 0; i < Layout.size(); ++i) {
3319    const Expr *E = Layout[i];
3320
3321    QualType FieldType = E->getType();
3322    IdentifierInfo *FieldName = 0;
3323    if (isa<CXXThisExpr>(E)) {
3324      FieldName = &Idents.get("this");
3325    } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3326      const ValueDecl *D = BDRE->getDecl();
3327      FieldName = D->getIdentifier();
3328      if (BDRE->isByRef())
3329        FieldType = BuildByRefType(D->getNameAsCString(), FieldType);
3330    } else {
3331      // Padding.
3332      assert(isa<ConstantArrayType>(FieldType) &&
3333             isa<DeclRefExpr>(E) &&
3334             !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3335             "doesn't match characteristics of padding decl");
3336    }
3337
3338    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3339                                         FieldName, FieldType, /*TInfo=*/0,
3340                                         /*BitWidth=*/0, /*Mutable=*/false);
3341    Field->setAccess(AS_public);
3342    T->addDecl(Field);
3343  }
3344
3345  T->completeDefinition();
3346
3347  return getPointerType(getTagDeclType(T));
3348}
3349
3350void ASTContext::setObjCFastEnumerationStateType(QualType T) {
3351  const RecordType *Rec = T->getAs<RecordType>();
3352  assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3353  ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3354}
3355
3356// This returns true if a type has been typedefed to BOOL:
3357// typedef <type> BOOL;
3358static bool isTypeTypedefedAsBOOL(QualType T) {
3359  if (const TypedefType *TT = dyn_cast<TypedefType>(T))
3360    if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3361      return II->isStr("BOOL");
3362
3363  return false;
3364}
3365
3366/// getObjCEncodingTypeSize returns size of type for objective-c encoding
3367/// purpose.
3368CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
3369  CharUnits sz = getTypeSizeInChars(type);
3370
3371  // Make all integer and enum types at least as large as an int
3372  if (sz.isPositive() && type->isIntegralOrEnumerationType())
3373    sz = std::max(sz, getTypeSizeInChars(IntTy));
3374  // Treat arrays as pointers, since that's how they're passed in.
3375  else if (type->isArrayType())
3376    sz = getTypeSizeInChars(VoidPtrTy);
3377  return sz;
3378}
3379
3380static inline
3381std::string charUnitsToString(const CharUnits &CU) {
3382  return llvm::itostr(CU.getQuantity());
3383}
3384
3385/// getObjCEncodingForBlockDecl - Return the encoded type for this block
3386/// declaration.
3387void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3388                                             std::string& S) {
3389  const BlockDecl *Decl = Expr->getBlockDecl();
3390  QualType BlockTy =
3391      Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3392  // Encode result type.
3393  getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
3394  // Compute size of all parameters.
3395  // Start with computing size of a pointer in number of bytes.
3396  // FIXME: There might(should) be a better way of doing this computation!
3397  SourceLocation Loc;
3398  CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3399  CharUnits ParmOffset = PtrSize;
3400  for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
3401       E = Decl->param_end(); PI != E; ++PI) {
3402    QualType PType = (*PI)->getType();
3403    CharUnits sz = getObjCEncodingTypeSize(PType);
3404    assert (sz.isPositive() && "BlockExpr - Incomplete param type");
3405    ParmOffset += sz;
3406  }
3407  // Size of the argument frame
3408  S += charUnitsToString(ParmOffset);
3409  // Block pointer and offset.
3410  S += "@?0";
3411  ParmOffset = PtrSize;
3412
3413  // Argument types.
3414  ParmOffset = PtrSize;
3415  for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3416       Decl->param_end(); PI != E; ++PI) {
3417    ParmVarDecl *PVDecl = *PI;
3418    QualType PType = PVDecl->getOriginalType();
3419    if (const ArrayType *AT =
3420          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3421      // Use array's original type only if it has known number of
3422      // elements.
3423      if (!isa<ConstantArrayType>(AT))
3424        PType = PVDecl->getType();
3425    } else if (PType->isFunctionType())
3426      PType = PVDecl->getType();
3427    getObjCEncodingForType(PType, S);
3428    S += charUnitsToString(ParmOffset);
3429    ParmOffset += getObjCEncodingTypeSize(PType);
3430  }
3431}
3432
3433/// getObjCEncodingForMethodDecl - Return the encoded type for this method
3434/// declaration.
3435void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
3436                                              std::string& S) {
3437  // FIXME: This is not very efficient.
3438  // Encode type qualifer, 'in', 'inout', etc. for the return type.
3439  getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
3440  // Encode result type.
3441  getObjCEncodingForType(Decl->getResultType(), S);
3442  // Compute size of all parameters.
3443  // Start with computing size of a pointer in number of bytes.
3444  // FIXME: There might(should) be a better way of doing this computation!
3445  SourceLocation Loc;
3446  CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3447  // The first two arguments (self and _cmd) are pointers; account for
3448  // their size.
3449  CharUnits ParmOffset = 2 * PtrSize;
3450  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3451       E = Decl->sel_param_end(); PI != E; ++PI) {
3452    QualType PType = (*PI)->getType();
3453    CharUnits sz = getObjCEncodingTypeSize(PType);
3454    assert (sz.isPositive() &&
3455        "getObjCEncodingForMethodDecl - Incomplete param type");
3456    ParmOffset += sz;
3457  }
3458  S += charUnitsToString(ParmOffset);
3459  S += "@0:";
3460  S += charUnitsToString(PtrSize);
3461
3462  // Argument types.
3463  ParmOffset = 2 * PtrSize;
3464  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3465       E = Decl->sel_param_end(); PI != E; ++PI) {
3466    ParmVarDecl *PVDecl = *PI;
3467    QualType PType = PVDecl->getOriginalType();
3468    if (const ArrayType *AT =
3469          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3470      // Use array's original type only if it has known number of
3471      // elements.
3472      if (!isa<ConstantArrayType>(AT))
3473        PType = PVDecl->getType();
3474    } else if (PType->isFunctionType())
3475      PType = PVDecl->getType();
3476    // Process argument qualifiers for user supplied arguments; such as,
3477    // 'in', 'inout', etc.
3478    getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
3479    getObjCEncodingForType(PType, S);
3480    S += charUnitsToString(ParmOffset);
3481    ParmOffset += getObjCEncodingTypeSize(PType);
3482  }
3483}
3484
3485/// getObjCEncodingForPropertyDecl - Return the encoded type for this
3486/// property declaration. If non-NULL, Container must be either an
3487/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3488/// NULL when getting encodings for protocol properties.
3489/// Property attributes are stored as a comma-delimited C string. The simple
3490/// attributes readonly and bycopy are encoded as single characters. The
3491/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3492/// encoded as single characters, followed by an identifier. Property types
3493/// are also encoded as a parametrized attribute. The characters used to encode
3494/// these attributes are defined by the following enumeration:
3495/// @code
3496/// enum PropertyAttributes {
3497/// kPropertyReadOnly = 'R',   // property is read-only.
3498/// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
3499/// kPropertyByref = '&',  // property is a reference to the value last assigned
3500/// kPropertyDynamic = 'D',    // property is dynamic
3501/// kPropertyGetter = 'G',     // followed by getter selector name
3502/// kPropertySetter = 'S',     // followed by setter selector name
3503/// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
3504/// kPropertyType = 't'              // followed by old-style type encoding.
3505/// kPropertyWeak = 'W'              // 'weak' property
3506/// kPropertyStrong = 'P'            // property GC'able
3507/// kPropertyNonAtomic = 'N'         // property non-atomic
3508/// };
3509/// @endcode
3510void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
3511                                                const Decl *Container,
3512                                                std::string& S) {
3513  // Collect information from the property implementation decl(s).
3514  bool Dynamic = false;
3515  ObjCPropertyImplDecl *SynthesizePID = 0;
3516
3517  // FIXME: Duplicated code due to poor abstraction.
3518  if (Container) {
3519    if (const ObjCCategoryImplDecl *CID =
3520        dyn_cast<ObjCCategoryImplDecl>(Container)) {
3521      for (ObjCCategoryImplDecl::propimpl_iterator
3522             i = CID->propimpl_begin(), e = CID->propimpl_end();
3523           i != e; ++i) {
3524        ObjCPropertyImplDecl *PID = *i;
3525        if (PID->getPropertyDecl() == PD) {
3526          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3527            Dynamic = true;
3528          } else {
3529            SynthesizePID = PID;
3530          }
3531        }
3532      }
3533    } else {
3534      const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
3535      for (ObjCCategoryImplDecl::propimpl_iterator
3536             i = OID->propimpl_begin(), e = OID->propimpl_end();
3537           i != e; ++i) {
3538        ObjCPropertyImplDecl *PID = *i;
3539        if (PID->getPropertyDecl() == PD) {
3540          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3541            Dynamic = true;
3542          } else {
3543            SynthesizePID = PID;
3544          }
3545        }
3546      }
3547    }
3548  }
3549
3550  // FIXME: This is not very efficient.
3551  S = "T";
3552
3553  // Encode result type.
3554  // GCC has some special rules regarding encoding of properties which
3555  // closely resembles encoding of ivars.
3556  getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
3557                             true /* outermost type */,
3558                             true /* encoding for property */);
3559
3560  if (PD->isReadOnly()) {
3561    S += ",R";
3562  } else {
3563    switch (PD->getSetterKind()) {
3564    case ObjCPropertyDecl::Assign: break;
3565    case ObjCPropertyDecl::Copy:   S += ",C"; break;
3566    case ObjCPropertyDecl::Retain: S += ",&"; break;
3567    }
3568  }
3569
3570  // It really isn't clear at all what this means, since properties
3571  // are "dynamic by default".
3572  if (Dynamic)
3573    S += ",D";
3574
3575  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3576    S += ",N";
3577
3578  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3579    S += ",G";
3580    S += PD->getGetterName().getAsString();
3581  }
3582
3583  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3584    S += ",S";
3585    S += PD->getSetterName().getAsString();
3586  }
3587
3588  if (SynthesizePID) {
3589    const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3590    S += ",V";
3591    S += OID->getNameAsString();
3592  }
3593
3594  // FIXME: OBJCGC: weak & strong
3595}
3596
3597/// getLegacyIntegralTypeEncoding -
3598/// Another legacy compatibility encoding: 32-bit longs are encoded as
3599/// 'l' or 'L' , but not always.  For typedefs, we need to use
3600/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3601///
3602void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
3603  if (isa<TypedefType>(PointeeTy.getTypePtr())) {
3604    if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
3605      if (BT->getKind() == BuiltinType::ULong &&
3606          ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
3607        PointeeTy = UnsignedIntTy;
3608      else
3609        if (BT->getKind() == BuiltinType::Long &&
3610            ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
3611          PointeeTy = IntTy;
3612    }
3613  }
3614}
3615
3616void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
3617                                        const FieldDecl *Field) {
3618  // We follow the behavior of gcc, expanding structures which are
3619  // directly pointed to, and expanding embedded structures. Note that
3620  // these rules are sufficient to prevent recursive encoding of the
3621  // same type.
3622  getObjCEncodingForTypeImpl(T, S, true, true, Field,
3623                             true /* outermost type */);
3624}
3625
3626static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3627    switch (T->getAs<BuiltinType>()->getKind()) {
3628    default: assert(0 && "Unhandled builtin type kind");
3629    case BuiltinType::Void:       return 'v';
3630    case BuiltinType::Bool:       return 'B';
3631    case BuiltinType::Char_U:
3632    case BuiltinType::UChar:      return 'C';
3633    case BuiltinType::UShort:     return 'S';
3634    case BuiltinType::UInt:       return 'I';
3635    case BuiltinType::ULong:
3636        return
3637          (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3638    case BuiltinType::UInt128:    return 'T';
3639    case BuiltinType::ULongLong:  return 'Q';
3640    case BuiltinType::Char_S:
3641    case BuiltinType::SChar:      return 'c';
3642    case BuiltinType::Short:      return 's';
3643    case BuiltinType::WChar:
3644    case BuiltinType::Int:        return 'i';
3645    case BuiltinType::Long:
3646      return
3647        (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3648    case BuiltinType::LongLong:   return 'q';
3649    case BuiltinType::Int128:     return 't';
3650    case BuiltinType::Float:      return 'f';
3651    case BuiltinType::Double:     return 'd';
3652    case BuiltinType::LongDouble: return 'd';
3653    }
3654}
3655
3656static void EncodeBitField(const ASTContext *Context, std::string& S,
3657                           QualType T, const FieldDecl *FD) {
3658  const Expr *E = FD->getBitWidth();
3659  assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3660  ASTContext *Ctx = const_cast<ASTContext*>(Context);
3661  S += 'b';
3662  // The NeXT runtime encodes bit fields as b followed by the number of bits.
3663  // The GNU runtime requires more information; bitfields are encoded as b,
3664  // then the offset (in bits) of the first element, then the type of the
3665  // bitfield, then the size in bits.  For example, in this structure:
3666  //
3667  // struct
3668  // {
3669  //    int integer;
3670  //    int flags:2;
3671  // };
3672  // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3673  // runtime, but b32i2 for the GNU runtime.  The reason for this extra
3674  // information is not especially sensible, but we're stuck with it for
3675  // compatibility with GCC, although providing it breaks anything that
3676  // actually uses runtime introspection and wants to work on both runtimes...
3677  if (!Ctx->getLangOptions().NeXTRuntime) {
3678    const RecordDecl *RD = FD->getParent();
3679    const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3680    // FIXME: This same linear search is also used in ExprConstant - it might
3681    // be better if the FieldDecl stored its offset.  We'd be increasing the
3682    // size of the object slightly, but saving some time every time it is used.
3683    unsigned i = 0;
3684    for (RecordDecl::field_iterator Field = RD->field_begin(),
3685                                 FieldEnd = RD->field_end();
3686         Field != FieldEnd; (void)++Field, ++i) {
3687      if (*Field == FD)
3688        break;
3689    }
3690    S += llvm::utostr(RL.getFieldOffset(i));
3691    S += ObjCEncodingForPrimitiveKind(Context, T);
3692  }
3693  unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
3694  S += llvm::utostr(N);
3695}
3696
3697// FIXME: Use SmallString for accumulating string.
3698void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3699                                            bool ExpandPointedToStructures,
3700                                            bool ExpandStructures,
3701                                            const FieldDecl *FD,
3702                                            bool OutermostType,
3703                                            bool EncodingProperty) {
3704  if (T->getAs<BuiltinType>()) {
3705    if (FD && FD->isBitField())
3706      return EncodeBitField(this, S, T, FD);
3707    S += ObjCEncodingForPrimitiveKind(this, T);
3708    return;
3709  }
3710
3711  if (const ComplexType *CT = T->getAs<ComplexType>()) {
3712    S += 'j';
3713    getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
3714                               false);
3715    return;
3716  }
3717
3718  // encoding for pointer or r3eference types.
3719  QualType PointeeTy;
3720  if (const PointerType *PT = T->getAs<PointerType>()) {
3721    if (PT->isObjCSelType()) {
3722      S += ':';
3723      return;
3724    }
3725    PointeeTy = PT->getPointeeType();
3726  }
3727  else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3728    PointeeTy = RT->getPointeeType();
3729  if (!PointeeTy.isNull()) {
3730    bool isReadOnly = false;
3731    // For historical/compatibility reasons, the read-only qualifier of the
3732    // pointee gets emitted _before_ the '^'.  The read-only qualifier of
3733    // the pointer itself gets ignored, _unless_ we are looking at a typedef!
3734    // Also, do not emit the 'r' for anything but the outermost type!
3735    if (isa<TypedefType>(T.getTypePtr())) {
3736      if (OutermostType && T.isConstQualified()) {
3737        isReadOnly = true;
3738        S += 'r';
3739      }
3740    } else if (OutermostType) {
3741      QualType P = PointeeTy;
3742      while (P->getAs<PointerType>())
3743        P = P->getAs<PointerType>()->getPointeeType();
3744      if (P.isConstQualified()) {
3745        isReadOnly = true;
3746        S += 'r';
3747      }
3748    }
3749    if (isReadOnly) {
3750      // Another legacy compatibility encoding. Some ObjC qualifier and type
3751      // combinations need to be rearranged.
3752      // Rewrite "in const" from "nr" to "rn"
3753      if (llvm::StringRef(S).endswith("nr"))
3754        S.replace(S.end()-2, S.end(), "rn");
3755    }
3756
3757    if (PointeeTy->isCharType()) {
3758      // char pointer types should be encoded as '*' unless it is a
3759      // type that has been typedef'd to 'BOOL'.
3760      if (!isTypeTypedefedAsBOOL(PointeeTy)) {
3761        S += '*';
3762        return;
3763      }
3764    } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
3765      // GCC binary compat: Need to convert "struct objc_class *" to "#".
3766      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3767        S += '#';
3768        return;
3769      }
3770      // GCC binary compat: Need to convert "struct objc_object *" to "@".
3771      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3772        S += '@';
3773        return;
3774      }
3775      // fall through...
3776    }
3777    S += '^';
3778    getLegacyIntegralTypeEncoding(PointeeTy);
3779
3780    getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
3781                               NULL);
3782    return;
3783  }
3784
3785  if (const ArrayType *AT =
3786      // Ignore type qualifiers etc.
3787        dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
3788    if (isa<IncompleteArrayType>(AT)) {
3789      // Incomplete arrays are encoded as a pointer to the array element.
3790      S += '^';
3791
3792      getObjCEncodingForTypeImpl(AT->getElementType(), S,
3793                                 false, ExpandStructures, FD);
3794    } else {
3795      S += '[';
3796
3797      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3798        S += llvm::utostr(CAT->getSize().getZExtValue());
3799      else {
3800        //Variable length arrays are encoded as a regular array with 0 elements.
3801        assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3802        S += '0';
3803      }
3804
3805      getObjCEncodingForTypeImpl(AT->getElementType(), S,
3806                                 false, ExpandStructures, FD);
3807      S += ']';
3808    }
3809    return;
3810  }
3811
3812  if (T->getAs<FunctionType>()) {
3813    S += '?';
3814    return;
3815  }
3816
3817  if (const RecordType *RTy = T->getAs<RecordType>()) {
3818    RecordDecl *RDecl = RTy->getDecl();
3819    S += RDecl->isUnion() ? '(' : '{';
3820    // Anonymous structures print as '?'
3821    if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3822      S += II->getName();
3823      if (ClassTemplateSpecializationDecl *Spec
3824          = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3825        const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3826        std::string TemplateArgsStr
3827          = TemplateSpecializationType::PrintTemplateArgumentList(
3828                                            TemplateArgs.getFlatArgumentList(),
3829                                            TemplateArgs.flat_size(),
3830                                            (*this).PrintingPolicy);
3831
3832        S += TemplateArgsStr;
3833      }
3834    } else {
3835      S += '?';
3836    }
3837    if (ExpandStructures) {
3838      S += '=';
3839      for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3840                                   FieldEnd = RDecl->field_end();
3841           Field != FieldEnd; ++Field) {
3842        if (FD) {
3843          S += '"';
3844          S += Field->getNameAsString();
3845          S += '"';
3846        }
3847
3848        // Special case bit-fields.
3849        if (Field->isBitField()) {
3850          getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
3851                                     (*Field));
3852        } else {
3853          QualType qt = Field->getType();
3854          getLegacyIntegralTypeEncoding(qt);
3855          getObjCEncodingForTypeImpl(qt, S, false, true,
3856                                     FD);
3857        }
3858      }
3859    }
3860    S += RDecl->isUnion() ? ')' : '}';
3861    return;
3862  }
3863
3864  if (T->isEnumeralType()) {
3865    if (FD && FD->isBitField())
3866      EncodeBitField(this, S, T, FD);
3867    else
3868      S += 'i';
3869    return;
3870  }
3871
3872  if (T->isBlockPointerType()) {
3873    S += "@?"; // Unlike a pointer-to-function, which is "^?".
3874    return;
3875  }
3876
3877  // Ignore protocol qualifiers when mangling at this level.
3878  if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3879    T = OT->getBaseType();
3880
3881  if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
3882    // @encode(class_name)
3883    ObjCInterfaceDecl *OI = OIT->getDecl();
3884    S += '{';
3885    const IdentifierInfo *II = OI->getIdentifier();
3886    S += II->getName();
3887    S += '=';
3888    llvm::SmallVector<FieldDecl*, 32> RecFields;
3889    CollectObjCIvars(OI, RecFields);
3890    for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
3891      if (RecFields[i]->isBitField())
3892        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
3893                                   RecFields[i]);
3894      else
3895        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
3896                                   FD);
3897    }
3898    S += '}';
3899    return;
3900  }
3901
3902  if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
3903    if (OPT->isObjCIdType()) {
3904      S += '@';
3905      return;
3906    }
3907
3908    if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3909      // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3910      // Since this is a binary compatibility issue, need to consult with runtime
3911      // folks. Fortunately, this is a *very* obsure construct.
3912      S += '#';
3913      return;
3914    }
3915
3916    if (OPT->isObjCQualifiedIdType()) {
3917      getObjCEncodingForTypeImpl(getObjCIdType(), S,
3918                                 ExpandPointedToStructures,
3919                                 ExpandStructures, FD);
3920      if (FD || EncodingProperty) {
3921        // Note that we do extended encoding of protocol qualifer list
3922        // Only when doing ivar or property encoding.
3923        S += '"';
3924        for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3925             E = OPT->qual_end(); I != E; ++I) {
3926          S += '<';
3927          S += (*I)->getNameAsString();
3928          S += '>';
3929        }
3930        S += '"';
3931      }
3932      return;
3933    }
3934
3935    QualType PointeeTy = OPT->getPointeeType();
3936    if (!EncodingProperty &&
3937        isa<TypedefType>(PointeeTy.getTypePtr())) {
3938      // Another historical/compatibility reason.
3939      // We encode the underlying type which comes out as
3940      // {...};
3941      S += '^';
3942      getObjCEncodingForTypeImpl(PointeeTy, S,
3943                                 false, ExpandPointedToStructures,
3944                                 NULL);
3945      return;
3946    }
3947
3948    S += '@';
3949    if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
3950      S += '"';
3951      S += OPT->getInterfaceDecl()->getIdentifier()->getName();
3952      for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3953           E = OPT->qual_end(); I != E; ++I) {
3954        S += '<';
3955        S += (*I)->getNameAsString();
3956        S += '>';
3957      }
3958      S += '"';
3959    }
3960    return;
3961  }
3962
3963  // gcc just blithely ignores member pointers.
3964  // TODO: maybe there should be a mangling for these
3965  if (T->getAs<MemberPointerType>())
3966    return;
3967
3968  assert(0 && "@encode for type not implemented!");
3969}
3970
3971void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
3972                                                 std::string& S) const {
3973  if (QT & Decl::OBJC_TQ_In)
3974    S += 'n';
3975  if (QT & Decl::OBJC_TQ_Inout)
3976    S += 'N';
3977  if (QT & Decl::OBJC_TQ_Out)
3978    S += 'o';
3979  if (QT & Decl::OBJC_TQ_Bycopy)
3980    S += 'O';
3981  if (QT & Decl::OBJC_TQ_Byref)
3982    S += 'R';
3983  if (QT & Decl::OBJC_TQ_Oneway)
3984    S += 'V';
3985}
3986
3987void ASTContext::setBuiltinVaListType(QualType T) {
3988  assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
3989
3990  BuiltinVaListType = T;
3991}
3992
3993void ASTContext::setObjCIdType(QualType T) {
3994  ObjCIdTypedefType = T;
3995}
3996
3997void ASTContext::setObjCSelType(QualType T) {
3998  ObjCSelTypedefType = T;
3999}
4000
4001void ASTContext::setObjCProtoType(QualType QT) {
4002  ObjCProtoType = QT;
4003}
4004
4005void ASTContext::setObjCClassType(QualType T) {
4006  ObjCClassTypedefType = T;
4007}
4008
4009void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
4010  assert(ObjCConstantStringType.isNull() &&
4011         "'NSConstantString' type already set!");
4012
4013  ObjCConstantStringType = getObjCInterfaceType(Decl);
4014}
4015
4016/// \brief Retrieve the template name that corresponds to a non-empty
4017/// lookup.
4018TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4019                                                   UnresolvedSetIterator End) {
4020  unsigned size = End - Begin;
4021  assert(size > 1 && "set is not overloaded!");
4022
4023  void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4024                          size * sizeof(FunctionTemplateDecl*));
4025  OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4026
4027  NamedDecl **Storage = OT->getStorage();
4028  for (UnresolvedSetIterator I = Begin; I != End; ++I) {
4029    NamedDecl *D = *I;
4030    assert(isa<FunctionTemplateDecl>(D) ||
4031           (isa<UsingShadowDecl>(D) &&
4032            isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4033    *Storage++ = D;
4034  }
4035
4036  return TemplateName(OT);
4037}
4038
4039/// \brief Retrieve the template name that represents a qualified
4040/// template name such as \c std::vector.
4041TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4042                                                  bool TemplateKeyword,
4043                                                  TemplateDecl *Template) {
4044  // FIXME: Canonicalization?
4045  llvm::FoldingSetNodeID ID;
4046  QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4047
4048  void *InsertPos = 0;
4049  QualifiedTemplateName *QTN =
4050    QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4051  if (!QTN) {
4052    QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4053    QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4054  }
4055
4056  return TemplateName(QTN);
4057}
4058
4059/// \brief Retrieve the template name that represents a dependent
4060/// template name such as \c MetaFun::template apply.
4061TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4062                                                  const IdentifierInfo *Name) {
4063  assert((!NNS || NNS->isDependent()) &&
4064         "Nested name specifier must be dependent");
4065
4066  llvm::FoldingSetNodeID ID;
4067  DependentTemplateName::Profile(ID, NNS, Name);
4068
4069  void *InsertPos = 0;
4070  DependentTemplateName *QTN =
4071    DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4072
4073  if (QTN)
4074    return TemplateName(QTN);
4075
4076  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4077  if (CanonNNS == NNS) {
4078    QTN = new (*this,4) DependentTemplateName(NNS, Name);
4079  } else {
4080    TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4081    QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
4082    DependentTemplateName *CheckQTN =
4083      DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4084    assert(!CheckQTN && "Dependent type name canonicalization broken");
4085    (void)CheckQTN;
4086  }
4087
4088  DependentTemplateNames.InsertNode(QTN, InsertPos);
4089  return TemplateName(QTN);
4090}
4091
4092/// \brief Retrieve the template name that represents a dependent
4093/// template name such as \c MetaFun::template operator+.
4094TemplateName
4095ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4096                                     OverloadedOperatorKind Operator) {
4097  assert((!NNS || NNS->isDependent()) &&
4098         "Nested name specifier must be dependent");
4099
4100  llvm::FoldingSetNodeID ID;
4101  DependentTemplateName::Profile(ID, NNS, Operator);
4102
4103  void *InsertPos = 0;
4104  DependentTemplateName *QTN
4105    = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4106
4107  if (QTN)
4108    return TemplateName(QTN);
4109
4110  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4111  if (CanonNNS == NNS) {
4112    QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4113  } else {
4114    TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4115    QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
4116
4117    DependentTemplateName *CheckQTN
4118      = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4119    assert(!CheckQTN && "Dependent template name canonicalization broken");
4120    (void)CheckQTN;
4121  }
4122
4123  DependentTemplateNames.InsertNode(QTN, InsertPos);
4124  return TemplateName(QTN);
4125}
4126
4127/// getFromTargetType - Given one of the integer types provided by
4128/// TargetInfo, produce the corresponding type. The unsigned @p Type
4129/// is actually a value of type @c TargetInfo::IntType.
4130CanQualType ASTContext::getFromTargetType(unsigned Type) const {
4131  switch (Type) {
4132  case TargetInfo::NoInt: return CanQualType();
4133  case TargetInfo::SignedShort: return ShortTy;
4134  case TargetInfo::UnsignedShort: return UnsignedShortTy;
4135  case TargetInfo::SignedInt: return IntTy;
4136  case TargetInfo::UnsignedInt: return UnsignedIntTy;
4137  case TargetInfo::SignedLong: return LongTy;
4138  case TargetInfo::UnsignedLong: return UnsignedLongTy;
4139  case TargetInfo::SignedLongLong: return LongLongTy;
4140  case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4141  }
4142
4143  assert(false && "Unhandled TargetInfo::IntType value");
4144  return CanQualType();
4145}
4146
4147//===----------------------------------------------------------------------===//
4148//                        Type Predicates.
4149//===----------------------------------------------------------------------===//
4150
4151/// isObjCNSObjectType - Return true if this is an NSObject object using
4152/// NSObject attribute on a c-style pointer type.
4153/// FIXME - Make it work directly on types.
4154/// FIXME: Move to Type.
4155///
4156bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4157  if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4158    if (TypedefDecl *TD = TDT->getDecl())
4159      if (TD->getAttr<ObjCNSObjectAttr>())
4160        return true;
4161  }
4162  return false;
4163}
4164
4165/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4166/// garbage collection attribute.
4167///
4168Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4169  Qualifiers::GC GCAttrs = Qualifiers::GCNone;
4170  if (getLangOptions().ObjC1 &&
4171      getLangOptions().getGCMode() != LangOptions::NonGC) {
4172    GCAttrs = Ty.getObjCGCAttr();
4173    // Default behavious under objective-c's gc is for objective-c pointers
4174    // (or pointers to them) be treated as though they were declared
4175    // as __strong.
4176    if (GCAttrs == Qualifiers::GCNone) {
4177      if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4178        GCAttrs = Qualifiers::Strong;
4179      else if (Ty->isPointerType())
4180        return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4181    }
4182    // Non-pointers have none gc'able attribute regardless of the attribute
4183    // set on them.
4184    else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
4185      return Qualifiers::GCNone;
4186  }
4187  return GCAttrs;
4188}
4189
4190//===----------------------------------------------------------------------===//
4191//                        Type Compatibility Testing
4192//===----------------------------------------------------------------------===//
4193
4194/// areCompatVectorTypes - Return true if the two specified vector types are
4195/// compatible.
4196static bool areCompatVectorTypes(const VectorType *LHS,
4197                                 const VectorType *RHS) {
4198  assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
4199  return LHS->getElementType() == RHS->getElementType() &&
4200         LHS->getNumElements() == RHS->getNumElements();
4201}
4202
4203//===----------------------------------------------------------------------===//
4204// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4205//===----------------------------------------------------------------------===//
4206
4207/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4208/// inheritance hierarchy of 'rProto'.
4209bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4210                                                ObjCProtocolDecl *rProto) {
4211  if (lProto == rProto)
4212    return true;
4213  for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4214       E = rProto->protocol_end(); PI != E; ++PI)
4215    if (ProtocolCompatibleWithProtocol(lProto, *PI))
4216      return true;
4217  return false;
4218}
4219
4220/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4221/// return true if lhs's protocols conform to rhs's protocol; false
4222/// otherwise.
4223bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4224  if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4225    return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4226  return false;
4227}
4228
4229/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4230/// ObjCQualifiedIDType.
4231bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4232                                                   bool compare) {
4233  // Allow id<P..> and an 'id' or void* type in all cases.
4234  if (lhs->isVoidPointerType() ||
4235      lhs->isObjCIdType() || lhs->isObjCClassType())
4236    return true;
4237  else if (rhs->isVoidPointerType() ||
4238           rhs->isObjCIdType() || rhs->isObjCClassType())
4239    return true;
4240
4241  if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
4242    const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4243
4244    if (!rhsOPT) return false;
4245
4246    if (rhsOPT->qual_empty()) {
4247      // If the RHS is a unqualified interface pointer "NSString*",
4248      // make sure we check the class hierarchy.
4249      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4250        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4251             E = lhsQID->qual_end(); I != E; ++I) {
4252          // when comparing an id<P> on lhs with a static type on rhs,
4253          // see if static class implements all of id's protocols, directly or
4254          // through its super class and categories.
4255          if (!rhsID->ClassImplementsProtocol(*I, true))
4256            return false;
4257        }
4258      }
4259      // If there are no qualifiers and no interface, we have an 'id'.
4260      return true;
4261    }
4262    // Both the right and left sides have qualifiers.
4263    for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4264         E = lhsQID->qual_end(); I != E; ++I) {
4265      ObjCProtocolDecl *lhsProto = *I;
4266      bool match = false;
4267
4268      // when comparing an id<P> on lhs with a static type on rhs,
4269      // see if static class implements all of id's protocols, directly or
4270      // through its super class and categories.
4271      for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4272           E = rhsOPT->qual_end(); J != E; ++J) {
4273        ObjCProtocolDecl *rhsProto = *J;
4274        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4275            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4276          match = true;
4277          break;
4278        }
4279      }
4280      // If the RHS is a qualified interface pointer "NSString<P>*",
4281      // make sure we check the class hierarchy.
4282      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4283        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4284             E = lhsQID->qual_end(); I != E; ++I) {
4285          // when comparing an id<P> on lhs with a static type on rhs,
4286          // see if static class implements all of id's protocols, directly or
4287          // through its super class and categories.
4288          if (rhsID->ClassImplementsProtocol(*I, true)) {
4289            match = true;
4290            break;
4291          }
4292        }
4293      }
4294      if (!match)
4295        return false;
4296    }
4297
4298    return true;
4299  }
4300
4301  const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4302  assert(rhsQID && "One of the LHS/RHS should be id<x>");
4303
4304  if (const ObjCObjectPointerType *lhsOPT =
4305        lhs->getAsObjCInterfacePointerType()) {
4306    if (lhsOPT->qual_empty()) {
4307      bool match = false;
4308      if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4309        for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4310             E = rhsQID->qual_end(); I != E; ++I) {
4311          // when comparing an id<P> on lhs with a static type on rhs,
4312          // see if static class implements all of id's protocols, directly or
4313          // through its super class and categories.
4314          if (lhsID->ClassImplementsProtocol(*I, true)) {
4315            match = true;
4316            break;
4317          }
4318        }
4319        if (!match)
4320          return false;
4321      }
4322      return true;
4323    }
4324    // Both the right and left sides have qualifiers.
4325    for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4326         E = lhsOPT->qual_end(); I != E; ++I) {
4327      ObjCProtocolDecl *lhsProto = *I;
4328      bool match = false;
4329
4330      // when comparing an id<P> on lhs with a static type on rhs,
4331      // see if static class implements all of id's protocols, directly or
4332      // through its super class and categories.
4333      for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4334           E = rhsQID->qual_end(); J != E; ++J) {
4335        ObjCProtocolDecl *rhsProto = *J;
4336        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4337            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4338          match = true;
4339          break;
4340        }
4341      }
4342      if (!match)
4343        return false;
4344    }
4345    return true;
4346  }
4347  return false;
4348}
4349
4350/// canAssignObjCInterfaces - Return true if the two interface types are
4351/// compatible for assignment from RHS to LHS.  This handles validation of any
4352/// protocol qualifiers on the LHS or RHS.
4353///
4354bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4355                                         const ObjCObjectPointerType *RHSOPT) {
4356  const ObjCObjectType* LHS = LHSOPT->getObjectType();
4357  const ObjCObjectType* RHS = RHSOPT->getObjectType();
4358
4359  // If either type represents the built-in 'id' or 'Class' types, return true.
4360  if (LHS->isObjCUnqualifiedIdOrClass() ||
4361      RHS->isObjCUnqualifiedIdOrClass())
4362    return true;
4363
4364  if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
4365    return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4366                                             QualType(RHSOPT,0),
4367                                             false);
4368
4369  // If we have 2 user-defined types, fall into that path.
4370  if (LHS->getInterface() && RHS->getInterface())
4371    return canAssignObjCInterfaces(LHS, RHS);
4372
4373  return false;
4374}
4375
4376/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4377/// for providing type-safty for objective-c pointers used to pass/return
4378/// arguments in block literals. When passed as arguments, passing 'A*' where
4379/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4380/// not OK. For the return type, the opposite is not OK.
4381bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4382                                         const ObjCObjectPointerType *LHSOPT,
4383                                         const ObjCObjectPointerType *RHSOPT) {
4384  if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
4385    return true;
4386
4387  if (LHSOPT->isObjCBuiltinType()) {
4388    return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4389  }
4390
4391  if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
4392    return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4393                                             QualType(RHSOPT,0),
4394                                             false);
4395
4396  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4397  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4398  if (LHS && RHS)  { // We have 2 user-defined types.
4399    if (LHS != RHS) {
4400      if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4401        return false;
4402      if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4403        return true;
4404    }
4405    else
4406      return true;
4407  }
4408  return false;
4409}
4410
4411/// getIntersectionOfProtocols - This routine finds the intersection of set
4412/// of protocols inherited from two distinct objective-c pointer objects.
4413/// It is used to build composite qualifier list of the composite type of
4414/// the conditional expression involving two objective-c pointer objects.
4415static
4416void getIntersectionOfProtocols(ASTContext &Context,
4417                                const ObjCObjectPointerType *LHSOPT,
4418                                const ObjCObjectPointerType *RHSOPT,
4419      llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4420
4421  const ObjCObjectType* LHS = LHSOPT->getObjectType();
4422  const ObjCObjectType* RHS = RHSOPT->getObjectType();
4423  assert(LHS->getInterface() && "LHS must have an interface base");
4424  assert(RHS->getInterface() && "RHS must have an interface base");
4425
4426  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4427  unsigned LHSNumProtocols = LHS->getNumProtocols();
4428  if (LHSNumProtocols > 0)
4429    InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4430  else {
4431    llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4432    Context.CollectInheritedProtocols(LHS->getInterface(),
4433                                      LHSInheritedProtocols);
4434    InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4435                                LHSInheritedProtocols.end());
4436  }
4437
4438  unsigned RHSNumProtocols = RHS->getNumProtocols();
4439  if (RHSNumProtocols > 0) {
4440    ObjCProtocolDecl **RHSProtocols =
4441      const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
4442    for (unsigned i = 0; i < RHSNumProtocols; ++i)
4443      if (InheritedProtocolSet.count(RHSProtocols[i]))
4444        IntersectionOfProtocols.push_back(RHSProtocols[i]);
4445  }
4446  else {
4447    llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
4448    Context.CollectInheritedProtocols(RHS->getInterface(),
4449                                      RHSInheritedProtocols);
4450    for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4451         RHSInheritedProtocols.begin(),
4452         E = RHSInheritedProtocols.end(); I != E; ++I)
4453      if (InheritedProtocolSet.count((*I)))
4454        IntersectionOfProtocols.push_back((*I));
4455  }
4456}
4457
4458/// areCommonBaseCompatible - Returns common base class of the two classes if
4459/// one found. Note that this is O'2 algorithm. But it will be called as the
4460/// last type comparison in a ?-exp of ObjC pointer types before a
4461/// warning is issued. So, its invokation is extremely rare.
4462QualType ASTContext::areCommonBaseCompatible(
4463                                          const ObjCObjectPointerType *Lptr,
4464                                          const ObjCObjectPointerType *Rptr) {
4465  const ObjCObjectType *LHS = Lptr->getObjectType();
4466  const ObjCObjectType *RHS = Rptr->getObjectType();
4467  const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4468  const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4469  if (!LDecl || !RDecl)
4470    return QualType();
4471
4472  while ((LDecl = LDecl->getSuperClass())) {
4473    LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
4474    if (canAssignObjCInterfaces(LHS, RHS)) {
4475      llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4476      getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4477
4478      QualType Result = QualType(LHS, 0);
4479      if (!Protocols.empty())
4480        Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4481      Result = getObjCObjectPointerType(Result);
4482      return Result;
4483    }
4484  }
4485
4486  return QualType();
4487}
4488
4489bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4490                                         const ObjCObjectType *RHS) {
4491  assert(LHS->getInterface() && "LHS is not an interface type");
4492  assert(RHS->getInterface() && "RHS is not an interface type");
4493
4494  // Verify that the base decls are compatible: the RHS must be a subclass of
4495  // the LHS.
4496  if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
4497    return false;
4498
4499  // RHS must have a superset of the protocols in the LHS.  If the LHS is not
4500  // protocol qualified at all, then we are good.
4501  if (LHS->getNumProtocols() == 0)
4502    return true;
4503
4504  // Okay, we know the LHS has protocol qualifiers.  If the RHS doesn't, then it
4505  // isn't a superset.
4506  if (RHS->getNumProtocols() == 0)
4507    return true;  // FIXME: should return false!
4508
4509  for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4510                                     LHSPE = LHS->qual_end();
4511       LHSPI != LHSPE; LHSPI++) {
4512    bool RHSImplementsProtocol = false;
4513
4514    // If the RHS doesn't implement the protocol on the left, the types
4515    // are incompatible.
4516    for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4517                                       RHSPE = RHS->qual_end();
4518         RHSPI != RHSPE; RHSPI++) {
4519      if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
4520        RHSImplementsProtocol = true;
4521        break;
4522      }
4523    }
4524    // FIXME: For better diagnostics, consider passing back the protocol name.
4525    if (!RHSImplementsProtocol)
4526      return false;
4527  }
4528  // The RHS implements all protocols listed on the LHS.
4529  return true;
4530}
4531
4532bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4533  // get the "pointed to" types
4534  const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4535  const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
4536
4537  if (!LHSOPT || !RHSOPT)
4538    return false;
4539
4540  return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4541         canAssignObjCInterfaces(RHSOPT, LHSOPT);
4542}
4543
4544/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
4545/// both shall have the identically qualified version of a compatible type.
4546/// C99 6.2.7p1: Two types have compatible types if their types are the
4547/// same. See 6.7.[2,3,5] for additional rules.
4548bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
4549  if (getLangOptions().CPlusPlus)
4550    return hasSameType(LHS, RHS);
4551
4552  return !mergeTypes(LHS, RHS).isNull();
4553}
4554
4555bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4556  return !mergeTypes(LHS, RHS, true).isNull();
4557}
4558
4559QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
4560                                        bool OfBlockPointer) {
4561  const FunctionType *lbase = lhs->getAs<FunctionType>();
4562  const FunctionType *rbase = rhs->getAs<FunctionType>();
4563  const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4564  const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
4565  bool allLTypes = true;
4566  bool allRTypes = true;
4567
4568  // Check return type
4569  QualType retType;
4570  if (OfBlockPointer)
4571    retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true);
4572  else
4573   retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
4574  if (retType.isNull()) return QualType();
4575  if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
4576    allLTypes = false;
4577  if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
4578    allRTypes = false;
4579  // FIXME: double check this
4580  // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4581  //                           rbase->getRegParmAttr() != 0 &&
4582  //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
4583  FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4584  FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
4585  unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4586      lbaseInfo.getRegParm();
4587  bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4588  if (NoReturn != lbaseInfo.getNoReturn() ||
4589      RegParm != lbaseInfo.getRegParm())
4590    allLTypes = false;
4591  if (NoReturn != rbaseInfo.getNoReturn() ||
4592      RegParm != rbaseInfo.getRegParm())
4593    allRTypes = false;
4594  CallingConv lcc = lbaseInfo.getCC();
4595  CallingConv rcc = rbaseInfo.getCC();
4596  // Compatible functions must have compatible calling conventions
4597  if (!isSameCallConv(lcc, rcc))
4598    return QualType();
4599
4600  if (lproto && rproto) { // two C99 style function prototypes
4601    assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4602           "C++ shouldn't be here");
4603    unsigned lproto_nargs = lproto->getNumArgs();
4604    unsigned rproto_nargs = rproto->getNumArgs();
4605
4606    // Compatible functions must have the same number of arguments
4607    if (lproto_nargs != rproto_nargs)
4608      return QualType();
4609
4610    // Variadic and non-variadic functions aren't compatible
4611    if (lproto->isVariadic() != rproto->isVariadic())
4612      return QualType();
4613
4614    if (lproto->getTypeQuals() != rproto->getTypeQuals())
4615      return QualType();
4616
4617    // Check argument compatibility
4618    llvm::SmallVector<QualType, 10> types;
4619    for (unsigned i = 0; i < lproto_nargs; i++) {
4620      QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4621      QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4622      QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer);
4623      if (argtype.isNull()) return QualType();
4624      types.push_back(argtype);
4625      if (getCanonicalType(argtype) != getCanonicalType(largtype))
4626        allLTypes = false;
4627      if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4628        allRTypes = false;
4629    }
4630    if (allLTypes) return lhs;
4631    if (allRTypes) return rhs;
4632    return getFunctionType(retType, types.begin(), types.size(),
4633                           lproto->isVariadic(), lproto->getTypeQuals(),
4634                           false, false, 0, 0,
4635                           FunctionType::ExtInfo(NoReturn, RegParm, lcc));
4636  }
4637
4638  if (lproto) allRTypes = false;
4639  if (rproto) allLTypes = false;
4640
4641  const FunctionProtoType *proto = lproto ? lproto : rproto;
4642  if (proto) {
4643    assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
4644    if (proto->isVariadic()) return QualType();
4645    // Check that the types are compatible with the types that
4646    // would result from default argument promotions (C99 6.7.5.3p15).
4647    // The only types actually affected are promotable integer
4648    // types and floats, which would be passed as a different
4649    // type depending on whether the prototype is visible.
4650    unsigned proto_nargs = proto->getNumArgs();
4651    for (unsigned i = 0; i < proto_nargs; ++i) {
4652      QualType argTy = proto->getArgType(i);
4653
4654      // Look at the promotion type of enum types, since that is the type used
4655      // to pass enum values.
4656      if (const EnumType *Enum = argTy->getAs<EnumType>())
4657        argTy = Enum->getDecl()->getPromotionType();
4658
4659      if (argTy->isPromotableIntegerType() ||
4660          getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4661        return QualType();
4662    }
4663
4664    if (allLTypes) return lhs;
4665    if (allRTypes) return rhs;
4666    return getFunctionType(retType, proto->arg_type_begin(),
4667                           proto->getNumArgs(), proto->isVariadic(),
4668                           proto->getTypeQuals(),
4669                           false, false, 0, 0,
4670                           FunctionType::ExtInfo(NoReturn, RegParm, lcc));
4671  }
4672
4673  if (allLTypes) return lhs;
4674  if (allRTypes) return rhs;
4675  FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
4676  return getFunctionNoProtoType(retType, Info);
4677}
4678
4679QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
4680                                bool OfBlockPointer) {
4681  // C++ [expr]: If an expression initially has the type "reference to T", the
4682  // type is adjusted to "T" prior to any further analysis, the expression
4683  // designates the object or function denoted by the reference, and the
4684  // expression is an lvalue unless the reference is an rvalue reference and
4685  // the expression is a function call (possibly inside parentheses).
4686  assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4687  assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4688
4689  QualType LHSCan = getCanonicalType(LHS),
4690           RHSCan = getCanonicalType(RHS);
4691
4692  // If two types are identical, they are compatible.
4693  if (LHSCan == RHSCan)
4694    return LHS;
4695
4696  // If the qualifiers are different, the types aren't compatible... mostly.
4697  Qualifiers LQuals = LHSCan.getLocalQualifiers();
4698  Qualifiers RQuals = RHSCan.getLocalQualifiers();
4699  if (LQuals != RQuals) {
4700    // If any of these qualifiers are different, we have a type
4701    // mismatch.
4702    if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4703        LQuals.getAddressSpace() != RQuals.getAddressSpace())
4704      return QualType();
4705
4706    // Exactly one GC qualifier difference is allowed: __strong is
4707    // okay if the other type has no GC qualifier but is an Objective
4708    // C object pointer (i.e. implicitly strong by default).  We fix
4709    // this by pretending that the unqualified type was actually
4710    // qualified __strong.
4711    Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4712    Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4713    assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4714
4715    if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4716      return QualType();
4717
4718    if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4719      return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4720    }
4721    if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4722      return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4723    }
4724    return QualType();
4725  }
4726
4727  // Okay, qualifiers are equal.
4728
4729  Type::TypeClass LHSClass = LHSCan->getTypeClass();
4730  Type::TypeClass RHSClass = RHSCan->getTypeClass();
4731
4732  // We want to consider the two function types to be the same for these
4733  // comparisons, just force one to the other.
4734  if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4735  if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
4736
4737  // Same as above for arrays
4738  if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4739    LHSClass = Type::ConstantArray;
4740  if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4741    RHSClass = Type::ConstantArray;
4742
4743  // ObjCInterfaces are just specialized ObjCObjects.
4744  if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4745  if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4746
4747  // Canonicalize ExtVector -> Vector.
4748  if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4749  if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
4750
4751  // If the canonical type classes don't match.
4752  if (LHSClass != RHSClass) {
4753    // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
4754    // a signed integer type, or an unsigned integer type.
4755    // Compatibility is based on the underlying type, not the promotion
4756    // type.
4757    if (const EnumType* ETy = LHS->getAs<EnumType>()) {
4758      if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4759        return RHS;
4760    }
4761    if (const EnumType* ETy = RHS->getAs<EnumType>()) {
4762      if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4763        return LHS;
4764    }
4765
4766    return QualType();
4767  }
4768
4769  // The canonical type classes match.
4770  switch (LHSClass) {
4771#define TYPE(Class, Base)
4772#define ABSTRACT_TYPE(Class, Base)
4773#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
4774#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4775#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4776#include "clang/AST/TypeNodes.def"
4777    assert(false && "Non-canonical and dependent types shouldn't get here");
4778    return QualType();
4779
4780  case Type::LValueReference:
4781  case Type::RValueReference:
4782  case Type::MemberPointer:
4783    assert(false && "C++ should never be in mergeTypes");
4784    return QualType();
4785
4786  case Type::ObjCInterface:
4787  case Type::IncompleteArray:
4788  case Type::VariableArray:
4789  case Type::FunctionProto:
4790  case Type::ExtVector:
4791    assert(false && "Types are eliminated above");
4792    return QualType();
4793
4794  case Type::Pointer:
4795  {
4796    // Merge two pointer types, while trying to preserve typedef info
4797    QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4798    QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
4799    QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4800    if (ResultType.isNull()) return QualType();
4801    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4802      return LHS;
4803    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4804      return RHS;
4805    return getPointerType(ResultType);
4806  }
4807  case Type::BlockPointer:
4808  {
4809    // Merge two block pointer types, while trying to preserve typedef info
4810    QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4811    QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
4812    QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer);
4813    if (ResultType.isNull()) return QualType();
4814    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4815      return LHS;
4816    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4817      return RHS;
4818    return getBlockPointerType(ResultType);
4819  }
4820  case Type::ConstantArray:
4821  {
4822    const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4823    const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4824    if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4825      return QualType();
4826
4827    QualType LHSElem = getAsArrayType(LHS)->getElementType();
4828    QualType RHSElem = getAsArrayType(RHS)->getElementType();
4829    QualType ResultType = mergeTypes(LHSElem, RHSElem);
4830    if (ResultType.isNull()) return QualType();
4831    if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4832      return LHS;
4833    if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4834      return RHS;
4835    if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4836                                          ArrayType::ArraySizeModifier(), 0);
4837    if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4838                                          ArrayType::ArraySizeModifier(), 0);
4839    const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4840    const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
4841    if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4842      return LHS;
4843    if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4844      return RHS;
4845    if (LVAT) {
4846      // FIXME: This isn't correct! But tricky to implement because
4847      // the array's size has to be the size of LHS, but the type
4848      // has to be different.
4849      return LHS;
4850    }
4851    if (RVAT) {
4852      // FIXME: This isn't correct! But tricky to implement because
4853      // the array's size has to be the size of RHS, but the type
4854      // has to be different.
4855      return RHS;
4856    }
4857    if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4858    if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
4859    return getIncompleteArrayType(ResultType,
4860                                  ArrayType::ArraySizeModifier(), 0);
4861  }
4862  case Type::FunctionNoProto:
4863    return mergeFunctionTypes(LHS, RHS, OfBlockPointer);
4864  case Type::Record:
4865  case Type::Enum:
4866    return QualType();
4867  case Type::Builtin:
4868    // Only exactly equal builtin types are compatible, which is tested above.
4869    return QualType();
4870  case Type::Complex:
4871    // Distinct complex types are incompatible.
4872    return QualType();
4873  case Type::Vector:
4874    // FIXME: The merged type should be an ExtVector!
4875    if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4876                             RHSCan->getAs<VectorType>()))
4877      return LHS;
4878    return QualType();
4879  case Type::ObjCObject: {
4880    // Check if the types are assignment compatible.
4881    // FIXME: This should be type compatibility, e.g. whether
4882    // "LHS x; RHS x;" at global scope is legal.
4883    const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
4884    const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
4885    if (canAssignObjCInterfaces(LHSIface, RHSIface))
4886      return LHS;
4887
4888    return QualType();
4889  }
4890  case Type::ObjCObjectPointer: {
4891    if (OfBlockPointer) {
4892      if (canAssignObjCInterfacesInBlockPointer(
4893                                          LHS->getAs<ObjCObjectPointerType>(),
4894                                          RHS->getAs<ObjCObjectPointerType>()))
4895      return LHS;
4896      return QualType();
4897    }
4898    if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4899                                RHS->getAs<ObjCObjectPointerType>()))
4900      return LHS;
4901
4902    return QualType();
4903    }
4904  }
4905
4906  return QualType();
4907}
4908
4909/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
4910/// 'RHS' attributes and returns the merged version; including for function
4911/// return types.
4912QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
4913  QualType LHSCan = getCanonicalType(LHS),
4914  RHSCan = getCanonicalType(RHS);
4915  // If two types are identical, they are compatible.
4916  if (LHSCan == RHSCan)
4917    return LHS;
4918  if (RHSCan->isFunctionType()) {
4919    if (!LHSCan->isFunctionType())
4920      return QualType();
4921    QualType OldReturnType =
4922      cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
4923    QualType NewReturnType =
4924      cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
4925    QualType ResReturnType =
4926      mergeObjCGCQualifiers(NewReturnType, OldReturnType);
4927    if (ResReturnType.isNull())
4928      return QualType();
4929    if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
4930      // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
4931      // In either case, use OldReturnType to build the new function type.
4932      const FunctionType *F = LHS->getAs<FunctionType>();
4933      if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
4934        FunctionType::ExtInfo Info = getFunctionExtInfo(LHS);
4935        QualType ResultType
4936          = getFunctionType(OldReturnType, FPT->arg_type_begin(),
4937                                  FPT->getNumArgs(), FPT->isVariadic(),
4938                                  FPT->getTypeQuals(),
4939                                  FPT->hasExceptionSpec(),
4940                                  FPT->hasAnyExceptionSpec(),
4941                                  FPT->getNumExceptions(),
4942                                  FPT->exception_begin(),
4943                                  Info);
4944        return ResultType;
4945      }
4946    }
4947    return QualType();
4948  }
4949
4950  // If the qualifiers are different, the types can still be merged.
4951  Qualifiers LQuals = LHSCan.getLocalQualifiers();
4952  Qualifiers RQuals = RHSCan.getLocalQualifiers();
4953  if (LQuals != RQuals) {
4954    // If any of these qualifiers are different, we have a type mismatch.
4955    if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4956        LQuals.getAddressSpace() != RQuals.getAddressSpace())
4957      return QualType();
4958
4959    // Exactly one GC qualifier difference is allowed: __strong is
4960    // okay if the other type has no GC qualifier but is an Objective
4961    // C object pointer (i.e. implicitly strong by default).  We fix
4962    // this by pretending that the unqualified type was actually
4963    // qualified __strong.
4964    Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4965    Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4966    assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4967
4968    if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4969      return QualType();
4970
4971    if (GC_L == Qualifiers::Strong)
4972      return LHS;
4973    if (GC_R == Qualifiers::Strong)
4974      return RHS;
4975    return QualType();
4976  }
4977
4978  if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
4979    QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4980    QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4981    QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
4982    if (ResQT == LHSBaseQT)
4983      return LHS;
4984    if (ResQT == RHSBaseQT)
4985      return RHS;
4986  }
4987  return QualType();
4988}
4989
4990//===----------------------------------------------------------------------===//
4991//                         Integer Predicates
4992//===----------------------------------------------------------------------===//
4993
4994unsigned ASTContext::getIntWidth(QualType T) {
4995  if (T->isBooleanType())
4996    return 1;
4997  if (EnumType *ET = dyn_cast<EnumType>(T))
4998    T = ET->getDecl()->getIntegerType();
4999  // For builtin types, just use the standard type sizing method
5000  return (unsigned)getTypeSize(T);
5001}
5002
5003QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
5004  assert(T->isSignedIntegerType() && "Unexpected type");
5005
5006  // Turn <4 x signed int> -> <4 x unsigned int>
5007  if (const VectorType *VTy = T->getAs<VectorType>())
5008    return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
5009             VTy->getNumElements(), VTy->getAltiVecSpecific());
5010
5011  // For enums, we return the unsigned version of the base type.
5012  if (const EnumType *ETy = T->getAs<EnumType>())
5013    T = ETy->getDecl()->getIntegerType();
5014
5015  const BuiltinType *BTy = T->getAs<BuiltinType>();
5016  assert(BTy && "Unexpected signed integer type");
5017  switch (BTy->getKind()) {
5018  case BuiltinType::Char_S:
5019  case BuiltinType::SChar:
5020    return UnsignedCharTy;
5021  case BuiltinType::Short:
5022    return UnsignedShortTy;
5023  case BuiltinType::Int:
5024    return UnsignedIntTy;
5025  case BuiltinType::Long:
5026    return UnsignedLongTy;
5027  case BuiltinType::LongLong:
5028    return UnsignedLongLongTy;
5029  case BuiltinType::Int128:
5030    return UnsignedInt128Ty;
5031  default:
5032    assert(0 && "Unexpected signed integer type");
5033    return QualType();
5034  }
5035}
5036
5037ExternalASTSource::~ExternalASTSource() { }
5038
5039void ExternalASTSource::PrintStats() { }
5040
5041
5042//===----------------------------------------------------------------------===//
5043//                          Builtin Type Computation
5044//===----------------------------------------------------------------------===//
5045
5046/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
5047/// pointer over the consumed characters.  This returns the resultant type.
5048static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
5049                                  ASTContext::GetBuiltinTypeError &Error,
5050                                  bool AllowTypeModifiers = true) {
5051  // Modifiers.
5052  int HowLong = 0;
5053  bool Signed = false, Unsigned = false;
5054
5055  // Read the modifiers first.
5056  bool Done = false;
5057  while (!Done) {
5058    switch (*Str++) {
5059    default: Done = true; --Str; break;
5060    case 'S':
5061      assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5062      assert(!Signed && "Can't use 'S' modifier multiple times!");
5063      Signed = true;
5064      break;
5065    case 'U':
5066      assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5067      assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5068      Unsigned = true;
5069      break;
5070    case 'L':
5071      assert(HowLong <= 2 && "Can't have LLLL modifier");
5072      ++HowLong;
5073      break;
5074    }
5075  }
5076
5077  QualType Type;
5078
5079  // Read the base type.
5080  switch (*Str++) {
5081  default: assert(0 && "Unknown builtin type letter!");
5082  case 'v':
5083    assert(HowLong == 0 && !Signed && !Unsigned &&
5084           "Bad modifiers used with 'v'!");
5085    Type = Context.VoidTy;
5086    break;
5087  case 'f':
5088    assert(HowLong == 0 && !Signed && !Unsigned &&
5089           "Bad modifiers used with 'f'!");
5090    Type = Context.FloatTy;
5091    break;
5092  case 'd':
5093    assert(HowLong < 2 && !Signed && !Unsigned &&
5094           "Bad modifiers used with 'd'!");
5095    if (HowLong)
5096      Type = Context.LongDoubleTy;
5097    else
5098      Type = Context.DoubleTy;
5099    break;
5100  case 's':
5101    assert(HowLong == 0 && "Bad modifiers used with 's'!");
5102    if (Unsigned)
5103      Type = Context.UnsignedShortTy;
5104    else
5105      Type = Context.ShortTy;
5106    break;
5107  case 'i':
5108    if (HowLong == 3)
5109      Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5110    else if (HowLong == 2)
5111      Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5112    else if (HowLong == 1)
5113      Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5114    else
5115      Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5116    break;
5117  case 'c':
5118    assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5119    if (Signed)
5120      Type = Context.SignedCharTy;
5121    else if (Unsigned)
5122      Type = Context.UnsignedCharTy;
5123    else
5124      Type = Context.CharTy;
5125    break;
5126  case 'b': // boolean
5127    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5128    Type = Context.BoolTy;
5129    break;
5130  case 'z':  // size_t.
5131    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5132    Type = Context.getSizeType();
5133    break;
5134  case 'F':
5135    Type = Context.getCFConstantStringType();
5136    break;
5137  case 'a':
5138    Type = Context.getBuiltinVaListType();
5139    assert(!Type.isNull() && "builtin va list type not initialized!");
5140    break;
5141  case 'A':
5142    // This is a "reference" to a va_list; however, what exactly
5143    // this means depends on how va_list is defined. There are two
5144    // different kinds of va_list: ones passed by value, and ones
5145    // passed by reference.  An example of a by-value va_list is
5146    // x86, where va_list is a char*. An example of by-ref va_list
5147    // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5148    // we want this argument to be a char*&; for x86-64, we want
5149    // it to be a __va_list_tag*.
5150    Type = Context.getBuiltinVaListType();
5151    assert(!Type.isNull() && "builtin va list type not initialized!");
5152    if (Type->isArrayType()) {
5153      Type = Context.getArrayDecayedType(Type);
5154    } else {
5155      Type = Context.getLValueReferenceType(Type);
5156    }
5157    break;
5158  case 'V': {
5159    char *End;
5160    unsigned NumElements = strtoul(Str, &End, 10);
5161    assert(End != Str && "Missing vector size");
5162
5163    Str = End;
5164
5165    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
5166    // FIXME: Don't know what to do about AltiVec.
5167    Type = Context.getVectorType(ElementType, NumElements,
5168                                 VectorType::NotAltiVec);
5169    break;
5170  }
5171  case 'X': {
5172    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
5173    Type = Context.getComplexType(ElementType);
5174    break;
5175  }
5176  case 'P':
5177    Type = Context.getFILEType();
5178    if (Type.isNull()) {
5179      Error = ASTContext::GE_Missing_stdio;
5180      return QualType();
5181    }
5182    break;
5183  case 'J':
5184    if (Signed)
5185      Type = Context.getsigjmp_bufType();
5186    else
5187      Type = Context.getjmp_bufType();
5188
5189    if (Type.isNull()) {
5190      Error = ASTContext::GE_Missing_setjmp;
5191      return QualType();
5192    }
5193    break;
5194  }
5195
5196  if (!AllowTypeModifiers)
5197    return Type;
5198
5199  Done = false;
5200  while (!Done) {
5201    switch (char c = *Str++) {
5202      default: Done = true; --Str; break;
5203      case '*':
5204      case '&':
5205        {
5206          // Both pointers and references can have their pointee types
5207          // qualified with an address space.
5208          char *End;
5209          unsigned AddrSpace = strtoul(Str, &End, 10);
5210          if (End != Str && AddrSpace != 0) {
5211            Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5212            Str = End;
5213          }
5214        }
5215        if (c == '*')
5216          Type = Context.getPointerType(Type);
5217        else
5218          Type = Context.getLValueReferenceType(Type);
5219        break;
5220      // FIXME: There's no way to have a built-in with an rvalue ref arg.
5221      case 'C':
5222        Type = Type.withConst();
5223        break;
5224      case 'D':
5225        Type = Context.getVolatileType(Type);
5226        break;
5227    }
5228  }
5229
5230  return Type;
5231}
5232
5233/// GetBuiltinType - Return the type for the specified builtin.
5234QualType ASTContext::GetBuiltinType(unsigned id,
5235                                    GetBuiltinTypeError &Error) {
5236  const char *TypeStr = BuiltinInfo.GetTypeString(id);
5237
5238  llvm::SmallVector<QualType, 8> ArgTypes;
5239
5240  Error = GE_None;
5241  QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5242  if (Error != GE_None)
5243    return QualType();
5244  while (TypeStr[0] && TypeStr[0] != '.') {
5245    QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5246    if (Error != GE_None)
5247      return QualType();
5248
5249    // Do array -> pointer decay.  The builtin should use the decayed type.
5250    if (Ty->isArrayType())
5251      Ty = getArrayDecayedType(Ty);
5252
5253    ArgTypes.push_back(Ty);
5254  }
5255
5256  assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5257         "'.' should only occur at end of builtin type list!");
5258
5259  // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5260  if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5261    return getFunctionNoProtoType(ResType);
5262
5263  // FIXME: Should we create noreturn types?
5264  return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
5265                         TypeStr[0] == '.', 0, false, false, 0, 0,
5266                         FunctionType::ExtInfo());
5267}
5268
5269QualType
5270ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5271  // Perform the usual unary conversions. We do this early so that
5272  // integral promotions to "int" can allow us to exit early, in the
5273  // lhs == rhs check. Also, for conversion purposes, we ignore any
5274  // qualifiers.  For example, "const float" and "float" are
5275  // equivalent.
5276  if (lhs->isPromotableIntegerType())
5277    lhs = getPromotedIntegerType(lhs);
5278  else
5279    lhs = lhs.getUnqualifiedType();
5280  if (rhs->isPromotableIntegerType())
5281    rhs = getPromotedIntegerType(rhs);
5282  else
5283    rhs = rhs.getUnqualifiedType();
5284
5285  // If both types are identical, no conversion is needed.
5286  if (lhs == rhs)
5287    return lhs;
5288
5289  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5290  // The caller can deal with this (e.g. pointer + int).
5291  if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5292    return lhs;
5293
5294  // At this point, we have two different arithmetic types.
5295
5296  // Handle complex types first (C99 6.3.1.8p1).
5297  if (lhs->isComplexType() || rhs->isComplexType()) {
5298    // if we have an integer operand, the result is the complex type.
5299    if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
5300      // convert the rhs to the lhs complex type.
5301      return lhs;
5302    }
5303    if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
5304      // convert the lhs to the rhs complex type.
5305      return rhs;
5306    }
5307    // This handles complex/complex, complex/float, or float/complex.
5308    // When both operands are complex, the shorter operand is converted to the
5309    // type of the longer, and that is the type of the result. This corresponds
5310    // to what is done when combining two real floating-point operands.
5311    // The fun begins when size promotion occur across type domains.
5312    // From H&S 6.3.4: When one operand is complex and the other is a real
5313    // floating-point type, the less precise type is converted, within it's
5314    // real or complex domain, to the precision of the other type. For example,
5315    // when combining a "long double" with a "double _Complex", the
5316    // "double _Complex" is promoted to "long double _Complex".
5317    int result = getFloatingTypeOrder(lhs, rhs);
5318
5319    if (result > 0) { // The left side is bigger, convert rhs.
5320      rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
5321    } else if (result < 0) { // The right side is bigger, convert lhs.
5322      lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
5323    }
5324    // At this point, lhs and rhs have the same rank/size. Now, make sure the
5325    // domains match. This is a requirement for our implementation, C99
5326    // does not require this promotion.
5327    if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5328      if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5329        return rhs;
5330      } else { // handle "_Complex double, double".
5331        return lhs;
5332      }
5333    }
5334    return lhs; // The domain/size match exactly.
5335  }
5336  // Now handle "real" floating types (i.e. float, double, long double).
5337  if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5338    // if we have an integer operand, the result is the real floating type.
5339    if (rhs->isIntegerType()) {
5340      // convert rhs to the lhs floating point type.
5341      return lhs;
5342    }
5343    if (rhs->isComplexIntegerType()) {
5344      // convert rhs to the complex floating point type.
5345      return getComplexType(lhs);
5346    }
5347    if (lhs->isIntegerType()) {
5348      // convert lhs to the rhs floating point type.
5349      return rhs;
5350    }
5351    if (lhs->isComplexIntegerType()) {
5352      // convert lhs to the complex floating point type.
5353      return getComplexType(rhs);
5354    }
5355    // We have two real floating types, float/complex combos were handled above.
5356    // Convert the smaller operand to the bigger result.
5357    int result = getFloatingTypeOrder(lhs, rhs);
5358    if (result > 0) // convert the rhs
5359      return lhs;
5360    assert(result < 0 && "illegal float comparison");
5361    return rhs;   // convert the lhs
5362  }
5363  if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5364    // Handle GCC complex int extension.
5365    const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5366    const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5367
5368    if (lhsComplexInt && rhsComplexInt) {
5369      if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
5370                              rhsComplexInt->getElementType()) >= 0)
5371        return lhs; // convert the rhs
5372      return rhs;
5373    } else if (lhsComplexInt && rhs->isIntegerType()) {
5374      // convert the rhs to the lhs complex type.
5375      return lhs;
5376    } else if (rhsComplexInt && lhs->isIntegerType()) {
5377      // convert the lhs to the rhs complex type.
5378      return rhs;
5379    }
5380  }
5381  // Finally, we have two differing integer types.
5382  // The rules for this case are in C99 6.3.1.8
5383  int compare = getIntegerTypeOrder(lhs, rhs);
5384  bool lhsSigned = lhs->isSignedIntegerType(),
5385       rhsSigned = rhs->isSignedIntegerType();
5386  QualType destType;
5387  if (lhsSigned == rhsSigned) {
5388    // Same signedness; use the higher-ranked type
5389    destType = compare >= 0 ? lhs : rhs;
5390  } else if (compare != (lhsSigned ? 1 : -1)) {
5391    // The unsigned type has greater than or equal rank to the
5392    // signed type, so use the unsigned type
5393    destType = lhsSigned ? rhs : lhs;
5394  } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5395    // The two types are different widths; if we are here, that
5396    // means the signed type is larger than the unsigned type, so
5397    // use the signed type.
5398    destType = lhsSigned ? lhs : rhs;
5399  } else {
5400    // The signed type is higher-ranked than the unsigned type,
5401    // but isn't actually any bigger (like unsigned int and long
5402    // on most 32-bit systems).  Use the unsigned type corresponding
5403    // to the signed type.
5404    destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5405  }
5406  return destType;
5407}
5408