MicrosoftMangle.cpp 148 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969
  1. //===--- MicrosoftMangle.cpp - Microsoft Visual C++ Name Mangling ---------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This provides C++ name mangling targeting the Microsoft Visual C++ ABI.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/ASTContext.h"
  13. #include "clang/AST/Attr.h"
  14. #include "clang/AST/CXXInheritance.h"
  15. #include "clang/AST/CharUnits.h"
  16. #include "clang/AST/Decl.h"
  17. #include "clang/AST/DeclCXX.h"
  18. #include "clang/AST/DeclObjC.h"
  19. #include "clang/AST/DeclOpenMP.h"
  20. #include "clang/AST/DeclTemplate.h"
  21. #include "clang/AST/Expr.h"
  22. #include "clang/AST/ExprCXX.h"
  23. #include "clang/AST/GlobalDecl.h"
  24. #include "clang/AST/Mangle.h"
  25. #include "clang/AST/VTableBuilder.h"
  26. #include "clang/Basic/ABI.h"
  27. #include "clang/Basic/DiagnosticOptions.h"
  28. #include "clang/Basic/FileManager.h"
  29. #include "clang/Basic/SourceManager.h"
  30. #include "clang/Basic/TargetInfo.h"
  31. #include "llvm/ADT/StringExtras.h"
  32. #include "llvm/Support/CRC.h"
  33. #include "llvm/Support/MD5.h"
  34. #include "llvm/Support/MathExtras.h"
  35. #include "llvm/Support/StringSaver.h"
  36. #include "llvm/Support/xxhash.h"
  37. #include <optional>
  38. using namespace clang;
  39. namespace {
  40. // Get GlobalDecl of DeclContext of local entities.
  41. static GlobalDecl getGlobalDeclAsDeclContext(const DeclContext *DC) {
  42. GlobalDecl GD;
  43. if (auto *CD = dyn_cast<CXXConstructorDecl>(DC))
  44. GD = GlobalDecl(CD, Ctor_Complete);
  45. else if (auto *DD = dyn_cast<CXXDestructorDecl>(DC))
  46. GD = GlobalDecl(DD, Dtor_Complete);
  47. else
  48. GD = GlobalDecl(cast<FunctionDecl>(DC));
  49. return GD;
  50. }
  51. struct msvc_hashing_ostream : public llvm::raw_svector_ostream {
  52. raw_ostream &OS;
  53. llvm::SmallString<64> Buffer;
  54. msvc_hashing_ostream(raw_ostream &OS)
  55. : llvm::raw_svector_ostream(Buffer), OS(OS) {}
  56. ~msvc_hashing_ostream() override {
  57. StringRef MangledName = str();
  58. bool StartsWithEscape = MangledName.startswith("\01");
  59. if (StartsWithEscape)
  60. MangledName = MangledName.drop_front(1);
  61. if (MangledName.size() < 4096) {
  62. OS << str();
  63. return;
  64. }
  65. llvm::MD5 Hasher;
  66. llvm::MD5::MD5Result Hash;
  67. Hasher.update(MangledName);
  68. Hasher.final(Hash);
  69. SmallString<32> HexString;
  70. llvm::MD5::stringifyResult(Hash, HexString);
  71. if (StartsWithEscape)
  72. OS << '\01';
  73. OS << "??@" << HexString << '@';
  74. }
  75. };
  76. static const DeclContext *
  77. getLambdaDefaultArgumentDeclContext(const Decl *D) {
  78. if (const auto *RD = dyn_cast<CXXRecordDecl>(D))
  79. if (RD->isLambda())
  80. if (const auto *Parm =
  81. dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
  82. return Parm->getDeclContext();
  83. return nullptr;
  84. }
  85. /// Retrieve the declaration context that should be used when mangling
  86. /// the given declaration.
  87. static const DeclContext *getEffectiveDeclContext(const Decl *D) {
  88. // The ABI assumes that lambda closure types that occur within
  89. // default arguments live in the context of the function. However, due to
  90. // the way in which Clang parses and creates function declarations, this is
  91. // not the case: the lambda closure type ends up living in the context
  92. // where the function itself resides, because the function declaration itself
  93. // had not yet been created. Fix the context here.
  94. if (const auto *LDADC = getLambdaDefaultArgumentDeclContext(D))
  95. return LDADC;
  96. // Perform the same check for block literals.
  97. if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
  98. if (ParmVarDecl *ContextParam =
  99. dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
  100. return ContextParam->getDeclContext();
  101. }
  102. const DeclContext *DC = D->getDeclContext();
  103. if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC) ||
  104. isa<OMPDeclareMapperDecl>(DC)) {
  105. return getEffectiveDeclContext(cast<Decl>(DC));
  106. }
  107. return DC->getRedeclContext();
  108. }
  109. static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
  110. return getEffectiveDeclContext(cast<Decl>(DC));
  111. }
  112. static const FunctionDecl *getStructor(const NamedDecl *ND) {
  113. if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(ND))
  114. return FTD->getTemplatedDecl()->getCanonicalDecl();
  115. const auto *FD = cast<FunctionDecl>(ND);
  116. if (const auto *FTD = FD->getPrimaryTemplate())
  117. return FTD->getTemplatedDecl()->getCanonicalDecl();
  118. return FD->getCanonicalDecl();
  119. }
  120. /// MicrosoftMangleContextImpl - Overrides the default MangleContext for the
  121. /// Microsoft Visual C++ ABI.
  122. class MicrosoftMangleContextImpl : public MicrosoftMangleContext {
  123. typedef std::pair<const DeclContext *, IdentifierInfo *> DiscriminatorKeyTy;
  124. llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
  125. llvm::DenseMap<const NamedDecl *, unsigned> Uniquifier;
  126. llvm::DenseMap<const CXXRecordDecl *, unsigned> LambdaIds;
  127. llvm::DenseMap<GlobalDecl, unsigned> SEHFilterIds;
  128. llvm::DenseMap<GlobalDecl, unsigned> SEHFinallyIds;
  129. SmallString<16> AnonymousNamespaceHash;
  130. public:
  131. MicrosoftMangleContextImpl(ASTContext &Context, DiagnosticsEngine &Diags,
  132. bool IsAux = false);
  133. bool shouldMangleCXXName(const NamedDecl *D) override;
  134. bool shouldMangleStringLiteral(const StringLiteral *SL) override;
  135. void mangleCXXName(GlobalDecl GD, raw_ostream &Out) override;
  136. void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
  137. const MethodVFTableLocation &ML,
  138. raw_ostream &Out) override;
  139. void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
  140. raw_ostream &) override;
  141. void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
  142. const ThisAdjustment &ThisAdjustment,
  143. raw_ostream &) override;
  144. void mangleCXXVFTable(const CXXRecordDecl *Derived,
  145. ArrayRef<const CXXRecordDecl *> BasePath,
  146. raw_ostream &Out) override;
  147. void mangleCXXVBTable(const CXXRecordDecl *Derived,
  148. ArrayRef<const CXXRecordDecl *> BasePath,
  149. raw_ostream &Out) override;
  150. void mangleCXXVirtualDisplacementMap(const CXXRecordDecl *SrcRD,
  151. const CXXRecordDecl *DstRD,
  152. raw_ostream &Out) override;
  153. void mangleCXXThrowInfo(QualType T, bool IsConst, bool IsVolatile,
  154. bool IsUnaligned, uint32_t NumEntries,
  155. raw_ostream &Out) override;
  156. void mangleCXXCatchableTypeArray(QualType T, uint32_t NumEntries,
  157. raw_ostream &Out) override;
  158. void mangleCXXCatchableType(QualType T, const CXXConstructorDecl *CD,
  159. CXXCtorType CT, uint32_t Size, uint32_t NVOffset,
  160. int32_t VBPtrOffset, uint32_t VBIndex,
  161. raw_ostream &Out) override;
  162. void mangleCXXRTTI(QualType T, raw_ostream &Out) override;
  163. void mangleCXXRTTIName(QualType T, raw_ostream &Out) override;
  164. void mangleCXXRTTIBaseClassDescriptor(const CXXRecordDecl *Derived,
  165. uint32_t NVOffset, int32_t VBPtrOffset,
  166. uint32_t VBTableOffset, uint32_t Flags,
  167. raw_ostream &Out) override;
  168. void mangleCXXRTTIBaseClassArray(const CXXRecordDecl *Derived,
  169. raw_ostream &Out) override;
  170. void mangleCXXRTTIClassHierarchyDescriptor(const CXXRecordDecl *Derived,
  171. raw_ostream &Out) override;
  172. void
  173. mangleCXXRTTICompleteObjectLocator(const CXXRecordDecl *Derived,
  174. ArrayRef<const CXXRecordDecl *> BasePath,
  175. raw_ostream &Out) override;
  176. void mangleTypeName(QualType T, raw_ostream &) override;
  177. void mangleReferenceTemporary(const VarDecl *, unsigned ManglingNumber,
  178. raw_ostream &) override;
  179. void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &Out) override;
  180. void mangleThreadSafeStaticGuardVariable(const VarDecl *D, unsigned GuardNum,
  181. raw_ostream &Out) override;
  182. void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
  183. void mangleDynamicAtExitDestructor(const VarDecl *D,
  184. raw_ostream &Out) override;
  185. void mangleSEHFilterExpression(GlobalDecl EnclosingDecl,
  186. raw_ostream &Out) override;
  187. void mangleSEHFinallyBlock(GlobalDecl EnclosingDecl,
  188. raw_ostream &Out) override;
  189. void mangleStringLiteral(const StringLiteral *SL, raw_ostream &Out) override;
  190. bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
  191. const DeclContext *DC = getEffectiveDeclContext(ND);
  192. if (!DC->isFunctionOrMethod())
  193. return false;
  194. // Lambda closure types are already numbered, give out a phony number so
  195. // that they demangle nicely.
  196. if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
  197. if (RD->isLambda()) {
  198. disc = 1;
  199. return true;
  200. }
  201. }
  202. // Use the canonical number for externally visible decls.
  203. if (ND->isExternallyVisible()) {
  204. disc = getASTContext().getManglingNumber(ND, isAux());
  205. return true;
  206. }
  207. // Anonymous tags are already numbered.
  208. if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
  209. if (!Tag->hasNameForLinkage() &&
  210. !getASTContext().getDeclaratorForUnnamedTagDecl(Tag) &&
  211. !getASTContext().getTypedefNameForUnnamedTagDecl(Tag))
  212. return false;
  213. }
  214. // Make up a reasonable number for internal decls.
  215. unsigned &discriminator = Uniquifier[ND];
  216. if (!discriminator)
  217. discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
  218. disc = discriminator + 1;
  219. return true;
  220. }
  221. std::string getLambdaString(const CXXRecordDecl *Lambda) override {
  222. assert(Lambda->isLambda() && "RD must be a lambda!");
  223. std::string Name("<lambda_");
  224. Decl *LambdaContextDecl = Lambda->getLambdaContextDecl();
  225. unsigned LambdaManglingNumber = Lambda->getLambdaManglingNumber();
  226. unsigned LambdaId;
  227. const ParmVarDecl *Parm = dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl);
  228. const FunctionDecl *Func =
  229. Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr;
  230. if (Func) {
  231. unsigned DefaultArgNo =
  232. Func->getNumParams() - Parm->getFunctionScopeIndex();
  233. Name += llvm::utostr(DefaultArgNo);
  234. Name += "_";
  235. }
  236. if (LambdaManglingNumber)
  237. LambdaId = LambdaManglingNumber;
  238. else
  239. LambdaId = getLambdaIdForDebugInfo(Lambda);
  240. Name += llvm::utostr(LambdaId);
  241. Name += ">";
  242. return Name;
  243. }
  244. unsigned getLambdaId(const CXXRecordDecl *RD) {
  245. assert(RD->isLambda() && "RD must be a lambda!");
  246. assert(!RD->isExternallyVisible() && "RD must not be visible!");
  247. assert(RD->getLambdaManglingNumber() == 0 &&
  248. "RD must not have a mangling number!");
  249. std::pair<llvm::DenseMap<const CXXRecordDecl *, unsigned>::iterator, bool>
  250. Result = LambdaIds.insert(std::make_pair(RD, LambdaIds.size()));
  251. return Result.first->second;
  252. }
  253. unsigned getLambdaIdForDebugInfo(const CXXRecordDecl *RD) {
  254. assert(RD->isLambda() && "RD must be a lambda!");
  255. assert(!RD->isExternallyVisible() && "RD must not be visible!");
  256. assert(RD->getLambdaManglingNumber() == 0 &&
  257. "RD must not have a mangling number!");
  258. llvm::DenseMap<const CXXRecordDecl *, unsigned>::iterator Result =
  259. LambdaIds.find(RD);
  260. // The lambda should exist, but return 0 in case it doesn't.
  261. if (Result == LambdaIds.end())
  262. return 0;
  263. return Result->second;
  264. }
  265. /// Return a character sequence that is (somewhat) unique to the TU suitable
  266. /// for mangling anonymous namespaces.
  267. StringRef getAnonymousNamespaceHash() const {
  268. return AnonymousNamespaceHash;
  269. }
  270. private:
  271. void mangleInitFiniStub(const VarDecl *D, char CharCode, raw_ostream &Out);
  272. };
  273. /// MicrosoftCXXNameMangler - Manage the mangling of a single name for the
  274. /// Microsoft Visual C++ ABI.
  275. class MicrosoftCXXNameMangler {
  276. MicrosoftMangleContextImpl &Context;
  277. raw_ostream &Out;
  278. /// The "structor" is the top-level declaration being mangled, if
  279. /// that's not a template specialization; otherwise it's the pattern
  280. /// for that specialization.
  281. const NamedDecl *Structor;
  282. unsigned StructorType;
  283. typedef llvm::SmallVector<std::string, 10> BackRefVec;
  284. BackRefVec NameBackReferences;
  285. typedef llvm::DenseMap<const void *, unsigned> ArgBackRefMap;
  286. ArgBackRefMap FunArgBackReferences;
  287. ArgBackRefMap TemplateArgBackReferences;
  288. typedef llvm::DenseMap<const void *, StringRef> TemplateArgStringMap;
  289. TemplateArgStringMap TemplateArgStrings;
  290. llvm::StringSaver TemplateArgStringStorage;
  291. llvm::BumpPtrAllocator TemplateArgStringStorageAlloc;
  292. typedef std::set<std::pair<int, bool>> PassObjectSizeArgsSet;
  293. PassObjectSizeArgsSet PassObjectSizeArgs;
  294. ASTContext &getASTContext() const { return Context.getASTContext(); }
  295. const bool PointersAre64Bit;
  296. public:
  297. enum QualifierMangleMode { QMM_Drop, QMM_Mangle, QMM_Escape, QMM_Result };
  298. MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_)
  299. : Context(C), Out(Out_), Structor(nullptr), StructorType(-1),
  300. TemplateArgStringStorage(TemplateArgStringStorageAlloc),
  301. PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(
  302. LangAS::Default) == 64) {}
  303. MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
  304. const CXXConstructorDecl *D, CXXCtorType Type)
  305. : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
  306. TemplateArgStringStorage(TemplateArgStringStorageAlloc),
  307. PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(
  308. LangAS::Default) == 64) {}
  309. MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
  310. const CXXDestructorDecl *D, CXXDtorType Type)
  311. : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
  312. TemplateArgStringStorage(TemplateArgStringStorageAlloc),
  313. PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(
  314. LangAS::Default) == 64) {}
  315. raw_ostream &getStream() const { return Out; }
  316. void mangle(GlobalDecl GD, StringRef Prefix = "?");
  317. void mangleName(GlobalDecl GD);
  318. void mangleFunctionEncoding(GlobalDecl GD, bool ShouldMangle);
  319. void mangleVariableEncoding(const VarDecl *VD);
  320. void mangleMemberDataPointer(const CXXRecordDecl *RD, const ValueDecl *VD,
  321. StringRef Prefix = "$");
  322. void mangleMemberFunctionPointer(const CXXRecordDecl *RD,
  323. const CXXMethodDecl *MD,
  324. StringRef Prefix = "$");
  325. void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
  326. const MethodVFTableLocation &ML);
  327. void mangleNumber(int64_t Number);
  328. void mangleNumber(llvm::APSInt Number);
  329. void mangleFloat(llvm::APFloat Number);
  330. void mangleBits(llvm::APInt Number);
  331. void mangleTagTypeKind(TagTypeKind TK);
  332. void mangleArtificialTagType(TagTypeKind TK, StringRef UnqualifiedName,
  333. ArrayRef<StringRef> NestedNames = std::nullopt);
  334. void mangleAddressSpaceType(QualType T, Qualifiers Quals, SourceRange Range);
  335. void mangleType(QualType T, SourceRange Range,
  336. QualifierMangleMode QMM = QMM_Mangle);
  337. void mangleFunctionType(const FunctionType *T,
  338. const FunctionDecl *D = nullptr,
  339. bool ForceThisQuals = false,
  340. bool MangleExceptionSpec = true);
  341. void mangleNestedName(GlobalDecl GD);
  342. private:
  343. bool isStructorDecl(const NamedDecl *ND) const {
  344. return ND == Structor || getStructor(ND) == Structor;
  345. }
  346. bool is64BitPointer(Qualifiers Quals) const {
  347. LangAS AddrSpace = Quals.getAddressSpace();
  348. return AddrSpace == LangAS::ptr64 ||
  349. (PointersAre64Bit && !(AddrSpace == LangAS::ptr32_sptr ||
  350. AddrSpace == LangAS::ptr32_uptr));
  351. }
  352. void mangleUnqualifiedName(GlobalDecl GD) {
  353. mangleUnqualifiedName(GD, cast<NamedDecl>(GD.getDecl())->getDeclName());
  354. }
  355. void mangleUnqualifiedName(GlobalDecl GD, DeclarationName Name);
  356. void mangleSourceName(StringRef Name);
  357. void mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc);
  358. void mangleCXXDtorType(CXXDtorType T);
  359. void mangleQualifiers(Qualifiers Quals, bool IsMember);
  360. void mangleRefQualifier(RefQualifierKind RefQualifier);
  361. void manglePointerCVQualifiers(Qualifiers Quals);
  362. void manglePointerExtQualifiers(Qualifiers Quals, QualType PointeeType);
  363. void mangleUnscopedTemplateName(GlobalDecl GD);
  364. void
  365. mangleTemplateInstantiationName(GlobalDecl GD,
  366. const TemplateArgumentList &TemplateArgs);
  367. void mangleObjCMethodName(const ObjCMethodDecl *MD);
  368. void mangleFunctionArgumentType(QualType T, SourceRange Range);
  369. void manglePassObjectSizeArg(const PassObjectSizeAttr *POSA);
  370. bool isArtificialTagType(QualType T) const;
  371. // Declare manglers for every type class.
  372. #define ABSTRACT_TYPE(CLASS, PARENT)
  373. #define NON_CANONICAL_TYPE(CLASS, PARENT)
  374. #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T, \
  375. Qualifiers Quals, \
  376. SourceRange Range);
  377. #include "clang/AST/TypeNodes.inc"
  378. #undef ABSTRACT_TYPE
  379. #undef NON_CANONICAL_TYPE
  380. #undef TYPE
  381. void mangleType(const TagDecl *TD);
  382. void mangleDecayedArrayType(const ArrayType *T);
  383. void mangleArrayType(const ArrayType *T);
  384. void mangleFunctionClass(const FunctionDecl *FD);
  385. void mangleCallingConvention(CallingConv CC);
  386. void mangleCallingConvention(const FunctionType *T);
  387. void mangleIntegerLiteral(const llvm::APSInt &Number,
  388. const NonTypeTemplateParmDecl *PD = nullptr,
  389. QualType TemplateArgType = QualType());
  390. void mangleExpression(const Expr *E, const NonTypeTemplateParmDecl *PD);
  391. void mangleThrowSpecification(const FunctionProtoType *T);
  392. void mangleTemplateArgs(const TemplateDecl *TD,
  393. const TemplateArgumentList &TemplateArgs);
  394. void mangleTemplateArg(const TemplateDecl *TD, const TemplateArgument &TA,
  395. const NamedDecl *Parm);
  396. void mangleTemplateArgValue(QualType T, const APValue &V,
  397. bool WithScalarType = false);
  398. void mangleObjCProtocol(const ObjCProtocolDecl *PD);
  399. void mangleObjCLifetime(const QualType T, Qualifiers Quals,
  400. SourceRange Range);
  401. void mangleObjCKindOfType(const ObjCObjectType *T, Qualifiers Quals,
  402. SourceRange Range);
  403. };
  404. }
  405. MicrosoftMangleContextImpl::MicrosoftMangleContextImpl(ASTContext &Context,
  406. DiagnosticsEngine &Diags,
  407. bool IsAux)
  408. : MicrosoftMangleContext(Context, Diags, IsAux) {
  409. // To mangle anonymous namespaces, hash the path to the main source file. The
  410. // path should be whatever (probably relative) path was passed on the command
  411. // line. The goal is for the compiler to produce the same output regardless of
  412. // working directory, so use the uncanonicalized relative path.
  413. //
  414. // It's important to make the mangled names unique because, when CodeView
  415. // debug info is in use, the debugger uses mangled type names to distinguish
  416. // between otherwise identically named types in anonymous namespaces.
  417. //
  418. // These symbols are always internal, so there is no need for the hash to
  419. // match what MSVC produces. For the same reason, clang is free to change the
  420. // hash at any time without breaking compatibility with old versions of clang.
  421. // The generated names are intended to look similar to what MSVC generates,
  422. // which are something like "?A0x01234567@".
  423. SourceManager &SM = Context.getSourceManager();
  424. if (const FileEntry *FE = SM.getFileEntryForID(SM.getMainFileID())) {
  425. // Truncate the hash so we get 8 characters of hexadecimal.
  426. uint32_t TruncatedHash = uint32_t(xxHash64(FE->getName()));
  427. AnonymousNamespaceHash = llvm::utohexstr(TruncatedHash);
  428. } else {
  429. // If we don't have a path to the main file, we'll just use 0.
  430. AnonymousNamespaceHash = "0";
  431. }
  432. }
  433. bool MicrosoftMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
  434. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  435. LanguageLinkage L = FD->getLanguageLinkage();
  436. // Overloadable functions need mangling.
  437. if (FD->hasAttr<OverloadableAttr>())
  438. return true;
  439. // The ABI expects that we would never mangle "typical" user-defined entry
  440. // points regardless of visibility or freestanding-ness.
  441. //
  442. // N.B. This is distinct from asking about "main". "main" has a lot of
  443. // special rules associated with it in the standard while these
  444. // user-defined entry points are outside of the purview of the standard.
  445. // For example, there can be only one definition for "main" in a standards
  446. // compliant program; however nothing forbids the existence of wmain and
  447. // WinMain in the same translation unit.
  448. if (FD->isMSVCRTEntryPoint())
  449. return false;
  450. // C++ functions and those whose names are not a simple identifier need
  451. // mangling.
  452. if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
  453. return true;
  454. // C functions are not mangled.
  455. if (L == CLanguageLinkage)
  456. return false;
  457. }
  458. // Otherwise, no mangling is done outside C++ mode.
  459. if (!getASTContext().getLangOpts().CPlusPlus)
  460. return false;
  461. const VarDecl *VD = dyn_cast<VarDecl>(D);
  462. if (VD && !isa<DecompositionDecl>(D)) {
  463. // C variables are not mangled.
  464. if (VD->isExternC())
  465. return false;
  466. // Variables at global scope with internal linkage are not mangled.
  467. const DeclContext *DC = getEffectiveDeclContext(D);
  468. // Check for extern variable declared locally.
  469. if (DC->isFunctionOrMethod() && D->hasLinkage())
  470. while (!DC->isNamespace() && !DC->isTranslationUnit())
  471. DC = getEffectiveParentContext(DC);
  472. if (DC->isTranslationUnit() && D->getFormalLinkage() == InternalLinkage &&
  473. !isa<VarTemplateSpecializationDecl>(D) &&
  474. D->getIdentifier() != nullptr)
  475. return false;
  476. }
  477. return true;
  478. }
  479. bool
  480. MicrosoftMangleContextImpl::shouldMangleStringLiteral(const StringLiteral *SL) {
  481. return true;
  482. }
  483. void MicrosoftCXXNameMangler::mangle(GlobalDecl GD, StringRef Prefix) {
  484. const NamedDecl *D = cast<NamedDecl>(GD.getDecl());
  485. // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
  486. // Therefore it's really important that we don't decorate the
  487. // name with leading underscores or leading/trailing at signs. So, by
  488. // default, we emit an asm marker at the start so we get the name right.
  489. // Callers can override this with a custom prefix.
  490. // <mangled-name> ::= ? <name> <type-encoding>
  491. Out << Prefix;
  492. mangleName(GD);
  493. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  494. mangleFunctionEncoding(GD, Context.shouldMangleDeclName(FD));
  495. else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  496. mangleVariableEncoding(VD);
  497. else if (isa<MSGuidDecl>(D))
  498. // MSVC appears to mangle GUIDs as if they were variables of type
  499. // 'const struct __s_GUID'.
  500. Out << "3U__s_GUID@@B";
  501. else if (isa<TemplateParamObjectDecl>(D)) {
  502. // Template parameter objects don't get a <type-encoding>; their type is
  503. // specified as part of their value.
  504. } else
  505. llvm_unreachable("Tried to mangle unexpected NamedDecl!");
  506. }
  507. void MicrosoftCXXNameMangler::mangleFunctionEncoding(GlobalDecl GD,
  508. bool ShouldMangle) {
  509. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  510. // <type-encoding> ::= <function-class> <function-type>
  511. // Since MSVC operates on the type as written and not the canonical type, it
  512. // actually matters which decl we have here. MSVC appears to choose the
  513. // first, since it is most likely to be the declaration in a header file.
  514. FD = FD->getFirstDecl();
  515. // We should never ever see a FunctionNoProtoType at this point.
  516. // We don't even know how to mangle their types anyway :).
  517. const FunctionProtoType *FT = FD->getType()->castAs<FunctionProtoType>();
  518. // extern "C" functions can hold entities that must be mangled.
  519. // As it stands, these functions still need to get expressed in the full
  520. // external name. They have their class and type omitted, replaced with '9'.
  521. if (ShouldMangle) {
  522. // We would like to mangle all extern "C" functions using this additional
  523. // component but this would break compatibility with MSVC's behavior.
  524. // Instead, do this when we know that compatibility isn't important (in
  525. // other words, when it is an overloaded extern "C" function).
  526. if (FD->isExternC() && FD->hasAttr<OverloadableAttr>())
  527. Out << "$$J0";
  528. mangleFunctionClass(FD);
  529. mangleFunctionType(FT, FD, false, false);
  530. } else {
  531. Out << '9';
  532. }
  533. }
  534. void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) {
  535. // <type-encoding> ::= <storage-class> <variable-type>
  536. // <storage-class> ::= 0 # private static member
  537. // ::= 1 # protected static member
  538. // ::= 2 # public static member
  539. // ::= 3 # global
  540. // ::= 4 # static local
  541. // The first character in the encoding (after the name) is the storage class.
  542. if (VD->isStaticDataMember()) {
  543. // If it's a static member, it also encodes the access level.
  544. switch (VD->getAccess()) {
  545. default:
  546. case AS_private: Out << '0'; break;
  547. case AS_protected: Out << '1'; break;
  548. case AS_public: Out << '2'; break;
  549. }
  550. }
  551. else if (!VD->isStaticLocal())
  552. Out << '3';
  553. else
  554. Out << '4';
  555. // Now mangle the type.
  556. // <variable-type> ::= <type> <cvr-qualifiers>
  557. // ::= <type> <pointee-cvr-qualifiers> # pointers, references
  558. // Pointers and references are odd. The type of 'int * const foo;' gets
  559. // mangled as 'QAHA' instead of 'PAHB', for example.
  560. SourceRange SR = VD->getSourceRange();
  561. QualType Ty = VD->getType();
  562. if (Ty->isPointerType() || Ty->isReferenceType() ||
  563. Ty->isMemberPointerType()) {
  564. mangleType(Ty, SR, QMM_Drop);
  565. manglePointerExtQualifiers(
  566. Ty.getDesugaredType(getASTContext()).getLocalQualifiers(), QualType());
  567. if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()) {
  568. mangleQualifiers(MPT->getPointeeType().getQualifiers(), true);
  569. // Member pointers are suffixed with a back reference to the member
  570. // pointer's class name.
  571. mangleName(MPT->getClass()->getAsCXXRecordDecl());
  572. } else
  573. mangleQualifiers(Ty->getPointeeType().getQualifiers(), false);
  574. } else if (const ArrayType *AT = getASTContext().getAsArrayType(Ty)) {
  575. // Global arrays are funny, too.
  576. mangleDecayedArrayType(AT);
  577. if (AT->getElementType()->isArrayType())
  578. Out << 'A';
  579. else
  580. mangleQualifiers(Ty.getQualifiers(), false);
  581. } else {
  582. mangleType(Ty, SR, QMM_Drop);
  583. mangleQualifiers(Ty.getQualifiers(), false);
  584. }
  585. }
  586. void MicrosoftCXXNameMangler::mangleMemberDataPointer(const CXXRecordDecl *RD,
  587. const ValueDecl *VD,
  588. StringRef Prefix) {
  589. // <member-data-pointer> ::= <integer-literal>
  590. // ::= $F <number> <number>
  591. // ::= $G <number> <number> <number>
  592. int64_t FieldOffset;
  593. int64_t VBTableOffset;
  594. MSInheritanceModel IM = RD->getMSInheritanceModel();
  595. if (VD) {
  596. FieldOffset = getASTContext().getFieldOffset(VD);
  597. assert(FieldOffset % getASTContext().getCharWidth() == 0 &&
  598. "cannot take address of bitfield");
  599. FieldOffset /= getASTContext().getCharWidth();
  600. VBTableOffset = 0;
  601. if (IM == MSInheritanceModel::Virtual)
  602. FieldOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity();
  603. } else {
  604. FieldOffset = RD->nullFieldOffsetIsZero() ? 0 : -1;
  605. VBTableOffset = -1;
  606. }
  607. char Code = '\0';
  608. switch (IM) {
  609. case MSInheritanceModel::Single: Code = '0'; break;
  610. case MSInheritanceModel::Multiple: Code = '0'; break;
  611. case MSInheritanceModel::Virtual: Code = 'F'; break;
  612. case MSInheritanceModel::Unspecified: Code = 'G'; break;
  613. }
  614. Out << Prefix << Code;
  615. mangleNumber(FieldOffset);
  616. // The C++ standard doesn't allow base-to-derived member pointer conversions
  617. // in template parameter contexts, so the vbptr offset of data member pointers
  618. // is always zero.
  619. if (inheritanceModelHasVBPtrOffsetField(IM))
  620. mangleNumber(0);
  621. if (inheritanceModelHasVBTableOffsetField(IM))
  622. mangleNumber(VBTableOffset);
  623. }
  624. void
  625. MicrosoftCXXNameMangler::mangleMemberFunctionPointer(const CXXRecordDecl *RD,
  626. const CXXMethodDecl *MD,
  627. StringRef Prefix) {
  628. // <member-function-pointer> ::= $1? <name>
  629. // ::= $H? <name> <number>
  630. // ::= $I? <name> <number> <number>
  631. // ::= $J? <name> <number> <number> <number>
  632. MSInheritanceModel IM = RD->getMSInheritanceModel();
  633. char Code = '\0';
  634. switch (IM) {
  635. case MSInheritanceModel::Single: Code = '1'; break;
  636. case MSInheritanceModel::Multiple: Code = 'H'; break;
  637. case MSInheritanceModel::Virtual: Code = 'I'; break;
  638. case MSInheritanceModel::Unspecified: Code = 'J'; break;
  639. }
  640. // If non-virtual, mangle the name. If virtual, mangle as a virtual memptr
  641. // thunk.
  642. uint64_t NVOffset = 0;
  643. uint64_t VBTableOffset = 0;
  644. uint64_t VBPtrOffset = 0;
  645. if (MD) {
  646. Out << Prefix << Code << '?';
  647. if (MD->isVirtual()) {
  648. MicrosoftVTableContext *VTContext =
  649. cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
  650. MethodVFTableLocation ML =
  651. VTContext->getMethodVFTableLocation(GlobalDecl(MD));
  652. mangleVirtualMemPtrThunk(MD, ML);
  653. NVOffset = ML.VFPtrOffset.getQuantity();
  654. VBTableOffset = ML.VBTableIndex * 4;
  655. if (ML.VBase) {
  656. const ASTRecordLayout &Layout = getASTContext().getASTRecordLayout(RD);
  657. VBPtrOffset = Layout.getVBPtrOffset().getQuantity();
  658. }
  659. } else {
  660. mangleName(MD);
  661. mangleFunctionEncoding(MD, /*ShouldMangle=*/true);
  662. }
  663. if (VBTableOffset == 0 && IM == MSInheritanceModel::Virtual)
  664. NVOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity();
  665. } else {
  666. // Null single inheritance member functions are encoded as a simple nullptr.
  667. if (IM == MSInheritanceModel::Single) {
  668. Out << Prefix << "0A@";
  669. return;
  670. }
  671. if (IM == MSInheritanceModel::Unspecified)
  672. VBTableOffset = -1;
  673. Out << Prefix << Code;
  674. }
  675. if (inheritanceModelHasNVOffsetField(/*IsMemberFunction=*/true, IM))
  676. mangleNumber(static_cast<uint32_t>(NVOffset));
  677. if (inheritanceModelHasVBPtrOffsetField(IM))
  678. mangleNumber(VBPtrOffset);
  679. if (inheritanceModelHasVBTableOffsetField(IM))
  680. mangleNumber(VBTableOffset);
  681. }
  682. void MicrosoftCXXNameMangler::mangleVirtualMemPtrThunk(
  683. const CXXMethodDecl *MD, const MethodVFTableLocation &ML) {
  684. // Get the vftable offset.
  685. CharUnits PointerWidth = getASTContext().toCharUnitsFromBits(
  686. getASTContext().getTargetInfo().getPointerWidth(LangAS::Default));
  687. uint64_t OffsetInVFTable = ML.Index * PointerWidth.getQuantity();
  688. Out << "?_9";
  689. mangleName(MD->getParent());
  690. Out << "$B";
  691. mangleNumber(OffsetInVFTable);
  692. Out << 'A';
  693. mangleCallingConvention(MD->getType()->castAs<FunctionProtoType>());
  694. }
  695. void MicrosoftCXXNameMangler::mangleName(GlobalDecl GD) {
  696. // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
  697. // Always start with the unqualified name.
  698. mangleUnqualifiedName(GD);
  699. mangleNestedName(GD);
  700. // Terminate the whole name with an '@'.
  701. Out << '@';
  702. }
  703. void MicrosoftCXXNameMangler::mangleNumber(int64_t Number) {
  704. mangleNumber(llvm::APSInt(llvm::APInt(64, Number), /*IsUnsigned*/false));
  705. }
  706. void MicrosoftCXXNameMangler::mangleNumber(llvm::APSInt Number) {
  707. // MSVC never mangles any integer wider than 64 bits. In general it appears
  708. // to convert every integer to signed 64 bit before mangling (including
  709. // unsigned 64 bit values). Do the same, but preserve bits beyond the bottom
  710. // 64.
  711. unsigned Width = std::max(Number.getBitWidth(), 64U);
  712. llvm::APInt Value = Number.extend(Width);
  713. // <non-negative integer> ::= A@ # when Number == 0
  714. // ::= <decimal digit> # when 1 <= Number <= 10
  715. // ::= <hex digit>+ @ # when Number >= 10
  716. //
  717. // <number> ::= [?] <non-negative integer>
  718. if (Value.isNegative()) {
  719. Value = -Value;
  720. Out << '?';
  721. }
  722. mangleBits(Value);
  723. }
  724. void MicrosoftCXXNameMangler::mangleFloat(llvm::APFloat Number) {
  725. using llvm::APFloat;
  726. switch (APFloat::SemanticsToEnum(Number.getSemantics())) {
  727. case APFloat::S_IEEEsingle: Out << 'A'; break;
  728. case APFloat::S_IEEEdouble: Out << 'B'; break;
  729. // The following are all Clang extensions. We try to pick manglings that are
  730. // unlikely to conflict with MSVC's scheme.
  731. case APFloat::S_IEEEhalf: Out << 'V'; break;
  732. case APFloat::S_BFloat: Out << 'W'; break;
  733. case APFloat::S_x87DoubleExtended: Out << 'X'; break;
  734. case APFloat::S_IEEEquad: Out << 'Y'; break;
  735. case APFloat::S_PPCDoubleDouble: Out << 'Z'; break;
  736. case APFloat::S_Float8E5M2:
  737. case APFloat::S_Float8E4M3FN:
  738. llvm_unreachable("Tried to mangle unexpected APFloat semantics");
  739. }
  740. mangleBits(Number.bitcastToAPInt());
  741. }
  742. void MicrosoftCXXNameMangler::mangleBits(llvm::APInt Value) {
  743. if (Value == 0)
  744. Out << "A@";
  745. else if (Value.uge(1) && Value.ule(10))
  746. Out << (Value - 1);
  747. else {
  748. // Numbers that are not encoded as decimal digits are represented as nibbles
  749. // in the range of ASCII characters 'A' to 'P'.
  750. // The number 0x123450 would be encoded as 'BCDEFA'
  751. llvm::SmallString<32> EncodedNumberBuffer;
  752. for (; Value != 0; Value.lshrInPlace(4))
  753. EncodedNumberBuffer.push_back('A' + (Value & 0xf).getZExtValue());
  754. std::reverse(EncodedNumberBuffer.begin(), EncodedNumberBuffer.end());
  755. Out.write(EncodedNumberBuffer.data(), EncodedNumberBuffer.size());
  756. Out << '@';
  757. }
  758. }
  759. static GlobalDecl isTemplate(GlobalDecl GD,
  760. const TemplateArgumentList *&TemplateArgs) {
  761. const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
  762. // Check if we have a function template.
  763. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  764. if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
  765. TemplateArgs = FD->getTemplateSpecializationArgs();
  766. return GD.getWithDecl(TD);
  767. }
  768. }
  769. // Check if we have a class template.
  770. if (const ClassTemplateSpecializationDecl *Spec =
  771. dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
  772. TemplateArgs = &Spec->getTemplateArgs();
  773. return GD.getWithDecl(Spec->getSpecializedTemplate());
  774. }
  775. // Check if we have a variable template.
  776. if (const VarTemplateSpecializationDecl *Spec =
  777. dyn_cast<VarTemplateSpecializationDecl>(ND)) {
  778. TemplateArgs = &Spec->getTemplateArgs();
  779. return GD.getWithDecl(Spec->getSpecializedTemplate());
  780. }
  781. return GlobalDecl();
  782. }
  783. void MicrosoftCXXNameMangler::mangleUnqualifiedName(GlobalDecl GD,
  784. DeclarationName Name) {
  785. const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
  786. // <unqualified-name> ::= <operator-name>
  787. // ::= <ctor-dtor-name>
  788. // ::= <source-name>
  789. // ::= <template-name>
  790. // Check if we have a template.
  791. const TemplateArgumentList *TemplateArgs = nullptr;
  792. if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
  793. // Function templates aren't considered for name back referencing. This
  794. // makes sense since function templates aren't likely to occur multiple
  795. // times in a symbol.
  796. if (isa<FunctionTemplateDecl>(TD.getDecl())) {
  797. mangleTemplateInstantiationName(TD, *TemplateArgs);
  798. Out << '@';
  799. return;
  800. }
  801. // Here comes the tricky thing: if we need to mangle something like
  802. // void foo(A::X<Y>, B::X<Y>),
  803. // the X<Y> part is aliased. However, if you need to mangle
  804. // void foo(A::X<A::Y>, A::X<B::Y>),
  805. // the A::X<> part is not aliased.
  806. // That is, from the mangler's perspective we have a structure like this:
  807. // namespace[s] -> type[ -> template-parameters]
  808. // but from the Clang perspective we have
  809. // type [ -> template-parameters]
  810. // \-> namespace[s]
  811. // What we do is we create a new mangler, mangle the same type (without
  812. // a namespace suffix) to a string using the extra mangler and then use
  813. // the mangled type name as a key to check the mangling of different types
  814. // for aliasing.
  815. // It's important to key cache reads off ND, not TD -- the same TD can
  816. // be used with different TemplateArgs, but ND uniquely identifies
  817. // TD / TemplateArg pairs.
  818. ArgBackRefMap::iterator Found = TemplateArgBackReferences.find(ND);
  819. if (Found == TemplateArgBackReferences.end()) {
  820. TemplateArgStringMap::iterator Found = TemplateArgStrings.find(ND);
  821. if (Found == TemplateArgStrings.end()) {
  822. // Mangle full template name into temporary buffer.
  823. llvm::SmallString<64> TemplateMangling;
  824. llvm::raw_svector_ostream Stream(TemplateMangling);
  825. MicrosoftCXXNameMangler Extra(Context, Stream);
  826. Extra.mangleTemplateInstantiationName(TD, *TemplateArgs);
  827. // Use the string backref vector to possibly get a back reference.
  828. mangleSourceName(TemplateMangling);
  829. // Memoize back reference for this type if one exist, else memoize
  830. // the mangling itself.
  831. BackRefVec::iterator StringFound =
  832. llvm::find(NameBackReferences, TemplateMangling);
  833. if (StringFound != NameBackReferences.end()) {
  834. TemplateArgBackReferences[ND] =
  835. StringFound - NameBackReferences.begin();
  836. } else {
  837. TemplateArgStrings[ND] =
  838. TemplateArgStringStorage.save(TemplateMangling.str());
  839. }
  840. } else {
  841. Out << Found->second << '@'; // Outputs a StringRef.
  842. }
  843. } else {
  844. Out << Found->second; // Outputs a back reference (an int).
  845. }
  846. return;
  847. }
  848. switch (Name.getNameKind()) {
  849. case DeclarationName::Identifier: {
  850. if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
  851. bool IsDeviceStub =
  852. ND &&
  853. ((isa<FunctionDecl>(ND) && ND->hasAttr<CUDAGlobalAttr>()) ||
  854. (isa<FunctionTemplateDecl>(ND) &&
  855. cast<FunctionTemplateDecl>(ND)
  856. ->getTemplatedDecl()
  857. ->hasAttr<CUDAGlobalAttr>())) &&
  858. GD.getKernelReferenceKind() == KernelReferenceKind::Stub;
  859. if (IsDeviceStub)
  860. mangleSourceName(
  861. (llvm::Twine("__device_stub__") + II->getName()).str());
  862. else
  863. mangleSourceName(II->getName());
  864. break;
  865. }
  866. // Otherwise, an anonymous entity. We must have a declaration.
  867. assert(ND && "mangling empty name without declaration");
  868. if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
  869. if (NS->isAnonymousNamespace()) {
  870. Out << "?A0x" << Context.getAnonymousNamespaceHash() << '@';
  871. break;
  872. }
  873. }
  874. if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(ND)) {
  875. // Decomposition declarations are considered anonymous, and get
  876. // numbered with a $S prefix.
  877. llvm::SmallString<64> Name("$S");
  878. // Get a unique id for the anonymous struct.
  879. Name += llvm::utostr(Context.getAnonymousStructId(DD) + 1);
  880. mangleSourceName(Name);
  881. break;
  882. }
  883. if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
  884. // We must have an anonymous union or struct declaration.
  885. const CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl();
  886. assert(RD && "expected variable decl to have a record type");
  887. // Anonymous types with no tag or typedef get the name of their
  888. // declarator mangled in. If they have no declarator, number them with
  889. // a $S prefix.
  890. llvm::SmallString<64> Name("$S");
  891. // Get a unique id for the anonymous struct.
  892. Name += llvm::utostr(Context.getAnonymousStructId(RD) + 1);
  893. mangleSourceName(Name.str());
  894. break;
  895. }
  896. if (const MSGuidDecl *GD = dyn_cast<MSGuidDecl>(ND)) {
  897. // Mangle a GUID object as if it were a variable with the corresponding
  898. // mangled name.
  899. SmallString<sizeof("_GUID_12345678_1234_1234_1234_1234567890ab")> GUID;
  900. llvm::raw_svector_ostream GUIDOS(GUID);
  901. Context.mangleMSGuidDecl(GD, GUIDOS);
  902. mangleSourceName(GUID);
  903. break;
  904. }
  905. if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
  906. Out << "?__N";
  907. mangleTemplateArgValue(TPO->getType().getUnqualifiedType(),
  908. TPO->getValue());
  909. break;
  910. }
  911. // We must have an anonymous struct.
  912. const TagDecl *TD = cast<TagDecl>(ND);
  913. if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
  914. assert(TD->getDeclContext() == D->getDeclContext() &&
  915. "Typedef should not be in another decl context!");
  916. assert(D->getDeclName().getAsIdentifierInfo() &&
  917. "Typedef was not named!");
  918. mangleSourceName(D->getDeclName().getAsIdentifierInfo()->getName());
  919. break;
  920. }
  921. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
  922. if (Record->isLambda()) {
  923. llvm::SmallString<10> Name("<lambda_");
  924. Decl *LambdaContextDecl = Record->getLambdaContextDecl();
  925. unsigned LambdaManglingNumber = Record->getLambdaManglingNumber();
  926. unsigned LambdaId;
  927. const ParmVarDecl *Parm =
  928. dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl);
  929. const FunctionDecl *Func =
  930. Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr;
  931. if (Func) {
  932. unsigned DefaultArgNo =
  933. Func->getNumParams() - Parm->getFunctionScopeIndex();
  934. Name += llvm::utostr(DefaultArgNo);
  935. Name += "_";
  936. }
  937. if (LambdaManglingNumber)
  938. LambdaId = LambdaManglingNumber;
  939. else
  940. LambdaId = Context.getLambdaId(Record);
  941. Name += llvm::utostr(LambdaId);
  942. Name += ">";
  943. mangleSourceName(Name);
  944. // If the context is a variable or a class member and not a parameter,
  945. // it is encoded in a qualified name.
  946. if (LambdaManglingNumber && LambdaContextDecl) {
  947. if ((isa<VarDecl>(LambdaContextDecl) ||
  948. isa<FieldDecl>(LambdaContextDecl)) &&
  949. !isa<ParmVarDecl>(LambdaContextDecl)) {
  950. mangleUnqualifiedName(cast<NamedDecl>(LambdaContextDecl));
  951. }
  952. }
  953. break;
  954. }
  955. }
  956. llvm::SmallString<64> Name;
  957. if (DeclaratorDecl *DD =
  958. Context.getASTContext().getDeclaratorForUnnamedTagDecl(TD)) {
  959. // Anonymous types without a name for linkage purposes have their
  960. // declarator mangled in if they have one.
  961. Name += "<unnamed-type-";
  962. Name += DD->getName();
  963. } else if (TypedefNameDecl *TND =
  964. Context.getASTContext().getTypedefNameForUnnamedTagDecl(
  965. TD)) {
  966. // Anonymous types without a name for linkage purposes have their
  967. // associate typedef mangled in if they have one.
  968. Name += "<unnamed-type-";
  969. Name += TND->getName();
  970. } else if (isa<EnumDecl>(TD) &&
  971. cast<EnumDecl>(TD)->enumerator_begin() !=
  972. cast<EnumDecl>(TD)->enumerator_end()) {
  973. // Anonymous non-empty enums mangle in the first enumerator.
  974. auto *ED = cast<EnumDecl>(TD);
  975. Name += "<unnamed-enum-";
  976. Name += ED->enumerator_begin()->getName();
  977. } else {
  978. // Otherwise, number the types using a $S prefix.
  979. Name += "<unnamed-type-$S";
  980. Name += llvm::utostr(Context.getAnonymousStructId(TD) + 1);
  981. }
  982. Name += ">";
  983. mangleSourceName(Name.str());
  984. break;
  985. }
  986. case DeclarationName::ObjCZeroArgSelector:
  987. case DeclarationName::ObjCOneArgSelector:
  988. case DeclarationName::ObjCMultiArgSelector: {
  989. // This is reachable only when constructing an outlined SEH finally
  990. // block. Nothing depends on this mangling and it's used only with
  991. // functinos with internal linkage.
  992. llvm::SmallString<64> Name;
  993. mangleSourceName(Name.str());
  994. break;
  995. }
  996. case DeclarationName::CXXConstructorName:
  997. if (isStructorDecl(ND)) {
  998. if (StructorType == Ctor_CopyingClosure) {
  999. Out << "?_O";
  1000. return;
  1001. }
  1002. if (StructorType == Ctor_DefaultClosure) {
  1003. Out << "?_F";
  1004. return;
  1005. }
  1006. }
  1007. Out << "?0";
  1008. return;
  1009. case DeclarationName::CXXDestructorName:
  1010. if (isStructorDecl(ND))
  1011. // If the named decl is the C++ destructor we're mangling,
  1012. // use the type we were given.
  1013. mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
  1014. else
  1015. // Otherwise, use the base destructor name. This is relevant if a
  1016. // class with a destructor is declared within a destructor.
  1017. mangleCXXDtorType(Dtor_Base);
  1018. break;
  1019. case DeclarationName::CXXConversionFunctionName:
  1020. // <operator-name> ::= ?B # (cast)
  1021. // The target type is encoded as the return type.
  1022. Out << "?B";
  1023. break;
  1024. case DeclarationName::CXXOperatorName:
  1025. mangleOperatorName(Name.getCXXOverloadedOperator(), ND->getLocation());
  1026. break;
  1027. case DeclarationName::CXXLiteralOperatorName: {
  1028. Out << "?__K";
  1029. mangleSourceName(Name.getCXXLiteralIdentifier()->getName());
  1030. break;
  1031. }
  1032. case DeclarationName::CXXDeductionGuideName:
  1033. llvm_unreachable("Can't mangle a deduction guide name!");
  1034. case DeclarationName::CXXUsingDirective:
  1035. llvm_unreachable("Can't mangle a using directive name!");
  1036. }
  1037. }
  1038. // <postfix> ::= <unqualified-name> [<postfix>]
  1039. // ::= <substitution> [<postfix>]
  1040. void MicrosoftCXXNameMangler::mangleNestedName(GlobalDecl GD) {
  1041. const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
  1042. const DeclContext *DC = getEffectiveDeclContext(ND);
  1043. while (!DC->isTranslationUnit()) {
  1044. if (isa<TagDecl>(ND) || isa<VarDecl>(ND)) {
  1045. unsigned Disc;
  1046. if (Context.getNextDiscriminator(ND, Disc)) {
  1047. Out << '?';
  1048. mangleNumber(Disc);
  1049. Out << '?';
  1050. }
  1051. }
  1052. if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
  1053. auto Discriminate =
  1054. [](StringRef Name, const unsigned Discriminator,
  1055. const unsigned ParameterDiscriminator) -> std::string {
  1056. std::string Buffer;
  1057. llvm::raw_string_ostream Stream(Buffer);
  1058. Stream << Name;
  1059. if (Discriminator)
  1060. Stream << '_' << Discriminator;
  1061. if (ParameterDiscriminator)
  1062. Stream << '_' << ParameterDiscriminator;
  1063. return Stream.str();
  1064. };
  1065. unsigned Discriminator = BD->getBlockManglingNumber();
  1066. if (!Discriminator)
  1067. Discriminator = Context.getBlockId(BD, /*Local=*/false);
  1068. // Mangle the parameter position as a discriminator to deal with unnamed
  1069. // parameters. Rather than mangling the unqualified parameter name,
  1070. // always use the position to give a uniform mangling.
  1071. unsigned ParameterDiscriminator = 0;
  1072. if (const auto *MC = BD->getBlockManglingContextDecl())
  1073. if (const auto *P = dyn_cast<ParmVarDecl>(MC))
  1074. if (const auto *F = dyn_cast<FunctionDecl>(P->getDeclContext()))
  1075. ParameterDiscriminator =
  1076. F->getNumParams() - P->getFunctionScopeIndex();
  1077. DC = getEffectiveDeclContext(BD);
  1078. Out << '?';
  1079. mangleSourceName(Discriminate("_block_invoke", Discriminator,
  1080. ParameterDiscriminator));
  1081. // If we have a block mangling context, encode that now. This allows us
  1082. // to discriminate between named static data initializers in the same
  1083. // scope. This is handled differently from parameters, which use
  1084. // positions to discriminate between multiple instances.
  1085. if (const auto *MC = BD->getBlockManglingContextDecl())
  1086. if (!isa<ParmVarDecl>(MC))
  1087. if (const auto *ND = dyn_cast<NamedDecl>(MC))
  1088. mangleUnqualifiedName(ND);
  1089. // MS ABI and Itanium manglings are in inverted scopes. In the case of a
  1090. // RecordDecl, mangle the entire scope hierarchy at this point rather than
  1091. // just the unqualified name to get the ordering correct.
  1092. if (const auto *RD = dyn_cast<RecordDecl>(DC))
  1093. mangleName(RD);
  1094. else
  1095. Out << '@';
  1096. // void __cdecl
  1097. Out << "YAX";
  1098. // struct __block_literal *
  1099. Out << 'P';
  1100. // __ptr64
  1101. if (PointersAre64Bit)
  1102. Out << 'E';
  1103. Out << 'A';
  1104. mangleArtificialTagType(TTK_Struct,
  1105. Discriminate("__block_literal", Discriminator,
  1106. ParameterDiscriminator));
  1107. Out << "@Z";
  1108. // If the effective context was a Record, we have fully mangled the
  1109. // qualified name and do not need to continue.
  1110. if (isa<RecordDecl>(DC))
  1111. break;
  1112. continue;
  1113. } else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC)) {
  1114. mangleObjCMethodName(Method);
  1115. } else if (isa<NamedDecl>(DC)) {
  1116. ND = cast<NamedDecl>(DC);
  1117. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  1118. mangle(getGlobalDeclAsDeclContext(FD), "?");
  1119. break;
  1120. } else {
  1121. mangleUnqualifiedName(ND);
  1122. // Lambdas in default arguments conceptually belong to the function the
  1123. // parameter corresponds to.
  1124. if (const auto *LDADC = getLambdaDefaultArgumentDeclContext(ND)) {
  1125. DC = LDADC;
  1126. continue;
  1127. }
  1128. }
  1129. }
  1130. DC = DC->getParent();
  1131. }
  1132. }
  1133. void MicrosoftCXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
  1134. // Microsoft uses the names on the case labels for these dtor variants. Clang
  1135. // uses the Itanium terminology internally. Everything in this ABI delegates
  1136. // towards the base dtor.
  1137. switch (T) {
  1138. // <operator-name> ::= ?1 # destructor
  1139. case Dtor_Base: Out << "?1"; return;
  1140. // <operator-name> ::= ?_D # vbase destructor
  1141. case Dtor_Complete: Out << "?_D"; return;
  1142. // <operator-name> ::= ?_G # scalar deleting destructor
  1143. case Dtor_Deleting: Out << "?_G"; return;
  1144. // <operator-name> ::= ?_E # vector deleting destructor
  1145. // FIXME: Add a vector deleting dtor type. It goes in the vtable, so we need
  1146. // it.
  1147. case Dtor_Comdat:
  1148. llvm_unreachable("not expecting a COMDAT");
  1149. }
  1150. llvm_unreachable("Unsupported dtor type?");
  1151. }
  1152. void MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO,
  1153. SourceLocation Loc) {
  1154. switch (OO) {
  1155. // ?0 # constructor
  1156. // ?1 # destructor
  1157. // <operator-name> ::= ?2 # new
  1158. case OO_New: Out << "?2"; break;
  1159. // <operator-name> ::= ?3 # delete
  1160. case OO_Delete: Out << "?3"; break;
  1161. // <operator-name> ::= ?4 # =
  1162. case OO_Equal: Out << "?4"; break;
  1163. // <operator-name> ::= ?5 # >>
  1164. case OO_GreaterGreater: Out << "?5"; break;
  1165. // <operator-name> ::= ?6 # <<
  1166. case OO_LessLess: Out << "?6"; break;
  1167. // <operator-name> ::= ?7 # !
  1168. case OO_Exclaim: Out << "?7"; break;
  1169. // <operator-name> ::= ?8 # ==
  1170. case OO_EqualEqual: Out << "?8"; break;
  1171. // <operator-name> ::= ?9 # !=
  1172. case OO_ExclaimEqual: Out << "?9"; break;
  1173. // <operator-name> ::= ?A # []
  1174. case OO_Subscript: Out << "?A"; break;
  1175. // ?B # conversion
  1176. // <operator-name> ::= ?C # ->
  1177. case OO_Arrow: Out << "?C"; break;
  1178. // <operator-name> ::= ?D # *
  1179. case OO_Star: Out << "?D"; break;
  1180. // <operator-name> ::= ?E # ++
  1181. case OO_PlusPlus: Out << "?E"; break;
  1182. // <operator-name> ::= ?F # --
  1183. case OO_MinusMinus: Out << "?F"; break;
  1184. // <operator-name> ::= ?G # -
  1185. case OO_Minus: Out << "?G"; break;
  1186. // <operator-name> ::= ?H # +
  1187. case OO_Plus: Out << "?H"; break;
  1188. // <operator-name> ::= ?I # &
  1189. case OO_Amp: Out << "?I"; break;
  1190. // <operator-name> ::= ?J # ->*
  1191. case OO_ArrowStar: Out << "?J"; break;
  1192. // <operator-name> ::= ?K # /
  1193. case OO_Slash: Out << "?K"; break;
  1194. // <operator-name> ::= ?L # %
  1195. case OO_Percent: Out << "?L"; break;
  1196. // <operator-name> ::= ?M # <
  1197. case OO_Less: Out << "?M"; break;
  1198. // <operator-name> ::= ?N # <=
  1199. case OO_LessEqual: Out << "?N"; break;
  1200. // <operator-name> ::= ?O # >
  1201. case OO_Greater: Out << "?O"; break;
  1202. // <operator-name> ::= ?P # >=
  1203. case OO_GreaterEqual: Out << "?P"; break;
  1204. // <operator-name> ::= ?Q # ,
  1205. case OO_Comma: Out << "?Q"; break;
  1206. // <operator-name> ::= ?R # ()
  1207. case OO_Call: Out << "?R"; break;
  1208. // <operator-name> ::= ?S # ~
  1209. case OO_Tilde: Out << "?S"; break;
  1210. // <operator-name> ::= ?T # ^
  1211. case OO_Caret: Out << "?T"; break;
  1212. // <operator-name> ::= ?U # |
  1213. case OO_Pipe: Out << "?U"; break;
  1214. // <operator-name> ::= ?V # &&
  1215. case OO_AmpAmp: Out << "?V"; break;
  1216. // <operator-name> ::= ?W # ||
  1217. case OO_PipePipe: Out << "?W"; break;
  1218. // <operator-name> ::= ?X # *=
  1219. case OO_StarEqual: Out << "?X"; break;
  1220. // <operator-name> ::= ?Y # +=
  1221. case OO_PlusEqual: Out << "?Y"; break;
  1222. // <operator-name> ::= ?Z # -=
  1223. case OO_MinusEqual: Out << "?Z"; break;
  1224. // <operator-name> ::= ?_0 # /=
  1225. case OO_SlashEqual: Out << "?_0"; break;
  1226. // <operator-name> ::= ?_1 # %=
  1227. case OO_PercentEqual: Out << "?_1"; break;
  1228. // <operator-name> ::= ?_2 # >>=
  1229. case OO_GreaterGreaterEqual: Out << "?_2"; break;
  1230. // <operator-name> ::= ?_3 # <<=
  1231. case OO_LessLessEqual: Out << "?_3"; break;
  1232. // <operator-name> ::= ?_4 # &=
  1233. case OO_AmpEqual: Out << "?_4"; break;
  1234. // <operator-name> ::= ?_5 # |=
  1235. case OO_PipeEqual: Out << "?_5"; break;
  1236. // <operator-name> ::= ?_6 # ^=
  1237. case OO_CaretEqual: Out << "?_6"; break;
  1238. // ?_7 # vftable
  1239. // ?_8 # vbtable
  1240. // ?_9 # vcall
  1241. // ?_A # typeof
  1242. // ?_B # local static guard
  1243. // ?_C # string
  1244. // ?_D # vbase destructor
  1245. // ?_E # vector deleting destructor
  1246. // ?_F # default constructor closure
  1247. // ?_G # scalar deleting destructor
  1248. // ?_H # vector constructor iterator
  1249. // ?_I # vector destructor iterator
  1250. // ?_J # vector vbase constructor iterator
  1251. // ?_K # virtual displacement map
  1252. // ?_L # eh vector constructor iterator
  1253. // ?_M # eh vector destructor iterator
  1254. // ?_N # eh vector vbase constructor iterator
  1255. // ?_O # copy constructor closure
  1256. // ?_P<name> # udt returning <name>
  1257. // ?_Q # <unknown>
  1258. // ?_R0 # RTTI Type Descriptor
  1259. // ?_R1 # RTTI Base Class Descriptor at (a,b,c,d)
  1260. // ?_R2 # RTTI Base Class Array
  1261. // ?_R3 # RTTI Class Hierarchy Descriptor
  1262. // ?_R4 # RTTI Complete Object Locator
  1263. // ?_S # local vftable
  1264. // ?_T # local vftable constructor closure
  1265. // <operator-name> ::= ?_U # new[]
  1266. case OO_Array_New: Out << "?_U"; break;
  1267. // <operator-name> ::= ?_V # delete[]
  1268. case OO_Array_Delete: Out << "?_V"; break;
  1269. // <operator-name> ::= ?__L # co_await
  1270. case OO_Coawait: Out << "?__L"; break;
  1271. // <operator-name> ::= ?__M # <=>
  1272. case OO_Spaceship: Out << "?__M"; break;
  1273. case OO_Conditional: {
  1274. DiagnosticsEngine &Diags = Context.getDiags();
  1275. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1276. "cannot mangle this conditional operator yet");
  1277. Diags.Report(Loc, DiagID);
  1278. break;
  1279. }
  1280. case OO_None:
  1281. case NUM_OVERLOADED_OPERATORS:
  1282. llvm_unreachable("Not an overloaded operator");
  1283. }
  1284. }
  1285. void MicrosoftCXXNameMangler::mangleSourceName(StringRef Name) {
  1286. // <source name> ::= <identifier> @
  1287. BackRefVec::iterator Found = llvm::find(NameBackReferences, Name);
  1288. if (Found == NameBackReferences.end()) {
  1289. if (NameBackReferences.size() < 10)
  1290. NameBackReferences.push_back(std::string(Name));
  1291. Out << Name << '@';
  1292. } else {
  1293. Out << (Found - NameBackReferences.begin());
  1294. }
  1295. }
  1296. void MicrosoftCXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
  1297. Context.mangleObjCMethodNameAsSourceName(MD, Out);
  1298. }
  1299. void MicrosoftCXXNameMangler::mangleTemplateInstantiationName(
  1300. GlobalDecl GD, const TemplateArgumentList &TemplateArgs) {
  1301. // <template-name> ::= <unscoped-template-name> <template-args>
  1302. // ::= <substitution>
  1303. // Always start with the unqualified name.
  1304. // Templates have their own context for back references.
  1305. ArgBackRefMap OuterFunArgsContext;
  1306. ArgBackRefMap OuterTemplateArgsContext;
  1307. BackRefVec OuterTemplateContext;
  1308. PassObjectSizeArgsSet OuterPassObjectSizeArgs;
  1309. NameBackReferences.swap(OuterTemplateContext);
  1310. FunArgBackReferences.swap(OuterFunArgsContext);
  1311. TemplateArgBackReferences.swap(OuterTemplateArgsContext);
  1312. PassObjectSizeArgs.swap(OuterPassObjectSizeArgs);
  1313. mangleUnscopedTemplateName(GD);
  1314. mangleTemplateArgs(cast<TemplateDecl>(GD.getDecl()), TemplateArgs);
  1315. // Restore the previous back reference contexts.
  1316. NameBackReferences.swap(OuterTemplateContext);
  1317. FunArgBackReferences.swap(OuterFunArgsContext);
  1318. TemplateArgBackReferences.swap(OuterTemplateArgsContext);
  1319. PassObjectSizeArgs.swap(OuterPassObjectSizeArgs);
  1320. }
  1321. void MicrosoftCXXNameMangler::mangleUnscopedTemplateName(GlobalDecl GD) {
  1322. // <unscoped-template-name> ::= ?$ <unqualified-name>
  1323. Out << "?$";
  1324. mangleUnqualifiedName(GD);
  1325. }
  1326. void MicrosoftCXXNameMangler::mangleIntegerLiteral(
  1327. const llvm::APSInt &Value, const NonTypeTemplateParmDecl *PD,
  1328. QualType TemplateArgType) {
  1329. // <integer-literal> ::= $0 <number>
  1330. Out << "$";
  1331. // Since MSVC 2019, add 'M[<type>]' after '$' for auto template parameter when
  1332. // argument is integer.
  1333. if (getASTContext().getLangOpts().isCompatibleWithMSVC(
  1334. LangOptions::MSVC2019) &&
  1335. PD && PD->getType()->getTypeClass() == Type::Auto &&
  1336. !TemplateArgType.isNull()) {
  1337. Out << "M";
  1338. mangleType(TemplateArgType, SourceRange(), QMM_Drop);
  1339. }
  1340. Out << "0";
  1341. mangleNumber(Value);
  1342. }
  1343. void MicrosoftCXXNameMangler::mangleExpression(
  1344. const Expr *E, const NonTypeTemplateParmDecl *PD) {
  1345. // See if this is a constant expression.
  1346. if (std::optional<llvm::APSInt> Value =
  1347. E->getIntegerConstantExpr(Context.getASTContext())) {
  1348. mangleIntegerLiteral(*Value, PD, E->getType());
  1349. return;
  1350. }
  1351. // As bad as this diagnostic is, it's better than crashing.
  1352. DiagnosticsEngine &Diags = Context.getDiags();
  1353. unsigned DiagID = Diags.getCustomDiagID(
  1354. DiagnosticsEngine::Error, "cannot yet mangle expression type %0");
  1355. Diags.Report(E->getExprLoc(), DiagID) << E->getStmtClassName()
  1356. << E->getSourceRange();
  1357. }
  1358. void MicrosoftCXXNameMangler::mangleTemplateArgs(
  1359. const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
  1360. // <template-args> ::= <template-arg>+
  1361. const TemplateParameterList *TPL = TD->getTemplateParameters();
  1362. assert(TPL->size() == TemplateArgs.size() &&
  1363. "size mismatch between args and parms!");
  1364. for (size_t i = 0; i < TemplateArgs.size(); ++i) {
  1365. const TemplateArgument &TA = TemplateArgs[i];
  1366. // Separate consecutive packs by $$Z.
  1367. if (i > 0 && TA.getKind() == TemplateArgument::Pack &&
  1368. TemplateArgs[i - 1].getKind() == TemplateArgument::Pack)
  1369. Out << "$$Z";
  1370. mangleTemplateArg(TD, TA, TPL->getParam(i));
  1371. }
  1372. }
  1373. void MicrosoftCXXNameMangler::mangleTemplateArg(const TemplateDecl *TD,
  1374. const TemplateArgument &TA,
  1375. const NamedDecl *Parm) {
  1376. // <template-arg> ::= <type>
  1377. // ::= <integer-literal>
  1378. // ::= <member-data-pointer>
  1379. // ::= <member-function-pointer>
  1380. // ::= $ <constant-value>
  1381. // ::= <template-args>
  1382. //
  1383. // <constant-value> ::= 0 <number> # integer
  1384. // ::= 1 <mangled-name> # address of D
  1385. // ::= 2 <type> <typed-constant-value>* @ # struct
  1386. // ::= 3 <type> <constant-value>* @ # array
  1387. // ::= 4 ??? # string
  1388. // ::= 5 <constant-value> @ # address of subobject
  1389. // ::= 6 <constant-value> <unqualified-name> @ # a.b
  1390. // ::= 7 <type> [<unqualified-name> <constant-value>] @
  1391. // # union, with or without an active member
  1392. // # pointer to member, symbolically
  1393. // ::= 8 <class> <unqualified-name> @
  1394. // ::= A <type> <non-negative integer> # float
  1395. // ::= B <type> <non-negative integer> # double
  1396. // ::= E <mangled-name> # reference to D
  1397. // # pointer to member, by component value
  1398. // ::= F <number> <number>
  1399. // ::= G <number> <number> <number>
  1400. // ::= H <mangled-name> <number>
  1401. // ::= I <mangled-name> <number> <number>
  1402. // ::= J <mangled-name> <number> <number> <number>
  1403. //
  1404. // <typed-constant-value> ::= [<type>] <constant-value>
  1405. //
  1406. // The <type> appears to be included in a <typed-constant-value> only in the
  1407. // '0', '1', '8', 'A', 'B', and 'E' cases.
  1408. switch (TA.getKind()) {
  1409. case TemplateArgument::Null:
  1410. llvm_unreachable("Can't mangle null template arguments!");
  1411. case TemplateArgument::TemplateExpansion:
  1412. llvm_unreachable("Can't mangle template expansion arguments!");
  1413. case TemplateArgument::Type: {
  1414. QualType T = TA.getAsType();
  1415. mangleType(T, SourceRange(), QMM_Escape);
  1416. break;
  1417. }
  1418. case TemplateArgument::Declaration: {
  1419. const NamedDecl *ND = TA.getAsDecl();
  1420. if (isa<FieldDecl>(ND) || isa<IndirectFieldDecl>(ND)) {
  1421. mangleMemberDataPointer(cast<CXXRecordDecl>(ND->getDeclContext())
  1422. ->getMostRecentNonInjectedDecl(),
  1423. cast<ValueDecl>(ND));
  1424. } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  1425. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  1426. if (MD && MD->isInstance()) {
  1427. mangleMemberFunctionPointer(
  1428. MD->getParent()->getMostRecentNonInjectedDecl(), MD);
  1429. } else {
  1430. Out << "$1?";
  1431. mangleName(FD);
  1432. mangleFunctionEncoding(FD, /*ShouldMangle=*/true);
  1433. }
  1434. } else if (TA.getParamTypeForDecl()->isRecordType()) {
  1435. Out << "$";
  1436. auto *TPO = cast<TemplateParamObjectDecl>(ND);
  1437. mangleTemplateArgValue(TPO->getType().getUnqualifiedType(),
  1438. TPO->getValue());
  1439. } else {
  1440. mangle(ND, TA.getParamTypeForDecl()->isReferenceType() ? "$E?" : "$1?");
  1441. }
  1442. break;
  1443. }
  1444. case TemplateArgument::Integral: {
  1445. QualType T = TA.getIntegralType();
  1446. mangleIntegerLiteral(TA.getAsIntegral(),
  1447. cast<NonTypeTemplateParmDecl>(Parm), T);
  1448. break;
  1449. }
  1450. case TemplateArgument::NullPtr: {
  1451. QualType T = TA.getNullPtrType();
  1452. if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) {
  1453. const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
  1454. if (MPT->isMemberFunctionPointerType() &&
  1455. !isa<FunctionTemplateDecl>(TD)) {
  1456. mangleMemberFunctionPointer(RD, nullptr);
  1457. return;
  1458. }
  1459. if (MPT->isMemberDataPointer()) {
  1460. if (!isa<FunctionTemplateDecl>(TD)) {
  1461. mangleMemberDataPointer(RD, nullptr);
  1462. return;
  1463. }
  1464. // nullptr data pointers are always represented with a single field
  1465. // which is initialized with either 0 or -1. Why -1? Well, we need to
  1466. // distinguish the case where the data member is at offset zero in the
  1467. // record.
  1468. // However, we are free to use 0 *if* we would use multiple fields for
  1469. // non-nullptr member pointers.
  1470. if (!RD->nullFieldOffsetIsZero()) {
  1471. mangleIntegerLiteral(llvm::APSInt::get(-1),
  1472. cast<NonTypeTemplateParmDecl>(Parm), T);
  1473. return;
  1474. }
  1475. }
  1476. }
  1477. mangleIntegerLiteral(llvm::APSInt::getUnsigned(0),
  1478. cast<NonTypeTemplateParmDecl>(Parm), T);
  1479. break;
  1480. }
  1481. case TemplateArgument::Expression:
  1482. mangleExpression(TA.getAsExpr(), cast<NonTypeTemplateParmDecl>(Parm));
  1483. break;
  1484. case TemplateArgument::Pack: {
  1485. ArrayRef<TemplateArgument> TemplateArgs = TA.getPackAsArray();
  1486. if (TemplateArgs.empty()) {
  1487. if (isa<TemplateTypeParmDecl>(Parm) ||
  1488. isa<TemplateTemplateParmDecl>(Parm))
  1489. // MSVC 2015 changed the mangling for empty expanded template packs,
  1490. // use the old mangling for link compatibility for old versions.
  1491. Out << (Context.getASTContext().getLangOpts().isCompatibleWithMSVC(
  1492. LangOptions::MSVC2015)
  1493. ? "$$V"
  1494. : "$$$V");
  1495. else if (isa<NonTypeTemplateParmDecl>(Parm))
  1496. Out << "$S";
  1497. else
  1498. llvm_unreachable("unexpected template parameter decl!");
  1499. } else {
  1500. for (const TemplateArgument &PA : TemplateArgs)
  1501. mangleTemplateArg(TD, PA, Parm);
  1502. }
  1503. break;
  1504. }
  1505. case TemplateArgument::Template: {
  1506. const NamedDecl *ND =
  1507. TA.getAsTemplate().getAsTemplateDecl()->getTemplatedDecl();
  1508. if (const auto *TD = dyn_cast<TagDecl>(ND)) {
  1509. mangleType(TD);
  1510. } else if (isa<TypeAliasDecl>(ND)) {
  1511. Out << "$$Y";
  1512. mangleName(ND);
  1513. } else {
  1514. llvm_unreachable("unexpected template template NamedDecl!");
  1515. }
  1516. break;
  1517. }
  1518. }
  1519. }
  1520. void MicrosoftCXXNameMangler::mangleTemplateArgValue(QualType T,
  1521. const APValue &V,
  1522. bool WithScalarType) {
  1523. switch (V.getKind()) {
  1524. case APValue::None:
  1525. case APValue::Indeterminate:
  1526. // FIXME: MSVC doesn't allow this, so we can't be sure how it should be
  1527. // mangled.
  1528. if (WithScalarType)
  1529. mangleType(T, SourceRange(), QMM_Escape);
  1530. Out << '@';
  1531. return;
  1532. case APValue::Int:
  1533. if (WithScalarType)
  1534. mangleType(T, SourceRange(), QMM_Escape);
  1535. Out << '0';
  1536. mangleNumber(V.getInt());
  1537. return;
  1538. case APValue::Float:
  1539. if (WithScalarType)
  1540. mangleType(T, SourceRange(), QMM_Escape);
  1541. mangleFloat(V.getFloat());
  1542. return;
  1543. case APValue::LValue: {
  1544. if (WithScalarType)
  1545. mangleType(T, SourceRange(), QMM_Escape);
  1546. // We don't know how to mangle past-the-end pointers yet.
  1547. if (V.isLValueOnePastTheEnd())
  1548. break;
  1549. APValue::LValueBase Base = V.getLValueBase();
  1550. if (!V.hasLValuePath() || V.getLValuePath().empty()) {
  1551. // Taking the address of a complete object has a special-case mangling.
  1552. if (Base.isNull()) {
  1553. // MSVC emits 0A@ for null pointers. Generalize this for arbitrary
  1554. // integers cast to pointers.
  1555. // FIXME: This mangles 0 cast to a pointer the same as a null pointer,
  1556. // even in cases where the two are different values.
  1557. Out << "0";
  1558. mangleNumber(V.getLValueOffset().getQuantity());
  1559. } else if (!V.hasLValuePath()) {
  1560. // FIXME: This can only happen as an extension. Invent a mangling.
  1561. break;
  1562. } else if (auto *VD = Base.dyn_cast<const ValueDecl*>()) {
  1563. Out << (T->isReferenceType() ? "E" : "1");
  1564. mangle(VD);
  1565. } else {
  1566. break;
  1567. }
  1568. } else {
  1569. unsigned NumAts = 0;
  1570. if (T->isPointerType()) {
  1571. Out << "5";
  1572. ++NumAts;
  1573. }
  1574. QualType T = Base.getType();
  1575. for (APValue::LValuePathEntry E : V.getLValuePath()) {
  1576. // We don't know how to mangle array subscripting yet.
  1577. if (T->isArrayType())
  1578. goto mangling_unknown;
  1579. const Decl *D = E.getAsBaseOrMember().getPointer();
  1580. auto *FD = dyn_cast<FieldDecl>(D);
  1581. // We don't know how to mangle derived-to-base conversions yet.
  1582. if (!FD)
  1583. goto mangling_unknown;
  1584. Out << "6";
  1585. ++NumAts;
  1586. T = FD->getType();
  1587. }
  1588. auto *VD = Base.dyn_cast<const ValueDecl*>();
  1589. if (!VD)
  1590. break;
  1591. Out << "E";
  1592. mangle(VD);
  1593. for (APValue::LValuePathEntry E : V.getLValuePath()) {
  1594. const Decl *D = E.getAsBaseOrMember().getPointer();
  1595. mangleUnqualifiedName(cast<FieldDecl>(D));
  1596. }
  1597. for (unsigned I = 0; I != NumAts; ++I)
  1598. Out << '@';
  1599. }
  1600. return;
  1601. }
  1602. case APValue::MemberPointer: {
  1603. if (WithScalarType)
  1604. mangleType(T, SourceRange(), QMM_Escape);
  1605. // FIXME: The below manglings don't include a conversion, so bail if there
  1606. // would be one. MSVC mangles the (possibly converted) value of the
  1607. // pointer-to-member object as if it were a struct, leading to collisions
  1608. // in some cases.
  1609. if (!V.getMemberPointerPath().empty())
  1610. break;
  1611. const CXXRecordDecl *RD =
  1612. T->castAs<MemberPointerType>()->getMostRecentCXXRecordDecl();
  1613. const ValueDecl *D = V.getMemberPointerDecl();
  1614. if (T->isMemberDataPointerType())
  1615. mangleMemberDataPointer(RD, D, "");
  1616. else
  1617. mangleMemberFunctionPointer(RD, cast_or_null<CXXMethodDecl>(D), "");
  1618. return;
  1619. }
  1620. case APValue::Struct: {
  1621. Out << '2';
  1622. mangleType(T, SourceRange(), QMM_Escape);
  1623. const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
  1624. assert(RD && "unexpected type for record value");
  1625. unsigned BaseIndex = 0;
  1626. for (const CXXBaseSpecifier &B : RD->bases())
  1627. mangleTemplateArgValue(B.getType(), V.getStructBase(BaseIndex++));
  1628. for (const FieldDecl *FD : RD->fields())
  1629. if (!FD->isUnnamedBitfield())
  1630. mangleTemplateArgValue(FD->getType(),
  1631. V.getStructField(FD->getFieldIndex()),
  1632. /*WithScalarType*/ true);
  1633. Out << '@';
  1634. return;
  1635. }
  1636. case APValue::Union:
  1637. Out << '7';
  1638. mangleType(T, SourceRange(), QMM_Escape);
  1639. if (const FieldDecl *FD = V.getUnionField()) {
  1640. mangleUnqualifiedName(FD);
  1641. mangleTemplateArgValue(FD->getType(), V.getUnionValue());
  1642. }
  1643. Out << '@';
  1644. return;
  1645. case APValue::ComplexInt:
  1646. // We mangle complex types as structs, so mangle the value as a struct too.
  1647. Out << '2';
  1648. mangleType(T, SourceRange(), QMM_Escape);
  1649. Out << '0';
  1650. mangleNumber(V.getComplexIntReal());
  1651. Out << '0';
  1652. mangleNumber(V.getComplexIntImag());
  1653. Out << '@';
  1654. return;
  1655. case APValue::ComplexFloat:
  1656. Out << '2';
  1657. mangleType(T, SourceRange(), QMM_Escape);
  1658. mangleFloat(V.getComplexFloatReal());
  1659. mangleFloat(V.getComplexFloatImag());
  1660. Out << '@';
  1661. return;
  1662. case APValue::Array: {
  1663. Out << '3';
  1664. QualType ElemT = getASTContext().getAsArrayType(T)->getElementType();
  1665. mangleType(ElemT, SourceRange(), QMM_Escape);
  1666. for (unsigned I = 0, N = V.getArraySize(); I != N; ++I) {
  1667. const APValue &ElemV = I < V.getArrayInitializedElts()
  1668. ? V.getArrayInitializedElt(I)
  1669. : V.getArrayFiller();
  1670. mangleTemplateArgValue(ElemT, ElemV);
  1671. Out << '@';
  1672. }
  1673. Out << '@';
  1674. return;
  1675. }
  1676. case APValue::Vector: {
  1677. // __m128 is mangled as a struct containing an array. We follow this
  1678. // approach for all vector types.
  1679. Out << '2';
  1680. mangleType(T, SourceRange(), QMM_Escape);
  1681. Out << '3';
  1682. QualType ElemT = T->castAs<VectorType>()->getElementType();
  1683. mangleType(ElemT, SourceRange(), QMM_Escape);
  1684. for (unsigned I = 0, N = V.getVectorLength(); I != N; ++I) {
  1685. const APValue &ElemV = V.getVectorElt(I);
  1686. mangleTemplateArgValue(ElemT, ElemV);
  1687. Out << '@';
  1688. }
  1689. Out << "@@";
  1690. return;
  1691. }
  1692. case APValue::AddrLabelDiff:
  1693. case APValue::FixedPoint:
  1694. break;
  1695. }
  1696. mangling_unknown:
  1697. DiagnosticsEngine &Diags = Context.getDiags();
  1698. unsigned DiagID = Diags.getCustomDiagID(
  1699. DiagnosticsEngine::Error, "cannot mangle this template argument yet");
  1700. Diags.Report(DiagID);
  1701. }
  1702. void MicrosoftCXXNameMangler::mangleObjCProtocol(const ObjCProtocolDecl *PD) {
  1703. llvm::SmallString<64> TemplateMangling;
  1704. llvm::raw_svector_ostream Stream(TemplateMangling);
  1705. MicrosoftCXXNameMangler Extra(Context, Stream);
  1706. Stream << "?$";
  1707. Extra.mangleSourceName("Protocol");
  1708. Extra.mangleArtificialTagType(TTK_Struct, PD->getName());
  1709. mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__ObjC"});
  1710. }
  1711. void MicrosoftCXXNameMangler::mangleObjCLifetime(const QualType Type,
  1712. Qualifiers Quals,
  1713. SourceRange Range) {
  1714. llvm::SmallString<64> TemplateMangling;
  1715. llvm::raw_svector_ostream Stream(TemplateMangling);
  1716. MicrosoftCXXNameMangler Extra(Context, Stream);
  1717. Stream << "?$";
  1718. switch (Quals.getObjCLifetime()) {
  1719. case Qualifiers::OCL_None:
  1720. case Qualifiers::OCL_ExplicitNone:
  1721. break;
  1722. case Qualifiers::OCL_Autoreleasing:
  1723. Extra.mangleSourceName("Autoreleasing");
  1724. break;
  1725. case Qualifiers::OCL_Strong:
  1726. Extra.mangleSourceName("Strong");
  1727. break;
  1728. case Qualifiers::OCL_Weak:
  1729. Extra.mangleSourceName("Weak");
  1730. break;
  1731. }
  1732. Extra.manglePointerCVQualifiers(Quals);
  1733. Extra.manglePointerExtQualifiers(Quals, Type);
  1734. Extra.mangleType(Type, Range);
  1735. mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__ObjC"});
  1736. }
  1737. void MicrosoftCXXNameMangler::mangleObjCKindOfType(const ObjCObjectType *T,
  1738. Qualifiers Quals,
  1739. SourceRange Range) {
  1740. llvm::SmallString<64> TemplateMangling;
  1741. llvm::raw_svector_ostream Stream(TemplateMangling);
  1742. MicrosoftCXXNameMangler Extra(Context, Stream);
  1743. Stream << "?$";
  1744. Extra.mangleSourceName("KindOf");
  1745. Extra.mangleType(QualType(T, 0)
  1746. .stripObjCKindOfType(getASTContext())
  1747. ->castAs<ObjCObjectType>(),
  1748. Quals, Range);
  1749. mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__ObjC"});
  1750. }
  1751. void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals,
  1752. bool IsMember) {
  1753. // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers>
  1754. // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only);
  1755. // 'I' means __restrict (32/64-bit).
  1756. // Note that the MSVC __restrict keyword isn't the same as the C99 restrict
  1757. // keyword!
  1758. // <base-cvr-qualifiers> ::= A # near
  1759. // ::= B # near const
  1760. // ::= C # near volatile
  1761. // ::= D # near const volatile
  1762. // ::= E # far (16-bit)
  1763. // ::= F # far const (16-bit)
  1764. // ::= G # far volatile (16-bit)
  1765. // ::= H # far const volatile (16-bit)
  1766. // ::= I # huge (16-bit)
  1767. // ::= J # huge const (16-bit)
  1768. // ::= K # huge volatile (16-bit)
  1769. // ::= L # huge const volatile (16-bit)
  1770. // ::= M <basis> # based
  1771. // ::= N <basis> # based const
  1772. // ::= O <basis> # based volatile
  1773. // ::= P <basis> # based const volatile
  1774. // ::= Q # near member
  1775. // ::= R # near const member
  1776. // ::= S # near volatile member
  1777. // ::= T # near const volatile member
  1778. // ::= U # far member (16-bit)
  1779. // ::= V # far const member (16-bit)
  1780. // ::= W # far volatile member (16-bit)
  1781. // ::= X # far const volatile member (16-bit)
  1782. // ::= Y # huge member (16-bit)
  1783. // ::= Z # huge const member (16-bit)
  1784. // ::= 0 # huge volatile member (16-bit)
  1785. // ::= 1 # huge const volatile member (16-bit)
  1786. // ::= 2 <basis> # based member
  1787. // ::= 3 <basis> # based const member
  1788. // ::= 4 <basis> # based volatile member
  1789. // ::= 5 <basis> # based const volatile member
  1790. // ::= 6 # near function (pointers only)
  1791. // ::= 7 # far function (pointers only)
  1792. // ::= 8 # near method (pointers only)
  1793. // ::= 9 # far method (pointers only)
  1794. // ::= _A <basis> # based function (pointers only)
  1795. // ::= _B <basis> # based function (far?) (pointers only)
  1796. // ::= _C <basis> # based method (pointers only)
  1797. // ::= _D <basis> # based method (far?) (pointers only)
  1798. // ::= _E # block (Clang)
  1799. // <basis> ::= 0 # __based(void)
  1800. // ::= 1 # __based(segment)?
  1801. // ::= 2 <name> # __based(name)
  1802. // ::= 3 # ?
  1803. // ::= 4 # ?
  1804. // ::= 5 # not really based
  1805. bool HasConst = Quals.hasConst(),
  1806. HasVolatile = Quals.hasVolatile();
  1807. if (!IsMember) {
  1808. if (HasConst && HasVolatile) {
  1809. Out << 'D';
  1810. } else if (HasVolatile) {
  1811. Out << 'C';
  1812. } else if (HasConst) {
  1813. Out << 'B';
  1814. } else {
  1815. Out << 'A';
  1816. }
  1817. } else {
  1818. if (HasConst && HasVolatile) {
  1819. Out << 'T';
  1820. } else if (HasVolatile) {
  1821. Out << 'S';
  1822. } else if (HasConst) {
  1823. Out << 'R';
  1824. } else {
  1825. Out << 'Q';
  1826. }
  1827. }
  1828. // FIXME: For now, just drop all extension qualifiers on the floor.
  1829. }
  1830. void
  1831. MicrosoftCXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
  1832. // <ref-qualifier> ::= G # lvalue reference
  1833. // ::= H # rvalue-reference
  1834. switch (RefQualifier) {
  1835. case RQ_None:
  1836. break;
  1837. case RQ_LValue:
  1838. Out << 'G';
  1839. break;
  1840. case RQ_RValue:
  1841. Out << 'H';
  1842. break;
  1843. }
  1844. }
  1845. void MicrosoftCXXNameMangler::manglePointerExtQualifiers(Qualifiers Quals,
  1846. QualType PointeeType) {
  1847. // Check if this is a default 64-bit pointer or has __ptr64 qualifier.
  1848. bool is64Bit = PointeeType.isNull() ? PointersAre64Bit :
  1849. is64BitPointer(PointeeType.getQualifiers());
  1850. if (is64Bit && (PointeeType.isNull() || !PointeeType->isFunctionType()))
  1851. Out << 'E';
  1852. if (Quals.hasRestrict())
  1853. Out << 'I';
  1854. if (Quals.hasUnaligned() ||
  1855. (!PointeeType.isNull() && PointeeType.getLocalQualifiers().hasUnaligned()))
  1856. Out << 'F';
  1857. }
  1858. void MicrosoftCXXNameMangler::manglePointerCVQualifiers(Qualifiers Quals) {
  1859. // <pointer-cv-qualifiers> ::= P # no qualifiers
  1860. // ::= Q # const
  1861. // ::= R # volatile
  1862. // ::= S # const volatile
  1863. bool HasConst = Quals.hasConst(),
  1864. HasVolatile = Quals.hasVolatile();
  1865. if (HasConst && HasVolatile) {
  1866. Out << 'S';
  1867. } else if (HasVolatile) {
  1868. Out << 'R';
  1869. } else if (HasConst) {
  1870. Out << 'Q';
  1871. } else {
  1872. Out << 'P';
  1873. }
  1874. }
  1875. void MicrosoftCXXNameMangler::mangleFunctionArgumentType(QualType T,
  1876. SourceRange Range) {
  1877. // MSVC will backreference two canonically equivalent types that have slightly
  1878. // different manglings when mangled alone.
  1879. // Decayed types do not match up with non-decayed versions of the same type.
  1880. //
  1881. // e.g.
  1882. // void (*x)(void) will not form a backreference with void x(void)
  1883. void *TypePtr;
  1884. if (const auto *DT = T->getAs<DecayedType>()) {
  1885. QualType OriginalType = DT->getOriginalType();
  1886. // All decayed ArrayTypes should be treated identically; as-if they were
  1887. // a decayed IncompleteArrayType.
  1888. if (const auto *AT = getASTContext().getAsArrayType(OriginalType))
  1889. OriginalType = getASTContext().getIncompleteArrayType(
  1890. AT->getElementType(), AT->getSizeModifier(),
  1891. AT->getIndexTypeCVRQualifiers());
  1892. TypePtr = OriginalType.getCanonicalType().getAsOpaquePtr();
  1893. // If the original parameter was textually written as an array,
  1894. // instead treat the decayed parameter like it's const.
  1895. //
  1896. // e.g.
  1897. // int [] -> int * const
  1898. if (OriginalType->isArrayType())
  1899. T = T.withConst();
  1900. } else {
  1901. TypePtr = T.getCanonicalType().getAsOpaquePtr();
  1902. }
  1903. ArgBackRefMap::iterator Found = FunArgBackReferences.find(TypePtr);
  1904. if (Found == FunArgBackReferences.end()) {
  1905. size_t OutSizeBefore = Out.tell();
  1906. mangleType(T, Range, QMM_Drop);
  1907. // See if it's worth creating a back reference.
  1908. // Only types longer than 1 character are considered
  1909. // and only 10 back references slots are available:
  1910. bool LongerThanOneChar = (Out.tell() - OutSizeBefore > 1);
  1911. if (LongerThanOneChar && FunArgBackReferences.size() < 10) {
  1912. size_t Size = FunArgBackReferences.size();
  1913. FunArgBackReferences[TypePtr] = Size;
  1914. }
  1915. } else {
  1916. Out << Found->second;
  1917. }
  1918. }
  1919. void MicrosoftCXXNameMangler::manglePassObjectSizeArg(
  1920. const PassObjectSizeAttr *POSA) {
  1921. int Type = POSA->getType();
  1922. bool Dynamic = POSA->isDynamic();
  1923. auto Iter = PassObjectSizeArgs.insert({Type, Dynamic}).first;
  1924. auto *TypePtr = (const void *)&*Iter;
  1925. ArgBackRefMap::iterator Found = FunArgBackReferences.find(TypePtr);
  1926. if (Found == FunArgBackReferences.end()) {
  1927. std::string Name =
  1928. Dynamic ? "__pass_dynamic_object_size" : "__pass_object_size";
  1929. mangleArtificialTagType(TTK_Enum, Name + llvm::utostr(Type), {"__clang"});
  1930. if (FunArgBackReferences.size() < 10) {
  1931. size_t Size = FunArgBackReferences.size();
  1932. FunArgBackReferences[TypePtr] = Size;
  1933. }
  1934. } else {
  1935. Out << Found->second;
  1936. }
  1937. }
  1938. void MicrosoftCXXNameMangler::mangleAddressSpaceType(QualType T,
  1939. Qualifiers Quals,
  1940. SourceRange Range) {
  1941. // Address space is mangled as an unqualified templated type in the __clang
  1942. // namespace. The demangled version of this is:
  1943. // In the case of a language specific address space:
  1944. // __clang::struct _AS[language_addr_space]<Type>
  1945. // where:
  1946. // <language_addr_space> ::= <OpenCL-addrspace> | <CUDA-addrspace>
  1947. // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
  1948. // "private"| "generic" | "device" | "host" ]
  1949. // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
  1950. // Note that the above were chosen to match the Itanium mangling for this.
  1951. //
  1952. // In the case of a non-language specific address space:
  1953. // __clang::struct _AS<TargetAS, Type>
  1954. assert(Quals.hasAddressSpace() && "Not valid without address space");
  1955. llvm::SmallString<32> ASMangling;
  1956. llvm::raw_svector_ostream Stream(ASMangling);
  1957. MicrosoftCXXNameMangler Extra(Context, Stream);
  1958. Stream << "?$";
  1959. LangAS AS = Quals.getAddressSpace();
  1960. if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
  1961. unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
  1962. Extra.mangleSourceName("_AS");
  1963. Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(TargetAS));
  1964. } else {
  1965. switch (AS) {
  1966. default:
  1967. llvm_unreachable("Not a language specific address space");
  1968. case LangAS::opencl_global:
  1969. Extra.mangleSourceName("_ASCLglobal");
  1970. break;
  1971. case LangAS::opencl_global_device:
  1972. Extra.mangleSourceName("_ASCLdevice");
  1973. break;
  1974. case LangAS::opencl_global_host:
  1975. Extra.mangleSourceName("_ASCLhost");
  1976. break;
  1977. case LangAS::opencl_local:
  1978. Extra.mangleSourceName("_ASCLlocal");
  1979. break;
  1980. case LangAS::opencl_constant:
  1981. Extra.mangleSourceName("_ASCLconstant");
  1982. break;
  1983. case LangAS::opencl_private:
  1984. Extra.mangleSourceName("_ASCLprivate");
  1985. break;
  1986. case LangAS::opencl_generic:
  1987. Extra.mangleSourceName("_ASCLgeneric");
  1988. break;
  1989. case LangAS::cuda_device:
  1990. Extra.mangleSourceName("_ASCUdevice");
  1991. break;
  1992. case LangAS::cuda_constant:
  1993. Extra.mangleSourceName("_ASCUconstant");
  1994. break;
  1995. case LangAS::cuda_shared:
  1996. Extra.mangleSourceName("_ASCUshared");
  1997. break;
  1998. case LangAS::ptr32_sptr:
  1999. case LangAS::ptr32_uptr:
  2000. case LangAS::ptr64:
  2001. llvm_unreachable("don't mangle ptr address spaces with _AS");
  2002. }
  2003. }
  2004. Extra.mangleType(T, Range, QMM_Escape);
  2005. mangleQualifiers(Qualifiers(), false);
  2006. mangleArtificialTagType(TTK_Struct, ASMangling, {"__clang"});
  2007. }
  2008. void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
  2009. QualifierMangleMode QMM) {
  2010. // Don't use the canonical types. MSVC includes things like 'const' on
  2011. // pointer arguments to function pointers that canonicalization strips away.
  2012. T = T.getDesugaredType(getASTContext());
  2013. Qualifiers Quals = T.getLocalQualifiers();
  2014. if (const ArrayType *AT = getASTContext().getAsArrayType(T)) {
  2015. // If there were any Quals, getAsArrayType() pushed them onto the array
  2016. // element type.
  2017. if (QMM == QMM_Mangle)
  2018. Out << 'A';
  2019. else if (QMM == QMM_Escape || QMM == QMM_Result)
  2020. Out << "$$B";
  2021. mangleArrayType(AT);
  2022. return;
  2023. }
  2024. bool IsPointer = T->isAnyPointerType() || T->isMemberPointerType() ||
  2025. T->isReferenceType() || T->isBlockPointerType();
  2026. switch (QMM) {
  2027. case QMM_Drop:
  2028. if (Quals.hasObjCLifetime())
  2029. Quals = Quals.withoutObjCLifetime();
  2030. break;
  2031. case QMM_Mangle:
  2032. if (const FunctionType *FT = dyn_cast<FunctionType>(T)) {
  2033. Out << '6';
  2034. mangleFunctionType(FT);
  2035. return;
  2036. }
  2037. mangleQualifiers(Quals, false);
  2038. break;
  2039. case QMM_Escape:
  2040. if (!IsPointer && Quals) {
  2041. Out << "$$C";
  2042. mangleQualifiers(Quals, false);
  2043. }
  2044. break;
  2045. case QMM_Result:
  2046. // Presence of __unaligned qualifier shouldn't affect mangling here.
  2047. Quals.removeUnaligned();
  2048. if (Quals.hasObjCLifetime())
  2049. Quals = Quals.withoutObjCLifetime();
  2050. if ((!IsPointer && Quals) || isa<TagType>(T) || isArtificialTagType(T)) {
  2051. Out << '?';
  2052. mangleQualifiers(Quals, false);
  2053. }
  2054. break;
  2055. }
  2056. const Type *ty = T.getTypePtr();
  2057. switch (ty->getTypeClass()) {
  2058. #define ABSTRACT_TYPE(CLASS, PARENT)
  2059. #define NON_CANONICAL_TYPE(CLASS, PARENT) \
  2060. case Type::CLASS: \
  2061. llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
  2062. return;
  2063. #define TYPE(CLASS, PARENT) \
  2064. case Type::CLASS: \
  2065. mangleType(cast<CLASS##Type>(ty), Quals, Range); \
  2066. break;
  2067. #include "clang/AST/TypeNodes.inc"
  2068. #undef ABSTRACT_TYPE
  2069. #undef NON_CANONICAL_TYPE
  2070. #undef TYPE
  2071. }
  2072. }
  2073. void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T, Qualifiers,
  2074. SourceRange Range) {
  2075. // <type> ::= <builtin-type>
  2076. // <builtin-type> ::= X # void
  2077. // ::= C # signed char
  2078. // ::= D # char
  2079. // ::= E # unsigned char
  2080. // ::= F # short
  2081. // ::= G # unsigned short (or wchar_t if it's not a builtin)
  2082. // ::= H # int
  2083. // ::= I # unsigned int
  2084. // ::= J # long
  2085. // ::= K # unsigned long
  2086. // L # <none>
  2087. // ::= M # float
  2088. // ::= N # double
  2089. // ::= O # long double (__float80 is mangled differently)
  2090. // ::= _J # long long, __int64
  2091. // ::= _K # unsigned long long, __int64
  2092. // ::= _L # __int128
  2093. // ::= _M # unsigned __int128
  2094. // ::= _N # bool
  2095. // _O # <array in parameter>
  2096. // ::= _Q # char8_t
  2097. // ::= _S # char16_t
  2098. // ::= _T # __float80 (Intel)
  2099. // ::= _U # char32_t
  2100. // ::= _W # wchar_t
  2101. // ::= _Z # __float80 (Digital Mars)
  2102. switch (T->getKind()) {
  2103. case BuiltinType::Void:
  2104. Out << 'X';
  2105. break;
  2106. case BuiltinType::SChar:
  2107. Out << 'C';
  2108. break;
  2109. case BuiltinType::Char_U:
  2110. case BuiltinType::Char_S:
  2111. Out << 'D';
  2112. break;
  2113. case BuiltinType::UChar:
  2114. Out << 'E';
  2115. break;
  2116. case BuiltinType::Short:
  2117. Out << 'F';
  2118. break;
  2119. case BuiltinType::UShort:
  2120. Out << 'G';
  2121. break;
  2122. case BuiltinType::Int:
  2123. Out << 'H';
  2124. break;
  2125. case BuiltinType::UInt:
  2126. Out << 'I';
  2127. break;
  2128. case BuiltinType::Long:
  2129. Out << 'J';
  2130. break;
  2131. case BuiltinType::ULong:
  2132. Out << 'K';
  2133. break;
  2134. case BuiltinType::Float:
  2135. Out << 'M';
  2136. break;
  2137. case BuiltinType::Double:
  2138. Out << 'N';
  2139. break;
  2140. // TODO: Determine size and mangle accordingly
  2141. case BuiltinType::LongDouble:
  2142. Out << 'O';
  2143. break;
  2144. case BuiltinType::LongLong:
  2145. Out << "_J";
  2146. break;
  2147. case BuiltinType::ULongLong:
  2148. Out << "_K";
  2149. break;
  2150. case BuiltinType::Int128:
  2151. Out << "_L";
  2152. break;
  2153. case BuiltinType::UInt128:
  2154. Out << "_M";
  2155. break;
  2156. case BuiltinType::Bool:
  2157. Out << "_N";
  2158. break;
  2159. case BuiltinType::Char8:
  2160. Out << "_Q";
  2161. break;
  2162. case BuiltinType::Char16:
  2163. Out << "_S";
  2164. break;
  2165. case BuiltinType::Char32:
  2166. Out << "_U";
  2167. break;
  2168. case BuiltinType::WChar_S:
  2169. case BuiltinType::WChar_U:
  2170. Out << "_W";
  2171. break;
  2172. #define BUILTIN_TYPE(Id, SingletonId)
  2173. #define PLACEHOLDER_TYPE(Id, SingletonId) \
  2174. case BuiltinType::Id:
  2175. #include "clang/AST/BuiltinTypes.def"
  2176. case BuiltinType::Dependent:
  2177. llvm_unreachable("placeholder types shouldn't get to name mangling");
  2178. case BuiltinType::ObjCId:
  2179. mangleArtificialTagType(TTK_Struct, "objc_object");
  2180. break;
  2181. case BuiltinType::ObjCClass:
  2182. mangleArtificialTagType(TTK_Struct, "objc_class");
  2183. break;
  2184. case BuiltinType::ObjCSel:
  2185. mangleArtificialTagType(TTK_Struct, "objc_selector");
  2186. break;
  2187. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  2188. case BuiltinType::Id: \
  2189. Out << "PAUocl_" #ImgType "_" #Suffix "@@"; \
  2190. break;
  2191. #include "clang/Basic/OpenCLImageTypes.def"
  2192. case BuiltinType::OCLSampler:
  2193. Out << "PA";
  2194. mangleArtificialTagType(TTK_Struct, "ocl_sampler");
  2195. break;
  2196. case BuiltinType::OCLEvent:
  2197. Out << "PA";
  2198. mangleArtificialTagType(TTK_Struct, "ocl_event");
  2199. break;
  2200. case BuiltinType::OCLClkEvent:
  2201. Out << "PA";
  2202. mangleArtificialTagType(TTK_Struct, "ocl_clkevent");
  2203. break;
  2204. case BuiltinType::OCLQueue:
  2205. Out << "PA";
  2206. mangleArtificialTagType(TTK_Struct, "ocl_queue");
  2207. break;
  2208. case BuiltinType::OCLReserveID:
  2209. Out << "PA";
  2210. mangleArtificialTagType(TTK_Struct, "ocl_reserveid");
  2211. break;
  2212. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  2213. case BuiltinType::Id: \
  2214. mangleArtificialTagType(TTK_Struct, "ocl_" #ExtType); \
  2215. break;
  2216. #include "clang/Basic/OpenCLExtensionTypes.def"
  2217. case BuiltinType::NullPtr:
  2218. Out << "$$T";
  2219. break;
  2220. case BuiltinType::Float16:
  2221. mangleArtificialTagType(TTK_Struct, "_Float16", {"__clang"});
  2222. break;
  2223. case BuiltinType::Half:
  2224. if (!getASTContext().getLangOpts().HLSL)
  2225. mangleArtificialTagType(TTK_Struct, "_Half", {"__clang"});
  2226. else if (getASTContext().getLangOpts().NativeHalfType)
  2227. Out << "$f16@";
  2228. else
  2229. Out << "$halff@";
  2230. break;
  2231. case BuiltinType::BFloat16:
  2232. mangleArtificialTagType(TTK_Struct, "__bf16", {"__clang"});
  2233. break;
  2234. #define SVE_TYPE(Name, Id, SingletonId) \
  2235. case BuiltinType::Id:
  2236. #include "clang/Basic/AArch64SVEACLETypes.def"
  2237. #define PPC_VECTOR_TYPE(Name, Id, Size) \
  2238. case BuiltinType::Id:
  2239. #include "clang/Basic/PPCTypes.def"
  2240. #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
  2241. #include "clang/Basic/RISCVVTypes.def"
  2242. case BuiltinType::ShortAccum:
  2243. case BuiltinType::Accum:
  2244. case BuiltinType::LongAccum:
  2245. case BuiltinType::UShortAccum:
  2246. case BuiltinType::UAccum:
  2247. case BuiltinType::ULongAccum:
  2248. case BuiltinType::ShortFract:
  2249. case BuiltinType::Fract:
  2250. case BuiltinType::LongFract:
  2251. case BuiltinType::UShortFract:
  2252. case BuiltinType::UFract:
  2253. case BuiltinType::ULongFract:
  2254. case BuiltinType::SatShortAccum:
  2255. case BuiltinType::SatAccum:
  2256. case BuiltinType::SatLongAccum:
  2257. case BuiltinType::SatUShortAccum:
  2258. case BuiltinType::SatUAccum:
  2259. case BuiltinType::SatULongAccum:
  2260. case BuiltinType::SatShortFract:
  2261. case BuiltinType::SatFract:
  2262. case BuiltinType::SatLongFract:
  2263. case BuiltinType::SatUShortFract:
  2264. case BuiltinType::SatUFract:
  2265. case BuiltinType::SatULongFract:
  2266. case BuiltinType::Ibm128:
  2267. case BuiltinType::Float128: {
  2268. DiagnosticsEngine &Diags = Context.getDiags();
  2269. unsigned DiagID = Diags.getCustomDiagID(
  2270. DiagnosticsEngine::Error, "cannot mangle this built-in %0 type yet");
  2271. Diags.Report(Range.getBegin(), DiagID)
  2272. << T->getName(Context.getASTContext().getPrintingPolicy()) << Range;
  2273. break;
  2274. }
  2275. }
  2276. }
  2277. // <type> ::= <function-type>
  2278. void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T, Qualifiers,
  2279. SourceRange) {
  2280. // Structors only appear in decls, so at this point we know it's not a
  2281. // structor type.
  2282. // FIXME: This may not be lambda-friendly.
  2283. if (T->getMethodQuals() || T->getRefQualifier() != RQ_None) {
  2284. Out << "$$A8@@";
  2285. mangleFunctionType(T, /*D=*/nullptr, /*ForceThisQuals=*/true);
  2286. } else {
  2287. Out << "$$A6";
  2288. mangleFunctionType(T);
  2289. }
  2290. }
  2291. void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
  2292. Qualifiers, SourceRange) {
  2293. Out << "$$A6";
  2294. mangleFunctionType(T);
  2295. }
  2296. void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T,
  2297. const FunctionDecl *D,
  2298. bool ForceThisQuals,
  2299. bool MangleExceptionSpec) {
  2300. // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
  2301. // <return-type> <argument-list> <throw-spec>
  2302. const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(T);
  2303. SourceRange Range;
  2304. if (D) Range = D->getSourceRange();
  2305. bool IsInLambda = false;
  2306. bool IsStructor = false, HasThisQuals = ForceThisQuals, IsCtorClosure = false;
  2307. CallingConv CC = T->getCallConv();
  2308. if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(D)) {
  2309. if (MD->getParent()->isLambda())
  2310. IsInLambda = true;
  2311. if (MD->isInstance())
  2312. HasThisQuals = true;
  2313. if (isa<CXXDestructorDecl>(MD)) {
  2314. IsStructor = true;
  2315. } else if (isa<CXXConstructorDecl>(MD)) {
  2316. IsStructor = true;
  2317. IsCtorClosure = (StructorType == Ctor_CopyingClosure ||
  2318. StructorType == Ctor_DefaultClosure) &&
  2319. isStructorDecl(MD);
  2320. if (IsCtorClosure)
  2321. CC = getASTContext().getDefaultCallingConvention(
  2322. /*IsVariadic=*/false, /*IsCXXMethod=*/true);
  2323. }
  2324. }
  2325. // If this is a C++ instance method, mangle the CVR qualifiers for the
  2326. // this pointer.
  2327. if (HasThisQuals) {
  2328. Qualifiers Quals = Proto->getMethodQuals();
  2329. manglePointerExtQualifiers(Quals, /*PointeeType=*/QualType());
  2330. mangleRefQualifier(Proto->getRefQualifier());
  2331. mangleQualifiers(Quals, /*IsMember=*/false);
  2332. }
  2333. mangleCallingConvention(CC);
  2334. // <return-type> ::= <type>
  2335. // ::= @ # structors (they have no declared return type)
  2336. if (IsStructor) {
  2337. if (isa<CXXDestructorDecl>(D) && isStructorDecl(D)) {
  2338. // The scalar deleting destructor takes an extra int argument which is not
  2339. // reflected in the AST.
  2340. if (StructorType == Dtor_Deleting) {
  2341. Out << (PointersAre64Bit ? "PEAXI@Z" : "PAXI@Z");
  2342. return;
  2343. }
  2344. // The vbase destructor returns void which is not reflected in the AST.
  2345. if (StructorType == Dtor_Complete) {
  2346. Out << "XXZ";
  2347. return;
  2348. }
  2349. }
  2350. if (IsCtorClosure) {
  2351. // Default constructor closure and copy constructor closure both return
  2352. // void.
  2353. Out << 'X';
  2354. if (StructorType == Ctor_DefaultClosure) {
  2355. // Default constructor closure always has no arguments.
  2356. Out << 'X';
  2357. } else if (StructorType == Ctor_CopyingClosure) {
  2358. // Copy constructor closure always takes an unqualified reference.
  2359. mangleFunctionArgumentType(getASTContext().getLValueReferenceType(
  2360. Proto->getParamType(0)
  2361. ->getAs<LValueReferenceType>()
  2362. ->getPointeeType(),
  2363. /*SpelledAsLValue=*/true),
  2364. Range);
  2365. Out << '@';
  2366. } else {
  2367. llvm_unreachable("unexpected constructor closure!");
  2368. }
  2369. Out << 'Z';
  2370. return;
  2371. }
  2372. Out << '@';
  2373. } else if (IsInLambda && D && isa<CXXConversionDecl>(D)) {
  2374. // The only lambda conversion operators are to function pointers, which
  2375. // can differ by their calling convention and are typically deduced. So
  2376. // we make sure that this type gets mangled properly.
  2377. mangleType(T->getReturnType(), Range, QMM_Result);
  2378. } else {
  2379. QualType ResultType = T->getReturnType();
  2380. if (IsInLambda && isa<CXXConversionDecl>(D)) {
  2381. // The only lambda conversion operators are to function pointers, which
  2382. // can differ by their calling convention and are typically deduced. So
  2383. // we make sure that this type gets mangled properly.
  2384. mangleType(ResultType, Range, QMM_Result);
  2385. } else if (const auto *AT = dyn_cast_or_null<AutoType>(
  2386. ResultType->getContainedAutoType())) {
  2387. Out << '?';
  2388. mangleQualifiers(ResultType.getLocalQualifiers(), /*IsMember=*/false);
  2389. Out << '?';
  2390. assert(AT->getKeyword() != AutoTypeKeyword::GNUAutoType &&
  2391. "shouldn't need to mangle __auto_type!");
  2392. mangleSourceName(AT->isDecltypeAuto() ? "<decltype-auto>" : "<auto>");
  2393. Out << '@';
  2394. } else if (IsInLambda) {
  2395. Out << '@';
  2396. } else {
  2397. if (ResultType->isVoidType())
  2398. ResultType = ResultType.getUnqualifiedType();
  2399. mangleType(ResultType, Range, QMM_Result);
  2400. }
  2401. }
  2402. // <argument-list> ::= X # void
  2403. // ::= <type>+ @
  2404. // ::= <type>* Z # varargs
  2405. if (!Proto) {
  2406. // Function types without prototypes can arise when mangling a function type
  2407. // within an overloadable function in C. We mangle these as the absence of
  2408. // any parameter types (not even an empty parameter list).
  2409. Out << '@';
  2410. } else if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
  2411. Out << 'X';
  2412. } else {
  2413. // Happens for function pointer type arguments for example.
  2414. for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
  2415. mangleFunctionArgumentType(Proto->getParamType(I), Range);
  2416. // Mangle each pass_object_size parameter as if it's a parameter of enum
  2417. // type passed directly after the parameter with the pass_object_size
  2418. // attribute. The aforementioned enum's name is __pass_object_size, and we
  2419. // pretend it resides in a top-level namespace called __clang.
  2420. //
  2421. // FIXME: Is there a defined extension notation for the MS ABI, or is it
  2422. // necessary to just cross our fingers and hope this type+namespace
  2423. // combination doesn't conflict with anything?
  2424. if (D)
  2425. if (const auto *P = D->getParamDecl(I)->getAttr<PassObjectSizeAttr>())
  2426. manglePassObjectSizeArg(P);
  2427. }
  2428. // <builtin-type> ::= Z # ellipsis
  2429. if (Proto->isVariadic())
  2430. Out << 'Z';
  2431. else
  2432. Out << '@';
  2433. }
  2434. if (MangleExceptionSpec && getASTContext().getLangOpts().CPlusPlus17 &&
  2435. getASTContext().getLangOpts().isCompatibleWithMSVC(
  2436. LangOptions::MSVC2017_5))
  2437. mangleThrowSpecification(Proto);
  2438. else
  2439. Out << 'Z';
  2440. }
  2441. void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
  2442. // <function-class> ::= <member-function> E? # E designates a 64-bit 'this'
  2443. // # pointer. in 64-bit mode *all*
  2444. // # 'this' pointers are 64-bit.
  2445. // ::= <global-function>
  2446. // <member-function> ::= A # private: near
  2447. // ::= B # private: far
  2448. // ::= C # private: static near
  2449. // ::= D # private: static far
  2450. // ::= E # private: virtual near
  2451. // ::= F # private: virtual far
  2452. // ::= I # protected: near
  2453. // ::= J # protected: far
  2454. // ::= K # protected: static near
  2455. // ::= L # protected: static far
  2456. // ::= M # protected: virtual near
  2457. // ::= N # protected: virtual far
  2458. // ::= Q # public: near
  2459. // ::= R # public: far
  2460. // ::= S # public: static near
  2461. // ::= T # public: static far
  2462. // ::= U # public: virtual near
  2463. // ::= V # public: virtual far
  2464. // <global-function> ::= Y # global near
  2465. // ::= Z # global far
  2466. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  2467. bool IsVirtual = MD->isVirtual();
  2468. // When mangling vbase destructor variants, ignore whether or not the
  2469. // underlying destructor was defined to be virtual.
  2470. if (isa<CXXDestructorDecl>(MD) && isStructorDecl(MD) &&
  2471. StructorType == Dtor_Complete) {
  2472. IsVirtual = false;
  2473. }
  2474. switch (MD->getAccess()) {
  2475. case AS_none:
  2476. llvm_unreachable("Unsupported access specifier");
  2477. case AS_private:
  2478. if (MD->isStatic())
  2479. Out << 'C';
  2480. else if (IsVirtual)
  2481. Out << 'E';
  2482. else
  2483. Out << 'A';
  2484. break;
  2485. case AS_protected:
  2486. if (MD->isStatic())
  2487. Out << 'K';
  2488. else if (IsVirtual)
  2489. Out << 'M';
  2490. else
  2491. Out << 'I';
  2492. break;
  2493. case AS_public:
  2494. if (MD->isStatic())
  2495. Out << 'S';
  2496. else if (IsVirtual)
  2497. Out << 'U';
  2498. else
  2499. Out << 'Q';
  2500. }
  2501. } else {
  2502. Out << 'Y';
  2503. }
  2504. }
  2505. void MicrosoftCXXNameMangler::mangleCallingConvention(CallingConv CC) {
  2506. // <calling-convention> ::= A # __cdecl
  2507. // ::= B # __export __cdecl
  2508. // ::= C # __pascal
  2509. // ::= D # __export __pascal
  2510. // ::= E # __thiscall
  2511. // ::= F # __export __thiscall
  2512. // ::= G # __stdcall
  2513. // ::= H # __export __stdcall
  2514. // ::= I # __fastcall
  2515. // ::= J # __export __fastcall
  2516. // ::= Q # __vectorcall
  2517. // ::= S # __attribute__((__swiftcall__)) // Clang-only
  2518. // ::= T # __attribute__((__swiftasynccall__))
  2519. // // Clang-only
  2520. // ::= w # __regcall
  2521. // The 'export' calling conventions are from a bygone era
  2522. // (*cough*Win16*cough*) when functions were declared for export with
  2523. // that keyword. (It didn't actually export them, it just made them so
  2524. // that they could be in a DLL and somebody from another module could call
  2525. // them.)
  2526. switch (CC) {
  2527. default:
  2528. llvm_unreachable("Unsupported CC for mangling");
  2529. case CC_Win64:
  2530. case CC_X86_64SysV:
  2531. case CC_C: Out << 'A'; break;
  2532. case CC_X86Pascal: Out << 'C'; break;
  2533. case CC_X86ThisCall: Out << 'E'; break;
  2534. case CC_X86StdCall: Out << 'G'; break;
  2535. case CC_X86FastCall: Out << 'I'; break;
  2536. case CC_X86VectorCall: Out << 'Q'; break;
  2537. case CC_Swift: Out << 'S'; break;
  2538. case CC_SwiftAsync: Out << 'W'; break;
  2539. case CC_PreserveMost: Out << 'U'; break;
  2540. case CC_X86RegCall: Out << 'w'; break;
  2541. }
  2542. }
  2543. void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T) {
  2544. mangleCallingConvention(T->getCallConv());
  2545. }
  2546. void MicrosoftCXXNameMangler::mangleThrowSpecification(
  2547. const FunctionProtoType *FT) {
  2548. // <throw-spec> ::= Z # (default)
  2549. // ::= _E # noexcept
  2550. if (FT->canThrow())
  2551. Out << 'Z';
  2552. else
  2553. Out << "_E";
  2554. }
  2555. void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
  2556. Qualifiers, SourceRange Range) {
  2557. // Probably should be mangled as a template instantiation; need to see what
  2558. // VC does first.
  2559. DiagnosticsEngine &Diags = Context.getDiags();
  2560. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2561. "cannot mangle this unresolved dependent type yet");
  2562. Diags.Report(Range.getBegin(), DiagID)
  2563. << Range;
  2564. }
  2565. // <type> ::= <union-type> | <struct-type> | <class-type> | <enum-type>
  2566. // <union-type> ::= T <name>
  2567. // <struct-type> ::= U <name>
  2568. // <class-type> ::= V <name>
  2569. // <enum-type> ::= W4 <name>
  2570. void MicrosoftCXXNameMangler::mangleTagTypeKind(TagTypeKind TTK) {
  2571. switch (TTK) {
  2572. case TTK_Union:
  2573. Out << 'T';
  2574. break;
  2575. case TTK_Struct:
  2576. case TTK_Interface:
  2577. Out << 'U';
  2578. break;
  2579. case TTK_Class:
  2580. Out << 'V';
  2581. break;
  2582. case TTK_Enum:
  2583. Out << "W4";
  2584. break;
  2585. }
  2586. }
  2587. void MicrosoftCXXNameMangler::mangleType(const EnumType *T, Qualifiers,
  2588. SourceRange) {
  2589. mangleType(cast<TagType>(T)->getDecl());
  2590. }
  2591. void MicrosoftCXXNameMangler::mangleType(const RecordType *T, Qualifiers,
  2592. SourceRange) {
  2593. mangleType(cast<TagType>(T)->getDecl());
  2594. }
  2595. void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) {
  2596. mangleTagTypeKind(TD->getTagKind());
  2597. mangleName(TD);
  2598. }
  2599. // If you add a call to this, consider updating isArtificialTagType() too.
  2600. void MicrosoftCXXNameMangler::mangleArtificialTagType(
  2601. TagTypeKind TK, StringRef UnqualifiedName,
  2602. ArrayRef<StringRef> NestedNames) {
  2603. // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
  2604. mangleTagTypeKind(TK);
  2605. // Always start with the unqualified name.
  2606. mangleSourceName(UnqualifiedName);
  2607. for (StringRef N : llvm::reverse(NestedNames))
  2608. mangleSourceName(N);
  2609. // Terminate the whole name with an '@'.
  2610. Out << '@';
  2611. }
  2612. // <type> ::= <array-type>
  2613. // <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
  2614. // [Y <dimension-count> <dimension>+]
  2615. // <element-type> # as global, E is never required
  2616. // It's supposed to be the other way around, but for some strange reason, it
  2617. // isn't. Today this behavior is retained for the sole purpose of backwards
  2618. // compatibility.
  2619. void MicrosoftCXXNameMangler::mangleDecayedArrayType(const ArrayType *T) {
  2620. // This isn't a recursive mangling, so now we have to do it all in this
  2621. // one call.
  2622. manglePointerCVQualifiers(T->getElementType().getQualifiers());
  2623. mangleType(T->getElementType(), SourceRange());
  2624. }
  2625. void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T, Qualifiers,
  2626. SourceRange) {
  2627. llvm_unreachable("Should have been special cased");
  2628. }
  2629. void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T, Qualifiers,
  2630. SourceRange) {
  2631. llvm_unreachable("Should have been special cased");
  2632. }
  2633. void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
  2634. Qualifiers, SourceRange) {
  2635. llvm_unreachable("Should have been special cased");
  2636. }
  2637. void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
  2638. Qualifiers, SourceRange) {
  2639. llvm_unreachable("Should have been special cased");
  2640. }
  2641. void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) {
  2642. QualType ElementTy(T, 0);
  2643. SmallVector<llvm::APInt, 3> Dimensions;
  2644. for (;;) {
  2645. if (ElementTy->isConstantArrayType()) {
  2646. const ConstantArrayType *CAT =
  2647. getASTContext().getAsConstantArrayType(ElementTy);
  2648. Dimensions.push_back(CAT->getSize());
  2649. ElementTy = CAT->getElementType();
  2650. } else if (ElementTy->isIncompleteArrayType()) {
  2651. const IncompleteArrayType *IAT =
  2652. getASTContext().getAsIncompleteArrayType(ElementTy);
  2653. Dimensions.push_back(llvm::APInt(32, 0));
  2654. ElementTy = IAT->getElementType();
  2655. } else if (ElementTy->isVariableArrayType()) {
  2656. const VariableArrayType *VAT =
  2657. getASTContext().getAsVariableArrayType(ElementTy);
  2658. Dimensions.push_back(llvm::APInt(32, 0));
  2659. ElementTy = VAT->getElementType();
  2660. } else if (ElementTy->isDependentSizedArrayType()) {
  2661. // The dependent expression has to be folded into a constant (TODO).
  2662. const DependentSizedArrayType *DSAT =
  2663. getASTContext().getAsDependentSizedArrayType(ElementTy);
  2664. DiagnosticsEngine &Diags = Context.getDiags();
  2665. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2666. "cannot mangle this dependent-length array yet");
  2667. Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
  2668. << DSAT->getBracketsRange();
  2669. return;
  2670. } else {
  2671. break;
  2672. }
  2673. }
  2674. Out << 'Y';
  2675. // <dimension-count> ::= <number> # number of extra dimensions
  2676. mangleNumber(Dimensions.size());
  2677. for (const llvm::APInt &Dimension : Dimensions)
  2678. mangleNumber(Dimension.getLimitedValue());
  2679. mangleType(ElementTy, SourceRange(), QMM_Escape);
  2680. }
  2681. // <type> ::= <pointer-to-member-type>
  2682. // <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
  2683. // <class name> <type>
  2684. void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T,
  2685. Qualifiers Quals, SourceRange Range) {
  2686. QualType PointeeType = T->getPointeeType();
  2687. manglePointerCVQualifiers(Quals);
  2688. manglePointerExtQualifiers(Quals, PointeeType);
  2689. if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
  2690. Out << '8';
  2691. mangleName(T->getClass()->castAs<RecordType>()->getDecl());
  2692. mangleFunctionType(FPT, nullptr, true);
  2693. } else {
  2694. mangleQualifiers(PointeeType.getQualifiers(), true);
  2695. mangleName(T->getClass()->castAs<RecordType>()->getDecl());
  2696. mangleType(PointeeType, Range, QMM_Drop);
  2697. }
  2698. }
  2699. void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
  2700. Qualifiers, SourceRange Range) {
  2701. DiagnosticsEngine &Diags = Context.getDiags();
  2702. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2703. "cannot mangle this template type parameter type yet");
  2704. Diags.Report(Range.getBegin(), DiagID)
  2705. << Range;
  2706. }
  2707. void MicrosoftCXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T,
  2708. Qualifiers, SourceRange Range) {
  2709. DiagnosticsEngine &Diags = Context.getDiags();
  2710. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2711. "cannot mangle this substituted parameter pack yet");
  2712. Diags.Report(Range.getBegin(), DiagID)
  2713. << Range;
  2714. }
  2715. // <type> ::= <pointer-type>
  2716. // <pointer-type> ::= E? <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
  2717. // # the E is required for 64-bit non-static pointers
  2718. void MicrosoftCXXNameMangler::mangleType(const PointerType *T, Qualifiers Quals,
  2719. SourceRange Range) {
  2720. QualType PointeeType = T->getPointeeType();
  2721. manglePointerCVQualifiers(Quals);
  2722. manglePointerExtQualifiers(Quals, PointeeType);
  2723. // For pointer size address spaces, go down the same type mangling path as
  2724. // non address space types.
  2725. LangAS AddrSpace = PointeeType.getQualifiers().getAddressSpace();
  2726. if (isPtrSizeAddressSpace(AddrSpace) || AddrSpace == LangAS::Default)
  2727. mangleType(PointeeType, Range);
  2728. else
  2729. mangleAddressSpaceType(PointeeType, PointeeType.getQualifiers(), Range);
  2730. }
  2731. void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
  2732. Qualifiers Quals, SourceRange Range) {
  2733. QualType PointeeType = T->getPointeeType();
  2734. switch (Quals.getObjCLifetime()) {
  2735. case Qualifiers::OCL_None:
  2736. case Qualifiers::OCL_ExplicitNone:
  2737. break;
  2738. case Qualifiers::OCL_Autoreleasing:
  2739. case Qualifiers::OCL_Strong:
  2740. case Qualifiers::OCL_Weak:
  2741. return mangleObjCLifetime(PointeeType, Quals, Range);
  2742. }
  2743. manglePointerCVQualifiers(Quals);
  2744. manglePointerExtQualifiers(Quals, PointeeType);
  2745. mangleType(PointeeType, Range);
  2746. }
  2747. // <type> ::= <reference-type>
  2748. // <reference-type> ::= A E? <cvr-qualifiers> <type>
  2749. // # the E is required for 64-bit non-static lvalue references
  2750. void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
  2751. Qualifiers Quals, SourceRange Range) {
  2752. QualType PointeeType = T->getPointeeType();
  2753. assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!");
  2754. Out << 'A';
  2755. manglePointerExtQualifiers(Quals, PointeeType);
  2756. mangleType(PointeeType, Range);
  2757. }
  2758. // <type> ::= <r-value-reference-type>
  2759. // <r-value-reference-type> ::= $$Q E? <cvr-qualifiers> <type>
  2760. // # the E is required for 64-bit non-static rvalue references
  2761. void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
  2762. Qualifiers Quals, SourceRange Range) {
  2763. QualType PointeeType = T->getPointeeType();
  2764. assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!");
  2765. Out << "$$Q";
  2766. manglePointerExtQualifiers(Quals, PointeeType);
  2767. mangleType(PointeeType, Range);
  2768. }
  2769. void MicrosoftCXXNameMangler::mangleType(const ComplexType *T, Qualifiers,
  2770. SourceRange Range) {
  2771. QualType ElementType = T->getElementType();
  2772. llvm::SmallString<64> TemplateMangling;
  2773. llvm::raw_svector_ostream Stream(TemplateMangling);
  2774. MicrosoftCXXNameMangler Extra(Context, Stream);
  2775. Stream << "?$";
  2776. Extra.mangleSourceName("_Complex");
  2777. Extra.mangleType(ElementType, Range, QMM_Escape);
  2778. mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__clang"});
  2779. }
  2780. // Returns true for types that mangleArtificialTagType() gets called for with
  2781. // TTK_Union, TTK_Struct, TTK_Class and where compatibility with MSVC's
  2782. // mangling matters.
  2783. // (It doesn't matter for Objective-C types and the like that cl.exe doesn't
  2784. // support.)
  2785. bool MicrosoftCXXNameMangler::isArtificialTagType(QualType T) const {
  2786. const Type *ty = T.getTypePtr();
  2787. switch (ty->getTypeClass()) {
  2788. default:
  2789. return false;
  2790. case Type::Vector: {
  2791. // For ABI compatibility only __m64, __m128(id), and __m256(id) matter,
  2792. // but since mangleType(VectorType*) always calls mangleArtificialTagType()
  2793. // just always return true (the other vector types are clang-only).
  2794. return true;
  2795. }
  2796. }
  2797. }
  2798. void MicrosoftCXXNameMangler::mangleType(const VectorType *T, Qualifiers Quals,
  2799. SourceRange Range) {
  2800. QualType EltTy = T->getElementType();
  2801. const BuiltinType *ET = EltTy->getAs<BuiltinType>();
  2802. const BitIntType *BitIntTy = EltTy->getAs<BitIntType>();
  2803. assert((ET || BitIntTy) &&
  2804. "vectors with non-builtin/_BitInt elements are unsupported");
  2805. uint64_t Width = getASTContext().getTypeSize(T);
  2806. // Pattern match exactly the typedefs in our intrinsic headers. Anything that
  2807. // doesn't match the Intel types uses a custom mangling below.
  2808. size_t OutSizeBefore = Out.tell();
  2809. if (!isa<ExtVectorType>(T)) {
  2810. if (getASTContext().getTargetInfo().getTriple().isX86() && ET) {
  2811. if (Width == 64 && ET->getKind() == BuiltinType::LongLong) {
  2812. mangleArtificialTagType(TTK_Union, "__m64");
  2813. } else if (Width >= 128) {
  2814. if (ET->getKind() == BuiltinType::Float)
  2815. mangleArtificialTagType(TTK_Union, "__m" + llvm::utostr(Width));
  2816. else if (ET->getKind() == BuiltinType::LongLong)
  2817. mangleArtificialTagType(TTK_Union, "__m" + llvm::utostr(Width) + 'i');
  2818. else if (ET->getKind() == BuiltinType::Double)
  2819. mangleArtificialTagType(TTK_Struct, "__m" + llvm::utostr(Width) + 'd');
  2820. }
  2821. }
  2822. }
  2823. bool IsBuiltin = Out.tell() != OutSizeBefore;
  2824. if (!IsBuiltin) {
  2825. // The MS ABI doesn't have a special mangling for vector types, so we define
  2826. // our own mangling to handle uses of __vector_size__ on user-specified
  2827. // types, and for extensions like __v4sf.
  2828. llvm::SmallString<64> TemplateMangling;
  2829. llvm::raw_svector_ostream Stream(TemplateMangling);
  2830. MicrosoftCXXNameMangler Extra(Context, Stream);
  2831. Stream << "?$";
  2832. Extra.mangleSourceName("__vector");
  2833. Extra.mangleType(QualType(ET ? static_cast<const Type *>(ET) : BitIntTy, 0),
  2834. Range, QMM_Escape);
  2835. Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(T->getNumElements()));
  2836. mangleArtificialTagType(TTK_Union, TemplateMangling, {"__clang"});
  2837. }
  2838. }
  2839. void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T,
  2840. Qualifiers Quals, SourceRange Range) {
  2841. mangleType(static_cast<const VectorType *>(T), Quals, Range);
  2842. }
  2843. void MicrosoftCXXNameMangler::mangleType(const DependentVectorType *T,
  2844. Qualifiers, SourceRange Range) {
  2845. DiagnosticsEngine &Diags = Context.getDiags();
  2846. unsigned DiagID = Diags.getCustomDiagID(
  2847. DiagnosticsEngine::Error,
  2848. "cannot mangle this dependent-sized vector type yet");
  2849. Diags.Report(Range.getBegin(), DiagID) << Range;
  2850. }
  2851. void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T,
  2852. Qualifiers, SourceRange Range) {
  2853. DiagnosticsEngine &Diags = Context.getDiags();
  2854. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2855. "cannot mangle this dependent-sized extended vector type yet");
  2856. Diags.Report(Range.getBegin(), DiagID)
  2857. << Range;
  2858. }
  2859. void MicrosoftCXXNameMangler::mangleType(const ConstantMatrixType *T,
  2860. Qualifiers quals, SourceRange Range) {
  2861. DiagnosticsEngine &Diags = Context.getDiags();
  2862. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2863. "Cannot mangle this matrix type yet");
  2864. Diags.Report(Range.getBegin(), DiagID) << Range;
  2865. }
  2866. void MicrosoftCXXNameMangler::mangleType(const DependentSizedMatrixType *T,
  2867. Qualifiers quals, SourceRange Range) {
  2868. DiagnosticsEngine &Diags = Context.getDiags();
  2869. unsigned DiagID = Diags.getCustomDiagID(
  2870. DiagnosticsEngine::Error,
  2871. "Cannot mangle this dependent-sized matrix type yet");
  2872. Diags.Report(Range.getBegin(), DiagID) << Range;
  2873. }
  2874. void MicrosoftCXXNameMangler::mangleType(const DependentAddressSpaceType *T,
  2875. Qualifiers, SourceRange Range) {
  2876. DiagnosticsEngine &Diags = Context.getDiags();
  2877. unsigned DiagID = Diags.getCustomDiagID(
  2878. DiagnosticsEngine::Error,
  2879. "cannot mangle this dependent address space type yet");
  2880. Diags.Report(Range.getBegin(), DiagID) << Range;
  2881. }
  2882. void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T, Qualifiers,
  2883. SourceRange) {
  2884. // ObjC interfaces have structs underlying them.
  2885. mangleTagTypeKind(TTK_Struct);
  2886. mangleName(T->getDecl());
  2887. }
  2888. void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T,
  2889. Qualifiers Quals, SourceRange Range) {
  2890. if (T->isKindOfType())
  2891. return mangleObjCKindOfType(T, Quals, Range);
  2892. if (T->qual_empty() && !T->isSpecialized())
  2893. return mangleType(T->getBaseType(), Range, QMM_Drop);
  2894. ArgBackRefMap OuterFunArgsContext;
  2895. ArgBackRefMap OuterTemplateArgsContext;
  2896. BackRefVec OuterTemplateContext;
  2897. FunArgBackReferences.swap(OuterFunArgsContext);
  2898. TemplateArgBackReferences.swap(OuterTemplateArgsContext);
  2899. NameBackReferences.swap(OuterTemplateContext);
  2900. mangleTagTypeKind(TTK_Struct);
  2901. Out << "?$";
  2902. if (T->isObjCId())
  2903. mangleSourceName("objc_object");
  2904. else if (T->isObjCClass())
  2905. mangleSourceName("objc_class");
  2906. else
  2907. mangleSourceName(T->getInterface()->getName());
  2908. for (const auto &Q : T->quals())
  2909. mangleObjCProtocol(Q);
  2910. if (T->isSpecialized())
  2911. for (const auto &TA : T->getTypeArgs())
  2912. mangleType(TA, Range, QMM_Drop);
  2913. Out << '@';
  2914. Out << '@';
  2915. FunArgBackReferences.swap(OuterFunArgsContext);
  2916. TemplateArgBackReferences.swap(OuterTemplateArgsContext);
  2917. NameBackReferences.swap(OuterTemplateContext);
  2918. }
  2919. void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
  2920. Qualifiers Quals, SourceRange Range) {
  2921. QualType PointeeType = T->getPointeeType();
  2922. manglePointerCVQualifiers(Quals);
  2923. manglePointerExtQualifiers(Quals, PointeeType);
  2924. Out << "_E";
  2925. mangleFunctionType(PointeeType->castAs<FunctionProtoType>());
  2926. }
  2927. void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *,
  2928. Qualifiers, SourceRange) {
  2929. llvm_unreachable("Cannot mangle injected class name type.");
  2930. }
  2931. void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T,
  2932. Qualifiers, SourceRange Range) {
  2933. DiagnosticsEngine &Diags = Context.getDiags();
  2934. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2935. "cannot mangle this template specialization type yet");
  2936. Diags.Report(Range.getBegin(), DiagID)
  2937. << Range;
  2938. }
  2939. void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T, Qualifiers,
  2940. SourceRange Range) {
  2941. DiagnosticsEngine &Diags = Context.getDiags();
  2942. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2943. "cannot mangle this dependent name type yet");
  2944. Diags.Report(Range.getBegin(), DiagID)
  2945. << Range;
  2946. }
  2947. void MicrosoftCXXNameMangler::mangleType(
  2948. const DependentTemplateSpecializationType *T, Qualifiers,
  2949. SourceRange Range) {
  2950. DiagnosticsEngine &Diags = Context.getDiags();
  2951. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2952. "cannot mangle this dependent template specialization type yet");
  2953. Diags.Report(Range.getBegin(), DiagID)
  2954. << Range;
  2955. }
  2956. void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T, Qualifiers,
  2957. SourceRange Range) {
  2958. DiagnosticsEngine &Diags = Context.getDiags();
  2959. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2960. "cannot mangle this pack expansion yet");
  2961. Diags.Report(Range.getBegin(), DiagID)
  2962. << Range;
  2963. }
  2964. void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T, Qualifiers,
  2965. SourceRange Range) {
  2966. DiagnosticsEngine &Diags = Context.getDiags();
  2967. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2968. "cannot mangle this typeof(type) yet");
  2969. Diags.Report(Range.getBegin(), DiagID)
  2970. << Range;
  2971. }
  2972. void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T, Qualifiers,
  2973. SourceRange Range) {
  2974. DiagnosticsEngine &Diags = Context.getDiags();
  2975. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2976. "cannot mangle this typeof(expression) yet");
  2977. Diags.Report(Range.getBegin(), DiagID)
  2978. << Range;
  2979. }
  2980. void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T, Qualifiers,
  2981. SourceRange Range) {
  2982. DiagnosticsEngine &Diags = Context.getDiags();
  2983. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2984. "cannot mangle this decltype() yet");
  2985. Diags.Report(Range.getBegin(), DiagID)
  2986. << Range;
  2987. }
  2988. void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T,
  2989. Qualifiers, SourceRange Range) {
  2990. DiagnosticsEngine &Diags = Context.getDiags();
  2991. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2992. "cannot mangle this unary transform type yet");
  2993. Diags.Report(Range.getBegin(), DiagID)
  2994. << Range;
  2995. }
  2996. void MicrosoftCXXNameMangler::mangleType(const AutoType *T, Qualifiers,
  2997. SourceRange Range) {
  2998. assert(T->getDeducedType().isNull() && "expecting a dependent type!");
  2999. DiagnosticsEngine &Diags = Context.getDiags();
  3000. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  3001. "cannot mangle this 'auto' type yet");
  3002. Diags.Report(Range.getBegin(), DiagID)
  3003. << Range;
  3004. }
  3005. void MicrosoftCXXNameMangler::mangleType(
  3006. const DeducedTemplateSpecializationType *T, Qualifiers, SourceRange Range) {
  3007. assert(T->getDeducedType().isNull() && "expecting a dependent type!");
  3008. DiagnosticsEngine &Diags = Context.getDiags();
  3009. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  3010. "cannot mangle this deduced class template specialization type yet");
  3011. Diags.Report(Range.getBegin(), DiagID)
  3012. << Range;
  3013. }
  3014. void MicrosoftCXXNameMangler::mangleType(const AtomicType *T, Qualifiers,
  3015. SourceRange Range) {
  3016. QualType ValueType = T->getValueType();
  3017. llvm::SmallString<64> TemplateMangling;
  3018. llvm::raw_svector_ostream Stream(TemplateMangling);
  3019. MicrosoftCXXNameMangler Extra(Context, Stream);
  3020. Stream << "?$";
  3021. Extra.mangleSourceName("_Atomic");
  3022. Extra.mangleType(ValueType, Range, QMM_Escape);
  3023. mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__clang"});
  3024. }
  3025. void MicrosoftCXXNameMangler::mangleType(const PipeType *T, Qualifiers,
  3026. SourceRange Range) {
  3027. QualType ElementType = T->getElementType();
  3028. llvm::SmallString<64> TemplateMangling;
  3029. llvm::raw_svector_ostream Stream(TemplateMangling);
  3030. MicrosoftCXXNameMangler Extra(Context, Stream);
  3031. Stream << "?$";
  3032. Extra.mangleSourceName("ocl_pipe");
  3033. Extra.mangleType(ElementType, Range, QMM_Escape);
  3034. Extra.mangleIntegerLiteral(llvm::APSInt::get(T->isReadOnly()));
  3035. mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__clang"});
  3036. }
  3037. void MicrosoftMangleContextImpl::mangleCXXName(GlobalDecl GD,
  3038. raw_ostream &Out) {
  3039. const NamedDecl *D = cast<NamedDecl>(GD.getDecl());
  3040. PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
  3041. getASTContext().getSourceManager(),
  3042. "Mangling declaration");
  3043. msvc_hashing_ostream MHO(Out);
  3044. if (auto *CD = dyn_cast<CXXConstructorDecl>(D)) {
  3045. auto Type = GD.getCtorType();
  3046. MicrosoftCXXNameMangler mangler(*this, MHO, CD, Type);
  3047. return mangler.mangle(GD);
  3048. }
  3049. if (auto *DD = dyn_cast<CXXDestructorDecl>(D)) {
  3050. auto Type = GD.getDtorType();
  3051. MicrosoftCXXNameMangler mangler(*this, MHO, DD, Type);
  3052. return mangler.mangle(GD);
  3053. }
  3054. MicrosoftCXXNameMangler Mangler(*this, MHO);
  3055. return Mangler.mangle(GD);
  3056. }
  3057. void MicrosoftCXXNameMangler::mangleType(const BitIntType *T, Qualifiers,
  3058. SourceRange Range) {
  3059. llvm::SmallString<64> TemplateMangling;
  3060. llvm::raw_svector_ostream Stream(TemplateMangling);
  3061. MicrosoftCXXNameMangler Extra(Context, Stream);
  3062. Stream << "?$";
  3063. if (T->isUnsigned())
  3064. Extra.mangleSourceName("_UBitInt");
  3065. else
  3066. Extra.mangleSourceName("_BitInt");
  3067. Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(T->getNumBits()));
  3068. mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__clang"});
  3069. }
  3070. void MicrosoftCXXNameMangler::mangleType(const DependentBitIntType *T,
  3071. Qualifiers, SourceRange Range) {
  3072. DiagnosticsEngine &Diags = Context.getDiags();
  3073. unsigned DiagID = Diags.getCustomDiagID(
  3074. DiagnosticsEngine::Error, "cannot mangle this DependentBitInt type yet");
  3075. Diags.Report(Range.getBegin(), DiagID) << Range;
  3076. }
  3077. // <this-adjustment> ::= <no-adjustment> | <static-adjustment> |
  3078. // <virtual-adjustment>
  3079. // <no-adjustment> ::= A # private near
  3080. // ::= B # private far
  3081. // ::= I # protected near
  3082. // ::= J # protected far
  3083. // ::= Q # public near
  3084. // ::= R # public far
  3085. // <static-adjustment> ::= G <static-offset> # private near
  3086. // ::= H <static-offset> # private far
  3087. // ::= O <static-offset> # protected near
  3088. // ::= P <static-offset> # protected far
  3089. // ::= W <static-offset> # public near
  3090. // ::= X <static-offset> # public far
  3091. // <virtual-adjustment> ::= $0 <virtual-shift> <static-offset> # private near
  3092. // ::= $1 <virtual-shift> <static-offset> # private far
  3093. // ::= $2 <virtual-shift> <static-offset> # protected near
  3094. // ::= $3 <virtual-shift> <static-offset> # protected far
  3095. // ::= $4 <virtual-shift> <static-offset> # public near
  3096. // ::= $5 <virtual-shift> <static-offset> # public far
  3097. // <virtual-shift> ::= <vtordisp-shift> | <vtordispex-shift>
  3098. // <vtordisp-shift> ::= <offset-to-vtordisp>
  3099. // <vtordispex-shift> ::= <offset-to-vbptr> <vbase-offset-offset>
  3100. // <offset-to-vtordisp>
  3101. static void mangleThunkThisAdjustment(AccessSpecifier AS,
  3102. const ThisAdjustment &Adjustment,
  3103. MicrosoftCXXNameMangler &Mangler,
  3104. raw_ostream &Out) {
  3105. if (!Adjustment.Virtual.isEmpty()) {
  3106. Out << '$';
  3107. char AccessSpec;
  3108. switch (AS) {
  3109. case AS_none:
  3110. llvm_unreachable("Unsupported access specifier");
  3111. case AS_private:
  3112. AccessSpec = '0';
  3113. break;
  3114. case AS_protected:
  3115. AccessSpec = '2';
  3116. break;
  3117. case AS_public:
  3118. AccessSpec = '4';
  3119. }
  3120. if (Adjustment.Virtual.Microsoft.VBPtrOffset) {
  3121. Out << 'R' << AccessSpec;
  3122. Mangler.mangleNumber(
  3123. static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBPtrOffset));
  3124. Mangler.mangleNumber(
  3125. static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBOffsetOffset));
  3126. Mangler.mangleNumber(
  3127. static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
  3128. Mangler.mangleNumber(static_cast<uint32_t>(Adjustment.NonVirtual));
  3129. } else {
  3130. Out << AccessSpec;
  3131. Mangler.mangleNumber(
  3132. static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
  3133. Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
  3134. }
  3135. } else if (Adjustment.NonVirtual != 0) {
  3136. switch (AS) {
  3137. case AS_none:
  3138. llvm_unreachable("Unsupported access specifier");
  3139. case AS_private:
  3140. Out << 'G';
  3141. break;
  3142. case AS_protected:
  3143. Out << 'O';
  3144. break;
  3145. case AS_public:
  3146. Out << 'W';
  3147. }
  3148. Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
  3149. } else {
  3150. switch (AS) {
  3151. case AS_none:
  3152. llvm_unreachable("Unsupported access specifier");
  3153. case AS_private:
  3154. Out << 'A';
  3155. break;
  3156. case AS_protected:
  3157. Out << 'I';
  3158. break;
  3159. case AS_public:
  3160. Out << 'Q';
  3161. }
  3162. }
  3163. }
  3164. void MicrosoftMangleContextImpl::mangleVirtualMemPtrThunk(
  3165. const CXXMethodDecl *MD, const MethodVFTableLocation &ML,
  3166. raw_ostream &Out) {
  3167. msvc_hashing_ostream MHO(Out);
  3168. MicrosoftCXXNameMangler Mangler(*this, MHO);
  3169. Mangler.getStream() << '?';
  3170. Mangler.mangleVirtualMemPtrThunk(MD, ML);
  3171. }
  3172. void MicrosoftMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
  3173. const ThunkInfo &Thunk,
  3174. raw_ostream &Out) {
  3175. msvc_hashing_ostream MHO(Out);
  3176. MicrosoftCXXNameMangler Mangler(*this, MHO);
  3177. Mangler.getStream() << '?';
  3178. Mangler.mangleName(MD);
  3179. // Usually the thunk uses the access specifier of the new method, but if this
  3180. // is a covariant return thunk, then MSVC always uses the public access
  3181. // specifier, and we do the same.
  3182. AccessSpecifier AS = Thunk.Return.isEmpty() ? MD->getAccess() : AS_public;
  3183. mangleThunkThisAdjustment(AS, Thunk.This, Mangler, MHO);
  3184. if (!Thunk.Return.isEmpty())
  3185. assert(Thunk.Method != nullptr &&
  3186. "Thunk info should hold the overridee decl");
  3187. const CXXMethodDecl *DeclForFPT = Thunk.Method ? Thunk.Method : MD;
  3188. Mangler.mangleFunctionType(
  3189. DeclForFPT->getType()->castAs<FunctionProtoType>(), MD);
  3190. }
  3191. void MicrosoftMangleContextImpl::mangleCXXDtorThunk(
  3192. const CXXDestructorDecl *DD, CXXDtorType Type,
  3193. const ThisAdjustment &Adjustment, raw_ostream &Out) {
  3194. // FIXME: Actually, the dtor thunk should be emitted for vector deleting
  3195. // dtors rather than scalar deleting dtors. Just use the vector deleting dtor
  3196. // mangling manually until we support both deleting dtor types.
  3197. assert(Type == Dtor_Deleting);
  3198. msvc_hashing_ostream MHO(Out);
  3199. MicrosoftCXXNameMangler Mangler(*this, MHO, DD, Type);
  3200. Mangler.getStream() << "??_E";
  3201. Mangler.mangleName(DD->getParent());
  3202. mangleThunkThisAdjustment(DD->getAccess(), Adjustment, Mangler, MHO);
  3203. Mangler.mangleFunctionType(DD->getType()->castAs<FunctionProtoType>(), DD);
  3204. }
  3205. void MicrosoftMangleContextImpl::mangleCXXVFTable(
  3206. const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
  3207. raw_ostream &Out) {
  3208. // <mangled-name> ::= ?_7 <class-name> <storage-class>
  3209. // <cvr-qualifiers> [<name>] @
  3210. // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
  3211. // is always '6' for vftables.
  3212. msvc_hashing_ostream MHO(Out);
  3213. MicrosoftCXXNameMangler Mangler(*this, MHO);
  3214. if (Derived->hasAttr<DLLImportAttr>())
  3215. Mangler.getStream() << "??_S";
  3216. else
  3217. Mangler.getStream() << "??_7";
  3218. Mangler.mangleName(Derived);
  3219. Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
  3220. for (const CXXRecordDecl *RD : BasePath)
  3221. Mangler.mangleName(RD);
  3222. Mangler.getStream() << '@';
  3223. }
  3224. void MicrosoftMangleContextImpl::mangleCXXVBTable(
  3225. const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
  3226. raw_ostream &Out) {
  3227. // <mangled-name> ::= ?_8 <class-name> <storage-class>
  3228. // <cvr-qualifiers> [<name>] @
  3229. // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
  3230. // is always '7' for vbtables.
  3231. msvc_hashing_ostream MHO(Out);
  3232. MicrosoftCXXNameMangler Mangler(*this, MHO);
  3233. Mangler.getStream() << "??_8";
  3234. Mangler.mangleName(Derived);
  3235. Mangler.getStream() << "7B"; // '7' for vbtable, 'B' for const.
  3236. for (const CXXRecordDecl *RD : BasePath)
  3237. Mangler.mangleName(RD);
  3238. Mangler.getStream() << '@';
  3239. }
  3240. void MicrosoftMangleContextImpl::mangleCXXRTTI(QualType T, raw_ostream &Out) {
  3241. msvc_hashing_ostream MHO(Out);
  3242. MicrosoftCXXNameMangler Mangler(*this, MHO);
  3243. Mangler.getStream() << "??_R0";
  3244. Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
  3245. Mangler.getStream() << "@8";
  3246. }
  3247. void MicrosoftMangleContextImpl::mangleCXXRTTIName(QualType T,
  3248. raw_ostream &Out) {
  3249. MicrosoftCXXNameMangler Mangler(*this, Out);
  3250. Mangler.getStream() << '.';
  3251. Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
  3252. }
  3253. void MicrosoftMangleContextImpl::mangleCXXVirtualDisplacementMap(
  3254. const CXXRecordDecl *SrcRD, const CXXRecordDecl *DstRD, raw_ostream &Out) {
  3255. msvc_hashing_ostream MHO(Out);
  3256. MicrosoftCXXNameMangler Mangler(*this, MHO);
  3257. Mangler.getStream() << "??_K";
  3258. Mangler.mangleName(SrcRD);
  3259. Mangler.getStream() << "$C";
  3260. Mangler.mangleName(DstRD);
  3261. }
  3262. void MicrosoftMangleContextImpl::mangleCXXThrowInfo(QualType T, bool IsConst,
  3263. bool IsVolatile,
  3264. bool IsUnaligned,
  3265. uint32_t NumEntries,
  3266. raw_ostream &Out) {
  3267. msvc_hashing_ostream MHO(Out);
  3268. MicrosoftCXXNameMangler Mangler(*this, MHO);
  3269. Mangler.getStream() << "_TI";
  3270. if (IsConst)
  3271. Mangler.getStream() << 'C';
  3272. if (IsVolatile)
  3273. Mangler.getStream() << 'V';
  3274. if (IsUnaligned)
  3275. Mangler.getStream() << 'U';
  3276. Mangler.getStream() << NumEntries;
  3277. Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
  3278. }
  3279. void MicrosoftMangleContextImpl::mangleCXXCatchableTypeArray(
  3280. QualType T, uint32_t NumEntries, raw_ostream &Out) {
  3281. msvc_hashing_ostream MHO(Out);
  3282. MicrosoftCXXNameMangler Mangler(*this, MHO);
  3283. Mangler.getStream() << "_CTA";
  3284. Mangler.getStream() << NumEntries;
  3285. Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
  3286. }
  3287. void MicrosoftMangleContextImpl::mangleCXXCatchableType(
  3288. QualType T, const CXXConstructorDecl *CD, CXXCtorType CT, uint32_t Size,
  3289. uint32_t NVOffset, int32_t VBPtrOffset, uint32_t VBIndex,
  3290. raw_ostream &Out) {
  3291. MicrosoftCXXNameMangler Mangler(*this, Out);
  3292. Mangler.getStream() << "_CT";
  3293. llvm::SmallString<64> RTTIMangling;
  3294. {
  3295. llvm::raw_svector_ostream Stream(RTTIMangling);
  3296. msvc_hashing_ostream MHO(Stream);
  3297. mangleCXXRTTI(T, MHO);
  3298. }
  3299. Mangler.getStream() << RTTIMangling;
  3300. // VS2015 and VS2017.1 omit the copy-constructor in the mangled name but
  3301. // both older and newer versions include it.
  3302. // FIXME: It is known that the Ctor is present in 2013, and in 2017.7
  3303. // (_MSC_VER 1914) and newer, and that it's omitted in 2015 and 2017.4
  3304. // (_MSC_VER 1911), but it's unknown when exactly it reappeared (1914?
  3305. // Or 1912, 1913 already?).
  3306. bool OmitCopyCtor = getASTContext().getLangOpts().isCompatibleWithMSVC(
  3307. LangOptions::MSVC2015) &&
  3308. !getASTContext().getLangOpts().isCompatibleWithMSVC(
  3309. LangOptions::MSVC2017_7);
  3310. llvm::SmallString<64> CopyCtorMangling;
  3311. if (!OmitCopyCtor && CD) {
  3312. llvm::raw_svector_ostream Stream(CopyCtorMangling);
  3313. msvc_hashing_ostream MHO(Stream);
  3314. mangleCXXName(GlobalDecl(CD, CT), MHO);
  3315. }
  3316. Mangler.getStream() << CopyCtorMangling;
  3317. Mangler.getStream() << Size;
  3318. if (VBPtrOffset == -1) {
  3319. if (NVOffset) {
  3320. Mangler.getStream() << NVOffset;
  3321. }
  3322. } else {
  3323. Mangler.getStream() << NVOffset;
  3324. Mangler.getStream() << VBPtrOffset;
  3325. Mangler.getStream() << VBIndex;
  3326. }
  3327. }
  3328. void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassDescriptor(
  3329. const CXXRecordDecl *Derived, uint32_t NVOffset, int32_t VBPtrOffset,
  3330. uint32_t VBTableOffset, uint32_t Flags, raw_ostream &Out) {
  3331. msvc_hashing_ostream MHO(Out);
  3332. MicrosoftCXXNameMangler Mangler(*this, MHO);
  3333. Mangler.getStream() << "??_R1";
  3334. Mangler.mangleNumber(NVOffset);
  3335. Mangler.mangleNumber(VBPtrOffset);
  3336. Mangler.mangleNumber(VBTableOffset);
  3337. Mangler.mangleNumber(Flags);
  3338. Mangler.mangleName(Derived);
  3339. Mangler.getStream() << "8";
  3340. }
  3341. void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassArray(
  3342. const CXXRecordDecl *Derived, raw_ostream &Out) {
  3343. msvc_hashing_ostream MHO(Out);
  3344. MicrosoftCXXNameMangler Mangler(*this, MHO);
  3345. Mangler.getStream() << "??_R2";
  3346. Mangler.mangleName(Derived);
  3347. Mangler.getStream() << "8";
  3348. }
  3349. void MicrosoftMangleContextImpl::mangleCXXRTTIClassHierarchyDescriptor(
  3350. const CXXRecordDecl *Derived, raw_ostream &Out) {
  3351. msvc_hashing_ostream MHO(Out);
  3352. MicrosoftCXXNameMangler Mangler(*this, MHO);
  3353. Mangler.getStream() << "??_R3";
  3354. Mangler.mangleName(Derived);
  3355. Mangler.getStream() << "8";
  3356. }
  3357. void MicrosoftMangleContextImpl::mangleCXXRTTICompleteObjectLocator(
  3358. const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
  3359. raw_ostream &Out) {
  3360. // <mangled-name> ::= ?_R4 <class-name> <storage-class>
  3361. // <cvr-qualifiers> [<name>] @
  3362. // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
  3363. // is always '6' for vftables.
  3364. llvm::SmallString<64> VFTableMangling;
  3365. llvm::raw_svector_ostream Stream(VFTableMangling);
  3366. mangleCXXVFTable(Derived, BasePath, Stream);
  3367. if (VFTableMangling.startswith("??@")) {
  3368. assert(VFTableMangling.endswith("@"));
  3369. Out << VFTableMangling << "??_R4@";
  3370. return;
  3371. }
  3372. assert(VFTableMangling.startswith("??_7") ||
  3373. VFTableMangling.startswith("??_S"));
  3374. Out << "??_R4" << VFTableMangling.str().drop_front(4);
  3375. }
  3376. void MicrosoftMangleContextImpl::mangleSEHFilterExpression(
  3377. GlobalDecl EnclosingDecl, raw_ostream &Out) {
  3378. msvc_hashing_ostream MHO(Out);
  3379. MicrosoftCXXNameMangler Mangler(*this, MHO);
  3380. // The function body is in the same comdat as the function with the handler,
  3381. // so the numbering here doesn't have to be the same across TUs.
  3382. //
  3383. // <mangled-name> ::= ?filt$ <filter-number> @0
  3384. Mangler.getStream() << "?filt$" << SEHFilterIds[EnclosingDecl]++ << "@0@";
  3385. Mangler.mangleName(EnclosingDecl);
  3386. }
  3387. void MicrosoftMangleContextImpl::mangleSEHFinallyBlock(
  3388. GlobalDecl EnclosingDecl, raw_ostream &Out) {
  3389. msvc_hashing_ostream MHO(Out);
  3390. MicrosoftCXXNameMangler Mangler(*this, MHO);
  3391. // The function body is in the same comdat as the function with the handler,
  3392. // so the numbering here doesn't have to be the same across TUs.
  3393. //
  3394. // <mangled-name> ::= ?fin$ <filter-number> @0
  3395. Mangler.getStream() << "?fin$" << SEHFinallyIds[EnclosingDecl]++ << "@0@";
  3396. Mangler.mangleName(EnclosingDecl);
  3397. }
  3398. void MicrosoftMangleContextImpl::mangleTypeName(QualType T, raw_ostream &Out) {
  3399. // This is just a made up unique string for the purposes of tbaa. undname
  3400. // does *not* know how to demangle it.
  3401. MicrosoftCXXNameMangler Mangler(*this, Out);
  3402. Mangler.getStream() << '?';
  3403. Mangler.mangleType(T, SourceRange());
  3404. }
  3405. void MicrosoftMangleContextImpl::mangleReferenceTemporary(
  3406. const VarDecl *VD, unsigned ManglingNumber, raw_ostream &Out) {
  3407. msvc_hashing_ostream MHO(Out);
  3408. MicrosoftCXXNameMangler Mangler(*this, MHO);
  3409. Mangler.getStream() << "?$RT" << ManglingNumber << '@';
  3410. Mangler.mangle(VD, "");
  3411. }
  3412. void MicrosoftMangleContextImpl::mangleThreadSafeStaticGuardVariable(
  3413. const VarDecl *VD, unsigned GuardNum, raw_ostream &Out) {
  3414. msvc_hashing_ostream MHO(Out);
  3415. MicrosoftCXXNameMangler Mangler(*this, MHO);
  3416. Mangler.getStream() << "?$TSS" << GuardNum << '@';
  3417. Mangler.mangleNestedName(VD);
  3418. Mangler.getStream() << "@4HA";
  3419. }
  3420. void MicrosoftMangleContextImpl::mangleStaticGuardVariable(const VarDecl *VD,
  3421. raw_ostream &Out) {
  3422. // <guard-name> ::= ?_B <postfix> @5 <scope-depth>
  3423. // ::= ?__J <postfix> @5 <scope-depth>
  3424. // ::= ?$S <guard-num> @ <postfix> @4IA
  3425. // The first mangling is what MSVC uses to guard static locals in inline
  3426. // functions. It uses a different mangling in external functions to support
  3427. // guarding more than 32 variables. MSVC rejects inline functions with more
  3428. // than 32 static locals. We don't fully implement the second mangling
  3429. // because those guards are not externally visible, and instead use LLVM's
  3430. // default renaming when creating a new guard variable.
  3431. msvc_hashing_ostream MHO(Out);
  3432. MicrosoftCXXNameMangler Mangler(*this, MHO);
  3433. bool Visible = VD->isExternallyVisible();
  3434. if (Visible) {
  3435. Mangler.getStream() << (VD->getTLSKind() ? "??__J" : "??_B");
  3436. } else {
  3437. Mangler.getStream() << "?$S1@";
  3438. }
  3439. unsigned ScopeDepth = 0;
  3440. if (Visible && !getNextDiscriminator(VD, ScopeDepth))
  3441. // If we do not have a discriminator and are emitting a guard variable for
  3442. // use at global scope, then mangling the nested name will not be enough to
  3443. // remove ambiguities.
  3444. Mangler.mangle(VD, "");
  3445. else
  3446. Mangler.mangleNestedName(VD);
  3447. Mangler.getStream() << (Visible ? "@5" : "@4IA");
  3448. if (ScopeDepth)
  3449. Mangler.mangleNumber(ScopeDepth);
  3450. }
  3451. void MicrosoftMangleContextImpl::mangleInitFiniStub(const VarDecl *D,
  3452. char CharCode,
  3453. raw_ostream &Out) {
  3454. msvc_hashing_ostream MHO(Out);
  3455. MicrosoftCXXNameMangler Mangler(*this, MHO);
  3456. Mangler.getStream() << "??__" << CharCode;
  3457. if (D->isStaticDataMember()) {
  3458. Mangler.getStream() << '?';
  3459. Mangler.mangleName(D);
  3460. Mangler.mangleVariableEncoding(D);
  3461. Mangler.getStream() << "@@";
  3462. } else {
  3463. Mangler.mangleName(D);
  3464. }
  3465. // This is the function class mangling. These stubs are global, non-variadic,
  3466. // cdecl functions that return void and take no args.
  3467. Mangler.getStream() << "YAXXZ";
  3468. }
  3469. void MicrosoftMangleContextImpl::mangleDynamicInitializer(const VarDecl *D,
  3470. raw_ostream &Out) {
  3471. // <initializer-name> ::= ?__E <name> YAXXZ
  3472. mangleInitFiniStub(D, 'E', Out);
  3473. }
  3474. void
  3475. MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
  3476. raw_ostream &Out) {
  3477. // <destructor-name> ::= ?__F <name> YAXXZ
  3478. mangleInitFiniStub(D, 'F', Out);
  3479. }
  3480. void MicrosoftMangleContextImpl::mangleStringLiteral(const StringLiteral *SL,
  3481. raw_ostream &Out) {
  3482. // <char-type> ::= 0 # char, char16_t, char32_t
  3483. // # (little endian char data in mangling)
  3484. // ::= 1 # wchar_t (big endian char data in mangling)
  3485. //
  3486. // <literal-length> ::= <non-negative integer> # the length of the literal
  3487. //
  3488. // <encoded-crc> ::= <hex digit>+ @ # crc of the literal including
  3489. // # trailing null bytes
  3490. //
  3491. // <encoded-string> ::= <simple character> # uninteresting character
  3492. // ::= '?$' <hex digit> <hex digit> # these two nibbles
  3493. // # encode the byte for the
  3494. // # character
  3495. // ::= '?' [a-z] # \xe1 - \xfa
  3496. // ::= '?' [A-Z] # \xc1 - \xda
  3497. // ::= '?' [0-9] # [,/\:. \n\t'-]
  3498. //
  3499. // <literal> ::= '??_C@_' <char-type> <literal-length> <encoded-crc>
  3500. // <encoded-string> '@'
  3501. MicrosoftCXXNameMangler Mangler(*this, Out);
  3502. Mangler.getStream() << "??_C@_";
  3503. // The actual string length might be different from that of the string literal
  3504. // in cases like:
  3505. // char foo[3] = "foobar";
  3506. // char bar[42] = "foobar";
  3507. // Where it is truncated or zero-padded to fit the array. This is the length
  3508. // used for mangling, and any trailing null-bytes also need to be mangled.
  3509. unsigned StringLength = getASTContext()
  3510. .getAsConstantArrayType(SL->getType())
  3511. ->getSize()
  3512. .getZExtValue();
  3513. unsigned StringByteLength = StringLength * SL->getCharByteWidth();
  3514. // <char-type>: The "kind" of string literal is encoded into the mangled name.
  3515. if (SL->isWide())
  3516. Mangler.getStream() << '1';
  3517. else
  3518. Mangler.getStream() << '0';
  3519. // <literal-length>: The next part of the mangled name consists of the length
  3520. // of the string in bytes.
  3521. Mangler.mangleNumber(StringByteLength);
  3522. auto GetLittleEndianByte = [&SL](unsigned Index) {
  3523. unsigned CharByteWidth = SL->getCharByteWidth();
  3524. if (Index / CharByteWidth >= SL->getLength())
  3525. return static_cast<char>(0);
  3526. uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
  3527. unsigned OffsetInCodeUnit = Index % CharByteWidth;
  3528. return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
  3529. };
  3530. auto GetBigEndianByte = [&SL](unsigned Index) {
  3531. unsigned CharByteWidth = SL->getCharByteWidth();
  3532. if (Index / CharByteWidth >= SL->getLength())
  3533. return static_cast<char>(0);
  3534. uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
  3535. unsigned OffsetInCodeUnit = (CharByteWidth - 1) - (Index % CharByteWidth);
  3536. return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
  3537. };
  3538. // CRC all the bytes of the StringLiteral.
  3539. llvm::JamCRC JC;
  3540. for (unsigned I = 0, E = StringByteLength; I != E; ++I)
  3541. JC.update(GetLittleEndianByte(I));
  3542. // <encoded-crc>: The CRC is encoded utilizing the standard number mangling
  3543. // scheme.
  3544. Mangler.mangleNumber(JC.getCRC());
  3545. // <encoded-string>: The mangled name also contains the first 32 bytes
  3546. // (including null-terminator bytes) of the encoded StringLiteral.
  3547. // Each character is encoded by splitting them into bytes and then encoding
  3548. // the constituent bytes.
  3549. auto MangleByte = [&Mangler](char Byte) {
  3550. // There are five different manglings for characters:
  3551. // - [a-zA-Z0-9_$]: A one-to-one mapping.
  3552. // - ?[a-z]: The range from \xe1 to \xfa.
  3553. // - ?[A-Z]: The range from \xc1 to \xda.
  3554. // - ?[0-9]: The set of [,/\:. \n\t'-].
  3555. // - ?$XX: A fallback which maps nibbles.
  3556. if (isAsciiIdentifierContinue(Byte, /*AllowDollar=*/true)) {
  3557. Mangler.getStream() << Byte;
  3558. } else if (isLetter(Byte & 0x7f)) {
  3559. Mangler.getStream() << '?' << static_cast<char>(Byte & 0x7f);
  3560. } else {
  3561. const char SpecialChars[] = {',', '/', '\\', ':', '.',
  3562. ' ', '\n', '\t', '\'', '-'};
  3563. const char *Pos = llvm::find(SpecialChars, Byte);
  3564. if (Pos != std::end(SpecialChars)) {
  3565. Mangler.getStream() << '?' << (Pos - std::begin(SpecialChars));
  3566. } else {
  3567. Mangler.getStream() << "?$";
  3568. Mangler.getStream() << static_cast<char>('A' + ((Byte >> 4) & 0xf));
  3569. Mangler.getStream() << static_cast<char>('A' + (Byte & 0xf));
  3570. }
  3571. }
  3572. };
  3573. // Enforce our 32 bytes max, except wchar_t which gets 32 chars instead.
  3574. unsigned MaxBytesToMangle = SL->isWide() ? 64U : 32U;
  3575. unsigned NumBytesToMangle = std::min(MaxBytesToMangle, StringByteLength);
  3576. for (unsigned I = 0; I != NumBytesToMangle; ++I) {
  3577. if (SL->isWide())
  3578. MangleByte(GetBigEndianByte(I));
  3579. else
  3580. MangleByte(GetLittleEndianByte(I));
  3581. }
  3582. Mangler.getStream() << '@';
  3583. }
  3584. MicrosoftMangleContext *MicrosoftMangleContext::create(ASTContext &Context,
  3585. DiagnosticsEngine &Diags,
  3586. bool IsAux) {
  3587. return new MicrosoftMangleContextImpl(Context, Diags, IsAux);
  3588. }