ItaniumMangle.cpp 139 KB

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