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