ASTContext.cpp revision f5f7d864f5067d1ea4bff7fcf41b53a43b7b48ba
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::fromRaw(getTypeSize(T) / getCharWidth());
818}
819CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
820  return CharUnits::fromRaw(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
2375DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2376  if (TemplateDecl *TD = Name.getAsTemplateDecl())
2377    return TD->getDeclName();
2378
2379  if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2380    if (DTN->isIdentifier()) {
2381      return DeclarationNames.getIdentifier(DTN->getIdentifier());
2382    } else {
2383      return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2384    }
2385  }
2386
2387  OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2388  assert(Storage);
2389  return (*Storage->begin())->getDeclName();
2390}
2391
2392TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2393  // If this template name refers to a template, the canonical
2394  // template name merely stores the template itself.
2395  if (TemplateDecl *Template = Name.getAsTemplateDecl())
2396    return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
2397
2398  assert(!Name.getAsOverloadedTemplate());
2399
2400  DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2401  assert(DTN && "Non-dependent template names must refer to template decls.");
2402  return DTN->CanonicalTemplateName;
2403}
2404
2405bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2406  X = getCanonicalTemplateName(X);
2407  Y = getCanonicalTemplateName(Y);
2408  return X.getAsVoidPointer() == Y.getAsVoidPointer();
2409}
2410
2411TemplateArgument
2412ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2413  switch (Arg.getKind()) {
2414    case TemplateArgument::Null:
2415      return Arg;
2416
2417    case TemplateArgument::Expression:
2418      return Arg;
2419
2420    case TemplateArgument::Declaration:
2421      return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
2422
2423    case TemplateArgument::Template:
2424      return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2425
2426    case TemplateArgument::Integral:
2427      return TemplateArgument(*Arg.getAsIntegral(),
2428                              getCanonicalType(Arg.getIntegralType()));
2429
2430    case TemplateArgument::Type:
2431      return TemplateArgument(getCanonicalType(Arg.getAsType()));
2432
2433    case TemplateArgument::Pack: {
2434      // FIXME: Allocate in ASTContext
2435      TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2436      unsigned Idx = 0;
2437      for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
2438                                        AEnd = Arg.pack_end();
2439           A != AEnd; (void)++A, ++Idx)
2440        CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
2441
2442      TemplateArgument Result;
2443      Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2444      return Result;
2445    }
2446  }
2447
2448  // Silence GCC warning
2449  assert(false && "Unhandled template argument kind");
2450  return TemplateArgument();
2451}
2452
2453NestedNameSpecifier *
2454ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
2455  if (!NNS)
2456    return 0;
2457
2458  switch (NNS->getKind()) {
2459  case NestedNameSpecifier::Identifier:
2460    // Canonicalize the prefix but keep the identifier the same.
2461    return NestedNameSpecifier::Create(*this,
2462                         getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2463                                       NNS->getAsIdentifier());
2464
2465  case NestedNameSpecifier::Namespace:
2466    // A namespace is canonical; build a nested-name-specifier with
2467    // this namespace and no prefix.
2468    return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2469
2470  case NestedNameSpecifier::TypeSpec:
2471  case NestedNameSpecifier::TypeSpecWithTemplate: {
2472    QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
2473    return NestedNameSpecifier::Create(*this, 0,
2474                 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
2475                                       T.getTypePtr());
2476  }
2477
2478  case NestedNameSpecifier::Global:
2479    // The global specifier is canonical and unique.
2480    return NNS;
2481  }
2482
2483  // Required to silence a GCC warning
2484  return 0;
2485}
2486
2487
2488const ArrayType *ASTContext::getAsArrayType(QualType T) {
2489  // Handle the non-qualified case efficiently.
2490  if (!T.hasLocalQualifiers()) {
2491    // Handle the common positive case fast.
2492    if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2493      return AT;
2494  }
2495
2496  // Handle the common negative case fast.
2497  QualType CType = T->getCanonicalTypeInternal();
2498  if (!isa<ArrayType>(CType))
2499    return 0;
2500
2501  // Apply any qualifiers from the array type to the element type.  This
2502  // implements C99 6.7.3p8: "If the specification of an array type includes
2503  // any type qualifiers, the element type is so qualified, not the array type."
2504
2505  // If we get here, we either have type qualifiers on the type, or we have
2506  // sugar such as a typedef in the way.  If we have type qualifiers on the type
2507  // we must propagate them down into the element type.
2508
2509  QualifierCollector Qs;
2510  const Type *Ty = Qs.strip(T.getDesugaredType());
2511
2512  // If we have a simple case, just return now.
2513  const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2514  if (ATy == 0 || Qs.empty())
2515    return ATy;
2516
2517  // Otherwise, we have an array and we have qualifiers on it.  Push the
2518  // qualifiers into the array element type and return a new array type.
2519  // Get the canonical version of the element with the extra qualifiers on it.
2520  // This can recursively sink qualifiers through multiple levels of arrays.
2521  QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
2522
2523  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2524    return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2525                                                CAT->getSizeModifier(),
2526                                           CAT->getIndexTypeCVRQualifiers()));
2527  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2528    return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2529                                                  IAT->getSizeModifier(),
2530                                           IAT->getIndexTypeCVRQualifiers()));
2531
2532  if (const DependentSizedArrayType *DSAT
2533        = dyn_cast<DependentSizedArrayType>(ATy))
2534    return cast<ArrayType>(
2535                     getDependentSizedArrayType(NewEltTy,
2536                                                DSAT->getSizeExpr() ?
2537                                              DSAT->getSizeExpr()->Retain() : 0,
2538                                                DSAT->getSizeModifier(),
2539                                              DSAT->getIndexTypeCVRQualifiers(),
2540                                                DSAT->getBracketsRange()));
2541
2542  const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
2543  return cast<ArrayType>(getVariableArrayType(NewEltTy,
2544                                              VAT->getSizeExpr() ?
2545                                              VAT->getSizeExpr()->Retain() : 0,
2546                                              VAT->getSizeModifier(),
2547                                              VAT->getIndexTypeCVRQualifiers(),
2548                                              VAT->getBracketsRange()));
2549}
2550
2551
2552/// getArrayDecayedType - Return the properly qualified result of decaying the
2553/// specified array type to a pointer.  This operation is non-trivial when
2554/// handling typedefs etc.  The canonical type of "T" must be an array type,
2555/// this returns a pointer to a properly qualified element of the array.
2556///
2557/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2558QualType ASTContext::getArrayDecayedType(QualType Ty) {
2559  // Get the element type with 'getAsArrayType' so that we don't lose any
2560  // typedefs in the element type of the array.  This also handles propagation
2561  // of type qualifiers from the array type into the element type if present
2562  // (C99 6.7.3p8).
2563  const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2564  assert(PrettyArrayType && "Not an array type!");
2565
2566  QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
2567
2568  // int x[restrict 4] ->  int *restrict
2569  return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
2570}
2571
2572QualType ASTContext::getBaseElementType(QualType QT) {
2573  QualifierCollector Qs;
2574  while (true) {
2575    const Type *UT = Qs.strip(QT);
2576    if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2577      QT = AT->getElementType();
2578    } else {
2579      return Qs.apply(QT);
2580    }
2581  }
2582}
2583
2584QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2585  QualType ElemTy = AT->getElementType();
2586
2587  if (const ArrayType *AT = getAsArrayType(ElemTy))
2588    return getBaseElementType(AT);
2589
2590  return ElemTy;
2591}
2592
2593/// getConstantArrayElementCount - Returns number of constant array elements.
2594uint64_t
2595ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
2596  uint64_t ElementCount = 1;
2597  do {
2598    ElementCount *= CA->getSize().getZExtValue();
2599    CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2600  } while (CA);
2601  return ElementCount;
2602}
2603
2604/// getFloatingRank - Return a relative rank for floating point types.
2605/// This routine will assert if passed a built-in type that isn't a float.
2606static FloatingRank getFloatingRank(QualType T) {
2607  if (const ComplexType *CT = T->getAs<ComplexType>())
2608    return getFloatingRank(CT->getElementType());
2609
2610  assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2611  switch (T->getAs<BuiltinType>()->getKind()) {
2612  default: assert(0 && "getFloatingRank(): not a floating type");
2613  case BuiltinType::Float:      return FloatRank;
2614  case BuiltinType::Double:     return DoubleRank;
2615  case BuiltinType::LongDouble: return LongDoubleRank;
2616  }
2617}
2618
2619/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2620/// point or a complex type (based on typeDomain/typeSize).
2621/// 'typeDomain' is a real floating point or complex type.
2622/// 'typeSize' is a real floating point or complex type.
2623QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2624                                                       QualType Domain) const {
2625  FloatingRank EltRank = getFloatingRank(Size);
2626  if (Domain->isComplexType()) {
2627    switch (EltRank) {
2628    default: assert(0 && "getFloatingRank(): illegal value for rank");
2629    case FloatRank:      return FloatComplexTy;
2630    case DoubleRank:     return DoubleComplexTy;
2631    case LongDoubleRank: return LongDoubleComplexTy;
2632    }
2633  }
2634
2635  assert(Domain->isRealFloatingType() && "Unknown domain!");
2636  switch (EltRank) {
2637  default: assert(0 && "getFloatingRank(): illegal value for rank");
2638  case FloatRank:      return FloatTy;
2639  case DoubleRank:     return DoubleTy;
2640  case LongDoubleRank: return LongDoubleTy;
2641  }
2642}
2643
2644/// getFloatingTypeOrder - Compare the rank of the two specified floating
2645/// point types, ignoring the domain of the type (i.e. 'double' ==
2646/// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
2647/// LHS < RHS, return -1.
2648int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2649  FloatingRank LHSR = getFloatingRank(LHS);
2650  FloatingRank RHSR = getFloatingRank(RHS);
2651
2652  if (LHSR == RHSR)
2653    return 0;
2654  if (LHSR > RHSR)
2655    return 1;
2656  return -1;
2657}
2658
2659/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2660/// routine will assert if passed a built-in type that isn't an integer or enum,
2661/// or if it is not canonicalized.
2662unsigned ASTContext::getIntegerRank(Type *T) {
2663  assert(T->isCanonicalUnqualified() && "T should be canonicalized");
2664  if (EnumType* ET = dyn_cast<EnumType>(T))
2665    T = ET->getDecl()->getPromotionType().getTypePtr();
2666
2667  if (T->isSpecificBuiltinType(BuiltinType::WChar))
2668    T = getFromTargetType(Target.getWCharType()).getTypePtr();
2669
2670  if (T->isSpecificBuiltinType(BuiltinType::Char16))
2671    T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2672
2673  if (T->isSpecificBuiltinType(BuiltinType::Char32))
2674    T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2675
2676  switch (cast<BuiltinType>(T)->getKind()) {
2677  default: assert(0 && "getIntegerRank(): not a built-in integer");
2678  case BuiltinType::Bool:
2679    return 1 + (getIntWidth(BoolTy) << 3);
2680  case BuiltinType::Char_S:
2681  case BuiltinType::Char_U:
2682  case BuiltinType::SChar:
2683  case BuiltinType::UChar:
2684    return 2 + (getIntWidth(CharTy) << 3);
2685  case BuiltinType::Short:
2686  case BuiltinType::UShort:
2687    return 3 + (getIntWidth(ShortTy) << 3);
2688  case BuiltinType::Int:
2689  case BuiltinType::UInt:
2690    return 4 + (getIntWidth(IntTy) << 3);
2691  case BuiltinType::Long:
2692  case BuiltinType::ULong:
2693    return 5 + (getIntWidth(LongTy) << 3);
2694  case BuiltinType::LongLong:
2695  case BuiltinType::ULongLong:
2696    return 6 + (getIntWidth(LongLongTy) << 3);
2697  case BuiltinType::Int128:
2698  case BuiltinType::UInt128:
2699    return 7 + (getIntWidth(Int128Ty) << 3);
2700  }
2701}
2702
2703/// \brief Whether this is a promotable bitfield reference according
2704/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2705///
2706/// \returns the type this bit-field will promote to, or NULL if no
2707/// promotion occurs.
2708QualType ASTContext::isPromotableBitField(Expr *E) {
2709  FieldDecl *Field = E->getBitField();
2710  if (!Field)
2711    return QualType();
2712
2713  QualType FT = Field->getType();
2714
2715  llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2716  uint64_t BitWidth = BitWidthAP.getZExtValue();
2717  uint64_t IntSize = getTypeSize(IntTy);
2718  // GCC extension compatibility: if the bit-field size is less than or equal
2719  // to the size of int, it gets promoted no matter what its type is.
2720  // For instance, unsigned long bf : 4 gets promoted to signed int.
2721  if (BitWidth < IntSize)
2722    return IntTy;
2723
2724  if (BitWidth == IntSize)
2725    return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2726
2727  // Types bigger than int are not subject to promotions, and therefore act
2728  // like the base type.
2729  // FIXME: This doesn't quite match what gcc does, but what gcc does here
2730  // is ridiculous.
2731  return QualType();
2732}
2733
2734/// getPromotedIntegerType - Returns the type that Promotable will
2735/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2736/// integer type.
2737QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2738  assert(!Promotable.isNull());
2739  assert(Promotable->isPromotableIntegerType());
2740  if (const EnumType *ET = Promotable->getAs<EnumType>())
2741    return ET->getDecl()->getPromotionType();
2742  if (Promotable->isSignedIntegerType())
2743    return IntTy;
2744  uint64_t PromotableSize = getTypeSize(Promotable);
2745  uint64_t IntSize = getTypeSize(IntTy);
2746  assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2747  return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2748}
2749
2750/// getIntegerTypeOrder - Returns the highest ranked integer type:
2751/// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
2752/// LHS < RHS, return -1.
2753int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
2754  Type *LHSC = getCanonicalType(LHS).getTypePtr();
2755  Type *RHSC = getCanonicalType(RHS).getTypePtr();
2756  if (LHSC == RHSC) return 0;
2757
2758  bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2759  bool RHSUnsigned = RHSC->isUnsignedIntegerType();
2760
2761  unsigned LHSRank = getIntegerRank(LHSC);
2762  unsigned RHSRank = getIntegerRank(RHSC);
2763
2764  if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
2765    if (LHSRank == RHSRank) return 0;
2766    return LHSRank > RHSRank ? 1 : -1;
2767  }
2768
2769  // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2770  if (LHSUnsigned) {
2771    // If the unsigned [LHS] type is larger, return it.
2772    if (LHSRank >= RHSRank)
2773      return 1;
2774
2775    // If the signed type can represent all values of the unsigned type, it
2776    // wins.  Because we are dealing with 2's complement and types that are
2777    // powers of two larger than each other, this is always safe.
2778    return -1;
2779  }
2780
2781  // If the unsigned [RHS] type is larger, return it.
2782  if (RHSRank >= LHSRank)
2783    return -1;
2784
2785  // If the signed type can represent all values of the unsigned type, it
2786  // wins.  Because we are dealing with 2's complement and types that are
2787  // powers of two larger than each other, this is always safe.
2788  return 1;
2789}
2790
2791static RecordDecl *
2792CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2793                 SourceLocation L, IdentifierInfo *Id) {
2794  if (Ctx.getLangOptions().CPlusPlus)
2795    return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2796  else
2797    return RecordDecl::Create(Ctx, TK, DC, L, Id);
2798}
2799
2800// getCFConstantStringType - Return the type used for constant CFStrings.
2801QualType ASTContext::getCFConstantStringType() {
2802  if (!CFConstantStringTypeDecl) {
2803    CFConstantStringTypeDecl =
2804      CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2805                       &Idents.get("NSConstantString"));
2806
2807    QualType FieldTypes[4];
2808
2809    // const int *isa;
2810    FieldTypes[0] = getPointerType(IntTy.withConst());
2811    // int flags;
2812    FieldTypes[1] = IntTy;
2813    // const char *str;
2814    FieldTypes[2] = getPointerType(CharTy.withConst());
2815    // long length;
2816    FieldTypes[3] = LongTy;
2817
2818    // Create fields
2819    for (unsigned i = 0; i < 4; ++i) {
2820      FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2821                                           SourceLocation(), 0,
2822                                           FieldTypes[i], /*TInfo=*/0,
2823                                           /*BitWidth=*/0,
2824                                           /*Mutable=*/false);
2825      CFConstantStringTypeDecl->addDecl(Field);
2826    }
2827
2828    CFConstantStringTypeDecl->completeDefinition(*this);
2829  }
2830
2831  return getTagDeclType(CFConstantStringTypeDecl);
2832}
2833
2834void ASTContext::setCFConstantStringType(QualType T) {
2835  const RecordType *Rec = T->getAs<RecordType>();
2836  assert(Rec && "Invalid CFConstantStringType");
2837  CFConstantStringTypeDecl = Rec->getDecl();
2838}
2839
2840QualType ASTContext::getObjCFastEnumerationStateType() {
2841  if (!ObjCFastEnumerationStateTypeDecl) {
2842    ObjCFastEnumerationStateTypeDecl =
2843      CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2844                       &Idents.get("__objcFastEnumerationState"));
2845
2846    QualType FieldTypes[] = {
2847      UnsignedLongTy,
2848      getPointerType(ObjCIdTypedefType),
2849      getPointerType(UnsignedLongTy),
2850      getConstantArrayType(UnsignedLongTy,
2851                           llvm::APInt(32, 5), ArrayType::Normal, 0)
2852    };
2853
2854    for (size_t i = 0; i < 4; ++i) {
2855      FieldDecl *Field = FieldDecl::Create(*this,
2856                                           ObjCFastEnumerationStateTypeDecl,
2857                                           SourceLocation(), 0,
2858                                           FieldTypes[i], /*TInfo=*/0,
2859                                           /*BitWidth=*/0,
2860                                           /*Mutable=*/false);
2861      ObjCFastEnumerationStateTypeDecl->addDecl(Field);
2862    }
2863
2864    ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
2865  }
2866
2867  return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2868}
2869
2870QualType ASTContext::getBlockDescriptorType() {
2871  if (BlockDescriptorType)
2872    return getTagDeclType(BlockDescriptorType);
2873
2874  RecordDecl *T;
2875  // FIXME: Needs the FlagAppleBlock bit.
2876  T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2877                       &Idents.get("__block_descriptor"));
2878
2879  QualType FieldTypes[] = {
2880    UnsignedLongTy,
2881    UnsignedLongTy,
2882  };
2883
2884  const char *FieldNames[] = {
2885    "reserved",
2886    "Size"
2887  };
2888
2889  for (size_t i = 0; i < 2; ++i) {
2890    FieldDecl *Field = FieldDecl::Create(*this,
2891                                         T,
2892                                         SourceLocation(),
2893                                         &Idents.get(FieldNames[i]),
2894                                         FieldTypes[i], /*TInfo=*/0,
2895                                         /*BitWidth=*/0,
2896                                         /*Mutable=*/false);
2897    T->addDecl(Field);
2898  }
2899
2900  T->completeDefinition(*this);
2901
2902  BlockDescriptorType = T;
2903
2904  return getTagDeclType(BlockDescriptorType);
2905}
2906
2907void ASTContext::setBlockDescriptorType(QualType T) {
2908  const RecordType *Rec = T->getAs<RecordType>();
2909  assert(Rec && "Invalid BlockDescriptorType");
2910  BlockDescriptorType = Rec->getDecl();
2911}
2912
2913QualType ASTContext::getBlockDescriptorExtendedType() {
2914  if (BlockDescriptorExtendedType)
2915    return getTagDeclType(BlockDescriptorExtendedType);
2916
2917  RecordDecl *T;
2918  // FIXME: Needs the FlagAppleBlock bit.
2919  T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2920                       &Idents.get("__block_descriptor_withcopydispose"));
2921
2922  QualType FieldTypes[] = {
2923    UnsignedLongTy,
2924    UnsignedLongTy,
2925    getPointerType(VoidPtrTy),
2926    getPointerType(VoidPtrTy)
2927  };
2928
2929  const char *FieldNames[] = {
2930    "reserved",
2931    "Size",
2932    "CopyFuncPtr",
2933    "DestroyFuncPtr"
2934  };
2935
2936  for (size_t i = 0; i < 4; ++i) {
2937    FieldDecl *Field = FieldDecl::Create(*this,
2938                                         T,
2939                                         SourceLocation(),
2940                                         &Idents.get(FieldNames[i]),
2941                                         FieldTypes[i], /*TInfo=*/0,
2942                                         /*BitWidth=*/0,
2943                                         /*Mutable=*/false);
2944    T->addDecl(Field);
2945  }
2946
2947  T->completeDefinition(*this);
2948
2949  BlockDescriptorExtendedType = T;
2950
2951  return getTagDeclType(BlockDescriptorExtendedType);
2952}
2953
2954void ASTContext::setBlockDescriptorExtendedType(QualType T) {
2955  const RecordType *Rec = T->getAs<RecordType>();
2956  assert(Rec && "Invalid BlockDescriptorType");
2957  BlockDescriptorExtendedType = Rec->getDecl();
2958}
2959
2960bool ASTContext::BlockRequiresCopying(QualType Ty) {
2961  if (Ty->isBlockPointerType())
2962    return true;
2963  if (isObjCNSObjectType(Ty))
2964    return true;
2965  if (Ty->isObjCObjectPointerType())
2966    return true;
2967  return false;
2968}
2969
2970QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
2971  //  type = struct __Block_byref_1_X {
2972  //    void *__isa;
2973  //    struct __Block_byref_1_X *__forwarding;
2974  //    unsigned int __flags;
2975  //    unsigned int __size;
2976  //    void *__copy_helper;		// as needed
2977  //    void *__destroy_help		// as needed
2978  //    int X;
2979  //  } *
2980
2981  bool HasCopyAndDispose = BlockRequiresCopying(Ty);
2982
2983  // FIXME: Move up
2984  static unsigned int UniqueBlockByRefTypeID = 0;
2985  llvm::SmallString<36> Name;
2986  llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
2987                                  ++UniqueBlockByRefTypeID << '_' << DeclName;
2988  RecordDecl *T;
2989  T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2990                       &Idents.get(Name.str()));
2991  T->startDefinition();
2992  QualType Int32Ty = IntTy;
2993  assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
2994  QualType FieldTypes[] = {
2995    getPointerType(VoidPtrTy),
2996    getPointerType(getTagDeclType(T)),
2997    Int32Ty,
2998    Int32Ty,
2999    getPointerType(VoidPtrTy),
3000    getPointerType(VoidPtrTy),
3001    Ty
3002  };
3003
3004  const char *FieldNames[] = {
3005    "__isa",
3006    "__forwarding",
3007    "__flags",
3008    "__size",
3009    "__copy_helper",
3010    "__destroy_helper",
3011    DeclName,
3012  };
3013
3014  for (size_t i = 0; i < 7; ++i) {
3015    if (!HasCopyAndDispose && i >=4 && i <= 5)
3016      continue;
3017    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3018                                         &Idents.get(FieldNames[i]),
3019                                         FieldTypes[i], /*TInfo=*/0,
3020                                         /*BitWidth=*/0, /*Mutable=*/false);
3021    T->addDecl(Field);
3022  }
3023
3024  T->completeDefinition(*this);
3025
3026  return getPointerType(getTagDeclType(T));
3027}
3028
3029
3030QualType ASTContext::getBlockParmType(
3031  bool BlockHasCopyDispose,
3032  llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
3033  // FIXME: Move up
3034  static unsigned int UniqueBlockParmTypeID = 0;
3035  llvm::SmallString<36> Name;
3036  llvm::raw_svector_ostream(Name) << "__block_literal_"
3037                                  << ++UniqueBlockParmTypeID;
3038  RecordDecl *T;
3039  T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3040                       &Idents.get(Name.str()));
3041  QualType FieldTypes[] = {
3042    getPointerType(VoidPtrTy),
3043    IntTy,
3044    IntTy,
3045    getPointerType(VoidPtrTy),
3046    (BlockHasCopyDispose ?
3047     getPointerType(getBlockDescriptorExtendedType()) :
3048     getPointerType(getBlockDescriptorType()))
3049  };
3050
3051  const char *FieldNames[] = {
3052    "__isa",
3053    "__flags",
3054    "__reserved",
3055    "__FuncPtr",
3056    "__descriptor"
3057  };
3058
3059  for (size_t i = 0; i < 5; ++i) {
3060    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3061                                         &Idents.get(FieldNames[i]),
3062                                         FieldTypes[i], /*TInfo=*/0,
3063                                         /*BitWidth=*/0, /*Mutable=*/false);
3064    T->addDecl(Field);
3065  }
3066
3067  for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3068    const Expr *E = BlockDeclRefDecls[i];
3069    const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3070    clang::IdentifierInfo *Name = 0;
3071    if (BDRE) {
3072      const ValueDecl *D = BDRE->getDecl();
3073      Name = &Idents.get(D->getName());
3074    }
3075    QualType FieldType = E->getType();
3076
3077    if (BDRE && BDRE->isByRef())
3078      FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3079                                 FieldType);
3080
3081    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3082                                         Name, FieldType, /*TInfo=*/0,
3083                                         /*BitWidth=*/0, /*Mutable=*/false);
3084    T->addDecl(Field);
3085  }
3086
3087  T->completeDefinition(*this);
3088
3089  return getPointerType(getTagDeclType(T));
3090}
3091
3092void ASTContext::setObjCFastEnumerationStateType(QualType T) {
3093  const RecordType *Rec = T->getAs<RecordType>();
3094  assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3095  ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3096}
3097
3098// This returns true if a type has been typedefed to BOOL:
3099// typedef <type> BOOL;
3100static bool isTypeTypedefedAsBOOL(QualType T) {
3101  if (const TypedefType *TT = dyn_cast<TypedefType>(T))
3102    if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3103      return II->isStr("BOOL");
3104
3105  return false;
3106}
3107
3108/// getObjCEncodingTypeSize returns size of type for objective-c encoding
3109/// purpose.
3110int ASTContext::getObjCEncodingTypeSize(QualType type) {
3111  uint64_t sz = getTypeSize(type);
3112
3113  // Make all integer and enum types at least as large as an int
3114  if (sz > 0 && type->isIntegralType())
3115    sz = std::max(sz, getTypeSize(IntTy));
3116  // Treat arrays as pointers, since that's how they're passed in.
3117  else if (type->isArrayType())
3118    sz = getTypeSize(VoidPtrTy);
3119  return sz / getTypeSize(CharTy);
3120}
3121
3122/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3123/// declaration.
3124void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3125                                             std::string& S) {
3126  const BlockDecl *Decl = Expr->getBlockDecl();
3127  QualType BlockTy =
3128      Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3129  // Encode result type.
3130  getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3131  // Compute size of all parameters.
3132  // Start with computing size of a pointer in number of bytes.
3133  // FIXME: There might(should) be a better way of doing this computation!
3134  SourceLocation Loc;
3135  int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
3136  int ParmOffset = PtrSize;
3137  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3138       E = Decl->param_end(); PI != E; ++PI) {
3139    QualType PType = (*PI)->getType();
3140    int sz = getObjCEncodingTypeSize(PType);
3141    assert (sz > 0 && "BlockExpr - Incomplete param type");
3142    ParmOffset += sz;
3143  }
3144  // Size of the argument frame
3145  S += llvm::utostr(ParmOffset);
3146  // Block pointer and offset.
3147  S += "@?0";
3148  ParmOffset = PtrSize;
3149
3150  // Argument types.
3151  ParmOffset = PtrSize;
3152  for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3153       Decl->param_end(); PI != E; ++PI) {
3154    ParmVarDecl *PVDecl = *PI;
3155    QualType PType = PVDecl->getOriginalType();
3156    if (const ArrayType *AT =
3157          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3158      // Use array's original type only if it has known number of
3159      // elements.
3160      if (!isa<ConstantArrayType>(AT))
3161        PType = PVDecl->getType();
3162    } else if (PType->isFunctionType())
3163      PType = PVDecl->getType();
3164    getObjCEncodingForType(PType, S);
3165    S += llvm::utostr(ParmOffset);
3166    ParmOffset += getObjCEncodingTypeSize(PType);
3167  }
3168}
3169
3170/// getObjCEncodingForMethodDecl - Return the encoded type for this method
3171/// declaration.
3172void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
3173                                              std::string& S) {
3174  // FIXME: This is not very efficient.
3175  // Encode type qualifer, 'in', 'inout', etc. for the return type.
3176  getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
3177  // Encode result type.
3178  getObjCEncodingForType(Decl->getResultType(), S);
3179  // Compute size of all parameters.
3180  // Start with computing size of a pointer in number of bytes.
3181  // FIXME: There might(should) be a better way of doing this computation!
3182  SourceLocation Loc;
3183  int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
3184  // The first two arguments (self and _cmd) are pointers; account for
3185  // their size.
3186  int ParmOffset = 2 * PtrSize;
3187  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3188       E = Decl->param_end(); PI != E; ++PI) {
3189    QualType PType = (*PI)->getType();
3190    int sz = getObjCEncodingTypeSize(PType);
3191    assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
3192    ParmOffset += sz;
3193  }
3194  S += llvm::utostr(ParmOffset);
3195  S += "@0:";
3196  S += llvm::utostr(PtrSize);
3197
3198  // Argument types.
3199  ParmOffset = 2 * PtrSize;
3200  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3201       E = Decl->param_end(); PI != E; ++PI) {
3202    ParmVarDecl *PVDecl = *PI;
3203    QualType PType = PVDecl->getOriginalType();
3204    if (const ArrayType *AT =
3205          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3206      // Use array's original type only if it has known number of
3207      // elements.
3208      if (!isa<ConstantArrayType>(AT))
3209        PType = PVDecl->getType();
3210    } else if (PType->isFunctionType())
3211      PType = PVDecl->getType();
3212    // Process argument qualifiers for user supplied arguments; such as,
3213    // 'in', 'inout', etc.
3214    getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
3215    getObjCEncodingForType(PType, S);
3216    S += llvm::utostr(ParmOffset);
3217    ParmOffset += getObjCEncodingTypeSize(PType);
3218  }
3219}
3220
3221/// getObjCEncodingForPropertyDecl - Return the encoded type for this
3222/// property declaration. If non-NULL, Container must be either an
3223/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3224/// NULL when getting encodings for protocol properties.
3225/// Property attributes are stored as a comma-delimited C string. The simple
3226/// attributes readonly and bycopy are encoded as single characters. The
3227/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3228/// encoded as single characters, followed by an identifier. Property types
3229/// are also encoded as a parametrized attribute. The characters used to encode
3230/// these attributes are defined by the following enumeration:
3231/// @code
3232/// enum PropertyAttributes {
3233/// kPropertyReadOnly = 'R',   // property is read-only.
3234/// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
3235/// kPropertyByref = '&',  // property is a reference to the value last assigned
3236/// kPropertyDynamic = 'D',    // property is dynamic
3237/// kPropertyGetter = 'G',     // followed by getter selector name
3238/// kPropertySetter = 'S',     // followed by setter selector name
3239/// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
3240/// kPropertyType = 't'              // followed by old-style type encoding.
3241/// kPropertyWeak = 'W'              // 'weak' property
3242/// kPropertyStrong = 'P'            // property GC'able
3243/// kPropertyNonAtomic = 'N'         // property non-atomic
3244/// };
3245/// @endcode
3246void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
3247                                                const Decl *Container,
3248                                                std::string& S) {
3249  // Collect information from the property implementation decl(s).
3250  bool Dynamic = false;
3251  ObjCPropertyImplDecl *SynthesizePID = 0;
3252
3253  // FIXME: Duplicated code due to poor abstraction.
3254  if (Container) {
3255    if (const ObjCCategoryImplDecl *CID =
3256        dyn_cast<ObjCCategoryImplDecl>(Container)) {
3257      for (ObjCCategoryImplDecl::propimpl_iterator
3258             i = CID->propimpl_begin(), e = CID->propimpl_end();
3259           i != e; ++i) {
3260        ObjCPropertyImplDecl *PID = *i;
3261        if (PID->getPropertyDecl() == PD) {
3262          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3263            Dynamic = true;
3264          } else {
3265            SynthesizePID = PID;
3266          }
3267        }
3268      }
3269    } else {
3270      const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
3271      for (ObjCCategoryImplDecl::propimpl_iterator
3272             i = OID->propimpl_begin(), e = OID->propimpl_end();
3273           i != e; ++i) {
3274        ObjCPropertyImplDecl *PID = *i;
3275        if (PID->getPropertyDecl() == PD) {
3276          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3277            Dynamic = true;
3278          } else {
3279            SynthesizePID = PID;
3280          }
3281        }
3282      }
3283    }
3284  }
3285
3286  // FIXME: This is not very efficient.
3287  S = "T";
3288
3289  // Encode result type.
3290  // GCC has some special rules regarding encoding of properties which
3291  // closely resembles encoding of ivars.
3292  getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
3293                             true /* outermost type */,
3294                             true /* encoding for property */);
3295
3296  if (PD->isReadOnly()) {
3297    S += ",R";
3298  } else {
3299    switch (PD->getSetterKind()) {
3300    case ObjCPropertyDecl::Assign: break;
3301    case ObjCPropertyDecl::Copy:   S += ",C"; break;
3302    case ObjCPropertyDecl::Retain: S += ",&"; break;
3303    }
3304  }
3305
3306  // It really isn't clear at all what this means, since properties
3307  // are "dynamic by default".
3308  if (Dynamic)
3309    S += ",D";
3310
3311  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3312    S += ",N";
3313
3314  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3315    S += ",G";
3316    S += PD->getGetterName().getAsString();
3317  }
3318
3319  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3320    S += ",S";
3321    S += PD->getSetterName().getAsString();
3322  }
3323
3324  if (SynthesizePID) {
3325    const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3326    S += ",V";
3327    S += OID->getNameAsString();
3328  }
3329
3330  // FIXME: OBJCGC: weak & strong
3331}
3332
3333/// getLegacyIntegralTypeEncoding -
3334/// Another legacy compatibility encoding: 32-bit longs are encoded as
3335/// 'l' or 'L' , but not always.  For typedefs, we need to use
3336/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3337///
3338void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
3339  if (isa<TypedefType>(PointeeTy.getTypePtr())) {
3340    if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
3341      if (BT->getKind() == BuiltinType::ULong &&
3342          ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
3343        PointeeTy = UnsignedIntTy;
3344      else
3345        if (BT->getKind() == BuiltinType::Long &&
3346            ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
3347          PointeeTy = IntTy;
3348    }
3349  }
3350}
3351
3352void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
3353                                        const FieldDecl *Field) {
3354  // We follow the behavior of gcc, expanding structures which are
3355  // directly pointed to, and expanding embedded structures. Note that
3356  // these rules are sufficient to prevent recursive encoding of the
3357  // same type.
3358  getObjCEncodingForTypeImpl(T, S, true, true, Field,
3359                             true /* outermost type */);
3360}
3361
3362static void EncodeBitField(const ASTContext *Context, std::string& S,
3363                           const FieldDecl *FD) {
3364  const Expr *E = FD->getBitWidth();
3365  assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3366  ASTContext *Ctx = const_cast<ASTContext*>(Context);
3367  unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
3368  S += 'b';
3369  S += llvm::utostr(N);
3370}
3371
3372// FIXME: Use SmallString for accumulating string.
3373void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3374                                            bool ExpandPointedToStructures,
3375                                            bool ExpandStructures,
3376                                            const FieldDecl *FD,
3377                                            bool OutermostType,
3378                                            bool EncodingProperty) {
3379  if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
3380    if (FD && FD->isBitField())
3381      return EncodeBitField(this, S, FD);
3382    char encoding;
3383    switch (BT->getKind()) {
3384    default: assert(0 && "Unhandled builtin type kind");
3385    case BuiltinType::Void:       encoding = 'v'; break;
3386    case BuiltinType::Bool:       encoding = 'B'; break;
3387    case BuiltinType::Char_U:
3388    case BuiltinType::UChar:      encoding = 'C'; break;
3389    case BuiltinType::UShort:     encoding = 'S'; break;
3390    case BuiltinType::UInt:       encoding = 'I'; break;
3391    case BuiltinType::ULong:
3392        encoding =
3393          (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
3394        break;
3395    case BuiltinType::UInt128:    encoding = 'T'; break;
3396    case BuiltinType::ULongLong:  encoding = 'Q'; break;
3397    case BuiltinType::Char_S:
3398    case BuiltinType::SChar:      encoding = 'c'; break;
3399    case BuiltinType::Short:      encoding = 's'; break;
3400    case BuiltinType::Int:        encoding = 'i'; break;
3401    case BuiltinType::Long:
3402      encoding =
3403        (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
3404      break;
3405    case BuiltinType::LongLong:   encoding = 'q'; break;
3406    case BuiltinType::Int128:     encoding = 't'; break;
3407    case BuiltinType::Float:      encoding = 'f'; break;
3408    case BuiltinType::Double:     encoding = 'd'; break;
3409    case BuiltinType::LongDouble: encoding = 'd'; break;
3410    }
3411
3412    S += encoding;
3413    return;
3414  }
3415
3416  if (const ComplexType *CT = T->getAs<ComplexType>()) {
3417    S += 'j';
3418    getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
3419                               false);
3420    return;
3421  }
3422
3423  if (const PointerType *PT = T->getAs<PointerType>()) {
3424    if (PT->isObjCSelType()) {
3425      S += ':';
3426      return;
3427    }
3428    QualType PointeeTy = PT->getPointeeType();
3429
3430    bool isReadOnly = false;
3431    // For historical/compatibility reasons, the read-only qualifier of the
3432    // pointee gets emitted _before_ the '^'.  The read-only qualifier of
3433    // the pointer itself gets ignored, _unless_ we are looking at a typedef!
3434    // Also, do not emit the 'r' for anything but the outermost type!
3435    if (isa<TypedefType>(T.getTypePtr())) {
3436      if (OutermostType && T.isConstQualified()) {
3437        isReadOnly = true;
3438        S += 'r';
3439      }
3440    } else if (OutermostType) {
3441      QualType P = PointeeTy;
3442      while (P->getAs<PointerType>())
3443        P = P->getAs<PointerType>()->getPointeeType();
3444      if (P.isConstQualified()) {
3445        isReadOnly = true;
3446        S += 'r';
3447      }
3448    }
3449    if (isReadOnly) {
3450      // Another legacy compatibility encoding. Some ObjC qualifier and type
3451      // combinations need to be rearranged.
3452      // Rewrite "in const" from "nr" to "rn"
3453      const char * s = S.c_str();
3454      int len = S.length();
3455      if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3456        std::string replace = "rn";
3457        S.replace(S.end()-2, S.end(), replace);
3458      }
3459    }
3460
3461    if (PointeeTy->isCharType()) {
3462      // char pointer types should be encoded as '*' unless it is a
3463      // type that has been typedef'd to 'BOOL'.
3464      if (!isTypeTypedefedAsBOOL(PointeeTy)) {
3465        S += '*';
3466        return;
3467      }
3468    } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
3469      // GCC binary compat: Need to convert "struct objc_class *" to "#".
3470      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3471        S += '#';
3472        return;
3473      }
3474      // GCC binary compat: Need to convert "struct objc_object *" to "@".
3475      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3476        S += '@';
3477        return;
3478      }
3479      // fall through...
3480    }
3481    S += '^';
3482    getLegacyIntegralTypeEncoding(PointeeTy);
3483
3484    getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
3485                               NULL);
3486    return;
3487  }
3488
3489  if (const ArrayType *AT =
3490      // Ignore type qualifiers etc.
3491        dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
3492    if (isa<IncompleteArrayType>(AT)) {
3493      // Incomplete arrays are encoded as a pointer to the array element.
3494      S += '^';
3495
3496      getObjCEncodingForTypeImpl(AT->getElementType(), S,
3497                                 false, ExpandStructures, FD);
3498    } else {
3499      S += '[';
3500
3501      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3502        S += llvm::utostr(CAT->getSize().getZExtValue());
3503      else {
3504        //Variable length arrays are encoded as a regular array with 0 elements.
3505        assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3506        S += '0';
3507      }
3508
3509      getObjCEncodingForTypeImpl(AT->getElementType(), S,
3510                                 false, ExpandStructures, FD);
3511      S += ']';
3512    }
3513    return;
3514  }
3515
3516  if (T->getAs<FunctionType>()) {
3517    S += '?';
3518    return;
3519  }
3520
3521  if (const RecordType *RTy = T->getAs<RecordType>()) {
3522    RecordDecl *RDecl = RTy->getDecl();
3523    S += RDecl->isUnion() ? '(' : '{';
3524    // Anonymous structures print as '?'
3525    if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3526      S += II->getName();
3527    } else {
3528      S += '?';
3529    }
3530    if (ExpandStructures) {
3531      S += '=';
3532      for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3533                                   FieldEnd = RDecl->field_end();
3534           Field != FieldEnd; ++Field) {
3535        if (FD) {
3536          S += '"';
3537          S += Field->getNameAsString();
3538          S += '"';
3539        }
3540
3541        // Special case bit-fields.
3542        if (Field->isBitField()) {
3543          getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
3544                                     (*Field));
3545        } else {
3546          QualType qt = Field->getType();
3547          getLegacyIntegralTypeEncoding(qt);
3548          getObjCEncodingForTypeImpl(qt, S, false, true,
3549                                     FD);
3550        }
3551      }
3552    }
3553    S += RDecl->isUnion() ? ')' : '}';
3554    return;
3555  }
3556
3557  if (T->isEnumeralType()) {
3558    if (FD && FD->isBitField())
3559      EncodeBitField(this, S, FD);
3560    else
3561      S += 'i';
3562    return;
3563  }
3564
3565  if (T->isBlockPointerType()) {
3566    S += "@?"; // Unlike a pointer-to-function, which is "^?".
3567    return;
3568  }
3569
3570  if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
3571    // @encode(class_name)
3572    ObjCInterfaceDecl *OI = OIT->getDecl();
3573    S += '{';
3574    const IdentifierInfo *II = OI->getIdentifier();
3575    S += II->getName();
3576    S += '=';
3577    llvm::SmallVector<FieldDecl*, 32> RecFields;
3578    CollectObjCIvars(OI, RecFields);
3579    for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
3580      if (RecFields[i]->isBitField())
3581        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
3582                                   RecFields[i]);
3583      else
3584        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
3585                                   FD);
3586    }
3587    S += '}';
3588    return;
3589  }
3590
3591  if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
3592    if (OPT->isObjCIdType()) {
3593      S += '@';
3594      return;
3595    }
3596
3597    if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3598      // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3599      // Since this is a binary compatibility issue, need to consult with runtime
3600      // folks. Fortunately, this is a *very* obsure construct.
3601      S += '#';
3602      return;
3603    }
3604
3605    if (OPT->isObjCQualifiedIdType()) {
3606      getObjCEncodingForTypeImpl(getObjCIdType(), S,
3607                                 ExpandPointedToStructures,
3608                                 ExpandStructures, FD);
3609      if (FD || EncodingProperty) {
3610        // Note that we do extended encoding of protocol qualifer list
3611        // Only when doing ivar or property encoding.
3612        S += '"';
3613        for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3614             E = OPT->qual_end(); I != E; ++I) {
3615          S += '<';
3616          S += (*I)->getNameAsString();
3617          S += '>';
3618        }
3619        S += '"';
3620      }
3621      return;
3622    }
3623
3624    QualType PointeeTy = OPT->getPointeeType();
3625    if (!EncodingProperty &&
3626        isa<TypedefType>(PointeeTy.getTypePtr())) {
3627      // Another historical/compatibility reason.
3628      // We encode the underlying type which comes out as
3629      // {...};
3630      S += '^';
3631      getObjCEncodingForTypeImpl(PointeeTy, S,
3632                                 false, ExpandPointedToStructures,
3633                                 NULL);
3634      return;
3635    }
3636
3637    S += '@';
3638    if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
3639      S += '"';
3640      S += OPT->getInterfaceDecl()->getIdentifier()->getName();
3641      for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3642           E = OPT->qual_end(); I != E; ++I) {
3643        S += '<';
3644        S += (*I)->getNameAsString();
3645        S += '>';
3646      }
3647      S += '"';
3648    }
3649    return;
3650  }
3651
3652  assert(0 && "@encode for type not implemented!");
3653}
3654
3655void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
3656                                                 std::string& S) const {
3657  if (QT & Decl::OBJC_TQ_In)
3658    S += 'n';
3659  if (QT & Decl::OBJC_TQ_Inout)
3660    S += 'N';
3661  if (QT & Decl::OBJC_TQ_Out)
3662    S += 'o';
3663  if (QT & Decl::OBJC_TQ_Bycopy)
3664    S += 'O';
3665  if (QT & Decl::OBJC_TQ_Byref)
3666    S += 'R';
3667  if (QT & Decl::OBJC_TQ_Oneway)
3668    S += 'V';
3669}
3670
3671void ASTContext::setBuiltinVaListType(QualType T) {
3672  assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
3673
3674  BuiltinVaListType = T;
3675}
3676
3677void ASTContext::setObjCIdType(QualType T) {
3678  ObjCIdTypedefType = T;
3679}
3680
3681void ASTContext::setObjCSelType(QualType T) {
3682  ObjCSelTypedefType = T;
3683}
3684
3685void ASTContext::setObjCProtoType(QualType QT) {
3686  ObjCProtoType = QT;
3687}
3688
3689void ASTContext::setObjCClassType(QualType T) {
3690  ObjCClassTypedefType = T;
3691}
3692
3693void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
3694  assert(ObjCConstantStringType.isNull() &&
3695         "'NSConstantString' type already set!");
3696
3697  ObjCConstantStringType = getObjCInterfaceType(Decl);
3698}
3699
3700/// \brief Retrieve the template name that corresponds to a non-empty
3701/// lookup.
3702TemplateName ASTContext::getOverloadedTemplateName(NamedDecl * const *Begin,
3703                                                   NamedDecl * const *End) {
3704  unsigned size = End - Begin;
3705  assert(size > 1 && "set is not overloaded!");
3706
3707  void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3708                          size * sizeof(FunctionTemplateDecl*));
3709  OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3710
3711  NamedDecl **Storage = OT->getStorage();
3712  for (NamedDecl * const *I = Begin; I != End; ++I) {
3713    NamedDecl *D = *I;
3714    assert(isa<FunctionTemplateDecl>(D) ||
3715           (isa<UsingShadowDecl>(D) &&
3716            isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3717    *Storage++ = D;
3718  }
3719
3720  return TemplateName(OT);
3721}
3722
3723/// \brief Retrieve the template name that represents a qualified
3724/// template name such as \c std::vector.
3725TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
3726                                                  bool TemplateKeyword,
3727                                                  TemplateDecl *Template) {
3728  llvm::FoldingSetNodeID ID;
3729  QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3730
3731  void *InsertPos = 0;
3732  QualifiedTemplateName *QTN =
3733    QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3734  if (!QTN) {
3735    QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3736    QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3737  }
3738
3739  return TemplateName(QTN);
3740}
3741
3742/// \brief Retrieve the template name that represents a dependent
3743/// template name such as \c MetaFun::template apply.
3744TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3745                                                  const IdentifierInfo *Name) {
3746  assert((!NNS || NNS->isDependent()) &&
3747         "Nested name specifier must be dependent");
3748
3749  llvm::FoldingSetNodeID ID;
3750  DependentTemplateName::Profile(ID, NNS, Name);
3751
3752  void *InsertPos = 0;
3753  DependentTemplateName *QTN =
3754    DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3755
3756  if (QTN)
3757    return TemplateName(QTN);
3758
3759  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3760  if (CanonNNS == NNS) {
3761    QTN = new (*this,4) DependentTemplateName(NNS, Name);
3762  } else {
3763    TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3764    QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3765  }
3766
3767  DependentTemplateNames.InsertNode(QTN, InsertPos);
3768  return TemplateName(QTN);
3769}
3770
3771/// \brief Retrieve the template name that represents a dependent
3772/// template name such as \c MetaFun::template operator+.
3773TemplateName
3774ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3775                                     OverloadedOperatorKind Operator) {
3776  assert((!NNS || NNS->isDependent()) &&
3777         "Nested name specifier must be dependent");
3778
3779  llvm::FoldingSetNodeID ID;
3780  DependentTemplateName::Profile(ID, NNS, Operator);
3781
3782  void *InsertPos = 0;
3783  DependentTemplateName *QTN =
3784  DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3785
3786  if (QTN)
3787    return TemplateName(QTN);
3788
3789  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3790  if (CanonNNS == NNS) {
3791    QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3792  } else {
3793    TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3794    QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
3795  }
3796
3797  DependentTemplateNames.InsertNode(QTN, InsertPos);
3798  return TemplateName(QTN);
3799}
3800
3801/// getFromTargetType - Given one of the integer types provided by
3802/// TargetInfo, produce the corresponding type. The unsigned @p Type
3803/// is actually a value of type @c TargetInfo::IntType.
3804CanQualType ASTContext::getFromTargetType(unsigned Type) const {
3805  switch (Type) {
3806  case TargetInfo::NoInt: return CanQualType();
3807  case TargetInfo::SignedShort: return ShortTy;
3808  case TargetInfo::UnsignedShort: return UnsignedShortTy;
3809  case TargetInfo::SignedInt: return IntTy;
3810  case TargetInfo::UnsignedInt: return UnsignedIntTy;
3811  case TargetInfo::SignedLong: return LongTy;
3812  case TargetInfo::UnsignedLong: return UnsignedLongTy;
3813  case TargetInfo::SignedLongLong: return LongLongTy;
3814  case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3815  }
3816
3817  assert(false && "Unhandled TargetInfo::IntType value");
3818  return CanQualType();
3819}
3820
3821//===----------------------------------------------------------------------===//
3822//                        Type Predicates.
3823//===----------------------------------------------------------------------===//
3824
3825/// isObjCNSObjectType - Return true if this is an NSObject object using
3826/// NSObject attribute on a c-style pointer type.
3827/// FIXME - Make it work directly on types.
3828/// FIXME: Move to Type.
3829///
3830bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3831  if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3832    if (TypedefDecl *TD = TDT->getDecl())
3833      if (TD->getAttr<ObjCNSObjectAttr>())
3834        return true;
3835  }
3836  return false;
3837}
3838
3839/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3840/// garbage collection attribute.
3841///
3842Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3843  Qualifiers::GC GCAttrs = Qualifiers::GCNone;
3844  if (getLangOptions().ObjC1 &&
3845      getLangOptions().getGCMode() != LangOptions::NonGC) {
3846    GCAttrs = Ty.getObjCGCAttr();
3847    // Default behavious under objective-c's gc is for objective-c pointers
3848    // (or pointers to them) be treated as though they were declared
3849    // as __strong.
3850    if (GCAttrs == Qualifiers::GCNone) {
3851      if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
3852        GCAttrs = Qualifiers::Strong;
3853      else if (Ty->isPointerType())
3854        return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
3855    }
3856    // Non-pointers have none gc'able attribute regardless of the attribute
3857    // set on them.
3858    else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
3859      return Qualifiers::GCNone;
3860  }
3861  return GCAttrs;
3862}
3863
3864//===----------------------------------------------------------------------===//
3865//                        Type Compatibility Testing
3866//===----------------------------------------------------------------------===//
3867
3868/// areCompatVectorTypes - Return true if the two specified vector types are
3869/// compatible.
3870static bool areCompatVectorTypes(const VectorType *LHS,
3871                                 const VectorType *RHS) {
3872  assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
3873  return LHS->getElementType() == RHS->getElementType() &&
3874         LHS->getNumElements() == RHS->getNumElements();
3875}
3876
3877//===----------------------------------------------------------------------===//
3878// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3879//===----------------------------------------------------------------------===//
3880
3881/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3882/// inheritance hierarchy of 'rProto'.
3883bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3884                                                ObjCProtocolDecl *rProto) {
3885  if (lProto == rProto)
3886    return true;
3887  for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3888       E = rProto->protocol_end(); PI != E; ++PI)
3889    if (ProtocolCompatibleWithProtocol(lProto, *PI))
3890      return true;
3891  return false;
3892}
3893
3894/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3895/// return true if lhs's protocols conform to rhs's protocol; false
3896/// otherwise.
3897bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3898  if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3899    return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3900  return false;
3901}
3902
3903/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3904/// ObjCQualifiedIDType.
3905bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3906                                                   bool compare) {
3907  // Allow id<P..> and an 'id' or void* type in all cases.
3908  if (lhs->isVoidPointerType() ||
3909      lhs->isObjCIdType() || lhs->isObjCClassType())
3910    return true;
3911  else if (rhs->isVoidPointerType() ||
3912           rhs->isObjCIdType() || rhs->isObjCClassType())
3913    return true;
3914
3915  if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
3916    const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
3917
3918    if (!rhsOPT) return false;
3919
3920    if (rhsOPT->qual_empty()) {
3921      // If the RHS is a unqualified interface pointer "NSString*",
3922      // make sure we check the class hierarchy.
3923      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3924        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3925             E = lhsQID->qual_end(); I != E; ++I) {
3926          // when comparing an id<P> on lhs with a static type on rhs,
3927          // see if static class implements all of id's protocols, directly or
3928          // through its super class and categories.
3929          if (!rhsID->ClassImplementsProtocol(*I, true))
3930            return false;
3931        }
3932      }
3933      // If there are no qualifiers and no interface, we have an 'id'.
3934      return true;
3935    }
3936    // Both the right and left sides have qualifiers.
3937    for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3938         E = lhsQID->qual_end(); I != E; ++I) {
3939      ObjCProtocolDecl *lhsProto = *I;
3940      bool match = false;
3941
3942      // when comparing an id<P> on lhs with a static type on rhs,
3943      // see if static class implements all of id's protocols, directly or
3944      // through its super class and categories.
3945      for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
3946           E = rhsOPT->qual_end(); J != E; ++J) {
3947        ObjCProtocolDecl *rhsProto = *J;
3948        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3949            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3950          match = true;
3951          break;
3952        }
3953      }
3954      // If the RHS is a qualified interface pointer "NSString<P>*",
3955      // make sure we check the class hierarchy.
3956      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3957        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3958             E = lhsQID->qual_end(); I != E; ++I) {
3959          // when comparing an id<P> on lhs with a static type on rhs,
3960          // see if static class implements all of id's protocols, directly or
3961          // through its super class and categories.
3962          if (rhsID->ClassImplementsProtocol(*I, true)) {
3963            match = true;
3964            break;
3965          }
3966        }
3967      }
3968      if (!match)
3969        return false;
3970    }
3971
3972    return true;
3973  }
3974
3975  const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
3976  assert(rhsQID && "One of the LHS/RHS should be id<x>");
3977
3978  if (const ObjCObjectPointerType *lhsOPT =
3979        lhs->getAsObjCInterfacePointerType()) {
3980    if (lhsOPT->qual_empty()) {
3981      bool match = false;
3982      if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
3983        for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
3984             E = rhsQID->qual_end(); I != E; ++I) {
3985          // when comparing an id<P> on lhs with a static type on rhs,
3986          // see if static class implements all of id's protocols, directly or
3987          // through its super class and categories.
3988          if (lhsID->ClassImplementsProtocol(*I, true)) {
3989            match = true;
3990            break;
3991          }
3992        }
3993        if (!match)
3994          return false;
3995      }
3996      return true;
3997    }
3998    // Both the right and left sides have qualifiers.
3999    for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4000         E = lhsOPT->qual_end(); I != E; ++I) {
4001      ObjCProtocolDecl *lhsProto = *I;
4002      bool match = false;
4003
4004      // when comparing an id<P> on lhs with a static type on rhs,
4005      // see if static class implements all of id's protocols, directly or
4006      // through its super class and categories.
4007      for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4008           E = rhsQID->qual_end(); J != E; ++J) {
4009        ObjCProtocolDecl *rhsProto = *J;
4010        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4011            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4012          match = true;
4013          break;
4014        }
4015      }
4016      if (!match)
4017        return false;
4018    }
4019    return true;
4020  }
4021  return false;
4022}
4023
4024/// canAssignObjCInterfaces - Return true if the two interface types are
4025/// compatible for assignment from RHS to LHS.  This handles validation of any
4026/// protocol qualifiers on the LHS or RHS.
4027///
4028bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4029                                         const ObjCObjectPointerType *RHSOPT) {
4030  // If either type represents the built-in 'id' or 'Class' types, return true.
4031  if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
4032    return true;
4033
4034  if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
4035    return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4036                                             QualType(RHSOPT,0),
4037                                             false);
4038
4039  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4040  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4041  if (LHS && RHS) // We have 2 user-defined types.
4042    return canAssignObjCInterfaces(LHS, RHS);
4043
4044  return false;
4045}
4046
4047/// getIntersectionOfProtocols - This routine finds the intersection of set
4048/// of protocols inherited from two distinct objective-c pointer objects.
4049/// It is used to build composite qualifier list of the composite type of
4050/// the conditional expression involving two objective-c pointer objects.
4051static
4052void getIntersectionOfProtocols(ASTContext &Context,
4053                                const ObjCObjectPointerType *LHSOPT,
4054                                const ObjCObjectPointerType *RHSOPT,
4055      llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4056
4057  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4058  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4059
4060  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4061  unsigned LHSNumProtocols = LHS->getNumProtocols();
4062  if (LHSNumProtocols > 0)
4063    InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4064  else {
4065    llvm::SmallVector<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4066     Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
4067    InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4068                                LHSInheritedProtocols.end());
4069  }
4070
4071  unsigned RHSNumProtocols = RHS->getNumProtocols();
4072  if (RHSNumProtocols > 0) {
4073    ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4074    for (unsigned i = 0; i < RHSNumProtocols; ++i)
4075      if (InheritedProtocolSet.count(RHSProtocols[i]))
4076        IntersectionOfProtocols.push_back(RHSProtocols[i]);
4077  }
4078  else {
4079    llvm::SmallVector<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
4080    Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
4081    // FIXME. This may cause duplication of protocols in the list, but should
4082    // be harmless.
4083    for (unsigned i = 0, len = RHSInheritedProtocols.size(); i < len; ++i)
4084      if (InheritedProtocolSet.count(RHSInheritedProtocols[i]))
4085        IntersectionOfProtocols.push_back(RHSInheritedProtocols[i]);
4086  }
4087}
4088
4089/// areCommonBaseCompatible - Returns common base class of the two classes if
4090/// one found. Note that this is O'2 algorithm. But it will be called as the
4091/// last type comparison in a ?-exp of ObjC pointer types before a
4092/// warning is issued. So, its invokation is extremely rare.
4093QualType ASTContext::areCommonBaseCompatible(
4094                                          const ObjCObjectPointerType *LHSOPT,
4095                                          const ObjCObjectPointerType *RHSOPT) {
4096  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4097  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4098  if (!LHS || !RHS)
4099    return QualType();
4100
4101  while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4102    QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4103    LHS = LHSTy->getAs<ObjCInterfaceType>();
4104    if (canAssignObjCInterfaces(LHS, RHS)) {
4105      llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4106      getIntersectionOfProtocols(*this,
4107                                 LHSOPT, RHSOPT, IntersectionOfProtocols);
4108      if (IntersectionOfProtocols.empty())
4109        LHSTy = getObjCObjectPointerType(LHSTy);
4110      else
4111        LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4112                                                IntersectionOfProtocols.size());
4113      return LHSTy;
4114    }
4115  }
4116
4117  return QualType();
4118}
4119
4120bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4121                                         const ObjCInterfaceType *RHS) {
4122  // Verify that the base decls are compatible: the RHS must be a subclass of
4123  // the LHS.
4124  if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4125    return false;
4126
4127  // RHS must have a superset of the protocols in the LHS.  If the LHS is not
4128  // protocol qualified at all, then we are good.
4129  if (LHS->getNumProtocols() == 0)
4130    return true;
4131
4132  // Okay, we know the LHS has protocol qualifiers.  If the RHS doesn't, then it
4133  // isn't a superset.
4134  if (RHS->getNumProtocols() == 0)
4135    return true;  // FIXME: should return false!
4136
4137  for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4138                                        LHSPE = LHS->qual_end();
4139       LHSPI != LHSPE; LHSPI++) {
4140    bool RHSImplementsProtocol = false;
4141
4142    // If the RHS doesn't implement the protocol on the left, the types
4143    // are incompatible.
4144    for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
4145                                          RHSPE = RHS->qual_end();
4146         RHSPI != RHSPE; RHSPI++) {
4147      if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
4148        RHSImplementsProtocol = true;
4149        break;
4150      }
4151    }
4152    // FIXME: For better diagnostics, consider passing back the protocol name.
4153    if (!RHSImplementsProtocol)
4154      return false;
4155  }
4156  // The RHS implements all protocols listed on the LHS.
4157  return true;
4158}
4159
4160bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4161  // get the "pointed to" types
4162  const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4163  const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
4164
4165  if (!LHSOPT || !RHSOPT)
4166    return false;
4167
4168  return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4169         canAssignObjCInterfaces(RHSOPT, LHSOPT);
4170}
4171
4172/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
4173/// both shall have the identically qualified version of a compatible type.
4174/// C99 6.2.7p1: Two types have compatible types if their types are the
4175/// same. See 6.7.[2,3,5] for additional rules.
4176bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
4177  return !mergeTypes(LHS, RHS).isNull();
4178}
4179
4180QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
4181  const FunctionType *lbase = lhs->getAs<FunctionType>();
4182  const FunctionType *rbase = rhs->getAs<FunctionType>();
4183  const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4184  const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
4185  bool allLTypes = true;
4186  bool allRTypes = true;
4187
4188  // Check return type
4189  QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
4190  if (retType.isNull()) return QualType();
4191  if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
4192    allLTypes = false;
4193  if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
4194    allRTypes = false;
4195  // FIXME: double check this
4196  bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4197  if (NoReturn != lbase->getNoReturnAttr())
4198    allLTypes = false;
4199  if (NoReturn != rbase->getNoReturnAttr())
4200    allRTypes = false;
4201
4202  if (lproto && rproto) { // two C99 style function prototypes
4203    assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4204           "C++ shouldn't be here");
4205    unsigned lproto_nargs = lproto->getNumArgs();
4206    unsigned rproto_nargs = rproto->getNumArgs();
4207
4208    // Compatible functions must have the same number of arguments
4209    if (lproto_nargs != rproto_nargs)
4210      return QualType();
4211
4212    // Variadic and non-variadic functions aren't compatible
4213    if (lproto->isVariadic() != rproto->isVariadic())
4214      return QualType();
4215
4216    if (lproto->getTypeQuals() != rproto->getTypeQuals())
4217      return QualType();
4218
4219    // Check argument compatibility
4220    llvm::SmallVector<QualType, 10> types;
4221    for (unsigned i = 0; i < lproto_nargs; i++) {
4222      QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4223      QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4224      QualType argtype = mergeTypes(largtype, rargtype);
4225      if (argtype.isNull()) return QualType();
4226      types.push_back(argtype);
4227      if (getCanonicalType(argtype) != getCanonicalType(largtype))
4228        allLTypes = false;
4229      if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4230        allRTypes = false;
4231    }
4232    if (allLTypes) return lhs;
4233    if (allRTypes) return rhs;
4234    return getFunctionType(retType, types.begin(), types.size(),
4235                           lproto->isVariadic(), lproto->getTypeQuals(),
4236                           NoReturn);
4237  }
4238
4239  if (lproto) allRTypes = false;
4240  if (rproto) allLTypes = false;
4241
4242  const FunctionProtoType *proto = lproto ? lproto : rproto;
4243  if (proto) {
4244    assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
4245    if (proto->isVariadic()) return QualType();
4246    // Check that the types are compatible with the types that
4247    // would result from default argument promotions (C99 6.7.5.3p15).
4248    // The only types actually affected are promotable integer
4249    // types and floats, which would be passed as a different
4250    // type depending on whether the prototype is visible.
4251    unsigned proto_nargs = proto->getNumArgs();
4252    for (unsigned i = 0; i < proto_nargs; ++i) {
4253      QualType argTy = proto->getArgType(i);
4254      if (argTy->isPromotableIntegerType() ||
4255          getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4256        return QualType();
4257    }
4258
4259    if (allLTypes) return lhs;
4260    if (allRTypes) return rhs;
4261    return getFunctionType(retType, proto->arg_type_begin(),
4262                           proto->getNumArgs(), proto->isVariadic(),
4263                           proto->getTypeQuals(), NoReturn);
4264  }
4265
4266  if (allLTypes) return lhs;
4267  if (allRTypes) return rhs;
4268  return getFunctionNoProtoType(retType, NoReturn);
4269}
4270
4271QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
4272  // C++ [expr]: If an expression initially has the type "reference to T", the
4273  // type is adjusted to "T" prior to any further analysis, the expression
4274  // designates the object or function denoted by the reference, and the
4275  // expression is an lvalue unless the reference is an rvalue reference and
4276  // the expression is a function call (possibly inside parentheses).
4277  // FIXME: C++ shouldn't be going through here!  The rules are different
4278  // enough that they should be handled separately.
4279  // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
4280  // shouldn't be going through here!
4281  if (const ReferenceType *RT = LHS->getAs<ReferenceType>())
4282    LHS = RT->getPointeeType();
4283  if (const ReferenceType *RT = RHS->getAs<ReferenceType>())
4284    RHS = RT->getPointeeType();
4285
4286  QualType LHSCan = getCanonicalType(LHS),
4287           RHSCan = getCanonicalType(RHS);
4288
4289  // If two types are identical, they are compatible.
4290  if (LHSCan == RHSCan)
4291    return LHS;
4292
4293  // If the qualifiers are different, the types aren't compatible... mostly.
4294  Qualifiers LQuals = LHSCan.getLocalQualifiers();
4295  Qualifiers RQuals = RHSCan.getLocalQualifiers();
4296  if (LQuals != RQuals) {
4297    // If any of these qualifiers are different, we have a type
4298    // mismatch.
4299    if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4300        LQuals.getAddressSpace() != RQuals.getAddressSpace())
4301      return QualType();
4302
4303    // Exactly one GC qualifier difference is allowed: __strong is
4304    // okay if the other type has no GC qualifier but is an Objective
4305    // C object pointer (i.e. implicitly strong by default).  We fix
4306    // this by pretending that the unqualified type was actually
4307    // qualified __strong.
4308    Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4309    Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4310    assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4311
4312    if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4313      return QualType();
4314
4315    if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4316      return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4317    }
4318    if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4319      return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4320    }
4321    return QualType();
4322  }
4323
4324  // Okay, qualifiers are equal.
4325
4326  Type::TypeClass LHSClass = LHSCan->getTypeClass();
4327  Type::TypeClass RHSClass = RHSCan->getTypeClass();
4328
4329  // We want to consider the two function types to be the same for these
4330  // comparisons, just force one to the other.
4331  if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4332  if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
4333
4334  // Same as above for arrays
4335  if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4336    LHSClass = Type::ConstantArray;
4337  if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4338    RHSClass = Type::ConstantArray;
4339
4340  // Canonicalize ExtVector -> Vector.
4341  if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4342  if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
4343
4344  // If the canonical type classes don't match.
4345  if (LHSClass != RHSClass) {
4346    // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
4347    // a signed integer type, or an unsigned integer type.
4348    // Compatibility is based on the underlying type, not the promotion
4349    // type.
4350    if (const EnumType* ETy = LHS->getAs<EnumType>()) {
4351      if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4352        return RHS;
4353    }
4354    if (const EnumType* ETy = RHS->getAs<EnumType>()) {
4355      if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4356        return LHS;
4357    }
4358
4359    return QualType();
4360  }
4361
4362  // The canonical type classes match.
4363  switch (LHSClass) {
4364#define TYPE(Class, Base)
4365#define ABSTRACT_TYPE(Class, Base)
4366#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4367#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4368#include "clang/AST/TypeNodes.def"
4369    assert(false && "Non-canonical and dependent types shouldn't get here");
4370    return QualType();
4371
4372  case Type::LValueReference:
4373  case Type::RValueReference:
4374  case Type::MemberPointer:
4375    assert(false && "C++ should never be in mergeTypes");
4376    return QualType();
4377
4378  case Type::IncompleteArray:
4379  case Type::VariableArray:
4380  case Type::FunctionProto:
4381  case Type::ExtVector:
4382    assert(false && "Types are eliminated above");
4383    return QualType();
4384
4385  case Type::Pointer:
4386  {
4387    // Merge two pointer types, while trying to preserve typedef info
4388    QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4389    QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
4390    QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4391    if (ResultType.isNull()) return QualType();
4392    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4393      return LHS;
4394    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4395      return RHS;
4396    return getPointerType(ResultType);
4397  }
4398  case Type::BlockPointer:
4399  {
4400    // Merge two block pointer types, while trying to preserve typedef info
4401    QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4402    QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
4403    QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4404    if (ResultType.isNull()) return QualType();
4405    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4406      return LHS;
4407    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4408      return RHS;
4409    return getBlockPointerType(ResultType);
4410  }
4411  case Type::ConstantArray:
4412  {
4413    const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4414    const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4415    if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4416      return QualType();
4417
4418    QualType LHSElem = getAsArrayType(LHS)->getElementType();
4419    QualType RHSElem = getAsArrayType(RHS)->getElementType();
4420    QualType ResultType = mergeTypes(LHSElem, RHSElem);
4421    if (ResultType.isNull()) return QualType();
4422    if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4423      return LHS;
4424    if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4425      return RHS;
4426    if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4427                                          ArrayType::ArraySizeModifier(), 0);
4428    if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4429                                          ArrayType::ArraySizeModifier(), 0);
4430    const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4431    const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
4432    if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4433      return LHS;
4434    if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4435      return RHS;
4436    if (LVAT) {
4437      // FIXME: This isn't correct! But tricky to implement because
4438      // the array's size has to be the size of LHS, but the type
4439      // has to be different.
4440      return LHS;
4441    }
4442    if (RVAT) {
4443      // FIXME: This isn't correct! But tricky to implement because
4444      // the array's size has to be the size of RHS, but the type
4445      // has to be different.
4446      return RHS;
4447    }
4448    if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4449    if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
4450    return getIncompleteArrayType(ResultType,
4451                                  ArrayType::ArraySizeModifier(), 0);
4452  }
4453  case Type::FunctionNoProto:
4454    return mergeFunctionTypes(LHS, RHS);
4455  case Type::Record:
4456  case Type::Enum:
4457    return QualType();
4458  case Type::Builtin:
4459    // Only exactly equal builtin types are compatible, which is tested above.
4460    return QualType();
4461  case Type::Complex:
4462    // Distinct complex types are incompatible.
4463    return QualType();
4464  case Type::Vector:
4465    // FIXME: The merged type should be an ExtVector!
4466    if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
4467      return LHS;
4468    return QualType();
4469  case Type::ObjCInterface: {
4470    // Check if the interfaces are assignment compatible.
4471    // FIXME: This should be type compatibility, e.g. whether
4472    // "LHS x; RHS x;" at global scope is legal.
4473    const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4474    const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
4475    if (LHSIface && RHSIface &&
4476        canAssignObjCInterfaces(LHSIface, RHSIface))
4477      return LHS;
4478
4479    return QualType();
4480  }
4481  case Type::ObjCObjectPointer: {
4482    if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4483                                RHS->getAs<ObjCObjectPointerType>()))
4484      return LHS;
4485
4486    return QualType();
4487  }
4488  case Type::TemplateSpecialization:
4489    assert(false && "Dependent types have no size");
4490    break;
4491  }
4492
4493  return QualType();
4494}
4495
4496//===----------------------------------------------------------------------===//
4497//                         Integer Predicates
4498//===----------------------------------------------------------------------===//
4499
4500unsigned ASTContext::getIntWidth(QualType T) {
4501  if (T->isBooleanType())
4502    return 1;
4503  if (EnumType *ET = dyn_cast<EnumType>(T))
4504    T = ET->getDecl()->getIntegerType();
4505  // For builtin types, just use the standard type sizing method
4506  return (unsigned)getTypeSize(T);
4507}
4508
4509QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4510  assert(T->isSignedIntegerType() && "Unexpected type");
4511
4512  // Turn <4 x signed int> -> <4 x unsigned int>
4513  if (const VectorType *VTy = T->getAs<VectorType>())
4514    return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
4515                         VTy->getNumElements());
4516
4517  // For enums, we return the unsigned version of the base type.
4518  if (const EnumType *ETy = T->getAs<EnumType>())
4519    T = ETy->getDecl()->getIntegerType();
4520
4521  const BuiltinType *BTy = T->getAs<BuiltinType>();
4522  assert(BTy && "Unexpected signed integer type");
4523  switch (BTy->getKind()) {
4524  case BuiltinType::Char_S:
4525  case BuiltinType::SChar:
4526    return UnsignedCharTy;
4527  case BuiltinType::Short:
4528    return UnsignedShortTy;
4529  case BuiltinType::Int:
4530    return UnsignedIntTy;
4531  case BuiltinType::Long:
4532    return UnsignedLongTy;
4533  case BuiltinType::LongLong:
4534    return UnsignedLongLongTy;
4535  case BuiltinType::Int128:
4536    return UnsignedInt128Ty;
4537  default:
4538    assert(0 && "Unexpected signed integer type");
4539    return QualType();
4540  }
4541}
4542
4543ExternalASTSource::~ExternalASTSource() { }
4544
4545void ExternalASTSource::PrintStats() { }
4546
4547
4548//===----------------------------------------------------------------------===//
4549//                          Builtin Type Computation
4550//===----------------------------------------------------------------------===//
4551
4552/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4553/// pointer over the consumed characters.  This returns the resultant type.
4554static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
4555                                  ASTContext::GetBuiltinTypeError &Error,
4556                                  bool AllowTypeModifiers = true) {
4557  // Modifiers.
4558  int HowLong = 0;
4559  bool Signed = false, Unsigned = false;
4560
4561  // Read the modifiers first.
4562  bool Done = false;
4563  while (!Done) {
4564    switch (*Str++) {
4565    default: Done = true; --Str; break;
4566    case 'S':
4567      assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4568      assert(!Signed && "Can't use 'S' modifier multiple times!");
4569      Signed = true;
4570      break;
4571    case 'U':
4572      assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4573      assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4574      Unsigned = true;
4575      break;
4576    case 'L':
4577      assert(HowLong <= 2 && "Can't have LLLL modifier");
4578      ++HowLong;
4579      break;
4580    }
4581  }
4582
4583  QualType Type;
4584
4585  // Read the base type.
4586  switch (*Str++) {
4587  default: assert(0 && "Unknown builtin type letter!");
4588  case 'v':
4589    assert(HowLong == 0 && !Signed && !Unsigned &&
4590           "Bad modifiers used with 'v'!");
4591    Type = Context.VoidTy;
4592    break;
4593  case 'f':
4594    assert(HowLong == 0 && !Signed && !Unsigned &&
4595           "Bad modifiers used with 'f'!");
4596    Type = Context.FloatTy;
4597    break;
4598  case 'd':
4599    assert(HowLong < 2 && !Signed && !Unsigned &&
4600           "Bad modifiers used with 'd'!");
4601    if (HowLong)
4602      Type = Context.LongDoubleTy;
4603    else
4604      Type = Context.DoubleTy;
4605    break;
4606  case 's':
4607    assert(HowLong == 0 && "Bad modifiers used with 's'!");
4608    if (Unsigned)
4609      Type = Context.UnsignedShortTy;
4610    else
4611      Type = Context.ShortTy;
4612    break;
4613  case 'i':
4614    if (HowLong == 3)
4615      Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4616    else if (HowLong == 2)
4617      Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4618    else if (HowLong == 1)
4619      Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4620    else
4621      Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4622    break;
4623  case 'c':
4624    assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4625    if (Signed)
4626      Type = Context.SignedCharTy;
4627    else if (Unsigned)
4628      Type = Context.UnsignedCharTy;
4629    else
4630      Type = Context.CharTy;
4631    break;
4632  case 'b': // boolean
4633    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4634    Type = Context.BoolTy;
4635    break;
4636  case 'z':  // size_t.
4637    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4638    Type = Context.getSizeType();
4639    break;
4640  case 'F':
4641    Type = Context.getCFConstantStringType();
4642    break;
4643  case 'a':
4644    Type = Context.getBuiltinVaListType();
4645    assert(!Type.isNull() && "builtin va list type not initialized!");
4646    break;
4647  case 'A':
4648    // This is a "reference" to a va_list; however, what exactly
4649    // this means depends on how va_list is defined. There are two
4650    // different kinds of va_list: ones passed by value, and ones
4651    // passed by reference.  An example of a by-value va_list is
4652    // x86, where va_list is a char*. An example of by-ref va_list
4653    // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4654    // we want this argument to be a char*&; for x86-64, we want
4655    // it to be a __va_list_tag*.
4656    Type = Context.getBuiltinVaListType();
4657    assert(!Type.isNull() && "builtin va list type not initialized!");
4658    if (Type->isArrayType()) {
4659      Type = Context.getArrayDecayedType(Type);
4660    } else {
4661      Type = Context.getLValueReferenceType(Type);
4662    }
4663    break;
4664  case 'V': {
4665    char *End;
4666    unsigned NumElements = strtoul(Str, &End, 10);
4667    assert(End != Str && "Missing vector size");
4668
4669    Str = End;
4670
4671    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4672    Type = Context.getVectorType(ElementType, NumElements);
4673    break;
4674  }
4675  case 'X': {
4676    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4677    Type = Context.getComplexType(ElementType);
4678    break;
4679  }
4680  case 'P':
4681    Type = Context.getFILEType();
4682    if (Type.isNull()) {
4683      Error = ASTContext::GE_Missing_stdio;
4684      return QualType();
4685    }
4686    break;
4687  case 'J':
4688    if (Signed)
4689      Type = Context.getsigjmp_bufType();
4690    else
4691      Type = Context.getjmp_bufType();
4692
4693    if (Type.isNull()) {
4694      Error = ASTContext::GE_Missing_setjmp;
4695      return QualType();
4696    }
4697    break;
4698  }
4699
4700  if (!AllowTypeModifiers)
4701    return Type;
4702
4703  Done = false;
4704  while (!Done) {
4705    switch (*Str++) {
4706      default: Done = true; --Str; break;
4707      case '*':
4708        Type = Context.getPointerType(Type);
4709        break;
4710      case '&':
4711        Type = Context.getLValueReferenceType(Type);
4712        break;
4713      // FIXME: There's no way to have a built-in with an rvalue ref arg.
4714      case 'C':
4715        Type = Type.withConst();
4716        break;
4717    }
4718  }
4719
4720  return Type;
4721}
4722
4723/// GetBuiltinType - Return the type for the specified builtin.
4724QualType ASTContext::GetBuiltinType(unsigned id,
4725                                    GetBuiltinTypeError &Error) {
4726  const char *TypeStr = BuiltinInfo.GetTypeString(id);
4727
4728  llvm::SmallVector<QualType, 8> ArgTypes;
4729
4730  Error = GE_None;
4731  QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4732  if (Error != GE_None)
4733    return QualType();
4734  while (TypeStr[0] && TypeStr[0] != '.') {
4735    QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4736    if (Error != GE_None)
4737      return QualType();
4738
4739    // Do array -> pointer decay.  The builtin should use the decayed type.
4740    if (Ty->isArrayType())
4741      Ty = getArrayDecayedType(Ty);
4742
4743    ArgTypes.push_back(Ty);
4744  }
4745
4746  assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4747         "'.' should only occur at end of builtin type list!");
4748
4749  // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4750  if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4751    return getFunctionNoProtoType(ResType);
4752  return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4753                         TypeStr[0] == '.', 0);
4754}
4755
4756QualType
4757ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4758  // Perform the usual unary conversions. We do this early so that
4759  // integral promotions to "int" can allow us to exit early, in the
4760  // lhs == rhs check. Also, for conversion purposes, we ignore any
4761  // qualifiers.  For example, "const float" and "float" are
4762  // equivalent.
4763  if (lhs->isPromotableIntegerType())
4764    lhs = getPromotedIntegerType(lhs);
4765  else
4766    lhs = lhs.getUnqualifiedType();
4767  if (rhs->isPromotableIntegerType())
4768    rhs = getPromotedIntegerType(rhs);
4769  else
4770    rhs = rhs.getUnqualifiedType();
4771
4772  // If both types are identical, no conversion is needed.
4773  if (lhs == rhs)
4774    return lhs;
4775
4776  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4777  // The caller can deal with this (e.g. pointer + int).
4778  if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4779    return lhs;
4780
4781  // At this point, we have two different arithmetic types.
4782
4783  // Handle complex types first (C99 6.3.1.8p1).
4784  if (lhs->isComplexType() || rhs->isComplexType()) {
4785    // if we have an integer operand, the result is the complex type.
4786    if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
4787      // convert the rhs to the lhs complex type.
4788      return lhs;
4789    }
4790    if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
4791      // convert the lhs to the rhs complex type.
4792      return rhs;
4793    }
4794    // This handles complex/complex, complex/float, or float/complex.
4795    // When both operands are complex, the shorter operand is converted to the
4796    // type of the longer, and that is the type of the result. This corresponds
4797    // to what is done when combining two real floating-point operands.
4798    // The fun begins when size promotion occur across type domains.
4799    // From H&S 6.3.4: When one operand is complex and the other is a real
4800    // floating-point type, the less precise type is converted, within it's
4801    // real or complex domain, to the precision of the other type. For example,
4802    // when combining a "long double" with a "double _Complex", the
4803    // "double _Complex" is promoted to "long double _Complex".
4804    int result = getFloatingTypeOrder(lhs, rhs);
4805
4806    if (result > 0) { // The left side is bigger, convert rhs.
4807      rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
4808    } else if (result < 0) { // The right side is bigger, convert lhs.
4809      lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
4810    }
4811    // At this point, lhs and rhs have the same rank/size. Now, make sure the
4812    // domains match. This is a requirement for our implementation, C99
4813    // does not require this promotion.
4814    if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4815      if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4816        return rhs;
4817      } else { // handle "_Complex double, double".
4818        return lhs;
4819      }
4820    }
4821    return lhs; // The domain/size match exactly.
4822  }
4823  // Now handle "real" floating types (i.e. float, double, long double).
4824  if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4825    // if we have an integer operand, the result is the real floating type.
4826    if (rhs->isIntegerType()) {
4827      // convert rhs to the lhs floating point type.
4828      return lhs;
4829    }
4830    if (rhs->isComplexIntegerType()) {
4831      // convert rhs to the complex floating point type.
4832      return getComplexType(lhs);
4833    }
4834    if (lhs->isIntegerType()) {
4835      // convert lhs to the rhs floating point type.
4836      return rhs;
4837    }
4838    if (lhs->isComplexIntegerType()) {
4839      // convert lhs to the complex floating point type.
4840      return getComplexType(rhs);
4841    }
4842    // We have two real floating types, float/complex combos were handled above.
4843    // Convert the smaller operand to the bigger result.
4844    int result = getFloatingTypeOrder(lhs, rhs);
4845    if (result > 0) // convert the rhs
4846      return lhs;
4847    assert(result < 0 && "illegal float comparison");
4848    return rhs;   // convert the lhs
4849  }
4850  if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
4851    // Handle GCC complex int extension.
4852    const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
4853    const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
4854
4855    if (lhsComplexInt && rhsComplexInt) {
4856      if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
4857                              rhsComplexInt->getElementType()) >= 0)
4858        return lhs; // convert the rhs
4859      return rhs;
4860    } else if (lhsComplexInt && rhs->isIntegerType()) {
4861      // convert the rhs to the lhs complex type.
4862      return lhs;
4863    } else if (rhsComplexInt && lhs->isIntegerType()) {
4864      // convert the lhs to the rhs complex type.
4865      return rhs;
4866    }
4867  }
4868  // Finally, we have two differing integer types.
4869  // The rules for this case are in C99 6.3.1.8
4870  int compare = getIntegerTypeOrder(lhs, rhs);
4871  bool lhsSigned = lhs->isSignedIntegerType(),
4872       rhsSigned = rhs->isSignedIntegerType();
4873  QualType destType;
4874  if (lhsSigned == rhsSigned) {
4875    // Same signedness; use the higher-ranked type
4876    destType = compare >= 0 ? lhs : rhs;
4877  } else if (compare != (lhsSigned ? 1 : -1)) {
4878    // The unsigned type has greater than or equal rank to the
4879    // signed type, so use the unsigned type
4880    destType = lhsSigned ? rhs : lhs;
4881  } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
4882    // The two types are different widths; if we are here, that
4883    // means the signed type is larger than the unsigned type, so
4884    // use the signed type.
4885    destType = lhsSigned ? lhs : rhs;
4886  } else {
4887    // The signed type is higher-ranked than the unsigned type,
4888    // but isn't actually any bigger (like unsigned int and long
4889    // on most 32-bit systems).  Use the unsigned type corresponding
4890    // to the signed type.
4891    destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
4892  }
4893  return destType;
4894}
4895