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