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