MicrosoftMangle.cpp 132 KB

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