ASTContext.cpp revision 4084c306635b70f37029dca938444e6013f08684
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/DeclCXX.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExternalASTSource.h"
20#include "clang/AST/RecordLayout.h"
21#include "clang/Basic/Builtins.h"
22#include "clang/Basic/SourceManager.h"
23#include "clang/Basic/TargetInfo.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/Support/MathExtras.h"
26#include "llvm/Support/MemoryBuffer.h"
27#include "RecordLayoutBuilder.h"
28
29using namespace clang;
30
31enum FloatingRank {
32  FloatRank, DoubleRank, LongDoubleRank
33};
34
35ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
36                       TargetInfo &t,
37                       IdentifierTable &idents, SelectorTable &sels,
38                       Builtin::Context &builtins,
39                       bool FreeMem, unsigned size_reserve) :
40  GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
41  ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0),
42  SourceMgr(SM), LangOpts(LOpts),
43  LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
44  Idents(idents), Selectors(sels),
45  BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
46  if (size_reserve > 0) Types.reserve(size_reserve);
47  TUDecl = TranslationUnitDecl::Create(*this);
48  InitBuiltinTypes();
49}
50
51ASTContext::~ASTContext() {
52  // Deallocate all the types.
53  while (!Types.empty()) {
54    Types.back()->Destroy(*this);
55    Types.pop_back();
56  }
57
58  {
59    llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
60      I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
61    while (I != E) {
62      ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
63      delete R;
64    }
65  }
66
67  {
68    llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
69      I = ObjCLayouts.begin(), E = ObjCLayouts.end();
70    while (I != E) {
71      ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
72      delete R;
73    }
74  }
75
76  // Destroy nested-name-specifiers.
77  for (llvm::FoldingSet<NestedNameSpecifier>::iterator
78         NNS = NestedNameSpecifiers.begin(),
79         NNSEnd = NestedNameSpecifiers.end();
80       NNS != NNSEnd;
81       /* Increment in loop */)
82    (*NNS++).Destroy(*this);
83
84  if (GlobalNestedNameSpecifier)
85    GlobalNestedNameSpecifier->Destroy(*this);
86
87  TUDecl->Destroy(*this);
88}
89
90void
91ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
92  ExternalSource.reset(Source.take());
93}
94
95void ASTContext::PrintStats() const {
96  fprintf(stderr, "*** AST Context Stats:\n");
97  fprintf(stderr, "  %d types total.\n", (int)Types.size());
98
99  unsigned counts[] = {
100#define TYPE(Name, Parent) 0,
101#define ABSTRACT_TYPE(Name, Parent)
102#include "clang/AST/TypeNodes.def"
103    0 // Extra
104  };
105
106  for (unsigned i = 0, e = Types.size(); i != e; ++i) {
107    Type *T = Types[i];
108    counts[(unsigned)T->getTypeClass()]++;
109  }
110
111  unsigned Idx = 0;
112  unsigned TotalBytes = 0;
113#define TYPE(Name, Parent)                                              \
114  if (counts[Idx])                                                      \
115    fprintf(stderr, "    %d %s types\n", (int)counts[Idx], #Name);      \
116  TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
117  ++Idx;
118#define ABSTRACT_TYPE(Name, Parent)
119#include "clang/AST/TypeNodes.def"
120
121  fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
122
123  if (ExternalSource.get()) {
124    fprintf(stderr, "\n");
125    ExternalSource->PrintStats();
126  }
127}
128
129
130void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
131  Types.push_back((R = QualType(new (*this,8) BuiltinType(K),0)).getTypePtr());
132}
133
134void ASTContext::InitBuiltinTypes() {
135  assert(VoidTy.isNull() && "Context reinitialized?");
136
137  // C99 6.2.5p19.
138  InitBuiltinType(VoidTy,              BuiltinType::Void);
139
140  // C99 6.2.5p2.
141  InitBuiltinType(BoolTy,              BuiltinType::Bool);
142  // C99 6.2.5p3.
143  if (LangOpts.CharIsSigned)
144    InitBuiltinType(CharTy,            BuiltinType::Char_S);
145  else
146    InitBuiltinType(CharTy,            BuiltinType::Char_U);
147  // C99 6.2.5p4.
148  InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
149  InitBuiltinType(ShortTy,             BuiltinType::Short);
150  InitBuiltinType(IntTy,               BuiltinType::Int);
151  InitBuiltinType(LongTy,              BuiltinType::Long);
152  InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
153
154  // C99 6.2.5p6.
155  InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
156  InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
157  InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
158  InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
159  InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
160
161  // C99 6.2.5p10.
162  InitBuiltinType(FloatTy,             BuiltinType::Float);
163  InitBuiltinType(DoubleTy,            BuiltinType::Double);
164  InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
165
166  // GNU extension, 128-bit integers.
167  InitBuiltinType(Int128Ty,            BuiltinType::Int128);
168  InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
169
170  if (LangOpts.CPlusPlus) // C++ 3.9.1p5
171    InitBuiltinType(WCharTy,           BuiltinType::WChar);
172  else // C99
173    WCharTy = getFromTargetType(Target.getWCharType());
174
175  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
176    InitBuiltinType(Char16Ty,           BuiltinType::Char16);
177  else // C99
178    Char16Ty = getFromTargetType(Target.getChar16Type());
179
180  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
181    InitBuiltinType(Char32Ty,           BuiltinType::Char32);
182  else // C99
183    Char32Ty = getFromTargetType(Target.getChar32Type());
184
185  // Placeholder type for functions.
186  InitBuiltinType(OverloadTy,          BuiltinType::Overload);
187
188  // Placeholder type for type-dependent expressions whose type is
189  // completely unknown. No code should ever check a type against
190  // DependentTy and users should never see it; however, it is here to
191  // help diagnose failures to properly check for type-dependent
192  // expressions.
193  InitBuiltinType(DependentTy,         BuiltinType::Dependent);
194
195  // Placeholder type for C++0x auto declarations whose real type has
196  // not yet been deduced.
197  InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
198
199  // C99 6.2.5p11.
200  FloatComplexTy      = getComplexType(FloatTy);
201  DoubleComplexTy     = getComplexType(DoubleTy);
202  LongDoubleComplexTy = getComplexType(LongDoubleTy);
203
204  BuiltinVaListType = QualType();
205
206  // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
207  ObjCIdTypedefType = QualType();
208  ObjCClassTypedefType = QualType();
209
210  // Builtin types for 'id' and 'Class'.
211  InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
212  InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
213
214  ObjCConstantStringType = QualType();
215
216  // void * type
217  VoidPtrTy = getPointerType(VoidTy);
218
219  // nullptr type (C++0x 2.14.7)
220  InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
221}
222
223namespace {
224  class BeforeInTranslationUnit
225    : std::binary_function<SourceRange, SourceRange, bool> {
226    SourceManager *SourceMgr;
227
228  public:
229    explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
230
231    bool operator()(SourceRange X, SourceRange Y) {
232      return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
233    }
234  };
235}
236
237/// \brief Determine whether the given comment is a Doxygen-style comment.
238///
239/// \param Start the start of the comment text.
240///
241/// \param End the end of the comment text.
242///
243/// \param Member whether we want to check whether this is a member comment
244/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
245/// we only return true when we find a non-member comment.
246static bool
247isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
248                 bool Member = false) {
249  const char *BufferStart
250    = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
251  const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
252  const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
253
254  if (End - Start < 4)
255    return false;
256
257  assert(Start[0] == '/' && "Not a comment?");
258  if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
259    return false;
260  if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
261    return false;
262
263  return (Start[3] == '<') == Member;
264}
265
266/// \brief Retrieve the comment associated with the given declaration, if
267/// it has one.
268const char *ASTContext::getCommentForDecl(const Decl *D) {
269  if (!D)
270    return 0;
271
272  // Check whether we have cached a comment string for this declaration
273  // already.
274  llvm::DenseMap<const Decl *, std::string>::iterator Pos
275    = DeclComments.find(D);
276  if (Pos != DeclComments.end())
277    return Pos->second.c_str();
278
279  // If we have an external AST source and have not yet loaded comments from
280  // that source, do so now.
281  if (ExternalSource && !LoadedExternalComments) {
282    std::vector<SourceRange> LoadedComments;
283    ExternalSource->ReadComments(LoadedComments);
284
285    if (!LoadedComments.empty())
286      Comments.insert(Comments.begin(), LoadedComments.begin(),
287                      LoadedComments.end());
288
289    LoadedExternalComments = true;
290  }
291
292  // If there are no comments anywhere, we won't find anything.
293  if (Comments.empty())
294    return 0;
295
296  // If the declaration doesn't map directly to a location in a file, we
297  // can't find the comment.
298  SourceLocation DeclStartLoc = D->getLocStart();
299  if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
300    return 0;
301
302  // Find the comment that occurs just before this declaration.
303  std::vector<SourceRange>::iterator LastComment
304    = std::lower_bound(Comments.begin(), Comments.end(),
305                       SourceRange(DeclStartLoc),
306                       BeforeInTranslationUnit(&SourceMgr));
307
308  // Decompose the location for the start of the declaration and find the
309  // beginning of the file buffer.
310  std::pair<FileID, unsigned> DeclStartDecomp
311    = SourceMgr.getDecomposedLoc(DeclStartLoc);
312  const char *FileBufferStart
313    = SourceMgr.getBufferData(DeclStartDecomp.first).first;
314
315  // First check whether we have a comment for a member.
316  if (LastComment != Comments.end() &&
317      !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
318      isDoxygenComment(SourceMgr, *LastComment, true)) {
319    std::pair<FileID, unsigned> LastCommentEndDecomp
320      = SourceMgr.getDecomposedLoc(LastComment->getEnd());
321    if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
322        SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
323          == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
324                                     LastCommentEndDecomp.second)) {
325      // The Doxygen member comment comes after the declaration starts and
326      // is on the same line and in the same file as the declaration. This
327      // is the comment we want.
328      std::string &Result = DeclComments[D];
329      Result.append(FileBufferStart +
330                      SourceMgr.getFileOffset(LastComment->getBegin()),
331                    FileBufferStart + LastCommentEndDecomp.second + 1);
332      return Result.c_str();
333    }
334  }
335
336  if (LastComment == Comments.begin())
337    return 0;
338  --LastComment;
339
340  // Decompose the end of the comment.
341  std::pair<FileID, unsigned> LastCommentEndDecomp
342    = SourceMgr.getDecomposedLoc(LastComment->getEnd());
343
344  // If the comment and the declaration aren't in the same file, then they
345  // aren't related.
346  if (DeclStartDecomp.first != LastCommentEndDecomp.first)
347    return 0;
348
349  // Check that we actually have a Doxygen comment.
350  if (!isDoxygenComment(SourceMgr, *LastComment))
351    return 0;
352
353  // Compute the starting line for the declaration and for the end of the
354  // comment (this is expensive).
355  unsigned DeclStartLine
356    = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
357  unsigned CommentEndLine
358    = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
359                              LastCommentEndDecomp.second);
360
361  // If the comment does not end on the line prior to the declaration, then
362  // the comment is not associated with the declaration at all.
363  if (CommentEndLine + 1 != DeclStartLine)
364    return 0;
365
366  // We have a comment, but there may be more comments on the previous lines.
367  // Keep looking so long as the comments are still Doxygen comments and are
368  // still adjacent.
369  unsigned ExpectedLine
370    = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
371  std::vector<SourceRange>::iterator FirstComment = LastComment;
372  while (FirstComment != Comments.begin()) {
373    // Look at the previous comment
374    --FirstComment;
375    std::pair<FileID, unsigned> Decomp
376      = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
377
378    // If this previous comment is in a different file, we're done.
379    if (Decomp.first != DeclStartDecomp.first) {
380      ++FirstComment;
381      break;
382    }
383
384    // If this comment is not a Doxygen comment, we're done.
385    if (!isDoxygenComment(SourceMgr, *FirstComment)) {
386      ++FirstComment;
387      break;
388    }
389
390    // If the line number is not what we expected, we're done.
391    unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
392    if (Line != ExpectedLine) {
393      ++FirstComment;
394      break;
395    }
396
397    // Set the next expected line number.
398    ExpectedLine
399      = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
400  }
401
402  // The iterator range [FirstComment, LastComment] contains all of the
403  // BCPL comments that, together, are associated with this declaration.
404  // Form a single comment block string for this declaration that concatenates
405  // all of these comments.
406  std::string &Result = DeclComments[D];
407  while (FirstComment != LastComment) {
408    std::pair<FileID, unsigned> DecompStart
409      = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
410    std::pair<FileID, unsigned> DecompEnd
411      = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
412    Result.append(FileBufferStart + DecompStart.second,
413                  FileBufferStart + DecompEnd.second + 1);
414    ++FirstComment;
415  }
416
417  // Append the last comment line.
418  Result.append(FileBufferStart +
419                  SourceMgr.getFileOffset(LastComment->getBegin()),
420                FileBufferStart + LastCommentEndDecomp.second + 1);
421  return Result.c_str();
422}
423
424//===----------------------------------------------------------------------===//
425//                         Type Sizing and Analysis
426//===----------------------------------------------------------------------===//
427
428/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
429/// scalar floating point type.
430const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
431  const BuiltinType *BT = T->getAsBuiltinType();
432  assert(BT && "Not a floating point type!");
433  switch (BT->getKind()) {
434  default: assert(0 && "Not a floating point type!");
435  case BuiltinType::Float:      return Target.getFloatFormat();
436  case BuiltinType::Double:     return Target.getDoubleFormat();
437  case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
438  }
439}
440
441/// getDeclAlign - Return a conservative estimate of the alignment of the
442/// specified decl.  Note that bitfields do not have a valid alignment, so
443/// this method will assert on them.
444unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
445  unsigned Align = Target.getCharWidth();
446
447  if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
448    Align = std::max(Align, AA->getAlignment());
449
450  if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
451    QualType T = VD->getType();
452    if (const ReferenceType* RT = T->getAsReferenceType()) {
453      unsigned AS = RT->getPointeeType().getAddressSpace();
454      Align = Target.getPointerAlign(AS);
455    } else if (!T->isIncompleteType() && !T->isFunctionType()) {
456      // Incomplete or function types default to 1.
457      while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
458        T = cast<ArrayType>(T)->getElementType();
459
460      Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
461    }
462  }
463
464  return Align / Target.getCharWidth();
465}
466
467/// getTypeSize - Return the size of the specified type, in bits.  This method
468/// does not work on incomplete types.
469std::pair<uint64_t, unsigned>
470ASTContext::getTypeInfo(const Type *T) {
471  uint64_t Width=0;
472  unsigned Align=8;
473  switch (T->getTypeClass()) {
474#define TYPE(Class, Base)
475#define ABSTRACT_TYPE(Class, Base)
476#define NON_CANONICAL_TYPE(Class, Base)
477#define DEPENDENT_TYPE(Class, Base) case Type::Class:
478#include "clang/AST/TypeNodes.def"
479    assert(false && "Should not see dependent types");
480    break;
481
482  case Type::FunctionNoProto:
483  case Type::FunctionProto:
484    // GCC extension: alignof(function) = 32 bits
485    Width = 0;
486    Align = 32;
487    break;
488
489  case Type::IncompleteArray:
490  case Type::VariableArray:
491    Width = 0;
492    Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
493    break;
494
495  case Type::ConstantArrayWithExpr:
496  case Type::ConstantArrayWithoutExpr:
497  case Type::ConstantArray: {
498    const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
499
500    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
501    Width = EltInfo.first*CAT->getSize().getZExtValue();
502    Align = EltInfo.second;
503    break;
504  }
505  case Type::ExtVector:
506  case Type::Vector: {
507    std::pair<uint64_t, unsigned> EltInfo =
508      getTypeInfo(cast<VectorType>(T)->getElementType());
509    Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
510    Align = Width;
511    // If the alignment is not a power of 2, round up to the next power of 2.
512    // This happens for non-power-of-2 length vectors.
513    // FIXME: this should probably be a target property.
514    Align = 1 << llvm::Log2_32_Ceil(Align);
515    break;
516  }
517
518  case Type::Builtin:
519    switch (cast<BuiltinType>(T)->getKind()) {
520    default: assert(0 && "Unknown builtin type!");
521    case BuiltinType::Void:
522      // GCC extension: alignof(void) = 8 bits.
523      Width = 0;
524      Align = 8;
525      break;
526
527    case BuiltinType::Bool:
528      Width = Target.getBoolWidth();
529      Align = Target.getBoolAlign();
530      break;
531    case BuiltinType::Char_S:
532    case BuiltinType::Char_U:
533    case BuiltinType::UChar:
534    case BuiltinType::SChar:
535      Width = Target.getCharWidth();
536      Align = Target.getCharAlign();
537      break;
538    case BuiltinType::WChar:
539      Width = Target.getWCharWidth();
540      Align = Target.getWCharAlign();
541      break;
542    case BuiltinType::Char16:
543      Width = Target.getChar16Width();
544      Align = Target.getChar16Align();
545      break;
546    case BuiltinType::Char32:
547      Width = Target.getChar32Width();
548      Align = Target.getChar32Align();
549      break;
550    case BuiltinType::UShort:
551    case BuiltinType::Short:
552      Width = Target.getShortWidth();
553      Align = Target.getShortAlign();
554      break;
555    case BuiltinType::UInt:
556    case BuiltinType::Int:
557      Width = Target.getIntWidth();
558      Align = Target.getIntAlign();
559      break;
560    case BuiltinType::ULong:
561    case BuiltinType::Long:
562      Width = Target.getLongWidth();
563      Align = Target.getLongAlign();
564      break;
565    case BuiltinType::ULongLong:
566    case BuiltinType::LongLong:
567      Width = Target.getLongLongWidth();
568      Align = Target.getLongLongAlign();
569      break;
570    case BuiltinType::Int128:
571    case BuiltinType::UInt128:
572      Width = 128;
573      Align = 128; // int128_t is 128-bit aligned on all targets.
574      break;
575    case BuiltinType::Float:
576      Width = Target.getFloatWidth();
577      Align = Target.getFloatAlign();
578      break;
579    case BuiltinType::Double:
580      Width = Target.getDoubleWidth();
581      Align = Target.getDoubleAlign();
582      break;
583    case BuiltinType::LongDouble:
584      Width = Target.getLongDoubleWidth();
585      Align = Target.getLongDoubleAlign();
586      break;
587    case BuiltinType::NullPtr:
588      Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
589      Align = Target.getPointerAlign(0); //   == sizeof(void*)
590      break;
591    }
592    break;
593  case Type::FixedWidthInt:
594    // FIXME: This isn't precisely correct; the width/alignment should depend
595    // on the available types for the target
596    Width = cast<FixedWidthIntType>(T)->getWidth();
597    Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
598    Align = Width;
599    break;
600  case Type::ExtQual:
601    // FIXME: Pointers into different addr spaces could have different sizes and
602    // alignment requirements: getPointerInfo should take an AddrSpace.
603    return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0));
604  case Type::ObjCObjectPointer:
605    Width = Target.getPointerWidth(0);
606    Align = Target.getPointerAlign(0);
607    break;
608  case Type::BlockPointer: {
609    unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
610    Width = Target.getPointerWidth(AS);
611    Align = Target.getPointerAlign(AS);
612    break;
613  }
614  case Type::Pointer: {
615    unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
616    Width = Target.getPointerWidth(AS);
617    Align = Target.getPointerAlign(AS);
618    break;
619  }
620  case Type::LValueReference:
621  case Type::RValueReference:
622    // "When applied to a reference or a reference type, the result is the size
623    // of the referenced type." C++98 5.3.3p2: expr.sizeof.
624    // FIXME: This is wrong for struct layout: a reference in a struct has
625    // pointer size.
626    return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
627  case Type::MemberPointer: {
628    // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
629    // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
630    // If we ever want to support other ABIs this needs to be abstracted.
631
632    QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
633    std::pair<uint64_t, unsigned> PtrDiffInfo =
634      getTypeInfo(getPointerDiffType());
635    Width = PtrDiffInfo.first;
636    if (Pointee->isFunctionType())
637      Width *= 2;
638    Align = PtrDiffInfo.second;
639    break;
640  }
641  case Type::Complex: {
642    // Complex types have the same alignment as their elements, but twice the
643    // size.
644    std::pair<uint64_t, unsigned> EltInfo =
645      getTypeInfo(cast<ComplexType>(T)->getElementType());
646    Width = EltInfo.first*2;
647    Align = EltInfo.second;
648    break;
649  }
650  case Type::ObjCInterface: {
651    const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
652    const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
653    Width = Layout.getSize();
654    Align = Layout.getAlignment();
655    break;
656  }
657  case Type::Record:
658  case Type::Enum: {
659    const TagType *TT = cast<TagType>(T);
660
661    if (TT->getDecl()->isInvalidDecl()) {
662      Width = 1;
663      Align = 1;
664      break;
665    }
666
667    if (const EnumType *ET = dyn_cast<EnumType>(TT))
668      return getTypeInfo(ET->getDecl()->getIntegerType());
669
670    const RecordType *RT = cast<RecordType>(TT);
671    const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
672    Width = Layout.getSize();
673    Align = Layout.getAlignment();
674    break;
675  }
676
677  case Type::Typedef: {
678    const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
679    if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
680      Align = Aligned->getAlignment();
681      Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
682    } else
683      return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
684    break;
685  }
686
687  case Type::TypeOfExpr:
688    return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
689                         .getTypePtr());
690
691  case Type::TypeOf:
692    return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
693
694  case Type::Decltype:
695    return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
696                        .getTypePtr());
697
698  case Type::QualifiedName:
699    return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
700
701  case Type::TemplateSpecialization:
702    assert(getCanonicalType(T) != T &&
703           "Cannot request the size of a dependent type");
704    // FIXME: this is likely to be wrong once we support template
705    // aliases, since a template alias could refer to a typedef that
706    // has an __aligned__ attribute on it.
707    return getTypeInfo(getCanonicalType(T));
708  }
709
710  assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
711  return std::make_pair(Width, Align);
712}
713
714/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
715/// type for the current target in bits.  This can be different than the ABI
716/// alignment in cases where it is beneficial for performance to overalign
717/// a data type.
718unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
719  unsigned ABIAlign = getTypeAlign(T);
720
721  // Double and long long should be naturally aligned if possible.
722  if (const ComplexType* CT = T->getAsComplexType())
723    T = CT->getElementType().getTypePtr();
724  if (T->isSpecificBuiltinType(BuiltinType::Double) ||
725      T->isSpecificBuiltinType(BuiltinType::LongLong))
726    return std::max(ABIAlign, (unsigned)getTypeSize(T));
727
728  return ABIAlign;
729}
730
731static void CollectLocalObjCIvars(ASTContext *Ctx,
732                                  const ObjCInterfaceDecl *OI,
733                                  llvm::SmallVectorImpl<FieldDecl*> &Fields) {
734  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
735       E = OI->ivar_end(); I != E; ++I) {
736    ObjCIvarDecl *IVDecl = *I;
737    if (!IVDecl->isInvalidDecl())
738      Fields.push_back(cast<FieldDecl>(IVDecl));
739  }
740}
741
742void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
743                             llvm::SmallVectorImpl<FieldDecl*> &Fields) {
744  if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
745    CollectObjCIvars(SuperClass, Fields);
746  CollectLocalObjCIvars(this, OI, Fields);
747}
748
749/// ShallowCollectObjCIvars -
750/// Collect all ivars, including those synthesized, in the current class.
751///
752void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
753                                 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
754                                 bool CollectSynthesized) {
755  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
756         E = OI->ivar_end(); I != E; ++I) {
757     Ivars.push_back(*I);
758  }
759  if (CollectSynthesized)
760    CollectSynthesizedIvars(OI, Ivars);
761}
762
763void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
764                                llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
765  for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
766       E = PD->prop_end(); I != E; ++I)
767    if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
768      Ivars.push_back(Ivar);
769
770  // Also look into nested protocols.
771  for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
772       E = PD->protocol_end(); P != E; ++P)
773    CollectProtocolSynthesizedIvars(*P, Ivars);
774}
775
776/// CollectSynthesizedIvars -
777/// This routine collect synthesized ivars for the designated class.
778///
779void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
780                                llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
781  for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
782       E = OI->prop_end(); I != E; ++I) {
783    if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
784      Ivars.push_back(Ivar);
785  }
786  // Also look into interface's protocol list for properties declared
787  // in the protocol and whose ivars are synthesized.
788  for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
789       PE = OI->protocol_end(); P != PE; ++P) {
790    ObjCProtocolDecl *PD = (*P);
791    CollectProtocolSynthesizedIvars(PD, Ivars);
792  }
793}
794
795unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
796  unsigned count = 0;
797  for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
798       E = PD->prop_end(); I != E; ++I)
799    if ((*I)->getPropertyIvarDecl())
800      ++count;
801
802  // Also look into nested protocols.
803  for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
804       E = PD->protocol_end(); P != E; ++P)
805    count += CountProtocolSynthesizedIvars(*P);
806  return count;
807}
808
809unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI)
810{
811  unsigned count = 0;
812  for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
813       E = OI->prop_end(); I != E; ++I) {
814    if ((*I)->getPropertyIvarDecl())
815      ++count;
816  }
817  // Also look into interface's protocol list for properties declared
818  // in the protocol and whose ivars are synthesized.
819  for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
820       PE = OI->protocol_end(); P != PE; ++P) {
821    ObjCProtocolDecl *PD = (*P);
822    count += CountProtocolSynthesizedIvars(PD);
823  }
824  return count;
825}
826
827/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
828ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
829  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
830    I = ObjCImpls.find(D);
831  if (I != ObjCImpls.end())
832    return cast<ObjCImplementationDecl>(I->second);
833  return 0;
834}
835/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
836ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
837  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
838    I = ObjCImpls.find(D);
839  if (I != ObjCImpls.end())
840    return cast<ObjCCategoryImplDecl>(I->second);
841  return 0;
842}
843
844/// \brief Set the implementation of ObjCInterfaceDecl.
845void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
846                           ObjCImplementationDecl *ImplD) {
847  assert(IFaceD && ImplD && "Passed null params");
848  ObjCImpls[IFaceD] = ImplD;
849}
850/// \brief Set the implementation of ObjCCategoryDecl.
851void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
852                           ObjCCategoryImplDecl *ImplD) {
853  assert(CatD && ImplD && "Passed null params");
854  ObjCImpls[CatD] = ImplD;
855}
856
857/// getInterfaceLayoutImpl - Get or compute information about the
858/// layout of the given interface.
859///
860/// \param Impl - If given, also include the layout of the interface's
861/// implementation. This may differ by including synthesized ivars.
862const ASTRecordLayout &
863ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
864                          const ObjCImplementationDecl *Impl) {
865  assert(!D->isForwardDecl() && "Invalid interface decl!");
866
867  // Look up this layout, if already laid out, return what we have.
868  ObjCContainerDecl *Key =
869    Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
870  if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
871    return *Entry;
872
873  // Add in synthesized ivar count if laying out an implementation.
874  if (Impl) {
875    unsigned FieldCount = D->ivar_size();
876    unsigned SynthCount = CountSynthesizedIvars(D);
877    FieldCount += SynthCount;
878    // If there aren't any sythesized ivars then reuse the interface
879    // entry. Note we can't cache this because we simply free all
880    // entries later; however we shouldn't look up implementations
881    // frequently.
882    if (SynthCount == 0)
883      return getObjCLayout(D, 0);
884  }
885
886  const ASTRecordLayout *NewEntry =
887    ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
888  ObjCLayouts[Key] = NewEntry;
889
890  return *NewEntry;
891}
892
893const ASTRecordLayout &
894ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
895  return getObjCLayout(D, 0);
896}
897
898const ASTRecordLayout &
899ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
900  return getObjCLayout(D->getClassInterface(), D);
901}
902
903/// getASTRecordLayout - Get or compute information about the layout of the
904/// specified record (struct/union/class), which indicates its size and field
905/// position information.
906const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
907  D = D->getDefinition(*this);
908  assert(D && "Cannot get layout of forward declarations!");
909
910  // Look up this layout, if already laid out, return what we have.
911  // Note that we can't save a reference to the entry because this function
912  // is recursive.
913  const ASTRecordLayout *Entry = ASTRecordLayouts[D];
914  if (Entry) return *Entry;
915
916  const ASTRecordLayout *NewEntry =
917    ASTRecordLayoutBuilder::ComputeLayout(*this, D);
918  ASTRecordLayouts[D] = NewEntry;
919
920  return *NewEntry;
921}
922
923//===----------------------------------------------------------------------===//
924//                   Type creation/memoization methods
925//===----------------------------------------------------------------------===//
926
927QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
928  QualType CanT = getCanonicalType(T);
929  if (CanT.getAddressSpace() == AddressSpace)
930    return T;
931
932  // If we are composing extended qualifiers together, merge together into one
933  // ExtQualType node.
934  unsigned CVRQuals = T.getCVRQualifiers();
935  QualType::GCAttrTypes GCAttr = QualType::GCNone;
936  Type *TypeNode = T.getTypePtr();
937
938  if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
939    // If this type already has an address space specified, it cannot get
940    // another one.
941    assert(EQT->getAddressSpace() == 0 &&
942           "Type cannot be in multiple addr spaces!");
943    GCAttr = EQT->getObjCGCAttr();
944    TypeNode = EQT->getBaseType();
945  }
946
947  // Check if we've already instantiated this type.
948  llvm::FoldingSetNodeID ID;
949  ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
950  void *InsertPos = 0;
951  if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
952    return QualType(EXTQy, CVRQuals);
953
954  // If the base type isn't canonical, this won't be a canonical type either,
955  // so fill in the canonical type field.
956  QualType Canonical;
957  if (!TypeNode->isCanonical()) {
958    Canonical = getAddrSpaceQualType(CanT, AddressSpace);
959
960    // Update InsertPos, the previous call could have invalidated it.
961    ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
962    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
963  }
964  ExtQualType *New =
965    new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
966  ExtQualTypes.InsertNode(New, InsertPos);
967  Types.push_back(New);
968  return QualType(New, CVRQuals);
969}
970
971QualType ASTContext::getObjCGCQualType(QualType T,
972                                       QualType::GCAttrTypes GCAttr) {
973  QualType CanT = getCanonicalType(T);
974  if (CanT.getObjCGCAttr() == GCAttr)
975    return T;
976
977  if (T->isPointerType()) {
978    QualType Pointee = T->getAsPointerType()->getPointeeType();
979    if (Pointee->isAnyPointerType()) {
980      QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
981      return getPointerType(ResultType);
982    }
983  }
984  // If we are composing extended qualifiers together, merge together into one
985  // ExtQualType node.
986  unsigned CVRQuals = T.getCVRQualifiers();
987  Type *TypeNode = T.getTypePtr();
988  unsigned AddressSpace = 0;
989
990  if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
991    // If this type already has an address space specified, it cannot get
992    // another one.
993    assert(EQT->getObjCGCAttr() == QualType::GCNone &&
994           "Type cannot be in multiple addr spaces!");
995    AddressSpace = EQT->getAddressSpace();
996    TypeNode = EQT->getBaseType();
997  }
998
999  // Check if we've already instantiated an gc qual'd type of this type.
1000  llvm::FoldingSetNodeID ID;
1001  ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
1002  void *InsertPos = 0;
1003  if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
1004    return QualType(EXTQy, CVRQuals);
1005
1006  // If the base type isn't canonical, this won't be a canonical type either,
1007  // so fill in the canonical type field.
1008  // FIXME: Isn't this also not canonical if the base type is a array
1009  // or pointer type?  I can't find any documentation for objc_gc, though...
1010  QualType Canonical;
1011  if (!T->isCanonical()) {
1012    Canonical = getObjCGCQualType(CanT, GCAttr);
1013
1014    // Update InsertPos, the previous call could have invalidated it.
1015    ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
1016    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1017  }
1018  ExtQualType *New =
1019    new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
1020  ExtQualTypes.InsertNode(New, InsertPos);
1021  Types.push_back(New);
1022  return QualType(New, CVRQuals);
1023}
1024
1025/// getComplexType - Return the uniqued reference to the type for a complex
1026/// number with the specified element type.
1027QualType ASTContext::getComplexType(QualType T) {
1028  // Unique pointers, to guarantee there is only one pointer of a particular
1029  // structure.
1030  llvm::FoldingSetNodeID ID;
1031  ComplexType::Profile(ID, T);
1032
1033  void *InsertPos = 0;
1034  if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1035    return QualType(CT, 0);
1036
1037  // If the pointee type isn't canonical, this won't be a canonical type either,
1038  // so fill in the canonical type field.
1039  QualType Canonical;
1040  if (!T->isCanonical()) {
1041    Canonical = getComplexType(getCanonicalType(T));
1042
1043    // Get the new insert position for the node we care about.
1044    ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
1045    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1046  }
1047  ComplexType *New = new (*this,8) ComplexType(T, Canonical);
1048  Types.push_back(New);
1049  ComplexTypes.InsertNode(New, InsertPos);
1050  return QualType(New, 0);
1051}
1052
1053QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1054  llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1055     SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1056  FixedWidthIntType *&Entry = Map[Width];
1057  if (!Entry)
1058    Entry = new FixedWidthIntType(Width, Signed);
1059  return QualType(Entry, 0);
1060}
1061
1062/// getPointerType - Return the uniqued reference to the type for a pointer to
1063/// the specified type.
1064QualType ASTContext::getPointerType(QualType T) {
1065  // Unique pointers, to guarantee there is only one pointer of a particular
1066  // structure.
1067  llvm::FoldingSetNodeID ID;
1068  PointerType::Profile(ID, T);
1069
1070  void *InsertPos = 0;
1071  if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1072    return QualType(PT, 0);
1073
1074  // If the pointee type isn't canonical, this won't be a canonical type either,
1075  // so fill in the canonical type field.
1076  QualType Canonical;
1077  if (!T->isCanonical()) {
1078    Canonical = getPointerType(getCanonicalType(T));
1079
1080    // Get the new insert position for the node we care about.
1081    PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1082    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1083  }
1084  PointerType *New = new (*this,8) PointerType(T, Canonical);
1085  Types.push_back(New);
1086  PointerTypes.InsertNode(New, InsertPos);
1087  return QualType(New, 0);
1088}
1089
1090/// getBlockPointerType - Return the uniqued reference to the type for
1091/// a pointer to the specified block.
1092QualType ASTContext::getBlockPointerType(QualType T) {
1093  assert(T->isFunctionType() && "block of function types only");
1094  // Unique pointers, to guarantee there is only one block of a particular
1095  // structure.
1096  llvm::FoldingSetNodeID ID;
1097  BlockPointerType::Profile(ID, T);
1098
1099  void *InsertPos = 0;
1100  if (BlockPointerType *PT =
1101        BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1102    return QualType(PT, 0);
1103
1104  // If the block pointee type isn't canonical, this won't be a canonical
1105  // type either so fill in the canonical type field.
1106  QualType Canonical;
1107  if (!T->isCanonical()) {
1108    Canonical = getBlockPointerType(getCanonicalType(T));
1109
1110    // Get the new insert position for the node we care about.
1111    BlockPointerType *NewIP =
1112      BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1113    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1114  }
1115  BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
1116  Types.push_back(New);
1117  BlockPointerTypes.InsertNode(New, InsertPos);
1118  return QualType(New, 0);
1119}
1120
1121/// getLValueReferenceType - Return the uniqued reference to the type for an
1122/// lvalue reference to the specified type.
1123QualType ASTContext::getLValueReferenceType(QualType T) {
1124  // Unique pointers, to guarantee there is only one pointer of a particular
1125  // structure.
1126  llvm::FoldingSetNodeID ID;
1127  ReferenceType::Profile(ID, T);
1128
1129  void *InsertPos = 0;
1130  if (LValueReferenceType *RT =
1131        LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1132    return QualType(RT, 0);
1133
1134  // If the referencee type isn't canonical, this won't be a canonical type
1135  // either, so fill in the canonical type field.
1136  QualType Canonical;
1137  if (!T->isCanonical()) {
1138    Canonical = getLValueReferenceType(getCanonicalType(T));
1139
1140    // Get the new insert position for the node we care about.
1141    LValueReferenceType *NewIP =
1142      LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1143    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1144  }
1145
1146  LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
1147  Types.push_back(New);
1148  LValueReferenceTypes.InsertNode(New, InsertPos);
1149  return QualType(New, 0);
1150}
1151
1152/// getRValueReferenceType - Return the uniqued reference to the type for an
1153/// rvalue reference to the specified type.
1154QualType ASTContext::getRValueReferenceType(QualType T) {
1155  // Unique pointers, to guarantee there is only one pointer of a particular
1156  // structure.
1157  llvm::FoldingSetNodeID ID;
1158  ReferenceType::Profile(ID, T);
1159
1160  void *InsertPos = 0;
1161  if (RValueReferenceType *RT =
1162        RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1163    return QualType(RT, 0);
1164
1165  // If the referencee type isn't canonical, this won't be a canonical type
1166  // either, so fill in the canonical type field.
1167  QualType Canonical;
1168  if (!T->isCanonical()) {
1169    Canonical = getRValueReferenceType(getCanonicalType(T));
1170
1171    // Get the new insert position for the node we care about.
1172    RValueReferenceType *NewIP =
1173      RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1174    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1175  }
1176
1177  RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
1178  Types.push_back(New);
1179  RValueReferenceTypes.InsertNode(New, InsertPos);
1180  return QualType(New, 0);
1181}
1182
1183/// getMemberPointerType - Return the uniqued reference to the type for a
1184/// member pointer to the specified type, in the specified class.
1185QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1186{
1187  // Unique pointers, to guarantee there is only one pointer of a particular
1188  // structure.
1189  llvm::FoldingSetNodeID ID;
1190  MemberPointerType::Profile(ID, T, Cls);
1191
1192  void *InsertPos = 0;
1193  if (MemberPointerType *PT =
1194      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1195    return QualType(PT, 0);
1196
1197  // If the pointee or class type isn't canonical, this won't be a canonical
1198  // type either, so fill in the canonical type field.
1199  QualType Canonical;
1200  if (!T->isCanonical()) {
1201    Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1202
1203    // Get the new insert position for the node we care about.
1204    MemberPointerType *NewIP =
1205      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1206    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1207  }
1208  MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
1209  Types.push_back(New);
1210  MemberPointerTypes.InsertNode(New, InsertPos);
1211  return QualType(New, 0);
1212}
1213
1214/// getConstantArrayType - Return the unique reference to the type for an
1215/// array of the specified element type.
1216QualType ASTContext::getConstantArrayType(QualType EltTy,
1217                                          const llvm::APInt &ArySizeIn,
1218                                          ArrayType::ArraySizeModifier ASM,
1219                                          unsigned EltTypeQuals) {
1220  assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1221         "Constant array of VLAs is illegal!");
1222
1223  // Convert the array size into a canonical width matching the pointer size for
1224  // the target.
1225  llvm::APInt ArySize(ArySizeIn);
1226  ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1227
1228  llvm::FoldingSetNodeID ID;
1229  ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
1230
1231  void *InsertPos = 0;
1232  if (ConstantArrayType *ATP =
1233      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1234    return QualType(ATP, 0);
1235
1236  // If the element type isn't canonical, this won't be a canonical type either,
1237  // so fill in the canonical type field.
1238  QualType Canonical;
1239  if (!EltTy->isCanonical()) {
1240    Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
1241                                     ASM, EltTypeQuals);
1242    // Get the new insert position for the node we care about.
1243    ConstantArrayType *NewIP =
1244      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1245    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1246  }
1247
1248  ConstantArrayType *New =
1249    new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
1250  ConstantArrayTypes.InsertNode(New, InsertPos);
1251  Types.push_back(New);
1252  return QualType(New, 0);
1253}
1254
1255/// getConstantArrayWithExprType - Return a reference to the type for
1256/// an array of the specified element type.
1257QualType
1258ASTContext::getConstantArrayWithExprType(QualType EltTy,
1259                                         const llvm::APInt &ArySizeIn,
1260                                         Expr *ArySizeExpr,
1261                                         ArrayType::ArraySizeModifier ASM,
1262                                         unsigned EltTypeQuals,
1263                                         SourceRange Brackets) {
1264  // Convert the array size into a canonical width matching the pointer
1265  // size for the target.
1266  llvm::APInt ArySize(ArySizeIn);
1267  ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1268
1269  // Compute the canonical ConstantArrayType.
1270  QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1271                                            ArySize, ASM, EltTypeQuals);
1272  // Since we don't unique expressions, it isn't possible to unique VLA's
1273  // that have an expression provided for their size.
1274  ConstantArrayWithExprType *New =
1275    new(*this,8)ConstantArrayWithExprType(EltTy, Canonical,
1276                                          ArySize, ArySizeExpr,
1277                                          ASM, EltTypeQuals, Brackets);
1278  Types.push_back(New);
1279  return QualType(New, 0);
1280}
1281
1282/// getConstantArrayWithoutExprType - Return a reference to the type for
1283/// an array of the specified element type.
1284QualType
1285ASTContext::getConstantArrayWithoutExprType(QualType EltTy,
1286                                            const llvm::APInt &ArySizeIn,
1287                                            ArrayType::ArraySizeModifier ASM,
1288                                            unsigned EltTypeQuals) {
1289  // Convert the array size into a canonical width matching the pointer
1290  // size for the target.
1291  llvm::APInt ArySize(ArySizeIn);
1292  ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1293
1294  // Compute the canonical ConstantArrayType.
1295  QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1296                                            ArySize, ASM, EltTypeQuals);
1297  ConstantArrayWithoutExprType *New =
1298    new(*this,8)ConstantArrayWithoutExprType(EltTy, Canonical,
1299                                             ArySize, ASM, EltTypeQuals);
1300  Types.push_back(New);
1301  return QualType(New, 0);
1302}
1303
1304/// getVariableArrayType - Returns a non-unique reference to the type for a
1305/// variable array of the specified element type.
1306QualType ASTContext::getVariableArrayType(QualType EltTy,
1307                                          Expr *NumElts,
1308                                          ArrayType::ArraySizeModifier ASM,
1309                                          unsigned EltTypeQuals,
1310                                          SourceRange Brackets) {
1311  // Since we don't unique expressions, it isn't possible to unique VLA's
1312  // that have an expression provided for their size.
1313
1314  VariableArrayType *New =
1315    new(*this,8)VariableArrayType(EltTy, QualType(),
1316                                  NumElts, ASM, EltTypeQuals, Brackets);
1317
1318  VariableArrayTypes.push_back(New);
1319  Types.push_back(New);
1320  return QualType(New, 0);
1321}
1322
1323/// getDependentSizedArrayType - Returns a non-unique reference to
1324/// the type for a dependently-sized array of the specified element
1325/// type. FIXME: We will need these to be uniqued, or at least
1326/// comparable, at some point.
1327QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1328                                                Expr *NumElts,
1329                                                ArrayType::ArraySizeModifier ASM,
1330                                                unsigned EltTypeQuals,
1331                                                SourceRange Brackets) {
1332  assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1333         "Size must be type- or value-dependent!");
1334
1335  // Since we don't unique expressions, it isn't possible to unique
1336  // dependently-sized array types.
1337
1338  DependentSizedArrayType *New =
1339    new (*this,8) DependentSizedArrayType(EltTy, QualType(),
1340                                          NumElts, ASM, EltTypeQuals,
1341                                          Brackets);
1342
1343  DependentSizedArrayTypes.push_back(New);
1344  Types.push_back(New);
1345  return QualType(New, 0);
1346}
1347
1348QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1349                                            ArrayType::ArraySizeModifier ASM,
1350                                            unsigned EltTypeQuals) {
1351  llvm::FoldingSetNodeID ID;
1352  IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
1353
1354  void *InsertPos = 0;
1355  if (IncompleteArrayType *ATP =
1356       IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1357    return QualType(ATP, 0);
1358
1359  // If the element type isn't canonical, this won't be a canonical type
1360  // either, so fill in the canonical type field.
1361  QualType Canonical;
1362
1363  if (!EltTy->isCanonical()) {
1364    Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
1365                                       ASM, EltTypeQuals);
1366
1367    // Get the new insert position for the node we care about.
1368    IncompleteArrayType *NewIP =
1369      IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1370    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1371  }
1372
1373  IncompleteArrayType *New
1374    = new (*this,8) IncompleteArrayType(EltTy, Canonical,
1375                                        ASM, EltTypeQuals);
1376
1377  IncompleteArrayTypes.InsertNode(New, InsertPos);
1378  Types.push_back(New);
1379  return QualType(New, 0);
1380}
1381
1382/// getVectorType - Return the unique reference to a vector type of
1383/// the specified element type and size. VectorType must be a built-in type.
1384QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
1385  BuiltinType *baseType;
1386
1387  baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1388  assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
1389
1390  // Check if we've already instantiated a vector of this type.
1391  llvm::FoldingSetNodeID ID;
1392  VectorType::Profile(ID, vecType, NumElts, Type::Vector);
1393  void *InsertPos = 0;
1394  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1395    return QualType(VTP, 0);
1396
1397  // If the element type isn't canonical, this won't be a canonical type either,
1398  // so fill in the canonical type field.
1399  QualType Canonical;
1400  if (!vecType->isCanonical()) {
1401    Canonical = getVectorType(getCanonicalType(vecType), NumElts);
1402
1403    // Get the new insert position for the node we care about.
1404    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1405    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1406  }
1407  VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
1408  VectorTypes.InsertNode(New, InsertPos);
1409  Types.push_back(New);
1410  return QualType(New, 0);
1411}
1412
1413/// getExtVectorType - Return the unique reference to an extended vector type of
1414/// the specified element type and size. VectorType must be a built-in type.
1415QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
1416  BuiltinType *baseType;
1417
1418  baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1419  assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
1420
1421  // Check if we've already instantiated a vector of this type.
1422  llvm::FoldingSetNodeID ID;
1423  VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
1424  void *InsertPos = 0;
1425  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1426    return QualType(VTP, 0);
1427
1428  // If the element type isn't canonical, this won't be a canonical type either,
1429  // so fill in the canonical type field.
1430  QualType Canonical;
1431  if (!vecType->isCanonical()) {
1432    Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
1433
1434    // Get the new insert position for the node we care about.
1435    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1436    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1437  }
1438  ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
1439  VectorTypes.InsertNode(New, InsertPos);
1440  Types.push_back(New);
1441  return QualType(New, 0);
1442}
1443
1444QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1445                                                    Expr *SizeExpr,
1446                                                    SourceLocation AttrLoc) {
1447  DependentSizedExtVectorType *New =
1448      new (*this,8) DependentSizedExtVectorType(vecType, QualType(),
1449                                                SizeExpr, AttrLoc);
1450
1451  DependentSizedExtVectorTypes.push_back(New);
1452  Types.push_back(New);
1453  return QualType(New, 0);
1454}
1455
1456/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
1457///
1458QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) {
1459  // Unique functions, to guarantee there is only one function of a particular
1460  // structure.
1461  llvm::FoldingSetNodeID ID;
1462  FunctionNoProtoType::Profile(ID, ResultTy);
1463
1464  void *InsertPos = 0;
1465  if (FunctionNoProtoType *FT =
1466        FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1467    return QualType(FT, 0);
1468
1469  QualType Canonical;
1470  if (!ResultTy->isCanonical()) {
1471    Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy));
1472
1473    // Get the new insert position for the node we care about.
1474    FunctionNoProtoType *NewIP =
1475      FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1476    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1477  }
1478
1479  FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical);
1480  Types.push_back(New);
1481  FunctionNoProtoTypes.InsertNode(New, InsertPos);
1482  return QualType(New, 0);
1483}
1484
1485/// getFunctionType - Return a normal function type with a typed argument
1486/// list.  isVariadic indicates whether the argument list includes '...'.
1487QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
1488                                     unsigned NumArgs, bool isVariadic,
1489                                     unsigned TypeQuals, bool hasExceptionSpec,
1490                                     bool hasAnyExceptionSpec, unsigned NumExs,
1491                                     const QualType *ExArray) {
1492  // Unique functions, to guarantee there is only one function of a particular
1493  // structure.
1494  llvm::FoldingSetNodeID ID;
1495  FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
1496                             TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1497                             NumExs, ExArray);
1498
1499  void *InsertPos = 0;
1500  if (FunctionProtoType *FTP =
1501        FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1502    return QualType(FTP, 0);
1503
1504  // Determine whether the type being created is already canonical or not.
1505  bool isCanonical = ResultTy->isCanonical();
1506  if (hasExceptionSpec)
1507    isCanonical = false;
1508  for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1509    if (!ArgArray[i]->isCanonical())
1510      isCanonical = false;
1511
1512  // If this type isn't canonical, get the canonical version of it.
1513  // The exception spec is not part of the canonical type.
1514  QualType Canonical;
1515  if (!isCanonical) {
1516    llvm::SmallVector<QualType, 16> CanonicalArgs;
1517    CanonicalArgs.reserve(NumArgs);
1518    for (unsigned i = 0; i != NumArgs; ++i)
1519      CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
1520
1521    Canonical = getFunctionType(getCanonicalType(ResultTy),
1522                                CanonicalArgs.data(), NumArgs,
1523                                isVariadic, TypeQuals);
1524
1525    // Get the new insert position for the node we care about.
1526    FunctionProtoType *NewIP =
1527      FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1528    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1529  }
1530
1531  // FunctionProtoType objects are allocated with extra bytes after them
1532  // for two variable size arrays (for parameter and exception types) at the
1533  // end of them.
1534  FunctionProtoType *FTP =
1535    (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1536                                 NumArgs*sizeof(QualType) +
1537                                 NumExs*sizeof(QualType), 8);
1538  new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
1539                              TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1540                              ExArray, NumExs, Canonical);
1541  Types.push_back(FTP);
1542  FunctionProtoTypes.InsertNode(FTP, InsertPos);
1543  return QualType(FTP, 0);
1544}
1545
1546/// getTypeDeclType - Return the unique reference to the type for the
1547/// specified type declaration.
1548QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
1549  assert(Decl && "Passed null for Decl param");
1550  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1551
1552  if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
1553    return getTypedefType(Typedef);
1554  else if (isa<TemplateTypeParmDecl>(Decl)) {
1555    assert(false && "Template type parameter types are always available.");
1556  } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
1557    return getObjCInterfaceType(ObjCInterface);
1558
1559  if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
1560    if (PrevDecl)
1561      Decl->TypeForDecl = PrevDecl->TypeForDecl;
1562    else
1563      Decl->TypeForDecl = new (*this,8) RecordType(Record);
1564  }
1565  else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1566    if (PrevDecl)
1567      Decl->TypeForDecl = PrevDecl->TypeForDecl;
1568    else
1569      Decl->TypeForDecl = new (*this,8) EnumType(Enum);
1570  }
1571  else
1572    assert(false && "TypeDecl without a type?");
1573
1574  if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
1575  return QualType(Decl->TypeForDecl, 0);
1576}
1577
1578/// getTypedefType - Return the unique reference to the type for the
1579/// specified typename decl.
1580QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1581  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1582
1583  QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
1584  Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
1585  Types.push_back(Decl->TypeForDecl);
1586  return QualType(Decl->TypeForDecl, 0);
1587}
1588
1589/// \brief Retrieve the template type parameter type for a template
1590/// parameter or parameter pack with the given depth, index, and (optionally)
1591/// name.
1592QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
1593                                             bool ParameterPack,
1594                                             IdentifierInfo *Name) {
1595  llvm::FoldingSetNodeID ID;
1596  TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
1597  void *InsertPos = 0;
1598  TemplateTypeParmType *TypeParm
1599    = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1600
1601  if (TypeParm)
1602    return QualType(TypeParm, 0);
1603
1604  if (Name) {
1605    QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1606    TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack,
1607                                                   Name, Canon);
1608  } else
1609    TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack);
1610
1611  Types.push_back(TypeParm);
1612  TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1613
1614  return QualType(TypeParm, 0);
1615}
1616
1617QualType
1618ASTContext::getTemplateSpecializationType(TemplateName Template,
1619                                          const TemplateArgument *Args,
1620                                          unsigned NumArgs,
1621                                          QualType Canon) {
1622  if (!Canon.isNull())
1623    Canon = getCanonicalType(Canon);
1624
1625  llvm::FoldingSetNodeID ID;
1626  TemplateSpecializationType::Profile(ID, Template, Args, NumArgs);
1627
1628  void *InsertPos = 0;
1629  TemplateSpecializationType *Spec
1630    = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1631
1632  if (Spec)
1633    return QualType(Spec, 0);
1634
1635  void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1636                        sizeof(TemplateArgument) * NumArgs),
1637                       8);
1638  Spec = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Canon);
1639  Types.push_back(Spec);
1640  TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1641
1642  return QualType(Spec, 0);
1643}
1644
1645QualType
1646ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
1647                                 QualType NamedType) {
1648  llvm::FoldingSetNodeID ID;
1649  QualifiedNameType::Profile(ID, NNS, NamedType);
1650
1651  void *InsertPos = 0;
1652  QualifiedNameType *T
1653    = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1654  if (T)
1655    return QualType(T, 0);
1656
1657  T = new (*this) QualifiedNameType(NNS, NamedType,
1658                                    getCanonicalType(NamedType));
1659  Types.push_back(T);
1660  QualifiedNameTypes.InsertNode(T, InsertPos);
1661  return QualType(T, 0);
1662}
1663
1664QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1665                                     const IdentifierInfo *Name,
1666                                     QualType Canon) {
1667  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1668
1669  if (Canon.isNull()) {
1670    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1671    if (CanonNNS != NNS)
1672      Canon = getTypenameType(CanonNNS, Name);
1673  }
1674
1675  llvm::FoldingSetNodeID ID;
1676  TypenameType::Profile(ID, NNS, Name);
1677
1678  void *InsertPos = 0;
1679  TypenameType *T
1680    = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1681  if (T)
1682    return QualType(T, 0);
1683
1684  T = new (*this) TypenameType(NNS, Name, Canon);
1685  Types.push_back(T);
1686  TypenameTypes.InsertNode(T, InsertPos);
1687  return QualType(T, 0);
1688}
1689
1690QualType
1691ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1692                            const TemplateSpecializationType *TemplateId,
1693                            QualType Canon) {
1694  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1695
1696  if (Canon.isNull()) {
1697    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1698    QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1699    if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1700      const TemplateSpecializationType *CanonTemplateId
1701        = CanonType->getAsTemplateSpecializationType();
1702      assert(CanonTemplateId &&
1703             "Canonical type must also be a template specialization type");
1704      Canon = getTypenameType(CanonNNS, CanonTemplateId);
1705    }
1706  }
1707
1708  llvm::FoldingSetNodeID ID;
1709  TypenameType::Profile(ID, NNS, TemplateId);
1710
1711  void *InsertPos = 0;
1712  TypenameType *T
1713    = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1714  if (T)
1715    return QualType(T, 0);
1716
1717  T = new (*this) TypenameType(NNS, TemplateId, Canon);
1718  Types.push_back(T);
1719  TypenameTypes.InsertNode(T, InsertPos);
1720  return QualType(T, 0);
1721}
1722
1723/// CmpProtocolNames - Comparison predicate for sorting protocols
1724/// alphabetically.
1725static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1726                            const ObjCProtocolDecl *RHS) {
1727  return LHS->getDeclName() < RHS->getDeclName();
1728}
1729
1730static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1731                                   unsigned &NumProtocols) {
1732  ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1733
1734  // Sort protocols, keyed by name.
1735  std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1736
1737  // Remove duplicates.
1738  ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1739  NumProtocols = ProtocolsEnd-Protocols;
1740}
1741
1742/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1743/// the given interface decl and the conforming protocol list.
1744QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
1745                                              ObjCProtocolDecl **Protocols,
1746                                              unsigned NumProtocols) {
1747  // Sort the protocol list alphabetically to canonicalize it.
1748  if (NumProtocols)
1749    SortAndUniqueProtocols(Protocols, NumProtocols);
1750
1751  llvm::FoldingSetNodeID ID;
1752  ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
1753
1754  void *InsertPos = 0;
1755  if (ObjCObjectPointerType *QT =
1756              ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1757    return QualType(QT, 0);
1758
1759  // No Match;
1760  ObjCObjectPointerType *QType =
1761    new (*this,8) ObjCObjectPointerType(InterfaceT, Protocols, NumProtocols);
1762
1763  Types.push_back(QType);
1764  ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1765  return QualType(QType, 0);
1766}
1767
1768/// getObjCInterfaceType - Return the unique reference to the type for the
1769/// specified ObjC interface decl. The list of protocols is optional.
1770QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
1771                       ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
1772  if (NumProtocols)
1773    // Sort the protocol list alphabetically to canonicalize it.
1774    SortAndUniqueProtocols(Protocols, NumProtocols);
1775
1776  llvm::FoldingSetNodeID ID;
1777  ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
1778
1779  void *InsertPos = 0;
1780  if (ObjCInterfaceType *QT =
1781      ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
1782    return QualType(QT, 0);
1783
1784  // No Match;
1785  ObjCInterfaceType *QType =
1786    new (*this,8) ObjCInterfaceType(const_cast<ObjCInterfaceDecl*>(Decl),
1787                                    Protocols, NumProtocols);
1788  Types.push_back(QType);
1789  ObjCInterfaceTypes.InsertNode(QType, InsertPos);
1790  return QualType(QType, 0);
1791}
1792
1793/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1794/// TypeOfExprType AST's (since expression's are never shared). For example,
1795/// multiple declarations that refer to "typeof(x)" all contain different
1796/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1797/// on canonical type's (which are always unique).
1798QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
1799  TypeOfExprType *toe;
1800  if (tofExpr->isTypeDependent())
1801    toe = new (*this, 8) TypeOfExprType(tofExpr);
1802  else {
1803    QualType Canonical = getCanonicalType(tofExpr->getType());
1804    toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
1805  }
1806  Types.push_back(toe);
1807  return QualType(toe, 0);
1808}
1809
1810/// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
1811/// TypeOfType AST's. The only motivation to unique these nodes would be
1812/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1813/// an issue. This doesn't effect the type checker, since it operates
1814/// on canonical type's (which are always unique).
1815QualType ASTContext::getTypeOfType(QualType tofType) {
1816  QualType Canonical = getCanonicalType(tofType);
1817  TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
1818  Types.push_back(tot);
1819  return QualType(tot, 0);
1820}
1821
1822/// getDecltypeForExpr - Given an expr, will return the decltype for that
1823/// expression, according to the rules in C++0x [dcl.type.simple]p4
1824static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
1825  if (e->isTypeDependent())
1826    return Context.DependentTy;
1827
1828  // If e is an id expression or a class member access, decltype(e) is defined
1829  // as the type of the entity named by e.
1830  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
1831    if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
1832      return VD->getType();
1833  }
1834  if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
1835    if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1836      return FD->getType();
1837  }
1838  // If e is a function call or an invocation of an overloaded operator,
1839  // (parentheses around e are ignored), decltype(e) is defined as the
1840  // return type of that function.
1841  if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
1842    return CE->getCallReturnType();
1843
1844  QualType T = e->getType();
1845
1846  // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
1847  // defined as T&, otherwise decltype(e) is defined as T.
1848  if (e->isLvalue(Context) == Expr::LV_Valid)
1849    T = Context.getLValueReferenceType(T);
1850
1851  return T;
1852}
1853
1854/// getDecltypeType -  Unlike many "get<Type>" functions, we don't unique
1855/// DecltypeType AST's. The only motivation to unique these nodes would be
1856/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
1857/// an issue. This doesn't effect the type checker, since it operates
1858/// on canonical type's (which are always unique).
1859QualType ASTContext::getDecltypeType(Expr *e) {
1860  DecltypeType *dt;
1861  if (e->isTypeDependent()) // FIXME: canonicalize the expression
1862    dt = new (*this, 8) DecltypeType(e, DependentTy);
1863  else {
1864    QualType T = getDecltypeForExpr(e, *this);
1865    dt = new (*this, 8) DecltypeType(e, T, getCanonicalType(T));
1866  }
1867  Types.push_back(dt);
1868  return QualType(dt, 0);
1869}
1870
1871/// getTagDeclType - Return the unique reference to the type for the
1872/// specified TagDecl (struct/union/class/enum) decl.
1873QualType ASTContext::getTagDeclType(TagDecl *Decl) {
1874  assert (Decl);
1875  return getTypeDeclType(Decl);
1876}
1877
1878/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
1879/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
1880/// needs to agree with the definition in <stddef.h>.
1881QualType ASTContext::getSizeType() const {
1882  return getFromTargetType(Target.getSizeType());
1883}
1884
1885/// getSignedWCharType - Return the type of "signed wchar_t".
1886/// Used when in C++, as a GCC extension.
1887QualType ASTContext::getSignedWCharType() const {
1888  // FIXME: derive from "Target" ?
1889  return WCharTy;
1890}
1891
1892/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
1893/// Used when in C++, as a GCC extension.
1894QualType ASTContext::getUnsignedWCharType() const {
1895  // FIXME: derive from "Target" ?
1896  return UnsignedIntTy;
1897}
1898
1899/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
1900/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1901QualType ASTContext::getPointerDiffType() const {
1902  return getFromTargetType(Target.getPtrDiffType(0));
1903}
1904
1905//===----------------------------------------------------------------------===//
1906//                              Type Operators
1907//===----------------------------------------------------------------------===//
1908
1909/// getCanonicalType - Return the canonical (structural) type corresponding to
1910/// the specified potentially non-canonical type.  The non-canonical version
1911/// of a type may have many "decorated" versions of types.  Decorators can
1912/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1913/// to be free of any of these, allowing two canonical types to be compared
1914/// for exact equality with a simple pointer comparison.
1915QualType ASTContext::getCanonicalType(QualType T) {
1916  QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
1917
1918  // If the result has type qualifiers, make sure to canonicalize them as well.
1919  unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
1920  if (TypeQuals == 0) return CanType;
1921
1922  // If the type qualifiers are on an array type, get the canonical type of the
1923  // array with the qualifiers applied to the element type.
1924  ArrayType *AT = dyn_cast<ArrayType>(CanType);
1925  if (!AT)
1926    return CanType.getQualifiedType(TypeQuals);
1927
1928  // Get the canonical version of the element with the extra qualifiers on it.
1929  // This can recursively sink qualifiers through multiple levels of arrays.
1930  QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
1931  NewEltTy = getCanonicalType(NewEltTy);
1932
1933  if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1934    return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
1935                                CAT->getIndexTypeQualifier());
1936  if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
1937    return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
1938                                  IAT->getIndexTypeQualifier());
1939
1940  if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
1941    return getDependentSizedArrayType(NewEltTy,
1942                                      DSAT->getSizeExpr(),
1943                                      DSAT->getSizeModifier(),
1944                                      DSAT->getIndexTypeQualifier(),
1945                                      DSAT->getBracketsRange());
1946
1947  VariableArrayType *VAT = cast<VariableArrayType>(AT);
1948  return getVariableArrayType(NewEltTy,
1949                              VAT->getSizeExpr(),
1950                              VAT->getSizeModifier(),
1951                              VAT->getIndexTypeQualifier(),
1952                              VAT->getBracketsRange());
1953}
1954
1955TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
1956  // If this template name refers to a template, the canonical
1957  // template name merely stores the template itself.
1958  if (TemplateDecl *Template = Name.getAsTemplateDecl())
1959    return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
1960
1961  DependentTemplateName *DTN = Name.getAsDependentTemplateName();
1962  assert(DTN && "Non-dependent template names must refer to template decls.");
1963  return DTN->CanonicalTemplateName;
1964}
1965
1966NestedNameSpecifier *
1967ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
1968  if (!NNS)
1969    return 0;
1970
1971  switch (NNS->getKind()) {
1972  case NestedNameSpecifier::Identifier:
1973    // Canonicalize the prefix but keep the identifier the same.
1974    return NestedNameSpecifier::Create(*this,
1975                         getCanonicalNestedNameSpecifier(NNS->getPrefix()),
1976                                       NNS->getAsIdentifier());
1977
1978  case NestedNameSpecifier::Namespace:
1979    // A namespace is canonical; build a nested-name-specifier with
1980    // this namespace and no prefix.
1981    return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
1982
1983  case NestedNameSpecifier::TypeSpec:
1984  case NestedNameSpecifier::TypeSpecWithTemplate: {
1985    QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
1986    NestedNameSpecifier *Prefix = 0;
1987
1988    // FIXME: This isn't the right check!
1989    if (T->isDependentType())
1990      Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
1991
1992    return NestedNameSpecifier::Create(*this, Prefix,
1993                 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
1994                                       T.getTypePtr());
1995  }
1996
1997  case NestedNameSpecifier::Global:
1998    // The global specifier is canonical and unique.
1999    return NNS;
2000  }
2001
2002  // Required to silence a GCC warning
2003  return 0;
2004}
2005
2006
2007const ArrayType *ASTContext::getAsArrayType(QualType T) {
2008  // Handle the non-qualified case efficiently.
2009  if (T.getCVRQualifiers() == 0) {
2010    // Handle the common positive case fast.
2011    if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2012      return AT;
2013  }
2014
2015  // Handle the common negative case fast, ignoring CVR qualifiers.
2016  QualType CType = T->getCanonicalTypeInternal();
2017
2018  // Make sure to look through type qualifiers (like ExtQuals) for the negative
2019  // test.
2020  if (!isa<ArrayType>(CType) &&
2021      !isa<ArrayType>(CType.getUnqualifiedType()))
2022    return 0;
2023
2024  // Apply any CVR qualifiers from the array type to the element type.  This
2025  // implements C99 6.7.3p8: "If the specification of an array type includes
2026  // any type qualifiers, the element type is so qualified, not the array type."
2027
2028  // If we get here, we either have type qualifiers on the type, or we have
2029  // sugar such as a typedef in the way.  If we have type qualifiers on the type
2030  // we must propagate them down into the elemeng type.
2031  unsigned CVRQuals = T.getCVRQualifiers();
2032  unsigned AddrSpace = 0;
2033  Type *Ty = T.getTypePtr();
2034
2035  // Rip through ExtQualType's and typedefs to get to a concrete type.
2036  while (1) {
2037    if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
2038      AddrSpace = EXTQT->getAddressSpace();
2039      Ty = EXTQT->getBaseType();
2040    } else {
2041      T = Ty->getDesugaredType();
2042      if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
2043        break;
2044      CVRQuals |= T.getCVRQualifiers();
2045      Ty = T.getTypePtr();
2046    }
2047  }
2048
2049  // If we have a simple case, just return now.
2050  const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2051  if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
2052    return ATy;
2053
2054  // Otherwise, we have an array and we have qualifiers on it.  Push the
2055  // qualifiers into the array element type and return a new array type.
2056  // Get the canonical version of the element with the extra qualifiers on it.
2057  // This can recursively sink qualifiers through multiple levels of arrays.
2058  QualType NewEltTy = ATy->getElementType();
2059  if (AddrSpace)
2060    NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
2061  NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
2062
2063  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2064    return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2065                                                CAT->getSizeModifier(),
2066                                                CAT->getIndexTypeQualifier()));
2067  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2068    return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2069                                                  IAT->getSizeModifier(),
2070                                                  IAT->getIndexTypeQualifier()));
2071
2072  if (const DependentSizedArrayType *DSAT
2073        = dyn_cast<DependentSizedArrayType>(ATy))
2074    return cast<ArrayType>(
2075                     getDependentSizedArrayType(NewEltTy,
2076                                                DSAT->getSizeExpr(),
2077                                                DSAT->getSizeModifier(),
2078                                                DSAT->getIndexTypeQualifier(),
2079                                                DSAT->getBracketsRange()));
2080
2081  const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
2082  return cast<ArrayType>(getVariableArrayType(NewEltTy,
2083                                              VAT->getSizeExpr(),
2084                                              VAT->getSizeModifier(),
2085                                              VAT->getIndexTypeQualifier(),
2086                                              VAT->getBracketsRange()));
2087}
2088
2089
2090/// getArrayDecayedType - Return the properly qualified result of decaying the
2091/// specified array type to a pointer.  This operation is non-trivial when
2092/// handling typedefs etc.  The canonical type of "T" must be an array type,
2093/// this returns a pointer to a properly qualified element of the array.
2094///
2095/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2096QualType ASTContext::getArrayDecayedType(QualType Ty) {
2097  // Get the element type with 'getAsArrayType' so that we don't lose any
2098  // typedefs in the element type of the array.  This also handles propagation
2099  // of type qualifiers from the array type into the element type if present
2100  // (C99 6.7.3p8).
2101  const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2102  assert(PrettyArrayType && "Not an array type!");
2103
2104  QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
2105
2106  // int x[restrict 4] ->  int *restrict
2107  return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
2108}
2109
2110QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
2111  QualType ElemTy = VAT->getElementType();
2112
2113  if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
2114    return getBaseElementType(VAT);
2115
2116  return ElemTy;
2117}
2118
2119/// getFloatingRank - Return a relative rank for floating point types.
2120/// This routine will assert if passed a built-in type that isn't a float.
2121static FloatingRank getFloatingRank(QualType T) {
2122  if (const ComplexType *CT = T->getAsComplexType())
2123    return getFloatingRank(CT->getElementType());
2124
2125  assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
2126  switch (T->getAsBuiltinType()->getKind()) {
2127  default: assert(0 && "getFloatingRank(): not a floating type");
2128  case BuiltinType::Float:      return FloatRank;
2129  case BuiltinType::Double:     return DoubleRank;
2130  case BuiltinType::LongDouble: return LongDoubleRank;
2131  }
2132}
2133
2134/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2135/// point or a complex type (based on typeDomain/typeSize).
2136/// 'typeDomain' is a real floating point or complex type.
2137/// 'typeSize' is a real floating point or complex type.
2138QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2139                                                       QualType Domain) const {
2140  FloatingRank EltRank = getFloatingRank(Size);
2141  if (Domain->isComplexType()) {
2142    switch (EltRank) {
2143    default: assert(0 && "getFloatingRank(): illegal value for rank");
2144    case FloatRank:      return FloatComplexTy;
2145    case DoubleRank:     return DoubleComplexTy;
2146    case LongDoubleRank: return LongDoubleComplexTy;
2147    }
2148  }
2149
2150  assert(Domain->isRealFloatingType() && "Unknown domain!");
2151  switch (EltRank) {
2152  default: assert(0 && "getFloatingRank(): illegal value for rank");
2153  case FloatRank:      return FloatTy;
2154  case DoubleRank:     return DoubleTy;
2155  case LongDoubleRank: return LongDoubleTy;
2156  }
2157}
2158
2159/// getFloatingTypeOrder - Compare the rank of the two specified floating
2160/// point types, ignoring the domain of the type (i.e. 'double' ==
2161/// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
2162/// LHS < RHS, return -1.
2163int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2164  FloatingRank LHSR = getFloatingRank(LHS);
2165  FloatingRank RHSR = getFloatingRank(RHS);
2166
2167  if (LHSR == RHSR)
2168    return 0;
2169  if (LHSR > RHSR)
2170    return 1;
2171  return -1;
2172}
2173
2174/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2175/// routine will assert if passed a built-in type that isn't an integer or enum,
2176/// or if it is not canonicalized.
2177unsigned ASTContext::getIntegerRank(Type *T) {
2178  assert(T->isCanonical() && "T should be canonicalized");
2179  if (EnumType* ET = dyn_cast<EnumType>(T))
2180    T = ET->getDecl()->getIntegerType().getTypePtr();
2181
2182  if (T->isSpecificBuiltinType(BuiltinType::WChar))
2183    T = getFromTargetType(Target.getWCharType()).getTypePtr();
2184
2185  if (T->isSpecificBuiltinType(BuiltinType::Char16))
2186    T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2187
2188  if (T->isSpecificBuiltinType(BuiltinType::Char32))
2189    T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2190
2191  // There are two things which impact the integer rank: the width, and
2192  // the ordering of builtins.  The builtin ordering is encoded in the
2193  // bottom three bits; the width is encoded in the bits above that.
2194  if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
2195    return FWIT->getWidth() << 3;
2196
2197  switch (cast<BuiltinType>(T)->getKind()) {
2198  default: assert(0 && "getIntegerRank(): not a built-in integer");
2199  case BuiltinType::Bool:
2200    return 1 + (getIntWidth(BoolTy) << 3);
2201  case BuiltinType::Char_S:
2202  case BuiltinType::Char_U:
2203  case BuiltinType::SChar:
2204  case BuiltinType::UChar:
2205    return 2 + (getIntWidth(CharTy) << 3);
2206  case BuiltinType::Short:
2207  case BuiltinType::UShort:
2208    return 3 + (getIntWidth(ShortTy) << 3);
2209  case BuiltinType::Int:
2210  case BuiltinType::UInt:
2211    return 4 + (getIntWidth(IntTy) << 3);
2212  case BuiltinType::Long:
2213  case BuiltinType::ULong:
2214    return 5 + (getIntWidth(LongTy) << 3);
2215  case BuiltinType::LongLong:
2216  case BuiltinType::ULongLong:
2217    return 6 + (getIntWidth(LongLongTy) << 3);
2218  case BuiltinType::Int128:
2219  case BuiltinType::UInt128:
2220    return 7 + (getIntWidth(Int128Ty) << 3);
2221  }
2222}
2223
2224/// getIntegerTypeOrder - Returns the highest ranked integer type:
2225/// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
2226/// LHS < RHS, return -1.
2227int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
2228  Type *LHSC = getCanonicalType(LHS).getTypePtr();
2229  Type *RHSC = getCanonicalType(RHS).getTypePtr();
2230  if (LHSC == RHSC) return 0;
2231
2232  bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2233  bool RHSUnsigned = RHSC->isUnsignedIntegerType();
2234
2235  unsigned LHSRank = getIntegerRank(LHSC);
2236  unsigned RHSRank = getIntegerRank(RHSC);
2237
2238  if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
2239    if (LHSRank == RHSRank) return 0;
2240    return LHSRank > RHSRank ? 1 : -1;
2241  }
2242
2243  // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2244  if (LHSUnsigned) {
2245    // If the unsigned [LHS] type is larger, return it.
2246    if (LHSRank >= RHSRank)
2247      return 1;
2248
2249    // If the signed type can represent all values of the unsigned type, it
2250    // wins.  Because we are dealing with 2's complement and types that are
2251    // powers of two larger than each other, this is always safe.
2252    return -1;
2253  }
2254
2255  // If the unsigned [RHS] type is larger, return it.
2256  if (RHSRank >= LHSRank)
2257    return -1;
2258
2259  // If the signed type can represent all values of the unsigned type, it
2260  // wins.  Because we are dealing with 2's complement and types that are
2261  // powers of two larger than each other, this is always safe.
2262  return 1;
2263}
2264
2265// getCFConstantStringType - Return the type used for constant CFStrings.
2266QualType ASTContext::getCFConstantStringType() {
2267  if (!CFConstantStringTypeDecl) {
2268    CFConstantStringTypeDecl =
2269      RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2270                         &Idents.get("NSConstantString"));
2271    QualType FieldTypes[4];
2272
2273    // const int *isa;
2274    FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
2275    // int flags;
2276    FieldTypes[1] = IntTy;
2277    // const char *str;
2278    FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
2279    // long length;
2280    FieldTypes[3] = LongTy;
2281
2282    // Create fields
2283    for (unsigned i = 0; i < 4; ++i) {
2284      FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2285                                           SourceLocation(), 0,
2286                                           FieldTypes[i], /*BitWidth=*/0,
2287                                           /*Mutable=*/false);
2288      CFConstantStringTypeDecl->addDecl(Field);
2289    }
2290
2291    CFConstantStringTypeDecl->completeDefinition(*this);
2292  }
2293
2294  return getTagDeclType(CFConstantStringTypeDecl);
2295}
2296
2297void ASTContext::setCFConstantStringType(QualType T) {
2298  const RecordType *Rec = T->getAsRecordType();
2299  assert(Rec && "Invalid CFConstantStringType");
2300  CFConstantStringTypeDecl = Rec->getDecl();
2301}
2302
2303QualType ASTContext::getObjCFastEnumerationStateType()
2304{
2305  if (!ObjCFastEnumerationStateTypeDecl) {
2306    ObjCFastEnumerationStateTypeDecl =
2307      RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2308                         &Idents.get("__objcFastEnumerationState"));
2309
2310    QualType FieldTypes[] = {
2311      UnsignedLongTy,
2312      getPointerType(ObjCIdTypedefType),
2313      getPointerType(UnsignedLongTy),
2314      getConstantArrayType(UnsignedLongTy,
2315                           llvm::APInt(32, 5), ArrayType::Normal, 0)
2316    };
2317
2318    for (size_t i = 0; i < 4; ++i) {
2319      FieldDecl *Field = FieldDecl::Create(*this,
2320                                           ObjCFastEnumerationStateTypeDecl,
2321                                           SourceLocation(), 0,
2322                                           FieldTypes[i], /*BitWidth=*/0,
2323                                           /*Mutable=*/false);
2324      ObjCFastEnumerationStateTypeDecl->addDecl(Field);
2325    }
2326
2327    ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
2328  }
2329
2330  return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2331}
2332
2333void ASTContext::setObjCFastEnumerationStateType(QualType T) {
2334  const RecordType *Rec = T->getAsRecordType();
2335  assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2336  ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2337}
2338
2339// This returns true if a type has been typedefed to BOOL:
2340// typedef <type> BOOL;
2341static bool isTypeTypedefedAsBOOL(QualType T) {
2342  if (const TypedefType *TT = dyn_cast<TypedefType>(T))
2343    if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2344      return II->isStr("BOOL");
2345
2346  return false;
2347}
2348
2349/// getObjCEncodingTypeSize returns size of type for objective-c encoding
2350/// purpose.
2351int ASTContext::getObjCEncodingTypeSize(QualType type) {
2352  uint64_t sz = getTypeSize(type);
2353
2354  // Make all integer and enum types at least as large as an int
2355  if (sz > 0 && type->isIntegralType())
2356    sz = std::max(sz, getTypeSize(IntTy));
2357  // Treat arrays as pointers, since that's how they're passed in.
2358  else if (type->isArrayType())
2359    sz = getTypeSize(VoidPtrTy);
2360  return sz / getTypeSize(CharTy);
2361}
2362
2363/// getObjCEncodingForMethodDecl - Return the encoded type for this method
2364/// declaration.
2365void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
2366                                              std::string& S) {
2367  // FIXME: This is not very efficient.
2368  // Encode type qualifer, 'in', 'inout', etc. for the return type.
2369  getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
2370  // Encode result type.
2371  getObjCEncodingForType(Decl->getResultType(), S);
2372  // Compute size of all parameters.
2373  // Start with computing size of a pointer in number of bytes.
2374  // FIXME: There might(should) be a better way of doing this computation!
2375  SourceLocation Loc;
2376  int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
2377  // The first two arguments (self and _cmd) are pointers; account for
2378  // their size.
2379  int ParmOffset = 2 * PtrSize;
2380  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2381       E = Decl->param_end(); PI != E; ++PI) {
2382    QualType PType = (*PI)->getType();
2383    int sz = getObjCEncodingTypeSize(PType);
2384    assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
2385    ParmOffset += sz;
2386  }
2387  S += llvm::utostr(ParmOffset);
2388  S += "@0:";
2389  S += llvm::utostr(PtrSize);
2390
2391  // Argument types.
2392  ParmOffset = 2 * PtrSize;
2393  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2394       E = Decl->param_end(); PI != E; ++PI) {
2395    ParmVarDecl *PVDecl = *PI;
2396    QualType PType = PVDecl->getOriginalType();
2397    if (const ArrayType *AT =
2398          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2399      // Use array's original type only if it has known number of
2400      // elements.
2401      if (!isa<ConstantArrayType>(AT))
2402        PType = PVDecl->getType();
2403    } else if (PType->isFunctionType())
2404      PType = PVDecl->getType();
2405    // Process argument qualifiers for user supplied arguments; such as,
2406    // 'in', 'inout', etc.
2407    getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
2408    getObjCEncodingForType(PType, S);
2409    S += llvm::utostr(ParmOffset);
2410    ParmOffset += getObjCEncodingTypeSize(PType);
2411  }
2412}
2413
2414/// getObjCEncodingForPropertyDecl - Return the encoded type for this
2415/// property declaration. If non-NULL, Container must be either an
2416/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2417/// NULL when getting encodings for protocol properties.
2418/// Property attributes are stored as a comma-delimited C string. The simple
2419/// attributes readonly and bycopy are encoded as single characters. The
2420/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2421/// encoded as single characters, followed by an identifier. Property types
2422/// are also encoded as a parametrized attribute. The characters used to encode
2423/// these attributes are defined by the following enumeration:
2424/// @code
2425/// enum PropertyAttributes {
2426/// kPropertyReadOnly = 'R',   // property is read-only.
2427/// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
2428/// kPropertyByref = '&',  // property is a reference to the value last assigned
2429/// kPropertyDynamic = 'D',    // property is dynamic
2430/// kPropertyGetter = 'G',     // followed by getter selector name
2431/// kPropertySetter = 'S',     // followed by setter selector name
2432/// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
2433/// kPropertyType = 't'              // followed by old-style type encoding.
2434/// kPropertyWeak = 'W'              // 'weak' property
2435/// kPropertyStrong = 'P'            // property GC'able
2436/// kPropertyNonAtomic = 'N'         // property non-atomic
2437/// };
2438/// @endcode
2439void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2440                                                const Decl *Container,
2441                                                std::string& S) {
2442  // Collect information from the property implementation decl(s).
2443  bool Dynamic = false;
2444  ObjCPropertyImplDecl *SynthesizePID = 0;
2445
2446  // FIXME: Duplicated code due to poor abstraction.
2447  if (Container) {
2448    if (const ObjCCategoryImplDecl *CID =
2449        dyn_cast<ObjCCategoryImplDecl>(Container)) {
2450      for (ObjCCategoryImplDecl::propimpl_iterator
2451             i = CID->propimpl_begin(), e = CID->propimpl_end();
2452           i != e; ++i) {
2453        ObjCPropertyImplDecl *PID = *i;
2454        if (PID->getPropertyDecl() == PD) {
2455          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2456            Dynamic = true;
2457          } else {
2458            SynthesizePID = PID;
2459          }
2460        }
2461      }
2462    } else {
2463      const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
2464      for (ObjCCategoryImplDecl::propimpl_iterator
2465             i = OID->propimpl_begin(), e = OID->propimpl_end();
2466           i != e; ++i) {
2467        ObjCPropertyImplDecl *PID = *i;
2468        if (PID->getPropertyDecl() == PD) {
2469          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2470            Dynamic = true;
2471          } else {
2472            SynthesizePID = PID;
2473          }
2474        }
2475      }
2476    }
2477  }
2478
2479  // FIXME: This is not very efficient.
2480  S = "T";
2481
2482  // Encode result type.
2483  // GCC has some special rules regarding encoding of properties which
2484  // closely resembles encoding of ivars.
2485  getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
2486                             true /* outermost type */,
2487                             true /* encoding for property */);
2488
2489  if (PD->isReadOnly()) {
2490    S += ",R";
2491  } else {
2492    switch (PD->getSetterKind()) {
2493    case ObjCPropertyDecl::Assign: break;
2494    case ObjCPropertyDecl::Copy:   S += ",C"; break;
2495    case ObjCPropertyDecl::Retain: S += ",&"; break;
2496    }
2497  }
2498
2499  // It really isn't clear at all what this means, since properties
2500  // are "dynamic by default".
2501  if (Dynamic)
2502    S += ",D";
2503
2504  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2505    S += ",N";
2506
2507  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2508    S += ",G";
2509    S += PD->getGetterName().getAsString();
2510  }
2511
2512  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2513    S += ",S";
2514    S += PD->getSetterName().getAsString();
2515  }
2516
2517  if (SynthesizePID) {
2518    const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2519    S += ",V";
2520    S += OID->getNameAsString();
2521  }
2522
2523  // FIXME: OBJCGC: weak & strong
2524}
2525
2526/// getLegacyIntegralTypeEncoding -
2527/// Another legacy compatibility encoding: 32-bit longs are encoded as
2528/// 'l' or 'L' , but not always.  For typedefs, we need to use
2529/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2530///
2531void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
2532  if (isa<TypedefType>(PointeeTy.getTypePtr())) {
2533    if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
2534      if (BT->getKind() == BuiltinType::ULong &&
2535          ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
2536        PointeeTy = UnsignedIntTy;
2537      else
2538        if (BT->getKind() == BuiltinType::Long &&
2539            ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
2540          PointeeTy = IntTy;
2541    }
2542  }
2543}
2544
2545void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
2546                                        const FieldDecl *Field) {
2547  // We follow the behavior of gcc, expanding structures which are
2548  // directly pointed to, and expanding embedded structures. Note that
2549  // these rules are sufficient to prevent recursive encoding of the
2550  // same type.
2551  getObjCEncodingForTypeImpl(T, S, true, true, Field,
2552                             true /* outermost type */);
2553}
2554
2555static void EncodeBitField(const ASTContext *Context, std::string& S,
2556                           const FieldDecl *FD) {
2557  const Expr *E = FD->getBitWidth();
2558  assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2559  ASTContext *Ctx = const_cast<ASTContext*>(Context);
2560  unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
2561  S += 'b';
2562  S += llvm::utostr(N);
2563}
2564
2565void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2566                                            bool ExpandPointedToStructures,
2567                                            bool ExpandStructures,
2568                                            const FieldDecl *FD,
2569                                            bool OutermostType,
2570                                            bool EncodingProperty) {
2571  if (const BuiltinType *BT = T->getAsBuiltinType()) {
2572    if (FD && FD->isBitField())
2573      return EncodeBitField(this, S, FD);
2574    char encoding;
2575    switch (BT->getKind()) {
2576    default: assert(0 && "Unhandled builtin type kind");
2577    case BuiltinType::Void:       encoding = 'v'; break;
2578    case BuiltinType::Bool:       encoding = 'B'; break;
2579    case BuiltinType::Char_U:
2580    case BuiltinType::UChar:      encoding = 'C'; break;
2581    case BuiltinType::UShort:     encoding = 'S'; break;
2582    case BuiltinType::UInt:       encoding = 'I'; break;
2583    case BuiltinType::ULong:
2584        encoding =
2585          (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
2586        break;
2587    case BuiltinType::UInt128:    encoding = 'T'; break;
2588    case BuiltinType::ULongLong:  encoding = 'Q'; break;
2589    case BuiltinType::Char_S:
2590    case BuiltinType::SChar:      encoding = 'c'; break;
2591    case BuiltinType::Short:      encoding = 's'; break;
2592    case BuiltinType::Int:        encoding = 'i'; break;
2593    case BuiltinType::Long:
2594      encoding =
2595        (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2596      break;
2597    case BuiltinType::LongLong:   encoding = 'q'; break;
2598    case BuiltinType::Int128:     encoding = 't'; break;
2599    case BuiltinType::Float:      encoding = 'f'; break;
2600    case BuiltinType::Double:     encoding = 'd'; break;
2601    case BuiltinType::LongDouble: encoding = 'd'; break;
2602    }
2603
2604    S += encoding;
2605    return;
2606  }
2607
2608  if (const ComplexType *CT = T->getAsComplexType()) {
2609    S += 'j';
2610    getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2611                               false);
2612    return;
2613  }
2614
2615  if (const PointerType *PT = T->getAsPointerType()) {
2616    QualType PointeeTy = PT->getPointeeType();
2617    bool isReadOnly = false;
2618    // For historical/compatibility reasons, the read-only qualifier of the
2619    // pointee gets emitted _before_ the '^'.  The read-only qualifier of
2620    // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2621    // Also, do not emit the 'r' for anything but the outermost type!
2622    if (isa<TypedefType>(T.getTypePtr())) {
2623      if (OutermostType && T.isConstQualified()) {
2624        isReadOnly = true;
2625        S += 'r';
2626      }
2627    }
2628    else if (OutermostType) {
2629      QualType P = PointeeTy;
2630      while (P->getAsPointerType())
2631        P = P->getAsPointerType()->getPointeeType();
2632      if (P.isConstQualified()) {
2633        isReadOnly = true;
2634        S += 'r';
2635      }
2636    }
2637    if (isReadOnly) {
2638      // Another legacy compatibility encoding. Some ObjC qualifier and type
2639      // combinations need to be rearranged.
2640      // Rewrite "in const" from "nr" to "rn"
2641      const char * s = S.c_str();
2642      int len = S.length();
2643      if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2644        std::string replace = "rn";
2645        S.replace(S.end()-2, S.end(), replace);
2646      }
2647    }
2648    if (isObjCSelType(PointeeTy)) {
2649      S += ':';
2650      return;
2651    }
2652
2653    if (PointeeTy->isCharType()) {
2654      // char pointer types should be encoded as '*' unless it is a
2655      // type that has been typedef'd to 'BOOL'.
2656      if (!isTypeTypedefedAsBOOL(PointeeTy)) {
2657        S += '*';
2658        return;
2659      }
2660    } else if (const RecordType *RTy = PointeeTy->getAsRecordType()) {
2661      // GCC binary compat: Need to convert "struct objc_class *" to "#".
2662      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
2663        S += '#';
2664        return;
2665      }
2666      // GCC binary compat: Need to convert "struct objc_object *" to "@".
2667      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
2668        S += '@';
2669        return;
2670      }
2671      // fall through...
2672    }
2673    S += '^';
2674    getLegacyIntegralTypeEncoding(PointeeTy);
2675
2676    getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
2677                               NULL);
2678    return;
2679  }
2680
2681  if (const ArrayType *AT =
2682      // Ignore type qualifiers etc.
2683        dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
2684    if (isa<IncompleteArrayType>(AT)) {
2685      // Incomplete arrays are encoded as a pointer to the array element.
2686      S += '^';
2687
2688      getObjCEncodingForTypeImpl(AT->getElementType(), S,
2689                                 false, ExpandStructures, FD);
2690    } else {
2691      S += '[';
2692
2693      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2694        S += llvm::utostr(CAT->getSize().getZExtValue());
2695      else {
2696        //Variable length arrays are encoded as a regular array with 0 elements.
2697        assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2698        S += '0';
2699      }
2700
2701      getObjCEncodingForTypeImpl(AT->getElementType(), S,
2702                                 false, ExpandStructures, FD);
2703      S += ']';
2704    }
2705    return;
2706  }
2707
2708  if (T->getAsFunctionType()) {
2709    S += '?';
2710    return;
2711  }
2712
2713  if (const RecordType *RTy = T->getAsRecordType()) {
2714    RecordDecl *RDecl = RTy->getDecl();
2715    S += RDecl->isUnion() ? '(' : '{';
2716    // Anonymous structures print as '?'
2717    if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2718      S += II->getName();
2719    } else {
2720      S += '?';
2721    }
2722    if (ExpandStructures) {
2723      S += '=';
2724      for (RecordDecl::field_iterator Field = RDecl->field_begin(),
2725                                   FieldEnd = RDecl->field_end();
2726           Field != FieldEnd; ++Field) {
2727        if (FD) {
2728          S += '"';
2729          S += Field->getNameAsString();
2730          S += '"';
2731        }
2732
2733        // Special case bit-fields.
2734        if (Field->isBitField()) {
2735          getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2736                                     (*Field));
2737        } else {
2738          QualType qt = Field->getType();
2739          getLegacyIntegralTypeEncoding(qt);
2740          getObjCEncodingForTypeImpl(qt, S, false, true,
2741                                     FD);
2742        }
2743      }
2744    }
2745    S += RDecl->isUnion() ? ')' : '}';
2746    return;
2747  }
2748
2749  if (T->isEnumeralType()) {
2750    if (FD && FD->isBitField())
2751      EncodeBitField(this, S, FD);
2752    else
2753      S += 'i';
2754    return;
2755  }
2756
2757  if (T->isBlockPointerType()) {
2758    S += "@?"; // Unlike a pointer-to-function, which is "^?".
2759    return;
2760  }
2761
2762  if (T->isObjCInterfaceType()) {
2763    // @encode(class_name)
2764    ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2765    S += '{';
2766    const IdentifierInfo *II = OI->getIdentifier();
2767    S += II->getName();
2768    S += '=';
2769    llvm::SmallVector<FieldDecl*, 32> RecFields;
2770    CollectObjCIvars(OI, RecFields);
2771    for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
2772      if (RecFields[i]->isBitField())
2773        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2774                                   RecFields[i]);
2775      else
2776        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2777                                   FD);
2778    }
2779    S += '}';
2780    return;
2781  }
2782
2783  if (const ObjCObjectPointerType *OPT = T->getAsObjCObjectPointerType()) {
2784    if (OPT->isObjCIdType()) {
2785      S += '@';
2786      return;
2787    }
2788
2789    if (OPT->isObjCClassType()) {
2790      S += '#';
2791      return;
2792    }
2793
2794    if (OPT->isObjCQualifiedIdType()) {
2795      getObjCEncodingForTypeImpl(getObjCIdType(), S,
2796                                 ExpandPointedToStructures,
2797                                 ExpandStructures, FD);
2798      if (FD || EncodingProperty) {
2799        // Note that we do extended encoding of protocol qualifer list
2800        // Only when doing ivar or property encoding.
2801        S += '"';
2802        for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2803             E = OPT->qual_end(); I != E; ++I) {
2804          S += '<';
2805          S += (*I)->getNameAsString();
2806          S += '>';
2807        }
2808        S += '"';
2809      }
2810      return;
2811    }
2812
2813    QualType PointeeTy = OPT->getPointeeType();
2814    if (!EncodingProperty &&
2815        isa<TypedefType>(PointeeTy.getTypePtr())) {
2816      // Another historical/compatibility reason.
2817      // We encode the underlying type which comes out as
2818      // {...};
2819      S += '^';
2820      getObjCEncodingForTypeImpl(PointeeTy, S,
2821                                 false, ExpandPointedToStructures,
2822                                 NULL);
2823      return;
2824    }
2825
2826    S += '@';
2827    if (FD || EncodingProperty) {
2828      S += '"';
2829      S += OPT->getInterfaceDecl()->getNameAsCString();
2830      for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2831           E = OPT->qual_end(); I != E; ++I) {
2832        S += '<';
2833        S += (*I)->getNameAsString();
2834        S += '>';
2835      }
2836      S += '"';
2837    }
2838    return;
2839  }
2840
2841  assert(0 && "@encode for type not implemented!");
2842}
2843
2844void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
2845                                                 std::string& S) const {
2846  if (QT & Decl::OBJC_TQ_In)
2847    S += 'n';
2848  if (QT & Decl::OBJC_TQ_Inout)
2849    S += 'N';
2850  if (QT & Decl::OBJC_TQ_Out)
2851    S += 'o';
2852  if (QT & Decl::OBJC_TQ_Bycopy)
2853    S += 'O';
2854  if (QT & Decl::OBJC_TQ_Byref)
2855    S += 'R';
2856  if (QT & Decl::OBJC_TQ_Oneway)
2857    S += 'V';
2858}
2859
2860void ASTContext::setBuiltinVaListType(QualType T) {
2861  assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
2862
2863  BuiltinVaListType = T;
2864}
2865
2866void ASTContext::setObjCIdType(QualType T) {
2867  ObjCIdTypedefType = T;
2868}
2869
2870void ASTContext::setObjCSelType(QualType T) {
2871  ObjCSelType = T;
2872
2873  const TypedefType *TT = T->getAsTypedefType();
2874  if (!TT)
2875    return;
2876  TypedefDecl *TD = TT->getDecl();
2877
2878  // typedef struct objc_selector *SEL;
2879  const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
2880  if (!ptr)
2881    return;
2882  const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
2883  if (!rec)
2884    return;
2885  SelStructType = rec;
2886}
2887
2888void ASTContext::setObjCProtoType(QualType QT) {
2889  ObjCProtoType = QT;
2890}
2891
2892void ASTContext::setObjCClassType(QualType T) {
2893  ObjCClassTypedefType = T;
2894}
2895
2896void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
2897  assert(ObjCConstantStringType.isNull() &&
2898         "'NSConstantString' type already set!");
2899
2900  ObjCConstantStringType = getObjCInterfaceType(Decl);
2901}
2902
2903/// \brief Retrieve the template name that represents a qualified
2904/// template name such as \c std::vector.
2905TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
2906                                                  bool TemplateKeyword,
2907                                                  TemplateDecl *Template) {
2908  llvm::FoldingSetNodeID ID;
2909  QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
2910
2911  void *InsertPos = 0;
2912  QualifiedTemplateName *QTN =
2913    QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2914  if (!QTN) {
2915    QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
2916    QualifiedTemplateNames.InsertNode(QTN, InsertPos);
2917  }
2918
2919  return TemplateName(QTN);
2920}
2921
2922/// \brief Retrieve the template name that represents a dependent
2923/// template name such as \c MetaFun::template apply.
2924TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
2925                                                  const IdentifierInfo *Name) {
2926  assert(NNS->isDependent() && "Nested name specifier must be dependent");
2927
2928  llvm::FoldingSetNodeID ID;
2929  DependentTemplateName::Profile(ID, NNS, Name);
2930
2931  void *InsertPos = 0;
2932  DependentTemplateName *QTN =
2933    DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2934
2935  if (QTN)
2936    return TemplateName(QTN);
2937
2938  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2939  if (CanonNNS == NNS) {
2940    QTN = new (*this,4) DependentTemplateName(NNS, Name);
2941  } else {
2942    TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
2943    QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
2944  }
2945
2946  DependentTemplateNames.InsertNode(QTN, InsertPos);
2947  return TemplateName(QTN);
2948}
2949
2950/// getFromTargetType - Given one of the integer types provided by
2951/// TargetInfo, produce the corresponding type. The unsigned @p Type
2952/// is actually a value of type @c TargetInfo::IntType.
2953QualType ASTContext::getFromTargetType(unsigned Type) const {
2954  switch (Type) {
2955  case TargetInfo::NoInt: return QualType();
2956  case TargetInfo::SignedShort: return ShortTy;
2957  case TargetInfo::UnsignedShort: return UnsignedShortTy;
2958  case TargetInfo::SignedInt: return IntTy;
2959  case TargetInfo::UnsignedInt: return UnsignedIntTy;
2960  case TargetInfo::SignedLong: return LongTy;
2961  case TargetInfo::UnsignedLong: return UnsignedLongTy;
2962  case TargetInfo::SignedLongLong: return LongLongTy;
2963  case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
2964  }
2965
2966  assert(false && "Unhandled TargetInfo::IntType value");
2967  return QualType();
2968}
2969
2970//===----------------------------------------------------------------------===//
2971//                        Type Predicates.
2972//===----------------------------------------------------------------------===//
2973
2974/// isObjCNSObjectType - Return true if this is an NSObject object using
2975/// NSObject attribute on a c-style pointer type.
2976/// FIXME - Make it work directly on types.
2977/// FIXME: Move to Type.
2978///
2979bool ASTContext::isObjCNSObjectType(QualType Ty) const {
2980  if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2981    if (TypedefDecl *TD = TDT->getDecl())
2982      if (TD->getAttr<ObjCNSObjectAttr>())
2983        return true;
2984  }
2985  return false;
2986}
2987
2988/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
2989/// garbage collection attribute.
2990///
2991QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
2992  QualType::GCAttrTypes GCAttrs = QualType::GCNone;
2993  if (getLangOptions().ObjC1 &&
2994      getLangOptions().getGCMode() != LangOptions::NonGC) {
2995    GCAttrs = Ty.getObjCGCAttr();
2996    // Default behavious under objective-c's gc is for objective-c pointers
2997    // (or pointers to them) be treated as though they were declared
2998    // as __strong.
2999    if (GCAttrs == QualType::GCNone) {
3000      if (Ty->isObjCObjectPointerType())
3001        GCAttrs = QualType::Strong;
3002      else if (Ty->isPointerType())
3003        return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType());
3004    }
3005    // Non-pointers have none gc'able attribute regardless of the attribute
3006    // set on them.
3007    else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
3008      return QualType::GCNone;
3009  }
3010  return GCAttrs;
3011}
3012
3013//===----------------------------------------------------------------------===//
3014//                        Type Compatibility Testing
3015//===----------------------------------------------------------------------===//
3016
3017/// areCompatVectorTypes - Return true if the two specified vector types are
3018/// compatible.
3019static bool areCompatVectorTypes(const VectorType *LHS,
3020                                 const VectorType *RHS) {
3021  assert(LHS->isCanonical() && RHS->isCanonical());
3022  return LHS->getElementType() == RHS->getElementType() &&
3023         LHS->getNumElements() == RHS->getNumElements();
3024}
3025
3026//===----------------------------------------------------------------------===//
3027// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3028//===----------------------------------------------------------------------===//
3029
3030/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3031/// inheritance hierarchy of 'rProto'.
3032static bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3033                                           ObjCProtocolDecl *rProto) {
3034  if (lProto == rProto)
3035    return true;
3036  for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3037       E = rProto->protocol_end(); PI != E; ++PI)
3038    if (ProtocolCompatibleWithProtocol(lProto, *PI))
3039      return true;
3040  return false;
3041}
3042
3043/// ClassImplementsProtocol - Checks that 'lProto' protocol
3044/// has been implemented in IDecl class, its super class or categories (if
3045/// lookupCategory is true).
3046static bool ClassImplementsProtocol(ObjCProtocolDecl *lProto,
3047                                    ObjCInterfaceDecl *IDecl,
3048                                    bool lookupCategory,
3049                                    bool RHSIsQualifiedID = false) {
3050
3051  // 1st, look up the class.
3052  const ObjCList<ObjCProtocolDecl> &Protocols =
3053    IDecl->getReferencedProtocols();
3054
3055  for (ObjCList<ObjCProtocolDecl>::iterator PI = Protocols.begin(),
3056       E = Protocols.end(); PI != E; ++PI) {
3057    if (ProtocolCompatibleWithProtocol(lProto, *PI))
3058      return true;
3059    // This is dubious and is added to be compatible with gcc.  In gcc, it is
3060    // also allowed assigning a protocol-qualified 'id' type to a LHS object
3061    // when protocol in qualified LHS is in list of protocols in the rhs 'id'
3062    // object. This IMO, should be a bug.
3063    // FIXME: Treat this as an extension, and flag this as an error when GCC
3064    // extensions are not enabled.
3065    if (RHSIsQualifiedID && ProtocolCompatibleWithProtocol(*PI, lProto))
3066      return true;
3067  }
3068
3069  // 2nd, look up the category.
3070  if (lookupCategory)
3071    for (ObjCCategoryDecl *CDecl = IDecl->getCategoryList(); CDecl;
3072         CDecl = CDecl->getNextClassCategory()) {
3073      for (ObjCCategoryDecl::protocol_iterator PI = CDecl->protocol_begin(),
3074           E = CDecl->protocol_end(); PI != E; ++PI)
3075        if (ProtocolCompatibleWithProtocol(lProto, *PI))
3076          return true;
3077    }
3078
3079  // 3rd, look up the super class(s)
3080  if (IDecl->getSuperClass())
3081    return
3082      ClassImplementsProtocol(lProto, IDecl->getSuperClass(), lookupCategory,
3083                              RHSIsQualifiedID);
3084
3085  return false;
3086}
3087
3088/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3089/// return true if lhs's protocols conform to rhs's protocol; false
3090/// otherwise.
3091bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3092  if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3093    return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3094  return false;
3095}
3096
3097/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3098/// ObjCQualifiedIDType.
3099bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3100                                                   bool compare) {
3101  // Allow id<P..> and an 'id' or void* type in all cases.
3102  if (lhs->isVoidPointerType() ||
3103      lhs->isObjCIdType() || lhs->isObjCClassType())
3104    return true;
3105  else if (rhs->isVoidPointerType() ||
3106           rhs->isObjCIdType() || rhs->isObjCClassType())
3107    return true;
3108
3109  if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
3110    const ObjCObjectPointerType *rhsOPT = rhs->getAsObjCObjectPointerType();
3111
3112    if (!rhsOPT) return false;
3113
3114    if (rhsOPT->qual_empty()) {
3115      // If the RHS is a unqualified interface pointer "NSString*",
3116      // make sure we check the class hierarchy.
3117      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3118        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3119             E = lhsQID->qual_end(); I != E; ++I) {
3120          // when comparing an id<P> on lhs with a static type on rhs,
3121          // see if static class implements all of id's protocols, directly or
3122          // through its super class and categories.
3123          if (!ClassImplementsProtocol(*I, rhsID, true))
3124            return false;
3125        }
3126      }
3127      // If there are no qualifiers and no interface, we have an 'id'.
3128      return true;
3129    }
3130    // Both the right and left sides have qualifiers.
3131    for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3132         E = lhsQID->qual_end(); I != E; ++I) {
3133      ObjCProtocolDecl *lhsProto = *I;
3134      bool match = false;
3135
3136      // when comparing an id<P> on lhs with a static type on rhs,
3137      // see if static class implements all of id's protocols, directly or
3138      // through its super class and categories.
3139      for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
3140           E = rhsOPT->qual_end(); J != E; ++J) {
3141        ObjCProtocolDecl *rhsProto = *J;
3142        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3143            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3144          match = true;
3145          break;
3146        }
3147      }
3148      // If the RHS is a qualified interface pointer "NSString<P>*",
3149      // make sure we check the class hierarchy.
3150      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3151        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3152             E = lhsQID->qual_end(); I != E; ++I) {
3153          // when comparing an id<P> on lhs with a static type on rhs,
3154          // see if static class implements all of id's protocols, directly or
3155          // through its super class and categories.
3156          if (ClassImplementsProtocol(*I, rhsID, true)) {
3157            match = true;
3158            break;
3159          }
3160        }
3161      }
3162      if (!match)
3163        return false;
3164    }
3165
3166    return true;
3167  }
3168
3169  const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
3170  assert(rhsQID && "One of the LHS/RHS should be id<x>");
3171
3172  if (const ObjCObjectPointerType *lhsOPT =
3173        lhs->getAsObjCInterfacePointerType()) {
3174    if (lhsOPT->qual_empty()) {
3175      bool match = false;
3176      if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
3177        for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
3178             E = rhsQID->qual_end(); I != E; ++I) {
3179          // when comparing an id<P> on lhs with a static type on rhs,
3180          // see if static class implements all of id's protocols, directly or
3181          // through its super class and categories.
3182          if (ClassImplementsProtocol(*I, lhsID, true)) {
3183            match = true;
3184            break;
3185          }
3186        }
3187        if (!match)
3188          return false;
3189      }
3190      return true;
3191    }
3192    // Both the right and left sides have qualifiers.
3193    for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
3194         E = lhsOPT->qual_end(); I != E; ++I) {
3195      ObjCProtocolDecl *lhsProto = *I;
3196      bool match = false;
3197
3198      // when comparing an id<P> on lhs with a static type on rhs,
3199      // see if static class implements all of id's protocols, directly or
3200      // through its super class and categories.
3201      for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
3202           E = rhsQID->qual_end(); J != E; ++J) {
3203        ObjCProtocolDecl *rhsProto = *J;
3204        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3205            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3206          match = true;
3207          break;
3208        }
3209      }
3210      if (!match)
3211        return false;
3212    }
3213    return true;
3214  }
3215  return false;
3216}
3217
3218/// canAssignObjCInterfaces - Return true if the two interface types are
3219/// compatible for assignment from RHS to LHS.  This handles validation of any
3220/// protocol qualifiers on the LHS or RHS.
3221///
3222bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
3223                                         const ObjCObjectPointerType *RHSOPT) {
3224  // If either type represents the built-in 'id' or 'Class' types, return true.
3225  if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
3226    return true;
3227
3228  if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
3229    return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
3230                                             QualType(RHSOPT,0),
3231                                             false);
3232
3233  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
3234  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
3235  if (LHS && RHS) // We have 2 user-defined types.
3236    return canAssignObjCInterfaces(LHS, RHS);
3237
3238  return false;
3239}
3240
3241bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
3242                                         const ObjCInterfaceType *RHS) {
3243  // Verify that the base decls are compatible: the RHS must be a subclass of
3244  // the LHS.
3245  if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
3246    return false;
3247
3248  // RHS must have a superset of the protocols in the LHS.  If the LHS is not
3249  // protocol qualified at all, then we are good.
3250  if (LHS->getNumProtocols() == 0)
3251    return true;
3252
3253  // Okay, we know the LHS has protocol qualifiers.  If the RHS doesn't, then it
3254  // isn't a superset.
3255  if (RHS->getNumProtocols() == 0)
3256    return true;  // FIXME: should return false!
3257
3258  for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
3259                                        LHSPE = LHS->qual_end();
3260       LHSPI != LHSPE; LHSPI++) {
3261    bool RHSImplementsProtocol = false;
3262
3263    // If the RHS doesn't implement the protocol on the left, the types
3264    // are incompatible.
3265    for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
3266                                          RHSPE = RHS->qual_end();
3267         RHSPI != RHSPE; RHSPI++) {
3268      if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
3269        RHSImplementsProtocol = true;
3270        break;
3271      }
3272    }
3273    // FIXME: For better diagnostics, consider passing back the protocol name.
3274    if (!RHSImplementsProtocol)
3275      return false;
3276  }
3277  // The RHS implements all protocols listed on the LHS.
3278  return true;
3279}
3280
3281bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
3282  // get the "pointed to" types
3283  const ObjCObjectPointerType *LHSOPT = LHS->getAsObjCObjectPointerType();
3284  const ObjCObjectPointerType *RHSOPT = RHS->getAsObjCObjectPointerType();
3285
3286  if (!LHSOPT || !RHSOPT)
3287    return false;
3288
3289  return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
3290         canAssignObjCInterfaces(RHSOPT, LHSOPT);
3291}
3292
3293/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
3294/// both shall have the identically qualified version of a compatible type.
3295/// C99 6.2.7p1: Two types have compatible types if their types are the
3296/// same. See 6.7.[2,3,5] for additional rules.
3297bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
3298  return !mergeTypes(LHS, RHS).isNull();
3299}
3300
3301QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
3302  const FunctionType *lbase = lhs->getAsFunctionType();
3303  const FunctionType *rbase = rhs->getAsFunctionType();
3304  const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
3305  const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
3306  bool allLTypes = true;
3307  bool allRTypes = true;
3308
3309  // Check return type
3310  QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3311  if (retType.isNull()) return QualType();
3312  if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3313    allLTypes = false;
3314  if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3315    allRTypes = false;
3316
3317  if (lproto && rproto) { // two C99 style function prototypes
3318    assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3319           "C++ shouldn't be here");
3320    unsigned lproto_nargs = lproto->getNumArgs();
3321    unsigned rproto_nargs = rproto->getNumArgs();
3322
3323    // Compatible functions must have the same number of arguments
3324    if (lproto_nargs != rproto_nargs)
3325      return QualType();
3326
3327    // Variadic and non-variadic functions aren't compatible
3328    if (lproto->isVariadic() != rproto->isVariadic())
3329      return QualType();
3330
3331    if (lproto->getTypeQuals() != rproto->getTypeQuals())
3332      return QualType();
3333
3334    // Check argument compatibility
3335    llvm::SmallVector<QualType, 10> types;
3336    for (unsigned i = 0; i < lproto_nargs; i++) {
3337      QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3338      QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3339      QualType argtype = mergeTypes(largtype, rargtype);
3340      if (argtype.isNull()) return QualType();
3341      types.push_back(argtype);
3342      if (getCanonicalType(argtype) != getCanonicalType(largtype))
3343        allLTypes = false;
3344      if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3345        allRTypes = false;
3346    }
3347    if (allLTypes) return lhs;
3348    if (allRTypes) return rhs;
3349    return getFunctionType(retType, types.begin(), types.size(),
3350                           lproto->isVariadic(), lproto->getTypeQuals());
3351  }
3352
3353  if (lproto) allRTypes = false;
3354  if (rproto) allLTypes = false;
3355
3356  const FunctionProtoType *proto = lproto ? lproto : rproto;
3357  if (proto) {
3358    assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
3359    if (proto->isVariadic()) return QualType();
3360    // Check that the types are compatible with the types that
3361    // would result from default argument promotions (C99 6.7.5.3p15).
3362    // The only types actually affected are promotable integer
3363    // types and floats, which would be passed as a different
3364    // type depending on whether the prototype is visible.
3365    unsigned proto_nargs = proto->getNumArgs();
3366    for (unsigned i = 0; i < proto_nargs; ++i) {
3367      QualType argTy = proto->getArgType(i);
3368      if (argTy->isPromotableIntegerType() ||
3369          getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3370        return QualType();
3371    }
3372
3373    if (allLTypes) return lhs;
3374    if (allRTypes) return rhs;
3375    return getFunctionType(retType, proto->arg_type_begin(),
3376                           proto->getNumArgs(), lproto->isVariadic(),
3377                           lproto->getTypeQuals());
3378  }
3379
3380  if (allLTypes) return lhs;
3381  if (allRTypes) return rhs;
3382  return getFunctionNoProtoType(retType);
3383}
3384
3385QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
3386  // C++ [expr]: If an expression initially has the type "reference to T", the
3387  // type is adjusted to "T" prior to any further analysis, the expression
3388  // designates the object or function denoted by the reference, and the
3389  // expression is an lvalue unless the reference is an rvalue reference and
3390  // the expression is a function call (possibly inside parentheses).
3391  // FIXME: C++ shouldn't be going through here!  The rules are different
3392  // enough that they should be handled separately.
3393  // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3394  // shouldn't be going through here!
3395  if (const ReferenceType *RT = LHS->getAsReferenceType())
3396    LHS = RT->getPointeeType();
3397  if (const ReferenceType *RT = RHS->getAsReferenceType())
3398    RHS = RT->getPointeeType();
3399
3400  QualType LHSCan = getCanonicalType(LHS),
3401           RHSCan = getCanonicalType(RHS);
3402
3403  // If two types are identical, they are compatible.
3404  if (LHSCan == RHSCan)
3405    return LHS;
3406
3407  // If the qualifiers are different, the types aren't compatible
3408  // Note that we handle extended qualifiers later, in the
3409  // case for ExtQualType.
3410  if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
3411    return QualType();
3412
3413  Type::TypeClass LHSClass = LHSCan->getTypeClass();
3414  Type::TypeClass RHSClass = RHSCan->getTypeClass();
3415
3416  // We want to consider the two function types to be the same for these
3417  // comparisons, just force one to the other.
3418  if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3419  if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
3420
3421  // Strip off objc_gc attributes off the top level so they can be merged.
3422  // This is a complete mess, but the attribute itself doesn't make much sense.
3423  if (RHSClass == Type::ExtQual) {
3424    QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr();
3425    if (GCAttr != QualType::GCNone) {
3426      QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr();
3427      // __weak attribute must appear on both declarations.
3428      // __strong attribue is redundant if other decl is an objective-c
3429      // object pointer (or decorated with __strong attribute); otherwise
3430      // issue error.
3431      if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) ||
3432          (GCAttr == QualType::Strong && GCLHSAttr != GCAttr &&
3433           !LHSCan->isObjCObjectPointerType()))
3434        return QualType();
3435
3436      RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(),
3437                     RHS.getCVRQualifiers());
3438      QualType Result = mergeTypes(LHS, RHS);
3439      if (!Result.isNull()) {
3440        if (Result.getObjCGCAttr() == QualType::GCNone)
3441          Result = getObjCGCQualType(Result, GCAttr);
3442        else if (Result.getObjCGCAttr() != GCAttr)
3443          Result = QualType();
3444      }
3445      return Result;
3446    }
3447  }
3448  if (LHSClass == Type::ExtQual) {
3449    QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr();
3450    if (GCAttr != QualType::GCNone) {
3451      QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr();
3452      // __weak attribute must appear on both declarations. __strong
3453      // __strong attribue is redundant if other decl is an objective-c
3454      // object pointer (or decorated with __strong attribute); otherwise
3455      // issue error.
3456      if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) ||
3457          (GCAttr == QualType::Strong && GCRHSAttr != GCAttr &&
3458           !RHSCan->isObjCObjectPointerType()))
3459        return QualType();
3460
3461      LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(),
3462                     LHS.getCVRQualifiers());
3463      QualType Result = mergeTypes(LHS, RHS);
3464      if (!Result.isNull()) {
3465        if (Result.getObjCGCAttr() == QualType::GCNone)
3466          Result = getObjCGCQualType(Result, GCAttr);
3467        else if (Result.getObjCGCAttr() != GCAttr)
3468          Result = QualType();
3469      }
3470      return Result;
3471    }
3472  }
3473
3474  // Same as above for arrays
3475  if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3476    LHSClass = Type::ConstantArray;
3477  if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3478    RHSClass = Type::ConstantArray;
3479
3480  // Canonicalize ExtVector -> Vector.
3481  if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3482  if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
3483
3484  // If the canonical type classes don't match.
3485  if (LHSClass != RHSClass) {
3486    // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3487    // a signed integer type, or an unsigned integer type.
3488    if (const EnumType* ETy = LHS->getAsEnumType()) {
3489      if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3490        return RHS;
3491    }
3492    if (const EnumType* ETy = RHS->getAsEnumType()) {
3493      if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3494        return LHS;
3495    }
3496
3497    return QualType();
3498  }
3499
3500  // The canonical type classes match.
3501  switch (LHSClass) {
3502#define TYPE(Class, Base)
3503#define ABSTRACT_TYPE(Class, Base)
3504#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3505#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3506#include "clang/AST/TypeNodes.def"
3507    assert(false && "Non-canonical and dependent types shouldn't get here");
3508    return QualType();
3509
3510  case Type::LValueReference:
3511  case Type::RValueReference:
3512  case Type::MemberPointer:
3513    assert(false && "C++ should never be in mergeTypes");
3514    return QualType();
3515
3516  case Type::IncompleteArray:
3517  case Type::VariableArray:
3518  case Type::FunctionProto:
3519  case Type::ExtVector:
3520    assert(false && "Types are eliminated above");
3521    return QualType();
3522
3523  case Type::Pointer:
3524  {
3525    // Merge two pointer types, while trying to preserve typedef info
3526    QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
3527    QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
3528    QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3529    if (ResultType.isNull()) return QualType();
3530    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3531      return LHS;
3532    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3533      return RHS;
3534    return getPointerType(ResultType);
3535  }
3536  case Type::BlockPointer:
3537  {
3538    // Merge two block pointer types, while trying to preserve typedef info
3539    QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
3540    QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
3541    QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3542    if (ResultType.isNull()) return QualType();
3543    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3544      return LHS;
3545    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3546      return RHS;
3547    return getBlockPointerType(ResultType);
3548  }
3549  case Type::ConstantArray:
3550  {
3551    const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3552    const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3553    if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3554      return QualType();
3555
3556    QualType LHSElem = getAsArrayType(LHS)->getElementType();
3557    QualType RHSElem = getAsArrayType(RHS)->getElementType();
3558    QualType ResultType = mergeTypes(LHSElem, RHSElem);
3559    if (ResultType.isNull()) return QualType();
3560    if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3561      return LHS;
3562    if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3563      return RHS;
3564    if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3565                                          ArrayType::ArraySizeModifier(), 0);
3566    if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3567                                          ArrayType::ArraySizeModifier(), 0);
3568    const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3569    const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
3570    if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3571      return LHS;
3572    if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3573      return RHS;
3574    if (LVAT) {
3575      // FIXME: This isn't correct! But tricky to implement because
3576      // the array's size has to be the size of LHS, but the type
3577      // has to be different.
3578      return LHS;
3579    }
3580    if (RVAT) {
3581      // FIXME: This isn't correct! But tricky to implement because
3582      // the array's size has to be the size of RHS, but the type
3583      // has to be different.
3584      return RHS;
3585    }
3586    if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3587    if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
3588    return getIncompleteArrayType(ResultType,
3589                                  ArrayType::ArraySizeModifier(), 0);
3590  }
3591  case Type::FunctionNoProto:
3592    return mergeFunctionTypes(LHS, RHS);
3593  case Type::Record:
3594  case Type::Enum:
3595    return QualType();
3596  case Type::Builtin:
3597    // Only exactly equal builtin types are compatible, which is tested above.
3598    return QualType();
3599  case Type::Complex:
3600    // Distinct complex types are incompatible.
3601    return QualType();
3602  case Type::Vector:
3603    // FIXME: The merged type should be an ExtVector!
3604    if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3605      return LHS;
3606    return QualType();
3607  case Type::ObjCInterface: {
3608    // Check if the interfaces are assignment compatible.
3609    // FIXME: This should be type compatibility, e.g. whether
3610    // "LHS x; RHS x;" at global scope is legal.
3611    const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3612    const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3613    if (LHSIface && RHSIface &&
3614        canAssignObjCInterfaces(LHSIface, RHSIface))
3615      return LHS;
3616
3617    return QualType();
3618  }
3619  case Type::ObjCObjectPointer: {
3620    if (canAssignObjCInterfaces(LHS->getAsObjCObjectPointerType(),
3621                                RHS->getAsObjCObjectPointerType()))
3622      return LHS;
3623
3624    return QualType();
3625  }
3626  case Type::FixedWidthInt:
3627    // Distinct fixed-width integers are not compatible.
3628    return QualType();
3629  case Type::ExtQual:
3630    // FIXME: ExtQual types can be compatible even if they're not
3631    // identical!
3632    return QualType();
3633    // First attempt at an implementation, but I'm not really sure it's
3634    // right...
3635#if 0
3636    ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3637    ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3638    if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3639        LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3640      return QualType();
3641    QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3642    LHSBase = QualType(LQual->getBaseType(), 0);
3643    RHSBase = QualType(RQual->getBaseType(), 0);
3644    ResultType = mergeTypes(LHSBase, RHSBase);
3645    if (ResultType.isNull()) return QualType();
3646    ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3647    if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3648      return LHS;
3649    if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3650      return RHS;
3651    ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3652    ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3653    ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3654    return ResultType;
3655#endif
3656
3657  case Type::TemplateSpecialization:
3658    assert(false && "Dependent types have no size");
3659    break;
3660  }
3661
3662  return QualType();
3663}
3664
3665//===----------------------------------------------------------------------===//
3666//                         Integer Predicates
3667//===----------------------------------------------------------------------===//
3668
3669unsigned ASTContext::getIntWidth(QualType T) {
3670  if (T == BoolTy)
3671    return 1;
3672  if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3673    return FWIT->getWidth();
3674  }
3675  // For builtin types, just use the standard type sizing method
3676  return (unsigned)getTypeSize(T);
3677}
3678
3679QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3680  assert(T->isSignedIntegerType() && "Unexpected type");
3681  if (const EnumType* ETy = T->getAsEnumType())
3682    T = ETy->getDecl()->getIntegerType();
3683  const BuiltinType* BTy = T->getAsBuiltinType();
3684  assert (BTy && "Unexpected signed integer type");
3685  switch (BTy->getKind()) {
3686  case BuiltinType::Char_S:
3687  case BuiltinType::SChar:
3688    return UnsignedCharTy;
3689  case BuiltinType::Short:
3690    return UnsignedShortTy;
3691  case BuiltinType::Int:
3692    return UnsignedIntTy;
3693  case BuiltinType::Long:
3694    return UnsignedLongTy;
3695  case BuiltinType::LongLong:
3696    return UnsignedLongLongTy;
3697  case BuiltinType::Int128:
3698    return UnsignedInt128Ty;
3699  default:
3700    assert(0 && "Unexpected signed integer type");
3701    return QualType();
3702  }
3703}
3704
3705ExternalASTSource::~ExternalASTSource() { }
3706
3707void ExternalASTSource::PrintStats() { }
3708
3709
3710//===----------------------------------------------------------------------===//
3711//                          Builtin Type Computation
3712//===----------------------------------------------------------------------===//
3713
3714/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
3715/// pointer over the consumed characters.  This returns the resultant type.
3716static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
3717                                  ASTContext::GetBuiltinTypeError &Error,
3718                                  bool AllowTypeModifiers = true) {
3719  // Modifiers.
3720  int HowLong = 0;
3721  bool Signed = false, Unsigned = false;
3722
3723  // Read the modifiers first.
3724  bool Done = false;
3725  while (!Done) {
3726    switch (*Str++) {
3727    default: Done = true; --Str; break;
3728    case 'S':
3729      assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
3730      assert(!Signed && "Can't use 'S' modifier multiple times!");
3731      Signed = true;
3732      break;
3733    case 'U':
3734      assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
3735      assert(!Unsigned && "Can't use 'S' modifier multiple times!");
3736      Unsigned = true;
3737      break;
3738    case 'L':
3739      assert(HowLong <= 2 && "Can't have LLLL modifier");
3740      ++HowLong;
3741      break;
3742    }
3743  }
3744
3745  QualType Type;
3746
3747  // Read the base type.
3748  switch (*Str++) {
3749  default: assert(0 && "Unknown builtin type letter!");
3750  case 'v':
3751    assert(HowLong == 0 && !Signed && !Unsigned &&
3752           "Bad modifiers used with 'v'!");
3753    Type = Context.VoidTy;
3754    break;
3755  case 'f':
3756    assert(HowLong == 0 && !Signed && !Unsigned &&
3757           "Bad modifiers used with 'f'!");
3758    Type = Context.FloatTy;
3759    break;
3760  case 'd':
3761    assert(HowLong < 2 && !Signed && !Unsigned &&
3762           "Bad modifiers used with 'd'!");
3763    if (HowLong)
3764      Type = Context.LongDoubleTy;
3765    else
3766      Type = Context.DoubleTy;
3767    break;
3768  case 's':
3769    assert(HowLong == 0 && "Bad modifiers used with 's'!");
3770    if (Unsigned)
3771      Type = Context.UnsignedShortTy;
3772    else
3773      Type = Context.ShortTy;
3774    break;
3775  case 'i':
3776    if (HowLong == 3)
3777      Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
3778    else if (HowLong == 2)
3779      Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
3780    else if (HowLong == 1)
3781      Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
3782    else
3783      Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
3784    break;
3785  case 'c':
3786    assert(HowLong == 0 && "Bad modifiers used with 'c'!");
3787    if (Signed)
3788      Type = Context.SignedCharTy;
3789    else if (Unsigned)
3790      Type = Context.UnsignedCharTy;
3791    else
3792      Type = Context.CharTy;
3793    break;
3794  case 'b': // boolean
3795    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
3796    Type = Context.BoolTy;
3797    break;
3798  case 'z':  // size_t.
3799    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
3800    Type = Context.getSizeType();
3801    break;
3802  case 'F':
3803    Type = Context.getCFConstantStringType();
3804    break;
3805  case 'a':
3806    Type = Context.getBuiltinVaListType();
3807    assert(!Type.isNull() && "builtin va list type not initialized!");
3808    break;
3809  case 'A':
3810    // This is a "reference" to a va_list; however, what exactly
3811    // this means depends on how va_list is defined. There are two
3812    // different kinds of va_list: ones passed by value, and ones
3813    // passed by reference.  An example of a by-value va_list is
3814    // x86, where va_list is a char*. An example of by-ref va_list
3815    // is x86-64, where va_list is a __va_list_tag[1]. For x86,
3816    // we want this argument to be a char*&; for x86-64, we want
3817    // it to be a __va_list_tag*.
3818    Type = Context.getBuiltinVaListType();
3819    assert(!Type.isNull() && "builtin va list type not initialized!");
3820    if (Type->isArrayType()) {
3821      Type = Context.getArrayDecayedType(Type);
3822    } else {
3823      Type = Context.getLValueReferenceType(Type);
3824    }
3825    break;
3826  case 'V': {
3827    char *End;
3828
3829    unsigned NumElements = strtoul(Str, &End, 10);
3830    assert(End != Str && "Missing vector size");
3831
3832    Str = End;
3833
3834    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
3835    Type = Context.getVectorType(ElementType, NumElements);
3836    break;
3837  }
3838  case 'P': {
3839    Type = Context.getFILEType();
3840    if (Type.isNull()) {
3841      Error = ASTContext::GE_Missing_FILE;
3842      return QualType();
3843    } else {
3844      break;
3845    }
3846  }
3847  }
3848
3849  if (!AllowTypeModifiers)
3850    return Type;
3851
3852  Done = false;
3853  while (!Done) {
3854    switch (*Str++) {
3855      default: Done = true; --Str; break;
3856      case '*':
3857        Type = Context.getPointerType(Type);
3858        break;
3859      case '&':
3860        Type = Context.getLValueReferenceType(Type);
3861        break;
3862      // FIXME: There's no way to have a built-in with an rvalue ref arg.
3863      case 'C':
3864        Type = Type.getQualifiedType(QualType::Const);
3865        break;
3866    }
3867  }
3868
3869  return Type;
3870}
3871
3872/// GetBuiltinType - Return the type for the specified builtin.
3873QualType ASTContext::GetBuiltinType(unsigned id,
3874                                    GetBuiltinTypeError &Error) {
3875  const char *TypeStr = BuiltinInfo.GetTypeString(id);
3876
3877  llvm::SmallVector<QualType, 8> ArgTypes;
3878
3879  Error = GE_None;
3880  QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
3881  if (Error != GE_None)
3882    return QualType();
3883  while (TypeStr[0] && TypeStr[0] != '.') {
3884    QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
3885    if (Error != GE_None)
3886      return QualType();
3887
3888    // Do array -> pointer decay.  The builtin should use the decayed type.
3889    if (Ty->isArrayType())
3890      Ty = getArrayDecayedType(Ty);
3891
3892    ArgTypes.push_back(Ty);
3893  }
3894
3895  assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
3896         "'.' should only occur at end of builtin type list!");
3897
3898  // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
3899  if (ArgTypes.size() == 0 && TypeStr[0] == '.')
3900    return getFunctionNoProtoType(ResType);
3901  return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
3902                         TypeStr[0] == '.', 0);
3903}
3904