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