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