ItaniumMangle.cpp 175 KB

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