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