TypePrinter.cpp 61 KB

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