ItaniumMangle.cpp 167 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954
  1. //===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // Implements C++ name mangling according to the Itanium C++ ABI,
  11. // which is used in GCC 3.2 and newer (and many compilers that are
  12. // ABI-compatible with GCC):
  13. //
  14. // http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "clang/AST/Mangle.h"
  18. #include "clang/AST/ASTContext.h"
  19. #include "clang/AST/Attr.h"
  20. #include "clang/AST/Decl.h"
  21. #include "clang/AST/DeclCXX.h"
  22. #include "clang/AST/DeclObjC.h"
  23. #include "clang/AST/DeclOpenMP.h"
  24. #include "clang/AST/DeclTemplate.h"
  25. #include "clang/AST/Expr.h"
  26. #include "clang/AST/ExprCXX.h"
  27. #include "clang/AST/ExprObjC.h"
  28. #include "clang/AST/TypeLoc.h"
  29. #include "clang/Basic/ABI.h"
  30. #include "clang/Basic/SourceManager.h"
  31. #include "clang/Basic/TargetInfo.h"
  32. #include "llvm/ADT/StringExtras.h"
  33. #include "llvm/Support/ErrorHandling.h"
  34. #include "llvm/Support/raw_ostream.h"
  35. #define MANGLE_CHECKER 0
  36. #if MANGLE_CHECKER
  37. #include <cxxabi.h>
  38. #endif
  39. using namespace clang;
  40. namespace {
  41. /// Retrieve the declaration context that should be used when mangling the given
  42. /// declaration.
  43. static const DeclContext *getEffectiveDeclContext(const Decl *D) {
  44. // The ABI assumes that lambda closure types that occur within
  45. // default arguments live in the context of the function. However, due to
  46. // the way in which Clang parses and creates function declarations, this is
  47. // not the case: the lambda closure type ends up living in the context
  48. // where the function itself resides, because the function declaration itself
  49. // had not yet been created. Fix the context here.
  50. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
  51. if (RD->isLambda())
  52. if (ParmVarDecl *ContextParam
  53. = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
  54. return ContextParam->getDeclContext();
  55. }
  56. // Perform the same check for block literals.
  57. if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
  58. if (ParmVarDecl *ContextParam
  59. = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
  60. return ContextParam->getDeclContext();
  61. }
  62. const DeclContext *DC = D->getDeclContext();
  63. if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC)) {
  64. return getEffectiveDeclContext(cast<Decl>(DC));
  65. }
  66. if (const auto *VD = dyn_cast<VarDecl>(D))
  67. if (VD->isExternC())
  68. return VD->getASTContext().getTranslationUnitDecl();
  69. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  70. if (FD->isExternC())
  71. return FD->getASTContext().getTranslationUnitDecl();
  72. return DC->getRedeclContext();
  73. }
  74. static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
  75. return getEffectiveDeclContext(cast<Decl>(DC));
  76. }
  77. static bool isLocalContainerContext(const DeclContext *DC) {
  78. return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
  79. }
  80. static const RecordDecl *GetLocalClassDecl(const Decl *D) {
  81. const DeclContext *DC = getEffectiveDeclContext(D);
  82. while (!DC->isNamespace() && !DC->isTranslationUnit()) {
  83. if (isLocalContainerContext(DC))
  84. return dyn_cast<RecordDecl>(D);
  85. D = cast<Decl>(DC);
  86. DC = getEffectiveDeclContext(D);
  87. }
  88. return nullptr;
  89. }
  90. static const FunctionDecl *getStructor(const FunctionDecl *fn) {
  91. if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
  92. return ftd->getTemplatedDecl();
  93. return fn;
  94. }
  95. static const NamedDecl *getStructor(const NamedDecl *decl) {
  96. const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
  97. return (fn ? getStructor(fn) : decl);
  98. }
  99. static bool isLambda(const NamedDecl *ND) {
  100. const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
  101. if (!Record)
  102. return false;
  103. return Record->isLambda();
  104. }
  105. static const unsigned UnknownArity = ~0U;
  106. class ItaniumMangleContextImpl : public ItaniumMangleContext {
  107. typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
  108. llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
  109. llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
  110. public:
  111. explicit ItaniumMangleContextImpl(ASTContext &Context,
  112. DiagnosticsEngine &Diags)
  113. : ItaniumMangleContext(Context, Diags) {}
  114. /// @name Mangler Entry Points
  115. /// @{
  116. bool shouldMangleCXXName(const NamedDecl *D) override;
  117. bool shouldMangleStringLiteral(const StringLiteral *) override {
  118. return false;
  119. }
  120. void mangleCXXName(const NamedDecl *D, raw_ostream &) override;
  121. void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
  122. raw_ostream &) override;
  123. void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
  124. const ThisAdjustment &ThisAdjustment,
  125. raw_ostream &) override;
  126. void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
  127. raw_ostream &) override;
  128. void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
  129. void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
  130. void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
  131. const CXXRecordDecl *Type, raw_ostream &) override;
  132. void mangleCXXRTTI(QualType T, raw_ostream &) override;
  133. void mangleCXXRTTIName(QualType T, raw_ostream &) override;
  134. void mangleTypeName(QualType T, raw_ostream &) override;
  135. void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
  136. raw_ostream &) override;
  137. void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
  138. raw_ostream &) override;
  139. void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
  140. void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
  141. void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
  142. void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
  143. void mangleDynamicAtExitDestructor(const VarDecl *D,
  144. raw_ostream &Out) override;
  145. void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
  146. raw_ostream &Out) override;
  147. void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
  148. raw_ostream &Out) override;
  149. void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
  150. void mangleItaniumThreadLocalWrapper(const VarDecl *D,
  151. raw_ostream &) override;
  152. void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
  153. bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
  154. // Lambda closure types are already numbered.
  155. if (isLambda(ND))
  156. return false;
  157. // Anonymous tags are already numbered.
  158. if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
  159. if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
  160. return false;
  161. }
  162. // Use the canonical number for externally visible decls.
  163. if (ND->isExternallyVisible()) {
  164. unsigned discriminator = getASTContext().getManglingNumber(ND);
  165. if (discriminator == 1)
  166. return false;
  167. disc = discriminator - 2;
  168. return true;
  169. }
  170. // Make up a reasonable number for internal decls.
  171. unsigned &discriminator = Uniquifier[ND];
  172. if (!discriminator) {
  173. const DeclContext *DC = getEffectiveDeclContext(ND);
  174. discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
  175. }
  176. if (discriminator == 1)
  177. return false;
  178. disc = discriminator-2;
  179. return true;
  180. }
  181. /// @}
  182. };
  183. /// Manage the mangling of a single name.
  184. class CXXNameMangler {
  185. ItaniumMangleContextImpl &Context;
  186. raw_ostream &Out;
  187. bool NullOut = false;
  188. /// In the "DisableDerivedAbiTags" mode derived ABI tags are not calculated.
  189. /// This mode is used when mangler creates another mangler recursively to
  190. /// calculate ABI tags for the function return value or the variable type.
  191. /// Also it is required to avoid infinite recursion in some cases.
  192. bool DisableDerivedAbiTags = false;
  193. /// The "structor" is the top-level declaration being mangled, if
  194. /// that's not a template specialization; otherwise it's the pattern
  195. /// for that specialization.
  196. const NamedDecl *Structor;
  197. unsigned StructorType;
  198. /// The next substitution sequence number.
  199. unsigned SeqID;
  200. class FunctionTypeDepthState {
  201. unsigned Bits;
  202. enum { InResultTypeMask = 1 };
  203. public:
  204. FunctionTypeDepthState() : Bits(0) {}
  205. /// The number of function types we're inside.
  206. unsigned getDepth() const {
  207. return Bits >> 1;
  208. }
  209. /// True if we're in the return type of the innermost function type.
  210. bool isInResultType() const {
  211. return Bits & InResultTypeMask;
  212. }
  213. FunctionTypeDepthState push() {
  214. FunctionTypeDepthState tmp = *this;
  215. Bits = (Bits & ~InResultTypeMask) + 2;
  216. return tmp;
  217. }
  218. void enterResultType() {
  219. Bits |= InResultTypeMask;
  220. }
  221. void leaveResultType() {
  222. Bits &= ~InResultTypeMask;
  223. }
  224. void pop(FunctionTypeDepthState saved) {
  225. assert(getDepth() == saved.getDepth() + 1);
  226. Bits = saved.Bits;
  227. }
  228. } FunctionTypeDepth;
  229. // abi_tag is a gcc attribute, taking one or more strings called "tags".
  230. // The goal is to annotate against which version of a library an object was
  231. // built and to be able to provide backwards compatibility ("dual abi").
  232. // For more information see docs/ItaniumMangleAbiTags.rst.
  233. typedef SmallVector<StringRef, 4> AbiTagList;
  234. // State to gather all implicit and explicit tags used in a mangled name.
  235. // Must always have an instance of this while emitting any name to keep
  236. // track.
  237. class AbiTagState final {
  238. public:
  239. explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) {
  240. Parent = LinkHead;
  241. LinkHead = this;
  242. }
  243. // No copy, no move.
  244. AbiTagState(const AbiTagState &) = delete;
  245. AbiTagState &operator=(const AbiTagState &) = delete;
  246. ~AbiTagState() { pop(); }
  247. void write(raw_ostream &Out, const NamedDecl *ND,
  248. const AbiTagList *AdditionalAbiTags) {
  249. ND = cast<NamedDecl>(ND->getCanonicalDecl());
  250. if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND)) {
  251. assert(
  252. !AdditionalAbiTags &&
  253. "only function and variables need a list of additional abi tags");
  254. if (const auto *NS = dyn_cast<NamespaceDecl>(ND)) {
  255. if (const auto *AbiTag = NS->getAttr<AbiTagAttr>()) {
  256. UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
  257. AbiTag->tags().end());
  258. }
  259. // Don't emit abi tags for namespaces.
  260. return;
  261. }
  262. }
  263. AbiTagList TagList;
  264. if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) {
  265. UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
  266. AbiTag->tags().end());
  267. TagList.insert(TagList.end(), AbiTag->tags().begin(),
  268. AbiTag->tags().end());
  269. }
  270. if (AdditionalAbiTags) {
  271. UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(),
  272. AdditionalAbiTags->end());
  273. TagList.insert(TagList.end(), AdditionalAbiTags->begin(),
  274. AdditionalAbiTags->end());
  275. }
  276. llvm::sort(TagList.begin(), TagList.end());
  277. TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end());
  278. writeSortedUniqueAbiTags(Out, TagList);
  279. }
  280. const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }
  281. void setUsedAbiTags(const AbiTagList &AbiTags) {
  282. UsedAbiTags = AbiTags;
  283. }
  284. const AbiTagList &getEmittedAbiTags() const {
  285. return EmittedAbiTags;
  286. }
  287. const AbiTagList &getSortedUniqueUsedAbiTags() {
  288. llvm::sort(UsedAbiTags.begin(), UsedAbiTags.end());
  289. UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),
  290. UsedAbiTags.end());
  291. return UsedAbiTags;
  292. }
  293. private:
  294. //! All abi tags used implicitly or explicitly.
  295. AbiTagList UsedAbiTags;
  296. //! All explicit abi tags (i.e. not from namespace).
  297. AbiTagList EmittedAbiTags;
  298. AbiTagState *&LinkHead;
  299. AbiTagState *Parent = nullptr;
  300. void pop() {
  301. assert(LinkHead == this &&
  302. "abi tag link head must point to us on destruction");
  303. if (Parent) {
  304. Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(),
  305. UsedAbiTags.begin(), UsedAbiTags.end());
  306. Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(),
  307. EmittedAbiTags.begin(),
  308. EmittedAbiTags.end());
  309. }
  310. LinkHead = Parent;
  311. }
  312. void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {
  313. for (const auto &Tag : AbiTags) {
  314. EmittedAbiTags.push_back(Tag);
  315. Out << "B";
  316. Out << Tag.size();
  317. Out << Tag;
  318. }
  319. }
  320. };
  321. AbiTagState *AbiTags = nullptr;
  322. AbiTagState AbiTagsRoot;
  323. llvm::DenseMap<uintptr_t, unsigned> Substitutions;
  324. llvm::DenseMap<StringRef, unsigned> ModuleSubstitutions;
  325. ASTContext &getASTContext() const { return Context.getASTContext(); }
  326. public:
  327. CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
  328. const NamedDecl *D = nullptr, bool NullOut_ = false)
  329. : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)),
  330. StructorType(0), SeqID(0), AbiTagsRoot(AbiTags) {
  331. // These can't be mangled without a ctor type or dtor type.
  332. assert(!D || (!isa<CXXDestructorDecl>(D) &&
  333. !isa<CXXConstructorDecl>(D)));
  334. }
  335. CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
  336. const CXXConstructorDecl *D, CXXCtorType Type)
  337. : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
  338. SeqID(0), AbiTagsRoot(AbiTags) { }
  339. CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
  340. const CXXDestructorDecl *D, CXXDtorType Type)
  341. : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
  342. SeqID(0), AbiTagsRoot(AbiTags) { }
  343. CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
  344. : Context(Outer.Context), Out(Out_), NullOut(false),
  345. Structor(Outer.Structor), StructorType(Outer.StructorType),
  346. SeqID(Outer.SeqID), FunctionTypeDepth(Outer.FunctionTypeDepth),
  347. AbiTagsRoot(AbiTags), Substitutions(Outer.Substitutions) {}
  348. CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
  349. : Context(Outer.Context), Out(Out_), NullOut(true),
  350. Structor(Outer.Structor), StructorType(Outer.StructorType),
  351. SeqID(Outer.SeqID), FunctionTypeDepth(Outer.FunctionTypeDepth),
  352. AbiTagsRoot(AbiTags), Substitutions(Outer.Substitutions) {}
  353. #if MANGLE_CHECKER
  354. ~CXXNameMangler() {
  355. if (Out.str()[0] == '\01')
  356. return;
  357. int status = 0;
  358. char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
  359. assert(status == 0 && "Could not demangle mangled name!");
  360. free(result);
  361. }
  362. #endif
  363. raw_ostream &getStream() { return Out; }
  364. void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
  365. static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
  366. void mangle(const NamedDecl *D);
  367. void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
  368. void mangleNumber(const llvm::APSInt &I);
  369. void mangleNumber(int64_t Number);
  370. void mangleFloat(const llvm::APFloat &F);
  371. void mangleFunctionEncoding(const FunctionDecl *FD);
  372. void mangleSeqID(unsigned SeqID);
  373. void mangleName(const NamedDecl *ND);
  374. void mangleType(QualType T);
  375. void mangleNameOrStandardSubstitution(const NamedDecl *ND);
  376. private:
  377. bool mangleSubstitution(const NamedDecl *ND);
  378. bool mangleSubstitution(QualType T);
  379. bool mangleSubstitution(TemplateName Template);
  380. bool mangleSubstitution(uintptr_t Ptr);
  381. void mangleExistingSubstitution(TemplateName name);
  382. bool mangleStandardSubstitution(const NamedDecl *ND);
  383. void addSubstitution(const NamedDecl *ND) {
  384. ND = cast<NamedDecl>(ND->getCanonicalDecl());
  385. addSubstitution(reinterpret_cast<uintptr_t>(ND));
  386. }
  387. void addSubstitution(QualType T);
  388. void addSubstitution(TemplateName Template);
  389. void addSubstitution(uintptr_t Ptr);
  390. // Destructive copy substitutions from other mangler.
  391. void extendSubstitutions(CXXNameMangler* Other);
  392. void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
  393. bool recursive = false);
  394. void mangleUnresolvedName(NestedNameSpecifier *qualifier,
  395. DeclarationName name,
  396. const TemplateArgumentLoc *TemplateArgs,
  397. unsigned NumTemplateArgs,
  398. unsigned KnownArity = UnknownArity);
  399. void mangleFunctionEncodingBareType(const FunctionDecl *FD);
  400. void mangleNameWithAbiTags(const NamedDecl *ND,
  401. const AbiTagList *AdditionalAbiTags);
  402. void mangleModuleName(const Module *M);
  403. void mangleModuleNamePrefix(StringRef Name);
  404. void mangleTemplateName(const TemplateDecl *TD,
  405. const TemplateArgument *TemplateArgs,
  406. unsigned NumTemplateArgs);
  407. void mangleUnqualifiedName(const NamedDecl *ND,
  408. const AbiTagList *AdditionalAbiTags) {
  409. mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity,
  410. AdditionalAbiTags);
  411. }
  412. void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
  413. unsigned KnownArity,
  414. const AbiTagList *AdditionalAbiTags);
  415. void mangleUnscopedName(const NamedDecl *ND,
  416. const AbiTagList *AdditionalAbiTags);
  417. void mangleUnscopedTemplateName(const TemplateDecl *ND,
  418. const AbiTagList *AdditionalAbiTags);
  419. void mangleUnscopedTemplateName(TemplateName,
  420. const AbiTagList *AdditionalAbiTags);
  421. void mangleSourceName(const IdentifierInfo *II);
  422. void mangleRegCallName(const IdentifierInfo *II);
  423. void mangleSourceNameWithAbiTags(
  424. const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);
  425. void mangleLocalName(const Decl *D,
  426. const AbiTagList *AdditionalAbiTags);
  427. void mangleBlockForPrefix(const BlockDecl *Block);
  428. void mangleUnqualifiedBlock(const BlockDecl *Block);
  429. void mangleLambda(const CXXRecordDecl *Lambda);
  430. void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
  431. const AbiTagList *AdditionalAbiTags,
  432. bool NoFunction=false);
  433. void mangleNestedName(const TemplateDecl *TD,
  434. const TemplateArgument *TemplateArgs,
  435. unsigned NumTemplateArgs);
  436. void manglePrefix(NestedNameSpecifier *qualifier);
  437. void manglePrefix(const DeclContext *DC, bool NoFunction=false);
  438. void manglePrefix(QualType type);
  439. void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
  440. void mangleTemplatePrefix(TemplateName Template);
  441. bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
  442. StringRef Prefix = "");
  443. void mangleOperatorName(DeclarationName Name, unsigned Arity);
  444. void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
  445. void mangleVendorQualifier(StringRef qualifier);
  446. void mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST = nullptr);
  447. void mangleRefQualifier(RefQualifierKind RefQualifier);
  448. void mangleObjCMethodName(const ObjCMethodDecl *MD);
  449. // Declare manglers for every type class.
  450. #define ABSTRACT_TYPE(CLASS, PARENT)
  451. #define NON_CANONICAL_TYPE(CLASS, PARENT)
  452. #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
  453. #include "clang/AST/TypeNodes.def"
  454. void mangleType(const TagType*);
  455. void mangleType(TemplateName);
  456. static StringRef getCallingConvQualifierName(CallingConv CC);
  457. void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
  458. void mangleExtFunctionInfo(const FunctionType *T);
  459. void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
  460. const FunctionDecl *FD = nullptr);
  461. void mangleNeonVectorType(const VectorType *T);
  462. void mangleAArch64NeonVectorType(const VectorType *T);
  463. void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
  464. void mangleMemberExprBase(const Expr *base, bool isArrow);
  465. void mangleMemberExpr(const Expr *base, bool isArrow,
  466. NestedNameSpecifier *qualifier,
  467. NamedDecl *firstQualifierLookup,
  468. DeclarationName name,
  469. const TemplateArgumentLoc *TemplateArgs,
  470. unsigned NumTemplateArgs,
  471. unsigned knownArity);
  472. void mangleCastExpression(const Expr *E, StringRef CastEncoding);
  473. void mangleInitListElements(const InitListExpr *InitList);
  474. void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
  475. void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
  476. void mangleCXXDtorType(CXXDtorType T);
  477. void mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
  478. unsigned NumTemplateArgs);
  479. void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
  480. unsigned NumTemplateArgs);
  481. void mangleTemplateArgs(const TemplateArgumentList &AL);
  482. void mangleTemplateArg(TemplateArgument A);
  483. void mangleTemplateParameter(unsigned Index);
  484. void mangleFunctionParam(const ParmVarDecl *parm);
  485. void writeAbiTags(const NamedDecl *ND,
  486. const AbiTagList *AdditionalAbiTags);
  487. // Returns sorted unique list of ABI tags.
  488. AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
  489. // Returns sorted unique list of ABI tags.
  490. AbiTagList makeVariableTypeTags(const VarDecl *VD);
  491. };
  492. }
  493. bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
  494. const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
  495. if (FD) {
  496. LanguageLinkage L = FD->getLanguageLinkage();
  497. // Overloadable functions need mangling.
  498. if (FD->hasAttr<OverloadableAttr>())
  499. return true;
  500. // "main" is not mangled.
  501. if (FD->isMain())
  502. return false;
  503. // C++ functions and those whose names are not a simple identifier need
  504. // mangling.
  505. if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
  506. return true;
  507. // C functions are not mangled.
  508. if (L == CLanguageLinkage)
  509. return false;
  510. }
  511. // Otherwise, no mangling is done outside C++ mode.
  512. if (!getASTContext().getLangOpts().CPlusPlus)
  513. return false;
  514. const VarDecl *VD = dyn_cast<VarDecl>(D);
  515. if (VD && !isa<DecompositionDecl>(D)) {
  516. // C variables are not mangled.
  517. if (VD->isExternC())
  518. return false;
  519. // Variables at global scope with non-internal linkage are not mangled
  520. const DeclContext *DC = getEffectiveDeclContext(D);
  521. // Check for extern variable declared locally.
  522. if (DC->isFunctionOrMethod() && D->hasLinkage())
  523. while (!DC->isNamespace() && !DC->isTranslationUnit())
  524. DC = getEffectiveParentContext(DC);
  525. if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
  526. !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
  527. !isa<VarTemplateSpecializationDecl>(D))
  528. return false;
  529. }
  530. return true;
  531. }
  532. void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
  533. const AbiTagList *AdditionalAbiTags) {
  534. assert(AbiTags && "require AbiTagState");
  535. AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
  536. }
  537. void CXXNameMangler::mangleSourceNameWithAbiTags(
  538. const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
  539. mangleSourceName(ND->getIdentifier());
  540. writeAbiTags(ND, AdditionalAbiTags);
  541. }
  542. void CXXNameMangler::mangle(const NamedDecl *D) {
  543. // <mangled-name> ::= _Z <encoding>
  544. // ::= <data name>
  545. // ::= <special-name>
  546. Out << "_Z";
  547. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  548. mangleFunctionEncoding(FD);
  549. else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  550. mangleName(VD);
  551. else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
  552. mangleName(IFD->getAnonField());
  553. else
  554. mangleName(cast<FieldDecl>(D));
  555. }
  556. void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
  557. // <encoding> ::= <function name> <bare-function-type>
  558. // Don't mangle in the type if this isn't a decl we should typically mangle.
  559. if (!Context.shouldMangleDeclName(FD)) {
  560. mangleName(FD);
  561. return;
  562. }
  563. AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
  564. if (ReturnTypeAbiTags.empty()) {
  565. // There are no tags for return type, the simplest case.
  566. mangleName(FD);
  567. mangleFunctionEncodingBareType(FD);
  568. return;
  569. }
  570. // Mangle function name and encoding to temporary buffer.
  571. // We have to output name and encoding to the same mangler to get the same
  572. // substitution as it will be in final mangling.
  573. SmallString<256> FunctionEncodingBuf;
  574. llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
  575. CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
  576. // Output name of the function.
  577. FunctionEncodingMangler.disableDerivedAbiTags();
  578. FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
  579. // Remember length of the function name in the buffer.
  580. size_t EncodingPositionStart = FunctionEncodingStream.str().size();
  581. FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
  582. // Get tags from return type that are not present in function name or
  583. // encoding.
  584. const AbiTagList &UsedAbiTags =
  585. FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
  586. AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
  587. AdditionalAbiTags.erase(
  588. std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
  589. UsedAbiTags.begin(), UsedAbiTags.end(),
  590. AdditionalAbiTags.begin()),
  591. AdditionalAbiTags.end());
  592. // Output name with implicit tags and function encoding from temporary buffer.
  593. mangleNameWithAbiTags(FD, &AdditionalAbiTags);
  594. Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
  595. // Function encoding could create new substitutions so we have to add
  596. // temp mangled substitutions to main mangler.
  597. extendSubstitutions(&FunctionEncodingMangler);
  598. }
  599. void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
  600. if (FD->hasAttr<EnableIfAttr>()) {
  601. FunctionTypeDepthState Saved = FunctionTypeDepth.push();
  602. Out << "Ua9enable_ifI";
  603. // FIXME: specific_attr_iterator iterates in reverse order. Fix that and use
  604. // it here.
  605. for (AttrVec::const_reverse_iterator I = FD->getAttrs().rbegin(),
  606. E = FD->getAttrs().rend();
  607. I != E; ++I) {
  608. EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
  609. if (!EIA)
  610. continue;
  611. Out << 'X';
  612. mangleExpression(EIA->getCond());
  613. Out << 'E';
  614. }
  615. Out << 'E';
  616. FunctionTypeDepth.pop(Saved);
  617. }
  618. // When mangling an inheriting constructor, the bare function type used is
  619. // that of the inherited constructor.
  620. if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
  621. if (auto Inherited = CD->getInheritedConstructor())
  622. FD = Inherited.getConstructor();
  623. // Whether the mangling of a function type includes the return type depends on
  624. // the context and the nature of the function. The rules for deciding whether
  625. // the return type is included are:
  626. //
  627. // 1. Template functions (names or types) have return types encoded, with
  628. // the exceptions listed below.
  629. // 2. Function types not appearing as part of a function name mangling,
  630. // e.g. parameters, pointer types, etc., have return type encoded, with the
  631. // exceptions listed below.
  632. // 3. Non-template function names do not have return types encoded.
  633. //
  634. // The exceptions mentioned in (1) and (2) above, for which the return type is
  635. // never included, are
  636. // 1. Constructors.
  637. // 2. Destructors.
  638. // 3. Conversion operator functions, e.g. operator int.
  639. bool MangleReturnType = false;
  640. if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
  641. if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
  642. isa<CXXConversionDecl>(FD)))
  643. MangleReturnType = true;
  644. // Mangle the type of the primary template.
  645. FD = PrimaryTemplate->getTemplatedDecl();
  646. }
  647. mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
  648. MangleReturnType, FD);
  649. }
  650. static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
  651. while (isa<LinkageSpecDecl>(DC)) {
  652. DC = getEffectiveParentContext(DC);
  653. }
  654. return DC;
  655. }
  656. /// Return whether a given namespace is the 'std' namespace.
  657. static bool isStd(const NamespaceDecl *NS) {
  658. if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
  659. ->isTranslationUnit())
  660. return false;
  661. const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
  662. return II && II->isStr("std");
  663. }
  664. // isStdNamespace - Return whether a given decl context is a toplevel 'std'
  665. // namespace.
  666. static bool isStdNamespace(const DeclContext *DC) {
  667. if (!DC->isNamespace())
  668. return false;
  669. return isStd(cast<NamespaceDecl>(DC));
  670. }
  671. static const TemplateDecl *
  672. isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
  673. // Check if we have a function template.
  674. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  675. if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
  676. TemplateArgs = FD->getTemplateSpecializationArgs();
  677. return TD;
  678. }
  679. }
  680. // Check if we have a class template.
  681. if (const ClassTemplateSpecializationDecl *Spec =
  682. dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
  683. TemplateArgs = &Spec->getTemplateArgs();
  684. return Spec->getSpecializedTemplate();
  685. }
  686. // Check if we have a variable template.
  687. if (const VarTemplateSpecializationDecl *Spec =
  688. dyn_cast<VarTemplateSpecializationDecl>(ND)) {
  689. TemplateArgs = &Spec->getTemplateArgs();
  690. return Spec->getSpecializedTemplate();
  691. }
  692. return nullptr;
  693. }
  694. void CXXNameMangler::mangleName(const NamedDecl *ND) {
  695. if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
  696. // Variables should have implicit tags from its type.
  697. AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);
  698. if (VariableTypeAbiTags.empty()) {
  699. // Simple case no variable type tags.
  700. mangleNameWithAbiTags(VD, nullptr);
  701. return;
  702. }
  703. // Mangle variable name to null stream to collect tags.
  704. llvm::raw_null_ostream NullOutStream;
  705. CXXNameMangler VariableNameMangler(*this, NullOutStream);
  706. VariableNameMangler.disableDerivedAbiTags();
  707. VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);
  708. // Get tags from variable type that are not present in its name.
  709. const AbiTagList &UsedAbiTags =
  710. VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
  711. AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());
  712. AdditionalAbiTags.erase(
  713. std::set_difference(VariableTypeAbiTags.begin(),
  714. VariableTypeAbiTags.end(), UsedAbiTags.begin(),
  715. UsedAbiTags.end(), AdditionalAbiTags.begin()),
  716. AdditionalAbiTags.end());
  717. // Output name with implicit tags.
  718. mangleNameWithAbiTags(VD, &AdditionalAbiTags);
  719. } else {
  720. mangleNameWithAbiTags(ND, nullptr);
  721. }
  722. }
  723. void CXXNameMangler::mangleNameWithAbiTags(const NamedDecl *ND,
  724. const AbiTagList *AdditionalAbiTags) {
  725. // <name> ::= [<module-name>] <nested-name>
  726. // ::= [<module-name>] <unscoped-name>
  727. // ::= [<module-name>] <unscoped-template-name> <template-args>
  728. // ::= <local-name>
  729. //
  730. const DeclContext *DC = getEffectiveDeclContext(ND);
  731. // If this is an extern variable declared locally, the relevant DeclContext
  732. // is that of the containing namespace, or the translation unit.
  733. // FIXME: This is a hack; extern variables declared locally should have
  734. // a proper semantic declaration context!
  735. if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
  736. while (!DC->isNamespace() && !DC->isTranslationUnit())
  737. DC = getEffectiveParentContext(DC);
  738. else if (GetLocalClassDecl(ND)) {
  739. mangleLocalName(ND, AdditionalAbiTags);
  740. return;
  741. }
  742. DC = IgnoreLinkageSpecDecls(DC);
  743. if (isLocalContainerContext(DC)) {
  744. mangleLocalName(ND, AdditionalAbiTags);
  745. return;
  746. }
  747. // Do not mangle the owning module for an external linkage declaration.
  748. // This enables backwards-compatibility with non-modular code, and is
  749. // a valid choice since conflicts are not permitted by C++ Modules TS
  750. // [basic.def.odr]/6.2.
  751. if (!ND->hasExternalFormalLinkage())
  752. if (Module *M = ND->getOwningModuleForLinkage())
  753. mangleModuleName(M);
  754. if (DC->isTranslationUnit() || isStdNamespace(DC)) {
  755. // Check if we have a template.
  756. const TemplateArgumentList *TemplateArgs = nullptr;
  757. if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
  758. mangleUnscopedTemplateName(TD, AdditionalAbiTags);
  759. mangleTemplateArgs(*TemplateArgs);
  760. return;
  761. }
  762. mangleUnscopedName(ND, AdditionalAbiTags);
  763. return;
  764. }
  765. mangleNestedName(ND, DC, AdditionalAbiTags);
  766. }
  767. void CXXNameMangler::mangleModuleName(const Module *M) {
  768. // Implement the C++ Modules TS name mangling proposal; see
  769. // https://gcc.gnu.org/wiki/cxx-modules?action=AttachFile
  770. //
  771. // <module-name> ::= W <unscoped-name>+ E
  772. // ::= W <module-subst> <unscoped-name>* E
  773. Out << 'W';
  774. mangleModuleNamePrefix(M->Name);
  775. Out << 'E';
  776. }
  777. void CXXNameMangler::mangleModuleNamePrefix(StringRef Name) {
  778. // <module-subst> ::= _ <seq-id> # 0 < seq-id < 10
  779. // ::= W <seq-id - 10> _ # otherwise
  780. auto It = ModuleSubstitutions.find(Name);
  781. if (It != ModuleSubstitutions.end()) {
  782. if (It->second < 10)
  783. Out << '_' << static_cast<char>('0' + It->second);
  784. else
  785. Out << 'W' << (It->second - 10) << '_';
  786. return;
  787. }
  788. // FIXME: Preserve hierarchy in module names rather than flattening
  789. // them to strings; use Module*s as substitution keys.
  790. auto Parts = Name.rsplit('.');
  791. if (Parts.second.empty())
  792. Parts.second = Parts.first;
  793. else
  794. mangleModuleNamePrefix(Parts.first);
  795. Out << Parts.second.size() << Parts.second;
  796. ModuleSubstitutions.insert({Name, ModuleSubstitutions.size()});
  797. }
  798. void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
  799. const TemplateArgument *TemplateArgs,
  800. unsigned NumTemplateArgs) {
  801. const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
  802. if (DC->isTranslationUnit() || isStdNamespace(DC)) {
  803. mangleUnscopedTemplateName(TD, nullptr);
  804. mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
  805. } else {
  806. mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
  807. }
  808. }
  809. void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND,
  810. const AbiTagList *AdditionalAbiTags) {
  811. // <unscoped-name> ::= <unqualified-name>
  812. // ::= St <unqualified-name> # ::std::
  813. if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
  814. Out << "St";
  815. mangleUnqualifiedName(ND, AdditionalAbiTags);
  816. }
  817. void CXXNameMangler::mangleUnscopedTemplateName(
  818. const TemplateDecl *ND, const AbiTagList *AdditionalAbiTags) {
  819. // <unscoped-template-name> ::= <unscoped-name>
  820. // ::= <substitution>
  821. if (mangleSubstitution(ND))
  822. return;
  823. // <template-template-param> ::= <template-param>
  824. if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
  825. assert(!AdditionalAbiTags &&
  826. "template template param cannot have abi tags");
  827. mangleTemplateParameter(TTP->getIndex());
  828. } else if (isa<BuiltinTemplateDecl>(ND)) {
  829. mangleUnscopedName(ND, AdditionalAbiTags);
  830. } else {
  831. mangleUnscopedName(ND->getTemplatedDecl(), AdditionalAbiTags);
  832. }
  833. addSubstitution(ND);
  834. }
  835. void CXXNameMangler::mangleUnscopedTemplateName(
  836. TemplateName Template, const AbiTagList *AdditionalAbiTags) {
  837. // <unscoped-template-name> ::= <unscoped-name>
  838. // ::= <substitution>
  839. if (TemplateDecl *TD = Template.getAsTemplateDecl())
  840. return mangleUnscopedTemplateName(TD, AdditionalAbiTags);
  841. if (mangleSubstitution(Template))
  842. return;
  843. assert(!AdditionalAbiTags &&
  844. "dependent template name cannot have abi tags");
  845. DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
  846. assert(Dependent && "Not a dependent template name?");
  847. if (const IdentifierInfo *Id = Dependent->getIdentifier())
  848. mangleSourceName(Id);
  849. else
  850. mangleOperatorName(Dependent->getOperator(), UnknownArity);
  851. addSubstitution(Template);
  852. }
  853. void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
  854. // ABI:
  855. // Floating-point literals are encoded using a fixed-length
  856. // lowercase hexadecimal string corresponding to the internal
  857. // representation (IEEE on Itanium), high-order bytes first,
  858. // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
  859. // on Itanium.
  860. // The 'without leading zeroes' thing seems to be an editorial
  861. // mistake; see the discussion on cxx-abi-dev beginning on
  862. // 2012-01-16.
  863. // Our requirements here are just barely weird enough to justify
  864. // using a custom algorithm instead of post-processing APInt::toString().
  865. llvm::APInt valueBits = f.bitcastToAPInt();
  866. unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
  867. assert(numCharacters != 0);
  868. // Allocate a buffer of the right number of characters.
  869. SmallVector<char, 20> buffer(numCharacters);
  870. // Fill the buffer left-to-right.
  871. for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
  872. // The bit-index of the next hex digit.
  873. unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
  874. // Project out 4 bits starting at 'digitIndex'.
  875. uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64];
  876. hexDigit >>= (digitBitIndex % 64);
  877. hexDigit &= 0xF;
  878. // Map that over to a lowercase hex digit.
  879. static const char charForHex[16] = {
  880. '0', '1', '2', '3', '4', '5', '6', '7',
  881. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
  882. };
  883. buffer[stringIndex] = charForHex[hexDigit];
  884. }
  885. Out.write(buffer.data(), numCharacters);
  886. }
  887. void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
  888. if (Value.isSigned() && Value.isNegative()) {
  889. Out << 'n';
  890. Value.abs().print(Out, /*signed*/ false);
  891. } else {
  892. Value.print(Out, /*signed*/ false);
  893. }
  894. }
  895. void CXXNameMangler::mangleNumber(int64_t Number) {
  896. // <number> ::= [n] <non-negative decimal integer>
  897. if (Number < 0) {
  898. Out << 'n';
  899. Number = -Number;
  900. }
  901. Out << Number;
  902. }
  903. void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
  904. // <call-offset> ::= h <nv-offset> _
  905. // ::= v <v-offset> _
  906. // <nv-offset> ::= <offset number> # non-virtual base override
  907. // <v-offset> ::= <offset number> _ <virtual offset number>
  908. // # virtual base override, with vcall offset
  909. if (!Virtual) {
  910. Out << 'h';
  911. mangleNumber(NonVirtual);
  912. Out << '_';
  913. return;
  914. }
  915. Out << 'v';
  916. mangleNumber(NonVirtual);
  917. Out << '_';
  918. mangleNumber(Virtual);
  919. Out << '_';
  920. }
  921. void CXXNameMangler::manglePrefix(QualType type) {
  922. if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
  923. if (!mangleSubstitution(QualType(TST, 0))) {
  924. mangleTemplatePrefix(TST->getTemplateName());
  925. // FIXME: GCC does not appear to mangle the template arguments when
  926. // the template in question is a dependent template name. Should we
  927. // emulate that badness?
  928. mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
  929. addSubstitution(QualType(TST, 0));
  930. }
  931. } else if (const auto *DTST =
  932. type->getAs<DependentTemplateSpecializationType>()) {
  933. if (!mangleSubstitution(QualType(DTST, 0))) {
  934. TemplateName Template = getASTContext().getDependentTemplateName(
  935. DTST->getQualifier(), DTST->getIdentifier());
  936. mangleTemplatePrefix(Template);
  937. // FIXME: GCC does not appear to mangle the template arguments when
  938. // the template in question is a dependent template name. Should we
  939. // emulate that badness?
  940. mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
  941. addSubstitution(QualType(DTST, 0));
  942. }
  943. } else {
  944. // We use the QualType mangle type variant here because it handles
  945. // substitutions.
  946. mangleType(type);
  947. }
  948. }
  949. /// Mangle everything prior to the base-unresolved-name in an unresolved-name.
  950. ///
  951. /// \param recursive - true if this is being called recursively,
  952. /// i.e. if there is more prefix "to the right".
  953. void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
  954. bool recursive) {
  955. // x, ::x
  956. // <unresolved-name> ::= [gs] <base-unresolved-name>
  957. // T::x / decltype(p)::x
  958. // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
  959. // T::N::x /decltype(p)::N::x
  960. // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
  961. // <base-unresolved-name>
  962. // A::x, N::y, A<T>::z; "gs" means leading "::"
  963. // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
  964. // <base-unresolved-name>
  965. switch (qualifier->getKind()) {
  966. case NestedNameSpecifier::Global:
  967. Out << "gs";
  968. // We want an 'sr' unless this is the entire NNS.
  969. if (recursive)
  970. Out << "sr";
  971. // We never want an 'E' here.
  972. return;
  973. case NestedNameSpecifier::Super:
  974. llvm_unreachable("Can't mangle __super specifier");
  975. case NestedNameSpecifier::Namespace:
  976. if (qualifier->getPrefix())
  977. mangleUnresolvedPrefix(qualifier->getPrefix(),
  978. /*recursive*/ true);
  979. else
  980. Out << "sr";
  981. mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
  982. break;
  983. case NestedNameSpecifier::NamespaceAlias:
  984. if (qualifier->getPrefix())
  985. mangleUnresolvedPrefix(qualifier->getPrefix(),
  986. /*recursive*/ true);
  987. else
  988. Out << "sr";
  989. mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
  990. break;
  991. case NestedNameSpecifier::TypeSpec:
  992. case NestedNameSpecifier::TypeSpecWithTemplate: {
  993. const Type *type = qualifier->getAsType();
  994. // We only want to use an unresolved-type encoding if this is one of:
  995. // - a decltype
  996. // - a template type parameter
  997. // - a template template parameter with arguments
  998. // In all of these cases, we should have no prefix.
  999. if (qualifier->getPrefix()) {
  1000. mangleUnresolvedPrefix(qualifier->getPrefix(),
  1001. /*recursive*/ true);
  1002. } else {
  1003. // Otherwise, all the cases want this.
  1004. Out << "sr";
  1005. }
  1006. if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
  1007. return;
  1008. break;
  1009. }
  1010. case NestedNameSpecifier::Identifier:
  1011. // Member expressions can have these without prefixes.
  1012. if (qualifier->getPrefix())
  1013. mangleUnresolvedPrefix(qualifier->getPrefix(),
  1014. /*recursive*/ true);
  1015. else
  1016. Out << "sr";
  1017. mangleSourceName(qualifier->getAsIdentifier());
  1018. // An Identifier has no type information, so we can't emit abi tags for it.
  1019. break;
  1020. }
  1021. // If this was the innermost part of the NNS, and we fell out to
  1022. // here, append an 'E'.
  1023. if (!recursive)
  1024. Out << 'E';
  1025. }
  1026. /// Mangle an unresolved-name, which is generally used for names which
  1027. /// weren't resolved to specific entities.
  1028. void CXXNameMangler::mangleUnresolvedName(
  1029. NestedNameSpecifier *qualifier, DeclarationName name,
  1030. const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,
  1031. unsigned knownArity) {
  1032. if (qualifier) mangleUnresolvedPrefix(qualifier);
  1033. switch (name.getNameKind()) {
  1034. // <base-unresolved-name> ::= <simple-id>
  1035. case DeclarationName::Identifier:
  1036. mangleSourceName(name.getAsIdentifierInfo());
  1037. break;
  1038. // <base-unresolved-name> ::= dn <destructor-name>
  1039. case DeclarationName::CXXDestructorName:
  1040. Out << "dn";
  1041. mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
  1042. break;
  1043. // <base-unresolved-name> ::= on <operator-name>
  1044. case DeclarationName::CXXConversionFunctionName:
  1045. case DeclarationName::CXXLiteralOperatorName:
  1046. case DeclarationName::CXXOperatorName:
  1047. Out << "on";
  1048. mangleOperatorName(name, knownArity);
  1049. break;
  1050. case DeclarationName::CXXConstructorName:
  1051. llvm_unreachable("Can't mangle a constructor name!");
  1052. case DeclarationName::CXXUsingDirective:
  1053. llvm_unreachable("Can't mangle a using directive name!");
  1054. case DeclarationName::CXXDeductionGuideName:
  1055. llvm_unreachable("Can't mangle a deduction guide name!");
  1056. case DeclarationName::ObjCMultiArgSelector:
  1057. case DeclarationName::ObjCOneArgSelector:
  1058. case DeclarationName::ObjCZeroArgSelector:
  1059. llvm_unreachable("Can't mangle Objective-C selector names here!");
  1060. }
  1061. // The <simple-id> and on <operator-name> productions end in an optional
  1062. // <template-args>.
  1063. if (TemplateArgs)
  1064. mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
  1065. }
  1066. void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
  1067. DeclarationName Name,
  1068. unsigned KnownArity,
  1069. const AbiTagList *AdditionalAbiTags) {
  1070. unsigned Arity = KnownArity;
  1071. // <unqualified-name> ::= <operator-name>
  1072. // ::= <ctor-dtor-name>
  1073. // ::= <source-name>
  1074. switch (Name.getNameKind()) {
  1075. case DeclarationName::Identifier: {
  1076. const IdentifierInfo *II = Name.getAsIdentifierInfo();
  1077. // We mangle decomposition declarations as the names of their bindings.
  1078. if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {
  1079. // FIXME: Non-standard mangling for decomposition declarations:
  1080. //
  1081. // <unqualified-name> ::= DC <source-name>* E
  1082. //
  1083. // These can never be referenced across translation units, so we do
  1084. // not need a cross-vendor mangling for anything other than demanglers.
  1085. // Proposed on cxx-abi-dev on 2016-08-12
  1086. Out << "DC";
  1087. for (auto *BD : DD->bindings())
  1088. mangleSourceName(BD->getDeclName().getAsIdentifierInfo());
  1089. Out << 'E';
  1090. writeAbiTags(ND, AdditionalAbiTags);
  1091. break;
  1092. }
  1093. if (II) {
  1094. // Match GCC's naming convention for internal linkage symbols, for
  1095. // symbols that are not actually visible outside of this TU. GCC
  1096. // distinguishes between internal and external linkage symbols in
  1097. // its mangling, to support cases like this that were valid C++ prior
  1098. // to DR426:
  1099. //
  1100. // void test() { extern void foo(); }
  1101. // static void foo();
  1102. //
  1103. // Don't bother with the L marker for names in anonymous namespaces; the
  1104. // 12_GLOBAL__N_1 mangling is quite sufficient there, and this better
  1105. // matches GCC anyway, because GCC does not treat anonymous namespaces as
  1106. // implying internal linkage.
  1107. if (ND && ND->getFormalLinkage() == InternalLinkage &&
  1108. !ND->isExternallyVisible() &&
  1109. getEffectiveDeclContext(ND)->isFileContext() &&
  1110. !ND->isInAnonymousNamespace())
  1111. Out << 'L';
  1112. auto *FD = dyn_cast<FunctionDecl>(ND);
  1113. bool IsRegCall = FD &&
  1114. FD->getType()->castAs<FunctionType>()->getCallConv() ==
  1115. clang::CC_X86RegCall;
  1116. if (IsRegCall)
  1117. mangleRegCallName(II);
  1118. else
  1119. mangleSourceName(II);
  1120. writeAbiTags(ND, AdditionalAbiTags);
  1121. break;
  1122. }
  1123. // Otherwise, an anonymous entity. We must have a declaration.
  1124. assert(ND && "mangling empty name without declaration");
  1125. if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
  1126. if (NS->isAnonymousNamespace()) {
  1127. // This is how gcc mangles these names.
  1128. Out << "12_GLOBAL__N_1";
  1129. break;
  1130. }
  1131. }
  1132. if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
  1133. // We must have an anonymous union or struct declaration.
  1134. const RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
  1135. // Itanium C++ ABI 5.1.2:
  1136. //
  1137. // For the purposes of mangling, the name of an anonymous union is
  1138. // considered to be the name of the first named data member found by a
  1139. // pre-order, depth-first, declaration-order walk of the data members of
  1140. // the anonymous union. If there is no such data member (i.e., if all of
  1141. // the data members in the union are unnamed), then there is no way for
  1142. // a program to refer to the anonymous union, and there is therefore no
  1143. // need to mangle its name.
  1144. assert(RD->isAnonymousStructOrUnion()
  1145. && "Expected anonymous struct or union!");
  1146. const FieldDecl *FD = RD->findFirstNamedDataMember();
  1147. // It's actually possible for various reasons for us to get here
  1148. // with an empty anonymous struct / union. Fortunately, it
  1149. // doesn't really matter what name we generate.
  1150. if (!FD) break;
  1151. assert(FD->getIdentifier() && "Data member name isn't an identifier!");
  1152. mangleSourceName(FD->getIdentifier());
  1153. // Not emitting abi tags: internal name anyway.
  1154. break;
  1155. }
  1156. // Class extensions have no name as a category, and it's possible
  1157. // for them to be the semantic parent of certain declarations
  1158. // (primarily, tag decls defined within declarations). Such
  1159. // declarations will always have internal linkage, so the name
  1160. // doesn't really matter, but we shouldn't crash on them. For
  1161. // safety, just handle all ObjC containers here.
  1162. if (isa<ObjCContainerDecl>(ND))
  1163. break;
  1164. // We must have an anonymous struct.
  1165. const TagDecl *TD = cast<TagDecl>(ND);
  1166. if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
  1167. assert(TD->getDeclContext() == D->getDeclContext() &&
  1168. "Typedef should not be in another decl context!");
  1169. assert(D->getDeclName().getAsIdentifierInfo() &&
  1170. "Typedef was not named!");
  1171. mangleSourceName(D->getDeclName().getAsIdentifierInfo());
  1172. assert(!AdditionalAbiTags && "Type cannot have additional abi tags");
  1173. // Explicit abi tags are still possible; take from underlying type, not
  1174. // from typedef.
  1175. writeAbiTags(TD, nullptr);
  1176. break;
  1177. }
  1178. // <unnamed-type-name> ::= <closure-type-name>
  1179. //
  1180. // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
  1181. // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
  1182. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
  1183. if (Record->isLambda() && Record->getLambdaManglingNumber()) {
  1184. assert(!AdditionalAbiTags &&
  1185. "Lambda type cannot have additional abi tags");
  1186. mangleLambda(Record);
  1187. break;
  1188. }
  1189. }
  1190. if (TD->isExternallyVisible()) {
  1191. unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
  1192. Out << "Ut";
  1193. if (UnnamedMangle > 1)
  1194. Out << UnnamedMangle - 2;
  1195. Out << '_';
  1196. writeAbiTags(TD, AdditionalAbiTags);
  1197. break;
  1198. }
  1199. // Get a unique id for the anonymous struct. If it is not a real output
  1200. // ID doesn't matter so use fake one.
  1201. unsigned AnonStructId = NullOut ? 0 : Context.getAnonymousStructId(TD);
  1202. // Mangle it as a source name in the form
  1203. // [n] $_<id>
  1204. // where n is the length of the string.
  1205. SmallString<8> Str;
  1206. Str += "$_";
  1207. Str += llvm::utostr(AnonStructId);
  1208. Out << Str.size();
  1209. Out << Str;
  1210. break;
  1211. }
  1212. case DeclarationName::ObjCZeroArgSelector:
  1213. case DeclarationName::ObjCOneArgSelector:
  1214. case DeclarationName::ObjCMultiArgSelector:
  1215. llvm_unreachable("Can't mangle Objective-C selector names here!");
  1216. case DeclarationName::CXXConstructorName: {
  1217. const CXXRecordDecl *InheritedFrom = nullptr;
  1218. const TemplateArgumentList *InheritedTemplateArgs = nullptr;
  1219. if (auto Inherited =
  1220. cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
  1221. InheritedFrom = Inherited.getConstructor()->getParent();
  1222. InheritedTemplateArgs =
  1223. Inherited.getConstructor()->getTemplateSpecializationArgs();
  1224. }
  1225. if (ND == Structor)
  1226. // If the named decl is the C++ constructor we're mangling, use the type
  1227. // we were given.
  1228. mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
  1229. else
  1230. // Otherwise, use the complete constructor name. This is relevant if a
  1231. // class with a constructor is declared within a constructor.
  1232. mangleCXXCtorType(Ctor_Complete, InheritedFrom);
  1233. // FIXME: The template arguments are part of the enclosing prefix or
  1234. // nested-name, but it's more convenient to mangle them here.
  1235. if (InheritedTemplateArgs)
  1236. mangleTemplateArgs(*InheritedTemplateArgs);
  1237. writeAbiTags(ND, AdditionalAbiTags);
  1238. break;
  1239. }
  1240. case DeclarationName::CXXDestructorName:
  1241. if (ND == Structor)
  1242. // If the named decl is the C++ destructor we're mangling, use the type we
  1243. // were given.
  1244. mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
  1245. else
  1246. // Otherwise, use the complete destructor name. This is relevant if a
  1247. // class with a destructor is declared within a destructor.
  1248. mangleCXXDtorType(Dtor_Complete);
  1249. writeAbiTags(ND, AdditionalAbiTags);
  1250. break;
  1251. case DeclarationName::CXXOperatorName:
  1252. if (ND && Arity == UnknownArity) {
  1253. Arity = cast<FunctionDecl>(ND)->getNumParams();
  1254. // If we have a member function, we need to include the 'this' pointer.
  1255. if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
  1256. if (!MD->isStatic())
  1257. Arity++;
  1258. }
  1259. LLVM_FALLTHROUGH;
  1260. case DeclarationName::CXXConversionFunctionName:
  1261. case DeclarationName::CXXLiteralOperatorName:
  1262. mangleOperatorName(Name, Arity);
  1263. writeAbiTags(ND, AdditionalAbiTags);
  1264. break;
  1265. case DeclarationName::CXXDeductionGuideName:
  1266. llvm_unreachable("Can't mangle a deduction guide name!");
  1267. case DeclarationName::CXXUsingDirective:
  1268. llvm_unreachable("Can't mangle a using directive name!");
  1269. }
  1270. }
  1271. void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) {
  1272. // <source-name> ::= <positive length number> __regcall3__ <identifier>
  1273. // <number> ::= [n] <non-negative decimal integer>
  1274. // <identifier> ::= <unqualified source code identifier>
  1275. Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"
  1276. << II->getName();
  1277. }
  1278. void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
  1279. // <source-name> ::= <positive length number> <identifier>
  1280. // <number> ::= [n] <non-negative decimal integer>
  1281. // <identifier> ::= <unqualified source code identifier>
  1282. Out << II->getLength() << II->getName();
  1283. }
  1284. void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
  1285. const DeclContext *DC,
  1286. const AbiTagList *AdditionalAbiTags,
  1287. bool NoFunction) {
  1288. // <nested-name>
  1289. // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
  1290. // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
  1291. // <template-args> E
  1292. Out << 'N';
  1293. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
  1294. Qualifiers MethodQuals =
  1295. Qualifiers::fromCVRUMask(Method->getTypeQualifiers());
  1296. // We do not consider restrict a distinguishing attribute for overloading
  1297. // purposes so we must not mangle it.
  1298. MethodQuals.removeRestrict();
  1299. mangleQualifiers(MethodQuals);
  1300. mangleRefQualifier(Method->getRefQualifier());
  1301. }
  1302. // Check if we have a template.
  1303. const TemplateArgumentList *TemplateArgs = nullptr;
  1304. if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
  1305. mangleTemplatePrefix(TD, NoFunction);
  1306. mangleTemplateArgs(*TemplateArgs);
  1307. }
  1308. else {
  1309. manglePrefix(DC, NoFunction);
  1310. mangleUnqualifiedName(ND, AdditionalAbiTags);
  1311. }
  1312. Out << 'E';
  1313. }
  1314. void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
  1315. const TemplateArgument *TemplateArgs,
  1316. unsigned NumTemplateArgs) {
  1317. // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
  1318. Out << 'N';
  1319. mangleTemplatePrefix(TD);
  1320. mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
  1321. Out << 'E';
  1322. }
  1323. void CXXNameMangler::mangleLocalName(const Decl *D,
  1324. const AbiTagList *AdditionalAbiTags) {
  1325. // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
  1326. // := Z <function encoding> E s [<discriminator>]
  1327. // <local-name> := Z <function encoding> E d [ <parameter number> ]
  1328. // _ <entity name>
  1329. // <discriminator> := _ <non-negative number>
  1330. assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
  1331. const RecordDecl *RD = GetLocalClassDecl(D);
  1332. const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
  1333. Out << 'Z';
  1334. {
  1335. AbiTagState LocalAbiTags(AbiTags);
  1336. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
  1337. mangleObjCMethodName(MD);
  1338. else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
  1339. mangleBlockForPrefix(BD);
  1340. else
  1341. mangleFunctionEncoding(cast<FunctionDecl>(DC));
  1342. // Implicit ABI tags (from namespace) are not available in the following
  1343. // entity; reset to actually emitted tags, which are available.
  1344. LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
  1345. }
  1346. Out << 'E';
  1347. // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
  1348. // be a bug that is fixed in trunk.
  1349. if (RD) {
  1350. // The parameter number is omitted for the last parameter, 0 for the
  1351. // second-to-last parameter, 1 for the third-to-last parameter, etc. The
  1352. // <entity name> will of course contain a <closure-type-name>: Its
  1353. // numbering will be local to the particular argument in which it appears
  1354. // -- other default arguments do not affect its encoding.
  1355. const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
  1356. if (CXXRD && CXXRD->isLambda()) {
  1357. if (const ParmVarDecl *Parm
  1358. = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
  1359. if (const FunctionDecl *Func
  1360. = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
  1361. Out << 'd';
  1362. unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
  1363. if (Num > 1)
  1364. mangleNumber(Num - 2);
  1365. Out << '_';
  1366. }
  1367. }
  1368. }
  1369. // Mangle the name relative to the closest enclosing function.
  1370. // equality ok because RD derived from ND above
  1371. if (D == RD) {
  1372. mangleUnqualifiedName(RD, AdditionalAbiTags);
  1373. } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
  1374. manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
  1375. assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
  1376. mangleUnqualifiedBlock(BD);
  1377. } else {
  1378. const NamedDecl *ND = cast<NamedDecl>(D);
  1379. mangleNestedName(ND, getEffectiveDeclContext(ND), AdditionalAbiTags,
  1380. true /*NoFunction*/);
  1381. }
  1382. } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
  1383. // Mangle a block in a default parameter; see above explanation for
  1384. // lambdas.
  1385. if (const ParmVarDecl *Parm
  1386. = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
  1387. if (const FunctionDecl *Func
  1388. = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
  1389. Out << 'd';
  1390. unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
  1391. if (Num > 1)
  1392. mangleNumber(Num - 2);
  1393. Out << '_';
  1394. }
  1395. }
  1396. assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
  1397. mangleUnqualifiedBlock(BD);
  1398. } else {
  1399. mangleUnqualifiedName(cast<NamedDecl>(D), AdditionalAbiTags);
  1400. }
  1401. if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
  1402. unsigned disc;
  1403. if (Context.getNextDiscriminator(ND, disc)) {
  1404. if (disc < 10)
  1405. Out << '_' << disc;
  1406. else
  1407. Out << "__" << disc << '_';
  1408. }
  1409. }
  1410. }
  1411. void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
  1412. if (GetLocalClassDecl(Block)) {
  1413. mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
  1414. return;
  1415. }
  1416. const DeclContext *DC = getEffectiveDeclContext(Block);
  1417. if (isLocalContainerContext(DC)) {
  1418. mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
  1419. return;
  1420. }
  1421. manglePrefix(getEffectiveDeclContext(Block));
  1422. mangleUnqualifiedBlock(Block);
  1423. }
  1424. void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
  1425. if (Decl *Context = Block->getBlockManglingContextDecl()) {
  1426. if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
  1427. Context->getDeclContext()->isRecord()) {
  1428. const auto *ND = cast<NamedDecl>(Context);
  1429. if (ND->getIdentifier()) {
  1430. mangleSourceNameWithAbiTags(ND);
  1431. Out << 'M';
  1432. }
  1433. }
  1434. }
  1435. // If we have a block mangling number, use it.
  1436. unsigned Number = Block->getBlockManglingNumber();
  1437. // Otherwise, just make up a number. It doesn't matter what it is because
  1438. // the symbol in question isn't externally visible.
  1439. if (!Number)
  1440. Number = Context.getBlockId(Block, false);
  1441. else {
  1442. // Stored mangling numbers are 1-based.
  1443. --Number;
  1444. }
  1445. Out << "Ub";
  1446. if (Number > 0)
  1447. Out << Number - 1;
  1448. Out << '_';
  1449. }
  1450. void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
  1451. // If the context of a closure type is an initializer for a class member
  1452. // (static or nonstatic), it is encoded in a qualified name with a final
  1453. // <prefix> of the form:
  1454. //
  1455. // <data-member-prefix> := <member source-name> M
  1456. //
  1457. // Technically, the data-member-prefix is part of the <prefix>. However,
  1458. // since a closure type will always be mangled with a prefix, it's easier
  1459. // to emit that last part of the prefix here.
  1460. if (Decl *Context = Lambda->getLambdaContextDecl()) {
  1461. if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
  1462. !isa<ParmVarDecl>(Context)) {
  1463. // FIXME: 'inline auto [a, b] = []{ return ... };' does not get a
  1464. // reasonable mangling here.
  1465. if (const IdentifierInfo *Name
  1466. = cast<NamedDecl>(Context)->getIdentifier()) {
  1467. mangleSourceName(Name);
  1468. const TemplateArgumentList *TemplateArgs = nullptr;
  1469. if (isTemplate(cast<NamedDecl>(Context), TemplateArgs))
  1470. mangleTemplateArgs(*TemplateArgs);
  1471. Out << 'M';
  1472. }
  1473. }
  1474. }
  1475. Out << "Ul";
  1476. const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
  1477. getAs<FunctionProtoType>();
  1478. mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
  1479. Lambda->getLambdaStaticInvoker());
  1480. Out << "E";
  1481. // The number is omitted for the first closure type with a given
  1482. // <lambda-sig> in a given context; it is n-2 for the nth closure type
  1483. // (in lexical order) with that same <lambda-sig> and context.
  1484. //
  1485. // The AST keeps track of the number for us.
  1486. unsigned Number = Lambda->getLambdaManglingNumber();
  1487. assert(Number > 0 && "Lambda should be mangled as an unnamed class");
  1488. if (Number > 1)
  1489. mangleNumber(Number - 2);
  1490. Out << '_';
  1491. }
  1492. void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
  1493. switch (qualifier->getKind()) {
  1494. case NestedNameSpecifier::Global:
  1495. // nothing
  1496. return;
  1497. case NestedNameSpecifier::Super:
  1498. llvm_unreachable("Can't mangle __super specifier");
  1499. case NestedNameSpecifier::Namespace:
  1500. mangleName(qualifier->getAsNamespace());
  1501. return;
  1502. case NestedNameSpecifier::NamespaceAlias:
  1503. mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
  1504. return;
  1505. case NestedNameSpecifier::TypeSpec:
  1506. case NestedNameSpecifier::TypeSpecWithTemplate:
  1507. manglePrefix(QualType(qualifier->getAsType(), 0));
  1508. return;
  1509. case NestedNameSpecifier::Identifier:
  1510. // Member expressions can have these without prefixes, but that
  1511. // should end up in mangleUnresolvedPrefix instead.
  1512. assert(qualifier->getPrefix());
  1513. manglePrefix(qualifier->getPrefix());
  1514. mangleSourceName(qualifier->getAsIdentifier());
  1515. return;
  1516. }
  1517. llvm_unreachable("unexpected nested name specifier");
  1518. }
  1519. void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
  1520. // <prefix> ::= <prefix> <unqualified-name>
  1521. // ::= <template-prefix> <template-args>
  1522. // ::= <template-param>
  1523. // ::= # empty
  1524. // ::= <substitution>
  1525. DC = IgnoreLinkageSpecDecls(DC);
  1526. if (DC->isTranslationUnit())
  1527. return;
  1528. if (NoFunction && isLocalContainerContext(DC))
  1529. return;
  1530. assert(!isLocalContainerContext(DC));
  1531. const NamedDecl *ND = cast<NamedDecl>(DC);
  1532. if (mangleSubstitution(ND))
  1533. return;
  1534. // Check if we have a template.
  1535. const TemplateArgumentList *TemplateArgs = nullptr;
  1536. if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
  1537. mangleTemplatePrefix(TD);
  1538. mangleTemplateArgs(*TemplateArgs);
  1539. } else {
  1540. manglePrefix(getEffectiveDeclContext(ND), NoFunction);
  1541. mangleUnqualifiedName(ND, nullptr);
  1542. }
  1543. addSubstitution(ND);
  1544. }
  1545. void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
  1546. // <template-prefix> ::= <prefix> <template unqualified-name>
  1547. // ::= <template-param>
  1548. // ::= <substitution>
  1549. if (TemplateDecl *TD = Template.getAsTemplateDecl())
  1550. return mangleTemplatePrefix(TD);
  1551. if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
  1552. manglePrefix(Qualified->getQualifier());
  1553. if (OverloadedTemplateStorage *Overloaded
  1554. = Template.getAsOverloadedTemplate()) {
  1555. mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
  1556. UnknownArity, nullptr);
  1557. return;
  1558. }
  1559. DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
  1560. assert(Dependent && "Unknown template name kind?");
  1561. if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
  1562. manglePrefix(Qualifier);
  1563. mangleUnscopedTemplateName(Template, /* AdditionalAbiTags */ nullptr);
  1564. }
  1565. void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
  1566. bool NoFunction) {
  1567. // <template-prefix> ::= <prefix> <template unqualified-name>
  1568. // ::= <template-param>
  1569. // ::= <substitution>
  1570. // <template-template-param> ::= <template-param>
  1571. // <substitution>
  1572. if (mangleSubstitution(ND))
  1573. return;
  1574. // <template-template-param> ::= <template-param>
  1575. if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
  1576. mangleTemplateParameter(TTP->getIndex());
  1577. } else {
  1578. manglePrefix(getEffectiveDeclContext(ND), NoFunction);
  1579. if (isa<BuiltinTemplateDecl>(ND))
  1580. mangleUnqualifiedName(ND, nullptr);
  1581. else
  1582. mangleUnqualifiedName(ND->getTemplatedDecl(), nullptr);
  1583. }
  1584. addSubstitution(ND);
  1585. }
  1586. /// Mangles a template name under the production <type>. Required for
  1587. /// template template arguments.
  1588. /// <type> ::= <class-enum-type>
  1589. /// ::= <template-param>
  1590. /// ::= <substitution>
  1591. void CXXNameMangler::mangleType(TemplateName TN) {
  1592. if (mangleSubstitution(TN))
  1593. return;
  1594. TemplateDecl *TD = nullptr;
  1595. switch (TN.getKind()) {
  1596. case TemplateName::QualifiedTemplate:
  1597. TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
  1598. goto HaveDecl;
  1599. case TemplateName::Template:
  1600. TD = TN.getAsTemplateDecl();
  1601. goto HaveDecl;
  1602. HaveDecl:
  1603. if (isa<TemplateTemplateParmDecl>(TD))
  1604. mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
  1605. else
  1606. mangleName(TD);
  1607. break;
  1608. case TemplateName::OverloadedTemplate:
  1609. llvm_unreachable("can't mangle an overloaded template name as a <type>");
  1610. case TemplateName::DependentTemplate: {
  1611. const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
  1612. assert(Dependent->isIdentifier());
  1613. // <class-enum-type> ::= <name>
  1614. // <name> ::= <nested-name>
  1615. mangleUnresolvedPrefix(Dependent->getQualifier());
  1616. mangleSourceName(Dependent->getIdentifier());
  1617. break;
  1618. }
  1619. case TemplateName::SubstTemplateTemplateParm: {
  1620. // Substituted template parameters are mangled as the substituted
  1621. // template. This will check for the substitution twice, which is
  1622. // fine, but we have to return early so that we don't try to *add*
  1623. // the substitution twice.
  1624. SubstTemplateTemplateParmStorage *subst
  1625. = TN.getAsSubstTemplateTemplateParm();
  1626. mangleType(subst->getReplacement());
  1627. return;
  1628. }
  1629. case TemplateName::SubstTemplateTemplateParmPack: {
  1630. // FIXME: not clear how to mangle this!
  1631. // template <template <class> class T...> class A {
  1632. // template <template <class> class U...> void foo(B<T,U> x...);
  1633. // };
  1634. Out << "_SUBSTPACK_";
  1635. break;
  1636. }
  1637. }
  1638. addSubstitution(TN);
  1639. }
  1640. bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
  1641. StringRef Prefix) {
  1642. // Only certain other types are valid as prefixes; enumerate them.
  1643. switch (Ty->getTypeClass()) {
  1644. case Type::Builtin:
  1645. case Type::Complex:
  1646. case Type::Adjusted:
  1647. case Type::Decayed:
  1648. case Type::Pointer:
  1649. case Type::BlockPointer:
  1650. case Type::LValueReference:
  1651. case Type::RValueReference:
  1652. case Type::MemberPointer:
  1653. case Type::ConstantArray:
  1654. case Type::IncompleteArray:
  1655. case Type::VariableArray:
  1656. case Type::DependentSizedArray:
  1657. case Type::DependentAddressSpace:
  1658. case Type::DependentSizedExtVector:
  1659. case Type::Vector:
  1660. case Type::ExtVector:
  1661. case Type::FunctionProto:
  1662. case Type::FunctionNoProto:
  1663. case Type::Paren:
  1664. case Type::Attributed:
  1665. case Type::Auto:
  1666. case Type::DeducedTemplateSpecialization:
  1667. case Type::PackExpansion:
  1668. case Type::ObjCObject:
  1669. case Type::ObjCInterface:
  1670. case Type::ObjCObjectPointer:
  1671. case Type::ObjCTypeParam:
  1672. case Type::Atomic:
  1673. case Type::Pipe:
  1674. llvm_unreachable("type is illegal as a nested name specifier");
  1675. case Type::SubstTemplateTypeParmPack:
  1676. // FIXME: not clear how to mangle this!
  1677. // template <class T...> class A {
  1678. // template <class U...> void foo(decltype(T::foo(U())) x...);
  1679. // };
  1680. Out << "_SUBSTPACK_";
  1681. break;
  1682. // <unresolved-type> ::= <template-param>
  1683. // ::= <decltype>
  1684. // ::= <template-template-param> <template-args>
  1685. // (this last is not official yet)
  1686. case Type::TypeOfExpr:
  1687. case Type::TypeOf:
  1688. case Type::Decltype:
  1689. case Type::TemplateTypeParm:
  1690. case Type::UnaryTransform:
  1691. case Type::SubstTemplateTypeParm:
  1692. unresolvedType:
  1693. // Some callers want a prefix before the mangled type.
  1694. Out << Prefix;
  1695. // This seems to do everything we want. It's not really
  1696. // sanctioned for a substituted template parameter, though.
  1697. mangleType(Ty);
  1698. // We never want to print 'E' directly after an unresolved-type,
  1699. // so we return directly.
  1700. return true;
  1701. case Type::Typedef:
  1702. mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
  1703. break;
  1704. case Type::UnresolvedUsing:
  1705. mangleSourceNameWithAbiTags(
  1706. cast<UnresolvedUsingType>(Ty)->getDecl());
  1707. break;
  1708. case Type::Enum:
  1709. case Type::Record:
  1710. mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
  1711. break;
  1712. case Type::TemplateSpecialization: {
  1713. const TemplateSpecializationType *TST =
  1714. cast<TemplateSpecializationType>(Ty);
  1715. TemplateName TN = TST->getTemplateName();
  1716. switch (TN.getKind()) {
  1717. case TemplateName::Template:
  1718. case TemplateName::QualifiedTemplate: {
  1719. TemplateDecl *TD = TN.getAsTemplateDecl();
  1720. // If the base is a template template parameter, this is an
  1721. // unresolved type.
  1722. assert(TD && "no template for template specialization type");
  1723. if (isa<TemplateTemplateParmDecl>(TD))
  1724. goto unresolvedType;
  1725. mangleSourceNameWithAbiTags(TD);
  1726. break;
  1727. }
  1728. case TemplateName::OverloadedTemplate:
  1729. case TemplateName::DependentTemplate:
  1730. llvm_unreachable("invalid base for a template specialization type");
  1731. case TemplateName::SubstTemplateTemplateParm: {
  1732. SubstTemplateTemplateParmStorage *subst =
  1733. TN.getAsSubstTemplateTemplateParm();
  1734. mangleExistingSubstitution(subst->getReplacement());
  1735. break;
  1736. }
  1737. case TemplateName::SubstTemplateTemplateParmPack: {
  1738. // FIXME: not clear how to mangle this!
  1739. // template <template <class U> class T...> class A {
  1740. // template <class U...> void foo(decltype(T<U>::foo) x...);
  1741. // };
  1742. Out << "_SUBSTPACK_";
  1743. break;
  1744. }
  1745. }
  1746. mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
  1747. break;
  1748. }
  1749. case Type::InjectedClassName:
  1750. mangleSourceNameWithAbiTags(
  1751. cast<InjectedClassNameType>(Ty)->getDecl());
  1752. break;
  1753. case Type::DependentName:
  1754. mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
  1755. break;
  1756. case Type::DependentTemplateSpecialization: {
  1757. const DependentTemplateSpecializationType *DTST =
  1758. cast<DependentTemplateSpecializationType>(Ty);
  1759. mangleSourceName(DTST->getIdentifier());
  1760. mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
  1761. break;
  1762. }
  1763. case Type::Elaborated:
  1764. return mangleUnresolvedTypeOrSimpleId(
  1765. cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
  1766. }
  1767. return false;
  1768. }
  1769. void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
  1770. switch (Name.getNameKind()) {
  1771. case DeclarationName::CXXConstructorName:
  1772. case DeclarationName::CXXDestructorName:
  1773. case DeclarationName::CXXDeductionGuideName:
  1774. case DeclarationName::CXXUsingDirective:
  1775. case DeclarationName::Identifier:
  1776. case DeclarationName::ObjCMultiArgSelector:
  1777. case DeclarationName::ObjCOneArgSelector:
  1778. case DeclarationName::ObjCZeroArgSelector:
  1779. llvm_unreachable("Not an operator name");
  1780. case DeclarationName::CXXConversionFunctionName:
  1781. // <operator-name> ::= cv <type> # (cast)
  1782. Out << "cv";
  1783. mangleType(Name.getCXXNameType());
  1784. break;
  1785. case DeclarationName::CXXLiteralOperatorName:
  1786. Out << "li";
  1787. mangleSourceName(Name.getCXXLiteralIdentifier());
  1788. return;
  1789. case DeclarationName::CXXOperatorName:
  1790. mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
  1791. break;
  1792. }
  1793. }
  1794. void
  1795. CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
  1796. switch (OO) {
  1797. // <operator-name> ::= nw # new
  1798. case OO_New: Out << "nw"; break;
  1799. // ::= na # new[]
  1800. case OO_Array_New: Out << "na"; break;
  1801. // ::= dl # delete
  1802. case OO_Delete: Out << "dl"; break;
  1803. // ::= da # delete[]
  1804. case OO_Array_Delete: Out << "da"; break;
  1805. // ::= ps # + (unary)
  1806. // ::= pl # + (binary or unknown)
  1807. case OO_Plus:
  1808. Out << (Arity == 1? "ps" : "pl"); break;
  1809. // ::= ng # - (unary)
  1810. // ::= mi # - (binary or unknown)
  1811. case OO_Minus:
  1812. Out << (Arity == 1? "ng" : "mi"); break;
  1813. // ::= ad # & (unary)
  1814. // ::= an # & (binary or unknown)
  1815. case OO_Amp:
  1816. Out << (Arity == 1? "ad" : "an"); break;
  1817. // ::= de # * (unary)
  1818. // ::= ml # * (binary or unknown)
  1819. case OO_Star:
  1820. // Use binary when unknown.
  1821. Out << (Arity == 1? "de" : "ml"); break;
  1822. // ::= co # ~
  1823. case OO_Tilde: Out << "co"; break;
  1824. // ::= dv # /
  1825. case OO_Slash: Out << "dv"; break;
  1826. // ::= rm # %
  1827. case OO_Percent: Out << "rm"; break;
  1828. // ::= or # |
  1829. case OO_Pipe: Out << "or"; break;
  1830. // ::= eo # ^
  1831. case OO_Caret: Out << "eo"; break;
  1832. // ::= aS # =
  1833. case OO_Equal: Out << "aS"; break;
  1834. // ::= pL # +=
  1835. case OO_PlusEqual: Out << "pL"; break;
  1836. // ::= mI # -=
  1837. case OO_MinusEqual: Out << "mI"; break;
  1838. // ::= mL # *=
  1839. case OO_StarEqual: Out << "mL"; break;
  1840. // ::= dV # /=
  1841. case OO_SlashEqual: Out << "dV"; break;
  1842. // ::= rM # %=
  1843. case OO_PercentEqual: Out << "rM"; break;
  1844. // ::= aN # &=
  1845. case OO_AmpEqual: Out << "aN"; break;
  1846. // ::= oR # |=
  1847. case OO_PipeEqual: Out << "oR"; break;
  1848. // ::= eO # ^=
  1849. case OO_CaretEqual: Out << "eO"; break;
  1850. // ::= ls # <<
  1851. case OO_LessLess: Out << "ls"; break;
  1852. // ::= rs # >>
  1853. case OO_GreaterGreater: Out << "rs"; break;
  1854. // ::= lS # <<=
  1855. case OO_LessLessEqual: Out << "lS"; break;
  1856. // ::= rS # >>=
  1857. case OO_GreaterGreaterEqual: Out << "rS"; break;
  1858. // ::= eq # ==
  1859. case OO_EqualEqual: Out << "eq"; break;
  1860. // ::= ne # !=
  1861. case OO_ExclaimEqual: Out << "ne"; break;
  1862. // ::= lt # <
  1863. case OO_Less: Out << "lt"; break;
  1864. // ::= gt # >
  1865. case OO_Greater: Out << "gt"; break;
  1866. // ::= le # <=
  1867. case OO_LessEqual: Out << "le"; break;
  1868. // ::= ge # >=
  1869. case OO_GreaterEqual: Out << "ge"; break;
  1870. // ::= nt # !
  1871. case OO_Exclaim: Out << "nt"; break;
  1872. // ::= aa # &&
  1873. case OO_AmpAmp: Out << "aa"; break;
  1874. // ::= oo # ||
  1875. case OO_PipePipe: Out << "oo"; break;
  1876. // ::= pp # ++
  1877. case OO_PlusPlus: Out << "pp"; break;
  1878. // ::= mm # --
  1879. case OO_MinusMinus: Out << "mm"; break;
  1880. // ::= cm # ,
  1881. case OO_Comma: Out << "cm"; break;
  1882. // ::= pm # ->*
  1883. case OO_ArrowStar: Out << "pm"; break;
  1884. // ::= pt # ->
  1885. case OO_Arrow: Out << "pt"; break;
  1886. // ::= cl # ()
  1887. case OO_Call: Out << "cl"; break;
  1888. // ::= ix # []
  1889. case OO_Subscript: Out << "ix"; break;
  1890. // ::= qu # ?
  1891. // The conditional operator can't be overloaded, but we still handle it when
  1892. // mangling expressions.
  1893. case OO_Conditional: Out << "qu"; break;
  1894. // Proposal on cxx-abi-dev, 2015-10-21.
  1895. // ::= aw # co_await
  1896. case OO_Coawait: Out << "aw"; break;
  1897. // Proposed in cxx-abi github issue 43.
  1898. // ::= ss # <=>
  1899. case OO_Spaceship: Out << "ss"; break;
  1900. case OO_None:
  1901. case NUM_OVERLOADED_OPERATORS:
  1902. llvm_unreachable("Not an overloaded operator");
  1903. }
  1904. }
  1905. void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) {
  1906. // Vendor qualifiers come first and if they are order-insensitive they must
  1907. // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.
  1908. // <type> ::= U <addrspace-expr>
  1909. if (DAST) {
  1910. Out << "U2ASI";
  1911. mangleExpression(DAST->getAddrSpaceExpr());
  1912. Out << "E";
  1913. }
  1914. // Address space qualifiers start with an ordinary letter.
  1915. if (Quals.hasAddressSpace()) {
  1916. // Address space extension:
  1917. //
  1918. // <type> ::= U <target-addrspace>
  1919. // <type> ::= U <OpenCL-addrspace>
  1920. // <type> ::= U <CUDA-addrspace>
  1921. SmallString<64> ASString;
  1922. LangAS AS = Quals.getAddressSpace();
  1923. if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
  1924. // <target-addrspace> ::= "AS" <address-space-number>
  1925. unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
  1926. if (TargetAS != 0)
  1927. ASString = "AS" + llvm::utostr(TargetAS);
  1928. } else {
  1929. switch (AS) {
  1930. default: llvm_unreachable("Not a language specific address space");
  1931. // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
  1932. // "private"| "generic" ]
  1933. case LangAS::opencl_global: ASString = "CLglobal"; break;
  1934. case LangAS::opencl_local: ASString = "CLlocal"; break;
  1935. case LangAS::opencl_constant: ASString = "CLconstant"; break;
  1936. case LangAS::opencl_private: ASString = "CLprivate"; break;
  1937. case LangAS::opencl_generic: ASString = "CLgeneric"; break;
  1938. // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
  1939. case LangAS::cuda_device: ASString = "CUdevice"; break;
  1940. case LangAS::cuda_constant: ASString = "CUconstant"; break;
  1941. case LangAS::cuda_shared: ASString = "CUshared"; break;
  1942. }
  1943. }
  1944. if (!ASString.empty())
  1945. mangleVendorQualifier(ASString);
  1946. }
  1947. // The ARC ownership qualifiers start with underscores.
  1948. // Objective-C ARC Extension:
  1949. //
  1950. // <type> ::= U "__strong"
  1951. // <type> ::= U "__weak"
  1952. // <type> ::= U "__autoreleasing"
  1953. //
  1954. // Note: we emit __weak first to preserve the order as
  1955. // required by the Itanium ABI.
  1956. if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak)
  1957. mangleVendorQualifier("__weak");
  1958. // __unaligned (from -fms-extensions)
  1959. if (Quals.hasUnaligned())
  1960. mangleVendorQualifier("__unaligned");
  1961. // Remaining ARC ownership qualifiers.
  1962. switch (Quals.getObjCLifetime()) {
  1963. case Qualifiers::OCL_None:
  1964. break;
  1965. case Qualifiers::OCL_Weak:
  1966. // Do nothing as we already handled this case above.
  1967. break;
  1968. case Qualifiers::OCL_Strong:
  1969. mangleVendorQualifier("__strong");
  1970. break;
  1971. case Qualifiers::OCL_Autoreleasing:
  1972. mangleVendorQualifier("__autoreleasing");
  1973. break;
  1974. case Qualifiers::OCL_ExplicitNone:
  1975. // The __unsafe_unretained qualifier is *not* mangled, so that
  1976. // __unsafe_unretained types in ARC produce the same manglings as the
  1977. // equivalent (but, naturally, unqualified) types in non-ARC, providing
  1978. // better ABI compatibility.
  1979. //
  1980. // It's safe to do this because unqualified 'id' won't show up
  1981. // in any type signatures that need to be mangled.
  1982. break;
  1983. }
  1984. // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
  1985. if (Quals.hasRestrict())
  1986. Out << 'r';
  1987. if (Quals.hasVolatile())
  1988. Out << 'V';
  1989. if (Quals.hasConst())
  1990. Out << 'K';
  1991. }
  1992. void CXXNameMangler::mangleVendorQualifier(StringRef name) {
  1993. Out << 'U' << name.size() << name;
  1994. }
  1995. void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
  1996. // <ref-qualifier> ::= R # lvalue reference
  1997. // ::= O # rvalue-reference
  1998. switch (RefQualifier) {
  1999. case RQ_None:
  2000. break;
  2001. case RQ_LValue:
  2002. Out << 'R';
  2003. break;
  2004. case RQ_RValue:
  2005. Out << 'O';
  2006. break;
  2007. }
  2008. }
  2009. void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
  2010. Context.mangleObjCMethodName(MD, Out);
  2011. }
  2012. static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty,
  2013. ASTContext &Ctx) {
  2014. if (Quals)
  2015. return true;
  2016. if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
  2017. return true;
  2018. if (Ty->isOpenCLSpecificType())
  2019. return true;
  2020. if (Ty->isBuiltinType())
  2021. return false;
  2022. // Through to Clang 6.0, we accidentally treated undeduced auto types as
  2023. // substitution candidates.
  2024. if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 &&
  2025. isa<AutoType>(Ty))
  2026. return false;
  2027. return true;
  2028. }
  2029. void CXXNameMangler::mangleType(QualType T) {
  2030. // If our type is instantiation-dependent but not dependent, we mangle
  2031. // it as it was written in the source, removing any top-level sugar.
  2032. // Otherwise, use the canonical type.
  2033. //
  2034. // FIXME: This is an approximation of the instantiation-dependent name
  2035. // mangling rules, since we should really be using the type as written and
  2036. // augmented via semantic analysis (i.e., with implicit conversions and
  2037. // default template arguments) for any instantiation-dependent type.
  2038. // Unfortunately, that requires several changes to our AST:
  2039. // - Instantiation-dependent TemplateSpecializationTypes will need to be
  2040. // uniqued, so that we can handle substitutions properly
  2041. // - Default template arguments will need to be represented in the
  2042. // TemplateSpecializationType, since they need to be mangled even though
  2043. // they aren't written.
  2044. // - Conversions on non-type template arguments need to be expressed, since
  2045. // they can affect the mangling of sizeof/alignof.
  2046. //
  2047. // FIXME: This is wrong when mapping to the canonical type for a dependent
  2048. // type discards instantiation-dependent portions of the type, such as for:
  2049. //
  2050. // template<typename T, int N> void f(T (&)[sizeof(N)]);
  2051. // template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
  2052. //
  2053. // It's also wrong in the opposite direction when instantiation-dependent,
  2054. // canonically-equivalent types differ in some irrelevant portion of inner
  2055. // type sugar. In such cases, we fail to form correct substitutions, eg:
  2056. //
  2057. // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
  2058. //
  2059. // We should instead canonicalize the non-instantiation-dependent parts,
  2060. // regardless of whether the type as a whole is dependent or instantiation
  2061. // dependent.
  2062. if (!T->isInstantiationDependentType() || T->isDependentType())
  2063. T = T.getCanonicalType();
  2064. else {
  2065. // Desugar any types that are purely sugar.
  2066. do {
  2067. // Don't desugar through template specialization types that aren't
  2068. // type aliases. We need to mangle the template arguments as written.
  2069. if (const TemplateSpecializationType *TST
  2070. = dyn_cast<TemplateSpecializationType>(T))
  2071. if (!TST->isTypeAlias())
  2072. break;
  2073. QualType Desugared
  2074. = T.getSingleStepDesugaredType(Context.getASTContext());
  2075. if (Desugared == T)
  2076. break;
  2077. T = Desugared;
  2078. } while (true);
  2079. }
  2080. SplitQualType split = T.split();
  2081. Qualifiers quals = split.Quals;
  2082. const Type *ty = split.Ty;
  2083. bool isSubstitutable =
  2084. isTypeSubstitutable(quals, ty, Context.getASTContext());
  2085. if (isSubstitutable && mangleSubstitution(T))
  2086. return;
  2087. // If we're mangling a qualified array type, push the qualifiers to
  2088. // the element type.
  2089. if (quals && isa<ArrayType>(T)) {
  2090. ty = Context.getASTContext().getAsArrayType(T);
  2091. quals = Qualifiers();
  2092. // Note that we don't update T: we want to add the
  2093. // substitution at the original type.
  2094. }
  2095. if (quals || ty->isDependentAddressSpaceType()) {
  2096. if (const DependentAddressSpaceType *DAST =
  2097. dyn_cast<DependentAddressSpaceType>(ty)) {
  2098. SplitQualType splitDAST = DAST->getPointeeType().split();
  2099. mangleQualifiers(splitDAST.Quals, DAST);
  2100. mangleType(QualType(splitDAST.Ty, 0));
  2101. } else {
  2102. mangleQualifiers(quals);
  2103. // Recurse: even if the qualified type isn't yet substitutable,
  2104. // the unqualified type might be.
  2105. mangleType(QualType(ty, 0));
  2106. }
  2107. } else {
  2108. switch (ty->getTypeClass()) {
  2109. #define ABSTRACT_TYPE(CLASS, PARENT)
  2110. #define NON_CANONICAL_TYPE(CLASS, PARENT) \
  2111. case Type::CLASS: \
  2112. llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
  2113. return;
  2114. #define TYPE(CLASS, PARENT) \
  2115. case Type::CLASS: \
  2116. mangleType(static_cast<const CLASS##Type*>(ty)); \
  2117. break;
  2118. #include "clang/AST/TypeNodes.def"
  2119. }
  2120. }
  2121. // Add the substitution.
  2122. if (isSubstitutable)
  2123. addSubstitution(T);
  2124. }
  2125. void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
  2126. if (!mangleStandardSubstitution(ND))
  2127. mangleName(ND);
  2128. }
  2129. void CXXNameMangler::mangleType(const BuiltinType *T) {
  2130. // <type> ::= <builtin-type>
  2131. // <builtin-type> ::= v # void
  2132. // ::= w # wchar_t
  2133. // ::= b # bool
  2134. // ::= c # char
  2135. // ::= a # signed char
  2136. // ::= h # unsigned char
  2137. // ::= s # short
  2138. // ::= t # unsigned short
  2139. // ::= i # int
  2140. // ::= j # unsigned int
  2141. // ::= l # long
  2142. // ::= m # unsigned long
  2143. // ::= x # long long, __int64
  2144. // ::= y # unsigned long long, __int64
  2145. // ::= n # __int128
  2146. // ::= o # unsigned __int128
  2147. // ::= f # float
  2148. // ::= d # double
  2149. // ::= e # long double, __float80
  2150. // ::= g # __float128
  2151. // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
  2152. // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
  2153. // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
  2154. // ::= Dh # IEEE 754r half-precision floating point (16 bits)
  2155. // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits);
  2156. // ::= Di # char32_t
  2157. // ::= Ds # char16_t
  2158. // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
  2159. // ::= u <source-name> # vendor extended type
  2160. std::string type_name;
  2161. switch (T->getKind()) {
  2162. case BuiltinType::Void:
  2163. Out << 'v';
  2164. break;
  2165. case BuiltinType::Bool:
  2166. Out << 'b';
  2167. break;
  2168. case BuiltinType::Char_U:
  2169. case BuiltinType::Char_S:
  2170. Out << 'c';
  2171. break;
  2172. case BuiltinType::UChar:
  2173. Out << 'h';
  2174. break;
  2175. case BuiltinType::UShort:
  2176. Out << 't';
  2177. break;
  2178. case BuiltinType::UInt:
  2179. Out << 'j';
  2180. break;
  2181. case BuiltinType::ULong:
  2182. Out << 'm';
  2183. break;
  2184. case BuiltinType::ULongLong:
  2185. Out << 'y';
  2186. break;
  2187. case BuiltinType::UInt128:
  2188. Out << 'o';
  2189. break;
  2190. case BuiltinType::SChar:
  2191. Out << 'a';
  2192. break;
  2193. case BuiltinType::WChar_S:
  2194. case BuiltinType::WChar_U:
  2195. Out << 'w';
  2196. break;
  2197. case BuiltinType::Char16:
  2198. Out << "Ds";
  2199. break;
  2200. case BuiltinType::Char32:
  2201. Out << "Di";
  2202. break;
  2203. case BuiltinType::Short:
  2204. Out << 's';
  2205. break;
  2206. case BuiltinType::Int:
  2207. Out << 'i';
  2208. break;
  2209. case BuiltinType::Long:
  2210. Out << 'l';
  2211. break;
  2212. case BuiltinType::LongLong:
  2213. Out << 'x';
  2214. break;
  2215. case BuiltinType::Int128:
  2216. Out << 'n';
  2217. break;
  2218. case BuiltinType::Float16:
  2219. Out << "DF16_";
  2220. break;
  2221. case BuiltinType::Half:
  2222. Out << "Dh";
  2223. break;
  2224. case BuiltinType::Float:
  2225. Out << 'f';
  2226. break;
  2227. case BuiltinType::Double:
  2228. Out << 'd';
  2229. break;
  2230. case BuiltinType::LongDouble:
  2231. Out << (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble()
  2232. ? 'g'
  2233. : 'e');
  2234. break;
  2235. case BuiltinType::Float128:
  2236. if (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble())
  2237. Out << "U10__float128"; // Match the GCC mangling
  2238. else
  2239. Out << 'g';
  2240. break;
  2241. case BuiltinType::NullPtr:
  2242. Out << "Dn";
  2243. break;
  2244. #define BUILTIN_TYPE(Id, SingletonId)
  2245. #define PLACEHOLDER_TYPE(Id, SingletonId) \
  2246. case BuiltinType::Id:
  2247. #include "clang/AST/BuiltinTypes.def"
  2248. case BuiltinType::Dependent:
  2249. if (!NullOut)
  2250. llvm_unreachable("mangling a placeholder type");
  2251. break;
  2252. case BuiltinType::ObjCId:
  2253. Out << "11objc_object";
  2254. break;
  2255. case BuiltinType::ObjCClass:
  2256. Out << "10objc_class";
  2257. break;
  2258. case BuiltinType::ObjCSel:
  2259. Out << "13objc_selector";
  2260. break;
  2261. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  2262. case BuiltinType::Id: \
  2263. type_name = "ocl_" #ImgType "_" #Suffix; \
  2264. Out << type_name.size() << type_name; \
  2265. break;
  2266. #include "clang/Basic/OpenCLImageTypes.def"
  2267. case BuiltinType::OCLSampler:
  2268. Out << "11ocl_sampler";
  2269. break;
  2270. case BuiltinType::OCLEvent:
  2271. Out << "9ocl_event";
  2272. break;
  2273. case BuiltinType::OCLClkEvent:
  2274. Out << "12ocl_clkevent";
  2275. break;
  2276. case BuiltinType::OCLQueue:
  2277. Out << "9ocl_queue";
  2278. break;
  2279. case BuiltinType::OCLReserveID:
  2280. Out << "13ocl_reserveid";
  2281. break;
  2282. }
  2283. }
  2284. StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
  2285. switch (CC) {
  2286. case CC_C:
  2287. return "";
  2288. case CC_X86StdCall:
  2289. case CC_X86FastCall:
  2290. case CC_X86ThisCall:
  2291. case CC_X86VectorCall:
  2292. case CC_X86Pascal:
  2293. case CC_Win64:
  2294. case CC_X86_64SysV:
  2295. case CC_X86RegCall:
  2296. case CC_AAPCS:
  2297. case CC_AAPCS_VFP:
  2298. case CC_IntelOclBicc:
  2299. case CC_SpirFunction:
  2300. case CC_OpenCLKernel:
  2301. case CC_PreserveMost:
  2302. case CC_PreserveAll:
  2303. // FIXME: we should be mangling all of the above.
  2304. return "";
  2305. case CC_Swift:
  2306. return "swiftcall";
  2307. }
  2308. llvm_unreachable("bad calling convention");
  2309. }
  2310. void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
  2311. // Fast path.
  2312. if (T->getExtInfo() == FunctionType::ExtInfo())
  2313. return;
  2314. // Vendor-specific qualifiers are emitted in reverse alphabetical order.
  2315. // This will get more complicated in the future if we mangle other
  2316. // things here; but for now, since we mangle ns_returns_retained as
  2317. // a qualifier on the result type, we can get away with this:
  2318. StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
  2319. if (!CCQualifier.empty())
  2320. mangleVendorQualifier(CCQualifier);
  2321. // FIXME: regparm
  2322. // FIXME: noreturn
  2323. }
  2324. void
  2325. CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
  2326. // Vendor-specific qualifiers are emitted in reverse alphabetical order.
  2327. // Note that these are *not* substitution candidates. Demanglers might
  2328. // have trouble with this if the parameter type is fully substituted.
  2329. switch (PI.getABI()) {
  2330. case ParameterABI::Ordinary:
  2331. break;
  2332. // All of these start with "swift", so they come before "ns_consumed".
  2333. case ParameterABI::SwiftContext:
  2334. case ParameterABI::SwiftErrorResult:
  2335. case ParameterABI::SwiftIndirectResult:
  2336. mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
  2337. break;
  2338. }
  2339. if (PI.isConsumed())
  2340. mangleVendorQualifier("ns_consumed");
  2341. if (PI.isNoEscape())
  2342. mangleVendorQualifier("noescape");
  2343. }
  2344. // <type> ::= <function-type>
  2345. // <function-type> ::= [<CV-qualifiers>] F [Y]
  2346. // <bare-function-type> [<ref-qualifier>] E
  2347. void CXXNameMangler::mangleType(const FunctionProtoType *T) {
  2348. mangleExtFunctionInfo(T);
  2349. // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
  2350. // e.g. "const" in "int (A::*)() const".
  2351. mangleQualifiers(Qualifiers::fromCVRUMask(T->getTypeQuals()));
  2352. // Mangle instantiation-dependent exception-specification, if present,
  2353. // per cxx-abi-dev proposal on 2016-10-11.
  2354. if (T->hasInstantiationDependentExceptionSpec()) {
  2355. if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
  2356. Out << "DO";
  2357. mangleExpression(T->getNoexceptExpr());
  2358. Out << "E";
  2359. } else {
  2360. assert(T->getExceptionSpecType() == EST_Dynamic);
  2361. Out << "Dw";
  2362. for (auto ExceptTy : T->exceptions())
  2363. mangleType(ExceptTy);
  2364. Out << "E";
  2365. }
  2366. } else if (T->isNothrow(getASTContext())) {
  2367. Out << "Do";
  2368. }
  2369. Out << 'F';
  2370. // FIXME: We don't have enough information in the AST to produce the 'Y'
  2371. // encoding for extern "C" function types.
  2372. mangleBareFunctionType(T, /*MangleReturnType=*/true);
  2373. // Mangle the ref-qualifier, if present.
  2374. mangleRefQualifier(T->getRefQualifier());
  2375. Out << 'E';
  2376. }
  2377. void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
  2378. // Function types without prototypes can arise when mangling a function type
  2379. // within an overloadable function in C. We mangle these as the absence of any
  2380. // parameter types (not even an empty parameter list).
  2381. Out << 'F';
  2382. FunctionTypeDepthState saved = FunctionTypeDepth.push();
  2383. FunctionTypeDepth.enterResultType();
  2384. mangleType(T->getReturnType());
  2385. FunctionTypeDepth.leaveResultType();
  2386. FunctionTypeDepth.pop(saved);
  2387. Out << 'E';
  2388. }
  2389. void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
  2390. bool MangleReturnType,
  2391. const FunctionDecl *FD) {
  2392. // Record that we're in a function type. See mangleFunctionParam
  2393. // for details on what we're trying to achieve here.
  2394. FunctionTypeDepthState saved = FunctionTypeDepth.push();
  2395. // <bare-function-type> ::= <signature type>+
  2396. if (MangleReturnType) {
  2397. FunctionTypeDepth.enterResultType();
  2398. // Mangle ns_returns_retained as an order-sensitive qualifier here.
  2399. if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
  2400. mangleVendorQualifier("ns_returns_retained");
  2401. // Mangle the return type without any direct ARC ownership qualifiers.
  2402. QualType ReturnTy = Proto->getReturnType();
  2403. if (ReturnTy.getObjCLifetime()) {
  2404. auto SplitReturnTy = ReturnTy.split();
  2405. SplitReturnTy.Quals.removeObjCLifetime();
  2406. ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
  2407. }
  2408. mangleType(ReturnTy);
  2409. FunctionTypeDepth.leaveResultType();
  2410. }
  2411. if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
  2412. // <builtin-type> ::= v # void
  2413. Out << 'v';
  2414. FunctionTypeDepth.pop(saved);
  2415. return;
  2416. }
  2417. assert(!FD || FD->getNumParams() == Proto->getNumParams());
  2418. for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
  2419. // Mangle extended parameter info as order-sensitive qualifiers here.
  2420. if (Proto->hasExtParameterInfos() && FD == nullptr) {
  2421. mangleExtParameterInfo(Proto->getExtParameterInfo(I));
  2422. }
  2423. // Mangle the type.
  2424. QualType ParamTy = Proto->getParamType(I);
  2425. mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
  2426. if (FD) {
  2427. if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
  2428. // Attr can only take 1 character, so we can hardcode the length below.
  2429. assert(Attr->getType() <= 9 && Attr->getType() >= 0);
  2430. Out << "U17pass_object_size" << Attr->getType();
  2431. }
  2432. }
  2433. }
  2434. FunctionTypeDepth.pop(saved);
  2435. // <builtin-type> ::= z # ellipsis
  2436. if (Proto->isVariadic())
  2437. Out << 'z';
  2438. }
  2439. // <type> ::= <class-enum-type>
  2440. // <class-enum-type> ::= <name>
  2441. void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
  2442. mangleName(T->getDecl());
  2443. }
  2444. // <type> ::= <class-enum-type>
  2445. // <class-enum-type> ::= <name>
  2446. void CXXNameMangler::mangleType(const EnumType *T) {
  2447. mangleType(static_cast<const TagType*>(T));
  2448. }
  2449. void CXXNameMangler::mangleType(const RecordType *T) {
  2450. mangleType(static_cast<const TagType*>(T));
  2451. }
  2452. void CXXNameMangler::mangleType(const TagType *T) {
  2453. mangleName(T->getDecl());
  2454. }
  2455. // <type> ::= <array-type>
  2456. // <array-type> ::= A <positive dimension number> _ <element type>
  2457. // ::= A [<dimension expression>] _ <element type>
  2458. void CXXNameMangler::mangleType(const ConstantArrayType *T) {
  2459. Out << 'A' << T->getSize() << '_';
  2460. mangleType(T->getElementType());
  2461. }
  2462. void CXXNameMangler::mangleType(const VariableArrayType *T) {
  2463. Out << 'A';
  2464. // decayed vla types (size 0) will just be skipped.
  2465. if (T->getSizeExpr())
  2466. mangleExpression(T->getSizeExpr());
  2467. Out << '_';
  2468. mangleType(T->getElementType());
  2469. }
  2470. void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
  2471. Out << 'A';
  2472. mangleExpression(T->getSizeExpr());
  2473. Out << '_';
  2474. mangleType(T->getElementType());
  2475. }
  2476. void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
  2477. Out << "A_";
  2478. mangleType(T->getElementType());
  2479. }
  2480. // <type> ::= <pointer-to-member-type>
  2481. // <pointer-to-member-type> ::= M <class type> <member type>
  2482. void CXXNameMangler::mangleType(const MemberPointerType *T) {
  2483. Out << 'M';
  2484. mangleType(QualType(T->getClass(), 0));
  2485. QualType PointeeType = T->getPointeeType();
  2486. if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
  2487. mangleType(FPT);
  2488. // Itanium C++ ABI 5.1.8:
  2489. //
  2490. // The type of a non-static member function is considered to be different,
  2491. // for the purposes of substitution, from the type of a namespace-scope or
  2492. // static member function whose type appears similar. The types of two
  2493. // non-static member functions are considered to be different, for the
  2494. // purposes of substitution, if the functions are members of different
  2495. // classes. In other words, for the purposes of substitution, the class of
  2496. // which the function is a member is considered part of the type of
  2497. // function.
  2498. // Given that we already substitute member function pointers as a
  2499. // whole, the net effect of this rule is just to unconditionally
  2500. // suppress substitution on the function type in a member pointer.
  2501. // We increment the SeqID here to emulate adding an entry to the
  2502. // substitution table.
  2503. ++SeqID;
  2504. } else
  2505. mangleType(PointeeType);
  2506. }
  2507. // <type> ::= <template-param>
  2508. void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
  2509. mangleTemplateParameter(T->getIndex());
  2510. }
  2511. // <type> ::= <template-param>
  2512. void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
  2513. // FIXME: not clear how to mangle this!
  2514. // template <class T...> class A {
  2515. // template <class U...> void foo(T(*)(U) x...);
  2516. // };
  2517. Out << "_SUBSTPACK_";
  2518. }
  2519. // <type> ::= P <type> # pointer-to
  2520. void CXXNameMangler::mangleType(const PointerType *T) {
  2521. Out << 'P';
  2522. mangleType(T->getPointeeType());
  2523. }
  2524. void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
  2525. Out << 'P';
  2526. mangleType(T->getPointeeType());
  2527. }
  2528. // <type> ::= R <type> # reference-to
  2529. void CXXNameMangler::mangleType(const LValueReferenceType *T) {
  2530. Out << 'R';
  2531. mangleType(T->getPointeeType());
  2532. }
  2533. // <type> ::= O <type> # rvalue reference-to (C++0x)
  2534. void CXXNameMangler::mangleType(const RValueReferenceType *T) {
  2535. Out << 'O';
  2536. mangleType(T->getPointeeType());
  2537. }
  2538. // <type> ::= C <type> # complex pair (C 2000)
  2539. void CXXNameMangler::mangleType(const ComplexType *T) {
  2540. Out << 'C';
  2541. mangleType(T->getElementType());
  2542. }
  2543. // ARM's ABI for Neon vector types specifies that they should be mangled as
  2544. // if they are structs (to match ARM's initial implementation). The
  2545. // vector type must be one of the special types predefined by ARM.
  2546. void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
  2547. QualType EltType = T->getElementType();
  2548. assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
  2549. const char *EltName = nullptr;
  2550. if (T->getVectorKind() == VectorType::NeonPolyVector) {
  2551. switch (cast<BuiltinType>(EltType)->getKind()) {
  2552. case BuiltinType::SChar:
  2553. case BuiltinType::UChar:
  2554. EltName = "poly8_t";
  2555. break;
  2556. case BuiltinType::Short:
  2557. case BuiltinType::UShort:
  2558. EltName = "poly16_t";
  2559. break;
  2560. case BuiltinType::ULongLong:
  2561. EltName = "poly64_t";
  2562. break;
  2563. default: llvm_unreachable("unexpected Neon polynomial vector element type");
  2564. }
  2565. } else {
  2566. switch (cast<BuiltinType>(EltType)->getKind()) {
  2567. case BuiltinType::SChar: EltName = "int8_t"; break;
  2568. case BuiltinType::UChar: EltName = "uint8_t"; break;
  2569. case BuiltinType::Short: EltName = "int16_t"; break;
  2570. case BuiltinType::UShort: EltName = "uint16_t"; break;
  2571. case BuiltinType::Int: EltName = "int32_t"; break;
  2572. case BuiltinType::UInt: EltName = "uint32_t"; break;
  2573. case BuiltinType::LongLong: EltName = "int64_t"; break;
  2574. case BuiltinType::ULongLong: EltName = "uint64_t"; break;
  2575. case BuiltinType::Double: EltName = "float64_t"; break;
  2576. case BuiltinType::Float: EltName = "float32_t"; break;
  2577. case BuiltinType::Half: EltName = "float16_t";break;
  2578. default:
  2579. llvm_unreachable("unexpected Neon vector element type");
  2580. }
  2581. }
  2582. const char *BaseName = nullptr;
  2583. unsigned BitSize = (T->getNumElements() *
  2584. getASTContext().getTypeSize(EltType));
  2585. if (BitSize == 64)
  2586. BaseName = "__simd64_";
  2587. else {
  2588. assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
  2589. BaseName = "__simd128_";
  2590. }
  2591. Out << strlen(BaseName) + strlen(EltName);
  2592. Out << BaseName << EltName;
  2593. }
  2594. static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
  2595. switch (EltType->getKind()) {
  2596. case BuiltinType::SChar:
  2597. return "Int8";
  2598. case BuiltinType::Short:
  2599. return "Int16";
  2600. case BuiltinType::Int:
  2601. return "Int32";
  2602. case BuiltinType::Long:
  2603. case BuiltinType::LongLong:
  2604. return "Int64";
  2605. case BuiltinType::UChar:
  2606. return "Uint8";
  2607. case BuiltinType::UShort:
  2608. return "Uint16";
  2609. case BuiltinType::UInt:
  2610. return "Uint32";
  2611. case BuiltinType::ULong:
  2612. case BuiltinType::ULongLong:
  2613. return "Uint64";
  2614. case BuiltinType::Half:
  2615. return "Float16";
  2616. case BuiltinType::Float:
  2617. return "Float32";
  2618. case BuiltinType::Double:
  2619. return "Float64";
  2620. default:
  2621. llvm_unreachable("Unexpected vector element base type");
  2622. }
  2623. }
  2624. // AArch64's ABI for Neon vector types specifies that they should be mangled as
  2625. // the equivalent internal name. The vector type must be one of the special
  2626. // types predefined by ARM.
  2627. void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
  2628. QualType EltType = T->getElementType();
  2629. assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
  2630. unsigned BitSize =
  2631. (T->getNumElements() * getASTContext().getTypeSize(EltType));
  2632. (void)BitSize; // Silence warning.
  2633. assert((BitSize == 64 || BitSize == 128) &&
  2634. "Neon vector type not 64 or 128 bits");
  2635. StringRef EltName;
  2636. if (T->getVectorKind() == VectorType::NeonPolyVector) {
  2637. switch (cast<BuiltinType>(EltType)->getKind()) {
  2638. case BuiltinType::UChar:
  2639. EltName = "Poly8";
  2640. break;
  2641. case BuiltinType::UShort:
  2642. EltName = "Poly16";
  2643. break;
  2644. case BuiltinType::ULong:
  2645. case BuiltinType::ULongLong:
  2646. EltName = "Poly64";
  2647. break;
  2648. default:
  2649. llvm_unreachable("unexpected Neon polynomial vector element type");
  2650. }
  2651. } else
  2652. EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
  2653. std::string TypeName =
  2654. ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
  2655. Out << TypeName.length() << TypeName;
  2656. }
  2657. // GNU extension: vector types
  2658. // <type> ::= <vector-type>
  2659. // <vector-type> ::= Dv <positive dimension number> _
  2660. // <extended element type>
  2661. // ::= Dv [<dimension expression>] _ <element type>
  2662. // <extended element type> ::= <element type>
  2663. // ::= p # AltiVec vector pixel
  2664. // ::= b # Altivec vector bool
  2665. void CXXNameMangler::mangleType(const VectorType *T) {
  2666. if ((T->getVectorKind() == VectorType::NeonVector ||
  2667. T->getVectorKind() == VectorType::NeonPolyVector)) {
  2668. llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
  2669. llvm::Triple::ArchType Arch =
  2670. getASTContext().getTargetInfo().getTriple().getArch();
  2671. if ((Arch == llvm::Triple::aarch64 ||
  2672. Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
  2673. mangleAArch64NeonVectorType(T);
  2674. else
  2675. mangleNeonVectorType(T);
  2676. return;
  2677. }
  2678. Out << "Dv" << T->getNumElements() << '_';
  2679. if (T->getVectorKind() == VectorType::AltiVecPixel)
  2680. Out << 'p';
  2681. else if (T->getVectorKind() == VectorType::AltiVecBool)
  2682. Out << 'b';
  2683. else
  2684. mangleType(T->getElementType());
  2685. }
  2686. void CXXNameMangler::mangleType(const ExtVectorType *T) {
  2687. mangleType(static_cast<const VectorType*>(T));
  2688. }
  2689. void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
  2690. Out << "Dv";
  2691. mangleExpression(T->getSizeExpr());
  2692. Out << '_';
  2693. mangleType(T->getElementType());
  2694. }
  2695. void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) {
  2696. SplitQualType split = T->getPointeeType().split();
  2697. mangleQualifiers(split.Quals, T);
  2698. mangleType(QualType(split.Ty, 0));
  2699. }
  2700. void CXXNameMangler::mangleType(const PackExpansionType *T) {
  2701. // <type> ::= Dp <type> # pack expansion (C++0x)
  2702. Out << "Dp";
  2703. mangleType(T->getPattern());
  2704. }
  2705. void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
  2706. mangleSourceName(T->getDecl()->getIdentifier());
  2707. }
  2708. void CXXNameMangler::mangleType(const ObjCObjectType *T) {
  2709. // Treat __kindof as a vendor extended type qualifier.
  2710. if (T->isKindOfType())
  2711. Out << "U8__kindof";
  2712. if (!T->qual_empty()) {
  2713. // Mangle protocol qualifiers.
  2714. SmallString<64> QualStr;
  2715. llvm::raw_svector_ostream QualOS(QualStr);
  2716. QualOS << "objcproto";
  2717. for (const auto *I : T->quals()) {
  2718. StringRef name = I->getName();
  2719. QualOS << name.size() << name;
  2720. }
  2721. Out << 'U' << QualStr.size() << QualStr;
  2722. }
  2723. mangleType(T->getBaseType());
  2724. if (T->isSpecialized()) {
  2725. // Mangle type arguments as I <type>+ E
  2726. Out << 'I';
  2727. for (auto typeArg : T->getTypeArgs())
  2728. mangleType(typeArg);
  2729. Out << 'E';
  2730. }
  2731. }
  2732. void CXXNameMangler::mangleType(const BlockPointerType *T) {
  2733. Out << "U13block_pointer";
  2734. mangleType(T->getPointeeType());
  2735. }
  2736. void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
  2737. // Mangle injected class name types as if the user had written the
  2738. // specialization out fully. It may not actually be possible to see
  2739. // this mangling, though.
  2740. mangleType(T->getInjectedSpecializationType());
  2741. }
  2742. void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
  2743. if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
  2744. mangleTemplateName(TD, T->getArgs(), T->getNumArgs());
  2745. } else {
  2746. if (mangleSubstitution(QualType(T, 0)))
  2747. return;
  2748. mangleTemplatePrefix(T->getTemplateName());
  2749. // FIXME: GCC does not appear to mangle the template arguments when
  2750. // the template in question is a dependent template name. Should we
  2751. // emulate that badness?
  2752. mangleTemplateArgs(T->getArgs(), T->getNumArgs());
  2753. addSubstitution(QualType(T, 0));
  2754. }
  2755. }
  2756. void CXXNameMangler::mangleType(const DependentNameType *T) {
  2757. // Proposal by cxx-abi-dev, 2014-03-26
  2758. // <class-enum-type> ::= <name> # non-dependent or dependent type name or
  2759. // # dependent elaborated type specifier using
  2760. // # 'typename'
  2761. // ::= Ts <name> # dependent elaborated type specifier using
  2762. // # 'struct' or 'class'
  2763. // ::= Tu <name> # dependent elaborated type specifier using
  2764. // # 'union'
  2765. // ::= Te <name> # dependent elaborated type specifier using
  2766. // # 'enum'
  2767. switch (T->getKeyword()) {
  2768. case ETK_None:
  2769. case ETK_Typename:
  2770. break;
  2771. case ETK_Struct:
  2772. case ETK_Class:
  2773. case ETK_Interface:
  2774. Out << "Ts";
  2775. break;
  2776. case ETK_Union:
  2777. Out << "Tu";
  2778. break;
  2779. case ETK_Enum:
  2780. Out << "Te";
  2781. break;
  2782. }
  2783. // Typename types are always nested
  2784. Out << 'N';
  2785. manglePrefix(T->getQualifier());
  2786. mangleSourceName(T->getIdentifier());
  2787. Out << 'E';
  2788. }
  2789. void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
  2790. // Dependently-scoped template types are nested if they have a prefix.
  2791. Out << 'N';
  2792. // TODO: avoid making this TemplateName.
  2793. TemplateName Prefix =
  2794. getASTContext().getDependentTemplateName(T->getQualifier(),
  2795. T->getIdentifier());
  2796. mangleTemplatePrefix(Prefix);
  2797. // FIXME: GCC does not appear to mangle the template arguments when
  2798. // the template in question is a dependent template name. Should we
  2799. // emulate that badness?
  2800. mangleTemplateArgs(T->getArgs(), T->getNumArgs());
  2801. Out << 'E';
  2802. }
  2803. void CXXNameMangler::mangleType(const TypeOfType *T) {
  2804. // FIXME: this is pretty unsatisfactory, but there isn't an obvious
  2805. // "extension with parameters" mangling.
  2806. Out << "u6typeof";
  2807. }
  2808. void CXXNameMangler::mangleType(const TypeOfExprType *T) {
  2809. // FIXME: this is pretty unsatisfactory, but there isn't an obvious
  2810. // "extension with parameters" mangling.
  2811. Out << "u6typeof";
  2812. }
  2813. void CXXNameMangler::mangleType(const DecltypeType *T) {
  2814. Expr *E = T->getUnderlyingExpr();
  2815. // type ::= Dt <expression> E # decltype of an id-expression
  2816. // # or class member access
  2817. // ::= DT <expression> E # decltype of an expression
  2818. // This purports to be an exhaustive list of id-expressions and
  2819. // class member accesses. Note that we do not ignore parentheses;
  2820. // parentheses change the semantics of decltype for these
  2821. // expressions (and cause the mangler to use the other form).
  2822. if (isa<DeclRefExpr>(E) ||
  2823. isa<MemberExpr>(E) ||
  2824. isa<UnresolvedLookupExpr>(E) ||
  2825. isa<DependentScopeDeclRefExpr>(E) ||
  2826. isa<CXXDependentScopeMemberExpr>(E) ||
  2827. isa<UnresolvedMemberExpr>(E))
  2828. Out << "Dt";
  2829. else
  2830. Out << "DT";
  2831. mangleExpression(E);
  2832. Out << 'E';
  2833. }
  2834. void CXXNameMangler::mangleType(const UnaryTransformType *T) {
  2835. // If this is dependent, we need to record that. If not, we simply
  2836. // mangle it as the underlying type since they are equivalent.
  2837. if (T->isDependentType()) {
  2838. Out << 'U';
  2839. switch (T->getUTTKind()) {
  2840. case UnaryTransformType::EnumUnderlyingType:
  2841. Out << "3eut";
  2842. break;
  2843. }
  2844. }
  2845. mangleType(T->getBaseType());
  2846. }
  2847. void CXXNameMangler::mangleType(const AutoType *T) {
  2848. assert(T->getDeducedType().isNull() &&
  2849. "Deduced AutoType shouldn't be handled here!");
  2850. assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
  2851. "shouldn't need to mangle __auto_type!");
  2852. // <builtin-type> ::= Da # auto
  2853. // ::= Dc # decltype(auto)
  2854. Out << (T->isDecltypeAuto() ? "Dc" : "Da");
  2855. }
  2856. void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {
  2857. // FIXME: This is not the right mangling. We also need to include a scope
  2858. // here in some cases.
  2859. QualType D = T->getDeducedType();
  2860. if (D.isNull())
  2861. mangleUnscopedTemplateName(T->getTemplateName(), nullptr);
  2862. else
  2863. mangleType(D);
  2864. }
  2865. void CXXNameMangler::mangleType(const AtomicType *T) {
  2866. // <type> ::= U <source-name> <type> # vendor extended type qualifier
  2867. // (Until there's a standardized mangling...)
  2868. Out << "U7_Atomic";
  2869. mangleType(T->getValueType());
  2870. }
  2871. void CXXNameMangler::mangleType(const PipeType *T) {
  2872. // Pipe type mangling rules are described in SPIR 2.0 specification
  2873. // A.1 Data types and A.3 Summary of changes
  2874. // <type> ::= 8ocl_pipe
  2875. Out << "8ocl_pipe";
  2876. }
  2877. void CXXNameMangler::mangleIntegerLiteral(QualType T,
  2878. const llvm::APSInt &Value) {
  2879. // <expr-primary> ::= L <type> <value number> E # integer literal
  2880. Out << 'L';
  2881. mangleType(T);
  2882. if (T->isBooleanType()) {
  2883. // Boolean values are encoded as 0/1.
  2884. Out << (Value.getBoolValue() ? '1' : '0');
  2885. } else {
  2886. mangleNumber(Value);
  2887. }
  2888. Out << 'E';
  2889. }
  2890. void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
  2891. // Ignore member expressions involving anonymous unions.
  2892. while (const auto *RT = Base->getType()->getAs<RecordType>()) {
  2893. if (!RT->getDecl()->isAnonymousStructOrUnion())
  2894. break;
  2895. const auto *ME = dyn_cast<MemberExpr>(Base);
  2896. if (!ME)
  2897. break;
  2898. Base = ME->getBase();
  2899. IsArrow = ME->isArrow();
  2900. }
  2901. if (Base->isImplicitCXXThis()) {
  2902. // Note: GCC mangles member expressions to the implicit 'this' as
  2903. // *this., whereas we represent them as this->. The Itanium C++ ABI
  2904. // does not specify anything here, so we follow GCC.
  2905. Out << "dtdefpT";
  2906. } else {
  2907. Out << (IsArrow ? "pt" : "dt");
  2908. mangleExpression(Base);
  2909. }
  2910. }
  2911. /// Mangles a member expression.
  2912. void CXXNameMangler::mangleMemberExpr(const Expr *base,
  2913. bool isArrow,
  2914. NestedNameSpecifier *qualifier,
  2915. NamedDecl *firstQualifierLookup,
  2916. DeclarationName member,
  2917. const TemplateArgumentLoc *TemplateArgs,
  2918. unsigned NumTemplateArgs,
  2919. unsigned arity) {
  2920. // <expression> ::= dt <expression> <unresolved-name>
  2921. // ::= pt <expression> <unresolved-name>
  2922. if (base)
  2923. mangleMemberExprBase(base, isArrow);
  2924. mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);
  2925. }
  2926. /// Look at the callee of the given call expression and determine if
  2927. /// it's a parenthesized id-expression which would have triggered ADL
  2928. /// otherwise.
  2929. static bool isParenthesizedADLCallee(const CallExpr *call) {
  2930. const Expr *callee = call->getCallee();
  2931. const Expr *fn = callee->IgnoreParens();
  2932. // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
  2933. // too, but for those to appear in the callee, it would have to be
  2934. // parenthesized.
  2935. if (callee == fn) return false;
  2936. // Must be an unresolved lookup.
  2937. const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
  2938. if (!lookup) return false;
  2939. assert(!lookup->requiresADL());
  2940. // Must be an unqualified lookup.
  2941. if (lookup->getQualifier()) return false;
  2942. // Must not have found a class member. Note that if one is a class
  2943. // member, they're all class members.
  2944. if (lookup->getNumDecls() > 0 &&
  2945. (*lookup->decls_begin())->isCXXClassMember())
  2946. return false;
  2947. // Otherwise, ADL would have been triggered.
  2948. return true;
  2949. }
  2950. void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
  2951. const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
  2952. Out << CastEncoding;
  2953. mangleType(ECE->getType());
  2954. mangleExpression(ECE->getSubExpr());
  2955. }
  2956. void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
  2957. if (auto *Syntactic = InitList->getSyntacticForm())
  2958. InitList = Syntactic;
  2959. for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
  2960. mangleExpression(InitList->getInit(i));
  2961. }
  2962. void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
  2963. // <expression> ::= <unary operator-name> <expression>
  2964. // ::= <binary operator-name> <expression> <expression>
  2965. // ::= <trinary operator-name> <expression> <expression> <expression>
  2966. // ::= cv <type> expression # conversion with one argument
  2967. // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
  2968. // ::= dc <type> <expression> # dynamic_cast<type> (expression)
  2969. // ::= sc <type> <expression> # static_cast<type> (expression)
  2970. // ::= cc <type> <expression> # const_cast<type> (expression)
  2971. // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
  2972. // ::= st <type> # sizeof (a type)
  2973. // ::= at <type> # alignof (a type)
  2974. // ::= <template-param>
  2975. // ::= <function-param>
  2976. // ::= sr <type> <unqualified-name> # dependent name
  2977. // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
  2978. // ::= ds <expression> <expression> # expr.*expr
  2979. // ::= sZ <template-param> # size of a parameter pack
  2980. // ::= sZ <function-param> # size of a function parameter pack
  2981. // ::= <expr-primary>
  2982. // <expr-primary> ::= L <type> <value number> E # integer literal
  2983. // ::= L <type <value float> E # floating literal
  2984. // ::= L <mangled-name> E # external name
  2985. // ::= fpT # 'this' expression
  2986. QualType ImplicitlyConvertedToType;
  2987. recurse:
  2988. switch (E->getStmtClass()) {
  2989. case Expr::NoStmtClass:
  2990. #define ABSTRACT_STMT(Type)
  2991. #define EXPR(Type, Base)
  2992. #define STMT(Type, Base) \
  2993. case Expr::Type##Class:
  2994. #include "clang/AST/StmtNodes.inc"
  2995. // fallthrough
  2996. // These all can only appear in local or variable-initialization
  2997. // contexts and so should never appear in a mangling.
  2998. case Expr::AddrLabelExprClass:
  2999. case Expr::DesignatedInitUpdateExprClass:
  3000. case Expr::ImplicitValueInitExprClass:
  3001. case Expr::ArrayInitLoopExprClass:
  3002. case Expr::ArrayInitIndexExprClass:
  3003. case Expr::NoInitExprClass:
  3004. case Expr::ParenListExprClass:
  3005. case Expr::LambdaExprClass:
  3006. case Expr::MSPropertyRefExprClass:
  3007. case Expr::MSPropertySubscriptExprClass:
  3008. case Expr::TypoExprClass: // This should no longer exist in the AST by now.
  3009. case Expr::OMPArraySectionExprClass:
  3010. case Expr::CXXInheritedCtorInitExprClass:
  3011. llvm_unreachable("unexpected statement kind");
  3012. // FIXME: invent manglings for all these.
  3013. case Expr::BlockExprClass:
  3014. case Expr::ChooseExprClass:
  3015. case Expr::CompoundLiteralExprClass:
  3016. case Expr::ExtVectorElementExprClass:
  3017. case Expr::GenericSelectionExprClass:
  3018. case Expr::ObjCEncodeExprClass:
  3019. case Expr::ObjCIsaExprClass:
  3020. case Expr::ObjCIvarRefExprClass:
  3021. case Expr::ObjCMessageExprClass:
  3022. case Expr::ObjCPropertyRefExprClass:
  3023. case Expr::ObjCProtocolExprClass:
  3024. case Expr::ObjCSelectorExprClass:
  3025. case Expr::ObjCStringLiteralClass:
  3026. case Expr::ObjCBoxedExprClass:
  3027. case Expr::ObjCArrayLiteralClass:
  3028. case Expr::ObjCDictionaryLiteralClass:
  3029. case Expr::ObjCSubscriptRefExprClass:
  3030. case Expr::ObjCIndirectCopyRestoreExprClass:
  3031. case Expr::ObjCAvailabilityCheckExprClass:
  3032. case Expr::OffsetOfExprClass:
  3033. case Expr::PredefinedExprClass:
  3034. case Expr::ShuffleVectorExprClass:
  3035. case Expr::ConvertVectorExprClass:
  3036. case Expr::StmtExprClass:
  3037. case Expr::TypeTraitExprClass:
  3038. case Expr::ArrayTypeTraitExprClass:
  3039. case Expr::ExpressionTraitExprClass:
  3040. case Expr::VAArgExprClass:
  3041. case Expr::CUDAKernelCallExprClass:
  3042. case Expr::AsTypeExprClass:
  3043. case Expr::PseudoObjectExprClass:
  3044. case Expr::AtomicExprClass:
  3045. {
  3046. if (!NullOut) {
  3047. // As bad as this diagnostic is, it's better than crashing.
  3048. DiagnosticsEngine &Diags = Context.getDiags();
  3049. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  3050. "cannot yet mangle expression type %0");
  3051. Diags.Report(E->getExprLoc(), DiagID)
  3052. << E->getStmtClassName() << E->getSourceRange();
  3053. }
  3054. break;
  3055. }
  3056. case Expr::CXXUuidofExprClass: {
  3057. const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
  3058. if (UE->isTypeOperand()) {
  3059. QualType UuidT = UE->getTypeOperand(Context.getASTContext());
  3060. Out << "u8__uuidoft";
  3061. mangleType(UuidT);
  3062. } else {
  3063. Expr *UuidExp = UE->getExprOperand();
  3064. Out << "u8__uuidofz";
  3065. mangleExpression(UuidExp, Arity);
  3066. }
  3067. break;
  3068. }
  3069. // Even gcc-4.5 doesn't mangle this.
  3070. case Expr::BinaryConditionalOperatorClass: {
  3071. DiagnosticsEngine &Diags = Context.getDiags();
  3072. unsigned DiagID =
  3073. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  3074. "?: operator with omitted middle operand cannot be mangled");
  3075. Diags.Report(E->getExprLoc(), DiagID)
  3076. << E->getStmtClassName() << E->getSourceRange();
  3077. break;
  3078. }
  3079. // These are used for internal purposes and cannot be meaningfully mangled.
  3080. case Expr::OpaqueValueExprClass:
  3081. llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
  3082. case Expr::InitListExprClass: {
  3083. Out << "il";
  3084. mangleInitListElements(cast<InitListExpr>(E));
  3085. Out << "E";
  3086. break;
  3087. }
  3088. case Expr::DesignatedInitExprClass: {
  3089. auto *DIE = cast<DesignatedInitExpr>(E);
  3090. for (const auto &Designator : DIE->designators()) {
  3091. if (Designator.isFieldDesignator()) {
  3092. Out << "di";
  3093. mangleSourceName(Designator.getFieldName());
  3094. } else if (Designator.isArrayDesignator()) {
  3095. Out << "dx";
  3096. mangleExpression(DIE->getArrayIndex(Designator));
  3097. } else {
  3098. assert(Designator.isArrayRangeDesignator() &&
  3099. "unknown designator kind");
  3100. Out << "dX";
  3101. mangleExpression(DIE->getArrayRangeStart(Designator));
  3102. mangleExpression(DIE->getArrayRangeEnd(Designator));
  3103. }
  3104. }
  3105. mangleExpression(DIE->getInit());
  3106. break;
  3107. }
  3108. case Expr::CXXDefaultArgExprClass:
  3109. mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
  3110. break;
  3111. case Expr::CXXDefaultInitExprClass:
  3112. mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
  3113. break;
  3114. case Expr::CXXStdInitializerListExprClass:
  3115. mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
  3116. break;
  3117. case Expr::SubstNonTypeTemplateParmExprClass:
  3118. mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
  3119. Arity);
  3120. break;
  3121. case Expr::UserDefinedLiteralClass:
  3122. // We follow g++'s approach of mangling a UDL as a call to the literal
  3123. // operator.
  3124. case Expr::CXXMemberCallExprClass: // fallthrough
  3125. case Expr::CallExprClass: {
  3126. const CallExpr *CE = cast<CallExpr>(E);
  3127. // <expression> ::= cp <simple-id> <expression>* E
  3128. // We use this mangling only when the call would use ADL except
  3129. // for being parenthesized. Per discussion with David
  3130. // Vandervoorde, 2011.04.25.
  3131. if (isParenthesizedADLCallee(CE)) {
  3132. Out << "cp";
  3133. // The callee here is a parenthesized UnresolvedLookupExpr with
  3134. // no qualifier and should always get mangled as a <simple-id>
  3135. // anyway.
  3136. // <expression> ::= cl <expression>* E
  3137. } else {
  3138. Out << "cl";
  3139. }
  3140. unsigned CallArity = CE->getNumArgs();
  3141. for (const Expr *Arg : CE->arguments())
  3142. if (isa<PackExpansionExpr>(Arg))
  3143. CallArity = UnknownArity;
  3144. mangleExpression(CE->getCallee(), CallArity);
  3145. for (const Expr *Arg : CE->arguments())
  3146. mangleExpression(Arg);
  3147. Out << 'E';
  3148. break;
  3149. }
  3150. case Expr::CXXNewExprClass: {
  3151. const CXXNewExpr *New = cast<CXXNewExpr>(E);
  3152. if (New->isGlobalNew()) Out << "gs";
  3153. Out << (New->isArray() ? "na" : "nw");
  3154. for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
  3155. E = New->placement_arg_end(); I != E; ++I)
  3156. mangleExpression(*I);
  3157. Out << '_';
  3158. mangleType(New->getAllocatedType());
  3159. if (New->hasInitializer()) {
  3160. if (New->getInitializationStyle() == CXXNewExpr::ListInit)
  3161. Out << "il";
  3162. else
  3163. Out << "pi";
  3164. const Expr *Init = New->getInitializer();
  3165. if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
  3166. // Directly inline the initializers.
  3167. for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
  3168. E = CCE->arg_end();
  3169. I != E; ++I)
  3170. mangleExpression(*I);
  3171. } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
  3172. for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
  3173. mangleExpression(PLE->getExpr(i));
  3174. } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
  3175. isa<InitListExpr>(Init)) {
  3176. // Only take InitListExprs apart for list-initialization.
  3177. mangleInitListElements(cast<InitListExpr>(Init));
  3178. } else
  3179. mangleExpression(Init);
  3180. }
  3181. Out << 'E';
  3182. break;
  3183. }
  3184. case Expr::CXXPseudoDestructorExprClass: {
  3185. const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
  3186. if (const Expr *Base = PDE->getBase())
  3187. mangleMemberExprBase(Base, PDE->isArrow());
  3188. NestedNameSpecifier *Qualifier = PDE->getQualifier();
  3189. if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
  3190. if (Qualifier) {
  3191. mangleUnresolvedPrefix(Qualifier,
  3192. /*Recursive=*/true);
  3193. mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
  3194. Out << 'E';
  3195. } else {
  3196. Out << "sr";
  3197. if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
  3198. Out << 'E';
  3199. }
  3200. } else if (Qualifier) {
  3201. mangleUnresolvedPrefix(Qualifier);
  3202. }
  3203. // <base-unresolved-name> ::= dn <destructor-name>
  3204. Out << "dn";
  3205. QualType DestroyedType = PDE->getDestroyedType();
  3206. mangleUnresolvedTypeOrSimpleId(DestroyedType);
  3207. break;
  3208. }
  3209. case Expr::MemberExprClass: {
  3210. const MemberExpr *ME = cast<MemberExpr>(E);
  3211. mangleMemberExpr(ME->getBase(), ME->isArrow(),
  3212. ME->getQualifier(), nullptr,
  3213. ME->getMemberDecl()->getDeclName(),
  3214. ME->getTemplateArgs(), ME->getNumTemplateArgs(),
  3215. Arity);
  3216. break;
  3217. }
  3218. case Expr::UnresolvedMemberExprClass: {
  3219. const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
  3220. mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
  3221. ME->isArrow(), ME->getQualifier(), nullptr,
  3222. ME->getMemberName(),
  3223. ME->getTemplateArgs(), ME->getNumTemplateArgs(),
  3224. Arity);
  3225. break;
  3226. }
  3227. case Expr::CXXDependentScopeMemberExprClass: {
  3228. const CXXDependentScopeMemberExpr *ME
  3229. = cast<CXXDependentScopeMemberExpr>(E);
  3230. mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
  3231. ME->isArrow(), ME->getQualifier(),
  3232. ME->getFirstQualifierFoundInScope(),
  3233. ME->getMember(),
  3234. ME->getTemplateArgs(), ME->getNumTemplateArgs(),
  3235. Arity);
  3236. break;
  3237. }
  3238. case Expr::UnresolvedLookupExprClass: {
  3239. const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
  3240. mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
  3241. ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
  3242. Arity);
  3243. break;
  3244. }
  3245. case Expr::CXXUnresolvedConstructExprClass: {
  3246. const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
  3247. unsigned N = CE->arg_size();
  3248. if (CE->isListInitialization()) {
  3249. assert(N == 1 && "unexpected form for list initialization");
  3250. auto *IL = cast<InitListExpr>(CE->getArg(0));
  3251. Out << "tl";
  3252. mangleType(CE->getType());
  3253. mangleInitListElements(IL);
  3254. Out << "E";
  3255. return;
  3256. }
  3257. Out << "cv";
  3258. mangleType(CE->getType());
  3259. if (N != 1) Out << '_';
  3260. for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
  3261. if (N != 1) Out << 'E';
  3262. break;
  3263. }
  3264. case Expr::CXXConstructExprClass: {
  3265. const auto *CE = cast<CXXConstructExpr>(E);
  3266. if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
  3267. assert(
  3268. CE->getNumArgs() >= 1 &&
  3269. (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
  3270. "implicit CXXConstructExpr must have one argument");
  3271. return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
  3272. }
  3273. Out << "il";
  3274. for (auto *E : CE->arguments())
  3275. mangleExpression(E);
  3276. Out << "E";
  3277. break;
  3278. }
  3279. case Expr::CXXTemporaryObjectExprClass: {
  3280. const auto *CE = cast<CXXTemporaryObjectExpr>(E);
  3281. unsigned N = CE->getNumArgs();
  3282. bool List = CE->isListInitialization();
  3283. if (List)
  3284. Out << "tl";
  3285. else
  3286. Out << "cv";
  3287. mangleType(CE->getType());
  3288. if (!List && N != 1)
  3289. Out << '_';
  3290. if (CE->isStdInitListInitialization()) {
  3291. // We implicitly created a std::initializer_list<T> for the first argument
  3292. // of a constructor of type U in an expression of the form U{a, b, c}.
  3293. // Strip all the semantic gunk off the initializer list.
  3294. auto *SILE =
  3295. cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
  3296. auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
  3297. mangleInitListElements(ILE);
  3298. } else {
  3299. for (auto *E : CE->arguments())
  3300. mangleExpression(E);
  3301. }
  3302. if (List || N != 1)
  3303. Out << 'E';
  3304. break;
  3305. }
  3306. case Expr::CXXScalarValueInitExprClass:
  3307. Out << "cv";
  3308. mangleType(E->getType());
  3309. Out << "_E";
  3310. break;
  3311. case Expr::CXXNoexceptExprClass:
  3312. Out << "nx";
  3313. mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
  3314. break;
  3315. case Expr::UnaryExprOrTypeTraitExprClass: {
  3316. const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
  3317. if (!SAE->isInstantiationDependent()) {
  3318. // Itanium C++ ABI:
  3319. // If the operand of a sizeof or alignof operator is not
  3320. // instantiation-dependent it is encoded as an integer literal
  3321. // reflecting the result of the operator.
  3322. //
  3323. // If the result of the operator is implicitly converted to a known
  3324. // integer type, that type is used for the literal; otherwise, the type
  3325. // of std::size_t or std::ptrdiff_t is used.
  3326. QualType T = (ImplicitlyConvertedToType.isNull() ||
  3327. !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
  3328. : ImplicitlyConvertedToType;
  3329. llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
  3330. mangleIntegerLiteral(T, V);
  3331. break;
  3332. }
  3333. switch(SAE->getKind()) {
  3334. case UETT_SizeOf:
  3335. Out << 's';
  3336. break;
  3337. case UETT_AlignOf:
  3338. Out << 'a';
  3339. break;
  3340. case UETT_VecStep: {
  3341. DiagnosticsEngine &Diags = Context.getDiags();
  3342. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  3343. "cannot yet mangle vec_step expression");
  3344. Diags.Report(DiagID);
  3345. return;
  3346. }
  3347. case UETT_OpenMPRequiredSimdAlign:
  3348. DiagnosticsEngine &Diags = Context.getDiags();
  3349. unsigned DiagID = Diags.getCustomDiagID(
  3350. DiagnosticsEngine::Error,
  3351. "cannot yet mangle __builtin_omp_required_simd_align expression");
  3352. Diags.Report(DiagID);
  3353. return;
  3354. }
  3355. if (SAE->isArgumentType()) {
  3356. Out << 't';
  3357. mangleType(SAE->getArgumentType());
  3358. } else {
  3359. Out << 'z';
  3360. mangleExpression(SAE->getArgumentExpr());
  3361. }
  3362. break;
  3363. }
  3364. case Expr::CXXThrowExprClass: {
  3365. const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
  3366. // <expression> ::= tw <expression> # throw expression
  3367. // ::= tr # rethrow
  3368. if (TE->getSubExpr()) {
  3369. Out << "tw";
  3370. mangleExpression(TE->getSubExpr());
  3371. } else {
  3372. Out << "tr";
  3373. }
  3374. break;
  3375. }
  3376. case Expr::CXXTypeidExprClass: {
  3377. const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
  3378. // <expression> ::= ti <type> # typeid (type)
  3379. // ::= te <expression> # typeid (expression)
  3380. if (TIE->isTypeOperand()) {
  3381. Out << "ti";
  3382. mangleType(TIE->getTypeOperand(Context.getASTContext()));
  3383. } else {
  3384. Out << "te";
  3385. mangleExpression(TIE->getExprOperand());
  3386. }
  3387. break;
  3388. }
  3389. case Expr::CXXDeleteExprClass: {
  3390. const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
  3391. // <expression> ::= [gs] dl <expression> # [::] delete expr
  3392. // ::= [gs] da <expression> # [::] delete [] expr
  3393. if (DE->isGlobalDelete()) Out << "gs";
  3394. Out << (DE->isArrayForm() ? "da" : "dl");
  3395. mangleExpression(DE->getArgument());
  3396. break;
  3397. }
  3398. case Expr::UnaryOperatorClass: {
  3399. const UnaryOperator *UO = cast<UnaryOperator>(E);
  3400. mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
  3401. /*Arity=*/1);
  3402. mangleExpression(UO->getSubExpr());
  3403. break;
  3404. }
  3405. case Expr::ArraySubscriptExprClass: {
  3406. const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
  3407. // Array subscript is treated as a syntactically weird form of
  3408. // binary operator.
  3409. Out << "ix";
  3410. mangleExpression(AE->getLHS());
  3411. mangleExpression(AE->getRHS());
  3412. break;
  3413. }
  3414. case Expr::CompoundAssignOperatorClass: // fallthrough
  3415. case Expr::BinaryOperatorClass: {
  3416. const BinaryOperator *BO = cast<BinaryOperator>(E);
  3417. if (BO->getOpcode() == BO_PtrMemD)
  3418. Out << "ds";
  3419. else
  3420. mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
  3421. /*Arity=*/2);
  3422. mangleExpression(BO->getLHS());
  3423. mangleExpression(BO->getRHS());
  3424. break;
  3425. }
  3426. case Expr::ConditionalOperatorClass: {
  3427. const ConditionalOperator *CO = cast<ConditionalOperator>(E);
  3428. mangleOperatorName(OO_Conditional, /*Arity=*/3);
  3429. mangleExpression(CO->getCond());
  3430. mangleExpression(CO->getLHS(), Arity);
  3431. mangleExpression(CO->getRHS(), Arity);
  3432. break;
  3433. }
  3434. case Expr::ImplicitCastExprClass: {
  3435. ImplicitlyConvertedToType = E->getType();
  3436. E = cast<ImplicitCastExpr>(E)->getSubExpr();
  3437. goto recurse;
  3438. }
  3439. case Expr::ObjCBridgedCastExprClass: {
  3440. // Mangle ownership casts as a vendor extended operator __bridge,
  3441. // __bridge_transfer, or __bridge_retain.
  3442. StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
  3443. Out << "v1U" << Kind.size() << Kind;
  3444. }
  3445. // Fall through to mangle the cast itself.
  3446. LLVM_FALLTHROUGH;
  3447. case Expr::CStyleCastExprClass:
  3448. mangleCastExpression(E, "cv");
  3449. break;
  3450. case Expr::CXXFunctionalCastExprClass: {
  3451. auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
  3452. // FIXME: Add isImplicit to CXXConstructExpr.
  3453. if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
  3454. if (CCE->getParenOrBraceRange().isInvalid())
  3455. Sub = CCE->getArg(0)->IgnoreImplicit();
  3456. if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
  3457. Sub = StdInitList->getSubExpr()->IgnoreImplicit();
  3458. if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
  3459. Out << "tl";
  3460. mangleType(E->getType());
  3461. mangleInitListElements(IL);
  3462. Out << "E";
  3463. } else {
  3464. mangleCastExpression(E, "cv");
  3465. }
  3466. break;
  3467. }
  3468. case Expr::CXXStaticCastExprClass:
  3469. mangleCastExpression(E, "sc");
  3470. break;
  3471. case Expr::CXXDynamicCastExprClass:
  3472. mangleCastExpression(E, "dc");
  3473. break;
  3474. case Expr::CXXReinterpretCastExprClass:
  3475. mangleCastExpression(E, "rc");
  3476. break;
  3477. case Expr::CXXConstCastExprClass:
  3478. mangleCastExpression(E, "cc");
  3479. break;
  3480. case Expr::CXXOperatorCallExprClass: {
  3481. const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
  3482. unsigned NumArgs = CE->getNumArgs();
  3483. // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
  3484. // (the enclosing MemberExpr covers the syntactic portion).
  3485. if (CE->getOperator() != OO_Arrow)
  3486. mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
  3487. // Mangle the arguments.
  3488. for (unsigned i = 0; i != NumArgs; ++i)
  3489. mangleExpression(CE->getArg(i));
  3490. break;
  3491. }
  3492. case Expr::ParenExprClass:
  3493. mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
  3494. break;
  3495. case Expr::DeclRefExprClass: {
  3496. const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
  3497. switch (D->getKind()) {
  3498. default:
  3499. // <expr-primary> ::= L <mangled-name> E # external name
  3500. Out << 'L';
  3501. mangle(D);
  3502. Out << 'E';
  3503. break;
  3504. case Decl::ParmVar:
  3505. mangleFunctionParam(cast<ParmVarDecl>(D));
  3506. break;
  3507. case Decl::EnumConstant: {
  3508. const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
  3509. mangleIntegerLiteral(ED->getType(), ED->getInitVal());
  3510. break;
  3511. }
  3512. case Decl::NonTypeTemplateParm: {
  3513. const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
  3514. mangleTemplateParameter(PD->getIndex());
  3515. break;
  3516. }
  3517. }
  3518. break;
  3519. }
  3520. case Expr::SubstNonTypeTemplateParmPackExprClass:
  3521. // FIXME: not clear how to mangle this!
  3522. // template <unsigned N...> class A {
  3523. // template <class U...> void foo(U (&x)[N]...);
  3524. // };
  3525. Out << "_SUBSTPACK_";
  3526. break;
  3527. case Expr::FunctionParmPackExprClass: {
  3528. // FIXME: not clear how to mangle this!
  3529. const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
  3530. Out << "v110_SUBSTPACK";
  3531. mangleFunctionParam(FPPE->getParameterPack());
  3532. break;
  3533. }
  3534. case Expr::DependentScopeDeclRefExprClass: {
  3535. const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
  3536. mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
  3537. DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
  3538. Arity);
  3539. break;
  3540. }
  3541. case Expr::CXXBindTemporaryExprClass:
  3542. mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
  3543. break;
  3544. case Expr::ExprWithCleanupsClass:
  3545. mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
  3546. break;
  3547. case Expr::FloatingLiteralClass: {
  3548. const FloatingLiteral *FL = cast<FloatingLiteral>(E);
  3549. Out << 'L';
  3550. mangleType(FL->getType());
  3551. mangleFloat(FL->getValue());
  3552. Out << 'E';
  3553. break;
  3554. }
  3555. case Expr::CharacterLiteralClass:
  3556. Out << 'L';
  3557. mangleType(E->getType());
  3558. Out << cast<CharacterLiteral>(E)->getValue();
  3559. Out << 'E';
  3560. break;
  3561. // FIXME. __objc_yes/__objc_no are mangled same as true/false
  3562. case Expr::ObjCBoolLiteralExprClass:
  3563. Out << "Lb";
  3564. Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
  3565. Out << 'E';
  3566. break;
  3567. case Expr::CXXBoolLiteralExprClass:
  3568. Out << "Lb";
  3569. Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
  3570. Out << 'E';
  3571. break;
  3572. case Expr::IntegerLiteralClass: {
  3573. llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
  3574. if (E->getType()->isSignedIntegerType())
  3575. Value.setIsSigned(true);
  3576. mangleIntegerLiteral(E->getType(), Value);
  3577. break;
  3578. }
  3579. case Expr::ImaginaryLiteralClass: {
  3580. const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
  3581. // Mangle as if a complex literal.
  3582. // Proposal from David Vandevoorde, 2010.06.30.
  3583. Out << 'L';
  3584. mangleType(E->getType());
  3585. if (const FloatingLiteral *Imag =
  3586. dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
  3587. // Mangle a floating-point zero of the appropriate type.
  3588. mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
  3589. Out << '_';
  3590. mangleFloat(Imag->getValue());
  3591. } else {
  3592. Out << "0_";
  3593. llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
  3594. if (IE->getSubExpr()->getType()->isSignedIntegerType())
  3595. Value.setIsSigned(true);
  3596. mangleNumber(Value);
  3597. }
  3598. Out << 'E';
  3599. break;
  3600. }
  3601. case Expr::StringLiteralClass: {
  3602. // Revised proposal from David Vandervoorde, 2010.07.15.
  3603. Out << 'L';
  3604. assert(isa<ConstantArrayType>(E->getType()));
  3605. mangleType(E->getType());
  3606. Out << 'E';
  3607. break;
  3608. }
  3609. case Expr::GNUNullExprClass:
  3610. // FIXME: should this really be mangled the same as nullptr?
  3611. // fallthrough
  3612. case Expr::CXXNullPtrLiteralExprClass: {
  3613. Out << "LDnE";
  3614. break;
  3615. }
  3616. case Expr::PackExpansionExprClass:
  3617. Out << "sp";
  3618. mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
  3619. break;
  3620. case Expr::SizeOfPackExprClass: {
  3621. auto *SPE = cast<SizeOfPackExpr>(E);
  3622. if (SPE->isPartiallySubstituted()) {
  3623. Out << "sP";
  3624. for (const auto &A : SPE->getPartialArguments())
  3625. mangleTemplateArg(A);
  3626. Out << "E";
  3627. break;
  3628. }
  3629. Out << "sZ";
  3630. const NamedDecl *Pack = SPE->getPack();
  3631. if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
  3632. mangleTemplateParameter(TTP->getIndex());
  3633. else if (const NonTypeTemplateParmDecl *NTTP
  3634. = dyn_cast<NonTypeTemplateParmDecl>(Pack))
  3635. mangleTemplateParameter(NTTP->getIndex());
  3636. else if (const TemplateTemplateParmDecl *TempTP
  3637. = dyn_cast<TemplateTemplateParmDecl>(Pack))
  3638. mangleTemplateParameter(TempTP->getIndex());
  3639. else
  3640. mangleFunctionParam(cast<ParmVarDecl>(Pack));
  3641. break;
  3642. }
  3643. case Expr::MaterializeTemporaryExprClass: {
  3644. mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
  3645. break;
  3646. }
  3647. case Expr::CXXFoldExprClass: {
  3648. auto *FE = cast<CXXFoldExpr>(E);
  3649. if (FE->isLeftFold())
  3650. Out << (FE->getInit() ? "fL" : "fl");
  3651. else
  3652. Out << (FE->getInit() ? "fR" : "fr");
  3653. if (FE->getOperator() == BO_PtrMemD)
  3654. Out << "ds";
  3655. else
  3656. mangleOperatorName(
  3657. BinaryOperator::getOverloadedOperator(FE->getOperator()),
  3658. /*Arity=*/2);
  3659. if (FE->getLHS())
  3660. mangleExpression(FE->getLHS());
  3661. if (FE->getRHS())
  3662. mangleExpression(FE->getRHS());
  3663. break;
  3664. }
  3665. case Expr::CXXThisExprClass:
  3666. Out << "fpT";
  3667. break;
  3668. case Expr::CoawaitExprClass:
  3669. // FIXME: Propose a non-vendor mangling.
  3670. Out << "v18co_await";
  3671. mangleExpression(cast<CoawaitExpr>(E)->getOperand());
  3672. break;
  3673. case Expr::DependentCoawaitExprClass:
  3674. // FIXME: Propose a non-vendor mangling.
  3675. Out << "v18co_await";
  3676. mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand());
  3677. break;
  3678. case Expr::CoyieldExprClass:
  3679. // FIXME: Propose a non-vendor mangling.
  3680. Out << "v18co_yield";
  3681. mangleExpression(cast<CoawaitExpr>(E)->getOperand());
  3682. break;
  3683. }
  3684. }
  3685. /// Mangle an expression which refers to a parameter variable.
  3686. ///
  3687. /// <expression> ::= <function-param>
  3688. /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
  3689. /// <function-param> ::= fp <top-level CV-qualifiers>
  3690. /// <parameter-2 non-negative number> _ # L == 0, I > 0
  3691. /// <function-param> ::= fL <L-1 non-negative number>
  3692. /// p <top-level CV-qualifiers> _ # L > 0, I == 0
  3693. /// <function-param> ::= fL <L-1 non-negative number>
  3694. /// p <top-level CV-qualifiers>
  3695. /// <I-1 non-negative number> _ # L > 0, I > 0
  3696. ///
  3697. /// L is the nesting depth of the parameter, defined as 1 if the
  3698. /// parameter comes from the innermost function prototype scope
  3699. /// enclosing the current context, 2 if from the next enclosing
  3700. /// function prototype scope, and so on, with one special case: if
  3701. /// we've processed the full parameter clause for the innermost
  3702. /// function type, then L is one less. This definition conveniently
  3703. /// makes it irrelevant whether a function's result type was written
  3704. /// trailing or leading, but is otherwise overly complicated; the
  3705. /// numbering was first designed without considering references to
  3706. /// parameter in locations other than return types, and then the
  3707. /// mangling had to be generalized without changing the existing
  3708. /// manglings.
  3709. ///
  3710. /// I is the zero-based index of the parameter within its parameter
  3711. /// declaration clause. Note that the original ABI document describes
  3712. /// this using 1-based ordinals.
  3713. void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
  3714. unsigned parmDepth = parm->getFunctionScopeDepth();
  3715. unsigned parmIndex = parm->getFunctionScopeIndex();
  3716. // Compute 'L'.
  3717. // parmDepth does not include the declaring function prototype.
  3718. // FunctionTypeDepth does account for that.
  3719. assert(parmDepth < FunctionTypeDepth.getDepth());
  3720. unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
  3721. if (FunctionTypeDepth.isInResultType())
  3722. nestingDepth--;
  3723. if (nestingDepth == 0) {
  3724. Out << "fp";
  3725. } else {
  3726. Out << "fL" << (nestingDepth - 1) << 'p';
  3727. }
  3728. // Top-level qualifiers. We don't have to worry about arrays here,
  3729. // because parameters declared as arrays should already have been
  3730. // transformed to have pointer type. FIXME: apparently these don't
  3731. // get mangled if used as an rvalue of a known non-class type?
  3732. assert(!parm->getType()->isArrayType()
  3733. && "parameter's type is still an array type?");
  3734. if (const DependentAddressSpaceType *DAST =
  3735. dyn_cast<DependentAddressSpaceType>(parm->getType())) {
  3736. mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST);
  3737. } else {
  3738. mangleQualifiers(parm->getType().getQualifiers());
  3739. }
  3740. // Parameter index.
  3741. if (parmIndex != 0) {
  3742. Out << (parmIndex - 1);
  3743. }
  3744. Out << '_';
  3745. }
  3746. void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
  3747. const CXXRecordDecl *InheritedFrom) {
  3748. // <ctor-dtor-name> ::= C1 # complete object constructor
  3749. // ::= C2 # base object constructor
  3750. // ::= CI1 <type> # complete inheriting constructor
  3751. // ::= CI2 <type> # base inheriting constructor
  3752. //
  3753. // In addition, C5 is a comdat name with C1 and C2 in it.
  3754. Out << 'C';
  3755. if (InheritedFrom)
  3756. Out << 'I';
  3757. switch (T) {
  3758. case Ctor_Complete:
  3759. Out << '1';
  3760. break;
  3761. case Ctor_Base:
  3762. Out << '2';
  3763. break;
  3764. case Ctor_Comdat:
  3765. Out << '5';
  3766. break;
  3767. case Ctor_DefaultClosure:
  3768. case Ctor_CopyingClosure:
  3769. llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
  3770. }
  3771. if (InheritedFrom)
  3772. mangleName(InheritedFrom);
  3773. }
  3774. void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
  3775. // <ctor-dtor-name> ::= D0 # deleting destructor
  3776. // ::= D1 # complete object destructor
  3777. // ::= D2 # base object destructor
  3778. //
  3779. // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
  3780. switch (T) {
  3781. case Dtor_Deleting:
  3782. Out << "D0";
  3783. break;
  3784. case Dtor_Complete:
  3785. Out << "D1";
  3786. break;
  3787. case Dtor_Base:
  3788. Out << "D2";
  3789. break;
  3790. case Dtor_Comdat:
  3791. Out << "D5";
  3792. break;
  3793. }
  3794. }
  3795. void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
  3796. unsigned NumTemplateArgs) {
  3797. // <template-args> ::= I <template-arg>+ E
  3798. Out << 'I';
  3799. for (unsigned i = 0; i != NumTemplateArgs; ++i)
  3800. mangleTemplateArg(TemplateArgs[i].getArgument());
  3801. Out << 'E';
  3802. }
  3803. void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
  3804. // <template-args> ::= I <template-arg>+ E
  3805. Out << 'I';
  3806. for (unsigned i = 0, e = AL.size(); i != e; ++i)
  3807. mangleTemplateArg(AL[i]);
  3808. Out << 'E';
  3809. }
  3810. void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
  3811. unsigned NumTemplateArgs) {
  3812. // <template-args> ::= I <template-arg>+ E
  3813. Out << 'I';
  3814. for (unsigned i = 0; i != NumTemplateArgs; ++i)
  3815. mangleTemplateArg(TemplateArgs[i]);
  3816. Out << 'E';
  3817. }
  3818. void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
  3819. // <template-arg> ::= <type> # type or template
  3820. // ::= X <expression> E # expression
  3821. // ::= <expr-primary> # simple expressions
  3822. // ::= J <template-arg>* E # argument pack
  3823. if (!A.isInstantiationDependent() || A.isDependent())
  3824. A = Context.getASTContext().getCanonicalTemplateArgument(A);
  3825. switch (A.getKind()) {
  3826. case TemplateArgument::Null:
  3827. llvm_unreachable("Cannot mangle NULL template argument");
  3828. case TemplateArgument::Type:
  3829. mangleType(A.getAsType());
  3830. break;
  3831. case TemplateArgument::Template:
  3832. // This is mangled as <type>.
  3833. mangleType(A.getAsTemplate());
  3834. break;
  3835. case TemplateArgument::TemplateExpansion:
  3836. // <type> ::= Dp <type> # pack expansion (C++0x)
  3837. Out << "Dp";
  3838. mangleType(A.getAsTemplateOrTemplatePattern());
  3839. break;
  3840. case TemplateArgument::Expression: {
  3841. // It's possible to end up with a DeclRefExpr here in certain
  3842. // dependent cases, in which case we should mangle as a
  3843. // declaration.
  3844. const Expr *E = A.getAsExpr()->IgnoreParens();
  3845. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  3846. const ValueDecl *D = DRE->getDecl();
  3847. if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
  3848. Out << 'L';
  3849. mangle(D);
  3850. Out << 'E';
  3851. break;
  3852. }
  3853. }
  3854. Out << 'X';
  3855. mangleExpression(E);
  3856. Out << 'E';
  3857. break;
  3858. }
  3859. case TemplateArgument::Integral:
  3860. mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
  3861. break;
  3862. case TemplateArgument::Declaration: {
  3863. // <expr-primary> ::= L <mangled-name> E # external name
  3864. // Clang produces AST's where pointer-to-member-function expressions
  3865. // and pointer-to-function expressions are represented as a declaration not
  3866. // an expression. We compensate for it here to produce the correct mangling.
  3867. ValueDecl *D = A.getAsDecl();
  3868. bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
  3869. if (compensateMangling) {
  3870. Out << 'X';
  3871. mangleOperatorName(OO_Amp, 1);
  3872. }
  3873. Out << 'L';
  3874. // References to external entities use the mangled name; if the name would
  3875. // not normally be mangled then mangle it as unqualified.
  3876. mangle(D);
  3877. Out << 'E';
  3878. if (compensateMangling)
  3879. Out << 'E';
  3880. break;
  3881. }
  3882. case TemplateArgument::NullPtr: {
  3883. // <expr-primary> ::= L <type> 0 E
  3884. Out << 'L';
  3885. mangleType(A.getNullPtrType());
  3886. Out << "0E";
  3887. break;
  3888. }
  3889. case TemplateArgument::Pack: {
  3890. // <template-arg> ::= J <template-arg>* E
  3891. Out << 'J';
  3892. for (const auto &P : A.pack_elements())
  3893. mangleTemplateArg(P);
  3894. Out << 'E';
  3895. }
  3896. }
  3897. }
  3898. void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
  3899. // <template-param> ::= T_ # first template parameter
  3900. // ::= T <parameter-2 non-negative number> _
  3901. if (Index == 0)
  3902. Out << "T_";
  3903. else
  3904. Out << 'T' << (Index - 1) << '_';
  3905. }
  3906. void CXXNameMangler::mangleSeqID(unsigned SeqID) {
  3907. if (SeqID == 1)
  3908. Out << '0';
  3909. else if (SeqID > 1) {
  3910. SeqID--;
  3911. // <seq-id> is encoded in base-36, using digits and upper case letters.
  3912. char Buffer[7]; // log(2**32) / log(36) ~= 7
  3913. MutableArrayRef<char> BufferRef(Buffer);
  3914. MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
  3915. for (; SeqID != 0; SeqID /= 36) {
  3916. unsigned C = SeqID % 36;
  3917. *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
  3918. }
  3919. Out.write(I.base(), I - BufferRef.rbegin());
  3920. }
  3921. Out << '_';
  3922. }
  3923. void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
  3924. bool result = mangleSubstitution(tname);
  3925. assert(result && "no existing substitution for template name");
  3926. (void) result;
  3927. }
  3928. // <substitution> ::= S <seq-id> _
  3929. // ::= S_
  3930. bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
  3931. // Try one of the standard substitutions first.
  3932. if (mangleStandardSubstitution(ND))
  3933. return true;
  3934. ND = cast<NamedDecl>(ND->getCanonicalDecl());
  3935. return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
  3936. }
  3937. /// Determine whether the given type has any qualifiers that are relevant for
  3938. /// substitutions.
  3939. static bool hasMangledSubstitutionQualifiers(QualType T) {
  3940. Qualifiers Qs = T.getQualifiers();
  3941. return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned();
  3942. }
  3943. bool CXXNameMangler::mangleSubstitution(QualType T) {
  3944. if (!hasMangledSubstitutionQualifiers(T)) {
  3945. if (const RecordType *RT = T->getAs<RecordType>())
  3946. return mangleSubstitution(RT->getDecl());
  3947. }
  3948. uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
  3949. return mangleSubstitution(TypePtr);
  3950. }
  3951. bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
  3952. if (TemplateDecl *TD = Template.getAsTemplateDecl())
  3953. return mangleSubstitution(TD);
  3954. Template = Context.getASTContext().getCanonicalTemplateName(Template);
  3955. return mangleSubstitution(
  3956. reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
  3957. }
  3958. bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
  3959. llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
  3960. if (I == Substitutions.end())
  3961. return false;
  3962. unsigned SeqID = I->second;
  3963. Out << 'S';
  3964. mangleSeqID(SeqID);
  3965. return true;
  3966. }
  3967. static bool isCharType(QualType T) {
  3968. if (T.isNull())
  3969. return false;
  3970. return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3971. T->isSpecificBuiltinType(BuiltinType::Char_U);
  3972. }
  3973. /// Returns whether a given type is a template specialization of a given name
  3974. /// with a single argument of type char.
  3975. static bool isCharSpecialization(QualType T, const char *Name) {
  3976. if (T.isNull())
  3977. return false;
  3978. const RecordType *RT = T->getAs<RecordType>();
  3979. if (!RT)
  3980. return false;
  3981. const ClassTemplateSpecializationDecl *SD =
  3982. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
  3983. if (!SD)
  3984. return false;
  3985. if (!isStdNamespace(getEffectiveDeclContext(SD)))
  3986. return false;
  3987. const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
  3988. if (TemplateArgs.size() != 1)
  3989. return false;
  3990. if (!isCharType(TemplateArgs[0].getAsType()))
  3991. return false;
  3992. return SD->getIdentifier()->getName() == Name;
  3993. }
  3994. template <std::size_t StrLen>
  3995. static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
  3996. const char (&Str)[StrLen]) {
  3997. if (!SD->getIdentifier()->isStr(Str))
  3998. return false;
  3999. const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
  4000. if (TemplateArgs.size() != 2)
  4001. return false;
  4002. if (!isCharType(TemplateArgs[0].getAsType()))
  4003. return false;
  4004. if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
  4005. return false;
  4006. return true;
  4007. }
  4008. bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
  4009. // <substitution> ::= St # ::std::
  4010. if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
  4011. if (isStd(NS)) {
  4012. Out << "St";
  4013. return true;
  4014. }
  4015. }
  4016. if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
  4017. if (!isStdNamespace(getEffectiveDeclContext(TD)))
  4018. return false;
  4019. // <substitution> ::= Sa # ::std::allocator
  4020. if (TD->getIdentifier()->isStr("allocator")) {
  4021. Out << "Sa";
  4022. return true;
  4023. }
  4024. // <<substitution> ::= Sb # ::std::basic_string
  4025. if (TD->getIdentifier()->isStr("basic_string")) {
  4026. Out << "Sb";
  4027. return true;
  4028. }
  4029. }
  4030. if (const ClassTemplateSpecializationDecl *SD =
  4031. dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
  4032. if (!isStdNamespace(getEffectiveDeclContext(SD)))
  4033. return false;
  4034. // <substitution> ::= Ss # ::std::basic_string<char,
  4035. // ::std::char_traits<char>,
  4036. // ::std::allocator<char> >
  4037. if (SD->getIdentifier()->isStr("basic_string")) {
  4038. const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
  4039. if (TemplateArgs.size() != 3)
  4040. return false;
  4041. if (!isCharType(TemplateArgs[0].getAsType()))
  4042. return false;
  4043. if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
  4044. return false;
  4045. if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
  4046. return false;
  4047. Out << "Ss";
  4048. return true;
  4049. }
  4050. // <substitution> ::= Si # ::std::basic_istream<char,
  4051. // ::std::char_traits<char> >
  4052. if (isStreamCharSpecialization(SD, "basic_istream")) {
  4053. Out << "Si";
  4054. return true;
  4055. }
  4056. // <substitution> ::= So # ::std::basic_ostream<char,
  4057. // ::std::char_traits<char> >
  4058. if (isStreamCharSpecialization(SD, "basic_ostream")) {
  4059. Out << "So";
  4060. return true;
  4061. }
  4062. // <substitution> ::= Sd # ::std::basic_iostream<char,
  4063. // ::std::char_traits<char> >
  4064. if (isStreamCharSpecialization(SD, "basic_iostream")) {
  4065. Out << "Sd";
  4066. return true;
  4067. }
  4068. }
  4069. return false;
  4070. }
  4071. void CXXNameMangler::addSubstitution(QualType T) {
  4072. if (!hasMangledSubstitutionQualifiers(T)) {
  4073. if (const RecordType *RT = T->getAs<RecordType>()) {
  4074. addSubstitution(RT->getDecl());
  4075. return;
  4076. }
  4077. }
  4078. uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
  4079. addSubstitution(TypePtr);
  4080. }
  4081. void CXXNameMangler::addSubstitution(TemplateName Template) {
  4082. if (TemplateDecl *TD = Template.getAsTemplateDecl())
  4083. return addSubstitution(TD);
  4084. Template = Context.getASTContext().getCanonicalTemplateName(Template);
  4085. addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
  4086. }
  4087. void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
  4088. assert(!Substitutions.count(Ptr) && "Substitution already exists!");
  4089. Substitutions[Ptr] = SeqID++;
  4090. }
  4091. void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) {
  4092. assert(Other->SeqID >= SeqID && "Must be superset of substitutions!");
  4093. if (Other->SeqID > SeqID) {
  4094. Substitutions.swap(Other->Substitutions);
  4095. SeqID = Other->SeqID;
  4096. }
  4097. }
  4098. CXXNameMangler::AbiTagList
  4099. CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
  4100. // When derived abi tags are disabled there is no need to make any list.
  4101. if (DisableDerivedAbiTags)
  4102. return AbiTagList();
  4103. llvm::raw_null_ostream NullOutStream;
  4104. CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
  4105. TrackReturnTypeTags.disableDerivedAbiTags();
  4106. const FunctionProtoType *Proto =
  4107. cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
  4108. FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push();
  4109. TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
  4110. TrackReturnTypeTags.mangleType(Proto->getReturnType());
  4111. TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
  4112. TrackReturnTypeTags.FunctionTypeDepth.pop(saved);
  4113. return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
  4114. }
  4115. CXXNameMangler::AbiTagList
  4116. CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
  4117. // When derived abi tags are disabled there is no need to make any list.
  4118. if (DisableDerivedAbiTags)
  4119. return AbiTagList();
  4120. llvm::raw_null_ostream NullOutStream;
  4121. CXXNameMangler TrackVariableType(*this, NullOutStream);
  4122. TrackVariableType.disableDerivedAbiTags();
  4123. TrackVariableType.mangleType(VD->getType());
  4124. return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
  4125. }
  4126. bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
  4127. const VarDecl *VD) {
  4128. llvm::raw_null_ostream NullOutStream;
  4129. CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
  4130. TrackAbiTags.mangle(VD);
  4131. return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
  4132. }
  4133. //
  4134. /// Mangles the name of the declaration D and emits that name to the given
  4135. /// output stream.
  4136. ///
  4137. /// If the declaration D requires a mangled name, this routine will emit that
  4138. /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
  4139. /// and this routine will return false. In this case, the caller should just
  4140. /// emit the identifier of the declaration (\c D->getIdentifier()) as its
  4141. /// name.
  4142. void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
  4143. raw_ostream &Out) {
  4144. assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
  4145. "Invalid mangleName() call, argument is not a variable or function!");
  4146. assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
  4147. "Invalid mangleName() call on 'structor decl!");
  4148. PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
  4149. getASTContext().getSourceManager(),
  4150. "Mangling declaration");
  4151. CXXNameMangler Mangler(*this, Out, D);
  4152. Mangler.mangle(D);
  4153. }
  4154. void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
  4155. CXXCtorType Type,
  4156. raw_ostream &Out) {
  4157. CXXNameMangler Mangler(*this, Out, D, Type);
  4158. Mangler.mangle(D);
  4159. }
  4160. void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
  4161. CXXDtorType Type,
  4162. raw_ostream &Out) {
  4163. CXXNameMangler Mangler(*this, Out, D, Type);
  4164. Mangler.mangle(D);
  4165. }
  4166. void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
  4167. raw_ostream &Out) {
  4168. CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
  4169. Mangler.mangle(D);
  4170. }
  4171. void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
  4172. raw_ostream &Out) {
  4173. CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
  4174. Mangler.mangle(D);
  4175. }
  4176. void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
  4177. const ThunkInfo &Thunk,
  4178. raw_ostream &Out) {
  4179. // <special-name> ::= T <call-offset> <base encoding>
  4180. // # base is the nominal target function of thunk
  4181. // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
  4182. // # base is the nominal target function of thunk
  4183. // # first call-offset is 'this' adjustment
  4184. // # second call-offset is result adjustment
  4185. assert(!isa<CXXDestructorDecl>(MD) &&
  4186. "Use mangleCXXDtor for destructor decls!");
  4187. CXXNameMangler Mangler(*this, Out);
  4188. Mangler.getStream() << "_ZT";
  4189. if (!Thunk.Return.isEmpty())
  4190. Mangler.getStream() << 'c';
  4191. // Mangle the 'this' pointer adjustment.
  4192. Mangler.mangleCallOffset(Thunk.This.NonVirtual,
  4193. Thunk.This.Virtual.Itanium.VCallOffsetOffset);
  4194. // Mangle the return pointer adjustment if there is one.
  4195. if (!Thunk.Return.isEmpty())
  4196. Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
  4197. Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
  4198. Mangler.mangleFunctionEncoding(MD);
  4199. }
  4200. void ItaniumMangleContextImpl::mangleCXXDtorThunk(
  4201. const CXXDestructorDecl *DD, CXXDtorType Type,
  4202. const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
  4203. // <special-name> ::= T <call-offset> <base encoding>
  4204. // # base is the nominal target function of thunk
  4205. CXXNameMangler Mangler(*this, Out, DD, Type);
  4206. Mangler.getStream() << "_ZT";
  4207. // Mangle the 'this' pointer adjustment.
  4208. Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
  4209. ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
  4210. Mangler.mangleFunctionEncoding(DD);
  4211. }
  4212. /// Returns the mangled name for a guard variable for the passed in VarDecl.
  4213. void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
  4214. raw_ostream &Out) {
  4215. // <special-name> ::= GV <object name> # Guard variable for one-time
  4216. // # initialization
  4217. CXXNameMangler Mangler(*this, Out);
  4218. // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
  4219. // be a bug that is fixed in trunk.
  4220. Mangler.getStream() << "_ZGV";
  4221. Mangler.mangleName(D);
  4222. }
  4223. void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
  4224. raw_ostream &Out) {
  4225. // These symbols are internal in the Itanium ABI, so the names don't matter.
  4226. // Clang has traditionally used this symbol and allowed LLVM to adjust it to
  4227. // avoid duplicate symbols.
  4228. Out << "__cxx_global_var_init";
  4229. }
  4230. void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
  4231. raw_ostream &Out) {
  4232. // Prefix the mangling of D with __dtor_.
  4233. CXXNameMangler Mangler(*this, Out);
  4234. Mangler.getStream() << "__dtor_";
  4235. if (shouldMangleDeclName(D))
  4236. Mangler.mangle(D);
  4237. else
  4238. Mangler.getStream() << D->getName();
  4239. }
  4240. void ItaniumMangleContextImpl::mangleSEHFilterExpression(
  4241. const NamedDecl *EnclosingDecl, raw_ostream &Out) {
  4242. CXXNameMangler Mangler(*this, Out);
  4243. Mangler.getStream() << "__filt_";
  4244. if (shouldMangleDeclName(EnclosingDecl))
  4245. Mangler.mangle(EnclosingDecl);
  4246. else
  4247. Mangler.getStream() << EnclosingDecl->getName();
  4248. }
  4249. void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
  4250. const NamedDecl *EnclosingDecl, raw_ostream &Out) {
  4251. CXXNameMangler Mangler(*this, Out);
  4252. Mangler.getStream() << "__fin_";
  4253. if (shouldMangleDeclName(EnclosingDecl))
  4254. Mangler.mangle(EnclosingDecl);
  4255. else
  4256. Mangler.getStream() << EnclosingDecl->getName();
  4257. }
  4258. void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
  4259. raw_ostream &Out) {
  4260. // <special-name> ::= TH <object name>
  4261. CXXNameMangler Mangler(*this, Out);
  4262. Mangler.getStream() << "_ZTH";
  4263. Mangler.mangleName(D);
  4264. }
  4265. void
  4266. ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
  4267. raw_ostream &Out) {
  4268. // <special-name> ::= TW <object name>
  4269. CXXNameMangler Mangler(*this, Out);
  4270. Mangler.getStream() << "_ZTW";
  4271. Mangler.mangleName(D);
  4272. }
  4273. void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
  4274. unsigned ManglingNumber,
  4275. raw_ostream &Out) {
  4276. // We match the GCC mangling here.
  4277. // <special-name> ::= GR <object name>
  4278. CXXNameMangler Mangler(*this, Out);
  4279. Mangler.getStream() << "_ZGR";
  4280. Mangler.mangleName(D);
  4281. assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
  4282. Mangler.mangleSeqID(ManglingNumber - 1);
  4283. }
  4284. void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
  4285. raw_ostream &Out) {
  4286. // <special-name> ::= TV <type> # virtual table
  4287. CXXNameMangler Mangler(*this, Out);
  4288. Mangler.getStream() << "_ZTV";
  4289. Mangler.mangleNameOrStandardSubstitution(RD);
  4290. }
  4291. void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
  4292. raw_ostream &Out) {
  4293. // <special-name> ::= TT <type> # VTT structure
  4294. CXXNameMangler Mangler(*this, Out);
  4295. Mangler.getStream() << "_ZTT";
  4296. Mangler.mangleNameOrStandardSubstitution(RD);
  4297. }
  4298. void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
  4299. int64_t Offset,
  4300. const CXXRecordDecl *Type,
  4301. raw_ostream &Out) {
  4302. // <special-name> ::= TC <type> <offset number> _ <base type>
  4303. CXXNameMangler Mangler(*this, Out);
  4304. Mangler.getStream() << "_ZTC";
  4305. Mangler.mangleNameOrStandardSubstitution(RD);
  4306. Mangler.getStream() << Offset;
  4307. Mangler.getStream() << '_';
  4308. Mangler.mangleNameOrStandardSubstitution(Type);
  4309. }
  4310. void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
  4311. // <special-name> ::= TI <type> # typeinfo structure
  4312. assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
  4313. CXXNameMangler Mangler(*this, Out);
  4314. Mangler.getStream() << "_ZTI";
  4315. Mangler.mangleType(Ty);
  4316. }
  4317. void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
  4318. raw_ostream &Out) {
  4319. // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
  4320. CXXNameMangler Mangler(*this, Out);
  4321. Mangler.getStream() << "_ZTS";
  4322. Mangler.mangleType(Ty);
  4323. }
  4324. void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
  4325. mangleCXXRTTIName(Ty, Out);
  4326. }
  4327. void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
  4328. llvm_unreachable("Can't mangle string literals");
  4329. }
  4330. ItaniumMangleContext *
  4331. ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
  4332. return new ItaniumMangleContextImpl(Context, Diags);
  4333. }