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