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