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