1 //===- TypePrinter.cpp - Pretty-Print Clang Types -------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This contains code to print types from Clang's type system. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/PrettyPrinter.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/Decl.h" 16 #include "clang/AST/DeclBase.h" 17 #include "clang/AST/DeclCXX.h" 18 #include "clang/AST/DeclObjC.h" 19 #include "clang/AST/DeclTemplate.h" 20 #include "clang/AST/Expr.h" 21 #include "clang/AST/NestedNameSpecifier.h" 22 #include "clang/AST/TemplateBase.h" 23 #include "clang/AST/TemplateName.h" 24 #include "clang/AST/Type.h" 25 #include "clang/Basic/AddressSpaces.h" 26 #include "clang/Basic/ExceptionSpecificationType.h" 27 #include "clang/Basic/IdentifierTable.h" 28 #include "clang/Basic/LLVM.h" 29 #include "clang/Basic/LangOptions.h" 30 #include "clang/Basic/SourceLocation.h" 31 #include "clang/Basic/SourceManager.h" 32 #include "clang/Basic/Specifiers.h" 33 #include "llvm/ADT/ArrayRef.h" 34 #include "llvm/ADT/SmallString.h" 35 #include "llvm/ADT/StringRef.h" 36 #include "llvm/ADT/Twine.h" 37 #include "llvm/Support/Casting.h" 38 #include "llvm/Support/Compiler.h" 39 #include "llvm/Support/ErrorHandling.h" 40 #include "llvm/Support/SaveAndRestore.h" 41 #include "llvm/Support/raw_ostream.h" 42 #include <cassert> 43 #include <string> 44 45 using namespace clang; 46 47 namespace { 48 49 /// RAII object that enables printing of the ARC __strong lifetime 50 /// qualifier. 51 class IncludeStrongLifetimeRAII { 52 PrintingPolicy &Policy; 53 bool Old; 54 55 public: 56 explicit IncludeStrongLifetimeRAII(PrintingPolicy &Policy) 57 : Policy(Policy), Old(Policy.SuppressStrongLifetime) { 58 if (!Policy.SuppressLifetimeQualifiers) 59 Policy.SuppressStrongLifetime = false; 60 } 61 62 ~IncludeStrongLifetimeRAII() { 63 Policy.SuppressStrongLifetime = Old; 64 } 65 }; 66 67 class ParamPolicyRAII { 68 PrintingPolicy &Policy; 69 bool Old; 70 71 public: 72 explicit ParamPolicyRAII(PrintingPolicy &Policy) 73 : Policy(Policy), Old(Policy.SuppressSpecifiers) { 74 Policy.SuppressSpecifiers = false; 75 } 76 77 ~ParamPolicyRAII() { 78 Policy.SuppressSpecifiers = Old; 79 } 80 }; 81 82 class ElaboratedTypePolicyRAII { 83 PrintingPolicy &Policy; 84 bool SuppressTagKeyword; 85 bool SuppressScope; 86 87 public: 88 explicit ElaboratedTypePolicyRAII(PrintingPolicy &Policy) : Policy(Policy) { 89 SuppressTagKeyword = Policy.SuppressTagKeyword; 90 SuppressScope = Policy.SuppressScope; 91 Policy.SuppressTagKeyword = true; 92 Policy.SuppressScope = true; 93 } 94 95 ~ElaboratedTypePolicyRAII() { 96 Policy.SuppressTagKeyword = SuppressTagKeyword; 97 Policy.SuppressScope = SuppressScope; 98 } 99 }; 100 101 class TypePrinter { 102 PrintingPolicy Policy; 103 unsigned Indentation; 104 bool HasEmptyPlaceHolder = false; 105 bool InsideCCAttribute = false; 106 107 public: 108 explicit TypePrinter(const PrintingPolicy &Policy, unsigned Indentation = 0) 109 : Policy(Policy), Indentation(Indentation) {} 110 111 void print(const Type *ty, Qualifiers qs, raw_ostream &OS, 112 StringRef PlaceHolder); 113 void print(QualType T, raw_ostream &OS, StringRef PlaceHolder); 114 115 static bool canPrefixQualifiers(const Type *T, bool &NeedARCStrongQualifier); 116 void spaceBeforePlaceHolder(raw_ostream &OS); 117 void printTypeSpec(NamedDecl *D, raw_ostream &OS); 118 119 void printBefore(QualType T, raw_ostream &OS); 120 void printAfter(QualType T, raw_ostream &OS); 121 void AppendScope(DeclContext *DC, raw_ostream &OS, 122 DeclarationName NameInScope); 123 void printTag(TagDecl *T, raw_ostream &OS); 124 void printFunctionAfter(const FunctionType::ExtInfo &Info, raw_ostream &OS); 125 #define ABSTRACT_TYPE(CLASS, PARENT) 126 #define TYPE(CLASS, PARENT) \ 127 void print##CLASS##Before(const CLASS##Type *T, raw_ostream &OS); \ 128 void print##CLASS##After(const CLASS##Type *T, raw_ostream &OS); 129 #include "clang/AST/TypeNodes.inc" 130 131 private: 132 void printBefore(const Type *ty, Qualifiers qs, raw_ostream &OS); 133 void printAfter(const Type *ty, Qualifiers qs, raw_ostream &OS); 134 }; 135 136 } // namespace 137 138 static void AppendTypeQualList(raw_ostream &OS, unsigned TypeQuals, 139 bool HasRestrictKeyword) { 140 bool appendSpace = false; 141 if (TypeQuals & Qualifiers::Const) { 142 OS << "const"; 143 appendSpace = true; 144 } 145 if (TypeQuals & Qualifiers::Volatile) { 146 if (appendSpace) OS << ' '; 147 OS << "volatile"; 148 appendSpace = true; 149 } 150 if (TypeQuals & Qualifiers::Restrict) { 151 if (appendSpace) OS << ' '; 152 if (HasRestrictKeyword) { 153 OS << "restrict"; 154 } else { 155 OS << "__restrict"; 156 } 157 } 158 } 159 160 void TypePrinter::spaceBeforePlaceHolder(raw_ostream &OS) { 161 if (!HasEmptyPlaceHolder) 162 OS << ' '; 163 } 164 165 static SplitQualType splitAccordingToPolicy(QualType QT, 166 const PrintingPolicy &Policy) { 167 if (Policy.PrintCanonicalTypes) 168 QT = QT.getCanonicalType(); 169 return QT.split(); 170 } 171 172 void TypePrinter::print(QualType t, raw_ostream &OS, StringRef PlaceHolder) { 173 SplitQualType split = splitAccordingToPolicy(t, Policy); 174 print(split.Ty, split.Quals, OS, PlaceHolder); 175 } 176 177 void TypePrinter::print(const Type *T, Qualifiers Quals, raw_ostream &OS, 178 StringRef PlaceHolder) { 179 if (!T) { 180 OS << "NULL TYPE"; 181 return; 182 } 183 184 SaveAndRestore<bool> PHVal(HasEmptyPlaceHolder, PlaceHolder.empty()); 185 186 printBefore(T, Quals, OS); 187 OS << PlaceHolder; 188 printAfter(T, Quals, OS); 189 } 190 191 bool TypePrinter::canPrefixQualifiers(const Type *T, 192 bool &NeedARCStrongQualifier) { 193 // CanPrefixQualifiers - We prefer to print type qualifiers before the type, 194 // so that we get "const int" instead of "int const", but we can't do this if 195 // the type is complex. For example if the type is "int*", we *must* print 196 // "int * const", printing "const int *" is different. Only do this when the 197 // type expands to a simple string. 198 bool CanPrefixQualifiers = false; 199 NeedARCStrongQualifier = false; 200 Type::TypeClass TC = T->getTypeClass(); 201 if (const auto *AT = dyn_cast<AutoType>(T)) 202 TC = AT->desugar()->getTypeClass(); 203 if (const auto *Subst = dyn_cast<SubstTemplateTypeParmType>(T)) 204 TC = Subst->getReplacementType()->getTypeClass(); 205 206 switch (TC) { 207 case Type::Auto: 208 case Type::Builtin: 209 case Type::Complex: 210 case Type::UnresolvedUsing: 211 case Type::Typedef: 212 case Type::TypeOfExpr: 213 case Type::TypeOf: 214 case Type::Decltype: 215 case Type::UnaryTransform: 216 case Type::Record: 217 case Type::Enum: 218 case Type::Elaborated: 219 case Type::TemplateTypeParm: 220 case Type::SubstTemplateTypeParmPack: 221 case Type::DeducedTemplateSpecialization: 222 case Type::TemplateSpecialization: 223 case Type::InjectedClassName: 224 case Type::DependentName: 225 case Type::DependentTemplateSpecialization: 226 case Type::ObjCObject: 227 case Type::ObjCTypeParam: 228 case Type::ObjCInterface: 229 case Type::Atomic: 230 case Type::Pipe: 231 case Type::ExtInt: 232 case Type::DependentExtInt: 233 CanPrefixQualifiers = true; 234 break; 235 236 case Type::ObjCObjectPointer: 237 CanPrefixQualifiers = T->isObjCIdType() || T->isObjCClassType() || 238 T->isObjCQualifiedIdType() || T->isObjCQualifiedClassType(); 239 break; 240 241 case Type::ConstantArray: 242 case Type::IncompleteArray: 243 case Type::VariableArray: 244 case Type::DependentSizedArray: 245 NeedARCStrongQualifier = true; 246 LLVM_FALLTHROUGH; 247 248 case Type::Adjusted: 249 case Type::Decayed: 250 case Type::Pointer: 251 case Type::BlockPointer: 252 case Type::LValueReference: 253 case Type::RValueReference: 254 case Type::MemberPointer: 255 case Type::DependentAddressSpace: 256 case Type::DependentVector: 257 case Type::DependentSizedExtVector: 258 case Type::Vector: 259 case Type::ExtVector: 260 case Type::ConstantMatrix: 261 case Type::DependentSizedMatrix: 262 case Type::FunctionProto: 263 case Type::FunctionNoProto: 264 case Type::Paren: 265 case Type::PackExpansion: 266 case Type::SubstTemplateTypeParm: 267 case Type::MacroQualified: 268 CanPrefixQualifiers = false; 269 break; 270 271 case Type::Attributed: { 272 // We still want to print the address_space before the type if it is an 273 // address_space attribute. 274 const auto *AttrTy = cast<AttributedType>(T); 275 CanPrefixQualifiers = AttrTy->getAttrKind() == attr::AddressSpace; 276 } 277 } 278 279 return CanPrefixQualifiers; 280 } 281 282 void TypePrinter::printBefore(QualType T, raw_ostream &OS) { 283 SplitQualType Split = splitAccordingToPolicy(T, Policy); 284 285 // If we have cv1 T, where T is substituted for cv2 U, only print cv1 - cv2 286 // at this level. 287 Qualifiers Quals = Split.Quals; 288 if (const auto *Subst = dyn_cast<SubstTemplateTypeParmType>(Split.Ty)) 289 Quals -= QualType(Subst, 0).getQualifiers(); 290 291 printBefore(Split.Ty, Quals, OS); 292 } 293 294 /// Prints the part of the type string before an identifier, e.g. for 295 /// "int foo[10]" it prints "int ". 296 void TypePrinter::printBefore(const Type *T,Qualifiers Quals, raw_ostream &OS) { 297 if (Policy.SuppressSpecifiers && T->isSpecifierType()) 298 return; 299 300 SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder); 301 302 // Print qualifiers as appropriate. 303 304 bool CanPrefixQualifiers = false; 305 bool NeedARCStrongQualifier = false; 306 CanPrefixQualifiers = canPrefixQualifiers(T, NeedARCStrongQualifier); 307 308 if (CanPrefixQualifiers && !Quals.empty()) { 309 if (NeedARCStrongQualifier) { 310 IncludeStrongLifetimeRAII Strong(Policy); 311 Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/true); 312 } else { 313 Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/true); 314 } 315 } 316 317 bool hasAfterQuals = false; 318 if (!CanPrefixQualifiers && !Quals.empty()) { 319 hasAfterQuals = !Quals.isEmptyWhenPrinted(Policy); 320 if (hasAfterQuals) 321 HasEmptyPlaceHolder = false; 322 } 323 324 switch (T->getTypeClass()) { 325 #define ABSTRACT_TYPE(CLASS, PARENT) 326 #define TYPE(CLASS, PARENT) case Type::CLASS: \ 327 print##CLASS##Before(cast<CLASS##Type>(T), OS); \ 328 break; 329 #include "clang/AST/TypeNodes.inc" 330 } 331 332 if (hasAfterQuals) { 333 if (NeedARCStrongQualifier) { 334 IncludeStrongLifetimeRAII Strong(Policy); 335 Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/!PrevPHIsEmpty.get()); 336 } else { 337 Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/!PrevPHIsEmpty.get()); 338 } 339 } 340 } 341 342 void TypePrinter::printAfter(QualType t, raw_ostream &OS) { 343 SplitQualType split = splitAccordingToPolicy(t, Policy); 344 printAfter(split.Ty, split.Quals, OS); 345 } 346 347 /// Prints the part of the type string after an identifier, e.g. for 348 /// "int foo[10]" it prints "[10]". 349 void TypePrinter::printAfter(const Type *T, Qualifiers Quals, raw_ostream &OS) { 350 switch (T->getTypeClass()) { 351 #define ABSTRACT_TYPE(CLASS, PARENT) 352 #define TYPE(CLASS, PARENT) case Type::CLASS: \ 353 print##CLASS##After(cast<CLASS##Type>(T), OS); \ 354 break; 355 #include "clang/AST/TypeNodes.inc" 356 } 357 } 358 359 void TypePrinter::printBuiltinBefore(const BuiltinType *T, raw_ostream &OS) { 360 OS << T->getName(Policy); 361 spaceBeforePlaceHolder(OS); 362 } 363 364 void TypePrinter::printBuiltinAfter(const BuiltinType *T, raw_ostream &OS) {} 365 366 void TypePrinter::printComplexBefore(const ComplexType *T, raw_ostream &OS) { 367 OS << "_Complex "; 368 printBefore(T->getElementType(), OS); 369 } 370 371 void TypePrinter::printComplexAfter(const ComplexType *T, raw_ostream &OS) { 372 printAfter(T->getElementType(), OS); 373 } 374 375 void TypePrinter::printPointerBefore(const PointerType *T, raw_ostream &OS) { 376 IncludeStrongLifetimeRAII Strong(Policy); 377 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 378 printBefore(T->getPointeeType(), 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->getPointeeType())) 382 OS << '('; 383 OS << '*'; 384 } 385 386 void TypePrinter::printPointerAfter(const PointerType *T, 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->getPointeeType())) 392 OS << ')'; 393 printAfter(T->getPointeeType(), OS); 394 } 395 396 void TypePrinter::printBlockPointerBefore(const BlockPointerType *T, 397 raw_ostream &OS) { 398 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 399 printBefore(T->getPointeeType(), OS); 400 OS << '^'; 401 } 402 403 void TypePrinter::printBlockPointerAfter(const BlockPointerType *T, 404 raw_ostream &OS) { 405 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 406 printAfter(T->getPointeeType(), OS); 407 } 408 409 // When printing a reference, the referenced type might also be a reference. 410 // If so, we want to skip that before printing the inner type. 411 static QualType skipTopLevelReferences(QualType T) { 412 if (auto *Ref = T->getAs<ReferenceType>()) 413 return skipTopLevelReferences(Ref->getPointeeTypeAsWritten()); 414 return T; 415 } 416 417 void TypePrinter::printLValueReferenceBefore(const LValueReferenceType *T, 418 raw_ostream &OS) { 419 IncludeStrongLifetimeRAII Strong(Policy); 420 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 421 QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten()); 422 printBefore(Inner, OS); 423 // Handle things like 'int (&A)[4];' correctly. 424 // FIXME: this should include vectors, but vectors use attributes I guess. 425 if (isa<ArrayType>(Inner)) 426 OS << '('; 427 OS << '&'; 428 } 429 430 void TypePrinter::printLValueReferenceAfter(const LValueReferenceType *T, 431 raw_ostream &OS) { 432 IncludeStrongLifetimeRAII Strong(Policy); 433 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 434 QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten()); 435 // Handle things like 'int (&A)[4];' correctly. 436 // FIXME: this should include vectors, but vectors use attributes I guess. 437 if (isa<ArrayType>(Inner)) 438 OS << ')'; 439 printAfter(Inner, OS); 440 } 441 442 void TypePrinter::printRValueReferenceBefore(const RValueReferenceType *T, 443 raw_ostream &OS) { 444 IncludeStrongLifetimeRAII Strong(Policy); 445 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 446 QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten()); 447 printBefore(Inner, OS); 448 // Handle things like 'int (&&A)[4];' correctly. 449 // FIXME: this should include vectors, but vectors use attributes I guess. 450 if (isa<ArrayType>(Inner)) 451 OS << '('; 452 OS << "&&"; 453 } 454 455 void TypePrinter::printRValueReferenceAfter(const RValueReferenceType *T, 456 raw_ostream &OS) { 457 IncludeStrongLifetimeRAII Strong(Policy); 458 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 459 QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten()); 460 // Handle things like 'int (&&A)[4];' correctly. 461 // FIXME: this should include vectors, but vectors use attributes I guess. 462 if (isa<ArrayType>(Inner)) 463 OS << ')'; 464 printAfter(Inner, OS); 465 } 466 467 void TypePrinter::printMemberPointerBefore(const MemberPointerType *T, 468 raw_ostream &OS) { 469 IncludeStrongLifetimeRAII Strong(Policy); 470 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 471 printBefore(T->getPointeeType(), OS); 472 // Handle things like 'int (Cls::*A)[4];' correctly. 473 // FIXME: this should include vectors, but vectors use attributes I guess. 474 if (isa<ArrayType>(T->getPointeeType())) 475 OS << '('; 476 477 PrintingPolicy InnerPolicy(Policy); 478 InnerPolicy.IncludeTagDefinition = false; 479 TypePrinter(InnerPolicy).print(QualType(T->getClass(), 0), OS, StringRef()); 480 481 OS << "::*"; 482 } 483 484 void TypePrinter::printMemberPointerAfter(const MemberPointerType *T, 485 raw_ostream &OS) { 486 IncludeStrongLifetimeRAII Strong(Policy); 487 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 488 // Handle things like 'int (Cls::*A)[4];' correctly. 489 // FIXME: this should include vectors, but vectors use attributes I guess. 490 if (isa<ArrayType>(T->getPointeeType())) 491 OS << ')'; 492 printAfter(T->getPointeeType(), OS); 493 } 494 495 void TypePrinter::printConstantArrayBefore(const ConstantArrayType *T, 496 raw_ostream &OS) { 497 IncludeStrongLifetimeRAII Strong(Policy); 498 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 499 printBefore(T->getElementType(), OS); 500 } 501 502 void TypePrinter::printConstantArrayAfter(const ConstantArrayType *T, 503 raw_ostream &OS) { 504 OS << '['; 505 if (T->getIndexTypeQualifiers().hasQualifiers()) { 506 AppendTypeQualList(OS, T->getIndexTypeCVRQualifiers(), 507 Policy.Restrict); 508 OS << ' '; 509 } 510 511 if (T->getSizeModifier() == ArrayType::Static) 512 OS << "static "; 513 514 OS << T->getSize().getZExtValue() << ']'; 515 printAfter(T->getElementType(), OS); 516 } 517 518 void TypePrinter::printIncompleteArrayBefore(const IncompleteArrayType *T, 519 raw_ostream &OS) { 520 IncludeStrongLifetimeRAII Strong(Policy); 521 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 522 printBefore(T->getElementType(), OS); 523 } 524 525 void TypePrinter::printIncompleteArrayAfter(const IncompleteArrayType *T, 526 raw_ostream &OS) { 527 OS << "[]"; 528 printAfter(T->getElementType(), OS); 529 } 530 531 void TypePrinter::printVariableArrayBefore(const VariableArrayType *T, 532 raw_ostream &OS) { 533 IncludeStrongLifetimeRAII Strong(Policy); 534 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 535 printBefore(T->getElementType(), OS); 536 } 537 538 void TypePrinter::printVariableArrayAfter(const VariableArrayType *T, 539 raw_ostream &OS) { 540 OS << '['; 541 if (T->getIndexTypeQualifiers().hasQualifiers()) { 542 AppendTypeQualList(OS, T->getIndexTypeCVRQualifiers(), Policy.Restrict); 543 OS << ' '; 544 } 545 546 if (T->getSizeModifier() == VariableArrayType::Static) 547 OS << "static "; 548 else if (T->getSizeModifier() == VariableArrayType::Star) 549 OS << '*'; 550 551 if (T->getSizeExpr()) 552 T->getSizeExpr()->printPretty(OS, nullptr, Policy); 553 OS << ']'; 554 555 printAfter(T->getElementType(), OS); 556 } 557 558 void TypePrinter::printAdjustedBefore(const AdjustedType *T, raw_ostream &OS) { 559 // Print the adjusted representation, otherwise the adjustment will be 560 // invisible. 561 printBefore(T->getAdjustedType(), OS); 562 } 563 564 void TypePrinter::printAdjustedAfter(const AdjustedType *T, raw_ostream &OS) { 565 printAfter(T->getAdjustedType(), OS); 566 } 567 568 void TypePrinter::printDecayedBefore(const DecayedType *T, raw_ostream &OS) { 569 // Print as though it's a pointer. 570 printAdjustedBefore(T, OS); 571 } 572 573 void TypePrinter::printDecayedAfter(const DecayedType *T, raw_ostream &OS) { 574 printAdjustedAfter(T, OS); 575 } 576 577 void TypePrinter::printDependentSizedArrayBefore( 578 const DependentSizedArrayType *T, 579 raw_ostream &OS) { 580 IncludeStrongLifetimeRAII Strong(Policy); 581 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 582 printBefore(T->getElementType(), OS); 583 } 584 585 void TypePrinter::printDependentSizedArrayAfter( 586 const DependentSizedArrayType *T, 587 raw_ostream &OS) { 588 OS << '['; 589 if (T->getSizeExpr()) 590 T->getSizeExpr()->printPretty(OS, nullptr, Policy); 591 OS << ']'; 592 printAfter(T->getElementType(), OS); 593 } 594 595 void TypePrinter::printDependentAddressSpaceBefore( 596 const DependentAddressSpaceType *T, raw_ostream &OS) { 597 printBefore(T->getPointeeType(), OS); 598 } 599 600 void TypePrinter::printDependentAddressSpaceAfter( 601 const DependentAddressSpaceType *T, raw_ostream &OS) { 602 OS << " __attribute__((address_space("; 603 if (T->getAddrSpaceExpr()) 604 T->getAddrSpaceExpr()->printPretty(OS, nullptr, Policy); 605 OS << ")))"; 606 printAfter(T->getPointeeType(), OS); 607 } 608 609 void TypePrinter::printDependentSizedExtVectorBefore( 610 const DependentSizedExtVectorType *T, 611 raw_ostream &OS) { 612 printBefore(T->getElementType(), OS); 613 } 614 615 void TypePrinter::printDependentSizedExtVectorAfter( 616 const DependentSizedExtVectorType *T, 617 raw_ostream &OS) { 618 OS << " __attribute__((ext_vector_type("; 619 if (T->getSizeExpr()) 620 T->getSizeExpr()->printPretty(OS, nullptr, Policy); 621 OS << ")))"; 622 printAfter(T->getElementType(), OS); 623 } 624 625 void TypePrinter::printVectorBefore(const VectorType *T, raw_ostream &OS) { 626 switch (T->getVectorKind()) { 627 case VectorType::AltiVecPixel: 628 OS << "__vector __pixel "; 629 break; 630 case VectorType::AltiVecBool: 631 OS << "__vector __bool "; 632 printBefore(T->getElementType(), OS); 633 break; 634 case VectorType::AltiVecVector: 635 OS << "__vector "; 636 printBefore(T->getElementType(), OS); 637 break; 638 case VectorType::NeonVector: 639 OS << "__attribute__((neon_vector_type(" 640 << T->getNumElements() << "))) "; 641 printBefore(T->getElementType(), OS); 642 break; 643 case VectorType::NeonPolyVector: 644 OS << "__attribute__((neon_polyvector_type(" << 645 T->getNumElements() << "))) "; 646 printBefore(T->getElementType(), OS); 647 break; 648 case VectorType::GenericVector: { 649 // FIXME: We prefer to print the size directly here, but have no way 650 // to get the size of the type. 651 OS << "__attribute__((__vector_size__(" 652 << T->getNumElements() 653 << " * sizeof("; 654 print(T->getElementType(), OS, StringRef()); 655 OS << ")))) "; 656 printBefore(T->getElementType(), OS); 657 break; 658 } 659 case VectorType::SveFixedLengthDataVector: 660 case VectorType::SveFixedLengthPredicateVector: 661 // FIXME: We prefer to print the size directly here, but have no way 662 // to get the size of the type. 663 OS << "__attribute__((__arm_sve_vector_bits__("; 664 665 if (T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 666 // Predicates take a bit per byte of the vector size, multiply by 8 to 667 // get the number of bits passed to the attribute. 668 OS << T->getNumElements() * 8; 669 else 670 OS << T->getNumElements(); 671 672 OS << " * sizeof("; 673 print(T->getElementType(), OS, StringRef()); 674 // Multiply by 8 for the number of bits. 675 OS << ") * 8))) "; 676 printBefore(T->getElementType(), OS); 677 } 678 } 679 680 void TypePrinter::printVectorAfter(const VectorType *T, raw_ostream &OS) { 681 printAfter(T->getElementType(), OS); 682 } 683 684 void TypePrinter::printDependentVectorBefore( 685 const DependentVectorType *T, raw_ostream &OS) { 686 switch (T->getVectorKind()) { 687 case VectorType::AltiVecPixel: 688 OS << "__vector __pixel "; 689 break; 690 case VectorType::AltiVecBool: 691 OS << "__vector __bool "; 692 printBefore(T->getElementType(), OS); 693 break; 694 case VectorType::AltiVecVector: 695 OS << "__vector "; 696 printBefore(T->getElementType(), OS); 697 break; 698 case VectorType::NeonVector: 699 OS << "__attribute__((neon_vector_type("; 700 if (T->getSizeExpr()) 701 T->getSizeExpr()->printPretty(OS, nullptr, Policy); 702 OS << "))) "; 703 printBefore(T->getElementType(), OS); 704 break; 705 case VectorType::NeonPolyVector: 706 OS << "__attribute__((neon_polyvector_type("; 707 if (T->getSizeExpr()) 708 T->getSizeExpr()->printPretty(OS, nullptr, Policy); 709 OS << "))) "; 710 printBefore(T->getElementType(), OS); 711 break; 712 case VectorType::GenericVector: { 713 // FIXME: We prefer to print the size directly here, but have no way 714 // to get the size of the type. 715 OS << "__attribute__((__vector_size__("; 716 if (T->getSizeExpr()) 717 T->getSizeExpr()->printPretty(OS, nullptr, Policy); 718 OS << " * sizeof("; 719 print(T->getElementType(), OS, StringRef()); 720 OS << ")))) "; 721 printBefore(T->getElementType(), OS); 722 break; 723 } 724 case VectorType::SveFixedLengthDataVector: 725 case VectorType::SveFixedLengthPredicateVector: 726 // FIXME: We prefer to print the size directly here, but have no way 727 // to get the size of the type. 728 OS << "__attribute__((__arm_sve_vector_bits__("; 729 if (T->getSizeExpr()) { 730 T->getSizeExpr()->printPretty(OS, nullptr, Policy); 731 if (T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 732 // Predicates take a bit per byte of the vector size, multiply by 8 to 733 // get the number of bits passed to the attribute. 734 OS << " * 8"; 735 OS << " * sizeof("; 736 print(T->getElementType(), OS, StringRef()); 737 // Multiply by 8 for the number of bits. 738 OS << ") * 8"; 739 } 740 OS << "))) "; 741 printBefore(T->getElementType(), OS); 742 } 743 } 744 745 void TypePrinter::printDependentVectorAfter( 746 const DependentVectorType *T, raw_ostream &OS) { 747 printAfter(T->getElementType(), OS); 748 } 749 750 void TypePrinter::printExtVectorBefore(const ExtVectorType *T, 751 raw_ostream &OS) { 752 printBefore(T->getElementType(), OS); 753 } 754 755 void TypePrinter::printExtVectorAfter(const ExtVectorType *T, raw_ostream &OS) { 756 printAfter(T->getElementType(), OS); 757 OS << " __attribute__((ext_vector_type("; 758 OS << T->getNumElements(); 759 OS << ")))"; 760 } 761 762 void TypePrinter::printConstantMatrixBefore(const ConstantMatrixType *T, 763 raw_ostream &OS) { 764 printBefore(T->getElementType(), OS); 765 OS << " __attribute__((matrix_type("; 766 OS << T->getNumRows() << ", " << T->getNumColumns(); 767 OS << ")))"; 768 } 769 770 void TypePrinter::printConstantMatrixAfter(const ConstantMatrixType *T, 771 raw_ostream &OS) { 772 printAfter(T->getElementType(), OS); 773 } 774 775 void TypePrinter::printDependentSizedMatrixBefore( 776 const DependentSizedMatrixType *T, raw_ostream &OS) { 777 printBefore(T->getElementType(), OS); 778 OS << " __attribute__((matrix_type("; 779 if (T->getRowExpr()) { 780 T->getRowExpr()->printPretty(OS, nullptr, Policy); 781 } 782 OS << ", "; 783 if (T->getColumnExpr()) { 784 T->getColumnExpr()->printPretty(OS, nullptr, Policy); 785 } 786 OS << ")))"; 787 } 788 789 void TypePrinter::printDependentSizedMatrixAfter( 790 const DependentSizedMatrixType *T, raw_ostream &OS) { 791 printAfter(T->getElementType(), OS); 792 } 793 794 void 795 FunctionProtoType::printExceptionSpecification(raw_ostream &OS, 796 const PrintingPolicy &Policy) 797 const { 798 if (hasDynamicExceptionSpec()) { 799 OS << " throw("; 800 if (getExceptionSpecType() == EST_MSAny) 801 OS << "..."; 802 else 803 for (unsigned I = 0, N = getNumExceptions(); I != N; ++I) { 804 if (I) 805 OS << ", "; 806 807 OS << getExceptionType(I).stream(Policy); 808 } 809 OS << ')'; 810 } else if (EST_NoThrow == getExceptionSpecType()) { 811 OS << " __attribute__((nothrow))"; 812 } else if (isNoexceptExceptionSpec(getExceptionSpecType())) { 813 OS << " noexcept"; 814 // FIXME:Is it useful to print out the expression for a non-dependent 815 // noexcept specification? 816 if (isComputedNoexcept(getExceptionSpecType())) { 817 OS << '('; 818 if (getNoexceptExpr()) 819 getNoexceptExpr()->printPretty(OS, nullptr, Policy); 820 OS << ')'; 821 } 822 } 823 } 824 825 void TypePrinter::printFunctionProtoBefore(const FunctionProtoType *T, 826 raw_ostream &OS) { 827 if (T->hasTrailingReturn()) { 828 OS << "auto "; 829 if (!HasEmptyPlaceHolder) 830 OS << '('; 831 } else { 832 // If needed for precedence reasons, wrap the inner part in grouping parens. 833 SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder, false); 834 printBefore(T->getReturnType(), OS); 835 if (!PrevPHIsEmpty.get()) 836 OS << '('; 837 } 838 } 839 840 StringRef clang::getParameterABISpelling(ParameterABI ABI) { 841 switch (ABI) { 842 case ParameterABI::Ordinary: 843 llvm_unreachable("asking for spelling of ordinary parameter ABI"); 844 case ParameterABI::SwiftContext: 845 return "swift_context"; 846 case ParameterABI::SwiftErrorResult: 847 return "swift_error_result"; 848 case ParameterABI::SwiftIndirectResult: 849 return "swift_indirect_result"; 850 } 851 llvm_unreachable("bad parameter ABI kind"); 852 } 853 854 void TypePrinter::printFunctionProtoAfter(const FunctionProtoType *T, 855 raw_ostream &OS) { 856 // If needed for precedence reasons, wrap the inner part in grouping parens. 857 if (!HasEmptyPlaceHolder) 858 OS << ')'; 859 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 860 861 OS << '('; 862 { 863 ParamPolicyRAII ParamPolicy(Policy); 864 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i) { 865 if (i) OS << ", "; 866 867 auto EPI = T->getExtParameterInfo(i); 868 if (EPI.isConsumed()) OS << "__attribute__((ns_consumed)) "; 869 if (EPI.isNoEscape()) 870 OS << "__attribute__((noescape)) "; 871 auto ABI = EPI.getABI(); 872 if (ABI != ParameterABI::Ordinary) 873 OS << "__attribute__((" << getParameterABISpelling(ABI) << ")) "; 874 875 print(T->getParamType(i), OS, StringRef()); 876 } 877 } 878 879 if (T->isVariadic()) { 880 if (T->getNumParams()) 881 OS << ", "; 882 OS << "..."; 883 } else if (T->getNumParams() == 0 && Policy.UseVoidForZeroParams) { 884 // Do not emit int() if we have a proto, emit 'int(void)'. 885 OS << "void"; 886 } 887 888 OS << ')'; 889 890 FunctionType::ExtInfo Info = T->getExtInfo(); 891 892 printFunctionAfter(Info, OS); 893 894 if (!T->getMethodQuals().empty()) 895 OS << " " << T->getMethodQuals().getAsString(); 896 897 switch (T->getRefQualifier()) { 898 case RQ_None: 899 break; 900 901 case RQ_LValue: 902 OS << " &"; 903 break; 904 905 case RQ_RValue: 906 OS << " &&"; 907 break; 908 } 909 T->printExceptionSpecification(OS, Policy); 910 911 if (T->hasTrailingReturn()) { 912 OS << " -> "; 913 print(T->getReturnType(), OS, StringRef()); 914 } else 915 printAfter(T->getReturnType(), OS); 916 } 917 918 void TypePrinter::printFunctionAfter(const FunctionType::ExtInfo &Info, 919 raw_ostream &OS) { 920 if (!InsideCCAttribute) { 921 switch (Info.getCC()) { 922 case CC_C: 923 // The C calling convention is the default on the vast majority of platforms 924 // we support. If the user wrote it explicitly, it will usually be printed 925 // while traversing the AttributedType. If the type has been desugared, let 926 // the canonical spelling be the implicit calling convention. 927 // FIXME: It would be better to be explicit in certain contexts, such as a 928 // cdecl function typedef used to declare a member function with the 929 // Microsoft C++ ABI. 930 break; 931 case CC_X86StdCall: 932 OS << " __attribute__((stdcall))"; 933 break; 934 case CC_X86FastCall: 935 OS << " __attribute__((fastcall))"; 936 break; 937 case CC_X86ThisCall: 938 OS << " __attribute__((thiscall))"; 939 break; 940 case CC_X86VectorCall: 941 OS << " __attribute__((vectorcall))"; 942 break; 943 case CC_X86Pascal: 944 OS << " __attribute__((pascal))"; 945 break; 946 case CC_AAPCS: 947 OS << " __attribute__((pcs(\"aapcs\")))"; 948 break; 949 case CC_AAPCS_VFP: 950 OS << " __attribute__((pcs(\"aapcs-vfp\")))"; 951 break; 952 case CC_AArch64VectorCall: 953 OS << "__attribute__((aarch64_vector_pcs))"; 954 break; 955 case CC_IntelOclBicc: 956 OS << " __attribute__((intel_ocl_bicc))"; 957 break; 958 case CC_Win64: 959 OS << " __attribute__((ms_abi))"; 960 break; 961 case CC_X86_64SysV: 962 OS << " __attribute__((sysv_abi))"; 963 break; 964 case CC_X86RegCall: 965 OS << " __attribute__((regcall))"; 966 break; 967 case CC_SpirFunction: 968 case CC_OpenCLKernel: 969 // Do nothing. These CCs are not available as attributes. 970 break; 971 case CC_Swift: 972 OS << " __attribute__((swiftcall))"; 973 break; 974 case CC_PreserveMost: 975 OS << " __attribute__((preserve_most))"; 976 break; 977 case CC_PreserveAll: 978 OS << " __attribute__((preserve_all))"; 979 break; 980 } 981 } 982 983 if (Info.getNoReturn()) 984 OS << " __attribute__((noreturn))"; 985 if (Info.getCmseNSCall()) 986 OS << " __attribute__((cmse_nonsecure_call))"; 987 if (Info.getProducesResult()) 988 OS << " __attribute__((ns_returns_retained))"; 989 if (Info.getRegParm()) 990 OS << " __attribute__((regparm (" 991 << Info.getRegParm() << ")))"; 992 if (Info.getNoCallerSavedRegs()) 993 OS << " __attribute__((no_caller_saved_registers))"; 994 if (Info.getNoCfCheck()) 995 OS << " __attribute__((nocf_check))"; 996 } 997 998 void TypePrinter::printFunctionNoProtoBefore(const FunctionNoProtoType *T, 999 raw_ostream &OS) { 1000 // If needed for precedence reasons, wrap the inner part in grouping parens. 1001 SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder, false); 1002 printBefore(T->getReturnType(), OS); 1003 if (!PrevPHIsEmpty.get()) 1004 OS << '('; 1005 } 1006 1007 void TypePrinter::printFunctionNoProtoAfter(const FunctionNoProtoType *T, 1008 raw_ostream &OS) { 1009 // If needed for precedence reasons, wrap the inner part in grouping parens. 1010 if (!HasEmptyPlaceHolder) 1011 OS << ')'; 1012 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 1013 1014 OS << "()"; 1015 printFunctionAfter(T->getExtInfo(), OS); 1016 printAfter(T->getReturnType(), OS); 1017 } 1018 1019 void TypePrinter::printTypeSpec(NamedDecl *D, raw_ostream &OS) { 1020 1021 // Compute the full nested-name-specifier for this type. 1022 // In C, this will always be empty except when the type 1023 // being printed is anonymous within other Record. 1024 if (!Policy.SuppressScope) 1025 AppendScope(D->getDeclContext(), OS, D->getDeclName()); 1026 1027 IdentifierInfo *II = D->getIdentifier(); 1028 OS << II->getName(); 1029 spaceBeforePlaceHolder(OS); 1030 } 1031 1032 void TypePrinter::printUnresolvedUsingBefore(const UnresolvedUsingType *T, 1033 raw_ostream &OS) { 1034 printTypeSpec(T->getDecl(), OS); 1035 } 1036 1037 void TypePrinter::printUnresolvedUsingAfter(const UnresolvedUsingType *T, 1038 raw_ostream &OS) {} 1039 1040 void TypePrinter::printTypedefBefore(const TypedefType *T, raw_ostream &OS) { 1041 printTypeSpec(T->getDecl(), OS); 1042 } 1043 1044 void TypePrinter::printMacroQualifiedBefore(const MacroQualifiedType *T, 1045 raw_ostream &OS) { 1046 StringRef MacroName = T->getMacroIdentifier()->getName(); 1047 OS << MacroName << " "; 1048 1049 // Since this type is meant to print the macro instead of the whole attribute, 1050 // we trim any attributes and go directly to the original modified type. 1051 printBefore(T->getModifiedType(), OS); 1052 } 1053 1054 void TypePrinter::printMacroQualifiedAfter(const MacroQualifiedType *T, 1055 raw_ostream &OS) { 1056 printAfter(T->getModifiedType(), OS); 1057 } 1058 1059 void TypePrinter::printTypedefAfter(const TypedefType *T, raw_ostream &OS) {} 1060 1061 void TypePrinter::printTypeOfExprBefore(const TypeOfExprType *T, 1062 raw_ostream &OS) { 1063 OS << "typeof "; 1064 if (T->getUnderlyingExpr()) 1065 T->getUnderlyingExpr()->printPretty(OS, nullptr, Policy); 1066 spaceBeforePlaceHolder(OS); 1067 } 1068 1069 void TypePrinter::printTypeOfExprAfter(const TypeOfExprType *T, 1070 raw_ostream &OS) {} 1071 1072 void TypePrinter::printTypeOfBefore(const TypeOfType *T, raw_ostream &OS) { 1073 OS << "typeof("; 1074 print(T->getUnderlyingType(), OS, StringRef()); 1075 OS << ')'; 1076 spaceBeforePlaceHolder(OS); 1077 } 1078 1079 void TypePrinter::printTypeOfAfter(const TypeOfType *T, raw_ostream &OS) {} 1080 1081 void TypePrinter::printDecltypeBefore(const DecltypeType *T, raw_ostream &OS) { 1082 OS << "decltype("; 1083 if (T->getUnderlyingExpr()) 1084 T->getUnderlyingExpr()->printPretty(OS, nullptr, Policy); 1085 OS << ')'; 1086 spaceBeforePlaceHolder(OS); 1087 } 1088 1089 void TypePrinter::printDecltypeAfter(const DecltypeType *T, raw_ostream &OS) {} 1090 1091 void TypePrinter::printUnaryTransformBefore(const UnaryTransformType *T, 1092 raw_ostream &OS) { 1093 IncludeStrongLifetimeRAII Strong(Policy); 1094 1095 switch (T->getUTTKind()) { 1096 case UnaryTransformType::EnumUnderlyingType: 1097 OS << "__underlying_type("; 1098 print(T->getBaseType(), OS, StringRef()); 1099 OS << ')'; 1100 spaceBeforePlaceHolder(OS); 1101 return; 1102 } 1103 1104 printBefore(T->getBaseType(), OS); 1105 } 1106 1107 void TypePrinter::printUnaryTransformAfter(const UnaryTransformType *T, 1108 raw_ostream &OS) { 1109 IncludeStrongLifetimeRAII Strong(Policy); 1110 1111 switch (T->getUTTKind()) { 1112 case UnaryTransformType::EnumUnderlyingType: 1113 return; 1114 } 1115 1116 printAfter(T->getBaseType(), OS); 1117 } 1118 1119 void TypePrinter::printAutoBefore(const AutoType *T, raw_ostream &OS) { 1120 // If the type has been deduced, do not print 'auto'. 1121 if (!T->getDeducedType().isNull()) { 1122 printBefore(T->getDeducedType(), OS); 1123 } else { 1124 if (T->isConstrained()) { 1125 OS << T->getTypeConstraintConcept()->getName(); 1126 auto Args = T->getTypeConstraintArguments(); 1127 if (!Args.empty()) 1128 printTemplateArgumentList( 1129 OS, Args, Policy, 1130 T->getTypeConstraintConcept()->getTemplateParameters()); 1131 OS << ' '; 1132 } 1133 switch (T->getKeyword()) { 1134 case AutoTypeKeyword::Auto: OS << "auto"; break; 1135 case AutoTypeKeyword::DecltypeAuto: OS << "decltype(auto)"; break; 1136 case AutoTypeKeyword::GNUAutoType: OS << "__auto_type"; break; 1137 } 1138 spaceBeforePlaceHolder(OS); 1139 } 1140 } 1141 1142 void TypePrinter::printAutoAfter(const AutoType *T, raw_ostream &OS) { 1143 // If the type has been deduced, do not print 'auto'. 1144 if (!T->getDeducedType().isNull()) 1145 printAfter(T->getDeducedType(), OS); 1146 } 1147 1148 void TypePrinter::printDeducedTemplateSpecializationBefore( 1149 const DeducedTemplateSpecializationType *T, raw_ostream &OS) { 1150 // If the type has been deduced, print the deduced type. 1151 if (!T->getDeducedType().isNull()) { 1152 printBefore(T->getDeducedType(), OS); 1153 } else { 1154 IncludeStrongLifetimeRAII Strong(Policy); 1155 T->getTemplateName().print(OS, Policy); 1156 spaceBeforePlaceHolder(OS); 1157 } 1158 } 1159 1160 void TypePrinter::printDeducedTemplateSpecializationAfter( 1161 const DeducedTemplateSpecializationType *T, raw_ostream &OS) { 1162 // If the type has been deduced, print the deduced type. 1163 if (!T->getDeducedType().isNull()) 1164 printAfter(T->getDeducedType(), OS); 1165 } 1166 1167 void TypePrinter::printAtomicBefore(const AtomicType *T, raw_ostream &OS) { 1168 IncludeStrongLifetimeRAII Strong(Policy); 1169 1170 OS << "_Atomic("; 1171 print(T->getValueType(), OS, StringRef()); 1172 OS << ')'; 1173 spaceBeforePlaceHolder(OS); 1174 } 1175 1176 void TypePrinter::printAtomicAfter(const AtomicType *T, raw_ostream &OS) {} 1177 1178 void TypePrinter::printPipeBefore(const PipeType *T, raw_ostream &OS) { 1179 IncludeStrongLifetimeRAII Strong(Policy); 1180 1181 if (T->isReadOnly()) 1182 OS << "read_only "; 1183 else 1184 OS << "write_only "; 1185 OS << "pipe "; 1186 print(T->getElementType(), OS, StringRef()); 1187 spaceBeforePlaceHolder(OS); 1188 } 1189 1190 void TypePrinter::printPipeAfter(const PipeType *T, raw_ostream &OS) {} 1191 1192 void TypePrinter::printExtIntBefore(const ExtIntType *T, raw_ostream &OS) { 1193 if (T->isUnsigned()) 1194 OS << "unsigned "; 1195 OS << "_ExtInt(" << T->getNumBits() << ")"; 1196 spaceBeforePlaceHolder(OS); 1197 } 1198 1199 void TypePrinter::printExtIntAfter(const ExtIntType *T, raw_ostream &OS) {} 1200 1201 void TypePrinter::printDependentExtIntBefore(const DependentExtIntType *T, 1202 raw_ostream &OS) { 1203 if (T->isUnsigned()) 1204 OS << "unsigned "; 1205 OS << "_ExtInt("; 1206 T->getNumBitsExpr()->printPretty(OS, nullptr, Policy); 1207 OS << ")"; 1208 spaceBeforePlaceHolder(OS); 1209 } 1210 1211 void TypePrinter::printDependentExtIntAfter(const DependentExtIntType *T, 1212 raw_ostream &OS) {} 1213 1214 /// Appends the given scope to the end of a string. 1215 void TypePrinter::AppendScope(DeclContext *DC, raw_ostream &OS, 1216 DeclarationName NameInScope) { 1217 if (DC->isTranslationUnit()) 1218 return; 1219 1220 // FIXME: Consider replacing this with NamedDecl::printNestedNameSpecifier, 1221 // which can also print names for function and method scopes. 1222 if (DC->isFunctionOrMethod()) 1223 return; 1224 1225 if (const auto *NS = dyn_cast<NamespaceDecl>(DC)) { 1226 if (Policy.SuppressUnwrittenScope && NS->isAnonymousNamespace()) 1227 return AppendScope(DC->getParent(), OS, NameInScope); 1228 1229 // Only suppress an inline namespace if the name has the same lookup 1230 // results in the enclosing namespace. 1231 if (Policy.SuppressInlineNamespace && NS->isInline() && NameInScope && 1232 DC->getParent()->lookup(NameInScope).size() == 1233 DC->lookup(NameInScope).size()) 1234 return AppendScope(DC->getParent(), OS, NameInScope); 1235 1236 AppendScope(DC->getParent(), OS, NS->getDeclName()); 1237 if (NS->getIdentifier()) 1238 OS << NS->getName() << "::"; 1239 else 1240 OS << "(anonymous namespace)::"; 1241 } else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 1242 AppendScope(DC->getParent(), OS, Spec->getDeclName()); 1243 IncludeStrongLifetimeRAII Strong(Policy); 1244 OS << Spec->getIdentifier()->getName(); 1245 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 1246 printTemplateArgumentList( 1247 OS, TemplateArgs.asArray(), Policy, 1248 Spec->getSpecializedTemplate()->getTemplateParameters()); 1249 OS << "::"; 1250 } else if (const auto *Tag = dyn_cast<TagDecl>(DC)) { 1251 AppendScope(DC->getParent(), OS, Tag->getDeclName()); 1252 if (TypedefNameDecl *Typedef = Tag->getTypedefNameForAnonDecl()) 1253 OS << Typedef->getIdentifier()->getName() << "::"; 1254 else if (Tag->getIdentifier()) 1255 OS << Tag->getIdentifier()->getName() << "::"; 1256 else 1257 return; 1258 } else { 1259 AppendScope(DC->getParent(), OS, NameInScope); 1260 } 1261 } 1262 1263 void TypePrinter::printTag(TagDecl *D, raw_ostream &OS) { 1264 if (Policy.IncludeTagDefinition) { 1265 PrintingPolicy SubPolicy = Policy; 1266 SubPolicy.IncludeTagDefinition = false; 1267 D->print(OS, SubPolicy, Indentation); 1268 spaceBeforePlaceHolder(OS); 1269 return; 1270 } 1271 1272 bool HasKindDecoration = false; 1273 1274 // We don't print tags unless this is an elaborated type. 1275 // In C, we just assume every RecordType is an elaborated type. 1276 if (!Policy.SuppressTagKeyword && !D->getTypedefNameForAnonDecl()) { 1277 HasKindDecoration = true; 1278 OS << D->getKindName(); 1279 OS << ' '; 1280 } 1281 1282 // Compute the full nested-name-specifier for this type. 1283 // In C, this will always be empty except when the type 1284 // being printed is anonymous within other Record. 1285 if (!Policy.SuppressScope) 1286 AppendScope(D->getDeclContext(), OS, D->getDeclName()); 1287 1288 if (const IdentifierInfo *II = D->getIdentifier()) 1289 OS << II->getName(); 1290 else if (TypedefNameDecl *Typedef = D->getTypedefNameForAnonDecl()) { 1291 assert(Typedef->getIdentifier() && "Typedef without identifier?"); 1292 OS << Typedef->getIdentifier()->getName(); 1293 } else { 1294 // Make an unambiguous representation for anonymous types, e.g. 1295 // (anonymous enum at /usr/include/string.h:120:9) 1296 OS << (Policy.MSVCFormatting ? '`' : '('); 1297 1298 if (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda()) { 1299 OS << "lambda"; 1300 HasKindDecoration = true; 1301 } else { 1302 OS << "anonymous"; 1303 } 1304 1305 if (Policy.AnonymousTagLocations) { 1306 // Suppress the redundant tag keyword if we just printed one. 1307 // We don't have to worry about ElaboratedTypes here because you can't 1308 // refer to an anonymous type with one. 1309 if (!HasKindDecoration) 1310 OS << " " << D->getKindName(); 1311 1312 PresumedLoc PLoc = D->getASTContext().getSourceManager().getPresumedLoc( 1313 D->getLocation()); 1314 if (PLoc.isValid()) { 1315 OS << " at "; 1316 StringRef File = PLoc.getFilename(); 1317 if (auto *Callbacks = Policy.Callbacks) 1318 OS << Callbacks->remapPath(File); 1319 else 1320 OS << File; 1321 OS << ':' << PLoc.getLine() << ':' << PLoc.getColumn(); 1322 } 1323 } 1324 1325 OS << (Policy.MSVCFormatting ? '\'' : ')'); 1326 } 1327 1328 // If this is a class template specialization, print the template 1329 // arguments. 1330 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 1331 ArrayRef<TemplateArgument> Args; 1332 TypeSourceInfo *TAW = Spec->getTypeAsWritten(); 1333 if (!Policy.PrintCanonicalTypes && TAW) { 1334 const TemplateSpecializationType *TST = 1335 cast<TemplateSpecializationType>(TAW->getType()); 1336 Args = TST->template_arguments(); 1337 } else { 1338 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 1339 Args = TemplateArgs.asArray(); 1340 } 1341 IncludeStrongLifetimeRAII Strong(Policy); 1342 printTemplateArgumentList( 1343 OS, Args, Policy, 1344 Spec->getSpecializedTemplate()->getTemplateParameters()); 1345 } 1346 1347 spaceBeforePlaceHolder(OS); 1348 } 1349 1350 void TypePrinter::printRecordBefore(const RecordType *T, raw_ostream &OS) { 1351 printTag(T->getDecl(), OS); 1352 } 1353 1354 void TypePrinter::printRecordAfter(const RecordType *T, raw_ostream &OS) {} 1355 1356 void TypePrinter::printEnumBefore(const EnumType *T, raw_ostream &OS) { 1357 printTag(T->getDecl(), OS); 1358 } 1359 1360 void TypePrinter::printEnumAfter(const EnumType *T, raw_ostream &OS) {} 1361 1362 void TypePrinter::printTemplateTypeParmBefore(const TemplateTypeParmType *T, 1363 raw_ostream &OS) { 1364 TemplateTypeParmDecl *D = T->getDecl(); 1365 if (D && D->isImplicit()) { 1366 if (auto *TC = D->getTypeConstraint()) { 1367 TC->print(OS, Policy); 1368 OS << ' '; 1369 } 1370 OS << "auto"; 1371 } else if (IdentifierInfo *Id = T->getIdentifier()) 1372 OS << Id->getName(); 1373 else 1374 OS << "type-parameter-" << T->getDepth() << '-' << T->getIndex(); 1375 1376 spaceBeforePlaceHolder(OS); 1377 } 1378 1379 void TypePrinter::printTemplateTypeParmAfter(const TemplateTypeParmType *T, 1380 raw_ostream &OS) {} 1381 1382 void TypePrinter::printSubstTemplateTypeParmBefore( 1383 const SubstTemplateTypeParmType *T, 1384 raw_ostream &OS) { 1385 IncludeStrongLifetimeRAII Strong(Policy); 1386 printBefore(T->getReplacementType(), OS); 1387 } 1388 1389 void TypePrinter::printSubstTemplateTypeParmAfter( 1390 const SubstTemplateTypeParmType *T, 1391 raw_ostream &OS) { 1392 IncludeStrongLifetimeRAII Strong(Policy); 1393 printAfter(T->getReplacementType(), OS); 1394 } 1395 1396 void TypePrinter::printSubstTemplateTypeParmPackBefore( 1397 const SubstTemplateTypeParmPackType *T, 1398 raw_ostream &OS) { 1399 IncludeStrongLifetimeRAII Strong(Policy); 1400 printTemplateTypeParmBefore(T->getReplacedParameter(), OS); 1401 } 1402 1403 void TypePrinter::printSubstTemplateTypeParmPackAfter( 1404 const SubstTemplateTypeParmPackType *T, 1405 raw_ostream &OS) { 1406 IncludeStrongLifetimeRAII Strong(Policy); 1407 printTemplateTypeParmAfter(T->getReplacedParameter(), OS); 1408 } 1409 1410 void TypePrinter::printTemplateSpecializationBefore( 1411 const TemplateSpecializationType *T, 1412 raw_ostream &OS) { 1413 IncludeStrongLifetimeRAII Strong(Policy); 1414 T->getTemplateName().print(OS, Policy); 1415 1416 const TemplateParameterList *TPL = nullptr; 1417 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) 1418 TPL = TD->getTemplateParameters(); 1419 1420 printTemplateArgumentList(OS, T->template_arguments(), Policy, TPL); 1421 spaceBeforePlaceHolder(OS); 1422 } 1423 1424 void TypePrinter::printTemplateSpecializationAfter( 1425 const TemplateSpecializationType *T, 1426 raw_ostream &OS) {} 1427 1428 void TypePrinter::printInjectedClassNameBefore(const InjectedClassNameType *T, 1429 raw_ostream &OS) { 1430 if (Policy.PrintInjectedClassNameWithArguments) 1431 return printTemplateSpecializationBefore(T->getInjectedTST(), OS); 1432 1433 IncludeStrongLifetimeRAII Strong(Policy); 1434 T->getTemplateName().print(OS, Policy); 1435 spaceBeforePlaceHolder(OS); 1436 } 1437 1438 void TypePrinter::printInjectedClassNameAfter(const InjectedClassNameType *T, 1439 raw_ostream &OS) {} 1440 1441 void TypePrinter::printElaboratedBefore(const ElaboratedType *T, 1442 raw_ostream &OS) { 1443 if (Policy.IncludeTagDefinition && T->getOwnedTagDecl()) { 1444 TagDecl *OwnedTagDecl = T->getOwnedTagDecl(); 1445 assert(OwnedTagDecl->getTypeForDecl() == T->getNamedType().getTypePtr() && 1446 "OwnedTagDecl expected to be a declaration for the type"); 1447 PrintingPolicy SubPolicy = Policy; 1448 SubPolicy.IncludeTagDefinition = false; 1449 OwnedTagDecl->print(OS, SubPolicy, Indentation); 1450 spaceBeforePlaceHolder(OS); 1451 return; 1452 } 1453 1454 // The tag definition will take care of these. 1455 if (!Policy.IncludeTagDefinition) 1456 { 1457 OS << TypeWithKeyword::getKeywordName(T->getKeyword()); 1458 if (T->getKeyword() != ETK_None) 1459 OS << " "; 1460 NestedNameSpecifier *Qualifier = T->getQualifier(); 1461 if (Qualifier) 1462 Qualifier->print(OS, Policy); 1463 } 1464 1465 ElaboratedTypePolicyRAII PolicyRAII(Policy); 1466 printBefore(T->getNamedType(), OS); 1467 } 1468 1469 void TypePrinter::printElaboratedAfter(const ElaboratedType *T, 1470 raw_ostream &OS) { 1471 if (Policy.IncludeTagDefinition && T->getOwnedTagDecl()) 1472 return; 1473 ElaboratedTypePolicyRAII PolicyRAII(Policy); 1474 printAfter(T->getNamedType(), OS); 1475 } 1476 1477 void TypePrinter::printParenBefore(const ParenType *T, raw_ostream &OS) { 1478 if (!HasEmptyPlaceHolder && !isa<FunctionType>(T->getInnerType())) { 1479 printBefore(T->getInnerType(), OS); 1480 OS << '('; 1481 } else 1482 printBefore(T->getInnerType(), OS); 1483 } 1484 1485 void TypePrinter::printParenAfter(const ParenType *T, raw_ostream &OS) { 1486 if (!HasEmptyPlaceHolder && !isa<FunctionType>(T->getInnerType())) { 1487 OS << ')'; 1488 printAfter(T->getInnerType(), OS); 1489 } else 1490 printAfter(T->getInnerType(), OS); 1491 } 1492 1493 void TypePrinter::printDependentNameBefore(const DependentNameType *T, 1494 raw_ostream &OS) { 1495 OS << TypeWithKeyword::getKeywordName(T->getKeyword()); 1496 if (T->getKeyword() != ETK_None) 1497 OS << " "; 1498 1499 T->getQualifier()->print(OS, Policy); 1500 1501 OS << T->getIdentifier()->getName(); 1502 spaceBeforePlaceHolder(OS); 1503 } 1504 1505 void TypePrinter::printDependentNameAfter(const DependentNameType *T, 1506 raw_ostream &OS) {} 1507 1508 void TypePrinter::printDependentTemplateSpecializationBefore( 1509 const DependentTemplateSpecializationType *T, raw_ostream &OS) { 1510 IncludeStrongLifetimeRAII Strong(Policy); 1511 1512 OS << TypeWithKeyword::getKeywordName(T->getKeyword()); 1513 if (T->getKeyword() != ETK_None) 1514 OS << " "; 1515 1516 if (T->getQualifier()) 1517 T->getQualifier()->print(OS, Policy); 1518 OS << "template " << T->getIdentifier()->getName(); 1519 printTemplateArgumentList(OS, T->template_arguments(), Policy); 1520 spaceBeforePlaceHolder(OS); 1521 } 1522 1523 void TypePrinter::printDependentTemplateSpecializationAfter( 1524 const DependentTemplateSpecializationType *T, raw_ostream &OS) {} 1525 1526 void TypePrinter::printPackExpansionBefore(const PackExpansionType *T, 1527 raw_ostream &OS) { 1528 printBefore(T->getPattern(), OS); 1529 } 1530 1531 void TypePrinter::printPackExpansionAfter(const PackExpansionType *T, 1532 raw_ostream &OS) { 1533 printAfter(T->getPattern(), OS); 1534 OS << "..."; 1535 } 1536 1537 void TypePrinter::printAttributedBefore(const AttributedType *T, 1538 raw_ostream &OS) { 1539 // FIXME: Generate this with TableGen. 1540 1541 // Prefer the macro forms of the GC and ownership qualifiers. 1542 if (T->getAttrKind() == attr::ObjCGC || 1543 T->getAttrKind() == attr::ObjCOwnership) 1544 return printBefore(T->getEquivalentType(), OS); 1545 1546 if (T->getAttrKind() == attr::ObjCKindOf) 1547 OS << "__kindof "; 1548 1549 if (T->getAttrKind() == attr::AddressSpace) 1550 printBefore(T->getEquivalentType(), OS); 1551 else 1552 printBefore(T->getModifiedType(), OS); 1553 1554 if (T->isMSTypeSpec()) { 1555 switch (T->getAttrKind()) { 1556 default: return; 1557 case attr::Ptr32: OS << " __ptr32"; break; 1558 case attr::Ptr64: OS << " __ptr64"; break; 1559 case attr::SPtr: OS << " __sptr"; break; 1560 case attr::UPtr: OS << " __uptr"; break; 1561 } 1562 spaceBeforePlaceHolder(OS); 1563 } 1564 1565 // Print nullability type specifiers. 1566 if (T->getImmediateNullability()) { 1567 if (T->getAttrKind() == attr::TypeNonNull) 1568 OS << " _Nonnull"; 1569 else if (T->getAttrKind() == attr::TypeNullable) 1570 OS << " _Nullable"; 1571 else if (T->getAttrKind() == attr::TypeNullUnspecified) 1572 OS << " _Null_unspecified"; 1573 else if (T->getAttrKind() == attr::TypeNullableResult) 1574 OS << " _Nullable_result"; 1575 else 1576 llvm_unreachable("unhandled nullability"); 1577 spaceBeforePlaceHolder(OS); 1578 } 1579 } 1580 1581 void TypePrinter::printAttributedAfter(const AttributedType *T, 1582 raw_ostream &OS) { 1583 // FIXME: Generate this with TableGen. 1584 1585 // Prefer the macro forms of the GC and ownership qualifiers. 1586 if (T->getAttrKind() == attr::ObjCGC || 1587 T->getAttrKind() == attr::ObjCOwnership) 1588 return printAfter(T->getEquivalentType(), OS); 1589 1590 // If this is a calling convention attribute, don't print the implicit CC from 1591 // the modified type. 1592 SaveAndRestore<bool> MaybeSuppressCC(InsideCCAttribute, T->isCallingConv()); 1593 1594 printAfter(T->getModifiedType(), OS); 1595 1596 // Some attributes are printed as qualifiers before the type, so we have 1597 // nothing left to do. 1598 if (T->getAttrKind() == attr::ObjCKindOf || 1599 T->isMSTypeSpec() || T->getImmediateNullability()) 1600 return; 1601 1602 // Don't print the inert __unsafe_unretained attribute at all. 1603 if (T->getAttrKind() == attr::ObjCInertUnsafeUnretained) 1604 return; 1605 1606 // Don't print ns_returns_retained unless it had an effect. 1607 if (T->getAttrKind() == attr::NSReturnsRetained && 1608 !T->getEquivalentType()->castAs<FunctionType>() 1609 ->getExtInfo().getProducesResult()) 1610 return; 1611 1612 if (T->getAttrKind() == attr::LifetimeBound) { 1613 OS << " [[clang::lifetimebound]]"; 1614 return; 1615 } 1616 1617 // The printing of the address_space attribute is handled by the qualifier 1618 // since it is still stored in the qualifier. Return early to prevent printing 1619 // this twice. 1620 if (T->getAttrKind() == attr::AddressSpace) 1621 return; 1622 1623 OS << " __attribute__(("; 1624 switch (T->getAttrKind()) { 1625 #define TYPE_ATTR(NAME) 1626 #define DECL_OR_TYPE_ATTR(NAME) 1627 #define ATTR(NAME) case attr::NAME: 1628 #include "clang/Basic/AttrList.inc" 1629 llvm_unreachable("non-type attribute attached to type"); 1630 1631 case attr::OpenCLPrivateAddressSpace: 1632 case attr::OpenCLGlobalAddressSpace: 1633 case attr::OpenCLGlobalDeviceAddressSpace: 1634 case attr::OpenCLGlobalHostAddressSpace: 1635 case attr::OpenCLLocalAddressSpace: 1636 case attr::OpenCLConstantAddressSpace: 1637 case attr::OpenCLGenericAddressSpace: 1638 // FIXME: Update printAttributedBefore to print these once we generate 1639 // AttributedType nodes for them. 1640 break; 1641 1642 case attr::LifetimeBound: 1643 case attr::TypeNonNull: 1644 case attr::TypeNullable: 1645 case attr::TypeNullableResult: 1646 case attr::TypeNullUnspecified: 1647 case attr::ObjCGC: 1648 case attr::ObjCInertUnsafeUnretained: 1649 case attr::ObjCKindOf: 1650 case attr::ObjCOwnership: 1651 case attr::Ptr32: 1652 case attr::Ptr64: 1653 case attr::SPtr: 1654 case attr::UPtr: 1655 case attr::AddressSpace: 1656 case attr::CmseNSCall: 1657 llvm_unreachable("This attribute should have been handled already"); 1658 1659 case attr::NSReturnsRetained: 1660 OS << "ns_returns_retained"; 1661 break; 1662 1663 // FIXME: When Sema learns to form this AttributedType, avoid printing the 1664 // attribute again in printFunctionProtoAfter. 1665 case attr::AnyX86NoCfCheck: OS << "nocf_check"; break; 1666 case attr::CDecl: OS << "cdecl"; break; 1667 case attr::FastCall: OS << "fastcall"; break; 1668 case attr::StdCall: OS << "stdcall"; break; 1669 case attr::ThisCall: OS << "thiscall"; break; 1670 case attr::SwiftCall: OS << "swiftcall"; break; 1671 case attr::VectorCall: OS << "vectorcall"; break; 1672 case attr::Pascal: OS << "pascal"; break; 1673 case attr::MSABI: OS << "ms_abi"; break; 1674 case attr::SysVABI: OS << "sysv_abi"; break; 1675 case attr::RegCall: OS << "regcall"; break; 1676 case attr::Pcs: { 1677 OS << "pcs("; 1678 QualType t = T->getEquivalentType(); 1679 while (!t->isFunctionType()) 1680 t = t->getPointeeType(); 1681 OS << (t->castAs<FunctionType>()->getCallConv() == CC_AAPCS ? 1682 "\"aapcs\"" : "\"aapcs-vfp\""); 1683 OS << ')'; 1684 break; 1685 } 1686 case attr::AArch64VectorPcs: OS << "aarch64_vector_pcs"; break; 1687 case attr::IntelOclBicc: OS << "inteloclbicc"; break; 1688 case attr::PreserveMost: 1689 OS << "preserve_most"; 1690 break; 1691 1692 case attr::PreserveAll: 1693 OS << "preserve_all"; 1694 break; 1695 case attr::NoDeref: 1696 OS << "noderef"; 1697 break; 1698 case attr::AcquireHandle: 1699 OS << "acquire_handle"; 1700 break; 1701 case attr::ArmMveStrictPolymorphism: 1702 OS << "__clang_arm_mve_strict_polymorphism"; 1703 break; 1704 } 1705 OS << "))"; 1706 } 1707 1708 void TypePrinter::printObjCInterfaceBefore(const ObjCInterfaceType *T, 1709 raw_ostream &OS) { 1710 OS << T->getDecl()->getName(); 1711 spaceBeforePlaceHolder(OS); 1712 } 1713 1714 void TypePrinter::printObjCInterfaceAfter(const ObjCInterfaceType *T, 1715 raw_ostream &OS) {} 1716 1717 void TypePrinter::printObjCTypeParamBefore(const ObjCTypeParamType *T, 1718 raw_ostream &OS) { 1719 OS << T->getDecl()->getName(); 1720 if (!T->qual_empty()) { 1721 bool isFirst = true; 1722 OS << '<'; 1723 for (const auto *I : T->quals()) { 1724 if (isFirst) 1725 isFirst = false; 1726 else 1727 OS << ','; 1728 OS << I->getName(); 1729 } 1730 OS << '>'; 1731 } 1732 1733 spaceBeforePlaceHolder(OS); 1734 } 1735 1736 void TypePrinter::printObjCTypeParamAfter(const ObjCTypeParamType *T, 1737 raw_ostream &OS) {} 1738 1739 void TypePrinter::printObjCObjectBefore(const ObjCObjectType *T, 1740 raw_ostream &OS) { 1741 if (T->qual_empty() && T->isUnspecializedAsWritten() && 1742 !T->isKindOfTypeAsWritten()) 1743 return printBefore(T->getBaseType(), OS); 1744 1745 if (T->isKindOfTypeAsWritten()) 1746 OS << "__kindof "; 1747 1748 print(T->getBaseType(), OS, StringRef()); 1749 1750 if (T->isSpecializedAsWritten()) { 1751 bool isFirst = true; 1752 OS << '<'; 1753 for (auto typeArg : T->getTypeArgsAsWritten()) { 1754 if (isFirst) 1755 isFirst = false; 1756 else 1757 OS << ","; 1758 1759 print(typeArg, OS, StringRef()); 1760 } 1761 OS << '>'; 1762 } 1763 1764 if (!T->qual_empty()) { 1765 bool isFirst = true; 1766 OS << '<'; 1767 for (const auto *I : T->quals()) { 1768 if (isFirst) 1769 isFirst = false; 1770 else 1771 OS << ','; 1772 OS << I->getName(); 1773 } 1774 OS << '>'; 1775 } 1776 1777 spaceBeforePlaceHolder(OS); 1778 } 1779 1780 void TypePrinter::printObjCObjectAfter(const ObjCObjectType *T, 1781 raw_ostream &OS) { 1782 if (T->qual_empty() && T->isUnspecializedAsWritten() && 1783 !T->isKindOfTypeAsWritten()) 1784 return printAfter(T->getBaseType(), OS); 1785 } 1786 1787 void TypePrinter::printObjCObjectPointerBefore(const ObjCObjectPointerType *T, 1788 raw_ostream &OS) { 1789 printBefore(T->getPointeeType(), OS); 1790 1791 // If we need to print the pointer, print it now. 1792 if (!T->isObjCIdType() && !T->isObjCQualifiedIdType() && 1793 !T->isObjCClassType() && !T->isObjCQualifiedClassType()) { 1794 if (HasEmptyPlaceHolder) 1795 OS << ' '; 1796 OS << '*'; 1797 } 1798 } 1799 1800 void TypePrinter::printObjCObjectPointerAfter(const ObjCObjectPointerType *T, 1801 raw_ostream &OS) {} 1802 1803 static 1804 const TemplateArgument &getArgument(const TemplateArgument &A) { return A; } 1805 1806 static const TemplateArgument &getArgument(const TemplateArgumentLoc &A) { 1807 return A.getArgument(); 1808 } 1809 1810 static void printArgument(const TemplateArgument &A, const PrintingPolicy &PP, 1811 llvm::raw_ostream &OS) { 1812 A.print(PP, OS); 1813 } 1814 1815 static void printArgument(const TemplateArgumentLoc &A, 1816 const PrintingPolicy &PP, llvm::raw_ostream &OS) { 1817 const TemplateArgument::ArgKind &Kind = A.getArgument().getKind(); 1818 if (Kind == TemplateArgument::ArgKind::Type) 1819 return A.getTypeSourceInfo()->getType().print(OS, PP); 1820 return A.getArgument().print(PP, OS); 1821 } 1822 1823 static bool isSubstitutedTemplateArgument(ASTContext &Ctx, TemplateArgument Arg, 1824 TemplateArgument Pattern, 1825 ArrayRef<TemplateArgument> Args, 1826 unsigned Depth); 1827 1828 static bool isSubstitutedType(ASTContext &Ctx, QualType T, QualType Pattern, 1829 ArrayRef<TemplateArgument> Args, unsigned Depth) { 1830 if (Ctx.hasSameType(T, Pattern)) 1831 return true; 1832 1833 // A type parameter matches its argument. 1834 if (auto *TTPT = Pattern->getAs<TemplateTypeParmType>()) { 1835 if (TTPT->getDepth() == Depth && TTPT->getIndex() < Args.size() && 1836 Args[TTPT->getIndex()].getKind() == TemplateArgument::Type) { 1837 QualType SubstArg = Ctx.getQualifiedType( 1838 Args[TTPT->getIndex()].getAsType(), Pattern.getQualifiers()); 1839 return Ctx.hasSameType(SubstArg, T); 1840 } 1841 return false; 1842 } 1843 1844 // FIXME: Recurse into array types. 1845 1846 // All other cases will need the types to be identically qualified. 1847 Qualifiers TQual, PatQual; 1848 T = Ctx.getUnqualifiedArrayType(T, TQual); 1849 Pattern = Ctx.getUnqualifiedArrayType(Pattern, PatQual); 1850 if (TQual != PatQual) 1851 return false; 1852 1853 // Recurse into pointer-like types. 1854 { 1855 QualType TPointee = T->getPointeeType(); 1856 QualType PPointee = Pattern->getPointeeType(); 1857 if (!TPointee.isNull() && !PPointee.isNull()) 1858 return T->getTypeClass() == Pattern->getTypeClass() && 1859 isSubstitutedType(Ctx, TPointee, PPointee, Args, Depth); 1860 } 1861 1862 // Recurse into template specialization types. 1863 if (auto *PTST = 1864 Pattern.getCanonicalType()->getAs<TemplateSpecializationType>()) { 1865 TemplateName Template; 1866 ArrayRef<TemplateArgument> TemplateArgs; 1867 if (auto *TTST = T->getAs<TemplateSpecializationType>()) { 1868 Template = TTST->getTemplateName(); 1869 TemplateArgs = TTST->template_arguments(); 1870 } else if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 1871 T->getAsCXXRecordDecl())) { 1872 Template = TemplateName(CTSD->getSpecializedTemplate()); 1873 TemplateArgs = CTSD->getTemplateArgs().asArray(); 1874 } else { 1875 return false; 1876 } 1877 1878 if (!isSubstitutedTemplateArgument(Ctx, Template, PTST->getTemplateName(), 1879 Args, Depth)) 1880 return false; 1881 if (TemplateArgs.size() != PTST->getNumArgs()) 1882 return false; 1883 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 1884 if (!isSubstitutedTemplateArgument(Ctx, TemplateArgs[I], PTST->getArg(I), 1885 Args, Depth)) 1886 return false; 1887 return true; 1888 } 1889 1890 // FIXME: Handle more cases. 1891 return false; 1892 } 1893 1894 static bool isSubstitutedTemplateArgument(ASTContext &Ctx, TemplateArgument Arg, 1895 TemplateArgument Pattern, 1896 ArrayRef<TemplateArgument> Args, 1897 unsigned Depth) { 1898 Arg = Ctx.getCanonicalTemplateArgument(Arg); 1899 Pattern = Ctx.getCanonicalTemplateArgument(Pattern); 1900 if (Arg.structurallyEquals(Pattern)) 1901 return true; 1902 1903 if (Pattern.getKind() == TemplateArgument::Expression) { 1904 if (auto *DRE = 1905 dyn_cast<DeclRefExpr>(Pattern.getAsExpr()->IgnoreParenImpCasts())) { 1906 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) 1907 return NTTP->getDepth() == Depth && Args.size() > NTTP->getIndex() && 1908 Args[NTTP->getIndex()].structurallyEquals(Arg); 1909 } 1910 } 1911 1912 if (Arg.getKind() != Pattern.getKind()) 1913 return false; 1914 1915 if (Arg.getKind() == TemplateArgument::Type) 1916 return isSubstitutedType(Ctx, Arg.getAsType(), Pattern.getAsType(), Args, 1917 Depth); 1918 1919 if (Arg.getKind() == TemplateArgument::Template) { 1920 TemplateDecl *PatTD = Pattern.getAsTemplate().getAsTemplateDecl(); 1921 if (auto *TTPD = dyn_cast_or_null<TemplateTemplateParmDecl>(PatTD)) 1922 return TTPD->getDepth() == Depth && Args.size() > TTPD->getIndex() && 1923 Ctx.getCanonicalTemplateArgument(Args[TTPD->getIndex()]) 1924 .structurallyEquals(Arg); 1925 } 1926 1927 // FIXME: Handle more cases. 1928 return false; 1929 } 1930 1931 /// Make a best-effort determination of whether the type T can be produced by 1932 /// substituting Args into the default argument of Param. 1933 static bool isSubstitutedDefaultArgument(ASTContext &Ctx, TemplateArgument Arg, 1934 const NamedDecl *Param, 1935 ArrayRef<TemplateArgument> Args, 1936 unsigned Depth) { 1937 // An empty pack is equivalent to not providing a pack argument. 1938 if (Arg.getKind() == TemplateArgument::Pack && Arg.pack_size() == 0) 1939 return true; 1940 1941 if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Param)) { 1942 return TTPD->hasDefaultArgument() && 1943 isSubstitutedTemplateArgument(Ctx, Arg, TTPD->getDefaultArgument(), 1944 Args, Depth); 1945 } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Param)) { 1946 return TTPD->hasDefaultArgument() && 1947 isSubstitutedTemplateArgument( 1948 Ctx, Arg, TTPD->getDefaultArgument().getArgument(), Args, Depth); 1949 } else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 1950 return NTTPD->hasDefaultArgument() && 1951 isSubstitutedTemplateArgument(Ctx, Arg, NTTPD->getDefaultArgument(), 1952 Args, Depth); 1953 } 1954 return false; 1955 } 1956 1957 template<typename TA> 1958 static void printTo(raw_ostream &OS, ArrayRef<TA> Args, 1959 const PrintingPolicy &Policy, bool SkipBrackets, 1960 const TemplateParameterList *TPL) { 1961 // Drop trailing template arguments that match default arguments. 1962 if (TPL && Policy.SuppressDefaultTemplateArgs && 1963 !Policy.PrintCanonicalTypes && !Args.empty() && 1964 Args.size() <= TPL->size()) { 1965 ASTContext &Ctx = TPL->getParam(0)->getASTContext(); 1966 llvm::SmallVector<TemplateArgument, 8> OrigArgs; 1967 for (const TA &A : Args) 1968 OrigArgs.push_back(getArgument(A)); 1969 while (!Args.empty() && 1970 isSubstitutedDefaultArgument(Ctx, getArgument(Args.back()), 1971 TPL->getParam(Args.size() - 1), 1972 OrigArgs, TPL->getDepth())) 1973 Args = Args.drop_back(); 1974 } 1975 1976 const char *Comma = Policy.MSVCFormatting ? "," : ", "; 1977 if (!SkipBrackets) 1978 OS << '<'; 1979 1980 bool NeedSpace = false; 1981 bool FirstArg = true; 1982 for (const auto &Arg : Args) { 1983 // Print the argument into a string. 1984 SmallString<128> Buf; 1985 llvm::raw_svector_ostream ArgOS(Buf); 1986 const TemplateArgument &Argument = getArgument(Arg); 1987 if (Argument.getKind() == TemplateArgument::Pack) { 1988 if (Argument.pack_size() && !FirstArg) 1989 OS << Comma; 1990 printTo(ArgOS, Argument.getPackAsArray(), Policy, true, nullptr); 1991 } else { 1992 if (!FirstArg) 1993 OS << Comma; 1994 // Tries to print the argument with location info if exists. 1995 printArgument(Arg, Policy, ArgOS); 1996 } 1997 StringRef ArgString = ArgOS.str(); 1998 1999 // If this is the first argument and its string representation 2000 // begins with the global scope specifier ('::foo'), add a space 2001 // to avoid printing the diagraph '<:'. 2002 if (FirstArg && !ArgString.empty() && ArgString[0] == ':') 2003 OS << ' '; 2004 2005 OS << ArgString; 2006 2007 // If the last character of our string is '>', add another space to 2008 // keep the two '>''s separate tokens. 2009 NeedSpace = Policy.SplitTemplateClosers && !ArgString.empty() && 2010 ArgString.back() == '>'; 2011 FirstArg = false; 2012 } 2013 2014 if (NeedSpace) 2015 OS << ' '; 2016 2017 if (!SkipBrackets) 2018 OS << '>'; 2019 } 2020 2021 void clang::printTemplateArgumentList(raw_ostream &OS, 2022 const TemplateArgumentListInfo &Args, 2023 const PrintingPolicy &Policy, 2024 const TemplateParameterList *TPL) { 2025 printTemplateArgumentList(OS, Args.arguments(), Policy, TPL); 2026 } 2027 2028 void clang::printTemplateArgumentList(raw_ostream &OS, 2029 ArrayRef<TemplateArgument> Args, 2030 const PrintingPolicy &Policy, 2031 const TemplateParameterList *TPL) { 2032 printTo(OS, Args, Policy, false, TPL); 2033 } 2034 2035 void clang::printTemplateArgumentList(raw_ostream &OS, 2036 ArrayRef<TemplateArgumentLoc> Args, 2037 const PrintingPolicy &Policy, 2038 const TemplateParameterList *TPL) { 2039 printTo(OS, Args, Policy, false, TPL); 2040 } 2041 2042 std::string Qualifiers::getAsString() const { 2043 LangOptions LO; 2044 return getAsString(PrintingPolicy(LO)); 2045 } 2046 2047 // Appends qualifiers to the given string, separated by spaces. Will 2048 // prefix a space if the string is non-empty. Will not append a final 2049 // space. 2050 std::string Qualifiers::getAsString(const PrintingPolicy &Policy) const { 2051 SmallString<64> Buf; 2052 llvm::raw_svector_ostream StrOS(Buf); 2053 print(StrOS, Policy); 2054 return std::string(StrOS.str()); 2055 } 2056 2057 bool Qualifiers::isEmptyWhenPrinted(const PrintingPolicy &Policy) const { 2058 if (getCVRQualifiers()) 2059 return false; 2060 2061 if (getAddressSpace() != LangAS::Default) 2062 return false; 2063 2064 if (getObjCGCAttr()) 2065 return false; 2066 2067 if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime()) 2068 if (!(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime)) 2069 return false; 2070 2071 return true; 2072 } 2073 2074 std::string Qualifiers::getAddrSpaceAsString(LangAS AS) { 2075 switch (AS) { 2076 case LangAS::Default: 2077 return ""; 2078 case LangAS::opencl_global: 2079 return "__global"; 2080 case LangAS::opencl_local: 2081 return "__local"; 2082 case LangAS::opencl_private: 2083 return "__private"; 2084 case LangAS::opencl_constant: 2085 return "__constant"; 2086 case LangAS::opencl_generic: 2087 return "__generic"; 2088 case LangAS::opencl_global_device: 2089 return "__global_device"; 2090 case LangAS::opencl_global_host: 2091 return "__global_host"; 2092 case LangAS::cuda_device: 2093 return "__device__"; 2094 case LangAS::cuda_constant: 2095 return "__constant__"; 2096 case LangAS::cuda_shared: 2097 return "__shared__"; 2098 case LangAS::ptr32_sptr: 2099 return "__sptr __ptr32"; 2100 case LangAS::ptr32_uptr: 2101 return "__uptr __ptr32"; 2102 case LangAS::ptr64: 2103 return "__ptr64"; 2104 default: 2105 return std::to_string(toTargetAddressSpace(AS)); 2106 } 2107 } 2108 2109 // Appends qualifiers to the given string, separated by spaces. Will 2110 // prefix a space if the string is non-empty. Will not append a final 2111 // space. 2112 void Qualifiers::print(raw_ostream &OS, const PrintingPolicy& Policy, 2113 bool appendSpaceIfNonEmpty) const { 2114 bool addSpace = false; 2115 2116 unsigned quals = getCVRQualifiers(); 2117 if (quals) { 2118 AppendTypeQualList(OS, quals, Policy.Restrict); 2119 addSpace = true; 2120 } 2121 if (hasUnaligned()) { 2122 if (addSpace) 2123 OS << ' '; 2124 OS << "__unaligned"; 2125 addSpace = true; 2126 } 2127 auto ASStr = getAddrSpaceAsString(getAddressSpace()); 2128 if (!ASStr.empty()) { 2129 if (addSpace) 2130 OS << ' '; 2131 addSpace = true; 2132 // Wrap target address space into an attribute syntax 2133 if (isTargetAddressSpace(getAddressSpace())) 2134 OS << "__attribute__((address_space(" << ASStr << ")))"; 2135 else 2136 OS << ASStr; 2137 } 2138 2139 if (Qualifiers::GC gc = getObjCGCAttr()) { 2140 if (addSpace) 2141 OS << ' '; 2142 addSpace = true; 2143 if (gc == Qualifiers::Weak) 2144 OS << "__weak"; 2145 else 2146 OS << "__strong"; 2147 } 2148 if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime()) { 2149 if (!(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime)){ 2150 if (addSpace) 2151 OS << ' '; 2152 addSpace = true; 2153 } 2154 2155 switch (lifetime) { 2156 case Qualifiers::OCL_None: llvm_unreachable("none but true"); 2157 case Qualifiers::OCL_ExplicitNone: OS << "__unsafe_unretained"; break; 2158 case Qualifiers::OCL_Strong: 2159 if (!Policy.SuppressStrongLifetime) 2160 OS << "__strong"; 2161 break; 2162 2163 case Qualifiers::OCL_Weak: OS << "__weak"; break; 2164 case Qualifiers::OCL_Autoreleasing: OS << "__autoreleasing"; break; 2165 } 2166 } 2167 2168 if (appendSpaceIfNonEmpty && addSpace) 2169 OS << ' '; 2170 } 2171 2172 std::string QualType::getAsString() const { 2173 return getAsString(split(), LangOptions()); 2174 } 2175 2176 std::string QualType::getAsString(const PrintingPolicy &Policy) const { 2177 std::string S; 2178 getAsStringInternal(S, Policy); 2179 return S; 2180 } 2181 2182 std::string QualType::getAsString(const Type *ty, Qualifiers qs, 2183 const PrintingPolicy &Policy) { 2184 std::string buffer; 2185 getAsStringInternal(ty, qs, buffer, Policy); 2186 return buffer; 2187 } 2188 2189 void QualType::print(raw_ostream &OS, const PrintingPolicy &Policy, 2190 const Twine &PlaceHolder, unsigned Indentation) const { 2191 print(splitAccordingToPolicy(*this, Policy), OS, Policy, PlaceHolder, 2192 Indentation); 2193 } 2194 2195 void QualType::print(const Type *ty, Qualifiers qs, 2196 raw_ostream &OS, const PrintingPolicy &policy, 2197 const Twine &PlaceHolder, unsigned Indentation) { 2198 SmallString<128> PHBuf; 2199 StringRef PH = PlaceHolder.toStringRef(PHBuf); 2200 2201 TypePrinter(policy, Indentation).print(ty, qs, OS, PH); 2202 } 2203 2204 void QualType::getAsStringInternal(std::string &Str, 2205 const PrintingPolicy &Policy) const { 2206 return getAsStringInternal(splitAccordingToPolicy(*this, Policy), Str, 2207 Policy); 2208 } 2209 2210 void QualType::getAsStringInternal(const Type *ty, Qualifiers qs, 2211 std::string &buffer, 2212 const PrintingPolicy &policy) { 2213 SmallString<256> Buf; 2214 llvm::raw_svector_ostream StrOS(Buf); 2215 TypePrinter(policy).print(ty, qs, StrOS, buffer); 2216 std::string str = std::string(StrOS.str()); 2217 buffer.swap(str); 2218 } 2219