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