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