ASTContext.cpp revision 60aeaddb123762e15efe7f268afe033448b70023
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/DeclCXX.h"
169f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "clang/AST/DeclObjC.h"
179f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "clang/AST/DeclTemplate.h"
189f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "clang/AST/TypeLoc.h"
199f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "clang/AST/Expr.h"
209f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "clang/AST/ExternalASTSource.h"
219f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "clang/AST/RecordLayout.h"
229f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "clang/Basic/Builtins.h"
239f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "clang/Basic/SourceManager.h"
249f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "clang/Basic/TargetInfo.h"
259f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "llvm/ADT/StringExtras.h"
269f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "llvm/Support/MathExtras.h"
279f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "llvm/Support/MemoryBuffer.h"
289f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "RecordLayoutBuilder.h"
299f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
309f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonusing namespace clang;
319f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
329f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonenum FloatingRank {
339f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  FloatRank, DoubleRank, LongDoubleRank
349f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson};
359f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
369f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
379f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                       TargetInfo &t,
389f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                       IdentifierTable &idents, SelectorTable &sels,
399f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                       Builtin::Context &builtins,
409f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                       bool FreeMem, unsigned size_reserve) :
419f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
429f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
439f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
449f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  SourceMgr(SM), LangOpts(LOpts),
459f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
469f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  Idents(idents), Selectors(sels),
479f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
489f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ObjCIdRedefinitionType = QualType();
499f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ObjCClassRedefinitionType = QualType();
509f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (size_reserve > 0) Types.reserve(size_reserve);
519f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  TUDecl = TranslationUnitDecl::Create(*this);
529f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinTypes();
539f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
549f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
559f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonASTContext::~ASTContext() {
569f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Deallocate all the types.
579f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  while (!Types.empty()) {
589f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Types.back()->Destroy(*this);
599f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Types.pop_back();
609f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
619f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
629f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  {
639f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    llvm::FoldingSet<ExtQuals>::iterator
649f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      I = ExtQualNodes.begin(), E = ExtQualNodes.end();
659f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    while (I != E)
669f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Deallocate(&*I++);
679f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
689f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
699f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  {
709f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
719f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
729f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    while (I != E) {
739f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
749f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      delete R;
759f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    }
769f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
779f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
789f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  {
799f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
809f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      I = ObjCLayouts.begin(), E = ObjCLayouts.end();
819f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    while (I != E) {
829f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
839f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      delete R;
849f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    }
859f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
869f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
879f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Destroy nested-name-specifiers.
889f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  for (llvm::FoldingSet<NestedNameSpecifier>::iterator
899f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson         NNS = NestedNameSpecifiers.begin(),
909f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson         NNSEnd = NestedNameSpecifiers.end();
919f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson       NNS != NNSEnd;
929f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson       /* Increment in loop */)
939f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    (*NNS++).Destroy(*this);
949f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
959f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (GlobalNestedNameSpecifier)
969f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    GlobalNestedNameSpecifier->Destroy(*this);
979f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
989f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  TUDecl->Destroy(*this);
999f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
1009f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
1019f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonvoid
1029f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
1039f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ExternalSource.reset(Source.take());
1049f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
1059f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
1069f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonvoid ASTContext::PrintStats() const {
1079f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  fprintf(stderr, "*** AST Context Stats:\n");
1089f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  fprintf(stderr, "  %d types total.\n", (int)Types.size());
1099f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
1109f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  unsigned counts[] = {
1119f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#define TYPE(Name, Parent) 0,
1129f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#define ABSTRACT_TYPE(Name, Parent)
1139f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "clang/AST/TypeNodes.def"
1149f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    0 // Extra
1159f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  };
1169f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
1179f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1189f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Type *T = Types[i];
1199f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    counts[(unsigned)T->getTypeClass()]++;
1209f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
1219f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
1229f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  unsigned Idx = 0;
1239f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  unsigned TotalBytes = 0;
1249f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#define TYPE(Name, Parent)                                              \
1259f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (counts[Idx])                                                      \
1269f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    fprintf(stderr, "    %d %s types\n", (int)counts[Idx], #Name);      \
1279f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
1289f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ++Idx;
1299f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#define ABSTRACT_TYPE(Name, Parent)
1309f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "clang/AST/TypeNodes.def"
1319f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
1329f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
1339f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
1349f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (ExternalSource.get()) {
1359f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    fprintf(stderr, "\n");
1369f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    ExternalSource->PrintStats();
1379f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
1389f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
1399f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
1409f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
1419f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonvoid ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1429f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
1439f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  R = CanQualType::CreateUnsafe(QualType(Ty, 0));
1449f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  Types.push_back(Ty);
1459f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
1469f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
1479f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonvoid ASTContext::InitBuiltinTypes() {
1489f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert(VoidTy.isNull() && "Context reinitialized?");
1499f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
1509f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // C99 6.2.5p19.
1519f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(VoidTy,              BuiltinType::Void);
1529f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
1539f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // C99 6.2.5p2.
1549f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(BoolTy,              BuiltinType::Bool);
1559f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // C99 6.2.5p3.
1569f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (LangOpts.CharIsSigned)
1579f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    InitBuiltinType(CharTy,            BuiltinType::Char_S);
1589f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  else
1599f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    InitBuiltinType(CharTy,            BuiltinType::Char_U);
1609f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // C99 6.2.5p4.
1619f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
1629f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(ShortTy,             BuiltinType::Short);
1639f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(IntTy,               BuiltinType::Int);
1649f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(LongTy,              BuiltinType::Long);
1659f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
1669f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
1679f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // C99 6.2.5p6.
1689f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
1699f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
1709f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
1719f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
1729f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
1739f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
1749f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // C99 6.2.5p10.
1759f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(FloatTy,             BuiltinType::Float);
1769f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(DoubleTy,            BuiltinType::Double);
1779f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
1789f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
1799f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // GNU extension, 128-bit integers.
1809f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(Int128Ty,            BuiltinType::Int128);
1819f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
1829f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
1839f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (LangOpts.CPlusPlus) // C++ 3.9.1p5
1849f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    InitBuiltinType(WCharTy,           BuiltinType::WChar);
1859f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  else // C99
1869f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    WCharTy = getFromTargetType(Target.getWCharType());
1879f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
1889f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1899f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    InitBuiltinType(Char16Ty,           BuiltinType::Char16);
1909f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  else // C99
1919f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Char16Ty = getFromTargetType(Target.getChar16Type());
1929f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
1939f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1949f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    InitBuiltinType(Char32Ty,           BuiltinType::Char32);
1959f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  else // C99
1969f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    Char32Ty = getFromTargetType(Target.getChar32Type());
1979f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
1989f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Placeholder type for functions.
1999f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(OverloadTy,          BuiltinType::Overload);
2009f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2019f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Placeholder type for type-dependent expressions whose type is
2029f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // completely unknown. No code should ever check a type against
2039f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // DependentTy and users should never see it; however, it is here to
2049f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // help diagnose failures to properly check for type-dependent
2059f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // expressions.
2069f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(DependentTy,         BuiltinType::Dependent);
2079f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2089f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Placeholder type for C++0x auto declarations whose real type has
2099f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // not yet been deduced.
2109f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
2119f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2129f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // C99 6.2.5p11.
2139f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  FloatComplexTy      = getComplexType(FloatTy);
2149f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  DoubleComplexTy     = getComplexType(DoubleTy);
2159f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  LongDoubleComplexTy = getComplexType(LongDoubleTy);
2169f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2179f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  BuiltinVaListType = QualType();
2189f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2199f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
2209f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ObjCIdTypedefType = QualType();
2219f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ObjCClassTypedefType = QualType();
2229f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2239f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Builtin types for 'id' and 'Class'.
2249f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
2259f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
2269f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2279f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  ObjCConstantStringType = QualType();
2289f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2299f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // void * type
2309f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  VoidPtrTy = getPointerType(VoidTy);
2319f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2329f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // nullptr type (C++0x 2.14.7)
2339f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
2349f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
2359f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2369f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonMemberSpecializationInfo *
2379f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
2389f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert(Var->isStaticDataMember() && "Not a static data member");
2399f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
2409f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    = InstantiatedFromStaticDataMember.find(Var);
2419f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (Pos == InstantiatedFromStaticDataMember.end())
2429f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return 0;
2439f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2449f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return Pos->second;
2459f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
2469f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2479f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonvoid
2489f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
2499f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                                TemplateSpecializationKind TSK) {
2509f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert(Inst->isStaticDataMember() && "Not a static data member");
2519f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert(Tmpl->isStaticDataMember() && "Not a static data member");
2529f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert(!InstantiatedFromStaticDataMember[Inst] &&
2539f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson         "Already noted what static data member was instantiated from");
2549f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InstantiatedFromStaticDataMember[Inst]
2559f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    = new (*this) MemberSpecializationInfo(Tmpl, TSK);
2569f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
2579f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2589f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonUnresolvedUsingDecl *
2599f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonASTContext::getInstantiatedFromUnresolvedUsingDecl(UsingDecl *UUD) {
2609f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  llvm::DenseMap<UsingDecl *, UnresolvedUsingDecl *>::iterator Pos
2619f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    = InstantiatedFromUnresolvedUsingDecl.find(UUD);
2629f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (Pos == InstantiatedFromUnresolvedUsingDecl.end())
2639f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return 0;
2649f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2659f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return Pos->second;
2669f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
2679f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2689f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonvoid
2699f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonASTContext::setInstantiatedFromUnresolvedUsingDecl(UsingDecl *UD,
2709f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                                   UnresolvedUsingDecl *UUD) {
2719f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert(!InstantiatedFromUnresolvedUsingDecl[UD] &&
2729f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson         "Already noted what using decl what instantiated from");
2739f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InstantiatedFromUnresolvedUsingDecl[UD] = UUD;
2749f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
2759f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2769f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonFieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
2779f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
2789f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    = InstantiatedFromUnnamedFieldDecl.find(Field);
2799f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (Pos == InstantiatedFromUnnamedFieldDecl.end())
2809f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return 0;
2819f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2829f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return Pos->second;
2839f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
2849f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2859f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonvoid ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
2869f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                                                     FieldDecl *Tmpl) {
2879f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
2889f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
2899f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
2909f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson         "Already noted what unnamed field was instantiated from");
2919f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2929f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
2939f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
2949f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
2959f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonnamespace {
2969f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  class BeforeInTranslationUnit
2979f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    : std::binary_function<SourceRange, SourceRange, bool> {
2989f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    SourceManager *SourceMgr;
2999f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3009f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  public:
3019f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
3029f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3039f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    bool operator()(SourceRange X, SourceRange Y) {
3049f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
3059f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    }
3069f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  };
3079f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
3089f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3099f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// \brief Determine whether the given comment is a Doxygen-style comment.
3109f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson///
3119f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// \param Start the start of the comment text.
3129f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson///
3139f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// \param End the end of the comment text.
3149f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson///
3159f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// \param Member whether we want to check whether this is a member comment
3169f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
3179f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// we only return true when we find a non-member comment.
3189f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonstatic bool
3199f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse WilsonisDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
3209f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                 bool Member = false) {
3219f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  const char *BufferStart
3229f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
3239f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
3249f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
3259f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3269f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (End - Start < 4)
3279f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return false;
3289f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3299f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  assert(Start[0] == '/' && "Not a comment?");
3309f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
3319f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return false;
3329f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
3339f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return false;
3349f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3359f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  return (Start[3] == '<') == Member;
3369f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson}
3379f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3389f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// \brief Retrieve the comment associated with the given declaration, if
3399f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson/// it has one.
3409f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonconst char *ASTContext::getCommentForDecl(const Decl *D) {
3419f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (!D)
3429f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return 0;
3439f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3449f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Check whether we have cached a comment string for this declaration
3459f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // already.
3469f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  llvm::DenseMap<const Decl *, std::string>::iterator Pos
3479f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    = DeclComments.find(D);
3489f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (Pos != DeclComments.end())
3499f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return Pos->second.c_str();
3509f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3519f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // If we have an external AST source and have not yet loaded comments from
3529f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // that source, do so now.
3539f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (ExternalSource && !LoadedExternalComments) {
3549f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    std::vector<SourceRange> LoadedComments;
3559f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    ExternalSource->ReadComments(LoadedComments);
3569f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3579f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    if (!LoadedComments.empty())
3589f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson      Comments.insert(Comments.begin(), LoadedComments.begin(),
3599f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                      LoadedComments.end());
3609f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3619f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    LoadedExternalComments = true;
3629f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  }
3639f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3649f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // If there are no comments anywhere, we won't find anything.
3659f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (Comments.empty())
3669f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return 0;
3679f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3689f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // If the declaration doesn't map directly to a location in a file, we
3699f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // can't find the comment.
3709f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  SourceLocation DeclStartLoc = D->getLocStart();
3719f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
3729f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return 0;
3739f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3749f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Find the comment that occurs just before this declaration.
3759f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  std::vector<SourceRange>::iterator LastComment
3769f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    = std::lower_bound(Comments.begin(), Comments.end(),
3779f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                       SourceRange(DeclStartLoc),
3789f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                       BeforeInTranslationUnit(&SourceMgr));
3799f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
3809f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // Decompose the location for the start of the declaration and find the
3819f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  // beginning of the file buffer.
3829f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  std::pair<FileID, unsigned> DeclStartDecomp
3839f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    = SourceMgr.getDecomposedLoc(DeclStartLoc);
384  const char *FileBufferStart
385    = SourceMgr.getBufferData(DeclStartDecomp.first).first;
386
387  // First check whether we have a comment for a member.
388  if (LastComment != Comments.end() &&
389      !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
390      isDoxygenComment(SourceMgr, *LastComment, true)) {
391    std::pair<FileID, unsigned> LastCommentEndDecomp
392      = SourceMgr.getDecomposedLoc(LastComment->getEnd());
393    if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
394        SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
395          == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
396                                     LastCommentEndDecomp.second)) {
397      // The Doxygen member comment comes after the declaration starts and
398      // is on the same line and in the same file as the declaration. This
399      // is the comment we want.
400      std::string &Result = DeclComments[D];
401      Result.append(FileBufferStart +
402                      SourceMgr.getFileOffset(LastComment->getBegin()),
403                    FileBufferStart + LastCommentEndDecomp.second + 1);
404      return Result.c_str();
405    }
406  }
407
408  if (LastComment == Comments.begin())
409    return 0;
410  --LastComment;
411
412  // Decompose the end of the comment.
413  std::pair<FileID, unsigned> LastCommentEndDecomp
414    = SourceMgr.getDecomposedLoc(LastComment->getEnd());
415
416  // If the comment and the declaration aren't in the same file, then they
417  // aren't related.
418  if (DeclStartDecomp.first != LastCommentEndDecomp.first)
419    return 0;
420
421  // Check that we actually have a Doxygen comment.
422  if (!isDoxygenComment(SourceMgr, *LastComment))
423    return 0;
424
425  // Compute the starting line for the declaration and for the end of the
426  // comment (this is expensive).
427  unsigned DeclStartLine
428    = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
429  unsigned CommentEndLine
430    = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
431                              LastCommentEndDecomp.second);
432
433  // If the comment does not end on the line prior to the declaration, then
434  // the comment is not associated with the declaration at all.
435  if (CommentEndLine + 1 != DeclStartLine)
436    return 0;
437
438  // We have a comment, but there may be more comments on the previous lines.
439  // Keep looking so long as the comments are still Doxygen comments and are
440  // still adjacent.
441  unsigned ExpectedLine
442    = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
443  std::vector<SourceRange>::iterator FirstComment = LastComment;
444  while (FirstComment != Comments.begin()) {
445    // Look at the previous comment
446    --FirstComment;
447    std::pair<FileID, unsigned> Decomp
448      = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
449
450    // If this previous comment is in a different file, we're done.
451    if (Decomp.first != DeclStartDecomp.first) {
452      ++FirstComment;
453      break;
454    }
455
456    // If this comment is not a Doxygen comment, we're done.
457    if (!isDoxygenComment(SourceMgr, *FirstComment)) {
458      ++FirstComment;
459      break;
460    }
461
462    // If the line number is not what we expected, we're done.
463    unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
464    if (Line != ExpectedLine) {
465      ++FirstComment;
466      break;
467    }
468
469    // Set the next expected line number.
470    ExpectedLine
471      = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
472  }
473
474  // The iterator range [FirstComment, LastComment] contains all of the
475  // BCPL comments that, together, are associated with this declaration.
476  // Form a single comment block string for this declaration that concatenates
477  // all of these comments.
478  std::string &Result = DeclComments[D];
479  while (FirstComment != LastComment) {
480    std::pair<FileID, unsigned> DecompStart
481      = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
482    std::pair<FileID, unsigned> DecompEnd
483      = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
484    Result.append(FileBufferStart + DecompStart.second,
485                  FileBufferStart + DecompEnd.second + 1);
486    ++FirstComment;
487  }
488
489  // Append the last comment line.
490  Result.append(FileBufferStart +
491                  SourceMgr.getFileOffset(LastComment->getBegin()),
492                FileBufferStart + LastCommentEndDecomp.second + 1);
493  return Result.c_str();
494}
495
496//===----------------------------------------------------------------------===//
497//                         Type Sizing and Analysis
498//===----------------------------------------------------------------------===//
499
500/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
501/// scalar floating point type.
502const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
503  const BuiltinType *BT = T->getAs<BuiltinType>();
504  assert(BT && "Not a floating point type!");
505  switch (BT->getKind()) {
506  default: assert(0 && "Not a floating point type!");
507  case BuiltinType::Float:      return Target.getFloatFormat();
508  case BuiltinType::Double:     return Target.getDoubleFormat();
509  case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
510  }
511}
512
513/// getDeclAlignInBytes - Return a conservative estimate of the alignment of the
514/// specified decl.  Note that bitfields do not have a valid alignment, so
515/// this method will assert on them.
516unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
517  unsigned Align = Target.getCharWidth();
518
519  if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
520    Align = std::max(Align, AA->getAlignment());
521
522  if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
523    QualType T = VD->getType();
524    if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
525      unsigned AS = RT->getPointeeType().getAddressSpace();
526      Align = Target.getPointerAlign(AS);
527    } else if (!T->isIncompleteType() && !T->isFunctionType()) {
528      // Incomplete or function types default to 1.
529      while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
530        T = cast<ArrayType>(T)->getElementType();
531
532      Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
533    }
534  }
535
536  return Align / Target.getCharWidth();
537}
538
539/// getTypeSize - Return the size of the specified type, in bits.  This method
540/// does not work on incomplete types.
541///
542/// FIXME: Pointers into different addr spaces could have different sizes and
543/// alignment requirements: getPointerInfo should take an AddrSpace, this
544/// should take a QualType, &c.
545std::pair<uint64_t, unsigned>
546ASTContext::getTypeInfo(const Type *T) {
547  uint64_t Width=0;
548  unsigned Align=8;
549  switch (T->getTypeClass()) {
550#define TYPE(Class, Base)
551#define ABSTRACT_TYPE(Class, Base)
552#define NON_CANONICAL_TYPE(Class, Base)
553#define DEPENDENT_TYPE(Class, Base) case Type::Class:
554#include "clang/AST/TypeNodes.def"
555    assert(false && "Should not see dependent types");
556    break;
557
558  case Type::FunctionNoProto:
559  case Type::FunctionProto:
560    // GCC extension: alignof(function) = 32 bits
561    Width = 0;
562    Align = 32;
563    break;
564
565  case Type::IncompleteArray:
566  case Type::VariableArray:
567    Width = 0;
568    Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
569    break;
570
571  case Type::ConstantArray: {
572    const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
573
574    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
575    Width = EltInfo.first*CAT->getSize().getZExtValue();
576    Align = EltInfo.second;
577    break;
578  }
579  case Type::ExtVector:
580  case Type::Vector: {
581    const VectorType *VT = cast<VectorType>(T);
582    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
583    Width = EltInfo.first*VT->getNumElements();
584    Align = Width;
585    // If the alignment is not a power of 2, round up to the next power of 2.
586    // This happens for non-power-of-2 length vectors.
587    if (VT->getNumElements() & (VT->getNumElements()-1)) {
588      Align = llvm::NextPowerOf2(Align);
589      Width = llvm::RoundUpToAlignment(Width, Align);
590    }
591    break;
592  }
593
594  case Type::Builtin:
595    switch (cast<BuiltinType>(T)->getKind()) {
596    default: assert(0 && "Unknown builtin type!");
597    case BuiltinType::Void:
598      // GCC extension: alignof(void) = 8 bits.
599      Width = 0;
600      Align = 8;
601      break;
602
603    case BuiltinType::Bool:
604      Width = Target.getBoolWidth();
605      Align = Target.getBoolAlign();
606      break;
607    case BuiltinType::Char_S:
608    case BuiltinType::Char_U:
609    case BuiltinType::UChar:
610    case BuiltinType::SChar:
611      Width = Target.getCharWidth();
612      Align = Target.getCharAlign();
613      break;
614    case BuiltinType::WChar:
615      Width = Target.getWCharWidth();
616      Align = Target.getWCharAlign();
617      break;
618    case BuiltinType::Char16:
619      Width = Target.getChar16Width();
620      Align = Target.getChar16Align();
621      break;
622    case BuiltinType::Char32:
623      Width = Target.getChar32Width();
624      Align = Target.getChar32Align();
625      break;
626    case BuiltinType::UShort:
627    case BuiltinType::Short:
628      Width = Target.getShortWidth();
629      Align = Target.getShortAlign();
630      break;
631    case BuiltinType::UInt:
632    case BuiltinType::Int:
633      Width = Target.getIntWidth();
634      Align = Target.getIntAlign();
635      break;
636    case BuiltinType::ULong:
637    case BuiltinType::Long:
638      Width = Target.getLongWidth();
639      Align = Target.getLongAlign();
640      break;
641    case BuiltinType::ULongLong:
642    case BuiltinType::LongLong:
643      Width = Target.getLongLongWidth();
644      Align = Target.getLongLongAlign();
645      break;
646    case BuiltinType::Int128:
647    case BuiltinType::UInt128:
648      Width = 128;
649      Align = 128; // int128_t is 128-bit aligned on all targets.
650      break;
651    case BuiltinType::Float:
652      Width = Target.getFloatWidth();
653      Align = Target.getFloatAlign();
654      break;
655    case BuiltinType::Double:
656      Width = Target.getDoubleWidth();
657      Align = Target.getDoubleAlign();
658      break;
659    case BuiltinType::LongDouble:
660      Width = Target.getLongDoubleWidth();
661      Align = Target.getLongDoubleAlign();
662      break;
663    case BuiltinType::NullPtr:
664      Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
665      Align = Target.getPointerAlign(0); //   == sizeof(void*)
666      break;
667    }
668    break;
669  case Type::FixedWidthInt:
670    // FIXME: This isn't precisely correct; the width/alignment should depend
671    // on the available types for the target
672    Width = cast<FixedWidthIntType>(T)->getWidth();
673    Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
674    Align = Width;
675    break;
676  case Type::ObjCObjectPointer:
677    Width = Target.getPointerWidth(0);
678    Align = Target.getPointerAlign(0);
679    break;
680  case Type::BlockPointer: {
681    unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
682    Width = Target.getPointerWidth(AS);
683    Align = Target.getPointerAlign(AS);
684    break;
685  }
686  case Type::Pointer: {
687    unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
688    Width = Target.getPointerWidth(AS);
689    Align = Target.getPointerAlign(AS);
690    break;
691  }
692  case Type::LValueReference:
693  case Type::RValueReference:
694    // "When applied to a reference or a reference type, the result is the size
695    // of the referenced type." C++98 5.3.3p2: expr.sizeof.
696    // FIXME: This is wrong for struct layout: a reference in a struct has
697    // pointer size.
698    return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
699  case Type::MemberPointer: {
700    // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
701    // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
702    // If we ever want to support other ABIs this needs to be abstracted.
703
704    QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
705    std::pair<uint64_t, unsigned> PtrDiffInfo =
706      getTypeInfo(getPointerDiffType());
707    Width = PtrDiffInfo.first;
708    if (Pointee->isFunctionType())
709      Width *= 2;
710    Align = PtrDiffInfo.second;
711    break;
712  }
713  case Type::Complex: {
714    // Complex types have the same alignment as their elements, but twice the
715    // size.
716    std::pair<uint64_t, unsigned> EltInfo =
717      getTypeInfo(cast<ComplexType>(T)->getElementType());
718    Width = EltInfo.first*2;
719    Align = EltInfo.second;
720    break;
721  }
722  case Type::ObjCInterface: {
723    const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
724    const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
725    Width = Layout.getSize();
726    Align = Layout.getAlignment();
727    break;
728  }
729  case Type::Record:
730  case Type::Enum: {
731    const TagType *TT = cast<TagType>(T);
732
733    if (TT->getDecl()->isInvalidDecl()) {
734      Width = 1;
735      Align = 1;
736      break;
737    }
738
739    if (const EnumType *ET = dyn_cast<EnumType>(TT))
740      return getTypeInfo(ET->getDecl()->getIntegerType());
741
742    const RecordType *RT = cast<RecordType>(TT);
743    const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
744    Width = Layout.getSize();
745    Align = Layout.getAlignment();
746    break;
747  }
748
749  case Type::SubstTemplateTypeParm:
750    return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
751                       getReplacementType().getTypePtr());
752
753  case Type::Elaborated:
754    return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType()
755                         .getTypePtr());
756
757  case Type::Typedef: {
758    const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
759    if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
760      Align = Aligned->getAlignment();
761      Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
762    } else
763      return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
764    break;
765  }
766
767  case Type::TypeOfExpr:
768    return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
769                         .getTypePtr());
770
771  case Type::TypeOf:
772    return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
773
774  case Type::Decltype:
775    return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
776                        .getTypePtr());
777
778  case Type::QualifiedName:
779    return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
780
781  case Type::TemplateSpecialization:
782    assert(getCanonicalType(T) != T &&
783           "Cannot request the size of a dependent type");
784    // FIXME: this is likely to be wrong once we support template
785    // aliases, since a template alias could refer to a typedef that
786    // has an __aligned__ attribute on it.
787    return getTypeInfo(getCanonicalType(T));
788  }
789
790  assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
791  return std::make_pair(Width, Align);
792}
793
794/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
795/// type for the current target in bits.  This can be different than the ABI
796/// alignment in cases where it is beneficial for performance to overalign
797/// a data type.
798unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
799  unsigned ABIAlign = getTypeAlign(T);
800
801  // Double and long long should be naturally aligned if possible.
802  if (const ComplexType* CT = T->getAs<ComplexType>())
803    T = CT->getElementType().getTypePtr();
804  if (T->isSpecificBuiltinType(BuiltinType::Double) ||
805      T->isSpecificBuiltinType(BuiltinType::LongLong))
806    return std::max(ABIAlign, (unsigned)getTypeSize(T));
807
808  return ABIAlign;
809}
810
811static void CollectLocalObjCIvars(ASTContext *Ctx,
812                                  const ObjCInterfaceDecl *OI,
813                                  llvm::SmallVectorImpl<FieldDecl*> &Fields) {
814  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
815       E = OI->ivar_end(); I != E; ++I) {
816    ObjCIvarDecl *IVDecl = *I;
817    if (!IVDecl->isInvalidDecl())
818      Fields.push_back(cast<FieldDecl>(IVDecl));
819  }
820}
821
822void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
823                             llvm::SmallVectorImpl<FieldDecl*> &Fields) {
824  if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
825    CollectObjCIvars(SuperClass, Fields);
826  CollectLocalObjCIvars(this, OI, Fields);
827}
828
829/// ShallowCollectObjCIvars -
830/// Collect all ivars, including those synthesized, in the current class.
831///
832void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
833                                 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
834                                 bool CollectSynthesized) {
835  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
836         E = OI->ivar_end(); I != E; ++I) {
837     Ivars.push_back(*I);
838  }
839  if (CollectSynthesized)
840    CollectSynthesizedIvars(OI, Ivars);
841}
842
843void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
844                                llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
845  for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
846       E = PD->prop_end(); I != E; ++I)
847    if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
848      Ivars.push_back(Ivar);
849
850  // Also look into nested protocols.
851  for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
852       E = PD->protocol_end(); P != E; ++P)
853    CollectProtocolSynthesizedIvars(*P, Ivars);
854}
855
856/// CollectSynthesizedIvars -
857/// This routine collect synthesized ivars for the designated class.
858///
859void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
860                                llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
861  for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
862       E = OI->prop_end(); I != E; ++I) {
863    if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
864      Ivars.push_back(Ivar);
865  }
866  // Also look into interface's protocol list for properties declared
867  // in the protocol and whose ivars are synthesized.
868  for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
869       PE = OI->protocol_end(); P != PE; ++P) {
870    ObjCProtocolDecl *PD = (*P);
871    CollectProtocolSynthesizedIvars(PD, Ivars);
872  }
873}
874
875unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
876  unsigned count = 0;
877  for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
878       E = PD->prop_end(); I != E; ++I)
879    if ((*I)->getPropertyIvarDecl())
880      ++count;
881
882  // Also look into nested protocols.
883  for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
884       E = PD->protocol_end(); P != E; ++P)
885    count += CountProtocolSynthesizedIvars(*P);
886  return count;
887}
888
889unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
890  unsigned count = 0;
891  for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
892       E = OI->prop_end(); I != E; ++I) {
893    if ((*I)->getPropertyIvarDecl())
894      ++count;
895  }
896  // Also look into interface's protocol list for properties declared
897  // in the protocol and whose ivars are synthesized.
898  for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
899       PE = OI->protocol_end(); P != PE; ++P) {
900    ObjCProtocolDecl *PD = (*P);
901    count += CountProtocolSynthesizedIvars(PD);
902  }
903  return count;
904}
905
906/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
907ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
908  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
909    I = ObjCImpls.find(D);
910  if (I != ObjCImpls.end())
911    return cast<ObjCImplementationDecl>(I->second);
912  return 0;
913}
914/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
915ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
916  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
917    I = ObjCImpls.find(D);
918  if (I != ObjCImpls.end())
919    return cast<ObjCCategoryImplDecl>(I->second);
920  return 0;
921}
922
923/// \brief Set the implementation of ObjCInterfaceDecl.
924void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
925                           ObjCImplementationDecl *ImplD) {
926  assert(IFaceD && ImplD && "Passed null params");
927  ObjCImpls[IFaceD] = ImplD;
928}
929/// \brief Set the implementation of ObjCCategoryDecl.
930void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
931                           ObjCCategoryImplDecl *ImplD) {
932  assert(CatD && ImplD && "Passed null params");
933  ObjCImpls[CatD] = ImplD;
934}
935
936/// \brief Allocate an uninitialized DeclaratorInfo.
937///
938/// The caller should initialize the memory held by DeclaratorInfo using
939/// the TypeLoc wrappers.
940///
941/// \param T the type that will be the basis for type source info. This type
942/// should refer to how the declarator was written in source code, not to
943/// what type semantic analysis resolved the declarator to.
944DeclaratorInfo *ASTContext::CreateDeclaratorInfo(QualType T,
945                                                 unsigned DataSize) {
946  if (!DataSize)
947    DataSize = TypeLoc::getFullDataSizeForType(T);
948  else
949    assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
950           "incorrect data size provided to CreateDeclaratorInfo!");
951
952  DeclaratorInfo *DInfo =
953    (DeclaratorInfo*)BumpAlloc.Allocate(sizeof(DeclaratorInfo) + DataSize, 8);
954  new (DInfo) DeclaratorInfo(T);
955  return DInfo;
956}
957
958DeclaratorInfo *ASTContext::getTrivialDeclaratorInfo(QualType T,
959                                                     SourceLocation L) {
960  DeclaratorInfo *DI = CreateDeclaratorInfo(T);
961  DI->getTypeLoc().initialize(L);
962  return DI;
963}
964
965/// getInterfaceLayoutImpl - Get or compute information about the
966/// layout of the given interface.
967///
968/// \param Impl - If given, also include the layout of the interface's
969/// implementation. This may differ by including synthesized ivars.
970const ASTRecordLayout &
971ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
972                          const ObjCImplementationDecl *Impl) {
973  assert(!D->isForwardDecl() && "Invalid interface decl!");
974
975  // Look up this layout, if already laid out, return what we have.
976  ObjCContainerDecl *Key =
977    Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
978  if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
979    return *Entry;
980
981  // Add in synthesized ivar count if laying out an implementation.
982  if (Impl) {
983    unsigned FieldCount = D->ivar_size();
984    unsigned SynthCount = CountSynthesizedIvars(D);
985    FieldCount += SynthCount;
986    // If there aren't any sythesized ivars then reuse the interface
987    // entry. Note we can't cache this because we simply free all
988    // entries later; however we shouldn't look up implementations
989    // frequently.
990    if (SynthCount == 0)
991      return getObjCLayout(D, 0);
992  }
993
994  const ASTRecordLayout *NewEntry =
995    ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
996  ObjCLayouts[Key] = NewEntry;
997
998  return *NewEntry;
999}
1000
1001const ASTRecordLayout &
1002ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1003  return getObjCLayout(D, 0);
1004}
1005
1006const ASTRecordLayout &
1007ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1008  return getObjCLayout(D->getClassInterface(), D);
1009}
1010
1011/// getASTRecordLayout - Get or compute information about the layout of the
1012/// specified record (struct/union/class), which indicates its size and field
1013/// position information.
1014const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
1015  D = D->getDefinition(*this);
1016  assert(D && "Cannot get layout of forward declarations!");
1017
1018  // Look up this layout, if already laid out, return what we have.
1019  // Note that we can't save a reference to the entry because this function
1020  // is recursive.
1021  const ASTRecordLayout *Entry = ASTRecordLayouts[D];
1022  if (Entry) return *Entry;
1023
1024  const ASTRecordLayout *NewEntry =
1025    ASTRecordLayoutBuilder::ComputeLayout(*this, D);
1026  ASTRecordLayouts[D] = NewEntry;
1027
1028  return *NewEntry;
1029}
1030
1031//===----------------------------------------------------------------------===//
1032//                   Type creation/memoization methods
1033//===----------------------------------------------------------------------===//
1034
1035QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1036  unsigned Fast = Quals.getFastQualifiers();
1037  Quals.removeFastQualifiers();
1038
1039  // Check if we've already instantiated this type.
1040  llvm::FoldingSetNodeID ID;
1041  ExtQuals::Profile(ID, TypeNode, Quals);
1042  void *InsertPos = 0;
1043  if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1044    assert(EQ->getQualifiers() == Quals);
1045    QualType T = QualType(EQ, Fast);
1046    return T;
1047  }
1048
1049  ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
1050  ExtQualNodes.InsertNode(New, InsertPos);
1051  QualType T = QualType(New, Fast);
1052  return T;
1053}
1054
1055QualType ASTContext::getVolatileType(QualType T) {
1056  QualType CanT = getCanonicalType(T);
1057  if (CanT.isVolatileQualified()) return T;
1058
1059  QualifierCollector Quals;
1060  const Type *TypeNode = Quals.strip(T);
1061  Quals.addVolatile();
1062
1063  return getExtQualType(TypeNode, Quals);
1064}
1065
1066QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
1067  QualType CanT = getCanonicalType(T);
1068  if (CanT.getAddressSpace() == AddressSpace)
1069    return T;
1070
1071  // If we are composing extended qualifiers together, merge together
1072  // into one ExtQuals node.
1073  QualifierCollector Quals;
1074  const Type *TypeNode = Quals.strip(T);
1075
1076  // If this type already has an address space specified, it cannot get
1077  // another one.
1078  assert(!Quals.hasAddressSpace() &&
1079         "Type cannot be in multiple addr spaces!");
1080  Quals.addAddressSpace(AddressSpace);
1081
1082  return getExtQualType(TypeNode, Quals);
1083}
1084
1085QualType ASTContext::getObjCGCQualType(QualType T,
1086                                       Qualifiers::GC GCAttr) {
1087  QualType CanT = getCanonicalType(T);
1088  if (CanT.getObjCGCAttr() == GCAttr)
1089    return T;
1090
1091  if (T->isPointerType()) {
1092    QualType Pointee = T->getAs<PointerType>()->getPointeeType();
1093    if (Pointee->isAnyPointerType()) {
1094      QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1095      return getPointerType(ResultType);
1096    }
1097  }
1098
1099  // If we are composing extended qualifiers together, merge together
1100  // into one ExtQuals node.
1101  QualifierCollector Quals;
1102  const Type *TypeNode = Quals.strip(T);
1103
1104  // If this type already has an ObjCGC specified, it cannot get
1105  // another one.
1106  assert(!Quals.hasObjCGCAttr() &&
1107         "Type cannot have multiple ObjCGCs!");
1108  Quals.addObjCGCAttr(GCAttr);
1109
1110  return getExtQualType(TypeNode, Quals);
1111}
1112
1113QualType ASTContext::getNoReturnType(QualType T) {
1114  QualType ResultType;
1115  if (T->isPointerType()) {
1116    QualType Pointee = T->getAs<PointerType>()->getPointeeType();
1117    ResultType = getNoReturnType(Pointee);
1118    ResultType = getPointerType(ResultType);
1119  } else if (T->isBlockPointerType()) {
1120    QualType Pointee = T->getAs<BlockPointerType>()->getPointeeType();
1121    ResultType = getNoReturnType(Pointee);
1122    ResultType = getBlockPointerType(ResultType);
1123  } else {
1124    assert (T->isFunctionType()
1125            && "can't noreturn qualify non-pointer to function or block type");
1126
1127    if (const FunctionNoProtoType *FNPT = T->getAs<FunctionNoProtoType>()) {
1128      ResultType = getFunctionNoProtoType(FNPT->getResultType(), true);
1129    } else {
1130      const FunctionProtoType *F = T->getAs<FunctionProtoType>();
1131      ResultType
1132        = getFunctionType(F->getResultType(), F->arg_type_begin(),
1133                          F->getNumArgs(), F->isVariadic(), F->getTypeQuals(),
1134                          F->hasExceptionSpec(), F->hasAnyExceptionSpec(),
1135                          F->getNumExceptions(), F->exception_begin(), true);
1136    }
1137  }
1138
1139  return getQualifiedType(ResultType, T.getQualifiers());
1140}
1141
1142/// getComplexType - Return the uniqued reference to the type for a complex
1143/// number with the specified element type.
1144QualType ASTContext::getComplexType(QualType T) {
1145  // Unique pointers, to guarantee there is only one pointer of a particular
1146  // structure.
1147  llvm::FoldingSetNodeID ID;
1148  ComplexType::Profile(ID, T);
1149
1150  void *InsertPos = 0;
1151  if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1152    return QualType(CT, 0);
1153
1154  // If the pointee type isn't canonical, this won't be a canonical type either,
1155  // so fill in the canonical type field.
1156  QualType Canonical;
1157  if (!T.isCanonical()) {
1158    Canonical = getComplexType(getCanonicalType(T));
1159
1160    // Get the new insert position for the node we care about.
1161    ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
1162    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1163  }
1164  ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
1165  Types.push_back(New);
1166  ComplexTypes.InsertNode(New, InsertPos);
1167  return QualType(New, 0);
1168}
1169
1170QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1171  llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1172     SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1173  FixedWidthIntType *&Entry = Map[Width];
1174  if (!Entry)
1175    Entry = new FixedWidthIntType(Width, Signed);
1176  return QualType(Entry, 0);
1177}
1178
1179/// getPointerType - Return the uniqued reference to the type for a pointer to
1180/// the specified type.
1181QualType ASTContext::getPointerType(QualType T) {
1182  // Unique pointers, to guarantee there is only one pointer of a particular
1183  // structure.
1184  llvm::FoldingSetNodeID ID;
1185  PointerType::Profile(ID, T);
1186
1187  void *InsertPos = 0;
1188  if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1189    return QualType(PT, 0);
1190
1191  // If the pointee type isn't canonical, this won't be a canonical type either,
1192  // so fill in the canonical type field.
1193  QualType Canonical;
1194  if (!T.isCanonical()) {
1195    Canonical = getPointerType(getCanonicalType(T));
1196
1197    // Get the new insert position for the node we care about.
1198    PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1199    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1200  }
1201  PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
1202  Types.push_back(New);
1203  PointerTypes.InsertNode(New, InsertPos);
1204  return QualType(New, 0);
1205}
1206
1207/// getBlockPointerType - Return the uniqued reference to the type for
1208/// a pointer to the specified block.
1209QualType ASTContext::getBlockPointerType(QualType T) {
1210  assert(T->isFunctionType() && "block of function types only");
1211  // Unique pointers, to guarantee there is only one block of a particular
1212  // structure.
1213  llvm::FoldingSetNodeID ID;
1214  BlockPointerType::Profile(ID, T);
1215
1216  void *InsertPos = 0;
1217  if (BlockPointerType *PT =
1218        BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1219    return QualType(PT, 0);
1220
1221  // If the block pointee type isn't canonical, this won't be a canonical
1222  // type either so fill in the canonical type field.
1223  QualType Canonical;
1224  if (!T.isCanonical()) {
1225    Canonical = getBlockPointerType(getCanonicalType(T));
1226
1227    // Get the new insert position for the node we care about.
1228    BlockPointerType *NewIP =
1229      BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1230    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1231  }
1232  BlockPointerType *New
1233    = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
1234  Types.push_back(New);
1235  BlockPointerTypes.InsertNode(New, InsertPos);
1236  return QualType(New, 0);
1237}
1238
1239/// getLValueReferenceType - Return the uniqued reference to the type for an
1240/// lvalue reference to the specified type.
1241QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
1242  // Unique pointers, to guarantee there is only one pointer of a particular
1243  // structure.
1244  llvm::FoldingSetNodeID ID;
1245  ReferenceType::Profile(ID, T, SpelledAsLValue);
1246
1247  void *InsertPos = 0;
1248  if (LValueReferenceType *RT =
1249        LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1250    return QualType(RT, 0);
1251
1252  const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1253
1254  // If the referencee type isn't canonical, this won't be a canonical type
1255  // either, so fill in the canonical type field.
1256  QualType Canonical;
1257  if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1258    QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1259    Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
1260
1261    // Get the new insert position for the node we care about.
1262    LValueReferenceType *NewIP =
1263      LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1264    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1265  }
1266
1267  LValueReferenceType *New
1268    = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1269                                                     SpelledAsLValue);
1270  Types.push_back(New);
1271  LValueReferenceTypes.InsertNode(New, InsertPos);
1272
1273  return QualType(New, 0);
1274}
1275
1276/// getRValueReferenceType - Return the uniqued reference to the type for an
1277/// rvalue reference to the specified type.
1278QualType ASTContext::getRValueReferenceType(QualType T) {
1279  // Unique pointers, to guarantee there is only one pointer of a particular
1280  // structure.
1281  llvm::FoldingSetNodeID ID;
1282  ReferenceType::Profile(ID, T, false);
1283
1284  void *InsertPos = 0;
1285  if (RValueReferenceType *RT =
1286        RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1287    return QualType(RT, 0);
1288
1289  const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1290
1291  // If the referencee type isn't canonical, this won't be a canonical type
1292  // either, so fill in the canonical type field.
1293  QualType Canonical;
1294  if (InnerRef || !T.isCanonical()) {
1295    QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1296    Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
1297
1298    // Get the new insert position for the node we care about.
1299    RValueReferenceType *NewIP =
1300      RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1301    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1302  }
1303
1304  RValueReferenceType *New
1305    = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
1306  Types.push_back(New);
1307  RValueReferenceTypes.InsertNode(New, InsertPos);
1308  return QualType(New, 0);
1309}
1310
1311/// getMemberPointerType - Return the uniqued reference to the type for a
1312/// member pointer to the specified type, in the specified class.
1313QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
1314  // Unique pointers, to guarantee there is only one pointer of a particular
1315  // structure.
1316  llvm::FoldingSetNodeID ID;
1317  MemberPointerType::Profile(ID, T, Cls);
1318
1319  void *InsertPos = 0;
1320  if (MemberPointerType *PT =
1321      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1322    return QualType(PT, 0);
1323
1324  // If the pointee or class type isn't canonical, this won't be a canonical
1325  // type either, so fill in the canonical type field.
1326  QualType Canonical;
1327  if (!T.isCanonical()) {
1328    Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1329
1330    // Get the new insert position for the node we care about.
1331    MemberPointerType *NewIP =
1332      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1333    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1334  }
1335  MemberPointerType *New
1336    = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
1337  Types.push_back(New);
1338  MemberPointerTypes.InsertNode(New, InsertPos);
1339  return QualType(New, 0);
1340}
1341
1342/// getConstantArrayType - Return the unique reference to the type for an
1343/// array of the specified element type.
1344QualType ASTContext::getConstantArrayType(QualType EltTy,
1345                                          const llvm::APInt &ArySizeIn,
1346                                          ArrayType::ArraySizeModifier ASM,
1347                                          unsigned EltTypeQuals) {
1348  assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1349         "Constant array of VLAs is illegal!");
1350
1351  // Convert the array size into a canonical width matching the pointer size for
1352  // the target.
1353  llvm::APInt ArySize(ArySizeIn);
1354  ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1355
1356  llvm::FoldingSetNodeID ID;
1357  ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
1358
1359  void *InsertPos = 0;
1360  if (ConstantArrayType *ATP =
1361      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1362    return QualType(ATP, 0);
1363
1364  // If the element type isn't canonical, this won't be a canonical type either,
1365  // so fill in the canonical type field.
1366  QualType Canonical;
1367  if (!EltTy.isCanonical()) {
1368    Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
1369                                     ASM, EltTypeQuals);
1370    // Get the new insert position for the node we care about.
1371    ConstantArrayType *NewIP =
1372      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1373    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1374  }
1375
1376  ConstantArrayType *New = new(*this,TypeAlignment)
1377    ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
1378  ConstantArrayTypes.InsertNode(New, InsertPos);
1379  Types.push_back(New);
1380  return QualType(New, 0);
1381}
1382
1383/// getVariableArrayType - Returns a non-unique reference to the type for a
1384/// variable array of the specified element type.
1385QualType ASTContext::getVariableArrayType(QualType EltTy,
1386                                          Expr *NumElts,
1387                                          ArrayType::ArraySizeModifier ASM,
1388                                          unsigned EltTypeQuals,
1389                                          SourceRange Brackets) {
1390  // Since we don't unique expressions, it isn't possible to unique VLA's
1391  // that have an expression provided for their size.
1392
1393  VariableArrayType *New = new(*this, TypeAlignment)
1394    VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
1395
1396  VariableArrayTypes.push_back(New);
1397  Types.push_back(New);
1398  return QualType(New, 0);
1399}
1400
1401/// getDependentSizedArrayType - Returns a non-unique reference to
1402/// the type for a dependently-sized array of the specified element
1403/// type.
1404QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1405                                                Expr *NumElts,
1406                                                ArrayType::ArraySizeModifier ASM,
1407                                                unsigned EltTypeQuals,
1408                                                SourceRange Brackets) {
1409  assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1410         "Size must be type- or value-dependent!");
1411
1412  llvm::FoldingSetNodeID ID;
1413  DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1414                                   EltTypeQuals, NumElts);
1415
1416  void *InsertPos = 0;
1417  DependentSizedArrayType *Canon
1418    = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1419  DependentSizedArrayType *New;
1420  if (Canon) {
1421    // We already have a canonical version of this array type; use it as
1422    // the canonical type for a newly-built type.
1423    New = new (*this, TypeAlignment)
1424      DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1425                              NumElts, ASM, EltTypeQuals, Brackets);
1426  } else {
1427    QualType CanonEltTy = getCanonicalType(EltTy);
1428    if (CanonEltTy == EltTy) {
1429      New = new (*this, TypeAlignment)
1430        DependentSizedArrayType(*this, EltTy, QualType(),
1431                                NumElts, ASM, EltTypeQuals, Brackets);
1432      DependentSizedArrayTypes.InsertNode(New, InsertPos);
1433    } else {
1434      QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1435                                                  ASM, EltTypeQuals,
1436                                                  SourceRange());
1437      New = new (*this, TypeAlignment)
1438        DependentSizedArrayType(*this, EltTy, Canon,
1439                                NumElts, ASM, EltTypeQuals, Brackets);
1440    }
1441  }
1442
1443  Types.push_back(New);
1444  return QualType(New, 0);
1445}
1446
1447QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1448                                            ArrayType::ArraySizeModifier ASM,
1449                                            unsigned EltTypeQuals) {
1450  llvm::FoldingSetNodeID ID;
1451  IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
1452
1453  void *InsertPos = 0;
1454  if (IncompleteArrayType *ATP =
1455       IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1456    return QualType(ATP, 0);
1457
1458  // If the element type isn't canonical, this won't be a canonical type
1459  // either, so fill in the canonical type field.
1460  QualType Canonical;
1461
1462  if (!EltTy.isCanonical()) {
1463    Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
1464                                       ASM, EltTypeQuals);
1465
1466    // Get the new insert position for the node we care about.
1467    IncompleteArrayType *NewIP =
1468      IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1469    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1470  }
1471
1472  IncompleteArrayType *New = new (*this, TypeAlignment)
1473    IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
1474
1475  IncompleteArrayTypes.InsertNode(New, InsertPos);
1476  Types.push_back(New);
1477  return QualType(New, 0);
1478}
1479
1480/// getVectorType - Return the unique reference to a vector type of
1481/// the specified element type and size. VectorType must be a built-in type.
1482QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
1483  BuiltinType *baseType;
1484
1485  baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1486  assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
1487
1488  // Check if we've already instantiated a vector of this type.
1489  llvm::FoldingSetNodeID ID;
1490  VectorType::Profile(ID, vecType, NumElts, Type::Vector);
1491  void *InsertPos = 0;
1492  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1493    return QualType(VTP, 0);
1494
1495  // If the element type isn't canonical, this won't be a canonical type either,
1496  // so fill in the canonical type field.
1497  QualType Canonical;
1498  if (!vecType.isCanonical()) {
1499    Canonical = getVectorType(getCanonicalType(vecType), NumElts);
1500
1501    // Get the new insert position for the node we care about.
1502    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1503    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1504  }
1505  VectorType *New = new (*this, TypeAlignment)
1506    VectorType(vecType, NumElts, Canonical);
1507  VectorTypes.InsertNode(New, InsertPos);
1508  Types.push_back(New);
1509  return QualType(New, 0);
1510}
1511
1512/// getExtVectorType - Return the unique reference to an extended vector type of
1513/// the specified element type and size. VectorType must be a built-in type.
1514QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
1515  BuiltinType *baseType;
1516
1517  baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1518  assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
1519
1520  // Check if we've already instantiated a vector of this type.
1521  llvm::FoldingSetNodeID ID;
1522  VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
1523  void *InsertPos = 0;
1524  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1525    return QualType(VTP, 0);
1526
1527  // If the element type isn't canonical, this won't be a canonical type either,
1528  // so fill in the canonical type field.
1529  QualType Canonical;
1530  if (!vecType.isCanonical()) {
1531    Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
1532
1533    // Get the new insert position for the node we care about.
1534    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1535    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1536  }
1537  ExtVectorType *New = new (*this, TypeAlignment)
1538    ExtVectorType(vecType, NumElts, Canonical);
1539  VectorTypes.InsertNode(New, InsertPos);
1540  Types.push_back(New);
1541  return QualType(New, 0);
1542}
1543
1544QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1545                                                    Expr *SizeExpr,
1546                                                    SourceLocation AttrLoc) {
1547  llvm::FoldingSetNodeID ID;
1548  DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
1549                                       SizeExpr);
1550
1551  void *InsertPos = 0;
1552  DependentSizedExtVectorType *Canon
1553    = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1554  DependentSizedExtVectorType *New;
1555  if (Canon) {
1556    // We already have a canonical version of this array type; use it as
1557    // the canonical type for a newly-built type.
1558    New = new (*this, TypeAlignment)
1559      DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1560                                  SizeExpr, AttrLoc);
1561  } else {
1562    QualType CanonVecTy = getCanonicalType(vecType);
1563    if (CanonVecTy == vecType) {
1564      New = new (*this, TypeAlignment)
1565        DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1566                                    AttrLoc);
1567      DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1568    } else {
1569      QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1570                                                      SourceLocation());
1571      New = new (*this, TypeAlignment)
1572        DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
1573    }
1574  }
1575
1576  Types.push_back(New);
1577  return QualType(New, 0);
1578}
1579
1580/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
1581///
1582QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn) {
1583  // Unique functions, to guarantee there is only one function of a particular
1584  // structure.
1585  llvm::FoldingSetNodeID ID;
1586  FunctionNoProtoType::Profile(ID, ResultTy, NoReturn);
1587
1588  void *InsertPos = 0;
1589  if (FunctionNoProtoType *FT =
1590        FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1591    return QualType(FT, 0);
1592
1593  QualType Canonical;
1594  if (!ResultTy.isCanonical()) {
1595    Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn);
1596
1597    // Get the new insert position for the node we care about.
1598    FunctionNoProtoType *NewIP =
1599      FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1600    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1601  }
1602
1603  FunctionNoProtoType *New = new (*this, TypeAlignment)
1604    FunctionNoProtoType(ResultTy, Canonical, NoReturn);
1605  Types.push_back(New);
1606  FunctionNoProtoTypes.InsertNode(New, InsertPos);
1607  return QualType(New, 0);
1608}
1609
1610/// getFunctionType - Return a normal function type with a typed argument
1611/// list.  isVariadic indicates whether the argument list includes '...'.
1612QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
1613                                     unsigned NumArgs, bool isVariadic,
1614                                     unsigned TypeQuals, bool hasExceptionSpec,
1615                                     bool hasAnyExceptionSpec, unsigned NumExs,
1616                                     const QualType *ExArray, bool NoReturn) {
1617  // Unique functions, to guarantee there is only one function of a particular
1618  // structure.
1619  llvm::FoldingSetNodeID ID;
1620  FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
1621                             TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1622                             NumExs, ExArray, NoReturn);
1623
1624  void *InsertPos = 0;
1625  if (FunctionProtoType *FTP =
1626        FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1627    return QualType(FTP, 0);
1628
1629  // Determine whether the type being created is already canonical or not.
1630  bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
1631  for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1632    if (!ArgArray[i].isCanonicalAsParam())
1633      isCanonical = false;
1634
1635  // If this type isn't canonical, get the canonical version of it.
1636  // The exception spec is not part of the canonical type.
1637  QualType Canonical;
1638  if (!isCanonical) {
1639    llvm::SmallVector<QualType, 16> CanonicalArgs;
1640    CanonicalArgs.reserve(NumArgs);
1641    for (unsigned i = 0; i != NumArgs; ++i)
1642      CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
1643
1644    Canonical = getFunctionType(getCanonicalType(ResultTy),
1645                                CanonicalArgs.data(), NumArgs,
1646                                isVariadic, TypeQuals, false,
1647                                false, 0, 0, NoReturn);
1648
1649    // Get the new insert position for the node we care about.
1650    FunctionProtoType *NewIP =
1651      FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1652    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1653  }
1654
1655  // FunctionProtoType objects are allocated with extra bytes after them
1656  // for two variable size arrays (for parameter and exception types) at the
1657  // end of them.
1658  FunctionProtoType *FTP =
1659    (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1660                                 NumArgs*sizeof(QualType) +
1661                                 NumExs*sizeof(QualType), TypeAlignment);
1662  new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
1663                              TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1664                              ExArray, NumExs, Canonical, NoReturn);
1665  Types.push_back(FTP);
1666  FunctionProtoTypes.InsertNode(FTP, InsertPos);
1667  return QualType(FTP, 0);
1668}
1669
1670/// getTypeDeclType - Return the unique reference to the type for the
1671/// specified type declaration.
1672QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
1673  assert(Decl && "Passed null for Decl param");
1674  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1675
1676  if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
1677    return getTypedefType(Typedef);
1678  else if (isa<TemplateTypeParmDecl>(Decl)) {
1679    assert(false && "Template type parameter types are always available.");
1680  } else if (ObjCInterfaceDecl *ObjCInterface
1681               = dyn_cast<ObjCInterfaceDecl>(Decl))
1682    return getObjCInterfaceType(ObjCInterface);
1683
1684  if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
1685    if (PrevDecl)
1686      Decl->TypeForDecl = PrevDecl->TypeForDecl;
1687    else
1688      Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
1689  } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1690    if (PrevDecl)
1691      Decl->TypeForDecl = PrevDecl->TypeForDecl;
1692    else
1693      Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
1694  } else
1695    assert(false && "TypeDecl without a type?");
1696
1697  if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
1698  return QualType(Decl->TypeForDecl, 0);
1699}
1700
1701/// getTypedefType - Return the unique reference to the type for the
1702/// specified typename decl.
1703QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1704  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1705
1706  QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
1707  Decl->TypeForDecl = new(*this, TypeAlignment)
1708    TypedefType(Type::Typedef, Decl, Canonical);
1709  Types.push_back(Decl->TypeForDecl);
1710  return QualType(Decl->TypeForDecl, 0);
1711}
1712
1713/// \brief Retrieve a substitution-result type.
1714QualType
1715ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1716                                         QualType Replacement) {
1717  assert(Replacement.isCanonical()
1718         && "replacement types must always be canonical");
1719
1720  llvm::FoldingSetNodeID ID;
1721  SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1722  void *InsertPos = 0;
1723  SubstTemplateTypeParmType *SubstParm
1724    = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1725
1726  if (!SubstParm) {
1727    SubstParm = new (*this, TypeAlignment)
1728      SubstTemplateTypeParmType(Parm, Replacement);
1729    Types.push_back(SubstParm);
1730    SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1731  }
1732
1733  return QualType(SubstParm, 0);
1734}
1735
1736/// \brief Retrieve the template type parameter type for a template
1737/// parameter or parameter pack with the given depth, index, and (optionally)
1738/// name.
1739QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
1740                                             bool ParameterPack,
1741                                             IdentifierInfo *Name) {
1742  llvm::FoldingSetNodeID ID;
1743  TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
1744  void *InsertPos = 0;
1745  TemplateTypeParmType *TypeParm
1746    = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1747
1748  if (TypeParm)
1749    return QualType(TypeParm, 0);
1750
1751  if (Name) {
1752    QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1753    TypeParm = new (*this, TypeAlignment)
1754      TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
1755  } else
1756    TypeParm = new (*this, TypeAlignment)
1757      TemplateTypeParmType(Depth, Index, ParameterPack);
1758
1759  Types.push_back(TypeParm);
1760  TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1761
1762  return QualType(TypeParm, 0);
1763}
1764
1765QualType
1766ASTContext::getTemplateSpecializationType(TemplateName Template,
1767                                          const TemplateArgument *Args,
1768                                          unsigned NumArgs,
1769                                          QualType Canon) {
1770  if (!Canon.isNull())
1771    Canon = getCanonicalType(Canon);
1772  else {
1773    // Build the canonical template specialization type.
1774    TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1775    llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1776    CanonArgs.reserve(NumArgs);
1777    for (unsigned I = 0; I != NumArgs; ++I)
1778      CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1779
1780    // Determine whether this canonical template specialization type already
1781    // exists.
1782    llvm::FoldingSetNodeID ID;
1783    TemplateSpecializationType::Profile(ID, CanonTemplate,
1784                                        CanonArgs.data(), NumArgs, *this);
1785
1786    void *InsertPos = 0;
1787    TemplateSpecializationType *Spec
1788      = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1789
1790    if (!Spec) {
1791      // Allocate a new canonical template specialization type.
1792      void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1793                            sizeof(TemplateArgument) * NumArgs),
1794                           TypeAlignment);
1795      Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
1796                                                  CanonArgs.data(), NumArgs,
1797                                                  Canon);
1798      Types.push_back(Spec);
1799      TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1800    }
1801
1802    if (Canon.isNull())
1803      Canon = QualType(Spec, 0);
1804    assert(Canon->isDependentType() &&
1805           "Non-dependent template-id type must have a canonical type");
1806  }
1807
1808  // Allocate the (non-canonical) template specialization type, but don't
1809  // try to unique it: these types typically have location information that
1810  // we don't unique and don't want to lose.
1811  void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1812                        sizeof(TemplateArgument) * NumArgs),
1813                       TypeAlignment);
1814  TemplateSpecializationType *Spec
1815    = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
1816                                           Canon);
1817
1818  Types.push_back(Spec);
1819  return QualType(Spec, 0);
1820}
1821
1822QualType
1823ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
1824                                 QualType NamedType) {
1825  llvm::FoldingSetNodeID ID;
1826  QualifiedNameType::Profile(ID, NNS, NamedType);
1827
1828  void *InsertPos = 0;
1829  QualifiedNameType *T
1830    = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1831  if (T)
1832    return QualType(T, 0);
1833
1834  T = new (*this) QualifiedNameType(NNS, NamedType,
1835                                    getCanonicalType(NamedType));
1836  Types.push_back(T);
1837  QualifiedNameTypes.InsertNode(T, InsertPos);
1838  return QualType(T, 0);
1839}
1840
1841QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1842                                     const IdentifierInfo *Name,
1843                                     QualType Canon) {
1844  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1845
1846  if (Canon.isNull()) {
1847    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1848    if (CanonNNS != NNS)
1849      Canon = getTypenameType(CanonNNS, Name);
1850  }
1851
1852  llvm::FoldingSetNodeID ID;
1853  TypenameType::Profile(ID, NNS, Name);
1854
1855  void *InsertPos = 0;
1856  TypenameType *T
1857    = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1858  if (T)
1859    return QualType(T, 0);
1860
1861  T = new (*this) TypenameType(NNS, Name, Canon);
1862  Types.push_back(T);
1863  TypenameTypes.InsertNode(T, InsertPos);
1864  return QualType(T, 0);
1865}
1866
1867QualType
1868ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1869                            const TemplateSpecializationType *TemplateId,
1870                            QualType Canon) {
1871  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1872
1873  if (Canon.isNull()) {
1874    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1875    QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1876    if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1877      const TemplateSpecializationType *CanonTemplateId
1878        = CanonType->getAs<TemplateSpecializationType>();
1879      assert(CanonTemplateId &&
1880             "Canonical type must also be a template specialization type");
1881      Canon = getTypenameType(CanonNNS, CanonTemplateId);
1882    }
1883  }
1884
1885  llvm::FoldingSetNodeID ID;
1886  TypenameType::Profile(ID, NNS, TemplateId);
1887
1888  void *InsertPos = 0;
1889  TypenameType *T
1890    = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1891  if (T)
1892    return QualType(T, 0);
1893
1894  T = new (*this) TypenameType(NNS, TemplateId, Canon);
1895  Types.push_back(T);
1896  TypenameTypes.InsertNode(T, InsertPos);
1897  return QualType(T, 0);
1898}
1899
1900QualType
1901ASTContext::getElaboratedType(QualType UnderlyingType,
1902                              ElaboratedType::TagKind Tag) {
1903  llvm::FoldingSetNodeID ID;
1904  ElaboratedType::Profile(ID, UnderlyingType, Tag);
1905
1906  void *InsertPos = 0;
1907  ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1908  if (T)
1909    return QualType(T, 0);
1910
1911  QualType Canon = getCanonicalType(UnderlyingType);
1912
1913  T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
1914  Types.push_back(T);
1915  ElaboratedTypes.InsertNode(T, InsertPos);
1916  return QualType(T, 0);
1917}
1918
1919/// CmpProtocolNames - Comparison predicate for sorting protocols
1920/// alphabetically.
1921static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1922                            const ObjCProtocolDecl *RHS) {
1923  return LHS->getDeclName() < RHS->getDeclName();
1924}
1925
1926static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
1927                                unsigned NumProtocols) {
1928  if (NumProtocols == 0) return true;
1929
1930  for (unsigned i = 1; i != NumProtocols; ++i)
1931    if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
1932      return false;
1933  return true;
1934}
1935
1936static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
1937                                   unsigned &NumProtocols) {
1938  ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1939
1940  // Sort protocols, keyed by name.
1941  std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1942
1943  // Remove duplicates.
1944  ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1945  NumProtocols = ProtocolsEnd-Protocols;
1946}
1947
1948/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1949/// the given interface decl and the conforming protocol list.
1950QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
1951                                              ObjCProtocolDecl **Protocols,
1952                                              unsigned NumProtocols) {
1953  llvm::FoldingSetNodeID ID;
1954  ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
1955
1956  void *InsertPos = 0;
1957  if (ObjCObjectPointerType *QT =
1958              ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1959    return QualType(QT, 0);
1960
1961  // Sort the protocol list alphabetically to canonicalize it.
1962  QualType Canonical;
1963  if (!InterfaceT.isCanonical() ||
1964      !areSortedAndUniqued(Protocols, NumProtocols)) {
1965    if (!areSortedAndUniqued(Protocols, NumProtocols)) {
1966      llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
1967      unsigned UniqueCount = NumProtocols;
1968
1969      std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
1970      SortAndUniqueProtocols(&Sorted[0], UniqueCount);
1971
1972      Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
1973                                           &Sorted[0], UniqueCount);
1974    } else {
1975      Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
1976                                           Protocols, NumProtocols);
1977    }
1978
1979    // Regenerate InsertPos.
1980    ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1981  }
1982
1983  // No Match;
1984  ObjCObjectPointerType *QType = new (*this, TypeAlignment)
1985    ObjCObjectPointerType(Canonical, InterfaceT, Protocols, NumProtocols);
1986
1987  Types.push_back(QType);
1988  ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1989  return QualType(QType, 0);
1990}
1991
1992/// getObjCInterfaceType - Return the unique reference to the type for the
1993/// specified ObjC interface decl. The list of protocols is optional.
1994QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
1995                       ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
1996  llvm::FoldingSetNodeID ID;
1997  ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
1998
1999  void *InsertPos = 0;
2000  if (ObjCInterfaceType *QT =
2001      ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
2002    return QualType(QT, 0);
2003
2004  // Sort the protocol list alphabetically to canonicalize it.
2005  QualType Canonical;
2006  if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2007    llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2008    std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2009
2010    unsigned UniqueCount = NumProtocols;
2011    SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2012
2013    Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2014
2015    ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2016  }
2017
2018  ObjCInterfaceType *QType = new (*this, TypeAlignment)
2019    ObjCInterfaceType(Canonical, const_cast<ObjCInterfaceDecl*>(Decl),
2020                      Protocols, NumProtocols);
2021
2022  Types.push_back(QType);
2023  ObjCInterfaceTypes.InsertNode(QType, InsertPos);
2024  return QualType(QType, 0);
2025}
2026
2027/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2028/// TypeOfExprType AST's (since expression's are never shared). For example,
2029/// multiple declarations that refer to "typeof(x)" all contain different
2030/// DeclRefExpr's. This doesn't effect the type checker, since it operates
2031/// on canonical type's (which are always unique).
2032QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
2033  TypeOfExprType *toe;
2034  if (tofExpr->isTypeDependent()) {
2035    llvm::FoldingSetNodeID ID;
2036    DependentTypeOfExprType::Profile(ID, *this, tofExpr);
2037
2038    void *InsertPos = 0;
2039    DependentTypeOfExprType *Canon
2040      = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2041    if (Canon) {
2042      // We already have a "canonical" version of an identical, dependent
2043      // typeof(expr) type. Use that as our canonical type.
2044      toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
2045                                          QualType((TypeOfExprType*)Canon, 0));
2046    }
2047    else {
2048      // Build a new, canonical typeof(expr) type.
2049      Canon
2050        = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
2051      DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2052      toe = Canon;
2053    }
2054  } else {
2055    QualType Canonical = getCanonicalType(tofExpr->getType());
2056    toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
2057  }
2058  Types.push_back(toe);
2059  return QualType(toe, 0);
2060}
2061
2062/// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
2063/// TypeOfType AST's. The only motivation to unique these nodes would be
2064/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
2065/// an issue. This doesn't effect the type checker, since it operates
2066/// on canonical type's (which are always unique).
2067QualType ASTContext::getTypeOfType(QualType tofType) {
2068  QualType Canonical = getCanonicalType(tofType);
2069  TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
2070  Types.push_back(tot);
2071  return QualType(tot, 0);
2072}
2073
2074/// getDecltypeForExpr - Given an expr, will return the decltype for that
2075/// expression, according to the rules in C++0x [dcl.type.simple]p4
2076static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
2077  if (e->isTypeDependent())
2078    return Context.DependentTy;
2079
2080  // If e is an id expression or a class member access, decltype(e) is defined
2081  // as the type of the entity named by e.
2082  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2083    if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2084      return VD->getType();
2085  }
2086  if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2087    if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2088      return FD->getType();
2089  }
2090  // If e is a function call or an invocation of an overloaded operator,
2091  // (parentheses around e are ignored), decltype(e) is defined as the
2092  // return type of that function.
2093  if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2094    return CE->getCallReturnType();
2095
2096  QualType T = e->getType();
2097
2098  // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
2099  // defined as T&, otherwise decltype(e) is defined as T.
2100  if (e->isLvalue(Context) == Expr::LV_Valid)
2101    T = Context.getLValueReferenceType(T);
2102
2103  return T;
2104}
2105
2106/// getDecltypeType -  Unlike many "get<Type>" functions, we don't unique
2107/// DecltypeType AST's. The only motivation to unique these nodes would be
2108/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
2109/// an issue. This doesn't effect the type checker, since it operates
2110/// on canonical type's (which are always unique).
2111QualType ASTContext::getDecltypeType(Expr *e) {
2112  DecltypeType *dt;
2113  if (e->isTypeDependent()) {
2114    llvm::FoldingSetNodeID ID;
2115    DependentDecltypeType::Profile(ID, *this, e);
2116
2117    void *InsertPos = 0;
2118    DependentDecltypeType *Canon
2119      = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2120    if (Canon) {
2121      // We already have a "canonical" version of an equivalent, dependent
2122      // decltype type. Use that as our canonical type.
2123      dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
2124                                       QualType((DecltypeType*)Canon, 0));
2125    }
2126    else {
2127      // Build a new, canonical typeof(expr) type.
2128      Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
2129      DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2130      dt = Canon;
2131    }
2132  } else {
2133    QualType T = getDecltypeForExpr(e, *this);
2134    dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
2135  }
2136  Types.push_back(dt);
2137  return QualType(dt, 0);
2138}
2139
2140/// getTagDeclType - Return the unique reference to the type for the
2141/// specified TagDecl (struct/union/class/enum) decl.
2142QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
2143  assert (Decl);
2144  // FIXME: What is the design on getTagDeclType when it requires casting
2145  // away const?  mutable?
2146  return getTypeDeclType(const_cast<TagDecl*>(Decl));
2147}
2148
2149/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2150/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2151/// needs to agree with the definition in <stddef.h>.
2152QualType ASTContext::getSizeType() const {
2153  return getFromTargetType(Target.getSizeType());
2154}
2155
2156/// getSignedWCharType - Return the type of "signed wchar_t".
2157/// Used when in C++, as a GCC extension.
2158QualType ASTContext::getSignedWCharType() const {
2159  // FIXME: derive from "Target" ?
2160  return WCharTy;
2161}
2162
2163/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2164/// Used when in C++, as a GCC extension.
2165QualType ASTContext::getUnsignedWCharType() const {
2166  // FIXME: derive from "Target" ?
2167  return UnsignedIntTy;
2168}
2169
2170/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2171/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2172QualType ASTContext::getPointerDiffType() const {
2173  return getFromTargetType(Target.getPtrDiffType(0));
2174}
2175
2176//===----------------------------------------------------------------------===//
2177//                              Type Operators
2178//===----------------------------------------------------------------------===//
2179
2180CanQualType ASTContext::getCanonicalParamType(QualType T) {
2181  // Push qualifiers into arrays, and then discard any remaining
2182  // qualifiers.
2183  T = getCanonicalType(T);
2184  const Type *Ty = T.getTypePtr();
2185
2186  QualType Result;
2187  if (isa<ArrayType>(Ty)) {
2188    Result = getArrayDecayedType(QualType(Ty,0));
2189  } else if (isa<FunctionType>(Ty)) {
2190    Result = getPointerType(QualType(Ty, 0));
2191  } else {
2192    Result = QualType(Ty, 0);
2193  }
2194
2195  return CanQualType::CreateUnsafe(Result);
2196}
2197
2198/// getCanonicalType - Return the canonical (structural) type corresponding to
2199/// the specified potentially non-canonical type.  The non-canonical version
2200/// of a type may have many "decorated" versions of types.  Decorators can
2201/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2202/// to be free of any of these, allowing two canonical types to be compared
2203/// for exact equality with a simple pointer comparison.
2204CanQualType ASTContext::getCanonicalType(QualType T) {
2205  QualifierCollector Quals;
2206  const Type *Ptr = Quals.strip(T);
2207  QualType CanType = Ptr->getCanonicalTypeInternal();
2208
2209  // The canonical internal type will be the canonical type *except*
2210  // that we push type qualifiers down through array types.
2211
2212  // If there are no new qualifiers to push down, stop here.
2213  if (!Quals.hasQualifiers())
2214    return CanQualType::CreateUnsafe(CanType);
2215
2216  // If the type qualifiers are on an array type, get the canonical
2217  // type of the array with the qualifiers applied to the element
2218  // type.
2219  ArrayType *AT = dyn_cast<ArrayType>(CanType);
2220  if (!AT)
2221    return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
2222
2223  // Get the canonical version of the element with the extra qualifiers on it.
2224  // This can recursively sink qualifiers through multiple levels of arrays.
2225  QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
2226  NewEltTy = getCanonicalType(NewEltTy);
2227
2228  if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2229    return CanQualType::CreateUnsafe(
2230             getConstantArrayType(NewEltTy, CAT->getSize(),
2231                                  CAT->getSizeModifier(),
2232                                  CAT->getIndexTypeCVRQualifiers()));
2233  if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
2234    return CanQualType::CreateUnsafe(
2235             getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
2236                                    IAT->getIndexTypeCVRQualifiers()));
2237
2238  if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
2239    return CanQualType::CreateUnsafe(
2240             getDependentSizedArrayType(NewEltTy,
2241                                        DSAT->getSizeExpr() ?
2242                                          DSAT->getSizeExpr()->Retain() : 0,
2243                                        DSAT->getSizeModifier(),
2244                                        DSAT->getIndexTypeCVRQualifiers(),
2245                                        DSAT->getBracketsRange()));
2246
2247  VariableArrayType *VAT = cast<VariableArrayType>(AT);
2248  return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
2249                                                        VAT->getSizeExpr() ?
2250                                              VAT->getSizeExpr()->Retain() : 0,
2251                                                        VAT->getSizeModifier(),
2252                                              VAT->getIndexTypeCVRQualifiers(),
2253                                                     VAT->getBracketsRange()));
2254}
2255
2256TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2257  // If this template name refers to a template, the canonical
2258  // template name merely stores the template itself.
2259  if (TemplateDecl *Template = Name.getAsTemplateDecl())
2260    return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
2261
2262  // If this template name refers to a set of overloaded function templates,
2263  /// the canonical template name merely stores the set of function templates.
2264  if (OverloadedFunctionDecl *Ovl = Name.getAsOverloadedFunctionDecl()) {
2265    OverloadedFunctionDecl *CanonOvl = 0;
2266    for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
2267                                                FEnd = Ovl->function_end();
2268         F != FEnd; ++F) {
2269      Decl *Canon = F->get()->getCanonicalDecl();
2270      if (CanonOvl || Canon != F->get()) {
2271        if (!CanonOvl)
2272          CanonOvl = OverloadedFunctionDecl::Create(*this,
2273                                                    Ovl->getDeclContext(),
2274                                                    Ovl->getDeclName());
2275
2276        CanonOvl->addOverload(
2277                    AnyFunctionDecl::getFromNamedDecl(cast<NamedDecl>(Canon)));
2278      }
2279    }
2280
2281    return TemplateName(CanonOvl? CanonOvl : Ovl);
2282  }
2283
2284  DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2285  assert(DTN && "Non-dependent template names must refer to template decls.");
2286  return DTN->CanonicalTemplateName;
2287}
2288
2289TemplateArgument
2290ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2291  switch (Arg.getKind()) {
2292    case TemplateArgument::Null:
2293      return Arg;
2294
2295    case TemplateArgument::Expression:
2296      // FIXME: Build canonical expression?
2297      return Arg;
2298
2299    case TemplateArgument::Declaration:
2300      return TemplateArgument(SourceLocation(),
2301                              Arg.getAsDecl()->getCanonicalDecl());
2302
2303    case TemplateArgument::Integral:
2304      return TemplateArgument(SourceLocation(),
2305                              *Arg.getAsIntegral(),
2306                              getCanonicalType(Arg.getIntegralType()));
2307
2308    case TemplateArgument::Type:
2309      return TemplateArgument(SourceLocation(),
2310                              getCanonicalType(Arg.getAsType()));
2311
2312    case TemplateArgument::Pack: {
2313      // FIXME: Allocate in ASTContext
2314      TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2315      unsigned Idx = 0;
2316      for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
2317                                        AEnd = Arg.pack_end();
2318           A != AEnd; (void)++A, ++Idx)
2319        CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
2320
2321      TemplateArgument Result;
2322      Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2323      return Result;
2324    }
2325  }
2326
2327  // Silence GCC warning
2328  assert(false && "Unhandled template argument kind");
2329  return TemplateArgument();
2330}
2331
2332NestedNameSpecifier *
2333ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
2334  if (!NNS)
2335    return 0;
2336
2337  switch (NNS->getKind()) {
2338  case NestedNameSpecifier::Identifier:
2339    // Canonicalize the prefix but keep the identifier the same.
2340    return NestedNameSpecifier::Create(*this,
2341                         getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2342                                       NNS->getAsIdentifier());
2343
2344  case NestedNameSpecifier::Namespace:
2345    // A namespace is canonical; build a nested-name-specifier with
2346    // this namespace and no prefix.
2347    return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2348
2349  case NestedNameSpecifier::TypeSpec:
2350  case NestedNameSpecifier::TypeSpecWithTemplate: {
2351    QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
2352    return NestedNameSpecifier::Create(*this, 0,
2353                 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
2354                                       T.getTypePtr());
2355  }
2356
2357  case NestedNameSpecifier::Global:
2358    // The global specifier is canonical and unique.
2359    return NNS;
2360  }
2361
2362  // Required to silence a GCC warning
2363  return 0;
2364}
2365
2366
2367const ArrayType *ASTContext::getAsArrayType(QualType T) {
2368  // Handle the non-qualified case efficiently.
2369  if (!T.hasQualifiers()) {
2370    // Handle the common positive case fast.
2371    if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2372      return AT;
2373  }
2374
2375  // Handle the common negative case fast.
2376  QualType CType = T->getCanonicalTypeInternal();
2377  if (!isa<ArrayType>(CType))
2378    return 0;
2379
2380  // Apply any qualifiers from the array type to the element type.  This
2381  // implements C99 6.7.3p8: "If the specification of an array type includes
2382  // any type qualifiers, the element type is so qualified, not the array type."
2383
2384  // If we get here, we either have type qualifiers on the type, or we have
2385  // sugar such as a typedef in the way.  If we have type qualifiers on the type
2386  // we must propagate them down into the element type.
2387
2388  QualifierCollector Qs;
2389  const Type *Ty = Qs.strip(T.getDesugaredType());
2390
2391  // If we have a simple case, just return now.
2392  const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2393  if (ATy == 0 || Qs.empty())
2394    return ATy;
2395
2396  // Otherwise, we have an array and we have qualifiers on it.  Push the
2397  // qualifiers into the array element type and return a new array type.
2398  // Get the canonical version of the element with the extra qualifiers on it.
2399  // This can recursively sink qualifiers through multiple levels of arrays.
2400  QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
2401
2402  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2403    return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2404                                                CAT->getSizeModifier(),
2405                                           CAT->getIndexTypeCVRQualifiers()));
2406  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2407    return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2408                                                  IAT->getSizeModifier(),
2409                                           IAT->getIndexTypeCVRQualifiers()));
2410
2411  if (const DependentSizedArrayType *DSAT
2412        = dyn_cast<DependentSizedArrayType>(ATy))
2413    return cast<ArrayType>(
2414                     getDependentSizedArrayType(NewEltTy,
2415                                                DSAT->getSizeExpr() ?
2416                                              DSAT->getSizeExpr()->Retain() : 0,
2417                                                DSAT->getSizeModifier(),
2418                                              DSAT->getIndexTypeCVRQualifiers(),
2419                                                DSAT->getBracketsRange()));
2420
2421  const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
2422  return cast<ArrayType>(getVariableArrayType(NewEltTy,
2423                                              VAT->getSizeExpr() ?
2424                                              VAT->getSizeExpr()->Retain() : 0,
2425                                              VAT->getSizeModifier(),
2426                                              VAT->getIndexTypeCVRQualifiers(),
2427                                              VAT->getBracketsRange()));
2428}
2429
2430
2431/// getArrayDecayedType - Return the properly qualified result of decaying the
2432/// specified array type to a pointer.  This operation is non-trivial when
2433/// handling typedefs etc.  The canonical type of "T" must be an array type,
2434/// this returns a pointer to a properly qualified element of the array.
2435///
2436/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2437QualType ASTContext::getArrayDecayedType(QualType Ty) {
2438  // Get the element type with 'getAsArrayType' so that we don't lose any
2439  // typedefs in the element type of the array.  This also handles propagation
2440  // of type qualifiers from the array type into the element type if present
2441  // (C99 6.7.3p8).
2442  const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2443  assert(PrettyArrayType && "Not an array type!");
2444
2445  QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
2446
2447  // int x[restrict 4] ->  int *restrict
2448  return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
2449}
2450
2451QualType ASTContext::getBaseElementType(QualType QT) {
2452  QualifierCollector Qs;
2453  while (true) {
2454    const Type *UT = Qs.strip(QT);
2455    if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2456      QT = AT->getElementType();
2457    } else {
2458      return Qs.apply(QT);
2459    }
2460  }
2461}
2462
2463QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2464  QualType ElemTy = AT->getElementType();
2465
2466  if (const ArrayType *AT = getAsArrayType(ElemTy))
2467    return getBaseElementType(AT);
2468
2469  return ElemTy;
2470}
2471
2472/// getConstantArrayElementCount - Returns number of constant array elements.
2473uint64_t
2474ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
2475  uint64_t ElementCount = 1;
2476  do {
2477    ElementCount *= CA->getSize().getZExtValue();
2478    CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2479  } while (CA);
2480  return ElementCount;
2481}
2482
2483/// getFloatingRank - Return a relative rank for floating point types.
2484/// This routine will assert if passed a built-in type that isn't a float.
2485static FloatingRank getFloatingRank(QualType T) {
2486  if (const ComplexType *CT = T->getAs<ComplexType>())
2487    return getFloatingRank(CT->getElementType());
2488
2489  assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2490  switch (T->getAs<BuiltinType>()->getKind()) {
2491  default: assert(0 && "getFloatingRank(): not a floating type");
2492  case BuiltinType::Float:      return FloatRank;
2493  case BuiltinType::Double:     return DoubleRank;
2494  case BuiltinType::LongDouble: return LongDoubleRank;
2495  }
2496}
2497
2498/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2499/// point or a complex type (based on typeDomain/typeSize).
2500/// 'typeDomain' is a real floating point or complex type.
2501/// 'typeSize' is a real floating point or complex type.
2502QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2503                                                       QualType Domain) const {
2504  FloatingRank EltRank = getFloatingRank(Size);
2505  if (Domain->isComplexType()) {
2506    switch (EltRank) {
2507    default: assert(0 && "getFloatingRank(): illegal value for rank");
2508    case FloatRank:      return FloatComplexTy;
2509    case DoubleRank:     return DoubleComplexTy;
2510    case LongDoubleRank: return LongDoubleComplexTy;
2511    }
2512  }
2513
2514  assert(Domain->isRealFloatingType() && "Unknown domain!");
2515  switch (EltRank) {
2516  default: assert(0 && "getFloatingRank(): illegal value for rank");
2517  case FloatRank:      return FloatTy;
2518  case DoubleRank:     return DoubleTy;
2519  case LongDoubleRank: return LongDoubleTy;
2520  }
2521}
2522
2523/// getFloatingTypeOrder - Compare the rank of the two specified floating
2524/// point types, ignoring the domain of the type (i.e. 'double' ==
2525/// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
2526/// LHS < RHS, return -1.
2527int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2528  FloatingRank LHSR = getFloatingRank(LHS);
2529  FloatingRank RHSR = getFloatingRank(RHS);
2530
2531  if (LHSR == RHSR)
2532    return 0;
2533  if (LHSR > RHSR)
2534    return 1;
2535  return -1;
2536}
2537
2538/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2539/// routine will assert if passed a built-in type that isn't an integer or enum,
2540/// or if it is not canonicalized.
2541unsigned ASTContext::getIntegerRank(Type *T) {
2542  assert(T->isCanonicalUnqualified() && "T should be canonicalized");
2543  if (EnumType* ET = dyn_cast<EnumType>(T))
2544    T = ET->getDecl()->getIntegerType().getTypePtr();
2545
2546  if (T->isSpecificBuiltinType(BuiltinType::WChar))
2547    T = getFromTargetType(Target.getWCharType()).getTypePtr();
2548
2549  if (T->isSpecificBuiltinType(BuiltinType::Char16))
2550    T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2551
2552  if (T->isSpecificBuiltinType(BuiltinType::Char32))
2553    T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2554
2555  // There are two things which impact the integer rank: the width, and
2556  // the ordering of builtins.  The builtin ordering is encoded in the
2557  // bottom three bits; the width is encoded in the bits above that.
2558  if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
2559    return FWIT->getWidth() << 3;
2560
2561  switch (cast<BuiltinType>(T)->getKind()) {
2562  default: assert(0 && "getIntegerRank(): not a built-in integer");
2563  case BuiltinType::Bool:
2564    return 1 + (getIntWidth(BoolTy) << 3);
2565  case BuiltinType::Char_S:
2566  case BuiltinType::Char_U:
2567  case BuiltinType::SChar:
2568  case BuiltinType::UChar:
2569    return 2 + (getIntWidth(CharTy) << 3);
2570  case BuiltinType::Short:
2571  case BuiltinType::UShort:
2572    return 3 + (getIntWidth(ShortTy) << 3);
2573  case BuiltinType::Int:
2574  case BuiltinType::UInt:
2575    return 4 + (getIntWidth(IntTy) << 3);
2576  case BuiltinType::Long:
2577  case BuiltinType::ULong:
2578    return 5 + (getIntWidth(LongTy) << 3);
2579  case BuiltinType::LongLong:
2580  case BuiltinType::ULongLong:
2581    return 6 + (getIntWidth(LongLongTy) << 3);
2582  case BuiltinType::Int128:
2583  case BuiltinType::UInt128:
2584    return 7 + (getIntWidth(Int128Ty) << 3);
2585  }
2586}
2587
2588/// \brief Whether this is a promotable bitfield reference according
2589/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2590///
2591/// \returns the type this bit-field will promote to, or NULL if no
2592/// promotion occurs.
2593QualType ASTContext::isPromotableBitField(Expr *E) {
2594  FieldDecl *Field = E->getBitField();
2595  if (!Field)
2596    return QualType();
2597
2598  QualType FT = Field->getType();
2599
2600  llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2601  uint64_t BitWidth = BitWidthAP.getZExtValue();
2602  uint64_t IntSize = getTypeSize(IntTy);
2603  // GCC extension compatibility: if the bit-field size is less than or equal
2604  // to the size of int, it gets promoted no matter what its type is.
2605  // For instance, unsigned long bf : 4 gets promoted to signed int.
2606  if (BitWidth < IntSize)
2607    return IntTy;
2608
2609  if (BitWidth == IntSize)
2610    return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2611
2612  // Types bigger than int are not subject to promotions, and therefore act
2613  // like the base type.
2614  // FIXME: This doesn't quite match what gcc does, but what gcc does here
2615  // is ridiculous.
2616  return QualType();
2617}
2618
2619/// getPromotedIntegerType - Returns the type that Promotable will
2620/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2621/// integer type.
2622QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2623  assert(!Promotable.isNull());
2624  assert(Promotable->isPromotableIntegerType());
2625  if (Promotable->isSignedIntegerType())
2626    return IntTy;
2627  uint64_t PromotableSize = getTypeSize(Promotable);
2628  uint64_t IntSize = getTypeSize(IntTy);
2629  assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2630  return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2631}
2632
2633/// getIntegerTypeOrder - Returns the highest ranked integer type:
2634/// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
2635/// LHS < RHS, return -1.
2636int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
2637  Type *LHSC = getCanonicalType(LHS).getTypePtr();
2638  Type *RHSC = getCanonicalType(RHS).getTypePtr();
2639  if (LHSC == RHSC) return 0;
2640
2641  bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2642  bool RHSUnsigned = RHSC->isUnsignedIntegerType();
2643
2644  unsigned LHSRank = getIntegerRank(LHSC);
2645  unsigned RHSRank = getIntegerRank(RHSC);
2646
2647  if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
2648    if (LHSRank == RHSRank) return 0;
2649    return LHSRank > RHSRank ? 1 : -1;
2650  }
2651
2652  // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2653  if (LHSUnsigned) {
2654    // If the unsigned [LHS] type is larger, return it.
2655    if (LHSRank >= RHSRank)
2656      return 1;
2657
2658    // If the signed type can represent all values of the unsigned type, it
2659    // wins.  Because we are dealing with 2's complement and types that are
2660    // powers of two larger than each other, this is always safe.
2661    return -1;
2662  }
2663
2664  // If the unsigned [RHS] type is larger, return it.
2665  if (RHSRank >= LHSRank)
2666    return -1;
2667
2668  // If the signed type can represent all values of the unsigned type, it
2669  // wins.  Because we are dealing with 2's complement and types that are
2670  // powers of two larger than each other, this is always safe.
2671  return 1;
2672}
2673
2674// getCFConstantStringType - Return the type used for constant CFStrings.
2675QualType ASTContext::getCFConstantStringType() {
2676  if (!CFConstantStringTypeDecl) {
2677    CFConstantStringTypeDecl =
2678      RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2679                         &Idents.get("NSConstantString"));
2680    QualType FieldTypes[4];
2681
2682    // const int *isa;
2683    FieldTypes[0] = getPointerType(IntTy.withConst());
2684    // int flags;
2685    FieldTypes[1] = IntTy;
2686    // const char *str;
2687    FieldTypes[2] = getPointerType(CharTy.withConst());
2688    // long length;
2689    FieldTypes[3] = LongTy;
2690
2691    // Create fields
2692    for (unsigned i = 0; i < 4; ++i) {
2693      FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2694                                           SourceLocation(), 0,
2695                                           FieldTypes[i], /*DInfo=*/0,
2696                                           /*BitWidth=*/0,
2697                                           /*Mutable=*/false);
2698      CFConstantStringTypeDecl->addDecl(Field);
2699    }
2700
2701    CFConstantStringTypeDecl->completeDefinition(*this);
2702  }
2703
2704  return getTagDeclType(CFConstantStringTypeDecl);
2705}
2706
2707void ASTContext::setCFConstantStringType(QualType T) {
2708  const RecordType *Rec = T->getAs<RecordType>();
2709  assert(Rec && "Invalid CFConstantStringType");
2710  CFConstantStringTypeDecl = Rec->getDecl();
2711}
2712
2713QualType ASTContext::getObjCFastEnumerationStateType() {
2714  if (!ObjCFastEnumerationStateTypeDecl) {
2715    ObjCFastEnumerationStateTypeDecl =
2716      RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2717                         &Idents.get("__objcFastEnumerationState"));
2718
2719    QualType FieldTypes[] = {
2720      UnsignedLongTy,
2721      getPointerType(ObjCIdTypedefType),
2722      getPointerType(UnsignedLongTy),
2723      getConstantArrayType(UnsignedLongTy,
2724                           llvm::APInt(32, 5), ArrayType::Normal, 0)
2725    };
2726
2727    for (size_t i = 0; i < 4; ++i) {
2728      FieldDecl *Field = FieldDecl::Create(*this,
2729                                           ObjCFastEnumerationStateTypeDecl,
2730                                           SourceLocation(), 0,
2731                                           FieldTypes[i], /*DInfo=*/0,
2732                                           /*BitWidth=*/0,
2733                                           /*Mutable=*/false);
2734      ObjCFastEnumerationStateTypeDecl->addDecl(Field);
2735    }
2736
2737    ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
2738  }
2739
2740  return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2741}
2742
2743QualType ASTContext::getBlockDescriptorType() {
2744  if (BlockDescriptorType)
2745    return getTagDeclType(BlockDescriptorType);
2746
2747  RecordDecl *T;
2748  // FIXME: Needs the FlagAppleBlock bit.
2749  T = RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2750                         &Idents.get("__block_descriptor"));
2751
2752  QualType FieldTypes[] = {
2753    UnsignedLongTy,
2754    UnsignedLongTy,
2755  };
2756
2757  const char *FieldNames[] = {
2758    "reserved",
2759    "Size"
2760  };
2761
2762  for (size_t i = 0; i < 2; ++i) {
2763    FieldDecl *Field = FieldDecl::Create(*this,
2764                                         T,
2765                                         SourceLocation(),
2766                                         &Idents.get(FieldNames[i]),
2767                                         FieldTypes[i], /*DInfo=*/0,
2768                                         /*BitWidth=*/0,
2769                                         /*Mutable=*/false);
2770    T->addDecl(Field);
2771  }
2772
2773  T->completeDefinition(*this);
2774
2775  BlockDescriptorType = T;
2776
2777  return getTagDeclType(BlockDescriptorType);
2778}
2779
2780void ASTContext::setBlockDescriptorType(QualType T) {
2781  const RecordType *Rec = T->getAs<RecordType>();
2782  assert(Rec && "Invalid BlockDescriptorType");
2783  BlockDescriptorType = Rec->getDecl();
2784}
2785
2786QualType ASTContext::getBlockDescriptorExtendedType() {
2787  if (BlockDescriptorExtendedType)
2788    return getTagDeclType(BlockDescriptorExtendedType);
2789
2790  RecordDecl *T;
2791  // FIXME: Needs the FlagAppleBlock bit.
2792  T = RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2793                         &Idents.get("__block_descriptor_withcopydispose"));
2794
2795  QualType FieldTypes[] = {
2796    UnsignedLongTy,
2797    UnsignedLongTy,
2798    getPointerType(VoidPtrTy),
2799    getPointerType(VoidPtrTy)
2800  };
2801
2802  const char *FieldNames[] = {
2803    "reserved",
2804    "Size",
2805    "CopyFuncPtr",
2806    "DestroyFuncPtr"
2807  };
2808
2809  for (size_t i = 0; i < 4; ++i) {
2810    FieldDecl *Field = FieldDecl::Create(*this,
2811                                         T,
2812                                         SourceLocation(),
2813                                         &Idents.get(FieldNames[i]),
2814                                         FieldTypes[i], /*DInfo=*/0,
2815                                         /*BitWidth=*/0,
2816                                         /*Mutable=*/false);
2817    T->addDecl(Field);
2818  }
2819
2820  T->completeDefinition(*this);
2821
2822  BlockDescriptorExtendedType = T;
2823
2824  return getTagDeclType(BlockDescriptorExtendedType);
2825}
2826
2827void ASTContext::setBlockDescriptorExtendedType(QualType T) {
2828  const RecordType *Rec = T->getAs<RecordType>();
2829  assert(Rec && "Invalid BlockDescriptorType");
2830  BlockDescriptorExtendedType = Rec->getDecl();
2831}
2832
2833bool ASTContext::BlockRequiresCopying(QualType Ty) {
2834  if (Ty->isBlockPointerType())
2835    return true;
2836  if (isObjCNSObjectType(Ty))
2837    return true;
2838  if (Ty->isObjCObjectPointerType())
2839    return true;
2840  return false;
2841}
2842
2843QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
2844  //  type = struct __Block_byref_1_X {
2845  //    void *__isa;
2846  //    struct __Block_byref_1_X *__forwarding;
2847  //    unsigned int __flags;
2848  //    unsigned int __size;
2849  //    void *__copy_helper;		// as needed
2850  //    void *__destroy_help		// as needed
2851  //    int X;
2852  //  } *
2853
2854  bool HasCopyAndDispose = BlockRequiresCopying(Ty);
2855
2856  // FIXME: Move up
2857  static int UniqueBlockByRefTypeID = 0;
2858  // FIXME. This is error prone. Luckinly stack-canary stuff caught it.
2859  char Name[128];
2860  sprintf(Name, "__Block_byref_%d_%s", ++UniqueBlockByRefTypeID, DeclName);
2861  assert((strlen(Name) < sizeof(Name)) && "BuildByRefType - buffer overflow");
2862  RecordDecl *T;
2863  T = RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2864                         &Idents.get(Name));
2865  T->startDefinition();
2866  QualType Int32Ty = IntTy;
2867  assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
2868  QualType FieldTypes[] = {
2869    getPointerType(VoidPtrTy),
2870    getPointerType(getTagDeclType(T)),
2871    Int32Ty,
2872    Int32Ty,
2873    getPointerType(VoidPtrTy),
2874    getPointerType(VoidPtrTy),
2875    Ty
2876  };
2877
2878  const char *FieldNames[] = {
2879    "__isa",
2880    "__forwarding",
2881    "__flags",
2882    "__size",
2883    "__copy_helper",
2884    "__destroy_helper",
2885    DeclName,
2886  };
2887
2888  for (size_t i = 0; i < 7; ++i) {
2889    if (!HasCopyAndDispose && i >=4 && i <= 5)
2890      continue;
2891    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
2892                                         &Idents.get(FieldNames[i]),
2893                                         FieldTypes[i], /*DInfo=*/0,
2894                                         /*BitWidth=*/0, /*Mutable=*/false);
2895    T->addDecl(Field);
2896  }
2897
2898  T->completeDefinition(*this);
2899
2900  return getPointerType(getTagDeclType(T));
2901}
2902
2903
2904QualType ASTContext::getBlockParmType(
2905  bool BlockHasCopyDispose,
2906  llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
2907  // FIXME: Move up
2908  static int UniqueBlockParmTypeID = 0;
2909  // FIXME. This is error prone. Luckinly stack-canary stuff caught it.
2910  char Name[128];
2911  sprintf(Name, "__block_literal_%u", ++UniqueBlockParmTypeID);
2912  assert((strlen(Name) < sizeof(Name)) && "getBlockParmType - buffer overflow");
2913  RecordDecl *T;
2914  T = RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2915                         &Idents.get(Name));
2916  QualType FieldTypes[] = {
2917    getPointerType(VoidPtrTy),
2918    IntTy,
2919    IntTy,
2920    getPointerType(VoidPtrTy),
2921    (BlockHasCopyDispose ?
2922     getPointerType(getBlockDescriptorExtendedType()) :
2923     getPointerType(getBlockDescriptorType()))
2924  };
2925
2926  const char *FieldNames[] = {
2927    "__isa",
2928    "__flags",
2929    "__reserved",
2930    "__FuncPtr",
2931    "__descriptor"
2932  };
2933
2934  for (size_t i = 0; i < 5; ++i) {
2935    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
2936                                         &Idents.get(FieldNames[i]),
2937                                         FieldTypes[i], /*DInfo=*/0,
2938                                         /*BitWidth=*/0, /*Mutable=*/false);
2939    T->addDecl(Field);
2940  }
2941
2942  for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
2943    const Expr *E = BlockDeclRefDecls[i];
2944    const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2945    clang::IdentifierInfo *Name = 0;
2946    if (BDRE) {
2947      const ValueDecl *D = BDRE->getDecl();
2948      Name = &Idents.get(D->getName());
2949    }
2950    QualType FieldType = E->getType();
2951
2952    if (BDRE && BDRE->isByRef())
2953      FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
2954                                 FieldType);
2955
2956    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
2957                                         Name, FieldType, /*DInfo=*/0,
2958                                         /*BitWidth=*/0, /*Mutable=*/false);
2959    T->addDecl(Field);
2960  }
2961
2962  T->completeDefinition(*this);
2963
2964  return getPointerType(getTagDeclType(T));
2965}
2966
2967void ASTContext::setObjCFastEnumerationStateType(QualType T) {
2968  const RecordType *Rec = T->getAs<RecordType>();
2969  assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2970  ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2971}
2972
2973// This returns true if a type has been typedefed to BOOL:
2974// typedef <type> BOOL;
2975static bool isTypeTypedefedAsBOOL(QualType T) {
2976  if (const TypedefType *TT = dyn_cast<TypedefType>(T))
2977    if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2978      return II->isStr("BOOL");
2979
2980  return false;
2981}
2982
2983/// getObjCEncodingTypeSize returns size of type for objective-c encoding
2984/// purpose.
2985int ASTContext::getObjCEncodingTypeSize(QualType type) {
2986  uint64_t sz = getTypeSize(type);
2987
2988  // Make all integer and enum types at least as large as an int
2989  if (sz > 0 && type->isIntegralType())
2990    sz = std::max(sz, getTypeSize(IntTy));
2991  // Treat arrays as pointers, since that's how they're passed in.
2992  else if (type->isArrayType())
2993    sz = getTypeSize(VoidPtrTy);
2994  return sz / getTypeSize(CharTy);
2995}
2996
2997/// getObjCEncodingForMethodDecl - Return the encoded type for this method
2998/// declaration.
2999void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
3000                                              std::string& S) {
3001  // FIXME: This is not very efficient.
3002  // Encode type qualifer, 'in', 'inout', etc. for the return type.
3003  getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
3004  // Encode result type.
3005  getObjCEncodingForType(Decl->getResultType(), S);
3006  // Compute size of all parameters.
3007  // Start with computing size of a pointer in number of bytes.
3008  // FIXME: There might(should) be a better way of doing this computation!
3009  SourceLocation Loc;
3010  int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
3011  // The first two arguments (self and _cmd) are pointers; account for
3012  // their size.
3013  int ParmOffset = 2 * PtrSize;
3014  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3015       E = Decl->param_end(); PI != E; ++PI) {
3016    QualType PType = (*PI)->getType();
3017    int sz = getObjCEncodingTypeSize(PType);
3018    assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
3019    ParmOffset += sz;
3020  }
3021  S += llvm::utostr(ParmOffset);
3022  S += "@0:";
3023  S += llvm::utostr(PtrSize);
3024
3025  // Argument types.
3026  ParmOffset = 2 * PtrSize;
3027  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3028       E = Decl->param_end(); PI != E; ++PI) {
3029    ParmVarDecl *PVDecl = *PI;
3030    QualType PType = PVDecl->getOriginalType();
3031    if (const ArrayType *AT =
3032          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3033      // Use array's original type only if it has known number of
3034      // elements.
3035      if (!isa<ConstantArrayType>(AT))
3036        PType = PVDecl->getType();
3037    } else if (PType->isFunctionType())
3038      PType = PVDecl->getType();
3039    // Process argument qualifiers for user supplied arguments; such as,
3040    // 'in', 'inout', etc.
3041    getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
3042    getObjCEncodingForType(PType, S);
3043    S += llvm::utostr(ParmOffset);
3044    ParmOffset += getObjCEncodingTypeSize(PType);
3045  }
3046}
3047
3048/// getObjCEncodingForPropertyDecl - Return the encoded type for this
3049/// property declaration. If non-NULL, Container must be either an
3050/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3051/// NULL when getting encodings for protocol properties.
3052/// Property attributes are stored as a comma-delimited C string. The simple
3053/// attributes readonly and bycopy are encoded as single characters. The
3054/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3055/// encoded as single characters, followed by an identifier. Property types
3056/// are also encoded as a parametrized attribute. The characters used to encode
3057/// these attributes are defined by the following enumeration:
3058/// @code
3059/// enum PropertyAttributes {
3060/// kPropertyReadOnly = 'R',   // property is read-only.
3061/// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
3062/// kPropertyByref = '&',  // property is a reference to the value last assigned
3063/// kPropertyDynamic = 'D',    // property is dynamic
3064/// kPropertyGetter = 'G',     // followed by getter selector name
3065/// kPropertySetter = 'S',     // followed by setter selector name
3066/// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
3067/// kPropertyType = 't'              // followed by old-style type encoding.
3068/// kPropertyWeak = 'W'              // 'weak' property
3069/// kPropertyStrong = 'P'            // property GC'able
3070/// kPropertyNonAtomic = 'N'         // property non-atomic
3071/// };
3072/// @endcode
3073void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
3074                                                const Decl *Container,
3075                                                std::string& S) {
3076  // Collect information from the property implementation decl(s).
3077  bool Dynamic = false;
3078  ObjCPropertyImplDecl *SynthesizePID = 0;
3079
3080  // FIXME: Duplicated code due to poor abstraction.
3081  if (Container) {
3082    if (const ObjCCategoryImplDecl *CID =
3083        dyn_cast<ObjCCategoryImplDecl>(Container)) {
3084      for (ObjCCategoryImplDecl::propimpl_iterator
3085             i = CID->propimpl_begin(), e = CID->propimpl_end();
3086           i != e; ++i) {
3087        ObjCPropertyImplDecl *PID = *i;
3088        if (PID->getPropertyDecl() == PD) {
3089          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3090            Dynamic = true;
3091          } else {
3092            SynthesizePID = PID;
3093          }
3094        }
3095      }
3096    } else {
3097      const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
3098      for (ObjCCategoryImplDecl::propimpl_iterator
3099             i = OID->propimpl_begin(), e = OID->propimpl_end();
3100           i != e; ++i) {
3101        ObjCPropertyImplDecl *PID = *i;
3102        if (PID->getPropertyDecl() == PD) {
3103          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3104            Dynamic = true;
3105          } else {
3106            SynthesizePID = PID;
3107          }
3108        }
3109      }
3110    }
3111  }
3112
3113  // FIXME: This is not very efficient.
3114  S = "T";
3115
3116  // Encode result type.
3117  // GCC has some special rules regarding encoding of properties which
3118  // closely resembles encoding of ivars.
3119  getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
3120                             true /* outermost type */,
3121                             true /* encoding for property */);
3122
3123  if (PD->isReadOnly()) {
3124    S += ",R";
3125  } else {
3126    switch (PD->getSetterKind()) {
3127    case ObjCPropertyDecl::Assign: break;
3128    case ObjCPropertyDecl::Copy:   S += ",C"; break;
3129    case ObjCPropertyDecl::Retain: S += ",&"; break;
3130    }
3131  }
3132
3133  // It really isn't clear at all what this means, since properties
3134  // are "dynamic by default".
3135  if (Dynamic)
3136    S += ",D";
3137
3138  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3139    S += ",N";
3140
3141  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3142    S += ",G";
3143    S += PD->getGetterName().getAsString();
3144  }
3145
3146  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3147    S += ",S";
3148    S += PD->getSetterName().getAsString();
3149  }
3150
3151  if (SynthesizePID) {
3152    const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3153    S += ",V";
3154    S += OID->getNameAsString();
3155  }
3156
3157  // FIXME: OBJCGC: weak & strong
3158}
3159
3160/// getLegacyIntegralTypeEncoding -
3161/// Another legacy compatibility encoding: 32-bit longs are encoded as
3162/// 'l' or 'L' , but not always.  For typedefs, we need to use
3163/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3164///
3165void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
3166  if (isa<TypedefType>(PointeeTy.getTypePtr())) {
3167    if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
3168      if (BT->getKind() == BuiltinType::ULong &&
3169          ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
3170        PointeeTy = UnsignedIntTy;
3171      else
3172        if (BT->getKind() == BuiltinType::Long &&
3173            ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
3174          PointeeTy = IntTy;
3175    }
3176  }
3177}
3178
3179void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
3180                                        const FieldDecl *Field) {
3181  // We follow the behavior of gcc, expanding structures which are
3182  // directly pointed to, and expanding embedded structures. Note that
3183  // these rules are sufficient to prevent recursive encoding of the
3184  // same type.
3185  getObjCEncodingForTypeImpl(T, S, true, true, Field,
3186                             true /* outermost type */);
3187}
3188
3189static void EncodeBitField(const ASTContext *Context, std::string& S,
3190                           const FieldDecl *FD) {
3191  const Expr *E = FD->getBitWidth();
3192  assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3193  ASTContext *Ctx = const_cast<ASTContext*>(Context);
3194  unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
3195  S += 'b';
3196  S += llvm::utostr(N);
3197}
3198
3199// FIXME: Use SmallString for accumulating string.
3200void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3201                                            bool ExpandPointedToStructures,
3202                                            bool ExpandStructures,
3203                                            const FieldDecl *FD,
3204                                            bool OutermostType,
3205                                            bool EncodingProperty) {
3206  if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
3207    if (FD && FD->isBitField())
3208      return EncodeBitField(this, S, FD);
3209    char encoding;
3210    switch (BT->getKind()) {
3211    default: assert(0 && "Unhandled builtin type kind");
3212    case BuiltinType::Void:       encoding = 'v'; break;
3213    case BuiltinType::Bool:       encoding = 'B'; break;
3214    case BuiltinType::Char_U:
3215    case BuiltinType::UChar:      encoding = 'C'; break;
3216    case BuiltinType::UShort:     encoding = 'S'; break;
3217    case BuiltinType::UInt:       encoding = 'I'; break;
3218    case BuiltinType::ULong:
3219        encoding =
3220          (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
3221        break;
3222    case BuiltinType::UInt128:    encoding = 'T'; break;
3223    case BuiltinType::ULongLong:  encoding = 'Q'; break;
3224    case BuiltinType::Char_S:
3225    case BuiltinType::SChar:      encoding = 'c'; break;
3226    case BuiltinType::Short:      encoding = 's'; break;
3227    case BuiltinType::Int:        encoding = 'i'; break;
3228    case BuiltinType::Long:
3229      encoding =
3230        (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
3231      break;
3232    case BuiltinType::LongLong:   encoding = 'q'; break;
3233    case BuiltinType::Int128:     encoding = 't'; break;
3234    case BuiltinType::Float:      encoding = 'f'; break;
3235    case BuiltinType::Double:     encoding = 'd'; break;
3236    case BuiltinType::LongDouble: encoding = 'd'; break;
3237    }
3238
3239    S += encoding;
3240    return;
3241  }
3242
3243  if (const ComplexType *CT = T->getAs<ComplexType>()) {
3244    S += 'j';
3245    getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
3246                               false);
3247    return;
3248  }
3249
3250  if (const PointerType *PT = T->getAs<PointerType>()) {
3251    QualType PointeeTy = PT->getPointeeType();
3252    bool isReadOnly = false;
3253    // For historical/compatibility reasons, the read-only qualifier of the
3254    // pointee gets emitted _before_ the '^'.  The read-only qualifier of
3255    // the pointer itself gets ignored, _unless_ we are looking at a typedef!
3256    // Also, do not emit the 'r' for anything but the outermost type!
3257    if (isa<TypedefType>(T.getTypePtr())) {
3258      if (OutermostType && T.isConstQualified()) {
3259        isReadOnly = true;
3260        S += 'r';
3261      }
3262    } else if (OutermostType) {
3263      QualType P = PointeeTy;
3264      while (P->getAs<PointerType>())
3265        P = P->getAs<PointerType>()->getPointeeType();
3266      if (P.isConstQualified()) {
3267        isReadOnly = true;
3268        S += 'r';
3269      }
3270    }
3271    if (isReadOnly) {
3272      // Another legacy compatibility encoding. Some ObjC qualifier and type
3273      // combinations need to be rearranged.
3274      // Rewrite "in const" from "nr" to "rn"
3275      const char * s = S.c_str();
3276      int len = S.length();
3277      if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3278        std::string replace = "rn";
3279        S.replace(S.end()-2, S.end(), replace);
3280      }
3281    }
3282    if (isObjCSelType(PointeeTy)) {
3283      S += ':';
3284      return;
3285    }
3286
3287    if (PointeeTy->isCharType()) {
3288      // char pointer types should be encoded as '*' unless it is a
3289      // type that has been typedef'd to 'BOOL'.
3290      if (!isTypeTypedefedAsBOOL(PointeeTy)) {
3291        S += '*';
3292        return;
3293      }
3294    } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
3295      // GCC binary compat: Need to convert "struct objc_class *" to "#".
3296      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3297        S += '#';
3298        return;
3299      }
3300      // GCC binary compat: Need to convert "struct objc_object *" to "@".
3301      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3302        S += '@';
3303        return;
3304      }
3305      // fall through...
3306    }
3307    S += '^';
3308    getLegacyIntegralTypeEncoding(PointeeTy);
3309
3310    getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
3311                               NULL);
3312    return;
3313  }
3314
3315  if (const ArrayType *AT =
3316      // Ignore type qualifiers etc.
3317        dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
3318    if (isa<IncompleteArrayType>(AT)) {
3319      // Incomplete arrays are encoded as a pointer to the array element.
3320      S += '^';
3321
3322      getObjCEncodingForTypeImpl(AT->getElementType(), S,
3323                                 false, ExpandStructures, FD);
3324    } else {
3325      S += '[';
3326
3327      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3328        S += llvm::utostr(CAT->getSize().getZExtValue());
3329      else {
3330        //Variable length arrays are encoded as a regular array with 0 elements.
3331        assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3332        S += '0';
3333      }
3334
3335      getObjCEncodingForTypeImpl(AT->getElementType(), S,
3336                                 false, ExpandStructures, FD);
3337      S += ']';
3338    }
3339    return;
3340  }
3341
3342  if (T->getAs<FunctionType>()) {
3343    S += '?';
3344    return;
3345  }
3346
3347  if (const RecordType *RTy = T->getAs<RecordType>()) {
3348    RecordDecl *RDecl = RTy->getDecl();
3349    S += RDecl->isUnion() ? '(' : '{';
3350    // Anonymous structures print as '?'
3351    if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3352      S += II->getName();
3353    } else {
3354      S += '?';
3355    }
3356    if (ExpandStructures) {
3357      S += '=';
3358      for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3359                                   FieldEnd = RDecl->field_end();
3360           Field != FieldEnd; ++Field) {
3361        if (FD) {
3362          S += '"';
3363          S += Field->getNameAsString();
3364          S += '"';
3365        }
3366
3367        // Special case bit-fields.
3368        if (Field->isBitField()) {
3369          getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
3370                                     (*Field));
3371        } else {
3372          QualType qt = Field->getType();
3373          getLegacyIntegralTypeEncoding(qt);
3374          getObjCEncodingForTypeImpl(qt, S, false, true,
3375                                     FD);
3376        }
3377      }
3378    }
3379    S += RDecl->isUnion() ? ')' : '}';
3380    return;
3381  }
3382
3383  if (T->isEnumeralType()) {
3384    if (FD && FD->isBitField())
3385      EncodeBitField(this, S, FD);
3386    else
3387      S += 'i';
3388    return;
3389  }
3390
3391  if (T->isBlockPointerType()) {
3392    S += "@?"; // Unlike a pointer-to-function, which is "^?".
3393    return;
3394  }
3395
3396  if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
3397    // @encode(class_name)
3398    ObjCInterfaceDecl *OI = OIT->getDecl();
3399    S += '{';
3400    const IdentifierInfo *II = OI->getIdentifier();
3401    S += II->getName();
3402    S += '=';
3403    llvm::SmallVector<FieldDecl*, 32> RecFields;
3404    CollectObjCIvars(OI, RecFields);
3405    for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
3406      if (RecFields[i]->isBitField())
3407        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
3408                                   RecFields[i]);
3409      else
3410        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
3411                                   FD);
3412    }
3413    S += '}';
3414    return;
3415  }
3416
3417  if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
3418    if (OPT->isObjCIdType()) {
3419      S += '@';
3420      return;
3421    }
3422
3423    if (OPT->isObjCClassType()) {
3424      S += '#';
3425      return;
3426    }
3427
3428    if (OPT->isObjCQualifiedIdType()) {
3429      getObjCEncodingForTypeImpl(getObjCIdType(), S,
3430                                 ExpandPointedToStructures,
3431                                 ExpandStructures, FD);
3432      if (FD || EncodingProperty) {
3433        // Note that we do extended encoding of protocol qualifer list
3434        // Only when doing ivar or property encoding.
3435        S += '"';
3436        for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3437             E = OPT->qual_end(); I != E; ++I) {
3438          S += '<';
3439          S += (*I)->getNameAsString();
3440          S += '>';
3441        }
3442        S += '"';
3443      }
3444      return;
3445    }
3446
3447    QualType PointeeTy = OPT->getPointeeType();
3448    if (!EncodingProperty &&
3449        isa<TypedefType>(PointeeTy.getTypePtr())) {
3450      // Another historical/compatibility reason.
3451      // We encode the underlying type which comes out as
3452      // {...};
3453      S += '^';
3454      getObjCEncodingForTypeImpl(PointeeTy, S,
3455                                 false, ExpandPointedToStructures,
3456                                 NULL);
3457      return;
3458    }
3459
3460    S += '@';
3461    if (FD || EncodingProperty) {
3462      S += '"';
3463      S += OPT->getInterfaceDecl()->getNameAsCString();
3464      for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3465           E = OPT->qual_end(); I != E; ++I) {
3466        S += '<';
3467        S += (*I)->getNameAsString();
3468        S += '>';
3469      }
3470      S += '"';
3471    }
3472    return;
3473  }
3474
3475  assert(0 && "@encode for type not implemented!");
3476}
3477
3478void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
3479                                                 std::string& S) const {
3480  if (QT & Decl::OBJC_TQ_In)
3481    S += 'n';
3482  if (QT & Decl::OBJC_TQ_Inout)
3483    S += 'N';
3484  if (QT & Decl::OBJC_TQ_Out)
3485    S += 'o';
3486  if (QT & Decl::OBJC_TQ_Bycopy)
3487    S += 'O';
3488  if (QT & Decl::OBJC_TQ_Byref)
3489    S += 'R';
3490  if (QT & Decl::OBJC_TQ_Oneway)
3491    S += 'V';
3492}
3493
3494void ASTContext::setBuiltinVaListType(QualType T) {
3495  assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
3496
3497  BuiltinVaListType = T;
3498}
3499
3500void ASTContext::setObjCIdType(QualType T) {
3501  ObjCIdTypedefType = T;
3502}
3503
3504void ASTContext::setObjCSelType(QualType T) {
3505  ObjCSelType = T;
3506
3507  const TypedefType *TT = T->getAs<TypedefType>();
3508  if (!TT)
3509    return;
3510  TypedefDecl *TD = TT->getDecl();
3511
3512  // typedef struct objc_selector *SEL;
3513  const PointerType *ptr = TD->getUnderlyingType()->getAs<PointerType>();
3514  if (!ptr)
3515    return;
3516  const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
3517  if (!rec)
3518    return;
3519  SelStructType = rec;
3520}
3521
3522void ASTContext::setObjCProtoType(QualType QT) {
3523  ObjCProtoType = QT;
3524}
3525
3526void ASTContext::setObjCClassType(QualType T) {
3527  ObjCClassTypedefType = T;
3528}
3529
3530void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
3531  assert(ObjCConstantStringType.isNull() &&
3532         "'NSConstantString' type already set!");
3533
3534  ObjCConstantStringType = getObjCInterfaceType(Decl);
3535}
3536
3537/// \brief Retrieve the template name that represents a qualified
3538/// template name such as \c std::vector.
3539TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
3540                                                  bool TemplateKeyword,
3541                                                  TemplateDecl *Template) {
3542  llvm::FoldingSetNodeID ID;
3543  QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3544
3545  void *InsertPos = 0;
3546  QualifiedTemplateName *QTN =
3547    QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3548  if (!QTN) {
3549    QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3550    QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3551  }
3552
3553  return TemplateName(QTN);
3554}
3555
3556/// \brief Retrieve the template name that represents a qualified
3557/// template name such as \c std::vector.
3558TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
3559                                                  bool TemplateKeyword,
3560                                            OverloadedFunctionDecl *Template) {
3561  llvm::FoldingSetNodeID ID;
3562  QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3563
3564  void *InsertPos = 0;
3565  QualifiedTemplateName *QTN =
3566  QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3567  if (!QTN) {
3568    QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3569    QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3570  }
3571
3572  return TemplateName(QTN);
3573}
3574
3575/// \brief Retrieve the template name that represents a dependent
3576/// template name such as \c MetaFun::template apply.
3577TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3578                                                  const IdentifierInfo *Name) {
3579  assert((!NNS || NNS->isDependent()) &&
3580         "Nested name specifier must be dependent");
3581
3582  llvm::FoldingSetNodeID ID;
3583  DependentTemplateName::Profile(ID, NNS, Name);
3584
3585  void *InsertPos = 0;
3586  DependentTemplateName *QTN =
3587    DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3588
3589  if (QTN)
3590    return TemplateName(QTN);
3591
3592  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3593  if (CanonNNS == NNS) {
3594    QTN = new (*this,4) DependentTemplateName(NNS, Name);
3595  } else {
3596    TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3597    QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3598  }
3599
3600  DependentTemplateNames.InsertNode(QTN, InsertPos);
3601  return TemplateName(QTN);
3602}
3603
3604/// getFromTargetType - Given one of the integer types provided by
3605/// TargetInfo, produce the corresponding type. The unsigned @p Type
3606/// is actually a value of type @c TargetInfo::IntType.
3607CanQualType ASTContext::getFromTargetType(unsigned Type) const {
3608  switch (Type) {
3609  case TargetInfo::NoInt: return CanQualType();
3610  case TargetInfo::SignedShort: return ShortTy;
3611  case TargetInfo::UnsignedShort: return UnsignedShortTy;
3612  case TargetInfo::SignedInt: return IntTy;
3613  case TargetInfo::UnsignedInt: return UnsignedIntTy;
3614  case TargetInfo::SignedLong: return LongTy;
3615  case TargetInfo::UnsignedLong: return UnsignedLongTy;
3616  case TargetInfo::SignedLongLong: return LongLongTy;
3617  case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3618  }
3619
3620  assert(false && "Unhandled TargetInfo::IntType value");
3621  return CanQualType();
3622}
3623
3624//===----------------------------------------------------------------------===//
3625//                        Type Predicates.
3626//===----------------------------------------------------------------------===//
3627
3628/// isObjCNSObjectType - Return true if this is an NSObject object using
3629/// NSObject attribute on a c-style pointer type.
3630/// FIXME - Make it work directly on types.
3631/// FIXME: Move to Type.
3632///
3633bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3634  if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3635    if (TypedefDecl *TD = TDT->getDecl())
3636      if (TD->getAttr<ObjCNSObjectAttr>())
3637        return true;
3638  }
3639  return false;
3640}
3641
3642/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3643/// garbage collection attribute.
3644///
3645Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3646  Qualifiers::GC GCAttrs = Qualifiers::GCNone;
3647  if (getLangOptions().ObjC1 &&
3648      getLangOptions().getGCMode() != LangOptions::NonGC) {
3649    GCAttrs = Ty.getObjCGCAttr();
3650    // Default behavious under objective-c's gc is for objective-c pointers
3651    // (or pointers to them) be treated as though they were declared
3652    // as __strong.
3653    if (GCAttrs == Qualifiers::GCNone) {
3654      if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
3655        GCAttrs = Qualifiers::Strong;
3656      else if (Ty->isPointerType())
3657        return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
3658    }
3659    // Non-pointers have none gc'able attribute regardless of the attribute
3660    // set on them.
3661    else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
3662      return Qualifiers::GCNone;
3663  }
3664  return GCAttrs;
3665}
3666
3667//===----------------------------------------------------------------------===//
3668//                        Type Compatibility Testing
3669//===----------------------------------------------------------------------===//
3670
3671/// areCompatVectorTypes - Return true if the two specified vector types are
3672/// compatible.
3673static bool areCompatVectorTypes(const VectorType *LHS,
3674                                 const VectorType *RHS) {
3675  assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
3676  return LHS->getElementType() == RHS->getElementType() &&
3677         LHS->getNumElements() == RHS->getNumElements();
3678}
3679
3680//===----------------------------------------------------------------------===//
3681// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3682//===----------------------------------------------------------------------===//
3683
3684/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3685/// inheritance hierarchy of 'rProto'.
3686bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3687                                                ObjCProtocolDecl *rProto) {
3688  if (lProto == rProto)
3689    return true;
3690  for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3691       E = rProto->protocol_end(); PI != E; ++PI)
3692    if (ProtocolCompatibleWithProtocol(lProto, *PI))
3693      return true;
3694  return false;
3695}
3696
3697/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3698/// return true if lhs's protocols conform to rhs's protocol; false
3699/// otherwise.
3700bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3701  if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3702    return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3703  return false;
3704}
3705
3706/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3707/// ObjCQualifiedIDType.
3708bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3709                                                   bool compare) {
3710  // Allow id<P..> and an 'id' or void* type in all cases.
3711  if (lhs->isVoidPointerType() ||
3712      lhs->isObjCIdType() || lhs->isObjCClassType())
3713    return true;
3714  else if (rhs->isVoidPointerType() ||
3715           rhs->isObjCIdType() || rhs->isObjCClassType())
3716    return true;
3717
3718  if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
3719    const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
3720
3721    if (!rhsOPT) return false;
3722
3723    if (rhsOPT->qual_empty()) {
3724      // If the RHS is a unqualified interface pointer "NSString*",
3725      // make sure we check the class hierarchy.
3726      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3727        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3728             E = lhsQID->qual_end(); I != E; ++I) {
3729          // when comparing an id<P> on lhs with a static type on rhs,
3730          // see if static class implements all of id's protocols, directly or
3731          // through its super class and categories.
3732          if (!rhsID->ClassImplementsProtocol(*I, true))
3733            return false;
3734        }
3735      }
3736      // If there are no qualifiers and no interface, we have an 'id'.
3737      return true;
3738    }
3739    // Both the right and left sides have qualifiers.
3740    for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3741         E = lhsQID->qual_end(); I != E; ++I) {
3742      ObjCProtocolDecl *lhsProto = *I;
3743      bool match = false;
3744
3745      // when comparing an id<P> on lhs with a static type on rhs,
3746      // see if static class implements all of id's protocols, directly or
3747      // through its super class and categories.
3748      for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
3749           E = rhsOPT->qual_end(); J != E; ++J) {
3750        ObjCProtocolDecl *rhsProto = *J;
3751        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3752            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3753          match = true;
3754          break;
3755        }
3756      }
3757      // If the RHS is a qualified interface pointer "NSString<P>*",
3758      // make sure we check the class hierarchy.
3759      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3760        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3761             E = lhsQID->qual_end(); I != E; ++I) {
3762          // when comparing an id<P> on lhs with a static type on rhs,
3763          // see if static class implements all of id's protocols, directly or
3764          // through its super class and categories.
3765          if (rhsID->ClassImplementsProtocol(*I, true)) {
3766            match = true;
3767            break;
3768          }
3769        }
3770      }
3771      if (!match)
3772        return false;
3773    }
3774
3775    return true;
3776  }
3777
3778  const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
3779  assert(rhsQID && "One of the LHS/RHS should be id<x>");
3780
3781  if (const ObjCObjectPointerType *lhsOPT =
3782        lhs->getAsObjCInterfacePointerType()) {
3783    if (lhsOPT->qual_empty()) {
3784      bool match = false;
3785      if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
3786        for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
3787             E = rhsQID->qual_end(); I != E; ++I) {
3788          // when comparing an id<P> on lhs with a static type on rhs,
3789          // see if static class implements all of id's protocols, directly or
3790          // through its super class and categories.
3791          if (lhsID->ClassImplementsProtocol(*I, true)) {
3792            match = true;
3793            break;
3794          }
3795        }
3796        if (!match)
3797          return false;
3798      }
3799      return true;
3800    }
3801    // Both the right and left sides have qualifiers.
3802    for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
3803         E = lhsOPT->qual_end(); I != E; ++I) {
3804      ObjCProtocolDecl *lhsProto = *I;
3805      bool match = false;
3806
3807      // when comparing an id<P> on lhs with a static type on rhs,
3808      // see if static class implements all of id's protocols, directly or
3809      // through its super class and categories.
3810      for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
3811           E = rhsQID->qual_end(); J != E; ++J) {
3812        ObjCProtocolDecl *rhsProto = *J;
3813        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3814            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3815          match = true;
3816          break;
3817        }
3818      }
3819      if (!match)
3820        return false;
3821    }
3822    return true;
3823  }
3824  return false;
3825}
3826
3827/// canAssignObjCInterfaces - Return true if the two interface types are
3828/// compatible for assignment from RHS to LHS.  This handles validation of any
3829/// protocol qualifiers on the LHS or RHS.
3830///
3831bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
3832                                         const ObjCObjectPointerType *RHSOPT) {
3833  // If either type represents the built-in 'id' or 'Class' types, return true.
3834  if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
3835    return true;
3836
3837  if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
3838    return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
3839                                             QualType(RHSOPT,0),
3840                                             false);
3841
3842  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
3843  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
3844  if (LHS && RHS) // We have 2 user-defined types.
3845    return canAssignObjCInterfaces(LHS, RHS);
3846
3847  return false;
3848}
3849
3850bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
3851                                         const ObjCInterfaceType *RHS) {
3852  // Verify that the base decls are compatible: the RHS must be a subclass of
3853  // the LHS.
3854  if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
3855    return false;
3856
3857  // RHS must have a superset of the protocols in the LHS.  If the LHS is not
3858  // protocol qualified at all, then we are good.
3859  if (LHS->getNumProtocols() == 0)
3860    return true;
3861
3862  // Okay, we know the LHS has protocol qualifiers.  If the RHS doesn't, then it
3863  // isn't a superset.
3864  if (RHS->getNumProtocols() == 0)
3865    return true;  // FIXME: should return false!
3866
3867  for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
3868                                        LHSPE = LHS->qual_end();
3869       LHSPI != LHSPE; LHSPI++) {
3870    bool RHSImplementsProtocol = false;
3871
3872    // If the RHS doesn't implement the protocol on the left, the types
3873    // are incompatible.
3874    for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
3875                                          RHSPE = RHS->qual_end();
3876         RHSPI != RHSPE; RHSPI++) {
3877      if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
3878        RHSImplementsProtocol = true;
3879        break;
3880      }
3881    }
3882    // FIXME: For better diagnostics, consider passing back the protocol name.
3883    if (!RHSImplementsProtocol)
3884      return false;
3885  }
3886  // The RHS implements all protocols listed on the LHS.
3887  return true;
3888}
3889
3890bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
3891  // get the "pointed to" types
3892  const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
3893  const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
3894
3895  if (!LHSOPT || !RHSOPT)
3896    return false;
3897
3898  return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
3899         canAssignObjCInterfaces(RHSOPT, LHSOPT);
3900}
3901
3902/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
3903/// both shall have the identically qualified version of a compatible type.
3904/// C99 6.2.7p1: Two types have compatible types if their types are the
3905/// same. See 6.7.[2,3,5] for additional rules.
3906bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
3907  return !mergeTypes(LHS, RHS).isNull();
3908}
3909
3910QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
3911  const FunctionType *lbase = lhs->getAs<FunctionType>();
3912  const FunctionType *rbase = rhs->getAs<FunctionType>();
3913  const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
3914  const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
3915  bool allLTypes = true;
3916  bool allRTypes = true;
3917
3918  // Check return type
3919  QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3920  if (retType.isNull()) return QualType();
3921  if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3922    allLTypes = false;
3923  if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3924    allRTypes = false;
3925  // FIXME: double check this
3926  bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
3927  if (NoReturn != lbase->getNoReturnAttr())
3928    allLTypes = false;
3929  if (NoReturn != rbase->getNoReturnAttr())
3930    allRTypes = false;
3931
3932  if (lproto && rproto) { // two C99 style function prototypes
3933    assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3934           "C++ shouldn't be here");
3935    unsigned lproto_nargs = lproto->getNumArgs();
3936    unsigned rproto_nargs = rproto->getNumArgs();
3937
3938    // Compatible functions must have the same number of arguments
3939    if (lproto_nargs != rproto_nargs)
3940      return QualType();
3941
3942    // Variadic and non-variadic functions aren't compatible
3943    if (lproto->isVariadic() != rproto->isVariadic())
3944      return QualType();
3945
3946    if (lproto->getTypeQuals() != rproto->getTypeQuals())
3947      return QualType();
3948
3949    // Check argument compatibility
3950    llvm::SmallVector<QualType, 10> types;
3951    for (unsigned i = 0; i < lproto_nargs; i++) {
3952      QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3953      QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3954      QualType argtype = mergeTypes(largtype, rargtype);
3955      if (argtype.isNull()) return QualType();
3956      types.push_back(argtype);
3957      if (getCanonicalType(argtype) != getCanonicalType(largtype))
3958        allLTypes = false;
3959      if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3960        allRTypes = false;
3961    }
3962    if (allLTypes) return lhs;
3963    if (allRTypes) return rhs;
3964    return getFunctionType(retType, types.begin(), types.size(),
3965                           lproto->isVariadic(), lproto->getTypeQuals(),
3966                           NoReturn);
3967  }
3968
3969  if (lproto) allRTypes = false;
3970  if (rproto) allLTypes = false;
3971
3972  const FunctionProtoType *proto = lproto ? lproto : rproto;
3973  if (proto) {
3974    assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
3975    if (proto->isVariadic()) return QualType();
3976    // Check that the types are compatible with the types that
3977    // would result from default argument promotions (C99 6.7.5.3p15).
3978    // The only types actually affected are promotable integer
3979    // types and floats, which would be passed as a different
3980    // type depending on whether the prototype is visible.
3981    unsigned proto_nargs = proto->getNumArgs();
3982    for (unsigned i = 0; i < proto_nargs; ++i) {
3983      QualType argTy = proto->getArgType(i);
3984      if (argTy->isPromotableIntegerType() ||
3985          getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3986        return QualType();
3987    }
3988
3989    if (allLTypes) return lhs;
3990    if (allRTypes) return rhs;
3991    return getFunctionType(retType, proto->arg_type_begin(),
3992                           proto->getNumArgs(), proto->isVariadic(),
3993                           proto->getTypeQuals(), NoReturn);
3994  }
3995
3996  if (allLTypes) return lhs;
3997  if (allRTypes) return rhs;
3998  return getFunctionNoProtoType(retType, NoReturn);
3999}
4000
4001QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
4002  // C++ [expr]: If an expression initially has the type "reference to T", the
4003  // type is adjusted to "T" prior to any further analysis, the expression
4004  // designates the object or function denoted by the reference, and the
4005  // expression is an lvalue unless the reference is an rvalue reference and
4006  // the expression is a function call (possibly inside parentheses).
4007  // FIXME: C++ shouldn't be going through here!  The rules are different
4008  // enough that they should be handled separately.
4009  // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
4010  // shouldn't be going through here!
4011  if (const ReferenceType *RT = LHS->getAs<ReferenceType>())
4012    LHS = RT->getPointeeType();
4013  if (const ReferenceType *RT = RHS->getAs<ReferenceType>())
4014    RHS = RT->getPointeeType();
4015
4016  QualType LHSCan = getCanonicalType(LHS),
4017           RHSCan = getCanonicalType(RHS);
4018
4019  // If two types are identical, they are compatible.
4020  if (LHSCan == RHSCan)
4021    return LHS;
4022
4023  // If the qualifiers are different, the types aren't compatible... mostly.
4024  Qualifiers LQuals = LHSCan.getQualifiers();
4025  Qualifiers RQuals = RHSCan.getQualifiers();
4026  if (LQuals != RQuals) {
4027    // If any of these qualifiers are different, we have a type
4028    // mismatch.
4029    if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4030        LQuals.getAddressSpace() != RQuals.getAddressSpace())
4031      return QualType();
4032
4033    // Exactly one GC qualifier difference is allowed: __strong is
4034    // okay if the other type has no GC qualifier but is an Objective
4035    // C object pointer (i.e. implicitly strong by default).  We fix
4036    // this by pretending that the unqualified type was actually
4037    // qualified __strong.
4038    Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4039    Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4040    assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4041
4042    if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4043      return QualType();
4044
4045    if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4046      return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4047    }
4048    if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4049      return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4050    }
4051    return QualType();
4052  }
4053
4054  // Okay, qualifiers are equal.
4055
4056  Type::TypeClass LHSClass = LHSCan->getTypeClass();
4057  Type::TypeClass RHSClass = RHSCan->getTypeClass();
4058
4059  // We want to consider the two function types to be the same for these
4060  // comparisons, just force one to the other.
4061  if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4062  if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
4063
4064  // Same as above for arrays
4065  if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4066    LHSClass = Type::ConstantArray;
4067  if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4068    RHSClass = Type::ConstantArray;
4069
4070  // Canonicalize ExtVector -> Vector.
4071  if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4072  if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
4073
4074  // If the canonical type classes don't match.
4075  if (LHSClass != RHSClass) {
4076    // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
4077    // a signed integer type, or an unsigned integer type.
4078    if (const EnumType* ETy = LHS->getAs<EnumType>()) {
4079      if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4080        return RHS;
4081    }
4082    if (const EnumType* ETy = RHS->getAs<EnumType>()) {
4083      if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4084        return LHS;
4085    }
4086
4087    return QualType();
4088  }
4089
4090  // The canonical type classes match.
4091  switch (LHSClass) {
4092#define TYPE(Class, Base)
4093#define ABSTRACT_TYPE(Class, Base)
4094#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4095#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4096#include "clang/AST/TypeNodes.def"
4097    assert(false && "Non-canonical and dependent types shouldn't get here");
4098    return QualType();
4099
4100  case Type::LValueReference:
4101  case Type::RValueReference:
4102  case Type::MemberPointer:
4103    assert(false && "C++ should never be in mergeTypes");
4104    return QualType();
4105
4106  case Type::IncompleteArray:
4107  case Type::VariableArray:
4108  case Type::FunctionProto:
4109  case Type::ExtVector:
4110    assert(false && "Types are eliminated above");
4111    return QualType();
4112
4113  case Type::Pointer:
4114  {
4115    // Merge two pointer types, while trying to preserve typedef info
4116    QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4117    QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
4118    QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4119    if (ResultType.isNull()) return QualType();
4120    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4121      return LHS;
4122    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4123      return RHS;
4124    return getPointerType(ResultType);
4125  }
4126  case Type::BlockPointer:
4127  {
4128    // Merge two block pointer types, while trying to preserve typedef info
4129    QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4130    QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
4131    QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4132    if (ResultType.isNull()) return QualType();
4133    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4134      return LHS;
4135    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4136      return RHS;
4137    return getBlockPointerType(ResultType);
4138  }
4139  case Type::ConstantArray:
4140  {
4141    const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4142    const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4143    if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4144      return QualType();
4145
4146    QualType LHSElem = getAsArrayType(LHS)->getElementType();
4147    QualType RHSElem = getAsArrayType(RHS)->getElementType();
4148    QualType ResultType = mergeTypes(LHSElem, RHSElem);
4149    if (ResultType.isNull()) return QualType();
4150    if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4151      return LHS;
4152    if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4153      return RHS;
4154    if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4155                                          ArrayType::ArraySizeModifier(), 0);
4156    if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4157                                          ArrayType::ArraySizeModifier(), 0);
4158    const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4159    const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
4160    if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4161      return LHS;
4162    if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4163      return RHS;
4164    if (LVAT) {
4165      // FIXME: This isn't correct! But tricky to implement because
4166      // the array's size has to be the size of LHS, but the type
4167      // has to be different.
4168      return LHS;
4169    }
4170    if (RVAT) {
4171      // FIXME: This isn't correct! But tricky to implement because
4172      // the array's size has to be the size of RHS, but the type
4173      // has to be different.
4174      return RHS;
4175    }
4176    if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4177    if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
4178    return getIncompleteArrayType(ResultType,
4179                                  ArrayType::ArraySizeModifier(), 0);
4180  }
4181  case Type::FunctionNoProto:
4182    return mergeFunctionTypes(LHS, RHS);
4183  case Type::Record:
4184  case Type::Enum:
4185    return QualType();
4186  case Type::Builtin:
4187    // Only exactly equal builtin types are compatible, which is tested above.
4188    return QualType();
4189  case Type::Complex:
4190    // Distinct complex types are incompatible.
4191    return QualType();
4192  case Type::Vector:
4193    // FIXME: The merged type should be an ExtVector!
4194    if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
4195      return LHS;
4196    return QualType();
4197  case Type::ObjCInterface: {
4198    // Check if the interfaces are assignment compatible.
4199    // FIXME: This should be type compatibility, e.g. whether
4200    // "LHS x; RHS x;" at global scope is legal.
4201    const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4202    const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
4203    if (LHSIface && RHSIface &&
4204        canAssignObjCInterfaces(LHSIface, RHSIface))
4205      return LHS;
4206
4207    return QualType();
4208  }
4209  case Type::ObjCObjectPointer: {
4210    if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4211                                RHS->getAs<ObjCObjectPointerType>()))
4212      return LHS;
4213
4214    return QualType();
4215  }
4216  case Type::FixedWidthInt:
4217    // Distinct fixed-width integers are not compatible.
4218    return QualType();
4219  case Type::TemplateSpecialization:
4220    assert(false && "Dependent types have no size");
4221    break;
4222  }
4223
4224  return QualType();
4225}
4226
4227//===----------------------------------------------------------------------===//
4228//                         Integer Predicates
4229//===----------------------------------------------------------------------===//
4230
4231unsigned ASTContext::getIntWidth(QualType T) {
4232  if (T == BoolTy)
4233    return 1;
4234  if (FixedWidthIntType *FWIT = dyn_cast<FixedWidthIntType>(T)) {
4235    return FWIT->getWidth();
4236  }
4237  // For builtin types, just use the standard type sizing method
4238  return (unsigned)getTypeSize(T);
4239}
4240
4241QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4242  assert(T->isSignedIntegerType() && "Unexpected type");
4243
4244  // Turn <4 x signed int> -> <4 x unsigned int>
4245  if (const VectorType *VTy = T->getAs<VectorType>())
4246    return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
4247                         VTy->getNumElements());
4248
4249  // For enums, we return the unsigned version of the base type.
4250  if (const EnumType *ETy = T->getAs<EnumType>())
4251    T = ETy->getDecl()->getIntegerType();
4252
4253  const BuiltinType *BTy = T->getAs<BuiltinType>();
4254  assert(BTy && "Unexpected signed integer type");
4255  switch (BTy->getKind()) {
4256  case BuiltinType::Char_S:
4257  case BuiltinType::SChar:
4258    return UnsignedCharTy;
4259  case BuiltinType::Short:
4260    return UnsignedShortTy;
4261  case BuiltinType::Int:
4262    return UnsignedIntTy;
4263  case BuiltinType::Long:
4264    return UnsignedLongTy;
4265  case BuiltinType::LongLong:
4266    return UnsignedLongLongTy;
4267  case BuiltinType::Int128:
4268    return UnsignedInt128Ty;
4269  default:
4270    assert(0 && "Unexpected signed integer type");
4271    return QualType();
4272  }
4273}
4274
4275ExternalASTSource::~ExternalASTSource() { }
4276
4277void ExternalASTSource::PrintStats() { }
4278
4279
4280//===----------------------------------------------------------------------===//
4281//                          Builtin Type Computation
4282//===----------------------------------------------------------------------===//
4283
4284/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4285/// pointer over the consumed characters.  This returns the resultant type.
4286static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
4287                                  ASTContext::GetBuiltinTypeError &Error,
4288                                  bool AllowTypeModifiers = true) {
4289  // Modifiers.
4290  int HowLong = 0;
4291  bool Signed = false, Unsigned = false;
4292
4293  // Read the modifiers first.
4294  bool Done = false;
4295  while (!Done) {
4296    switch (*Str++) {
4297    default: Done = true; --Str; break;
4298    case 'S':
4299      assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4300      assert(!Signed && "Can't use 'S' modifier multiple times!");
4301      Signed = true;
4302      break;
4303    case 'U':
4304      assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4305      assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4306      Unsigned = true;
4307      break;
4308    case 'L':
4309      assert(HowLong <= 2 && "Can't have LLLL modifier");
4310      ++HowLong;
4311      break;
4312    }
4313  }
4314
4315  QualType Type;
4316
4317  // Read the base type.
4318  switch (*Str++) {
4319  default: assert(0 && "Unknown builtin type letter!");
4320  case 'v':
4321    assert(HowLong == 0 && !Signed && !Unsigned &&
4322           "Bad modifiers used with 'v'!");
4323    Type = Context.VoidTy;
4324    break;
4325  case 'f':
4326    assert(HowLong == 0 && !Signed && !Unsigned &&
4327           "Bad modifiers used with 'f'!");
4328    Type = Context.FloatTy;
4329    break;
4330  case 'd':
4331    assert(HowLong < 2 && !Signed && !Unsigned &&
4332           "Bad modifiers used with 'd'!");
4333    if (HowLong)
4334      Type = Context.LongDoubleTy;
4335    else
4336      Type = Context.DoubleTy;
4337    break;
4338  case 's':
4339    assert(HowLong == 0 && "Bad modifiers used with 's'!");
4340    if (Unsigned)
4341      Type = Context.UnsignedShortTy;
4342    else
4343      Type = Context.ShortTy;
4344    break;
4345  case 'i':
4346    if (HowLong == 3)
4347      Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4348    else if (HowLong == 2)
4349      Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4350    else if (HowLong == 1)
4351      Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4352    else
4353      Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4354    break;
4355  case 'c':
4356    assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4357    if (Signed)
4358      Type = Context.SignedCharTy;
4359    else if (Unsigned)
4360      Type = Context.UnsignedCharTy;
4361    else
4362      Type = Context.CharTy;
4363    break;
4364  case 'b': // boolean
4365    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4366    Type = Context.BoolTy;
4367    break;
4368  case 'z':  // size_t.
4369    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4370    Type = Context.getSizeType();
4371    break;
4372  case 'F':
4373    Type = Context.getCFConstantStringType();
4374    break;
4375  case 'a':
4376    Type = Context.getBuiltinVaListType();
4377    assert(!Type.isNull() && "builtin va list type not initialized!");
4378    break;
4379  case 'A':
4380    // This is a "reference" to a va_list; however, what exactly
4381    // this means depends on how va_list is defined. There are two
4382    // different kinds of va_list: ones passed by value, and ones
4383    // passed by reference.  An example of a by-value va_list is
4384    // x86, where va_list is a char*. An example of by-ref va_list
4385    // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4386    // we want this argument to be a char*&; for x86-64, we want
4387    // it to be a __va_list_tag*.
4388    Type = Context.getBuiltinVaListType();
4389    assert(!Type.isNull() && "builtin va list type not initialized!");
4390    if (Type->isArrayType()) {
4391      Type = Context.getArrayDecayedType(Type);
4392    } else {
4393      Type = Context.getLValueReferenceType(Type);
4394    }
4395    break;
4396  case 'V': {
4397    char *End;
4398    unsigned NumElements = strtoul(Str, &End, 10);
4399    assert(End != Str && "Missing vector size");
4400
4401    Str = End;
4402
4403    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4404    Type = Context.getVectorType(ElementType, NumElements);
4405    break;
4406  }
4407  case 'X': {
4408    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4409    Type = Context.getComplexType(ElementType);
4410    break;
4411  }
4412  case 'P':
4413    Type = Context.getFILEType();
4414    if (Type.isNull()) {
4415      Error = ASTContext::GE_Missing_stdio;
4416      return QualType();
4417    }
4418    break;
4419  case 'J':
4420    if (Signed)
4421      Type = Context.getsigjmp_bufType();
4422    else
4423      Type = Context.getjmp_bufType();
4424
4425    if (Type.isNull()) {
4426      Error = ASTContext::GE_Missing_setjmp;
4427      return QualType();
4428    }
4429    break;
4430  }
4431
4432  if (!AllowTypeModifiers)
4433    return Type;
4434
4435  Done = false;
4436  while (!Done) {
4437    switch (*Str++) {
4438      default: Done = true; --Str; break;
4439      case '*':
4440        Type = Context.getPointerType(Type);
4441        break;
4442      case '&':
4443        Type = Context.getLValueReferenceType(Type);
4444        break;
4445      // FIXME: There's no way to have a built-in with an rvalue ref arg.
4446      case 'C':
4447        Type = Type.withConst();
4448        break;
4449    }
4450  }
4451
4452  return Type;
4453}
4454
4455/// GetBuiltinType - Return the type for the specified builtin.
4456QualType ASTContext::GetBuiltinType(unsigned id,
4457                                    GetBuiltinTypeError &Error) {
4458  const char *TypeStr = BuiltinInfo.GetTypeString(id);
4459
4460  llvm::SmallVector<QualType, 8> ArgTypes;
4461
4462  Error = GE_None;
4463  QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4464  if (Error != GE_None)
4465    return QualType();
4466  while (TypeStr[0] && TypeStr[0] != '.') {
4467    QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4468    if (Error != GE_None)
4469      return QualType();
4470
4471    // Do array -> pointer decay.  The builtin should use the decayed type.
4472    if (Ty->isArrayType())
4473      Ty = getArrayDecayedType(Ty);
4474
4475    ArgTypes.push_back(Ty);
4476  }
4477
4478  assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4479         "'.' should only occur at end of builtin type list!");
4480
4481  // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4482  if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4483    return getFunctionNoProtoType(ResType);
4484  return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4485                         TypeStr[0] == '.', 0);
4486}
4487
4488QualType
4489ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4490  // Perform the usual unary conversions. We do this early so that
4491  // integral promotions to "int" can allow us to exit early, in the
4492  // lhs == rhs check. Also, for conversion purposes, we ignore any
4493  // qualifiers.  For example, "const float" and "float" are
4494  // equivalent.
4495  if (lhs->isPromotableIntegerType())
4496    lhs = getPromotedIntegerType(lhs);
4497  else
4498    lhs = lhs.getUnqualifiedType();
4499  if (rhs->isPromotableIntegerType())
4500    rhs = getPromotedIntegerType(rhs);
4501  else
4502    rhs = rhs.getUnqualifiedType();
4503
4504  // If both types are identical, no conversion is needed.
4505  if (lhs == rhs)
4506    return lhs;
4507
4508  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4509  // The caller can deal with this (e.g. pointer + int).
4510  if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4511    return lhs;
4512
4513  // At this point, we have two different arithmetic types.
4514
4515  // Handle complex types first (C99 6.3.1.8p1).
4516  if (lhs->isComplexType() || rhs->isComplexType()) {
4517    // if we have an integer operand, the result is the complex type.
4518    if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
4519      // convert the rhs to the lhs complex type.
4520      return lhs;
4521    }
4522    if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
4523      // convert the lhs to the rhs complex type.
4524      return rhs;
4525    }
4526    // This handles complex/complex, complex/float, or float/complex.
4527    // When both operands are complex, the shorter operand is converted to the
4528    // type of the longer, and that is the type of the result. This corresponds
4529    // to what is done when combining two real floating-point operands.
4530    // The fun begins when size promotion occur across type domains.
4531    // From H&S 6.3.4: When one operand is complex and the other is a real
4532    // floating-point type, the less precise type is converted, within it's
4533    // real or complex domain, to the precision of the other type. For example,
4534    // when combining a "long double" with a "double _Complex", the
4535    // "double _Complex" is promoted to "long double _Complex".
4536    int result = getFloatingTypeOrder(lhs, rhs);
4537
4538    if (result > 0) { // The left side is bigger, convert rhs.
4539      rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
4540    } else if (result < 0) { // The right side is bigger, convert lhs.
4541      lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
4542    }
4543    // At this point, lhs and rhs have the same rank/size. Now, make sure the
4544    // domains match. This is a requirement for our implementation, C99
4545    // does not require this promotion.
4546    if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4547      if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4548        return rhs;
4549      } else { // handle "_Complex double, double".
4550        return lhs;
4551      }
4552    }
4553    return lhs; // The domain/size match exactly.
4554  }
4555  // Now handle "real" floating types (i.e. float, double, long double).
4556  if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4557    // if we have an integer operand, the result is the real floating type.
4558    if (rhs->isIntegerType()) {
4559      // convert rhs to the lhs floating point type.
4560      return lhs;
4561    }
4562    if (rhs->isComplexIntegerType()) {
4563      // convert rhs to the complex floating point type.
4564      return getComplexType(lhs);
4565    }
4566    if (lhs->isIntegerType()) {
4567      // convert lhs to the rhs floating point type.
4568      return rhs;
4569    }
4570    if (lhs->isComplexIntegerType()) {
4571      // convert lhs to the complex floating point type.
4572      return getComplexType(rhs);
4573    }
4574    // We have two real floating types, float/complex combos were handled above.
4575    // Convert the smaller operand to the bigger result.
4576    int result = getFloatingTypeOrder(lhs, rhs);
4577    if (result > 0) // convert the rhs
4578      return lhs;
4579    assert(result < 0 && "illegal float comparison");
4580    return rhs;   // convert the lhs
4581  }
4582  if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
4583    // Handle GCC complex int extension.
4584    const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
4585    const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
4586
4587    if (lhsComplexInt && rhsComplexInt) {
4588      if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
4589                              rhsComplexInt->getElementType()) >= 0)
4590        return lhs; // convert the rhs
4591      return rhs;
4592    } else if (lhsComplexInt && rhs->isIntegerType()) {
4593      // convert the rhs to the lhs complex type.
4594      return lhs;
4595    } else if (rhsComplexInt && lhs->isIntegerType()) {
4596      // convert the lhs to the rhs complex type.
4597      return rhs;
4598    }
4599  }
4600  // Finally, we have two differing integer types.
4601  // The rules for this case are in C99 6.3.1.8
4602  int compare = getIntegerTypeOrder(lhs, rhs);
4603  bool lhsSigned = lhs->isSignedIntegerType(),
4604       rhsSigned = rhs->isSignedIntegerType();
4605  QualType destType;
4606  if (lhsSigned == rhsSigned) {
4607    // Same signedness; use the higher-ranked type
4608    destType = compare >= 0 ? lhs : rhs;
4609  } else if (compare != (lhsSigned ? 1 : -1)) {
4610    // The unsigned type has greater than or equal rank to the
4611    // signed type, so use the unsigned type
4612    destType = lhsSigned ? rhs : lhs;
4613  } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
4614    // The two types are different widths; if we are here, that
4615    // means the signed type is larger than the unsigned type, so
4616    // use the signed type.
4617    destType = lhsSigned ? lhs : rhs;
4618  } else {
4619    // The signed type is higher-ranked than the unsigned type,
4620    // but isn't actually any bigger (like unsigned int and long
4621    // on most 32-bit systems).  Use the unsigned type corresponding
4622    // to the signed type.
4623    destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
4624  }
4625  return destType;
4626}
4627