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