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