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