1 //===--- TypePrinter.cpp - Pretty-Print Clang Types -----------------------===//
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 contains code to print types from Clang's type system.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/PrettyPrinter.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/Type.h"
21 #include "clang/Basic/LangOptions.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/Support/SaveAndRestore.h"
26 #include "llvm/Support/raw_ostream.h"
27 using namespace clang;
28 
29 namespace {
30   /// \brief RAII object that enables printing of the ARC __strong lifetime
31   /// qualifier.
32   class IncludeStrongLifetimeRAII {
33     PrintingPolicy &Policy;
34     bool Old;
35 
36   public:
37     explicit IncludeStrongLifetimeRAII(PrintingPolicy &Policy)
38       : Policy(Policy), Old(Policy.SuppressStrongLifetime) {
39       Policy.SuppressStrongLifetime = false;
40     }
41 
42     ~IncludeStrongLifetimeRAII() {
43       Policy.SuppressStrongLifetime = Old;
44     }
45   };
46 
47   class ParamPolicyRAII {
48     PrintingPolicy &Policy;
49     bool Old;
50 
51   public:
52     explicit ParamPolicyRAII(PrintingPolicy &Policy)
53       : Policy(Policy), Old(Policy.SuppressSpecifiers) {
54       Policy.SuppressSpecifiers = false;
55     }
56 
57     ~ParamPolicyRAII() {
58       Policy.SuppressSpecifiers = Old;
59     }
60   };
61 
62   class ElaboratedTypePolicyRAII {
63     PrintingPolicy &Policy;
64     bool SuppressTagKeyword;
65     bool SuppressScope;
66 
67   public:
68     explicit ElaboratedTypePolicyRAII(PrintingPolicy &Policy) : Policy(Policy) {
69       SuppressTagKeyword = Policy.SuppressTagKeyword;
70       SuppressScope = Policy.SuppressScope;
71       Policy.SuppressTagKeyword = true;
72       Policy.SuppressScope = true;
73     }
74 
75     ~ElaboratedTypePolicyRAII() {
76       Policy.SuppressTagKeyword = SuppressTagKeyword;
77       Policy.SuppressScope = SuppressScope;
78     }
79   };
80 
81   class TypePrinter {
82     PrintingPolicy Policy;
83     bool HasEmptyPlaceHolder;
84     bool InsideCCAttribute;
85 
86   public:
87     explicit TypePrinter(const PrintingPolicy &Policy)
88       : Policy(Policy), HasEmptyPlaceHolder(false), InsideCCAttribute(false) { }
89 
90     void print(const Type *ty, Qualifiers qs, raw_ostream &OS,
91                StringRef PlaceHolder);
92     void print(QualType T, raw_ostream &OS, StringRef PlaceHolder);
93 
94     static bool canPrefixQualifiers(const Type *T, bool &NeedARCStrongQualifier);
95     void spaceBeforePlaceHolder(raw_ostream &OS);
96     void printTypeSpec(const NamedDecl *D, raw_ostream &OS);
97 
98     void printBefore(const Type *ty, Qualifiers qs, raw_ostream &OS);
99     void printBefore(QualType T, raw_ostream &OS);
100     void printAfter(const Type *ty, Qualifiers qs, raw_ostream &OS);
101     void printAfter(QualType T, raw_ostream &OS);
102     void AppendScope(DeclContext *DC, raw_ostream &OS);
103     void printTag(TagDecl *T, raw_ostream &OS);
104 #define ABSTRACT_TYPE(CLASS, PARENT)
105 #define TYPE(CLASS, PARENT) \
106     void print##CLASS##Before(const CLASS##Type *T, raw_ostream &OS); \
107     void print##CLASS##After(const CLASS##Type *T, raw_ostream &OS);
108 #include "clang/AST/TypeNodes.def"
109   };
110 }
111 
112 static void AppendTypeQualList(raw_ostream &OS, unsigned TypeQuals) {
113   bool appendSpace = false;
114   if (TypeQuals & Qualifiers::Const) {
115     OS << "const";
116     appendSpace = true;
117   }
118   if (TypeQuals & Qualifiers::Volatile) {
119     if (appendSpace) OS << ' ';
120     OS << "volatile";
121     appendSpace = true;
122   }
123   if (TypeQuals & Qualifiers::Restrict) {
124     if (appendSpace) OS << ' ';
125     OS << "restrict";
126   }
127 }
128 
129 void TypePrinter::spaceBeforePlaceHolder(raw_ostream &OS) {
130   if (!HasEmptyPlaceHolder)
131     OS << ' ';
132 }
133 
134 void TypePrinter::print(QualType t, raw_ostream &OS, StringRef PlaceHolder) {
135   SplitQualType split = t.split();
136   print(split.Ty, split.Quals, OS, PlaceHolder);
137 }
138 
139 void TypePrinter::print(const Type *T, Qualifiers Quals, raw_ostream &OS,
140                         StringRef PlaceHolder) {
141   if (!T) {
142     OS << "NULL TYPE";
143     return;
144   }
145 
146   SaveAndRestore<bool> PHVal(HasEmptyPlaceHolder, PlaceHolder.empty());
147 
148   printBefore(T, Quals, OS);
149   OS << PlaceHolder;
150   printAfter(T, Quals, OS);
151 }
152 
153 bool TypePrinter::canPrefixQualifiers(const Type *T,
154                                       bool &NeedARCStrongQualifier) {
155   // CanPrefixQualifiers - We prefer to print type qualifiers before the type,
156   // so that we get "const int" instead of "int const", but we can't do this if
157   // the type is complex.  For example if the type is "int*", we *must* print
158   // "int * const", printing "const int *" is different.  Only do this when the
159   // type expands to a simple string.
160   bool CanPrefixQualifiers = false;
161   NeedARCStrongQualifier = false;
162   Type::TypeClass TC = T->getTypeClass();
163   if (const AutoType *AT = dyn_cast<AutoType>(T))
164     TC = AT->desugar()->getTypeClass();
165   if (const SubstTemplateTypeParmType *Subst
166                                       = dyn_cast<SubstTemplateTypeParmType>(T))
167     TC = Subst->getReplacementType()->getTypeClass();
168 
169   switch (TC) {
170     case Type::Builtin:
171     case Type::Complex:
172     case Type::UnresolvedUsing:
173     case Type::Typedef:
174     case Type::TypeOfExpr:
175     case Type::TypeOf:
176     case Type::Decltype:
177     case Type::UnaryTransform:
178     case Type::Record:
179     case Type::Enum:
180     case Type::Elaborated:
181     case Type::TemplateTypeParm:
182     case Type::SubstTemplateTypeParmPack:
183     case Type::TemplateSpecialization:
184     case Type::InjectedClassName:
185     case Type::DependentName:
186     case Type::DependentTemplateSpecialization:
187     case Type::ObjCObject:
188     case Type::ObjCInterface:
189     case Type::Atomic:
190       CanPrefixQualifiers = true;
191       break;
192 
193     case Type::ObjCObjectPointer:
194       CanPrefixQualifiers = T->isObjCIdType() || T->isObjCClassType() ||
195         T->isObjCQualifiedIdType() || T->isObjCQualifiedClassType();
196       break;
197 
198     case Type::ConstantArray:
199     case Type::IncompleteArray:
200     case Type::VariableArray:
201     case Type::DependentSizedArray:
202       NeedARCStrongQualifier = true;
203       // Fall through
204 
205     case Type::Decayed:
206     case Type::Pointer:
207     case Type::BlockPointer:
208     case Type::LValueReference:
209     case Type::RValueReference:
210     case Type::MemberPointer:
211     case Type::DependentSizedExtVector:
212     case Type::Vector:
213     case Type::ExtVector:
214     case Type::FunctionProto:
215     case Type::FunctionNoProto:
216     case Type::Paren:
217     case Type::Attributed:
218     case Type::PackExpansion:
219     case Type::SubstTemplateTypeParm:
220     case Type::Auto:
221       CanPrefixQualifiers = false;
222       break;
223   }
224 
225   return CanPrefixQualifiers;
226 }
227 
228 void TypePrinter::printBefore(QualType T, raw_ostream &OS) {
229   SplitQualType Split = T.split();
230 
231   // If we have cv1 T, where T is substituted for cv2 U, only print cv1 - cv2
232   // at this level.
233   Qualifiers Quals = Split.Quals;
234   if (const SubstTemplateTypeParmType *Subst =
235         dyn_cast<SubstTemplateTypeParmType>(Split.Ty))
236     Quals -= QualType(Subst, 0).getQualifiers();
237 
238   printBefore(Split.Ty, Quals, OS);
239 }
240 
241 /// \brief Prints the part of the type string before an identifier, e.g. for
242 /// "int foo[10]" it prints "int ".
243 void TypePrinter::printBefore(const Type *T,Qualifiers Quals, raw_ostream &OS) {
244   if (Policy.SuppressSpecifiers && T->isSpecifierType())
245     return;
246 
247   SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder);
248 
249   // Print qualifiers as appropriate.
250 
251   bool CanPrefixQualifiers = false;
252   bool NeedARCStrongQualifier = false;
253   CanPrefixQualifiers = canPrefixQualifiers(T, NeedARCStrongQualifier);
254 
255   if (CanPrefixQualifiers && !Quals.empty()) {
256     if (NeedARCStrongQualifier) {
257       IncludeStrongLifetimeRAII Strong(Policy);
258       Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/true);
259     } else {
260       Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/true);
261     }
262   }
263 
264   bool hasAfterQuals = false;
265   if (!CanPrefixQualifiers && !Quals.empty()) {
266     hasAfterQuals = !Quals.isEmptyWhenPrinted(Policy);
267     if (hasAfterQuals)
268       HasEmptyPlaceHolder = false;
269   }
270 
271   switch (T->getTypeClass()) {
272 #define ABSTRACT_TYPE(CLASS, PARENT)
273 #define TYPE(CLASS, PARENT) case Type::CLASS: \
274     print##CLASS##Before(cast<CLASS##Type>(T), OS); \
275     break;
276 #include "clang/AST/TypeNodes.def"
277   }
278 
279   if (hasAfterQuals) {
280     if (NeedARCStrongQualifier) {
281       IncludeStrongLifetimeRAII Strong(Policy);
282       Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/!PrevPHIsEmpty.get());
283     } else {
284       Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/!PrevPHIsEmpty.get());
285     }
286   }
287 }
288 
289 void TypePrinter::printAfter(QualType t, raw_ostream &OS) {
290   SplitQualType split = t.split();
291   printAfter(split.Ty, split.Quals, OS);
292 }
293 
294 /// \brief Prints the part of the type string after an identifier, e.g. for
295 /// "int foo[10]" it prints "[10]".
296 void TypePrinter::printAfter(const Type *T, Qualifiers Quals, raw_ostream &OS) {
297   switch (T->getTypeClass()) {
298 #define ABSTRACT_TYPE(CLASS, PARENT)
299 #define TYPE(CLASS, PARENT) case Type::CLASS: \
300     print##CLASS##After(cast<CLASS##Type>(T), OS); \
301     break;
302 #include "clang/AST/TypeNodes.def"
303   }
304 }
305 
306 void TypePrinter::printBuiltinBefore(const BuiltinType *T, raw_ostream &OS) {
307   OS << T->getName(Policy);
308   spaceBeforePlaceHolder(OS);
309 }
310 void TypePrinter::printBuiltinAfter(const BuiltinType *T, raw_ostream &OS) { }
311 
312 void TypePrinter::printComplexBefore(const ComplexType *T, raw_ostream &OS) {
313   OS << "_Complex ";
314   printBefore(T->getElementType(), OS);
315 }
316 void TypePrinter::printComplexAfter(const ComplexType *T, raw_ostream &OS) {
317   printAfter(T->getElementType(), OS);
318 }
319 
320 void TypePrinter::printPointerBefore(const PointerType *T, raw_ostream &OS) {
321   IncludeStrongLifetimeRAII Strong(Policy);
322   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
323   printBefore(T->getPointeeType(), OS);
324   // Handle things like 'int (*A)[4];' correctly.
325   // FIXME: this should include vectors, but vectors use attributes I guess.
326   if (isa<ArrayType>(T->getPointeeType()))
327     OS << '(';
328   OS << '*';
329 }
330 void TypePrinter::printPointerAfter(const PointerType *T, raw_ostream &OS) {
331   IncludeStrongLifetimeRAII Strong(Policy);
332   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
333   // Handle things like 'int (*A)[4];' correctly.
334   // FIXME: this should include vectors, but vectors use attributes I guess.
335   if (isa<ArrayType>(T->getPointeeType()))
336     OS << ')';
337   printAfter(T->getPointeeType(), OS);
338 }
339 
340 void TypePrinter::printBlockPointerBefore(const BlockPointerType *T,
341                                           raw_ostream &OS) {
342   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
343   printBefore(T->getPointeeType(), OS);
344   OS << '^';
345 }
346 void TypePrinter::printBlockPointerAfter(const BlockPointerType *T,
347                                           raw_ostream &OS) {
348   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
349   printAfter(T->getPointeeType(), OS);
350 }
351 
352 void TypePrinter::printLValueReferenceBefore(const LValueReferenceType *T,
353                                              raw_ostream &OS) {
354   IncludeStrongLifetimeRAII Strong(Policy);
355   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
356   printBefore(T->getPointeeTypeAsWritten(), OS);
357   // Handle things like 'int (&A)[4];' correctly.
358   // FIXME: this should include vectors, but vectors use attributes I guess.
359   if (isa<ArrayType>(T->getPointeeTypeAsWritten()))
360     OS << '(';
361   OS << '&';
362 }
363 void TypePrinter::printLValueReferenceAfter(const LValueReferenceType *T,
364                                             raw_ostream &OS) {
365   IncludeStrongLifetimeRAII Strong(Policy);
366   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
367   // Handle things like 'int (&A)[4];' correctly.
368   // FIXME: this should include vectors, but vectors use attributes I guess.
369   if (isa<ArrayType>(T->getPointeeTypeAsWritten()))
370     OS << ')';
371   printAfter(T->getPointeeTypeAsWritten(), OS);
372 }
373 
374 void TypePrinter::printRValueReferenceBefore(const RValueReferenceType *T,
375                                              raw_ostream &OS) {
376   IncludeStrongLifetimeRAII Strong(Policy);
377   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
378   printBefore(T->getPointeeTypeAsWritten(), OS);
379   // Handle things like 'int (&&A)[4];' correctly.
380   // FIXME: this should include vectors, but vectors use attributes I guess.
381   if (isa<ArrayType>(T->getPointeeTypeAsWritten()))
382     OS << '(';
383   OS << "&&";
384 }
385 void TypePrinter::printRValueReferenceAfter(const RValueReferenceType *T,
386                                             raw_ostream &OS) {
387   IncludeStrongLifetimeRAII Strong(Policy);
388   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
389   // Handle things like 'int (&&A)[4];' correctly.
390   // FIXME: this should include vectors, but vectors use attributes I guess.
391   if (isa<ArrayType>(T->getPointeeTypeAsWritten()))
392     OS << ')';
393   printAfter(T->getPointeeTypeAsWritten(), OS);
394 }
395 
396 void TypePrinter::printMemberPointerBefore(const MemberPointerType *T,
397                                            raw_ostream &OS) {
398   IncludeStrongLifetimeRAII Strong(Policy);
399   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
400   printBefore(T->getPointeeType(), OS);
401   // Handle things like 'int (Cls::*A)[4];' correctly.
402   // FIXME: this should include vectors, but vectors use attributes I guess.
403   if (isa<ArrayType>(T->getPointeeType()))
404     OS << '(';
405 
406   PrintingPolicy InnerPolicy(Policy);
407   InnerPolicy.SuppressTag = false;
408   TypePrinter(InnerPolicy).print(QualType(T->getClass(), 0), OS, StringRef());
409 
410   OS << "::*";
411 }
412 void TypePrinter::printMemberPointerAfter(const MemberPointerType *T,
413                                           raw_ostream &OS) {
414   IncludeStrongLifetimeRAII Strong(Policy);
415   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
416   // Handle things like 'int (Cls::*A)[4];' correctly.
417   // FIXME: this should include vectors, but vectors use attributes I guess.
418   if (isa<ArrayType>(T->getPointeeType()))
419     OS << ')';
420   printAfter(T->getPointeeType(), OS);
421 }
422 
423 void TypePrinter::printConstantArrayBefore(const ConstantArrayType *T,
424                                            raw_ostream &OS) {
425   IncludeStrongLifetimeRAII Strong(Policy);
426   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
427   printBefore(T->getElementType(), OS);
428 }
429 void TypePrinter::printConstantArrayAfter(const ConstantArrayType *T,
430                                           raw_ostream &OS) {
431   OS << '[' << T->getSize().getZExtValue() << ']';
432   printAfter(T->getElementType(), OS);
433 }
434 
435 void TypePrinter::printIncompleteArrayBefore(const IncompleteArrayType *T,
436                                              raw_ostream &OS) {
437   IncludeStrongLifetimeRAII Strong(Policy);
438   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
439   printBefore(T->getElementType(), OS);
440 }
441 void TypePrinter::printIncompleteArrayAfter(const IncompleteArrayType *T,
442                                             raw_ostream &OS) {
443   OS << "[]";
444   printAfter(T->getElementType(), OS);
445 }
446 
447 void TypePrinter::printVariableArrayBefore(const VariableArrayType *T,
448                                            raw_ostream &OS) {
449   IncludeStrongLifetimeRAII Strong(Policy);
450   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
451   printBefore(T->getElementType(), OS);
452 }
453 void TypePrinter::printVariableArrayAfter(const VariableArrayType *T,
454                                           raw_ostream &OS) {
455   OS << '[';
456   if (T->getIndexTypeQualifiers().hasQualifiers()) {
457     AppendTypeQualList(OS, T->getIndexTypeCVRQualifiers());
458     OS << ' ';
459   }
460 
461   if (T->getSizeModifier() == VariableArrayType::Static)
462     OS << "static";
463   else if (T->getSizeModifier() == VariableArrayType::Star)
464     OS << '*';
465 
466   if (T->getSizeExpr())
467     T->getSizeExpr()->printPretty(OS, 0, Policy);
468   OS << ']';
469 
470   printAfter(T->getElementType(), OS);
471 }
472 
473 void TypePrinter::printDecayedBefore(const DecayedType *T, raw_ostream &OS) {
474   // Print as though it's a pointer.
475   printBefore(T->getDecayedType(), OS);
476 }
477 void TypePrinter::printDecayedAfter(const DecayedType *T, raw_ostream &OS) {
478   printAfter(T->getDecayedType(), OS);
479 }
480 
481 void TypePrinter::printDependentSizedArrayBefore(
482                                                const DependentSizedArrayType *T,
483                                                raw_ostream &OS) {
484   IncludeStrongLifetimeRAII Strong(Policy);
485   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
486   printBefore(T->getElementType(), OS);
487 }
488 void TypePrinter::printDependentSizedArrayAfter(
489                                                const DependentSizedArrayType *T,
490                                                raw_ostream &OS) {
491   OS << '[';
492   if (T->getSizeExpr())
493     T->getSizeExpr()->printPretty(OS, 0, Policy);
494   OS << ']';
495   printAfter(T->getElementType(), OS);
496 }
497 
498 void TypePrinter::printDependentSizedExtVectorBefore(
499                                           const DependentSizedExtVectorType *T,
500                                           raw_ostream &OS) {
501   printBefore(T->getElementType(), OS);
502 }
503 void TypePrinter::printDependentSizedExtVectorAfter(
504                                           const DependentSizedExtVectorType *T,
505                                           raw_ostream &OS) {
506   OS << " __attribute__((ext_vector_type(";
507   if (T->getSizeExpr())
508     T->getSizeExpr()->printPretty(OS, 0, Policy);
509   OS << ")))";
510   printAfter(T->getElementType(), OS);
511 }
512 
513 void TypePrinter::printVectorBefore(const VectorType *T, raw_ostream &OS) {
514   switch (T->getVectorKind()) {
515   case VectorType::AltiVecPixel:
516     OS << "__vector __pixel ";
517     break;
518   case VectorType::AltiVecBool:
519     OS << "__vector __bool ";
520     printBefore(T->getElementType(), OS);
521     break;
522   case VectorType::AltiVecVector:
523     OS << "__vector ";
524     printBefore(T->getElementType(), OS);
525     break;
526   case VectorType::NeonVector:
527     OS << "__attribute__((neon_vector_type("
528        << T->getNumElements() << "))) ";
529     printBefore(T->getElementType(), OS);
530     break;
531   case VectorType::NeonPolyVector:
532     OS << "__attribute__((neon_polyvector_type(" <<
533           T->getNumElements() << "))) ";
534     printBefore(T->getElementType(), OS);
535     break;
536   case VectorType::GenericVector: {
537     // FIXME: We prefer to print the size directly here, but have no way
538     // to get the size of the type.
539     OS << "__attribute__((__vector_size__("
540        << T->getNumElements()
541        << " * sizeof(";
542     print(T->getElementType(), OS, StringRef());
543     OS << ")))) ";
544     printBefore(T->getElementType(), OS);
545     break;
546   }
547   }
548 }
549 void TypePrinter::printVectorAfter(const VectorType *T, raw_ostream &OS) {
550   printAfter(T->getElementType(), OS);
551 }
552 
553 void TypePrinter::printExtVectorBefore(const ExtVectorType *T,
554                                        raw_ostream &OS) {
555   printBefore(T->getElementType(), OS);
556 }
557 void TypePrinter::printExtVectorAfter(const ExtVectorType *T, raw_ostream &OS) {
558   printAfter(T->getElementType(), OS);
559   OS << " __attribute__((ext_vector_type(";
560   OS << T->getNumElements();
561   OS << ")))";
562 }
563 
564 void
565 FunctionProtoType::printExceptionSpecification(raw_ostream &OS,
566                                                const PrintingPolicy &Policy)
567                                                                          const {
568 
569   if (hasDynamicExceptionSpec()) {
570     OS << " throw(";
571     if (getExceptionSpecType() == EST_MSAny)
572       OS << "...";
573     else
574       for (unsigned I = 0, N = getNumExceptions(); I != N; ++I) {
575         if (I)
576           OS << ", ";
577 
578         OS << getExceptionType(I).stream(Policy);
579       }
580     OS << ')';
581   } else if (isNoexceptExceptionSpec(getExceptionSpecType())) {
582     OS << " noexcept";
583     if (getExceptionSpecType() == EST_ComputedNoexcept) {
584       OS << '(';
585       getNoexceptExpr()->printPretty(OS, 0, Policy);
586       OS << ')';
587     }
588   }
589 }
590 
591 void TypePrinter::printFunctionProtoBefore(const FunctionProtoType *T,
592                                            raw_ostream &OS) {
593   if (T->hasTrailingReturn()) {
594     OS << "auto ";
595     if (!HasEmptyPlaceHolder)
596       OS << '(';
597   } else {
598     // If needed for precedence reasons, wrap the inner part in grouping parens.
599     SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder, false);
600     printBefore(T->getResultType(), OS);
601     if (!PrevPHIsEmpty.get())
602       OS << '(';
603   }
604 }
605 
606 void TypePrinter::printFunctionProtoAfter(const FunctionProtoType *T,
607                                           raw_ostream &OS) {
608   // If needed for precedence reasons, wrap the inner part in grouping parens.
609   if (!HasEmptyPlaceHolder)
610     OS << ')';
611   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
612 
613   OS << '(';
614   {
615     ParamPolicyRAII ParamPolicy(Policy);
616     for (unsigned i = 0, e = T->getNumArgs(); i != e; ++i) {
617       if (i) OS << ", ";
618       print(T->getArgType(i), OS, StringRef());
619     }
620   }
621 
622   if (T->isVariadic()) {
623     if (T->getNumArgs())
624       OS << ", ";
625     OS << "...";
626   } else if (T->getNumArgs() == 0 && !Policy.LangOpts.CPlusPlus) {
627     // Do not emit int() if we have a proto, emit 'int(void)'.
628     OS << "void";
629   }
630 
631   OS << ')';
632 
633   FunctionType::ExtInfo Info = T->getExtInfo();
634 
635   if (!InsideCCAttribute) {
636     switch (Info.getCC()) {
637     case CC_Default: break;
638     case CC_C:
639       OS << " __attribute__((cdecl))";
640       break;
641     case CC_X86StdCall:
642       OS << " __attribute__((stdcall))";
643       break;
644     case CC_X86FastCall:
645       OS << " __attribute__((fastcall))";
646       break;
647     case CC_X86ThisCall:
648       OS << " __attribute__((thiscall))";
649       break;
650     case CC_X86Pascal:
651       OS << " __attribute__((pascal))";
652       break;
653     case CC_AAPCS:
654       OS << " __attribute__((pcs(\"aapcs\")))";
655       break;
656     case CC_AAPCS_VFP:
657       OS << " __attribute__((pcs(\"aapcs-vfp\")))";
658       break;
659     case CC_PnaclCall:
660       OS << " __attribute__((pnaclcall))";
661       break;
662     case CC_IntelOclBicc:
663       OS << " __attribute__((intel_ocl_bicc))";
664       break;
665     }
666   }
667 
668   if (Info.getNoReturn())
669     OS << " __attribute__((noreturn))";
670   if (Info.getRegParm())
671     OS << " __attribute__((regparm ("
672        << Info.getRegParm() << ")))";
673 
674   if (unsigned quals = T->getTypeQuals()) {
675     OS << ' ';
676     AppendTypeQualList(OS, quals);
677   }
678 
679   switch (T->getRefQualifier()) {
680   case RQ_None:
681     break;
682 
683   case RQ_LValue:
684     OS << " &";
685     break;
686 
687   case RQ_RValue:
688     OS << " &&";
689     break;
690   }
691   T->printExceptionSpecification(OS, Policy);
692 
693   if (T->hasTrailingReturn()) {
694     OS << " -> ";
695     print(T->getResultType(), OS, StringRef());
696   } else
697     printAfter(T->getResultType(), OS);
698 }
699 
700 void TypePrinter::printFunctionNoProtoBefore(const FunctionNoProtoType *T,
701                                              raw_ostream &OS) {
702   // If needed for precedence reasons, wrap the inner part in grouping parens.
703   SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder, false);
704   printBefore(T->getResultType(), OS);
705   if (!PrevPHIsEmpty.get())
706     OS << '(';
707 }
708 void TypePrinter::printFunctionNoProtoAfter(const FunctionNoProtoType *T,
709                                             raw_ostream &OS) {
710   // If needed for precedence reasons, wrap the inner part in grouping parens.
711   if (!HasEmptyPlaceHolder)
712     OS << ')';
713   SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
714 
715   OS << "()";
716   if (T->getNoReturnAttr())
717     OS << " __attribute__((noreturn))";
718   printAfter(T->getResultType(), OS);
719 }
720 
721 void TypePrinter::printTypeSpec(const NamedDecl *D, raw_ostream &OS) {
722   IdentifierInfo *II = D->getIdentifier();
723   OS << II->getName();
724   spaceBeforePlaceHolder(OS);
725 }
726 
727 void TypePrinter::printUnresolvedUsingBefore(const UnresolvedUsingType *T,
728                                              raw_ostream &OS) {
729   printTypeSpec(T->getDecl(), OS);
730 }
731 void TypePrinter::printUnresolvedUsingAfter(const UnresolvedUsingType *T,
732                                              raw_ostream &OS) { }
733 
734 void TypePrinter::printTypedefBefore(const TypedefType *T, raw_ostream &OS) {
735   printTypeSpec(T->getDecl(), OS);
736 }
737 void TypePrinter::printTypedefAfter(const TypedefType *T, raw_ostream &OS) { }
738 
739 void TypePrinter::printTypeOfExprBefore(const TypeOfExprType *T,
740                                         raw_ostream &OS) {
741   OS << "typeof ";
742   T->getUnderlyingExpr()->printPretty(OS, 0, Policy);
743   spaceBeforePlaceHolder(OS);
744 }
745 void TypePrinter::printTypeOfExprAfter(const TypeOfExprType *T,
746                                        raw_ostream &OS) { }
747 
748 void TypePrinter::printTypeOfBefore(const TypeOfType *T, raw_ostream &OS) {
749   OS << "typeof(";
750   print(T->getUnderlyingType(), OS, StringRef());
751   OS << ')';
752   spaceBeforePlaceHolder(OS);
753 }
754 void TypePrinter::printTypeOfAfter(const TypeOfType *T, raw_ostream &OS) { }
755 
756 void TypePrinter::printDecltypeBefore(const DecltypeType *T, raw_ostream &OS) {
757   OS << "decltype(";
758   T->getUnderlyingExpr()->printPretty(OS, 0, Policy);
759   OS << ')';
760   spaceBeforePlaceHolder(OS);
761 }
762 void TypePrinter::printDecltypeAfter(const DecltypeType *T, raw_ostream &OS) { }
763 
764 void TypePrinter::printUnaryTransformBefore(const UnaryTransformType *T,
765                                             raw_ostream &OS) {
766   IncludeStrongLifetimeRAII Strong(Policy);
767 
768   switch (T->getUTTKind()) {
769     case UnaryTransformType::EnumUnderlyingType:
770       OS << "__underlying_type(";
771       print(T->getBaseType(), OS, StringRef());
772       OS << ')';
773       spaceBeforePlaceHolder(OS);
774       return;
775   }
776 
777   printBefore(T->getBaseType(), OS);
778 }
779 void TypePrinter::printUnaryTransformAfter(const UnaryTransformType *T,
780                                            raw_ostream &OS) {
781   IncludeStrongLifetimeRAII Strong(Policy);
782 
783   switch (T->getUTTKind()) {
784     case UnaryTransformType::EnumUnderlyingType:
785       return;
786   }
787 
788   printAfter(T->getBaseType(), OS);
789 }
790 
791 void TypePrinter::printAutoBefore(const AutoType *T, raw_ostream &OS) {
792   // If the type has been deduced, do not print 'auto'.
793   if (!T->getDeducedType().isNull()) {
794     printBefore(T->getDeducedType(), OS);
795   } else {
796     OS << (T->isDecltypeAuto() ? "decltype(auto)" : "auto");
797     spaceBeforePlaceHolder(OS);
798   }
799 }
800 void TypePrinter::printAutoAfter(const AutoType *T, raw_ostream &OS) {
801   // If the type has been deduced, do not print 'auto'.
802   if (!T->getDeducedType().isNull())
803     printAfter(T->getDeducedType(), OS);
804 }
805 
806 void TypePrinter::printAtomicBefore(const AtomicType *T, raw_ostream &OS) {
807   IncludeStrongLifetimeRAII Strong(Policy);
808 
809   OS << "_Atomic(";
810   print(T->getValueType(), OS, StringRef());
811   OS << ')';
812   spaceBeforePlaceHolder(OS);
813 }
814 void TypePrinter::printAtomicAfter(const AtomicType *T, raw_ostream &OS) { }
815 
816 /// Appends the given scope to the end of a string.
817 void TypePrinter::AppendScope(DeclContext *DC, raw_ostream &OS) {
818   if (DC->isTranslationUnit()) return;
819   if (DC->isFunctionOrMethod()) return;
820   AppendScope(DC->getParent(), OS);
821 
822   if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(DC)) {
823     if (Policy.SuppressUnwrittenScope &&
824         (NS->isAnonymousNamespace() || NS->isInline()))
825       return;
826     if (NS->getIdentifier())
827       OS << NS->getName() << "::";
828     else
829       OS << "<anonymous>::";
830   } else if (ClassTemplateSpecializationDecl *Spec
831                = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
832     IncludeStrongLifetimeRAII Strong(Policy);
833     OS << Spec->getIdentifier()->getName();
834     const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
835     TemplateSpecializationType::PrintTemplateArgumentList(OS,
836                                             TemplateArgs.data(),
837                                             TemplateArgs.size(),
838                                             Policy);
839     OS << "::";
840   } else if (TagDecl *Tag = dyn_cast<TagDecl>(DC)) {
841     if (TypedefNameDecl *Typedef = Tag->getTypedefNameForAnonDecl())
842       OS << Typedef->getIdentifier()->getName() << "::";
843     else if (Tag->getIdentifier())
844       OS << Tag->getIdentifier()->getName() << "::";
845     else
846       return;
847   }
848 }
849 
850 void TypePrinter::printTag(TagDecl *D, raw_ostream &OS) {
851   if (Policy.SuppressTag)
852     return;
853 
854   bool HasKindDecoration = false;
855 
856   // bool SuppressTagKeyword
857   //   = Policy.LangOpts.CPlusPlus || Policy.SuppressTagKeyword;
858 
859   // We don't print tags unless this is an elaborated type.
860   // In C, we just assume every RecordType is an elaborated type.
861   if (!(Policy.LangOpts.CPlusPlus || Policy.SuppressTagKeyword ||
862         D->getTypedefNameForAnonDecl())) {
863     HasKindDecoration = true;
864     OS << D->getKindName();
865     OS << ' ';
866   }
867 
868   // Compute the full nested-name-specifier for this type.
869   // In C, this will always be empty except when the type
870   // being printed is anonymous within other Record.
871   if (!Policy.SuppressScope)
872     AppendScope(D->getDeclContext(), OS);
873 
874   if (const IdentifierInfo *II = D->getIdentifier())
875     OS << II->getName();
876   else if (TypedefNameDecl *Typedef = D->getTypedefNameForAnonDecl()) {
877     assert(Typedef->getIdentifier() && "Typedef without identifier?");
878     OS << Typedef->getIdentifier()->getName();
879   } else {
880     // Make an unambiguous representation for anonymous types, e.g.
881     //   <anonymous enum at /usr/include/string.h:120:9>
882 
883     if (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda()) {
884       OS << "<lambda";
885       HasKindDecoration = true;
886     } else {
887       OS << "<anonymous";
888     }
889 
890     if (Policy.AnonymousTagLocations) {
891       // Suppress the redundant tag keyword if we just printed one.
892       // We don't have to worry about ElaboratedTypes here because you can't
893       // refer to an anonymous type with one.
894       if (!HasKindDecoration)
895         OS << " " << D->getKindName();
896 
897       PresumedLoc PLoc = D->getASTContext().getSourceManager().getPresumedLoc(
898           D->getLocation());
899       if (PLoc.isValid()) {
900         OS << " at " << PLoc.getFilename()
901            << ':' << PLoc.getLine()
902            << ':' << PLoc.getColumn();
903       }
904     }
905 
906     OS << '>';
907   }
908 
909   // If this is a class template specialization, print the template
910   // arguments.
911   if (ClassTemplateSpecializationDecl *Spec
912         = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
913     const TemplateArgument *Args;
914     unsigned NumArgs;
915     if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
916       const TemplateSpecializationType *TST =
917         cast<TemplateSpecializationType>(TAW->getType());
918       Args = TST->getArgs();
919       NumArgs = TST->getNumArgs();
920     } else {
921       const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
922       Args = TemplateArgs.data();
923       NumArgs = TemplateArgs.size();
924     }
925     IncludeStrongLifetimeRAII Strong(Policy);
926     TemplateSpecializationType::PrintTemplateArgumentList(OS,
927                                                           Args, NumArgs,
928                                                           Policy);
929   }
930 
931   spaceBeforePlaceHolder(OS);
932 }
933 
934 void TypePrinter::printRecordBefore(const RecordType *T, raw_ostream &OS) {
935   printTag(T->getDecl(), OS);
936 }
937 void TypePrinter::printRecordAfter(const RecordType *T, raw_ostream &OS) { }
938 
939 void TypePrinter::printEnumBefore(const EnumType *T, raw_ostream &OS) {
940   printTag(T->getDecl(), OS);
941 }
942 void TypePrinter::printEnumAfter(const EnumType *T, raw_ostream &OS) { }
943 
944 void TypePrinter::printTemplateTypeParmBefore(const TemplateTypeParmType *T,
945                                               raw_ostream &OS) {
946   if (IdentifierInfo *Id = T->getIdentifier())
947     OS << Id->getName();
948   else
949     OS << "type-parameter-" << T->getDepth() << '-' << T->getIndex();
950   spaceBeforePlaceHolder(OS);
951 }
952 void TypePrinter::printTemplateTypeParmAfter(const TemplateTypeParmType *T,
953                                              raw_ostream &OS) { }
954 
955 void TypePrinter::printSubstTemplateTypeParmBefore(
956                                              const SubstTemplateTypeParmType *T,
957                                              raw_ostream &OS) {
958   IncludeStrongLifetimeRAII Strong(Policy);
959   printBefore(T->getReplacementType(), OS);
960 }
961 void TypePrinter::printSubstTemplateTypeParmAfter(
962                                              const SubstTemplateTypeParmType *T,
963                                              raw_ostream &OS) {
964   IncludeStrongLifetimeRAII Strong(Policy);
965   printAfter(T->getReplacementType(), OS);
966 }
967 
968 void TypePrinter::printSubstTemplateTypeParmPackBefore(
969                                         const SubstTemplateTypeParmPackType *T,
970                                         raw_ostream &OS) {
971   IncludeStrongLifetimeRAII Strong(Policy);
972   printTemplateTypeParmBefore(T->getReplacedParameter(), OS);
973 }
974 void TypePrinter::printSubstTemplateTypeParmPackAfter(
975                                         const SubstTemplateTypeParmPackType *T,
976                                         raw_ostream &OS) {
977   IncludeStrongLifetimeRAII Strong(Policy);
978   printTemplateTypeParmAfter(T->getReplacedParameter(), OS);
979 }
980 
981 void TypePrinter::printTemplateSpecializationBefore(
982                                             const TemplateSpecializationType *T,
983                                             raw_ostream &OS) {
984   IncludeStrongLifetimeRAII Strong(Policy);
985   T->getTemplateName().print(OS, Policy);
986 
987   TemplateSpecializationType::PrintTemplateArgumentList(OS,
988                                                         T->getArgs(),
989                                                         T->getNumArgs(),
990                                                         Policy);
991   spaceBeforePlaceHolder(OS);
992 }
993 void TypePrinter::printTemplateSpecializationAfter(
994                                             const TemplateSpecializationType *T,
995                                             raw_ostream &OS) { }
996 
997 void TypePrinter::printInjectedClassNameBefore(const InjectedClassNameType *T,
998                                                raw_ostream &OS) {
999   printTemplateSpecializationBefore(T->getInjectedTST(), OS);
1000 }
1001 void TypePrinter::printInjectedClassNameAfter(const InjectedClassNameType *T,
1002                                                raw_ostream &OS) { }
1003 
1004 void TypePrinter::printElaboratedBefore(const ElaboratedType *T,
1005                                         raw_ostream &OS) {
1006   if (Policy.SuppressTag && isa<TagType>(T->getNamedType()))
1007     return;
1008   OS << TypeWithKeyword::getKeywordName(T->getKeyword());
1009   if (T->getKeyword() != ETK_None)
1010     OS << " ";
1011   NestedNameSpecifier* Qualifier = T->getQualifier();
1012   if (Qualifier)
1013     Qualifier->print(OS, Policy);
1014 
1015   ElaboratedTypePolicyRAII PolicyRAII(Policy);
1016   printBefore(T->getNamedType(), OS);
1017 }
1018 void TypePrinter::printElaboratedAfter(const ElaboratedType *T,
1019                                         raw_ostream &OS) {
1020   ElaboratedTypePolicyRAII PolicyRAII(Policy);
1021   printAfter(T->getNamedType(), OS);
1022 }
1023 
1024 void TypePrinter::printParenBefore(const ParenType *T, raw_ostream &OS) {
1025   if (!HasEmptyPlaceHolder && !isa<FunctionType>(T->getInnerType())) {
1026     printBefore(T->getInnerType(), OS);
1027     OS << '(';
1028   } else
1029     printBefore(T->getInnerType(), OS);
1030 }
1031 void TypePrinter::printParenAfter(const ParenType *T, raw_ostream &OS) {
1032   if (!HasEmptyPlaceHolder && !isa<FunctionType>(T->getInnerType())) {
1033     OS << ')';
1034     printAfter(T->getInnerType(), OS);
1035   } else
1036     printAfter(T->getInnerType(), OS);
1037 }
1038 
1039 void TypePrinter::printDependentNameBefore(const DependentNameType *T,
1040                                            raw_ostream &OS) {
1041   OS << TypeWithKeyword::getKeywordName(T->getKeyword());
1042   if (T->getKeyword() != ETK_None)
1043     OS << " ";
1044 
1045   T->getQualifier()->print(OS, Policy);
1046 
1047   OS << T->getIdentifier()->getName();
1048   spaceBeforePlaceHolder(OS);
1049 }
1050 void TypePrinter::printDependentNameAfter(const DependentNameType *T,
1051                                           raw_ostream &OS) { }
1052 
1053 void TypePrinter::printDependentTemplateSpecializationBefore(
1054         const DependentTemplateSpecializationType *T, raw_ostream &OS) {
1055   IncludeStrongLifetimeRAII Strong(Policy);
1056 
1057   OS << TypeWithKeyword::getKeywordName(T->getKeyword());
1058   if (T->getKeyword() != ETK_None)
1059     OS << " ";
1060 
1061   if (T->getQualifier())
1062     T->getQualifier()->print(OS, Policy);
1063   OS << T->getIdentifier()->getName();
1064   TemplateSpecializationType::PrintTemplateArgumentList(OS,
1065                                                         T->getArgs(),
1066                                                         T->getNumArgs(),
1067                                                         Policy);
1068   spaceBeforePlaceHolder(OS);
1069 }
1070 void TypePrinter::printDependentTemplateSpecializationAfter(
1071         const DependentTemplateSpecializationType *T, raw_ostream &OS) { }
1072 
1073 void TypePrinter::printPackExpansionBefore(const PackExpansionType *T,
1074                                            raw_ostream &OS) {
1075   printBefore(T->getPattern(), OS);
1076 }
1077 void TypePrinter::printPackExpansionAfter(const PackExpansionType *T,
1078                                           raw_ostream &OS) {
1079   printAfter(T->getPattern(), OS);
1080   OS << "...";
1081 }
1082 
1083 void TypePrinter::printAttributedBefore(const AttributedType *T,
1084                                         raw_ostream &OS) {
1085   // Prefer the macro forms of the GC and ownership qualifiers.
1086   if (T->getAttrKind() == AttributedType::attr_objc_gc ||
1087       T->getAttrKind() == AttributedType::attr_objc_ownership)
1088     return printBefore(T->getEquivalentType(), OS);
1089 
1090   printBefore(T->getModifiedType(), OS);
1091 
1092   if (T->isMSTypeSpec()) {
1093     switch (T->getAttrKind()) {
1094     default: return;
1095     case AttributedType::attr_ptr32: OS << " __ptr32"; break;
1096     case AttributedType::attr_ptr64: OS << " __ptr64"; break;
1097     case AttributedType::attr_sptr: OS << " __sptr"; break;
1098     case AttributedType::attr_uptr: OS << " __uptr"; break;
1099     }
1100     spaceBeforePlaceHolder(OS);
1101   }
1102 }
1103 
1104 void TypePrinter::printAttributedAfter(const AttributedType *T,
1105                                        raw_ostream &OS) {
1106   // Prefer the macro forms of the GC and ownership qualifiers.
1107   if (T->getAttrKind() == AttributedType::attr_objc_gc ||
1108       T->getAttrKind() == AttributedType::attr_objc_ownership)
1109     return printAfter(T->getEquivalentType(), OS);
1110 
1111   // TODO: not all attributes are GCC-style attributes.
1112   if (T->isMSTypeSpec())
1113     return;
1114 
1115   // If this is a calling convention attribute, don't print the implicit CC from
1116   // the modified type.
1117   SaveAndRestore<bool> MaybeSuppressCC(InsideCCAttribute, T->isCallingConv());
1118 
1119   printAfter(T->getModifiedType(), OS);
1120 
1121   OS << " __attribute__((";
1122   switch (T->getAttrKind()) {
1123   default: llvm_unreachable("This attribute should have been handled already");
1124   case AttributedType::attr_address_space:
1125     OS << "address_space(";
1126     OS << T->getEquivalentType().getAddressSpace();
1127     OS << ')';
1128     break;
1129 
1130   case AttributedType::attr_vector_size: {
1131     OS << "__vector_size__(";
1132     if (const VectorType *vector =T->getEquivalentType()->getAs<VectorType>()) {
1133       OS << vector->getNumElements();
1134       OS << " * sizeof(";
1135       print(vector->getElementType(), OS, StringRef());
1136       OS << ')';
1137     }
1138     OS << ')';
1139     break;
1140   }
1141 
1142   case AttributedType::attr_neon_vector_type:
1143   case AttributedType::attr_neon_polyvector_type: {
1144     if (T->getAttrKind() == AttributedType::attr_neon_vector_type)
1145       OS << "neon_vector_type(";
1146     else
1147       OS << "neon_polyvector_type(";
1148     const VectorType *vector = T->getEquivalentType()->getAs<VectorType>();
1149     OS << vector->getNumElements();
1150     OS << ')';
1151     break;
1152   }
1153 
1154   case AttributedType::attr_regparm: {
1155     OS << "regparm(";
1156     QualType t = T->getEquivalentType();
1157     while (!t->isFunctionType())
1158       t = t->getPointeeType();
1159     OS << t->getAs<FunctionType>()->getRegParmType();
1160     OS << ')';
1161     break;
1162   }
1163 
1164   case AttributedType::attr_objc_gc: {
1165     OS << "objc_gc(";
1166 
1167     QualType tmp = T->getEquivalentType();
1168     while (tmp.getObjCGCAttr() == Qualifiers::GCNone) {
1169       QualType next = tmp->getPointeeType();
1170       if (next == tmp) break;
1171       tmp = next;
1172     }
1173 
1174     if (tmp.isObjCGCWeak())
1175       OS << "weak";
1176     else
1177       OS << "strong";
1178     OS << ')';
1179     break;
1180   }
1181 
1182   case AttributedType::attr_objc_ownership:
1183     OS << "objc_ownership(";
1184     switch (T->getEquivalentType().getObjCLifetime()) {
1185     case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
1186     case Qualifiers::OCL_ExplicitNone: OS << "none"; break;
1187     case Qualifiers::OCL_Strong: OS << "strong"; break;
1188     case Qualifiers::OCL_Weak: OS << "weak"; break;
1189     case Qualifiers::OCL_Autoreleasing: OS << "autoreleasing"; break;
1190     }
1191     OS << ')';
1192     break;
1193 
1194   case AttributedType::attr_noreturn: OS << "noreturn"; break;
1195   case AttributedType::attr_cdecl: OS << "cdecl"; break;
1196   case AttributedType::attr_fastcall: OS << "fastcall"; break;
1197   case AttributedType::attr_stdcall: OS << "stdcall"; break;
1198   case AttributedType::attr_thiscall: OS << "thiscall"; break;
1199   case AttributedType::attr_pascal: OS << "pascal"; break;
1200   case AttributedType::attr_pcs: {
1201     OS << "pcs(";
1202    QualType t = T->getEquivalentType();
1203    while (!t->isFunctionType())
1204      t = t->getPointeeType();
1205    OS << (t->getAs<FunctionType>()->getCallConv() == CC_AAPCS ?
1206          "\"aapcs\"" : "\"aapcs-vfp\"");
1207    OS << ')';
1208    break;
1209   }
1210   case AttributedType::attr_pnaclcall: OS << "pnaclcall"; break;
1211   case AttributedType::attr_inteloclbicc: OS << "inteloclbicc"; break;
1212   }
1213   OS << "))";
1214 }
1215 
1216 void TypePrinter::printObjCInterfaceBefore(const ObjCInterfaceType *T,
1217                                            raw_ostream &OS) {
1218   OS << T->getDecl()->getName();
1219   spaceBeforePlaceHolder(OS);
1220 }
1221 void TypePrinter::printObjCInterfaceAfter(const ObjCInterfaceType *T,
1222                                           raw_ostream &OS) { }
1223 
1224 void TypePrinter::printObjCObjectBefore(const ObjCObjectType *T,
1225                                         raw_ostream &OS) {
1226   if (T->qual_empty())
1227     return printBefore(T->getBaseType(), OS);
1228 
1229   print(T->getBaseType(), OS, StringRef());
1230   OS << '<';
1231   bool isFirst = true;
1232   for (ObjCObjectType::qual_iterator
1233          I = T->qual_begin(), E = T->qual_end(); I != E; ++I) {
1234     if (isFirst)
1235       isFirst = false;
1236     else
1237       OS << ',';
1238     OS << (*I)->getName();
1239   }
1240   OS << '>';
1241   spaceBeforePlaceHolder(OS);
1242 }
1243 void TypePrinter::printObjCObjectAfter(const ObjCObjectType *T,
1244                                         raw_ostream &OS) {
1245   if (T->qual_empty())
1246     return printAfter(T->getBaseType(), OS);
1247 }
1248 
1249 void TypePrinter::printObjCObjectPointerBefore(const ObjCObjectPointerType *T,
1250                                                raw_ostream &OS) {
1251   T->getPointeeType().getLocalQualifiers().print(OS, Policy,
1252                                                 /*appendSpaceIfNonEmpty=*/true);
1253 
1254   if (T->isObjCIdType() || T->isObjCQualifiedIdType())
1255     OS << "id";
1256   else if (T->isObjCClassType() || T->isObjCQualifiedClassType())
1257     OS << "Class";
1258   else if (T->isObjCSelType())
1259     OS << "SEL";
1260   else
1261     OS << T->getInterfaceDecl()->getName();
1262 
1263   if (!T->qual_empty()) {
1264     OS << '<';
1265     for (ObjCObjectPointerType::qual_iterator I = T->qual_begin(),
1266                                               E = T->qual_end();
1267          I != E; ++I) {
1268       OS << (*I)->getName();
1269       if (I+1 != E)
1270         OS << ',';
1271     }
1272     OS << '>';
1273   }
1274 
1275   if (!T->isObjCIdType() && !T->isObjCQualifiedIdType()) {
1276     OS << " *"; // Don't forget the implicit pointer.
1277   } else {
1278     spaceBeforePlaceHolder(OS);
1279   }
1280 }
1281 void TypePrinter::printObjCObjectPointerAfter(const ObjCObjectPointerType *T,
1282                                               raw_ostream &OS) { }
1283 
1284 void TemplateSpecializationType::
1285   PrintTemplateArgumentList(raw_ostream &OS,
1286                             const TemplateArgumentListInfo &Args,
1287                             const PrintingPolicy &Policy) {
1288   return PrintTemplateArgumentList(OS,
1289                                    Args.getArgumentArray(),
1290                                    Args.size(),
1291                                    Policy);
1292 }
1293 
1294 void
1295 TemplateSpecializationType::PrintTemplateArgumentList(
1296                                                 raw_ostream &OS,
1297                                                 const TemplateArgument *Args,
1298                                                 unsigned NumArgs,
1299                                                   const PrintingPolicy &Policy,
1300                                                       bool SkipBrackets) {
1301   if (!SkipBrackets)
1302     OS << '<';
1303 
1304   bool needSpace = false;
1305   for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1306     // Print the argument into a string.
1307     SmallString<128> Buf;
1308     llvm::raw_svector_ostream ArgOS(Buf);
1309     if (Args[Arg].getKind() == TemplateArgument::Pack) {
1310       if (Args[Arg].pack_size() && Arg > 0)
1311         OS << ", ";
1312       PrintTemplateArgumentList(ArgOS,
1313                                 Args[Arg].pack_begin(),
1314                                 Args[Arg].pack_size(),
1315                                 Policy, true);
1316     } else {
1317       if (Arg > 0)
1318         OS << ", ";
1319       Args[Arg].print(Policy, ArgOS);
1320     }
1321     StringRef ArgString = ArgOS.str();
1322 
1323     // If this is the first argument and its string representation
1324     // begins with the global scope specifier ('::foo'), add a space
1325     // to avoid printing the diagraph '<:'.
1326     if (!Arg && !ArgString.empty() && ArgString[0] == ':')
1327       OS << ' ';
1328 
1329     OS << ArgString;
1330 
1331     needSpace = (!ArgString.empty() && ArgString.back() == '>');
1332   }
1333 
1334   // If the last character of our string is '>', add another space to
1335   // keep the two '>''s separate tokens. We don't *have* to do this in
1336   // C++0x, but it's still good hygiene.
1337   if (needSpace)
1338     OS << ' ';
1339 
1340   if (!SkipBrackets)
1341     OS << '>';
1342 }
1343 
1344 // Sadly, repeat all that with TemplateArgLoc.
1345 void TemplateSpecializationType::
1346 PrintTemplateArgumentList(raw_ostream &OS,
1347                           const TemplateArgumentLoc *Args, unsigned NumArgs,
1348                           const PrintingPolicy &Policy) {
1349   OS << '<';
1350 
1351   bool needSpace = false;
1352   for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1353     if (Arg > 0)
1354       OS << ", ";
1355 
1356     // Print the argument into a string.
1357     SmallString<128> Buf;
1358     llvm::raw_svector_ostream ArgOS(Buf);
1359     if (Args[Arg].getArgument().getKind() == TemplateArgument::Pack) {
1360       PrintTemplateArgumentList(ArgOS,
1361                                 Args[Arg].getArgument().pack_begin(),
1362                                 Args[Arg].getArgument().pack_size(),
1363                                 Policy, true);
1364     } else {
1365       Args[Arg].getArgument().print(Policy, ArgOS);
1366     }
1367     StringRef ArgString = ArgOS.str();
1368 
1369     // If this is the first argument and its string representation
1370     // begins with the global scope specifier ('::foo'), add a space
1371     // to avoid printing the diagraph '<:'.
1372     if (!Arg && !ArgString.empty() && ArgString[0] == ':')
1373       OS << ' ';
1374 
1375     OS << ArgString;
1376 
1377     needSpace = (!ArgString.empty() && ArgString.back() == '>');
1378   }
1379 
1380   // If the last character of our string is '>', add another space to
1381   // keep the two '>''s separate tokens. We don't *have* to do this in
1382   // C++0x, but it's still good hygiene.
1383   if (needSpace)
1384     OS << ' ';
1385 
1386   OS << '>';
1387 }
1388 
1389 void QualType::dump(const char *msg) const {
1390   if (msg)
1391     llvm::errs() << msg << ": ";
1392   LangOptions LO;
1393   print(llvm::errs(), PrintingPolicy(LO), "identifier");
1394   llvm::errs() << '\n';
1395 }
1396 void QualType::dump() const {
1397   dump(0);
1398 }
1399 
1400 void Type::dump() const {
1401   QualType(this, 0).dump();
1402 }
1403 
1404 std::string Qualifiers::getAsString() const {
1405   LangOptions LO;
1406   return getAsString(PrintingPolicy(LO));
1407 }
1408 
1409 // Appends qualifiers to the given string, separated by spaces.  Will
1410 // prefix a space if the string is non-empty.  Will not append a final
1411 // space.
1412 std::string Qualifiers::getAsString(const PrintingPolicy &Policy) const {
1413   SmallString<64> Buf;
1414   llvm::raw_svector_ostream StrOS(Buf);
1415   print(StrOS, Policy);
1416   return StrOS.str();
1417 }
1418 
1419 bool Qualifiers::isEmptyWhenPrinted(const PrintingPolicy &Policy) const {
1420   if (getCVRQualifiers())
1421     return false;
1422 
1423   if (getAddressSpace())
1424     return false;
1425 
1426   if (getObjCGCAttr())
1427     return false;
1428 
1429   if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime())
1430     if (!(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime))
1431       return false;
1432 
1433   return true;
1434 }
1435 
1436 // Appends qualifiers to the given string, separated by spaces.  Will
1437 // prefix a space if the string is non-empty.  Will not append a final
1438 // space.
1439 void Qualifiers::print(raw_ostream &OS, const PrintingPolicy& Policy,
1440                        bool appendSpaceIfNonEmpty) const {
1441   bool addSpace = false;
1442 
1443   unsigned quals = getCVRQualifiers();
1444   if (quals) {
1445     AppendTypeQualList(OS, quals);
1446     addSpace = true;
1447   }
1448   if (unsigned addrspace = getAddressSpace()) {
1449     if (addSpace)
1450       OS << ' ';
1451     addSpace = true;
1452     switch (addrspace) {
1453       case LangAS::opencl_global:
1454         OS << "__global";
1455         break;
1456       case LangAS::opencl_local:
1457         OS << "__local";
1458         break;
1459       case LangAS::opencl_constant:
1460         OS << "__constant";
1461         break;
1462       default:
1463         OS << "__attribute__((address_space(";
1464         OS << addrspace;
1465         OS << ")))";
1466     }
1467   }
1468   if (Qualifiers::GC gc = getObjCGCAttr()) {
1469     if (addSpace)
1470       OS << ' ';
1471     addSpace = true;
1472     if (gc == Qualifiers::Weak)
1473       OS << "__weak";
1474     else
1475       OS << "__strong";
1476   }
1477   if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime()) {
1478     if (!(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime)){
1479       if (addSpace)
1480         OS << ' ';
1481       addSpace = true;
1482     }
1483 
1484     switch (lifetime) {
1485     case Qualifiers::OCL_None: llvm_unreachable("none but true");
1486     case Qualifiers::OCL_ExplicitNone: OS << "__unsafe_unretained"; break;
1487     case Qualifiers::OCL_Strong:
1488       if (!Policy.SuppressStrongLifetime)
1489         OS << "__strong";
1490       break;
1491 
1492     case Qualifiers::OCL_Weak: OS << "__weak"; break;
1493     case Qualifiers::OCL_Autoreleasing: OS << "__autoreleasing"; break;
1494     }
1495   }
1496 
1497   if (appendSpaceIfNonEmpty && addSpace)
1498     OS << ' ';
1499 }
1500 
1501 std::string QualType::getAsString(const PrintingPolicy &Policy) const {
1502   std::string S;
1503   getAsStringInternal(S, Policy);
1504   return S;
1505 }
1506 
1507 std::string QualType::getAsString(const Type *ty, Qualifiers qs) {
1508   std::string buffer;
1509   LangOptions options;
1510   getAsStringInternal(ty, qs, buffer, PrintingPolicy(options));
1511   return buffer;
1512 }
1513 
1514 void QualType::print(const Type *ty, Qualifiers qs,
1515                      raw_ostream &OS, const PrintingPolicy &policy,
1516                      const Twine &PlaceHolder) {
1517   SmallString<128> PHBuf;
1518   StringRef PH = PlaceHolder.toStringRef(PHBuf);
1519 
1520   TypePrinter(policy).print(ty, qs, OS, PH);
1521 }
1522 
1523 void QualType::getAsStringInternal(const Type *ty, Qualifiers qs,
1524                                    std::string &buffer,
1525                                    const PrintingPolicy &policy) {
1526   SmallString<256> Buf;
1527   llvm::raw_svector_ostream StrOS(Buf);
1528   TypePrinter(policy).print(ty, qs, StrOS, buffer);
1529   std::string str = StrOS.str();
1530   buffer.swap(str);
1531 }
1532