MicrosoftMangle.cpp 147 KB

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