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