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