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