ItaniumMangle.cpp 138 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118
  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 (const IdentifierInfo *II = 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. }
  1767. }
  1768. // <type> ::= <function-type>
  1769. // <function-type> ::= [<CV-qualifiers>] F [Y]
  1770. // <bare-function-type> [<ref-qualifier>] E
  1771. void CXXNameMangler::mangleType(const FunctionProtoType *T) {
  1772. // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
  1773. // e.g. "const" in "int (A::*)() const".
  1774. mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
  1775. Out << 'F';
  1776. // FIXME: We don't have enough information in the AST to produce the 'Y'
  1777. // encoding for extern "C" function types.
  1778. mangleBareFunctionType(T, /*MangleReturnType=*/true);
  1779. // Mangle the ref-qualifier, if present.
  1780. mangleRefQualifier(T->getRefQualifier());
  1781. Out << 'E';
  1782. }
  1783. void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
  1784. llvm_unreachable("Can't mangle K&R function prototypes");
  1785. }
  1786. void CXXNameMangler::mangleBareFunctionType(const FunctionType *T,
  1787. bool MangleReturnType) {
  1788. // We should never be mangling something without a prototype.
  1789. const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
  1790. // Record that we're in a function type. See mangleFunctionParam
  1791. // for details on what we're trying to achieve here.
  1792. FunctionTypeDepthState saved = FunctionTypeDepth.push();
  1793. // <bare-function-type> ::= <signature type>+
  1794. if (MangleReturnType) {
  1795. FunctionTypeDepth.enterResultType();
  1796. mangleType(Proto->getReturnType());
  1797. FunctionTypeDepth.leaveResultType();
  1798. }
  1799. if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
  1800. // <builtin-type> ::= v # void
  1801. Out << 'v';
  1802. FunctionTypeDepth.pop(saved);
  1803. return;
  1804. }
  1805. for (const auto &Arg : Proto->param_types())
  1806. mangleType(Context.getASTContext().getSignatureParameterType(Arg));
  1807. FunctionTypeDepth.pop(saved);
  1808. // <builtin-type> ::= z # ellipsis
  1809. if (Proto->isVariadic())
  1810. Out << 'z';
  1811. }
  1812. // <type> ::= <class-enum-type>
  1813. // <class-enum-type> ::= <name>
  1814. void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
  1815. mangleName(T->getDecl());
  1816. }
  1817. // <type> ::= <class-enum-type>
  1818. // <class-enum-type> ::= <name>
  1819. void CXXNameMangler::mangleType(const EnumType *T) {
  1820. mangleType(static_cast<const TagType*>(T));
  1821. }
  1822. void CXXNameMangler::mangleType(const RecordType *T) {
  1823. mangleType(static_cast<const TagType*>(T));
  1824. }
  1825. void CXXNameMangler::mangleType(const TagType *T) {
  1826. mangleName(T->getDecl());
  1827. }
  1828. // <type> ::= <array-type>
  1829. // <array-type> ::= A <positive dimension number> _ <element type>
  1830. // ::= A [<dimension expression>] _ <element type>
  1831. void CXXNameMangler::mangleType(const ConstantArrayType *T) {
  1832. Out << 'A' << T->getSize() << '_';
  1833. mangleType(T->getElementType());
  1834. }
  1835. void CXXNameMangler::mangleType(const VariableArrayType *T) {
  1836. Out << 'A';
  1837. // decayed vla types (size 0) will just be skipped.
  1838. if (T->getSizeExpr())
  1839. mangleExpression(T->getSizeExpr());
  1840. Out << '_';
  1841. mangleType(T->getElementType());
  1842. }
  1843. void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
  1844. Out << 'A';
  1845. mangleExpression(T->getSizeExpr());
  1846. Out << '_';
  1847. mangleType(T->getElementType());
  1848. }
  1849. void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
  1850. Out << "A_";
  1851. mangleType(T->getElementType());
  1852. }
  1853. // <type> ::= <pointer-to-member-type>
  1854. // <pointer-to-member-type> ::= M <class type> <member type>
  1855. void CXXNameMangler::mangleType(const MemberPointerType *T) {
  1856. Out << 'M';
  1857. mangleType(QualType(T->getClass(), 0));
  1858. QualType PointeeType = T->getPointeeType();
  1859. if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
  1860. mangleType(FPT);
  1861. // Itanium C++ ABI 5.1.8:
  1862. //
  1863. // The type of a non-static member function is considered to be different,
  1864. // for the purposes of substitution, from the type of a namespace-scope or
  1865. // static member function whose type appears similar. The types of two
  1866. // non-static member functions are considered to be different, for the
  1867. // purposes of substitution, if the functions are members of different
  1868. // classes. In other words, for the purposes of substitution, the class of
  1869. // which the function is a member is considered part of the type of
  1870. // function.
  1871. // Given that we already substitute member function pointers as a
  1872. // whole, the net effect of this rule is just to unconditionally
  1873. // suppress substitution on the function type in a member pointer.
  1874. // We increment the SeqID here to emulate adding an entry to the
  1875. // substitution table.
  1876. ++SeqID;
  1877. } else
  1878. mangleType(PointeeType);
  1879. }
  1880. // <type> ::= <template-param>
  1881. void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
  1882. mangleTemplateParameter(T->getIndex());
  1883. }
  1884. // <type> ::= <template-param>
  1885. void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
  1886. // FIXME: not clear how to mangle this!
  1887. // template <class T...> class A {
  1888. // template <class U...> void foo(T(*)(U) x...);
  1889. // };
  1890. Out << "_SUBSTPACK_";
  1891. }
  1892. // <type> ::= P <type> # pointer-to
  1893. void CXXNameMangler::mangleType(const PointerType *T) {
  1894. Out << 'P';
  1895. mangleType(T->getPointeeType());
  1896. }
  1897. void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
  1898. Out << 'P';
  1899. mangleType(T->getPointeeType());
  1900. }
  1901. // <type> ::= R <type> # reference-to
  1902. void CXXNameMangler::mangleType(const LValueReferenceType *T) {
  1903. Out << 'R';
  1904. mangleType(T->getPointeeType());
  1905. }
  1906. // <type> ::= O <type> # rvalue reference-to (C++0x)
  1907. void CXXNameMangler::mangleType(const RValueReferenceType *T) {
  1908. Out << 'O';
  1909. mangleType(T->getPointeeType());
  1910. }
  1911. // <type> ::= C <type> # complex pair (C 2000)
  1912. void CXXNameMangler::mangleType(const ComplexType *T) {
  1913. Out << 'C';
  1914. mangleType(T->getElementType());
  1915. }
  1916. // ARM's ABI for Neon vector types specifies that they should be mangled as
  1917. // if they are structs (to match ARM's initial implementation). The
  1918. // vector type must be one of the special types predefined by ARM.
  1919. void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
  1920. QualType EltType = T->getElementType();
  1921. assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
  1922. const char *EltName = nullptr;
  1923. if (T->getVectorKind() == VectorType::NeonPolyVector) {
  1924. switch (cast<BuiltinType>(EltType)->getKind()) {
  1925. case BuiltinType::SChar:
  1926. case BuiltinType::UChar:
  1927. EltName = "poly8_t";
  1928. break;
  1929. case BuiltinType::Short:
  1930. case BuiltinType::UShort:
  1931. EltName = "poly16_t";
  1932. break;
  1933. case BuiltinType::ULongLong:
  1934. EltName = "poly64_t";
  1935. break;
  1936. default: llvm_unreachable("unexpected Neon polynomial vector element type");
  1937. }
  1938. } else {
  1939. switch (cast<BuiltinType>(EltType)->getKind()) {
  1940. case BuiltinType::SChar: EltName = "int8_t"; break;
  1941. case BuiltinType::UChar: EltName = "uint8_t"; break;
  1942. case BuiltinType::Short: EltName = "int16_t"; break;
  1943. case BuiltinType::UShort: EltName = "uint16_t"; break;
  1944. case BuiltinType::Int: EltName = "int32_t"; break;
  1945. case BuiltinType::UInt: EltName = "uint32_t"; break;
  1946. case BuiltinType::LongLong: EltName = "int64_t"; break;
  1947. case BuiltinType::ULongLong: EltName = "uint64_t"; break;
  1948. case BuiltinType::Double: EltName = "float64_t"; break;
  1949. case BuiltinType::Float: EltName = "float32_t"; break;
  1950. case BuiltinType::Half: EltName = "float16_t";break;
  1951. default:
  1952. llvm_unreachable("unexpected Neon vector element type");
  1953. }
  1954. }
  1955. const char *BaseName = nullptr;
  1956. unsigned BitSize = (T->getNumElements() *
  1957. getASTContext().getTypeSize(EltType));
  1958. if (BitSize == 64)
  1959. BaseName = "__simd64_";
  1960. else {
  1961. assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
  1962. BaseName = "__simd128_";
  1963. }
  1964. Out << strlen(BaseName) + strlen(EltName);
  1965. Out << BaseName << EltName;
  1966. }
  1967. static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
  1968. switch (EltType->getKind()) {
  1969. case BuiltinType::SChar:
  1970. return "Int8";
  1971. case BuiltinType::Short:
  1972. return "Int16";
  1973. case BuiltinType::Int:
  1974. return "Int32";
  1975. case BuiltinType::Long:
  1976. case BuiltinType::LongLong:
  1977. return "Int64";
  1978. case BuiltinType::UChar:
  1979. return "Uint8";
  1980. case BuiltinType::UShort:
  1981. return "Uint16";
  1982. case BuiltinType::UInt:
  1983. return "Uint32";
  1984. case BuiltinType::ULong:
  1985. case BuiltinType::ULongLong:
  1986. return "Uint64";
  1987. case BuiltinType::Half:
  1988. return "Float16";
  1989. case BuiltinType::Float:
  1990. return "Float32";
  1991. case BuiltinType::Double:
  1992. return "Float64";
  1993. default:
  1994. llvm_unreachable("Unexpected vector element base type");
  1995. }
  1996. }
  1997. // AArch64's ABI for Neon vector types specifies that they should be mangled as
  1998. // the equivalent internal name. The vector type must be one of the special
  1999. // types predefined by ARM.
  2000. void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
  2001. QualType EltType = T->getElementType();
  2002. assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
  2003. unsigned BitSize =
  2004. (T->getNumElements() * getASTContext().getTypeSize(EltType));
  2005. (void)BitSize; // Silence warning.
  2006. assert((BitSize == 64 || BitSize == 128) &&
  2007. "Neon vector type not 64 or 128 bits");
  2008. StringRef EltName;
  2009. if (T->getVectorKind() == VectorType::NeonPolyVector) {
  2010. switch (cast<BuiltinType>(EltType)->getKind()) {
  2011. case BuiltinType::UChar:
  2012. EltName = "Poly8";
  2013. break;
  2014. case BuiltinType::UShort:
  2015. EltName = "Poly16";
  2016. break;
  2017. case BuiltinType::ULong:
  2018. case BuiltinType::ULongLong:
  2019. EltName = "Poly64";
  2020. break;
  2021. default:
  2022. llvm_unreachable("unexpected Neon polynomial vector element type");
  2023. }
  2024. } else
  2025. EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
  2026. std::string TypeName =
  2027. ("__" + EltName + "x" + llvm::utostr(T->getNumElements()) + "_t").str();
  2028. Out << TypeName.length() << TypeName;
  2029. }
  2030. // GNU extension: vector types
  2031. // <type> ::= <vector-type>
  2032. // <vector-type> ::= Dv <positive dimension number> _
  2033. // <extended element type>
  2034. // ::= Dv [<dimension expression>] _ <element type>
  2035. // <extended element type> ::= <element type>
  2036. // ::= p # AltiVec vector pixel
  2037. // ::= b # Altivec vector bool
  2038. void CXXNameMangler::mangleType(const VectorType *T) {
  2039. if ((T->getVectorKind() == VectorType::NeonVector ||
  2040. T->getVectorKind() == VectorType::NeonPolyVector)) {
  2041. llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
  2042. llvm::Triple::ArchType Arch =
  2043. getASTContext().getTargetInfo().getTriple().getArch();
  2044. if ((Arch == llvm::Triple::aarch64 ||
  2045. Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
  2046. mangleAArch64NeonVectorType(T);
  2047. else
  2048. mangleNeonVectorType(T);
  2049. return;
  2050. }
  2051. Out << "Dv" << T->getNumElements() << '_';
  2052. if (T->getVectorKind() == VectorType::AltiVecPixel)
  2053. Out << 'p';
  2054. else if (T->getVectorKind() == VectorType::AltiVecBool)
  2055. Out << 'b';
  2056. else
  2057. mangleType(T->getElementType());
  2058. }
  2059. void CXXNameMangler::mangleType(const ExtVectorType *T) {
  2060. mangleType(static_cast<const VectorType*>(T));
  2061. }
  2062. void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
  2063. Out << "Dv";
  2064. mangleExpression(T->getSizeExpr());
  2065. Out << '_';
  2066. mangleType(T->getElementType());
  2067. }
  2068. void CXXNameMangler::mangleType(const PackExpansionType *T) {
  2069. // <type> ::= Dp <type> # pack expansion (C++0x)
  2070. Out << "Dp";
  2071. mangleType(T->getPattern());
  2072. }
  2073. void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
  2074. mangleSourceName(T->getDecl()->getIdentifier());
  2075. }
  2076. void CXXNameMangler::mangleType(const ObjCObjectType *T) {
  2077. // Treat __kindof as a vendor extended type qualifier.
  2078. if (T->isKindOfType())
  2079. Out << "U8__kindof";
  2080. if (!T->qual_empty()) {
  2081. // Mangle protocol qualifiers.
  2082. SmallString<64> QualStr;
  2083. llvm::raw_svector_ostream QualOS(QualStr);
  2084. QualOS << "objcproto";
  2085. for (const auto *I : T->quals()) {
  2086. StringRef name = I->getName();
  2087. QualOS << name.size() << name;
  2088. }
  2089. QualOS.flush();
  2090. Out << 'U' << QualStr.size() << QualStr;
  2091. }
  2092. mangleType(T->getBaseType());
  2093. if (T->isSpecialized()) {
  2094. // Mangle type arguments as I <type>+ E
  2095. Out << 'I';
  2096. for (auto typeArg : T->getTypeArgs())
  2097. mangleType(typeArg);
  2098. Out << 'E';
  2099. }
  2100. }
  2101. void CXXNameMangler::mangleType(const BlockPointerType *T) {
  2102. Out << "U13block_pointer";
  2103. mangleType(T->getPointeeType());
  2104. }
  2105. void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
  2106. // Mangle injected class name types as if the user had written the
  2107. // specialization out fully. It may not actually be possible to see
  2108. // this mangling, though.
  2109. mangleType(T->getInjectedSpecializationType());
  2110. }
  2111. void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
  2112. if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
  2113. mangleName(TD, T->getArgs(), T->getNumArgs());
  2114. } else {
  2115. if (mangleSubstitution(QualType(T, 0)))
  2116. return;
  2117. mangleTemplatePrefix(T->getTemplateName());
  2118. // FIXME: GCC does not appear to mangle the template arguments when
  2119. // the template in question is a dependent template name. Should we
  2120. // emulate that badness?
  2121. mangleTemplateArgs(T->getArgs(), T->getNumArgs());
  2122. addSubstitution(QualType(T, 0));
  2123. }
  2124. }
  2125. void CXXNameMangler::mangleType(const DependentNameType *T) {
  2126. // Proposal by cxx-abi-dev, 2014-03-26
  2127. // <class-enum-type> ::= <name> # non-dependent or dependent type name or
  2128. // # dependent elaborated type specifier using
  2129. // # 'typename'
  2130. // ::= Ts <name> # dependent elaborated type specifier using
  2131. // # 'struct' or 'class'
  2132. // ::= Tu <name> # dependent elaborated type specifier using
  2133. // # 'union'
  2134. // ::= Te <name> # dependent elaborated type specifier using
  2135. // # 'enum'
  2136. switch (T->getKeyword()) {
  2137. case ETK_Typename:
  2138. break;
  2139. case ETK_Struct:
  2140. case ETK_Class:
  2141. case ETK_Interface:
  2142. Out << "Ts";
  2143. break;
  2144. case ETK_Union:
  2145. Out << "Tu";
  2146. break;
  2147. case ETK_Enum:
  2148. Out << "Te";
  2149. break;
  2150. default:
  2151. llvm_unreachable("unexpected keyword for dependent type name");
  2152. }
  2153. // Typename types are always nested
  2154. Out << 'N';
  2155. manglePrefix(T->getQualifier());
  2156. mangleSourceName(T->getIdentifier());
  2157. Out << 'E';
  2158. }
  2159. void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
  2160. // Dependently-scoped template types are nested if they have a prefix.
  2161. Out << 'N';
  2162. // TODO: avoid making this TemplateName.
  2163. TemplateName Prefix =
  2164. getASTContext().getDependentTemplateName(T->getQualifier(),
  2165. T->getIdentifier());
  2166. mangleTemplatePrefix(Prefix);
  2167. // FIXME: GCC does not appear to mangle the template arguments when
  2168. // the template in question is a dependent template name. Should we
  2169. // emulate that badness?
  2170. mangleTemplateArgs(T->getArgs(), T->getNumArgs());
  2171. Out << 'E';
  2172. }
  2173. void CXXNameMangler::mangleType(const TypeOfType *T) {
  2174. // FIXME: this is pretty unsatisfactory, but there isn't an obvious
  2175. // "extension with parameters" mangling.
  2176. Out << "u6typeof";
  2177. }
  2178. void CXXNameMangler::mangleType(const TypeOfExprType *T) {
  2179. // FIXME: this is pretty unsatisfactory, but there isn't an obvious
  2180. // "extension with parameters" mangling.
  2181. Out << "u6typeof";
  2182. }
  2183. void CXXNameMangler::mangleType(const DecltypeType *T) {
  2184. Expr *E = T->getUnderlyingExpr();
  2185. // type ::= Dt <expression> E # decltype of an id-expression
  2186. // # or class member access
  2187. // ::= DT <expression> E # decltype of an expression
  2188. // This purports to be an exhaustive list of id-expressions and
  2189. // class member accesses. Note that we do not ignore parentheses;
  2190. // parentheses change the semantics of decltype for these
  2191. // expressions (and cause the mangler to use the other form).
  2192. if (isa<DeclRefExpr>(E) ||
  2193. isa<MemberExpr>(E) ||
  2194. isa<UnresolvedLookupExpr>(E) ||
  2195. isa<DependentScopeDeclRefExpr>(E) ||
  2196. isa<CXXDependentScopeMemberExpr>(E) ||
  2197. isa<UnresolvedMemberExpr>(E))
  2198. Out << "Dt";
  2199. else
  2200. Out << "DT";
  2201. mangleExpression(E);
  2202. Out << 'E';
  2203. }
  2204. void CXXNameMangler::mangleType(const UnaryTransformType *T) {
  2205. // If this is dependent, we need to record that. If not, we simply
  2206. // mangle it as the underlying type since they are equivalent.
  2207. if (T->isDependentType()) {
  2208. Out << 'U';
  2209. switch (T->getUTTKind()) {
  2210. case UnaryTransformType::EnumUnderlyingType:
  2211. Out << "3eut";
  2212. break;
  2213. }
  2214. }
  2215. mangleType(T->getUnderlyingType());
  2216. }
  2217. void CXXNameMangler::mangleType(const AutoType *T) {
  2218. QualType D = T->getDeducedType();
  2219. // <builtin-type> ::= Da # dependent auto
  2220. if (D.isNull())
  2221. Out << (T->isDecltypeAuto() ? "Dc" : "Da");
  2222. else
  2223. mangleType(D);
  2224. }
  2225. void CXXNameMangler::mangleType(const AtomicType *T) {
  2226. // <type> ::= U <source-name> <type> # vendor extended type qualifier
  2227. // (Until there's a standardized mangling...)
  2228. Out << "U7_Atomic";
  2229. mangleType(T->getValueType());
  2230. }
  2231. void CXXNameMangler::mangleIntegerLiteral(QualType T,
  2232. const llvm::APSInt &Value) {
  2233. // <expr-primary> ::= L <type> <value number> E # integer literal
  2234. Out << 'L';
  2235. mangleType(T);
  2236. if (T->isBooleanType()) {
  2237. // Boolean values are encoded as 0/1.
  2238. Out << (Value.getBoolValue() ? '1' : '0');
  2239. } else {
  2240. mangleNumber(Value);
  2241. }
  2242. Out << 'E';
  2243. }
  2244. void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
  2245. // Ignore member expressions involving anonymous unions.
  2246. while (const auto *RT = Base->getType()->getAs<RecordType>()) {
  2247. if (!RT->getDecl()->isAnonymousStructOrUnion())
  2248. break;
  2249. const auto *ME = dyn_cast<MemberExpr>(Base);
  2250. if (!ME)
  2251. break;
  2252. Base = ME->getBase();
  2253. IsArrow = ME->isArrow();
  2254. }
  2255. if (Base->isImplicitCXXThis()) {
  2256. // Note: GCC mangles member expressions to the implicit 'this' as
  2257. // *this., whereas we represent them as this->. The Itanium C++ ABI
  2258. // does not specify anything here, so we follow GCC.
  2259. Out << "dtdefpT";
  2260. } else {
  2261. Out << (IsArrow ? "pt" : "dt");
  2262. mangleExpression(Base);
  2263. }
  2264. }
  2265. /// Mangles a member expression.
  2266. void CXXNameMangler::mangleMemberExpr(const Expr *base,
  2267. bool isArrow,
  2268. NestedNameSpecifier *qualifier,
  2269. NamedDecl *firstQualifierLookup,
  2270. DeclarationName member,
  2271. unsigned arity) {
  2272. // <expression> ::= dt <expression> <unresolved-name>
  2273. // ::= pt <expression> <unresolved-name>
  2274. if (base)
  2275. mangleMemberExprBase(base, isArrow);
  2276. mangleUnresolvedName(qualifier, member, arity);
  2277. }
  2278. /// Look at the callee of the given call expression and determine if
  2279. /// it's a parenthesized id-expression which would have triggered ADL
  2280. /// otherwise.
  2281. static bool isParenthesizedADLCallee(const CallExpr *call) {
  2282. const Expr *callee = call->getCallee();
  2283. const Expr *fn = callee->IgnoreParens();
  2284. // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
  2285. // too, but for those to appear in the callee, it would have to be
  2286. // parenthesized.
  2287. if (callee == fn) return false;
  2288. // Must be an unresolved lookup.
  2289. const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
  2290. if (!lookup) return false;
  2291. assert(!lookup->requiresADL());
  2292. // Must be an unqualified lookup.
  2293. if (lookup->getQualifier()) return false;
  2294. // Must not have found a class member. Note that if one is a class
  2295. // member, they're all class members.
  2296. if (lookup->getNumDecls() > 0 &&
  2297. (*lookup->decls_begin())->isCXXClassMember())
  2298. return false;
  2299. // Otherwise, ADL would have been triggered.
  2300. return true;
  2301. }
  2302. void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
  2303. const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
  2304. Out << CastEncoding;
  2305. mangleType(ECE->getType());
  2306. mangleExpression(ECE->getSubExpr());
  2307. }
  2308. void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
  2309. if (auto *Syntactic = InitList->getSyntacticForm())
  2310. InitList = Syntactic;
  2311. for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
  2312. mangleExpression(InitList->getInit(i));
  2313. }
  2314. void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
  2315. // <expression> ::= <unary operator-name> <expression>
  2316. // ::= <binary operator-name> <expression> <expression>
  2317. // ::= <trinary operator-name> <expression> <expression> <expression>
  2318. // ::= cv <type> expression # conversion with one argument
  2319. // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
  2320. // ::= dc <type> <expression> # dynamic_cast<type> (expression)
  2321. // ::= sc <type> <expression> # static_cast<type> (expression)
  2322. // ::= cc <type> <expression> # const_cast<type> (expression)
  2323. // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
  2324. // ::= st <type> # sizeof (a type)
  2325. // ::= at <type> # alignof (a type)
  2326. // ::= <template-param>
  2327. // ::= <function-param>
  2328. // ::= sr <type> <unqualified-name> # dependent name
  2329. // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
  2330. // ::= ds <expression> <expression> # expr.*expr
  2331. // ::= sZ <template-param> # size of a parameter pack
  2332. // ::= sZ <function-param> # size of a function parameter pack
  2333. // ::= <expr-primary>
  2334. // <expr-primary> ::= L <type> <value number> E # integer literal
  2335. // ::= L <type <value float> E # floating literal
  2336. // ::= L <mangled-name> E # external name
  2337. // ::= fpT # 'this' expression
  2338. QualType ImplicitlyConvertedToType;
  2339. recurse:
  2340. switch (E->getStmtClass()) {
  2341. case Expr::NoStmtClass:
  2342. #define ABSTRACT_STMT(Type)
  2343. #define EXPR(Type, Base)
  2344. #define STMT(Type, Base) \
  2345. case Expr::Type##Class:
  2346. #include "clang/AST/StmtNodes.inc"
  2347. // fallthrough
  2348. // These all can only appear in local or variable-initialization
  2349. // contexts and so should never appear in a mangling.
  2350. case Expr::AddrLabelExprClass:
  2351. case Expr::DesignatedInitUpdateExprClass:
  2352. case Expr::ImplicitValueInitExprClass:
  2353. case Expr::NoInitExprClass:
  2354. case Expr::ParenListExprClass:
  2355. case Expr::LambdaExprClass:
  2356. case Expr::MSPropertyRefExprClass:
  2357. case Expr::TypoExprClass: // This should no longer exist in the AST by now.
  2358. llvm_unreachable("unexpected statement kind");
  2359. // FIXME: invent manglings for all these.
  2360. case Expr::BlockExprClass:
  2361. case Expr::ChooseExprClass:
  2362. case Expr::CompoundLiteralExprClass:
  2363. case Expr::DesignatedInitExprClass:
  2364. case Expr::ExtVectorElementExprClass:
  2365. case Expr::ExtMatrixElementExprClass: // HLSL Change
  2366. case Expr::HLSLVectorElementExprClass: // HLSL Change
  2367. case Expr::GenericSelectionExprClass:
  2368. case Expr::ObjCEncodeExprClass:
  2369. case Expr::ObjCIsaExprClass:
  2370. case Expr::ObjCIvarRefExprClass:
  2371. case Expr::ObjCMessageExprClass:
  2372. case Expr::ObjCPropertyRefExprClass:
  2373. case Expr::ObjCProtocolExprClass:
  2374. case Expr::ObjCSelectorExprClass:
  2375. case Expr::ObjCStringLiteralClass:
  2376. case Expr::ObjCBoxedExprClass:
  2377. case Expr::ObjCArrayLiteralClass:
  2378. case Expr::ObjCDictionaryLiteralClass:
  2379. case Expr::ObjCSubscriptRefExprClass:
  2380. case Expr::ObjCIndirectCopyRestoreExprClass:
  2381. case Expr::OffsetOfExprClass:
  2382. case Expr::PredefinedExprClass:
  2383. case Expr::ShuffleVectorExprClass:
  2384. case Expr::ConvertVectorExprClass:
  2385. case Expr::StmtExprClass:
  2386. case Expr::TypeTraitExprClass:
  2387. case Expr::ArrayTypeTraitExprClass:
  2388. case Expr::ExpressionTraitExprClass:
  2389. case Expr::VAArgExprClass:
  2390. case Expr::CUDAKernelCallExprClass:
  2391. case Expr::AsTypeExprClass:
  2392. case Expr::PseudoObjectExprClass:
  2393. case Expr::AtomicExprClass:
  2394. {
  2395. // As bad as this diagnostic is, it's better than crashing.
  2396. DiagnosticsEngine &Diags = Context.getDiags();
  2397. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2398. "cannot yet mangle expression type %0");
  2399. Diags.Report(E->getExprLoc(), DiagID)
  2400. << E->getStmtClassName() << E->getSourceRange();
  2401. break;
  2402. }
  2403. case Expr::CXXUuidofExprClass: {
  2404. const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
  2405. if (UE->isTypeOperand()) {
  2406. QualType UuidT = UE->getTypeOperand(Context.getASTContext());
  2407. Out << "u8__uuidoft";
  2408. mangleType(UuidT);
  2409. } else {
  2410. Expr *UuidExp = UE->getExprOperand();
  2411. Out << "u8__uuidofz";
  2412. mangleExpression(UuidExp, Arity);
  2413. }
  2414. break;
  2415. }
  2416. // Even gcc-4.5 doesn't mangle this.
  2417. case Expr::BinaryConditionalOperatorClass: {
  2418. DiagnosticsEngine &Diags = Context.getDiags();
  2419. unsigned DiagID =
  2420. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2421. "?: operator with omitted middle operand cannot be mangled");
  2422. Diags.Report(E->getExprLoc(), DiagID)
  2423. << E->getStmtClassName() << E->getSourceRange();
  2424. break;
  2425. }
  2426. // These are used for internal purposes and cannot be meaningfully mangled.
  2427. case Expr::OpaqueValueExprClass:
  2428. llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
  2429. case Expr::InitListExprClass: {
  2430. Out << "il";
  2431. mangleInitListElements(cast<InitListExpr>(E));
  2432. Out << "E";
  2433. break;
  2434. }
  2435. case Expr::CXXDefaultArgExprClass:
  2436. mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
  2437. break;
  2438. case Expr::CXXDefaultInitExprClass:
  2439. mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
  2440. break;
  2441. case Expr::CXXStdInitializerListExprClass:
  2442. mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
  2443. break;
  2444. case Expr::SubstNonTypeTemplateParmExprClass:
  2445. mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
  2446. Arity);
  2447. break;
  2448. case Expr::UserDefinedLiteralClass:
  2449. // We follow g++'s approach of mangling a UDL as a call to the literal
  2450. // operator.
  2451. case Expr::CXXMemberCallExprClass: // fallthrough
  2452. case Expr::CallExprClass: {
  2453. const CallExpr *CE = cast<CallExpr>(E);
  2454. // <expression> ::= cp <simple-id> <expression>* E
  2455. // We use this mangling only when the call would use ADL except
  2456. // for being parenthesized. Per discussion with David
  2457. // Vandervoorde, 2011.04.25.
  2458. if (isParenthesizedADLCallee(CE)) {
  2459. Out << "cp";
  2460. // The callee here is a parenthesized UnresolvedLookupExpr with
  2461. // no qualifier and should always get mangled as a <simple-id>
  2462. // anyway.
  2463. // <expression> ::= cl <expression>* E
  2464. } else {
  2465. Out << "cl";
  2466. }
  2467. unsigned CallArity = CE->getNumArgs();
  2468. for (const Expr *Arg : CE->arguments())
  2469. if (isa<PackExpansionExpr>(Arg))
  2470. CallArity = UnknownArity;
  2471. mangleExpression(CE->getCallee(), CallArity);
  2472. for (const Expr *Arg : CE->arguments())
  2473. mangleExpression(Arg);
  2474. Out << 'E';
  2475. break;
  2476. }
  2477. case Expr::CXXNewExprClass: {
  2478. const CXXNewExpr *New = cast<CXXNewExpr>(E);
  2479. if (New->isGlobalNew()) Out << "gs";
  2480. Out << (New->isArray() ? "na" : "nw");
  2481. for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
  2482. E = New->placement_arg_end(); I != E; ++I)
  2483. mangleExpression(*I);
  2484. Out << '_';
  2485. mangleType(New->getAllocatedType());
  2486. if (New->hasInitializer()) {
  2487. if (New->getInitializationStyle() == CXXNewExpr::ListInit)
  2488. Out << "il";
  2489. else
  2490. Out << "pi";
  2491. const Expr *Init = New->getInitializer();
  2492. if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
  2493. // Directly inline the initializers.
  2494. for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
  2495. E = CCE->arg_end();
  2496. I != E; ++I)
  2497. mangleExpression(*I);
  2498. } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
  2499. for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
  2500. mangleExpression(PLE->getExpr(i));
  2501. } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
  2502. isa<InitListExpr>(Init)) {
  2503. // Only take InitListExprs apart for list-initialization.
  2504. mangleInitListElements(cast<InitListExpr>(Init));
  2505. } else
  2506. mangleExpression(Init);
  2507. }
  2508. Out << 'E';
  2509. break;
  2510. }
  2511. case Expr::CXXPseudoDestructorExprClass: {
  2512. const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
  2513. if (const Expr *Base = PDE->getBase())
  2514. mangleMemberExprBase(Base, PDE->isArrow());
  2515. NestedNameSpecifier *Qualifier = PDE->getQualifier();
  2516. QualType ScopeType;
  2517. if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
  2518. if (Qualifier) {
  2519. mangleUnresolvedPrefix(Qualifier,
  2520. /*Recursive=*/true);
  2521. mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
  2522. Out << 'E';
  2523. } else {
  2524. Out << "sr";
  2525. if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
  2526. Out << 'E';
  2527. }
  2528. } else if (Qualifier) {
  2529. mangleUnresolvedPrefix(Qualifier);
  2530. }
  2531. // <base-unresolved-name> ::= dn <destructor-name>
  2532. Out << "dn";
  2533. QualType DestroyedType = PDE->getDestroyedType();
  2534. mangleUnresolvedTypeOrSimpleId(DestroyedType);
  2535. break;
  2536. }
  2537. case Expr::MemberExprClass: {
  2538. const MemberExpr *ME = cast<MemberExpr>(E);
  2539. mangleMemberExpr(ME->getBase(), ME->isArrow(),
  2540. ME->getQualifier(), nullptr,
  2541. ME->getMemberDecl()->getDeclName(), Arity);
  2542. break;
  2543. }
  2544. case Expr::UnresolvedMemberExprClass: {
  2545. const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
  2546. mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
  2547. ME->isArrow(), ME->getQualifier(), nullptr,
  2548. ME->getMemberName(), Arity);
  2549. if (ME->hasExplicitTemplateArgs())
  2550. mangleTemplateArgs(ME->getExplicitTemplateArgs());
  2551. break;
  2552. }
  2553. case Expr::CXXDependentScopeMemberExprClass: {
  2554. const CXXDependentScopeMemberExpr *ME
  2555. = cast<CXXDependentScopeMemberExpr>(E);
  2556. mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
  2557. ME->isArrow(), ME->getQualifier(),
  2558. ME->getFirstQualifierFoundInScope(),
  2559. ME->getMember(), Arity);
  2560. if (ME->hasExplicitTemplateArgs())
  2561. mangleTemplateArgs(ME->getExplicitTemplateArgs());
  2562. break;
  2563. }
  2564. case Expr::UnresolvedLookupExprClass: {
  2565. const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
  2566. mangleUnresolvedName(ULE->getQualifier(), ULE->getName(), Arity);
  2567. // All the <unresolved-name> productions end in a
  2568. // base-unresolved-name, where <template-args> are just tacked
  2569. // onto the end.
  2570. if (ULE->hasExplicitTemplateArgs())
  2571. mangleTemplateArgs(ULE->getExplicitTemplateArgs());
  2572. break;
  2573. }
  2574. case Expr::CXXUnresolvedConstructExprClass: {
  2575. const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
  2576. unsigned N = CE->arg_size();
  2577. Out << "cv";
  2578. mangleType(CE->getType());
  2579. if (N != 1) Out << '_';
  2580. for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
  2581. if (N != 1) Out << 'E';
  2582. break;
  2583. }
  2584. case Expr::CXXConstructExprClass: {
  2585. const auto *CE = cast<CXXConstructExpr>(E);
  2586. if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
  2587. assert(
  2588. CE->getNumArgs() >= 1 &&
  2589. (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
  2590. "implicit CXXConstructExpr must have one argument");
  2591. return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
  2592. }
  2593. Out << "il";
  2594. for (auto *E : CE->arguments())
  2595. mangleExpression(E);
  2596. Out << "E";
  2597. break;
  2598. }
  2599. case Expr::CXXTemporaryObjectExprClass: {
  2600. const auto *CE = cast<CXXTemporaryObjectExpr>(E);
  2601. unsigned N = CE->getNumArgs();
  2602. bool List = CE->isListInitialization();
  2603. if (List)
  2604. Out << "tl";
  2605. else
  2606. Out << "cv";
  2607. mangleType(CE->getType());
  2608. if (!List && N != 1)
  2609. Out << '_';
  2610. if (CE->isStdInitListInitialization()) {
  2611. // We implicitly created a std::initializer_list<T> for the first argument
  2612. // of a constructor of type U in an expression of the form U{a, b, c}.
  2613. // Strip all the semantic gunk off the initializer list.
  2614. auto *SILE =
  2615. cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
  2616. auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
  2617. mangleInitListElements(ILE);
  2618. } else {
  2619. for (auto *E : CE->arguments())
  2620. mangleExpression(E);
  2621. }
  2622. if (List || N != 1)
  2623. Out << 'E';
  2624. break;
  2625. }
  2626. case Expr::CXXScalarValueInitExprClass:
  2627. Out << "cv";
  2628. mangleType(E->getType());
  2629. Out << "_E";
  2630. break;
  2631. case Expr::CXXNoexceptExprClass:
  2632. Out << "nx";
  2633. mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
  2634. break;
  2635. case Expr::UnaryExprOrTypeTraitExprClass: {
  2636. const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
  2637. if (!SAE->isInstantiationDependent()) {
  2638. // Itanium C++ ABI:
  2639. // If the operand of a sizeof or alignof operator is not
  2640. // instantiation-dependent it is encoded as an integer literal
  2641. // reflecting the result of the operator.
  2642. //
  2643. // If the result of the operator is implicitly converted to a known
  2644. // integer type, that type is used for the literal; otherwise, the type
  2645. // of std::size_t or std::ptrdiff_t is used.
  2646. QualType T = (ImplicitlyConvertedToType.isNull() ||
  2647. !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
  2648. : ImplicitlyConvertedToType;
  2649. llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
  2650. mangleIntegerLiteral(T, V);
  2651. break;
  2652. }
  2653. switch(SAE->getKind()) {
  2654. case UETT_SizeOf:
  2655. Out << 's';
  2656. break;
  2657. case UETT_AlignOf:
  2658. Out << 'a';
  2659. break;
  2660. case UETT_VecStep: {
  2661. DiagnosticsEngine &Diags = Context.getDiags();
  2662. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2663. "cannot yet mangle vec_step expression");
  2664. Diags.Report(DiagID);
  2665. return;
  2666. }
  2667. case UETT_OpenMPRequiredSimdAlign:
  2668. DiagnosticsEngine &Diags = Context.getDiags();
  2669. unsigned DiagID = Diags.getCustomDiagID(
  2670. DiagnosticsEngine::Error,
  2671. "cannot yet mangle __builtin_omp_required_simd_align expression");
  2672. Diags.Report(DiagID);
  2673. return;
  2674. }
  2675. if (SAE->isArgumentType()) {
  2676. Out << 't';
  2677. mangleType(SAE->getArgumentType());
  2678. } else {
  2679. Out << 'z';
  2680. mangleExpression(SAE->getArgumentExpr());
  2681. }
  2682. break;
  2683. }
  2684. case Expr::CXXThrowExprClass: {
  2685. const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
  2686. // <expression> ::= tw <expression> # throw expression
  2687. // ::= tr # rethrow
  2688. if (TE->getSubExpr()) {
  2689. Out << "tw";
  2690. mangleExpression(TE->getSubExpr());
  2691. } else {
  2692. Out << "tr";
  2693. }
  2694. break;
  2695. }
  2696. case Expr::CXXTypeidExprClass: {
  2697. const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
  2698. // <expression> ::= ti <type> # typeid (type)
  2699. // ::= te <expression> # typeid (expression)
  2700. if (TIE->isTypeOperand()) {
  2701. Out << "ti";
  2702. mangleType(TIE->getTypeOperand(Context.getASTContext()));
  2703. } else {
  2704. Out << "te";
  2705. mangleExpression(TIE->getExprOperand());
  2706. }
  2707. break;
  2708. }
  2709. case Expr::CXXDeleteExprClass: {
  2710. const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
  2711. // <expression> ::= [gs] dl <expression> # [::] delete expr
  2712. // ::= [gs] da <expression> # [::] delete [] expr
  2713. if (DE->isGlobalDelete()) Out << "gs";
  2714. Out << (DE->isArrayForm() ? "da" : "dl");
  2715. mangleExpression(DE->getArgument());
  2716. break;
  2717. }
  2718. case Expr::UnaryOperatorClass: {
  2719. const UnaryOperator *UO = cast<UnaryOperator>(E);
  2720. mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
  2721. /*Arity=*/1);
  2722. mangleExpression(UO->getSubExpr());
  2723. break;
  2724. }
  2725. case Expr::ArraySubscriptExprClass: {
  2726. const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
  2727. // Array subscript is treated as a syntactically weird form of
  2728. // binary operator.
  2729. Out << "ix";
  2730. mangleExpression(AE->getLHS());
  2731. mangleExpression(AE->getRHS());
  2732. break;
  2733. }
  2734. case Expr::CompoundAssignOperatorClass: // fallthrough
  2735. case Expr::BinaryOperatorClass: {
  2736. const BinaryOperator *BO = cast<BinaryOperator>(E);
  2737. if (BO->getOpcode() == BO_PtrMemD)
  2738. Out << "ds";
  2739. else
  2740. mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
  2741. /*Arity=*/2);
  2742. mangleExpression(BO->getLHS());
  2743. mangleExpression(BO->getRHS());
  2744. break;
  2745. }
  2746. case Expr::ConditionalOperatorClass: {
  2747. const ConditionalOperator *CO = cast<ConditionalOperator>(E);
  2748. mangleOperatorName(OO_Conditional, /*Arity=*/3);
  2749. mangleExpression(CO->getCond());
  2750. mangleExpression(CO->getLHS(), Arity);
  2751. mangleExpression(CO->getRHS(), Arity);
  2752. break;
  2753. }
  2754. case Expr::ImplicitCastExprClass: {
  2755. ImplicitlyConvertedToType = E->getType();
  2756. E = cast<ImplicitCastExpr>(E)->getSubExpr();
  2757. goto recurse;
  2758. }
  2759. case Expr::ObjCBridgedCastExprClass: {
  2760. // Mangle ownership casts as a vendor extended operator __bridge,
  2761. // __bridge_transfer, or __bridge_retain.
  2762. StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
  2763. Out << "v1U" << Kind.size() << Kind;
  2764. }
  2765. // Fall through to mangle the cast itself.
  2766. case Expr::CStyleCastExprClass:
  2767. mangleCastExpression(E, "cv");
  2768. break;
  2769. case Expr::CXXFunctionalCastExprClass: {
  2770. auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
  2771. // FIXME: Add isImplicit to CXXConstructExpr.
  2772. if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
  2773. if (CCE->getParenOrBraceRange().isInvalid())
  2774. Sub = CCE->getArg(0)->IgnoreImplicit();
  2775. if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
  2776. Sub = StdInitList->getSubExpr()->IgnoreImplicit();
  2777. if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
  2778. Out << "tl";
  2779. mangleType(E->getType());
  2780. mangleInitListElements(IL);
  2781. Out << "E";
  2782. } else {
  2783. mangleCastExpression(E, "cv");
  2784. }
  2785. break;
  2786. }
  2787. case Expr::CXXStaticCastExprClass:
  2788. mangleCastExpression(E, "sc");
  2789. break;
  2790. case Expr::CXXDynamicCastExprClass:
  2791. mangleCastExpression(E, "dc");
  2792. break;
  2793. case Expr::CXXReinterpretCastExprClass:
  2794. mangleCastExpression(E, "rc");
  2795. break;
  2796. case Expr::CXXConstCastExprClass:
  2797. mangleCastExpression(E, "cc");
  2798. break;
  2799. case Expr::CXXOperatorCallExprClass: {
  2800. const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
  2801. unsigned NumArgs = CE->getNumArgs();
  2802. mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
  2803. // Mangle the arguments.
  2804. for (unsigned i = 0; i != NumArgs; ++i)
  2805. mangleExpression(CE->getArg(i));
  2806. break;
  2807. }
  2808. case Expr::ParenExprClass:
  2809. mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
  2810. break;
  2811. case Expr::DeclRefExprClass: {
  2812. const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
  2813. switch (D->getKind()) {
  2814. default:
  2815. // <expr-primary> ::= L <mangled-name> E # external name
  2816. Out << 'L';
  2817. mangle(D);
  2818. Out << 'E';
  2819. break;
  2820. case Decl::ParmVar:
  2821. mangleFunctionParam(cast<ParmVarDecl>(D));
  2822. break;
  2823. case Decl::EnumConstant: {
  2824. const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
  2825. mangleIntegerLiteral(ED->getType(), ED->getInitVal());
  2826. break;
  2827. }
  2828. case Decl::NonTypeTemplateParm: {
  2829. const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
  2830. mangleTemplateParameter(PD->getIndex());
  2831. break;
  2832. }
  2833. }
  2834. break;
  2835. }
  2836. case Expr::SubstNonTypeTemplateParmPackExprClass:
  2837. // FIXME: not clear how to mangle this!
  2838. // template <unsigned N...> class A {
  2839. // template <class U...> void foo(U (&x)[N]...);
  2840. // };
  2841. Out << "_SUBSTPACK_";
  2842. break;
  2843. case Expr::FunctionParmPackExprClass: {
  2844. // FIXME: not clear how to mangle this!
  2845. const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
  2846. Out << "v110_SUBSTPACK";
  2847. mangleFunctionParam(FPPE->getParameterPack());
  2848. break;
  2849. }
  2850. case Expr::DependentScopeDeclRefExprClass: {
  2851. const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
  2852. mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(), Arity);
  2853. // All the <unresolved-name> productions end in a
  2854. // base-unresolved-name, where <template-args> are just tacked
  2855. // onto the end.
  2856. if (DRE->hasExplicitTemplateArgs())
  2857. mangleTemplateArgs(DRE->getExplicitTemplateArgs());
  2858. break;
  2859. }
  2860. case Expr::CXXBindTemporaryExprClass:
  2861. mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
  2862. break;
  2863. case Expr::ExprWithCleanupsClass:
  2864. mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
  2865. break;
  2866. case Expr::FloatingLiteralClass: {
  2867. const FloatingLiteral *FL = cast<FloatingLiteral>(E);
  2868. Out << 'L';
  2869. mangleType(FL->getType());
  2870. mangleFloat(FL->getValue());
  2871. Out << 'E';
  2872. break;
  2873. }
  2874. case Expr::CharacterLiteralClass:
  2875. Out << 'L';
  2876. mangleType(E->getType());
  2877. Out << cast<CharacterLiteral>(E)->getValue();
  2878. Out << 'E';
  2879. break;
  2880. // FIXME. __objc_yes/__objc_no are mangled same as true/false
  2881. case Expr::ObjCBoolLiteralExprClass:
  2882. Out << "Lb";
  2883. Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
  2884. Out << 'E';
  2885. break;
  2886. case Expr::CXXBoolLiteralExprClass:
  2887. Out << "Lb";
  2888. Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
  2889. Out << 'E';
  2890. break;
  2891. case Expr::IntegerLiteralClass: {
  2892. llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
  2893. if (E->getType()->isSignedIntegerType())
  2894. Value.setIsSigned(true);
  2895. mangleIntegerLiteral(E->getType(), Value);
  2896. break;
  2897. }
  2898. case Expr::ImaginaryLiteralClass: {
  2899. const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
  2900. // Mangle as if a complex literal.
  2901. // Proposal from David Vandevoorde, 2010.06.30.
  2902. Out << 'L';
  2903. mangleType(E->getType());
  2904. if (const FloatingLiteral *Imag =
  2905. dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
  2906. // Mangle a floating-point zero of the appropriate type.
  2907. mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
  2908. Out << '_';
  2909. mangleFloat(Imag->getValue());
  2910. } else {
  2911. Out << "0_";
  2912. llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
  2913. if (IE->getSubExpr()->getType()->isSignedIntegerType())
  2914. Value.setIsSigned(true);
  2915. mangleNumber(Value);
  2916. }
  2917. Out << 'E';
  2918. break;
  2919. }
  2920. case Expr::StringLiteralClass: {
  2921. // Revised proposal from David Vandervoorde, 2010.07.15.
  2922. Out << 'L';
  2923. assert(isa<ConstantArrayType>(E->getType()));
  2924. mangleType(E->getType());
  2925. Out << 'E';
  2926. break;
  2927. }
  2928. case Expr::GNUNullExprClass:
  2929. // FIXME: should this really be mangled the same as nullptr?
  2930. // fallthrough
  2931. case Expr::CXXNullPtrLiteralExprClass: {
  2932. Out << "LDnE";
  2933. break;
  2934. }
  2935. case Expr::PackExpansionExprClass:
  2936. Out << "sp";
  2937. mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
  2938. break;
  2939. case Expr::SizeOfPackExprClass: {
  2940. Out << "sZ";
  2941. const NamedDecl *Pack = cast<SizeOfPackExpr>(E)->getPack();
  2942. if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
  2943. mangleTemplateParameter(TTP->getIndex());
  2944. else if (const NonTypeTemplateParmDecl *NTTP
  2945. = dyn_cast<NonTypeTemplateParmDecl>(Pack))
  2946. mangleTemplateParameter(NTTP->getIndex());
  2947. else if (const TemplateTemplateParmDecl *TempTP
  2948. = dyn_cast<TemplateTemplateParmDecl>(Pack))
  2949. mangleTemplateParameter(TempTP->getIndex());
  2950. else
  2951. mangleFunctionParam(cast<ParmVarDecl>(Pack));
  2952. break;
  2953. }
  2954. case Expr::MaterializeTemporaryExprClass: {
  2955. mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
  2956. break;
  2957. }
  2958. case Expr::CXXFoldExprClass: {
  2959. auto *FE = cast<CXXFoldExpr>(E);
  2960. if (FE->isLeftFold())
  2961. Out << (FE->getInit() ? "fL" : "fl");
  2962. else
  2963. Out << (FE->getInit() ? "fR" : "fr");
  2964. if (FE->getOperator() == BO_PtrMemD)
  2965. Out << "ds";
  2966. else
  2967. mangleOperatorName(
  2968. BinaryOperator::getOverloadedOperator(FE->getOperator()),
  2969. /*Arity=*/2);
  2970. if (FE->getLHS())
  2971. mangleExpression(FE->getLHS());
  2972. if (FE->getRHS())
  2973. mangleExpression(FE->getRHS());
  2974. break;
  2975. }
  2976. case Expr::CXXThisExprClass:
  2977. Out << "fpT";
  2978. break;
  2979. }
  2980. }
  2981. /// Mangle an expression which refers to a parameter variable.
  2982. ///
  2983. /// <expression> ::= <function-param>
  2984. /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
  2985. /// <function-param> ::= fp <top-level CV-qualifiers>
  2986. /// <parameter-2 non-negative number> _ # L == 0, I > 0
  2987. /// <function-param> ::= fL <L-1 non-negative number>
  2988. /// p <top-level CV-qualifiers> _ # L > 0, I == 0
  2989. /// <function-param> ::= fL <L-1 non-negative number>
  2990. /// p <top-level CV-qualifiers>
  2991. /// <I-1 non-negative number> _ # L > 0, I > 0
  2992. ///
  2993. /// L is the nesting depth of the parameter, defined as 1 if the
  2994. /// parameter comes from the innermost function prototype scope
  2995. /// enclosing the current context, 2 if from the next enclosing
  2996. /// function prototype scope, and so on, with one special case: if
  2997. /// we've processed the full parameter clause for the innermost
  2998. /// function type, then L is one less. This definition conveniently
  2999. /// makes it irrelevant whether a function's result type was written
  3000. /// trailing or leading, but is otherwise overly complicated; the
  3001. /// numbering was first designed without considering references to
  3002. /// parameter in locations other than return types, and then the
  3003. /// mangling had to be generalized without changing the existing
  3004. /// manglings.
  3005. ///
  3006. /// I is the zero-based index of the parameter within its parameter
  3007. /// declaration clause. Note that the original ABI document describes
  3008. /// this using 1-based ordinals.
  3009. void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
  3010. unsigned parmDepth = parm->getFunctionScopeDepth();
  3011. unsigned parmIndex = parm->getFunctionScopeIndex();
  3012. // Compute 'L'.
  3013. // parmDepth does not include the declaring function prototype.
  3014. // FunctionTypeDepth does account for that.
  3015. assert(parmDepth < FunctionTypeDepth.getDepth());
  3016. unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
  3017. if (FunctionTypeDepth.isInResultType())
  3018. nestingDepth--;
  3019. if (nestingDepth == 0) {
  3020. Out << "fp";
  3021. } else {
  3022. Out << "fL" << (nestingDepth - 1) << 'p';
  3023. }
  3024. // Top-level qualifiers. We don't have to worry about arrays here,
  3025. // because parameters declared as arrays should already have been
  3026. // transformed to have pointer type. FIXME: apparently these don't
  3027. // get mangled if used as an rvalue of a known non-class type?
  3028. assert(!parm->getType()->isArrayType()
  3029. && "parameter's type is still an array type?");
  3030. mangleQualifiers(parm->getType().getQualifiers());
  3031. // Parameter index.
  3032. if (parmIndex != 0) {
  3033. Out << (parmIndex - 1);
  3034. }
  3035. Out << '_';
  3036. }
  3037. void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) {
  3038. // <ctor-dtor-name> ::= C1 # complete object constructor
  3039. // ::= C2 # base object constructor
  3040. //
  3041. // In addition, C5 is a comdat name with C1 and C2 in it.
  3042. switch (T) {
  3043. case Ctor_Complete:
  3044. Out << "C1";
  3045. break;
  3046. case Ctor_Base:
  3047. Out << "C2";
  3048. break;
  3049. case Ctor_Comdat:
  3050. Out << "C5";
  3051. break;
  3052. case Ctor_DefaultClosure:
  3053. case Ctor_CopyingClosure:
  3054. llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
  3055. }
  3056. }
  3057. void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
  3058. // <ctor-dtor-name> ::= D0 # deleting destructor
  3059. // ::= D1 # complete object destructor
  3060. // ::= D2 # base object destructor
  3061. //
  3062. // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
  3063. switch (T) {
  3064. case Dtor_Deleting:
  3065. Out << "D0";
  3066. break;
  3067. case Dtor_Complete:
  3068. Out << "D1";
  3069. break;
  3070. case Dtor_Base:
  3071. Out << "D2";
  3072. break;
  3073. case Dtor_Comdat:
  3074. Out << "D5";
  3075. break;
  3076. }
  3077. }
  3078. void CXXNameMangler::mangleTemplateArgs(
  3079. const ASTTemplateArgumentListInfo &TemplateArgs) {
  3080. // <template-args> ::= I <template-arg>+ E
  3081. Out << 'I';
  3082. for (unsigned i = 0, e = TemplateArgs.NumTemplateArgs; i != e; ++i)
  3083. mangleTemplateArg(TemplateArgs.getTemplateArgs()[i].getArgument());
  3084. Out << 'E';
  3085. }
  3086. void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
  3087. // <template-args> ::= I <template-arg>+ E
  3088. Out << 'I';
  3089. for (unsigned i = 0, e = AL.size(); i != e; ++i)
  3090. mangleTemplateArg(AL[i]);
  3091. Out << 'E';
  3092. }
  3093. void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
  3094. unsigned NumTemplateArgs) {
  3095. // <template-args> ::= I <template-arg>+ E
  3096. Out << 'I';
  3097. for (unsigned i = 0; i != NumTemplateArgs; ++i)
  3098. mangleTemplateArg(TemplateArgs[i]);
  3099. Out << 'E';
  3100. }
  3101. void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
  3102. // <template-arg> ::= <type> # type or template
  3103. // ::= X <expression> E # expression
  3104. // ::= <expr-primary> # simple expressions
  3105. // ::= J <template-arg>* E # argument pack
  3106. if (!A.isInstantiationDependent() || A.isDependent())
  3107. A = Context.getASTContext().getCanonicalTemplateArgument(A);
  3108. switch (A.getKind()) {
  3109. case TemplateArgument::Null:
  3110. llvm_unreachable("Cannot mangle NULL template argument");
  3111. case TemplateArgument::Type:
  3112. mangleType(A.getAsType());
  3113. break;
  3114. case TemplateArgument::Template:
  3115. // This is mangled as <type>.
  3116. mangleType(A.getAsTemplate());
  3117. break;
  3118. case TemplateArgument::TemplateExpansion:
  3119. // <type> ::= Dp <type> # pack expansion (C++0x)
  3120. Out << "Dp";
  3121. mangleType(A.getAsTemplateOrTemplatePattern());
  3122. break;
  3123. case TemplateArgument::Expression: {
  3124. // It's possible to end up with a DeclRefExpr here in certain
  3125. // dependent cases, in which case we should mangle as a
  3126. // declaration.
  3127. const Expr *E = A.getAsExpr()->IgnoreParens();
  3128. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  3129. const ValueDecl *D = DRE->getDecl();
  3130. if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
  3131. Out << 'L';
  3132. mangle(D);
  3133. Out << 'E';
  3134. break;
  3135. }
  3136. }
  3137. Out << 'X';
  3138. mangleExpression(E);
  3139. Out << 'E';
  3140. break;
  3141. }
  3142. case TemplateArgument::Integral:
  3143. mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
  3144. break;
  3145. case TemplateArgument::Declaration: {
  3146. // <expr-primary> ::= L <mangled-name> E # external name
  3147. // Clang produces AST's where pointer-to-member-function expressions
  3148. // and pointer-to-function expressions are represented as a declaration not
  3149. // an expression. We compensate for it here to produce the correct mangling.
  3150. ValueDecl *D = A.getAsDecl();
  3151. bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
  3152. if (compensateMangling) {
  3153. Out << 'X';
  3154. mangleOperatorName(OO_Amp, 1);
  3155. }
  3156. Out << 'L';
  3157. // References to external entities use the mangled name; if the name would
  3158. // not normally be manged then mangle it as unqualified.
  3159. mangle(D);
  3160. Out << 'E';
  3161. if (compensateMangling)
  3162. Out << 'E';
  3163. break;
  3164. }
  3165. case TemplateArgument::NullPtr: {
  3166. // <expr-primary> ::= L <type> 0 E
  3167. Out << 'L';
  3168. mangleType(A.getNullPtrType());
  3169. Out << "0E";
  3170. break;
  3171. }
  3172. case TemplateArgument::Pack: {
  3173. // <template-arg> ::= J <template-arg>* E
  3174. Out << 'J';
  3175. for (const auto &P : A.pack_elements())
  3176. mangleTemplateArg(P);
  3177. Out << 'E';
  3178. }
  3179. }
  3180. }
  3181. void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
  3182. // <template-param> ::= T_ # first template parameter
  3183. // ::= T <parameter-2 non-negative number> _
  3184. if (Index == 0)
  3185. Out << "T_";
  3186. else
  3187. Out << 'T' << (Index - 1) << '_';
  3188. }
  3189. void CXXNameMangler::mangleSeqID(unsigned SeqID) {
  3190. if (SeqID == 1)
  3191. Out << '0';
  3192. else if (SeqID > 1) {
  3193. SeqID--;
  3194. // <seq-id> is encoded in base-36, using digits and upper case letters.
  3195. char Buffer[7]; // log(2**32) / log(36) ~= 7
  3196. MutableArrayRef<char> BufferRef(Buffer);
  3197. MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
  3198. for (; SeqID != 0; SeqID /= 36) {
  3199. unsigned C = SeqID % 36;
  3200. *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
  3201. }
  3202. Out.write(I.base(), I - BufferRef.rbegin());
  3203. }
  3204. Out << '_';
  3205. }
  3206. void CXXNameMangler::mangleExistingSubstitution(QualType type) {
  3207. bool result = mangleSubstitution(type);
  3208. assert(result && "no existing substitution for type");
  3209. (void) result;
  3210. }
  3211. void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
  3212. bool result = mangleSubstitution(tname);
  3213. assert(result && "no existing substitution for template name");
  3214. (void) result;
  3215. }
  3216. // <substitution> ::= S <seq-id> _
  3217. // ::= S_
  3218. bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
  3219. // Try one of the standard substitutions first.
  3220. if (mangleStandardSubstitution(ND))
  3221. return true;
  3222. ND = cast<NamedDecl>(ND->getCanonicalDecl());
  3223. return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
  3224. }
  3225. /// Determine whether the given type has any qualifiers that are relevant for
  3226. /// substitutions.
  3227. static bool hasMangledSubstitutionQualifiers(QualType T) {
  3228. Qualifiers Qs = T.getQualifiers();
  3229. return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
  3230. }
  3231. bool CXXNameMangler::mangleSubstitution(QualType T) {
  3232. if (!hasMangledSubstitutionQualifiers(T)) {
  3233. if (const RecordType *RT = T->getAs<RecordType>())
  3234. return mangleSubstitution(RT->getDecl());
  3235. }
  3236. uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
  3237. return mangleSubstitution(TypePtr);
  3238. }
  3239. bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
  3240. if (TemplateDecl *TD = Template.getAsTemplateDecl())
  3241. return mangleSubstitution(TD);
  3242. Template = Context.getASTContext().getCanonicalTemplateName(Template);
  3243. return mangleSubstitution(
  3244. reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
  3245. }
  3246. bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
  3247. llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
  3248. if (I == Substitutions.end())
  3249. return false;
  3250. unsigned SeqID = I->second;
  3251. Out << 'S';
  3252. mangleSeqID(SeqID);
  3253. return true;
  3254. }
  3255. static bool isCharType(QualType T) {
  3256. if (T.isNull())
  3257. return false;
  3258. return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3259. T->isSpecificBuiltinType(BuiltinType::Char_U);
  3260. }
  3261. /// Returns whether a given type is a template specialization of a given name
  3262. /// with a single argument of type char.
  3263. static bool isCharSpecialization(QualType T, const char *Name) {
  3264. if (T.isNull())
  3265. return false;
  3266. const RecordType *RT = T->getAs<RecordType>();
  3267. if (!RT)
  3268. return false;
  3269. const ClassTemplateSpecializationDecl *SD =
  3270. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
  3271. if (!SD)
  3272. return false;
  3273. if (!isStdNamespace(getEffectiveDeclContext(SD)))
  3274. return false;
  3275. const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
  3276. if (TemplateArgs.size() != 1)
  3277. return false;
  3278. if (!isCharType(TemplateArgs[0].getAsType()))
  3279. return false;
  3280. return SD->getIdentifier()->getName() == Name;
  3281. }
  3282. template <std::size_t StrLen>
  3283. static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
  3284. const char (&Str)[StrLen]) {
  3285. if (!SD->getIdentifier()->isStr(Str))
  3286. return false;
  3287. const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
  3288. if (TemplateArgs.size() != 2)
  3289. return false;
  3290. if (!isCharType(TemplateArgs[0].getAsType()))
  3291. return false;
  3292. if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
  3293. return false;
  3294. return true;
  3295. }
  3296. bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
  3297. // <substitution> ::= St # ::std::
  3298. if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
  3299. if (isStd(NS)) {
  3300. Out << "St";
  3301. return true;
  3302. }
  3303. }
  3304. if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
  3305. if (!isStdNamespace(getEffectiveDeclContext(TD)))
  3306. return false;
  3307. // <substitution> ::= Sa # ::std::allocator
  3308. if (TD->getIdentifier()->isStr("allocator")) {
  3309. Out << "Sa";
  3310. return true;
  3311. }
  3312. // <<substitution> ::= Sb # ::std::basic_string
  3313. if (TD->getIdentifier()->isStr("basic_string")) {
  3314. Out << "Sb";
  3315. return true;
  3316. }
  3317. }
  3318. if (const ClassTemplateSpecializationDecl *SD =
  3319. dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
  3320. if (!isStdNamespace(getEffectiveDeclContext(SD)))
  3321. return false;
  3322. // <substitution> ::= Ss # ::std::basic_string<char,
  3323. // ::std::char_traits<char>,
  3324. // ::std::allocator<char> >
  3325. if (SD->getIdentifier()->isStr("basic_string")) {
  3326. const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
  3327. if (TemplateArgs.size() != 3)
  3328. return false;
  3329. if (!isCharType(TemplateArgs[0].getAsType()))
  3330. return false;
  3331. if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
  3332. return false;
  3333. if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
  3334. return false;
  3335. Out << "Ss";
  3336. return true;
  3337. }
  3338. // <substitution> ::= Si # ::std::basic_istream<char,
  3339. // ::std::char_traits<char> >
  3340. if (isStreamCharSpecialization(SD, "basic_istream")) {
  3341. Out << "Si";
  3342. return true;
  3343. }
  3344. // <substitution> ::= So # ::std::basic_ostream<char,
  3345. // ::std::char_traits<char> >
  3346. if (isStreamCharSpecialization(SD, "basic_ostream")) {
  3347. Out << "So";
  3348. return true;
  3349. }
  3350. // <substitution> ::= Sd # ::std::basic_iostream<char,
  3351. // ::std::char_traits<char> >
  3352. if (isStreamCharSpecialization(SD, "basic_iostream")) {
  3353. Out << "Sd";
  3354. return true;
  3355. }
  3356. }
  3357. return false;
  3358. }
  3359. void CXXNameMangler::addSubstitution(QualType T) {
  3360. if (!hasMangledSubstitutionQualifiers(T)) {
  3361. if (const RecordType *RT = T->getAs<RecordType>()) {
  3362. addSubstitution(RT->getDecl());
  3363. return;
  3364. }
  3365. }
  3366. uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
  3367. addSubstitution(TypePtr);
  3368. }
  3369. void CXXNameMangler::addSubstitution(TemplateName Template) {
  3370. if (TemplateDecl *TD = Template.getAsTemplateDecl())
  3371. return addSubstitution(TD);
  3372. Template = Context.getASTContext().getCanonicalTemplateName(Template);
  3373. addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
  3374. }
  3375. void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
  3376. assert(!Substitutions.count(Ptr) && "Substitution already exists!");
  3377. Substitutions[Ptr] = SeqID++;
  3378. }
  3379. //
  3380. /// Mangles the name of the declaration D and emits that name to the given
  3381. /// output stream.
  3382. ///
  3383. /// If the declaration D requires a mangled name, this routine will emit that
  3384. /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
  3385. /// and this routine will return false. In this case, the caller should just
  3386. /// emit the identifier of the declaration (\c D->getIdentifier()) as its
  3387. /// name.
  3388. void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
  3389. raw_ostream &Out) {
  3390. assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
  3391. "Invalid mangleName() call, argument is not a variable or function!");
  3392. assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
  3393. "Invalid mangleName() call on 'structor decl!");
  3394. PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
  3395. getASTContext().getSourceManager(),
  3396. "Mangling declaration");
  3397. CXXNameMangler Mangler(*this, Out, D);
  3398. Mangler.mangle(D);
  3399. }
  3400. void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
  3401. CXXCtorType Type,
  3402. raw_ostream &Out) {
  3403. CXXNameMangler Mangler(*this, Out, D, Type);
  3404. Mangler.mangle(D);
  3405. }
  3406. void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
  3407. CXXDtorType Type,
  3408. raw_ostream &Out) {
  3409. CXXNameMangler Mangler(*this, Out, D, Type);
  3410. Mangler.mangle(D);
  3411. }
  3412. void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
  3413. raw_ostream &Out) {
  3414. CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
  3415. Mangler.mangle(D);
  3416. }
  3417. void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
  3418. raw_ostream &Out) {
  3419. CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
  3420. Mangler.mangle(D);
  3421. }
  3422. void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
  3423. const ThunkInfo &Thunk,
  3424. raw_ostream &Out) {
  3425. // <special-name> ::= T <call-offset> <base encoding>
  3426. // # base is the nominal target function of thunk
  3427. // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
  3428. // # base is the nominal target function of thunk
  3429. // # first call-offset is 'this' adjustment
  3430. // # second call-offset is result adjustment
  3431. assert(!isa<CXXDestructorDecl>(MD) &&
  3432. "Use mangleCXXDtor for destructor decls!");
  3433. CXXNameMangler Mangler(*this, Out);
  3434. Mangler.getStream() << "_ZT";
  3435. if (!Thunk.Return.isEmpty())
  3436. Mangler.getStream() << 'c';
  3437. // Mangle the 'this' pointer adjustment.
  3438. Mangler.mangleCallOffset(Thunk.This.NonVirtual,
  3439. Thunk.This.Virtual.Itanium.VCallOffsetOffset);
  3440. // Mangle the return pointer adjustment if there is one.
  3441. if (!Thunk.Return.isEmpty())
  3442. Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
  3443. Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
  3444. Mangler.mangleFunctionEncoding(MD);
  3445. }
  3446. void ItaniumMangleContextImpl::mangleCXXDtorThunk(
  3447. const CXXDestructorDecl *DD, CXXDtorType Type,
  3448. const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
  3449. // <special-name> ::= T <call-offset> <base encoding>
  3450. // # base is the nominal target function of thunk
  3451. CXXNameMangler Mangler(*this, Out, DD, Type);
  3452. Mangler.getStream() << "_ZT";
  3453. // Mangle the 'this' pointer adjustment.
  3454. Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
  3455. ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
  3456. Mangler.mangleFunctionEncoding(DD);
  3457. }
  3458. /// Returns the mangled name for a guard variable for the passed in VarDecl.
  3459. void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
  3460. raw_ostream &Out) {
  3461. // <special-name> ::= GV <object name> # Guard variable for one-time
  3462. // # initialization
  3463. CXXNameMangler Mangler(*this, Out);
  3464. Mangler.getStream() << "_ZGV";
  3465. Mangler.mangleName(D);
  3466. }
  3467. void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
  3468. raw_ostream &Out) {
  3469. // These symbols are internal in the Itanium ABI, so the names don't matter.
  3470. // Clang has traditionally used this symbol and allowed LLVM to adjust it to
  3471. // avoid duplicate symbols.
  3472. Out << "__cxx_global_var_init";
  3473. }
  3474. void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
  3475. raw_ostream &Out) {
  3476. // Prefix the mangling of D with __dtor_.
  3477. CXXNameMangler Mangler(*this, Out);
  3478. Mangler.getStream() << "__dtor_";
  3479. if (shouldMangleDeclName(D))
  3480. Mangler.mangle(D);
  3481. else
  3482. Mangler.getStream() << D->getName();
  3483. }
  3484. void ItaniumMangleContextImpl::mangleSEHFilterExpression(
  3485. const NamedDecl *EnclosingDecl, raw_ostream &Out) {
  3486. CXXNameMangler Mangler(*this, Out);
  3487. Mangler.getStream() << "__filt_";
  3488. if (shouldMangleDeclName(EnclosingDecl))
  3489. Mangler.mangle(EnclosingDecl);
  3490. else
  3491. Mangler.getStream() << EnclosingDecl->getName();
  3492. }
  3493. void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
  3494. const NamedDecl *EnclosingDecl, raw_ostream &Out) {
  3495. CXXNameMangler Mangler(*this, Out);
  3496. Mangler.getStream() << "__fin_";
  3497. if (shouldMangleDeclName(EnclosingDecl))
  3498. Mangler.mangle(EnclosingDecl);
  3499. else
  3500. Mangler.getStream() << EnclosingDecl->getName();
  3501. }
  3502. void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
  3503. raw_ostream &Out) {
  3504. // <special-name> ::= TH <object name>
  3505. CXXNameMangler Mangler(*this, Out);
  3506. Mangler.getStream() << "_ZTH";
  3507. Mangler.mangleName(D);
  3508. }
  3509. void
  3510. ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
  3511. raw_ostream &Out) {
  3512. // <special-name> ::= TW <object name>
  3513. CXXNameMangler Mangler(*this, Out);
  3514. Mangler.getStream() << "_ZTW";
  3515. Mangler.mangleName(D);
  3516. }
  3517. void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
  3518. unsigned ManglingNumber,
  3519. raw_ostream &Out) {
  3520. // We match the GCC mangling here.
  3521. // <special-name> ::= GR <object name>
  3522. CXXNameMangler Mangler(*this, Out);
  3523. Mangler.getStream() << "_ZGR";
  3524. Mangler.mangleName(D);
  3525. assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
  3526. Mangler.mangleSeqID(ManglingNumber - 1);
  3527. }
  3528. void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
  3529. raw_ostream &Out) {
  3530. // <special-name> ::= TV <type> # virtual table
  3531. CXXNameMangler Mangler(*this, Out);
  3532. Mangler.getStream() << "_ZTV";
  3533. Mangler.mangleNameOrStandardSubstitution(RD);
  3534. }
  3535. void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
  3536. raw_ostream &Out) {
  3537. // <special-name> ::= TT <type> # VTT structure
  3538. CXXNameMangler Mangler(*this, Out);
  3539. Mangler.getStream() << "_ZTT";
  3540. Mangler.mangleNameOrStandardSubstitution(RD);
  3541. }
  3542. void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
  3543. int64_t Offset,
  3544. const CXXRecordDecl *Type,
  3545. raw_ostream &Out) {
  3546. // <special-name> ::= TC <type> <offset number> _ <base type>
  3547. CXXNameMangler Mangler(*this, Out);
  3548. Mangler.getStream() << "_ZTC";
  3549. Mangler.mangleNameOrStandardSubstitution(RD);
  3550. Mangler.getStream() << Offset;
  3551. Mangler.getStream() << '_';
  3552. Mangler.mangleNameOrStandardSubstitution(Type);
  3553. }
  3554. void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
  3555. // <special-name> ::= TI <type> # typeinfo structure
  3556. assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
  3557. CXXNameMangler Mangler(*this, Out);
  3558. Mangler.getStream() << "_ZTI";
  3559. Mangler.mangleType(Ty);
  3560. }
  3561. void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
  3562. raw_ostream &Out) {
  3563. // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
  3564. CXXNameMangler Mangler(*this, Out);
  3565. Mangler.getStream() << "_ZTS";
  3566. Mangler.mangleType(Ty);
  3567. }
  3568. void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
  3569. mangleCXXRTTIName(Ty, Out);
  3570. }
  3571. void ItaniumMangleContextImpl::mangleCXXVTableBitSet(const CXXRecordDecl *RD,
  3572. raw_ostream &Out) {
  3573. if (!RD->isExternallyVisible()) {
  3574. // This part of the identifier needs to be unique across all translation
  3575. // units in the linked program. The scheme fails if multiple translation
  3576. // units are compiled using the same relative source file path, or if
  3577. // multiple translation units are built from the same source file.
  3578. SourceManager &SM = getASTContext().getSourceManager();
  3579. Out << "[" << SM.getFileEntryForID(SM.getMainFileID())->getName() << "]";
  3580. }
  3581. CXXNameMangler Mangler(*this, Out);
  3582. Mangler.mangleType(QualType(RD->getTypeForDecl(), 0));
  3583. }
  3584. void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
  3585. llvm_unreachable("Can't mangle string literals");
  3586. }
  3587. ItaniumMangleContext *
  3588. ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
  3589. return new ItaniumMangleContextImpl(Context, Diags);
  3590. }