MicrosoftMangle.cpp 107 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814
  1. //===--- MicrosoftMangle.cpp - Microsoft Visual C++ Name Mangling ---------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This provides C++ name mangling targeting the Microsoft Visual C++ ABI.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/AST/Mangle.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/Attr.h"
  16. #include "clang/AST/CXXInheritance.h"
  17. #include "clang/AST/CharUnits.h"
  18. #include "clang/AST/Decl.h"
  19. #include "clang/AST/DeclCXX.h"
  20. #include "clang/AST/DeclObjC.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/MathExtras.h"
  30. using namespace clang;
  31. namespace {
  32. /// \brief Retrieve the declaration context that should be used when mangling
  33. /// the given declaration.
  34. static const DeclContext *getEffectiveDeclContext(const Decl *D) {
  35. // The ABI assumes that lambda closure types that occur within
  36. // default arguments live in the context of the function. However, due to
  37. // the way in which Clang parses and creates function declarations, this is
  38. // not the case: the lambda closure type ends up living in the context
  39. // where the function itself resides, because the function declaration itself
  40. // had not yet been created. Fix the context here.
  41. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
  42. if (RD->isLambda())
  43. if (ParmVarDecl *ContextParam =
  44. dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
  45. return ContextParam->getDeclContext();
  46. }
  47. // Perform the same check for block literals.
  48. if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
  49. if (ParmVarDecl *ContextParam =
  50. dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
  51. return ContextParam->getDeclContext();
  52. }
  53. const DeclContext *DC = D->getDeclContext();
  54. if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(DC))
  55. return getEffectiveDeclContext(CD);
  56. return DC;
  57. }
  58. static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
  59. return getEffectiveDeclContext(cast<Decl>(DC));
  60. }
  61. static const FunctionDecl *getStructor(const NamedDecl *ND) {
  62. if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(ND))
  63. return FTD->getTemplatedDecl();
  64. const auto *FD = cast<FunctionDecl>(ND);
  65. if (const auto *FTD = FD->getPrimaryTemplate())
  66. return FTD->getTemplatedDecl();
  67. return FD;
  68. }
  69. static bool isLambda(const NamedDecl *ND) {
  70. const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
  71. if (!Record)
  72. return false;
  73. return Record->isLambda();
  74. }
  75. /// MicrosoftMangleContextImpl - Overrides the default MangleContext for the
  76. /// Microsoft Visual C++ ABI.
  77. class MicrosoftMangleContextImpl : public MicrosoftMangleContext {
  78. typedef std::pair<const DeclContext *, IdentifierInfo *> DiscriminatorKeyTy;
  79. llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
  80. llvm::DenseMap<const NamedDecl *, unsigned> Uniquifier;
  81. llvm::DenseMap<const CXXRecordDecl *, unsigned> LambdaIds;
  82. llvm::DenseMap<const NamedDecl *, unsigned> SEHFilterIds;
  83. llvm::DenseMap<const NamedDecl *, unsigned> SEHFinallyIds;
  84. public:
  85. MicrosoftMangleContextImpl(ASTContext &Context, DiagnosticsEngine &Diags)
  86. : MicrosoftMangleContext(Context, Diags) {}
  87. bool shouldMangleCXXName(const NamedDecl *D) override;
  88. bool shouldMangleStringLiteral(const StringLiteral *SL) override;
  89. void mangleCXXName(const NamedDecl *D, raw_ostream &Out) override;
  90. void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
  91. raw_ostream &) override;
  92. void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
  93. raw_ostream &) override;
  94. void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
  95. const ThisAdjustment &ThisAdjustment,
  96. raw_ostream &) override;
  97. void mangleCXXVFTable(const CXXRecordDecl *Derived,
  98. ArrayRef<const CXXRecordDecl *> BasePath,
  99. raw_ostream &Out) override;
  100. void mangleCXXVBTable(const CXXRecordDecl *Derived,
  101. ArrayRef<const CXXRecordDecl *> BasePath,
  102. raw_ostream &Out) override;
  103. void mangleCXXVirtualDisplacementMap(const CXXRecordDecl *SrcRD,
  104. const CXXRecordDecl *DstRD,
  105. raw_ostream &Out) override;
  106. void mangleCXXThrowInfo(QualType T, bool IsConst, bool IsVolatile,
  107. uint32_t NumEntries, raw_ostream &Out) override;
  108. void mangleCXXCatchableTypeArray(QualType T, uint32_t NumEntries,
  109. raw_ostream &Out) override;
  110. void mangleCXXCatchableType(QualType T, const CXXConstructorDecl *CD,
  111. CXXCtorType CT, uint32_t Size, uint32_t NVOffset,
  112. int32_t VBPtrOffset, uint32_t VBIndex,
  113. raw_ostream &Out) override;
  114. void mangleCXXCatchHandlerType(QualType T, uint32_t Flags,
  115. raw_ostream &Out) override;
  116. void mangleCXXRTTI(QualType T, raw_ostream &Out) override;
  117. void mangleCXXRTTIName(QualType T, raw_ostream &Out) override;
  118. void mangleCXXRTTIBaseClassDescriptor(const CXXRecordDecl *Derived,
  119. uint32_t NVOffset, int32_t VBPtrOffset,
  120. uint32_t VBTableOffset, uint32_t Flags,
  121. raw_ostream &Out) override;
  122. void mangleCXXRTTIBaseClassArray(const CXXRecordDecl *Derived,
  123. raw_ostream &Out) override;
  124. void mangleCXXRTTIClassHierarchyDescriptor(const CXXRecordDecl *Derived,
  125. raw_ostream &Out) override;
  126. void
  127. mangleCXXRTTICompleteObjectLocator(const CXXRecordDecl *Derived,
  128. ArrayRef<const CXXRecordDecl *> BasePath,
  129. raw_ostream &Out) override;
  130. void mangleTypeName(QualType T, raw_ostream &) override;
  131. void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
  132. raw_ostream &) override;
  133. void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
  134. raw_ostream &) override;
  135. void mangleReferenceTemporary(const VarDecl *, unsigned ManglingNumber,
  136. raw_ostream &) override;
  137. void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &Out) override;
  138. void mangleThreadSafeStaticGuardVariable(const VarDecl *D, unsigned GuardNum,
  139. raw_ostream &Out) override;
  140. void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
  141. void mangleDynamicAtExitDestructor(const VarDecl *D,
  142. raw_ostream &Out) override;
  143. void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
  144. raw_ostream &Out) override;
  145. void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
  146. raw_ostream &Out) override;
  147. void mangleStringLiteral(const StringLiteral *SL, raw_ostream &Out) override;
  148. void mangleCXXVTableBitSet(const CXXRecordDecl *RD,
  149. raw_ostream &Out) override;
  150. bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
  151. // Lambda closure types are already numbered.
  152. if (isLambda(ND))
  153. return false;
  154. const DeclContext *DC = getEffectiveDeclContext(ND);
  155. if (!DC->isFunctionOrMethod())
  156. return false;
  157. // Use the canonical number for externally visible decls.
  158. if (ND->isExternallyVisible()) {
  159. disc = getASTContext().getManglingNumber(ND);
  160. return true;
  161. }
  162. // Anonymous tags are already numbered.
  163. if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
  164. if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
  165. return false;
  166. }
  167. // Make up a reasonable number for internal decls.
  168. unsigned &discriminator = Uniquifier[ND];
  169. if (!discriminator)
  170. discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
  171. disc = discriminator + 1;
  172. return true;
  173. }
  174. unsigned getLambdaId(const CXXRecordDecl *RD) {
  175. assert(RD->isLambda() && "RD must be a lambda!");
  176. assert(!RD->isExternallyVisible() && "RD must not be visible!");
  177. assert(RD->getLambdaManglingNumber() == 0 &&
  178. "RD must not have a mangling number!");
  179. std::pair<llvm::DenseMap<const CXXRecordDecl *, unsigned>::iterator, bool>
  180. Result = LambdaIds.insert(std::make_pair(RD, LambdaIds.size()));
  181. return Result.first->second;
  182. }
  183. private:
  184. void mangleInitFiniStub(const VarDecl *D, raw_ostream &Out, char CharCode);
  185. };
  186. /// MicrosoftCXXNameMangler - Manage the mangling of a single name for the
  187. /// Microsoft Visual C++ ABI.
  188. class MicrosoftCXXNameMangler {
  189. MicrosoftMangleContextImpl &Context;
  190. raw_ostream &Out;
  191. /// The "structor" is the top-level declaration being mangled, if
  192. /// that's not a template specialization; otherwise it's the pattern
  193. /// for that specialization.
  194. const NamedDecl *Structor;
  195. unsigned StructorType;
  196. typedef llvm::SmallVector<std::string, 10> BackRefVec;
  197. BackRefVec NameBackReferences;
  198. typedef llvm::DenseMap<void *, unsigned> ArgBackRefMap;
  199. ArgBackRefMap TypeBackReferences;
  200. ASTContext &getASTContext() const { return Context.getASTContext(); }
  201. // FIXME: If we add support for __ptr32/64 qualifiers, then we should push
  202. // this check into mangleQualifiers().
  203. const bool PointersAre64Bit;
  204. public:
  205. enum QualifierMangleMode { QMM_Drop, QMM_Mangle, QMM_Escape, QMM_Result };
  206. MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_)
  207. : Context(C), Out(Out_), Structor(nullptr), StructorType(-1),
  208. PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
  209. 64) {}
  210. MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
  211. const CXXConstructorDecl *D, CXXCtorType Type)
  212. : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
  213. PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
  214. 64) {}
  215. MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
  216. const CXXDestructorDecl *D, CXXDtorType Type)
  217. : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
  218. PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
  219. 64) {}
  220. raw_ostream &getStream() const { return Out; }
  221. void mangle(const NamedDecl *D, StringRef Prefix = "\01?");
  222. void mangleName(const NamedDecl *ND);
  223. void mangleFunctionEncoding(const FunctionDecl *FD, bool ShouldMangle);
  224. void mangleVariableEncoding(const VarDecl *VD);
  225. void mangleMemberDataPointer(const CXXRecordDecl *RD, const ValueDecl *VD);
  226. void mangleMemberFunctionPointer(const CXXRecordDecl *RD,
  227. const CXXMethodDecl *MD);
  228. void mangleVirtualMemPtrThunk(
  229. const CXXMethodDecl *MD,
  230. const MicrosoftVTableContext::MethodVFTableLocation &ML);
  231. void mangleNumber(int64_t Number);
  232. void mangleType(QualType T, SourceRange Range,
  233. QualifierMangleMode QMM = QMM_Mangle);
  234. void mangleFunctionType(const FunctionType *T,
  235. const FunctionDecl *D = nullptr,
  236. bool ForceThisQuals = false);
  237. void mangleNestedName(const NamedDecl *ND);
  238. private:
  239. void mangleUnqualifiedName(const NamedDecl *ND) {
  240. mangleUnqualifiedName(ND, ND->getDeclName());
  241. }
  242. void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name);
  243. void mangleSourceName(StringRef Name);
  244. void mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc);
  245. void mangleCXXDtorType(CXXDtorType T);
  246. void mangleQualifiers(Qualifiers Quals, bool IsMember);
  247. void mangleRefQualifier(RefQualifierKind RefQualifier);
  248. void manglePointerCVQualifiers(Qualifiers Quals);
  249. void manglePointerExtQualifiers(Qualifiers Quals, QualType PointeeType);
  250. void mangleUnscopedTemplateName(const TemplateDecl *ND);
  251. void
  252. mangleTemplateInstantiationName(const TemplateDecl *TD,
  253. const TemplateArgumentList &TemplateArgs);
  254. void mangleObjCMethodName(const ObjCMethodDecl *MD);
  255. void mangleArgumentType(QualType T, SourceRange Range);
  256. // Declare manglers for every type class.
  257. #define ABSTRACT_TYPE(CLASS, PARENT)
  258. #define NON_CANONICAL_TYPE(CLASS, PARENT)
  259. #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T, \
  260. Qualifiers Quals, \
  261. SourceRange Range);
  262. #include "clang/AST/TypeNodes.def"
  263. #undef ABSTRACT_TYPE
  264. #undef NON_CANONICAL_TYPE
  265. #undef TYPE
  266. void mangleType(const TagDecl *TD);
  267. void mangleDecayedArrayType(const ArrayType *T);
  268. void mangleArrayType(const ArrayType *T);
  269. void mangleFunctionClass(const FunctionDecl *FD);
  270. void mangleCallingConvention(CallingConv CC);
  271. void mangleCallingConvention(const FunctionType *T);
  272. void mangleIntegerLiteral(const llvm::APSInt &Number, bool IsBoolean);
  273. void mangleExpression(const Expr *E);
  274. void mangleThrowSpecification(const FunctionProtoType *T);
  275. void mangleTemplateArgs(const TemplateDecl *TD,
  276. const TemplateArgumentList &TemplateArgs);
  277. void mangleTemplateArg(const TemplateDecl *TD, const TemplateArgument &TA,
  278. const NamedDecl *Parm);
  279. };
  280. }
  281. bool MicrosoftMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
  282. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  283. LanguageLinkage L = FD->getLanguageLinkage();
  284. // Overloadable functions need mangling.
  285. if (FD->hasAttr<OverloadableAttr>())
  286. return true;
  287. // The ABI expects that we would never mangle "typical" user-defined entry
  288. // points regardless of visibility or freestanding-ness.
  289. //
  290. // N.B. This is distinct from asking about "main". "main" has a lot of
  291. // special rules associated with it in the standard while these
  292. // user-defined entry points are outside of the purview of the standard.
  293. // For example, there can be only one definition for "main" in a standards
  294. // compliant program; however nothing forbids the existence of wmain and
  295. // WinMain in the same translation unit.
  296. if (FD->isMSVCRTEntryPoint())
  297. return false;
  298. // C++ functions and those whose names are not a simple identifier need
  299. // mangling.
  300. if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
  301. return true;
  302. // C functions are not mangled.
  303. if (L == CLanguageLinkage)
  304. return false;
  305. }
  306. // Otherwise, no mangling is done outside C++ mode.
  307. if (!getASTContext().getLangOpts().CPlusPlus)
  308. return false;
  309. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  310. // C variables are not mangled.
  311. if (VD->isExternC())
  312. return false;
  313. // Variables at global scope with non-internal linkage are not mangled.
  314. const DeclContext *DC = getEffectiveDeclContext(D);
  315. // Check for extern variable declared locally.
  316. if (DC->isFunctionOrMethod() && D->hasLinkage())
  317. while (!DC->isNamespace() && !DC->isTranslationUnit())
  318. DC = getEffectiveParentContext(DC);
  319. if (DC->isTranslationUnit() && D->getFormalLinkage() == InternalLinkage &&
  320. !isa<VarTemplateSpecializationDecl>(D))
  321. return false;
  322. }
  323. return true;
  324. }
  325. bool
  326. MicrosoftMangleContextImpl::shouldMangleStringLiteral(const StringLiteral *SL) {
  327. return true;
  328. }
  329. void MicrosoftCXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) {
  330. // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
  331. // Therefore it's really important that we don't decorate the
  332. // name with leading underscores or leading/trailing at signs. So, by
  333. // default, we emit an asm marker at the start so we get the name right.
  334. // Callers can override this with a custom prefix.
  335. // <mangled-name> ::= ? <name> <type-encoding>
  336. Out << Prefix;
  337. mangleName(D);
  338. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  339. mangleFunctionEncoding(FD, Context.shouldMangleDeclName(FD));
  340. else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  341. mangleVariableEncoding(VD);
  342. else {
  343. // TODO: Fields? Can MSVC even mangle them?
  344. // Issue a diagnostic for now.
  345. DiagnosticsEngine &Diags = Context.getDiags();
  346. unsigned DiagID = Diags.getCustomDiagID(
  347. DiagnosticsEngine::Error, "cannot mangle this declaration yet");
  348. Diags.Report(D->getLocation(), DiagID) << D->getSourceRange();
  349. }
  350. }
  351. void MicrosoftCXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD,
  352. bool ShouldMangle) {
  353. // <type-encoding> ::= <function-class> <function-type>
  354. // Since MSVC operates on the type as written and not the canonical type, it
  355. // actually matters which decl we have here. MSVC appears to choose the
  356. // first, since it is most likely to be the declaration in a header file.
  357. FD = FD->getFirstDecl();
  358. // We should never ever see a FunctionNoProtoType at this point.
  359. // We don't even know how to mangle their types anyway :).
  360. const FunctionProtoType *FT = FD->getType()->castAs<FunctionProtoType>();
  361. // extern "C" functions can hold entities that must be mangled.
  362. // As it stands, these functions still need to get expressed in the full
  363. // external name. They have their class and type omitted, replaced with '9'.
  364. if (ShouldMangle) {
  365. // We would like to mangle all extern "C" functions using this additional
  366. // component but this would break compatibility with MSVC's behavior.
  367. // Instead, do this when we know that compatibility isn't important (in
  368. // other words, when it is an overloaded extern "C" funciton).
  369. if (FD->isExternC() && FD->hasAttr<OverloadableAttr>())
  370. Out << "$$J0";
  371. mangleFunctionClass(FD);
  372. mangleFunctionType(FT, FD);
  373. } else {
  374. Out << '9';
  375. }
  376. }
  377. void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) {
  378. // <type-encoding> ::= <storage-class> <variable-type>
  379. // <storage-class> ::= 0 # private static member
  380. // ::= 1 # protected static member
  381. // ::= 2 # public static member
  382. // ::= 3 # global
  383. // ::= 4 # static local
  384. // The first character in the encoding (after the name) is the storage class.
  385. if (VD->isStaticDataMember()) {
  386. // If it's a static member, it also encodes the access level.
  387. switch (VD->getAccess()) {
  388. default:
  389. case AS_private: Out << '0'; break;
  390. case AS_protected: Out << '1'; break;
  391. case AS_public: Out << '2'; break;
  392. }
  393. }
  394. else if (!VD->isStaticLocal())
  395. Out << '3';
  396. else
  397. Out << '4';
  398. // Now mangle the type.
  399. // <variable-type> ::= <type> <cvr-qualifiers>
  400. // ::= <type> <pointee-cvr-qualifiers> # pointers, references
  401. // Pointers and references are odd. The type of 'int * const foo;' gets
  402. // mangled as 'QAHA' instead of 'PAHB', for example.
  403. SourceRange SR = VD->getSourceRange();
  404. QualType Ty = VD->getType();
  405. if (Ty->isPointerType() || Ty->isReferenceType() ||
  406. Ty->isMemberPointerType()) {
  407. mangleType(Ty, SR, QMM_Drop);
  408. manglePointerExtQualifiers(
  409. Ty.getDesugaredType(getASTContext()).getLocalQualifiers(), QualType());
  410. if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()) {
  411. mangleQualifiers(MPT->getPointeeType().getQualifiers(), true);
  412. // Member pointers are suffixed with a back reference to the member
  413. // pointer's class name.
  414. mangleName(MPT->getClass()->getAsCXXRecordDecl());
  415. } else
  416. mangleQualifiers(Ty->getPointeeType().getQualifiers(), false);
  417. } else if (const ArrayType *AT = getASTContext().getAsArrayType(Ty)) {
  418. // Global arrays are funny, too.
  419. mangleDecayedArrayType(AT);
  420. if (AT->getElementType()->isArrayType())
  421. Out << 'A';
  422. else
  423. mangleQualifiers(Ty.getQualifiers(), false);
  424. } else {
  425. mangleType(Ty, SR, QMM_Drop);
  426. mangleQualifiers(Ty.getQualifiers(), false);
  427. }
  428. }
  429. void MicrosoftCXXNameMangler::mangleMemberDataPointer(const CXXRecordDecl *RD,
  430. const ValueDecl *VD) {
  431. // <member-data-pointer> ::= <integer-literal>
  432. // ::= $F <number> <number>
  433. // ::= $G <number> <number> <number>
  434. int64_t FieldOffset;
  435. int64_t VBTableOffset;
  436. MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
  437. if (VD) {
  438. FieldOffset = getASTContext().getFieldOffset(VD);
  439. assert(FieldOffset % getASTContext().getCharWidth() == 0 &&
  440. "cannot take address of bitfield");
  441. FieldOffset /= getASTContext().getCharWidth();
  442. VBTableOffset = 0;
  443. if (IM == MSInheritanceAttr::Keyword_virtual_inheritance)
  444. FieldOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity();
  445. } else {
  446. FieldOffset = RD->nullFieldOffsetIsZero() ? 0 : -1;
  447. VBTableOffset = -1;
  448. }
  449. char Code = '\0';
  450. switch (IM) {
  451. case MSInheritanceAttr::Keyword_single_inheritance: Code = '0'; break;
  452. case MSInheritanceAttr::Keyword_multiple_inheritance: Code = '0'; break;
  453. case MSInheritanceAttr::Keyword_virtual_inheritance: Code = 'F'; break;
  454. case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'G'; break;
  455. }
  456. Out << '$' << Code;
  457. mangleNumber(FieldOffset);
  458. // The C++ standard doesn't allow base-to-derived member pointer conversions
  459. // in template parameter contexts, so the vbptr offset of data member pointers
  460. // is always zero.
  461. if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
  462. mangleNumber(0);
  463. if (MSInheritanceAttr::hasVBTableOffsetField(IM))
  464. mangleNumber(VBTableOffset);
  465. }
  466. void
  467. MicrosoftCXXNameMangler::mangleMemberFunctionPointer(const CXXRecordDecl *RD,
  468. const CXXMethodDecl *MD) {
  469. // <member-function-pointer> ::= $1? <name>
  470. // ::= $H? <name> <number>
  471. // ::= $I? <name> <number> <number>
  472. // ::= $J? <name> <number> <number> <number>
  473. MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
  474. char Code = '\0';
  475. switch (IM) {
  476. case MSInheritanceAttr::Keyword_single_inheritance: Code = '1'; break;
  477. case MSInheritanceAttr::Keyword_multiple_inheritance: Code = 'H'; break;
  478. case MSInheritanceAttr::Keyword_virtual_inheritance: Code = 'I'; break;
  479. case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'J'; break;
  480. }
  481. // If non-virtual, mangle the name. If virtual, mangle as a virtual memptr
  482. // thunk.
  483. uint64_t NVOffset = 0;
  484. uint64_t VBTableOffset = 0;
  485. uint64_t VBPtrOffset = 0;
  486. if (MD) {
  487. Out << '$' << Code << '?';
  488. if (MD->isVirtual()) {
  489. MicrosoftVTableContext *VTContext =
  490. cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
  491. const MicrosoftVTableContext::MethodVFTableLocation &ML =
  492. VTContext->getMethodVFTableLocation(GlobalDecl(MD));
  493. mangleVirtualMemPtrThunk(MD, ML);
  494. NVOffset = ML.VFPtrOffset.getQuantity();
  495. VBTableOffset = ML.VBTableIndex * 4;
  496. if (ML.VBase) {
  497. const ASTRecordLayout &Layout = getASTContext().getASTRecordLayout(RD);
  498. VBPtrOffset = Layout.getVBPtrOffset().getQuantity();
  499. }
  500. } else {
  501. mangleName(MD);
  502. mangleFunctionEncoding(MD, /*ShouldMangle=*/true);
  503. }
  504. if (VBTableOffset == 0 &&
  505. IM == MSInheritanceAttr::Keyword_virtual_inheritance)
  506. NVOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity();
  507. } else {
  508. // Null single inheritance member functions are encoded as a simple nullptr.
  509. if (IM == MSInheritanceAttr::Keyword_single_inheritance) {
  510. Out << "$0A@";
  511. return;
  512. }
  513. if (IM == MSInheritanceAttr::Keyword_unspecified_inheritance)
  514. VBTableOffset = -1;
  515. Out << '$' << Code;
  516. }
  517. if (MSInheritanceAttr::hasNVOffsetField(/*IsMemberFunction=*/true, IM))
  518. mangleNumber(static_cast<uint32_t>(NVOffset));
  519. if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
  520. mangleNumber(VBPtrOffset);
  521. if (MSInheritanceAttr::hasVBTableOffsetField(IM))
  522. mangleNumber(VBTableOffset);
  523. }
  524. void MicrosoftCXXNameMangler::mangleVirtualMemPtrThunk(
  525. const CXXMethodDecl *MD,
  526. const MicrosoftVTableContext::MethodVFTableLocation &ML) {
  527. // Get the vftable offset.
  528. CharUnits PointerWidth = getASTContext().toCharUnitsFromBits(
  529. getASTContext().getTargetInfo().getPointerWidth(0));
  530. uint64_t OffsetInVFTable = ML.Index * PointerWidth.getQuantity();
  531. Out << "?_9";
  532. mangleName(MD->getParent());
  533. Out << "$B";
  534. mangleNumber(OffsetInVFTable);
  535. Out << 'A';
  536. mangleCallingConvention(MD->getType()->getAs<FunctionProtoType>());
  537. }
  538. void MicrosoftCXXNameMangler::mangleName(const NamedDecl *ND) {
  539. // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
  540. // Always start with the unqualified name.
  541. mangleUnqualifiedName(ND);
  542. mangleNestedName(ND);
  543. // Terminate the whole name with an '@'.
  544. Out << '@';
  545. }
  546. void MicrosoftCXXNameMangler::mangleNumber(int64_t Number) {
  547. // <non-negative integer> ::= A@ # when Number == 0
  548. // ::= <decimal digit> # when 1 <= Number <= 10
  549. // ::= <hex digit>+ @ # when Number >= 10
  550. //
  551. // <number> ::= [?] <non-negative integer>
  552. uint64_t Value = static_cast<uint64_t>(Number);
  553. if (Number < 0) {
  554. Value = -Value;
  555. Out << '?';
  556. }
  557. if (Value == 0)
  558. Out << "A@";
  559. else if (Value >= 1 && Value <= 10)
  560. Out << (Value - 1);
  561. else {
  562. // Numbers that are not encoded as decimal digits are represented as nibbles
  563. // in the range of ASCII characters 'A' to 'P'.
  564. // The number 0x123450 would be encoded as 'BCDEFA'
  565. char EncodedNumberBuffer[sizeof(uint64_t) * 2];
  566. MutableArrayRef<char> BufferRef(EncodedNumberBuffer);
  567. MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
  568. for (; Value != 0; Value >>= 4)
  569. *I++ = 'A' + (Value & 0xf);
  570. Out.write(I.base(), I - BufferRef.rbegin());
  571. Out << '@';
  572. }
  573. }
  574. static const TemplateDecl *
  575. isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
  576. // Check if we have a function template.
  577. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  578. if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
  579. TemplateArgs = FD->getTemplateSpecializationArgs();
  580. return TD;
  581. }
  582. }
  583. // Check if we have a class template.
  584. if (const ClassTemplateSpecializationDecl *Spec =
  585. dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
  586. TemplateArgs = &Spec->getTemplateArgs();
  587. return Spec->getSpecializedTemplate();
  588. }
  589. // Check if we have a variable template.
  590. if (const VarTemplateSpecializationDecl *Spec =
  591. dyn_cast<VarTemplateSpecializationDecl>(ND)) {
  592. TemplateArgs = &Spec->getTemplateArgs();
  593. return Spec->getSpecializedTemplate();
  594. }
  595. return nullptr;
  596. }
  597. void MicrosoftCXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
  598. DeclarationName Name) {
  599. // <unqualified-name> ::= <operator-name>
  600. // ::= <ctor-dtor-name>
  601. // ::= <source-name>
  602. // ::= <template-name>
  603. // Check if we have a template.
  604. const TemplateArgumentList *TemplateArgs = nullptr;
  605. if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
  606. // Function templates aren't considered for name back referencing. This
  607. // makes sense since function templates aren't likely to occur multiple
  608. // times in a symbol.
  609. // FIXME: Test alias template mangling with MSVC 2013.
  610. if (!isa<ClassTemplateDecl>(TD)) {
  611. mangleTemplateInstantiationName(TD, *TemplateArgs);
  612. Out << '@';
  613. return;
  614. }
  615. // Here comes the tricky thing: if we need to mangle something like
  616. // void foo(A::X<Y>, B::X<Y>),
  617. // the X<Y> part is aliased. However, if you need to mangle
  618. // void foo(A::X<A::Y>, A::X<B::Y>),
  619. // the A::X<> part is not aliased.
  620. // That said, from the mangler's perspective we have a structure like this:
  621. // namespace[s] -> type[ -> template-parameters]
  622. // but from the Clang perspective we have
  623. // type [ -> template-parameters]
  624. // \-> namespace[s]
  625. // What we do is we create a new mangler, mangle the same type (without
  626. // a namespace suffix) to a string using the extra mangler and then use
  627. // the mangled type name as a key to check the mangling of different types
  628. // for aliasing.
  629. llvm::SmallString<64> TemplateMangling;
  630. llvm::raw_svector_ostream Stream(TemplateMangling);
  631. MicrosoftCXXNameMangler Extra(Context, Stream);
  632. Extra.mangleTemplateInstantiationName(TD, *TemplateArgs);
  633. Stream.flush();
  634. mangleSourceName(TemplateMangling);
  635. return;
  636. }
  637. switch (Name.getNameKind()) {
  638. case DeclarationName::Identifier: {
  639. if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
  640. mangleSourceName(II->getName());
  641. break;
  642. }
  643. // Otherwise, an anonymous entity. We must have a declaration.
  644. assert(ND && "mangling empty name without declaration");
  645. if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
  646. if (NS->isAnonymousNamespace()) {
  647. Out << "?A@";
  648. break;
  649. }
  650. }
  651. if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
  652. // We must have an anonymous union or struct declaration.
  653. const CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl();
  654. assert(RD && "expected variable decl to have a record type");
  655. // Anonymous types with no tag or typedef get the name of their
  656. // declarator mangled in. If they have no declarator, number them with
  657. // a $S prefix.
  658. llvm::SmallString<64> Name("$S");
  659. // Get a unique id for the anonymous struct.
  660. Name += llvm::utostr(Context.getAnonymousStructId(RD) + 1);
  661. mangleSourceName(Name.str());
  662. break;
  663. }
  664. // We must have an anonymous struct.
  665. const TagDecl *TD = cast<TagDecl>(ND);
  666. if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
  667. assert(TD->getDeclContext() == D->getDeclContext() &&
  668. "Typedef should not be in another decl context!");
  669. assert(D->getDeclName().getAsIdentifierInfo() &&
  670. "Typedef was not named!");
  671. mangleSourceName(D->getDeclName().getAsIdentifierInfo()->getName());
  672. break;
  673. }
  674. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
  675. if (Record->isLambda()) {
  676. llvm::SmallString<10> Name("<lambda_");
  677. unsigned LambdaId;
  678. if (Record->getLambdaManglingNumber())
  679. LambdaId = Record->getLambdaManglingNumber();
  680. else
  681. LambdaId = Context.getLambdaId(Record);
  682. Name += llvm::utostr(LambdaId);
  683. Name += ">";
  684. mangleSourceName(Name);
  685. break;
  686. }
  687. }
  688. llvm::SmallString<64> Name("<unnamed-type-");
  689. if (TD->hasDeclaratorForAnonDecl()) {
  690. // Anonymous types with no tag or typedef get the name of their
  691. // declarator mangled in if they have one.
  692. Name += TD->getDeclaratorForAnonDecl()->getName();
  693. } else {
  694. // Otherwise, number the types using a $S prefix.
  695. Name += "$S";
  696. Name += llvm::utostr(Context.getAnonymousStructId(TD));
  697. }
  698. Name += ">";
  699. mangleSourceName(Name.str());
  700. break;
  701. }
  702. case DeclarationName::ObjCZeroArgSelector:
  703. case DeclarationName::ObjCOneArgSelector:
  704. case DeclarationName::ObjCMultiArgSelector:
  705. llvm_unreachable("Can't mangle Objective-C selector names here!");
  706. case DeclarationName::CXXConstructorName:
  707. if (Structor == getStructor(ND)) {
  708. if (StructorType == Ctor_CopyingClosure) {
  709. Out << "?_O";
  710. return;
  711. }
  712. if (StructorType == Ctor_DefaultClosure) {
  713. Out << "?_F";
  714. return;
  715. }
  716. }
  717. Out << "?0";
  718. return;
  719. case DeclarationName::CXXDestructorName:
  720. if (ND == Structor)
  721. // If the named decl is the C++ destructor we're mangling,
  722. // use the type we were given.
  723. mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
  724. else
  725. // Otherwise, use the base destructor name. This is relevant if a
  726. // class with a destructor is declared within a destructor.
  727. mangleCXXDtorType(Dtor_Base);
  728. break;
  729. case DeclarationName::CXXConversionFunctionName:
  730. // <operator-name> ::= ?B # (cast)
  731. // The target type is encoded as the return type.
  732. Out << "?B";
  733. break;
  734. case DeclarationName::CXXOperatorName:
  735. mangleOperatorName(Name.getCXXOverloadedOperator(), ND->getLocation());
  736. break;
  737. case DeclarationName::CXXLiteralOperatorName: {
  738. Out << "?__K";
  739. mangleSourceName(Name.getCXXLiteralIdentifier()->getName());
  740. break;
  741. }
  742. case DeclarationName::CXXUsingDirective:
  743. llvm_unreachable("Can't mangle a using directive name!");
  744. }
  745. }
  746. void MicrosoftCXXNameMangler::mangleNestedName(const NamedDecl *ND) {
  747. // <postfix> ::= <unqualified-name> [<postfix>]
  748. // ::= <substitution> [<postfix>]
  749. const DeclContext *DC = getEffectiveDeclContext(ND);
  750. while (!DC->isTranslationUnit()) {
  751. if (isa<TagDecl>(ND) || isa<VarDecl>(ND)) {
  752. unsigned Disc;
  753. if (Context.getNextDiscriminator(ND, Disc)) {
  754. Out << '?';
  755. mangleNumber(Disc);
  756. Out << '?';
  757. }
  758. }
  759. if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
  760. DiagnosticsEngine &Diags = Context.getDiags();
  761. unsigned DiagID =
  762. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  763. "cannot mangle a local inside this block yet");
  764. Diags.Report(BD->getLocation(), DiagID);
  765. // FIXME: This is completely, utterly, wrong; see ItaniumMangle
  766. // for how this should be done.
  767. Out << "__block_invoke" << Context.getBlockId(BD, false);
  768. Out << '@';
  769. continue;
  770. } else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC)) {
  771. mangleObjCMethodName(Method);
  772. } else if (isa<NamedDecl>(DC)) {
  773. ND = cast<NamedDecl>(DC);
  774. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  775. mangle(FD, "?");
  776. break;
  777. } else
  778. mangleUnqualifiedName(ND);
  779. }
  780. DC = DC->getParent();
  781. }
  782. }
  783. void MicrosoftCXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
  784. // Microsoft uses the names on the case labels for these dtor variants. Clang
  785. // uses the Itanium terminology internally. Everything in this ABI delegates
  786. // towards the base dtor.
  787. switch (T) {
  788. // <operator-name> ::= ?1 # destructor
  789. case Dtor_Base: Out << "?1"; return;
  790. // <operator-name> ::= ?_D # vbase destructor
  791. case Dtor_Complete: Out << "?_D"; return;
  792. // <operator-name> ::= ?_G # scalar deleting destructor
  793. case Dtor_Deleting: Out << "?_G"; return;
  794. // <operator-name> ::= ?_E # vector deleting destructor
  795. // FIXME: Add a vector deleting dtor type. It goes in the vtable, so we need
  796. // it.
  797. case Dtor_Comdat:
  798. llvm_unreachable("not expecting a COMDAT");
  799. }
  800. llvm_unreachable("Unsupported dtor type?");
  801. }
  802. void MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO,
  803. SourceLocation Loc) {
  804. switch (OO) {
  805. // ?0 # constructor
  806. // ?1 # destructor
  807. // <operator-name> ::= ?2 # new
  808. case OO_New: Out << "?2"; break;
  809. // <operator-name> ::= ?3 # delete
  810. case OO_Delete: Out << "?3"; break;
  811. // <operator-name> ::= ?4 # =
  812. case OO_Equal: Out << "?4"; break;
  813. // <operator-name> ::= ?5 # >>
  814. case OO_GreaterGreater: Out << "?5"; break;
  815. // <operator-name> ::= ?6 # <<
  816. case OO_LessLess: Out << "?6"; break;
  817. // <operator-name> ::= ?7 # !
  818. case OO_Exclaim: Out << "?7"; break;
  819. // <operator-name> ::= ?8 # ==
  820. case OO_EqualEqual: Out << "?8"; break;
  821. // <operator-name> ::= ?9 # !=
  822. case OO_ExclaimEqual: Out << "?9"; break;
  823. // <operator-name> ::= ?A # []
  824. case OO_Subscript: Out << "?A"; break;
  825. // ?B # conversion
  826. // <operator-name> ::= ?C # ->
  827. case OO_Arrow: Out << "?C"; break;
  828. // <operator-name> ::= ?D # *
  829. case OO_Star: Out << "?D"; break;
  830. // <operator-name> ::= ?E # ++
  831. case OO_PlusPlus: Out << "?E"; break;
  832. // <operator-name> ::= ?F # --
  833. case OO_MinusMinus: Out << "?F"; break;
  834. // <operator-name> ::= ?G # -
  835. case OO_Minus: Out << "?G"; break;
  836. // <operator-name> ::= ?H # +
  837. case OO_Plus: Out << "?H"; break;
  838. // <operator-name> ::= ?I # &
  839. case OO_Amp: Out << "?I"; break;
  840. // <operator-name> ::= ?J # ->*
  841. case OO_ArrowStar: Out << "?J"; break;
  842. // <operator-name> ::= ?K # /
  843. case OO_Slash: Out << "?K"; break;
  844. // <operator-name> ::= ?L # %
  845. case OO_Percent: Out << "?L"; break;
  846. // <operator-name> ::= ?M # <
  847. case OO_Less: Out << "?M"; break;
  848. // <operator-name> ::= ?N # <=
  849. case OO_LessEqual: Out << "?N"; break;
  850. // <operator-name> ::= ?O # >
  851. case OO_Greater: Out << "?O"; break;
  852. // <operator-name> ::= ?P # >=
  853. case OO_GreaterEqual: Out << "?P"; break;
  854. // <operator-name> ::= ?Q # ,
  855. case OO_Comma: Out << "?Q"; break;
  856. // <operator-name> ::= ?R # ()
  857. case OO_Call: Out << "?R"; break;
  858. // <operator-name> ::= ?S # ~
  859. case OO_Tilde: Out << "?S"; break;
  860. // <operator-name> ::= ?T # ^
  861. case OO_Caret: Out << "?T"; break;
  862. // <operator-name> ::= ?U # |
  863. case OO_Pipe: Out << "?U"; break;
  864. // <operator-name> ::= ?V # &&
  865. case OO_AmpAmp: Out << "?V"; break;
  866. // <operator-name> ::= ?W # ||
  867. case OO_PipePipe: Out << "?W"; break;
  868. // <operator-name> ::= ?X # *=
  869. case OO_StarEqual: Out << "?X"; break;
  870. // <operator-name> ::= ?Y # +=
  871. case OO_PlusEqual: Out << "?Y"; break;
  872. // <operator-name> ::= ?Z # -=
  873. case OO_MinusEqual: Out << "?Z"; break;
  874. // <operator-name> ::= ?_0 # /=
  875. case OO_SlashEqual: Out << "?_0"; break;
  876. // <operator-name> ::= ?_1 # %=
  877. case OO_PercentEqual: Out << "?_1"; break;
  878. // <operator-name> ::= ?_2 # >>=
  879. case OO_GreaterGreaterEqual: Out << "?_2"; break;
  880. // <operator-name> ::= ?_3 # <<=
  881. case OO_LessLessEqual: Out << "?_3"; break;
  882. // <operator-name> ::= ?_4 # &=
  883. case OO_AmpEqual: Out << "?_4"; break;
  884. // <operator-name> ::= ?_5 # |=
  885. case OO_PipeEqual: Out << "?_5"; break;
  886. // <operator-name> ::= ?_6 # ^=
  887. case OO_CaretEqual: Out << "?_6"; break;
  888. // ?_7 # vftable
  889. // ?_8 # vbtable
  890. // ?_9 # vcall
  891. // ?_A # typeof
  892. // ?_B # local static guard
  893. // ?_C # string
  894. // ?_D # vbase destructor
  895. // ?_E # vector deleting destructor
  896. // ?_F # default constructor closure
  897. // ?_G # scalar deleting destructor
  898. // ?_H # vector constructor iterator
  899. // ?_I # vector destructor iterator
  900. // ?_J # vector vbase constructor iterator
  901. // ?_K # virtual displacement map
  902. // ?_L # eh vector constructor iterator
  903. // ?_M # eh vector destructor iterator
  904. // ?_N # eh vector vbase constructor iterator
  905. // ?_O # copy constructor closure
  906. // ?_P<name> # udt returning <name>
  907. // ?_Q # <unknown>
  908. // ?_R0 # RTTI Type Descriptor
  909. // ?_R1 # RTTI Base Class Descriptor at (a,b,c,d)
  910. // ?_R2 # RTTI Base Class Array
  911. // ?_R3 # RTTI Class Hierarchy Descriptor
  912. // ?_R4 # RTTI Complete Object Locator
  913. // ?_S # local vftable
  914. // ?_T # local vftable constructor closure
  915. // <operator-name> ::= ?_U # new[]
  916. case OO_Array_New: Out << "?_U"; break;
  917. // <operator-name> ::= ?_V # delete[]
  918. case OO_Array_Delete: Out << "?_V"; break;
  919. case OO_Conditional: {
  920. DiagnosticsEngine &Diags = Context.getDiags();
  921. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  922. "cannot mangle this conditional operator yet");
  923. Diags.Report(Loc, DiagID);
  924. break;
  925. }
  926. case OO_None:
  927. case NUM_OVERLOADED_OPERATORS:
  928. llvm_unreachable("Not an overloaded operator");
  929. }
  930. }
  931. void MicrosoftCXXNameMangler::mangleSourceName(StringRef Name) {
  932. // <source name> ::= <identifier> @
  933. BackRefVec::iterator Found =
  934. std::find(NameBackReferences.begin(), NameBackReferences.end(), Name);
  935. if (Found == NameBackReferences.end()) {
  936. if (NameBackReferences.size() < 10)
  937. NameBackReferences.push_back(Name);
  938. Out << Name << '@';
  939. } else {
  940. Out << (Found - NameBackReferences.begin());
  941. }
  942. }
  943. void MicrosoftCXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
  944. Context.mangleObjCMethodName(MD, Out);
  945. }
  946. void MicrosoftCXXNameMangler::mangleTemplateInstantiationName(
  947. const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
  948. // <template-name> ::= <unscoped-template-name> <template-args>
  949. // ::= <substitution>
  950. // Always start with the unqualified name.
  951. // Templates have their own context for back references.
  952. ArgBackRefMap OuterArgsContext;
  953. BackRefVec OuterTemplateContext;
  954. NameBackReferences.swap(OuterTemplateContext);
  955. TypeBackReferences.swap(OuterArgsContext);
  956. mangleUnscopedTemplateName(TD);
  957. mangleTemplateArgs(TD, TemplateArgs);
  958. // Restore the previous back reference contexts.
  959. NameBackReferences.swap(OuterTemplateContext);
  960. TypeBackReferences.swap(OuterArgsContext);
  961. }
  962. void
  963. MicrosoftCXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *TD) {
  964. // <unscoped-template-name> ::= ?$ <unqualified-name>
  965. Out << "?$";
  966. mangleUnqualifiedName(TD);
  967. }
  968. void MicrosoftCXXNameMangler::mangleIntegerLiteral(const llvm::APSInt &Value,
  969. bool IsBoolean) {
  970. // <integer-literal> ::= $0 <number>
  971. Out << "$0";
  972. // Make sure booleans are encoded as 0/1.
  973. if (IsBoolean && Value.getBoolValue())
  974. mangleNumber(1);
  975. else if (Value.isSigned())
  976. mangleNumber(Value.getSExtValue());
  977. else
  978. mangleNumber(Value.getZExtValue());
  979. }
  980. void MicrosoftCXXNameMangler::mangleExpression(const Expr *E) {
  981. // See if this is a constant expression.
  982. llvm::APSInt Value;
  983. if (E->isIntegerConstantExpr(Value, Context.getASTContext())) {
  984. mangleIntegerLiteral(Value, E->getType()->isBooleanType());
  985. return;
  986. }
  987. // Look through no-op casts like template parameter substitutions.
  988. E = E->IgnoreParenNoopCasts(Context.getASTContext());
  989. const CXXUuidofExpr *UE = nullptr;
  990. if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  991. if (UO->getOpcode() == UO_AddrOf)
  992. UE = dyn_cast<CXXUuidofExpr>(UO->getSubExpr());
  993. } else
  994. UE = dyn_cast<CXXUuidofExpr>(E);
  995. if (UE) {
  996. // This CXXUuidofExpr is mangled as-if it were actually a VarDecl from
  997. // const __s_GUID _GUID_{lower case UUID with underscores}
  998. StringRef Uuid = UE->getUuidAsStringRef(Context.getASTContext());
  999. std::string Name = "_GUID_" + Uuid.lower();
  1000. std::replace(Name.begin(), Name.end(), '-', '_');
  1001. // If we had to peek through an address-of operator, treat this like we are
  1002. // dealing with a pointer type. Otherwise, treat it like a const reference.
  1003. //
  1004. // N.B. This matches up with the handling of TemplateArgument::Declaration
  1005. // in mangleTemplateArg
  1006. if (UE == E)
  1007. Out << "$E?";
  1008. else
  1009. Out << "$1?";
  1010. Out << Name << "@@3U__s_GUID@@B";
  1011. return;
  1012. }
  1013. // As bad as this diagnostic is, it's better than crashing.
  1014. DiagnosticsEngine &Diags = Context.getDiags();
  1015. unsigned DiagID = Diags.getCustomDiagID(
  1016. DiagnosticsEngine::Error, "cannot yet mangle expression type %0");
  1017. Diags.Report(E->getExprLoc(), DiagID) << E->getStmtClassName()
  1018. << E->getSourceRange();
  1019. }
  1020. void MicrosoftCXXNameMangler::mangleTemplateArgs(
  1021. const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
  1022. // <template-args> ::= <template-arg>+
  1023. const TemplateParameterList *TPL = TD->getTemplateParameters();
  1024. assert(TPL->size() == TemplateArgs.size() &&
  1025. "size mismatch between args and parms!");
  1026. unsigned Idx = 0;
  1027. for (const TemplateArgument &TA : TemplateArgs.asArray())
  1028. mangleTemplateArg(TD, TA, TPL->getParam(Idx++));
  1029. }
  1030. void MicrosoftCXXNameMangler::mangleTemplateArg(const TemplateDecl *TD,
  1031. const TemplateArgument &TA,
  1032. const NamedDecl *Parm) {
  1033. // <template-arg> ::= <type>
  1034. // ::= <integer-literal>
  1035. // ::= <member-data-pointer>
  1036. // ::= <member-function-pointer>
  1037. // ::= $E? <name> <type-encoding>
  1038. // ::= $1? <name> <type-encoding>
  1039. // ::= $0A@
  1040. // ::= <template-args>
  1041. switch (TA.getKind()) {
  1042. case TemplateArgument::Null:
  1043. llvm_unreachable("Can't mangle null template arguments!");
  1044. case TemplateArgument::TemplateExpansion:
  1045. llvm_unreachable("Can't mangle template expansion arguments!");
  1046. case TemplateArgument::Type: {
  1047. QualType T = TA.getAsType();
  1048. mangleType(T, SourceRange(), QMM_Escape);
  1049. break;
  1050. }
  1051. case TemplateArgument::Declaration: {
  1052. const NamedDecl *ND = cast<NamedDecl>(TA.getAsDecl());
  1053. if (isa<FieldDecl>(ND) || isa<IndirectFieldDecl>(ND)) {
  1054. mangleMemberDataPointer(
  1055. cast<CXXRecordDecl>(ND->getDeclContext())->getMostRecentDecl(),
  1056. cast<ValueDecl>(ND));
  1057. } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  1058. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  1059. if (MD && MD->isInstance()) {
  1060. mangleMemberFunctionPointer(MD->getParent()->getMostRecentDecl(), MD);
  1061. } else {
  1062. Out << "$1?";
  1063. mangleName(FD);
  1064. mangleFunctionEncoding(FD, /*ShouldMangle=*/true);
  1065. }
  1066. } else {
  1067. mangle(ND, TA.getParamTypeForDecl()->isReferenceType() ? "$E?" : "$1?");
  1068. }
  1069. break;
  1070. }
  1071. case TemplateArgument::Integral:
  1072. mangleIntegerLiteral(TA.getAsIntegral(),
  1073. TA.getIntegralType()->isBooleanType());
  1074. break;
  1075. case TemplateArgument::NullPtr: {
  1076. QualType T = TA.getNullPtrType();
  1077. if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) {
  1078. const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
  1079. if (MPT->isMemberFunctionPointerType() && isa<ClassTemplateDecl>(TD)) {
  1080. mangleMemberFunctionPointer(RD, nullptr);
  1081. return;
  1082. }
  1083. if (MPT->isMemberDataPointer()) {
  1084. if (isa<ClassTemplateDecl>(TD)) {
  1085. mangleMemberDataPointer(RD, nullptr);
  1086. return;
  1087. }
  1088. // nullptr data pointers are always represented with a single field
  1089. // which is initialized with either 0 or -1. Why -1? Well, we need to
  1090. // distinguish the case where the data member is at offset zero in the
  1091. // record.
  1092. // However, we are free to use 0 *if* we would use multiple fields for
  1093. // non-nullptr member pointers.
  1094. if (!RD->nullFieldOffsetIsZero()) {
  1095. mangleIntegerLiteral(llvm::APSInt::get(-1), /*IsBoolean=*/false);
  1096. return;
  1097. }
  1098. }
  1099. }
  1100. mangleIntegerLiteral(llvm::APSInt::getUnsigned(0), /*IsBoolean=*/false);
  1101. break;
  1102. }
  1103. case TemplateArgument::Expression:
  1104. mangleExpression(TA.getAsExpr());
  1105. break;
  1106. case TemplateArgument::Pack: {
  1107. ArrayRef<TemplateArgument> TemplateArgs = TA.getPackAsArray();
  1108. if (TemplateArgs.empty()) {
  1109. if (isa<TemplateTypeParmDecl>(Parm) ||
  1110. isa<TemplateTemplateParmDecl>(Parm))
  1111. // MSVC 2015 changed the mangling for empty expanded template packs,
  1112. // use the old mangling for link compatibility for old versions.
  1113. Out << (Context.getASTContext().getLangOpts().isCompatibleWithMSVC(
  1114. LangOptions::MSVC2015)
  1115. ? "$$V"
  1116. : "$$$V");
  1117. else if (isa<NonTypeTemplateParmDecl>(Parm))
  1118. Out << "$S";
  1119. else
  1120. llvm_unreachable("unexpected template parameter decl!");
  1121. } else {
  1122. for (const TemplateArgument &PA : TemplateArgs)
  1123. mangleTemplateArg(TD, PA, Parm);
  1124. }
  1125. break;
  1126. }
  1127. case TemplateArgument::Template: {
  1128. const NamedDecl *ND =
  1129. TA.getAsTemplate().getAsTemplateDecl()->getTemplatedDecl();
  1130. if (const auto *TD = dyn_cast<TagDecl>(ND)) {
  1131. mangleType(TD);
  1132. } else if (isa<TypeAliasDecl>(ND)) {
  1133. Out << "$$Y";
  1134. mangleName(ND);
  1135. } else {
  1136. llvm_unreachable("unexpected template template NamedDecl!");
  1137. }
  1138. break;
  1139. }
  1140. }
  1141. }
  1142. void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals,
  1143. bool IsMember) {
  1144. // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers>
  1145. // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only);
  1146. // 'I' means __restrict (32/64-bit).
  1147. // Note that the MSVC __restrict keyword isn't the same as the C99 restrict
  1148. // keyword!
  1149. // <base-cvr-qualifiers> ::= A # near
  1150. // ::= B # near const
  1151. // ::= C # near volatile
  1152. // ::= D # near const volatile
  1153. // ::= E # far (16-bit)
  1154. // ::= F # far const (16-bit)
  1155. // ::= G # far volatile (16-bit)
  1156. // ::= H # far const volatile (16-bit)
  1157. // ::= I # huge (16-bit)
  1158. // ::= J # huge const (16-bit)
  1159. // ::= K # huge volatile (16-bit)
  1160. // ::= L # huge const volatile (16-bit)
  1161. // ::= M <basis> # based
  1162. // ::= N <basis> # based const
  1163. // ::= O <basis> # based volatile
  1164. // ::= P <basis> # based const volatile
  1165. // ::= Q # near member
  1166. // ::= R # near const member
  1167. // ::= S # near volatile member
  1168. // ::= T # near const volatile member
  1169. // ::= U # far member (16-bit)
  1170. // ::= V # far const member (16-bit)
  1171. // ::= W # far volatile member (16-bit)
  1172. // ::= X # far const volatile member (16-bit)
  1173. // ::= Y # huge member (16-bit)
  1174. // ::= Z # huge const member (16-bit)
  1175. // ::= 0 # huge volatile member (16-bit)
  1176. // ::= 1 # huge const volatile member (16-bit)
  1177. // ::= 2 <basis> # based member
  1178. // ::= 3 <basis> # based const member
  1179. // ::= 4 <basis> # based volatile member
  1180. // ::= 5 <basis> # based const volatile member
  1181. // ::= 6 # near function (pointers only)
  1182. // ::= 7 # far function (pointers only)
  1183. // ::= 8 # near method (pointers only)
  1184. // ::= 9 # far method (pointers only)
  1185. // ::= _A <basis> # based function (pointers only)
  1186. // ::= _B <basis> # based function (far?) (pointers only)
  1187. // ::= _C <basis> # based method (pointers only)
  1188. // ::= _D <basis> # based method (far?) (pointers only)
  1189. // ::= _E # block (Clang)
  1190. // <basis> ::= 0 # __based(void)
  1191. // ::= 1 # __based(segment)?
  1192. // ::= 2 <name> # __based(name)
  1193. // ::= 3 # ?
  1194. // ::= 4 # ?
  1195. // ::= 5 # not really based
  1196. bool HasConst = Quals.hasConst(),
  1197. HasVolatile = Quals.hasVolatile();
  1198. if (!IsMember) {
  1199. if (HasConst && HasVolatile) {
  1200. Out << 'D';
  1201. } else if (HasVolatile) {
  1202. Out << 'C';
  1203. } else if (HasConst) {
  1204. Out << 'B';
  1205. } else {
  1206. Out << 'A';
  1207. }
  1208. } else {
  1209. if (HasConst && HasVolatile) {
  1210. Out << 'T';
  1211. } else if (HasVolatile) {
  1212. Out << 'S';
  1213. } else if (HasConst) {
  1214. Out << 'R';
  1215. } else {
  1216. Out << 'Q';
  1217. }
  1218. }
  1219. // FIXME: For now, just drop all extension qualifiers on the floor.
  1220. }
  1221. void
  1222. MicrosoftCXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
  1223. // <ref-qualifier> ::= G # lvalue reference
  1224. // ::= H # rvalue-reference
  1225. switch (RefQualifier) {
  1226. case RQ_None:
  1227. break;
  1228. case RQ_LValue:
  1229. Out << 'G';
  1230. break;
  1231. case RQ_RValue:
  1232. Out << 'H';
  1233. break;
  1234. }
  1235. }
  1236. void MicrosoftCXXNameMangler::manglePointerExtQualifiers(Qualifiers Quals,
  1237. QualType PointeeType) {
  1238. bool HasRestrict = Quals.hasRestrict();
  1239. if (PointersAre64Bit &&
  1240. (PointeeType.isNull() || !PointeeType->isFunctionType()))
  1241. Out << 'E';
  1242. if (HasRestrict)
  1243. Out << 'I';
  1244. }
  1245. void MicrosoftCXXNameMangler::manglePointerCVQualifiers(Qualifiers Quals) {
  1246. // <pointer-cv-qualifiers> ::= P # no qualifiers
  1247. // ::= Q # const
  1248. // ::= R # volatile
  1249. // ::= S # const volatile
  1250. bool HasConst = Quals.hasConst(),
  1251. HasVolatile = Quals.hasVolatile();
  1252. if (HasConst && HasVolatile) {
  1253. Out << 'S';
  1254. } else if (HasVolatile) {
  1255. Out << 'R';
  1256. } else if (HasConst) {
  1257. Out << 'Q';
  1258. } else {
  1259. Out << 'P';
  1260. }
  1261. }
  1262. void MicrosoftCXXNameMangler::mangleArgumentType(QualType T,
  1263. SourceRange Range) {
  1264. // MSVC will backreference two canonically equivalent types that have slightly
  1265. // different manglings when mangled alone.
  1266. // Decayed types do not match up with non-decayed versions of the same type.
  1267. //
  1268. // e.g.
  1269. // void (*x)(void) will not form a backreference with void x(void)
  1270. void *TypePtr;
  1271. if (const auto *DT = T->getAs<DecayedType>()) {
  1272. QualType OriginalType = DT->getOriginalType();
  1273. // All decayed ArrayTypes should be treated identically; as-if they were
  1274. // a decayed IncompleteArrayType.
  1275. if (const auto *AT = getASTContext().getAsArrayType(OriginalType))
  1276. OriginalType = getASTContext().getIncompleteArrayType(
  1277. AT->getElementType(), AT->getSizeModifier(),
  1278. AT->getIndexTypeCVRQualifiers());
  1279. TypePtr = OriginalType.getCanonicalType().getAsOpaquePtr();
  1280. // If the original parameter was textually written as an array,
  1281. // instead treat the decayed parameter like it's const.
  1282. //
  1283. // e.g.
  1284. // int [] -> int * const
  1285. if (OriginalType->isArrayType())
  1286. T = T.withConst();
  1287. } else {
  1288. TypePtr = T.getCanonicalType().getAsOpaquePtr();
  1289. }
  1290. ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
  1291. if (Found == TypeBackReferences.end()) {
  1292. size_t OutSizeBefore = Out.tell();
  1293. mangleType(T, Range, QMM_Drop);
  1294. // See if it's worth creating a back reference.
  1295. // Only types longer than 1 character are considered
  1296. // and only 10 back references slots are available:
  1297. bool LongerThanOneChar = (Out.tell() - OutSizeBefore > 1);
  1298. if (LongerThanOneChar && TypeBackReferences.size() < 10) {
  1299. size_t Size = TypeBackReferences.size();
  1300. TypeBackReferences[TypePtr] = Size;
  1301. }
  1302. } else {
  1303. Out << Found->second;
  1304. }
  1305. }
  1306. void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
  1307. QualifierMangleMode QMM) {
  1308. // Don't use the canonical types. MSVC includes things like 'const' on
  1309. // pointer arguments to function pointers that canonicalization strips away.
  1310. T = T.getDesugaredType(getASTContext());
  1311. Qualifiers Quals = T.getLocalQualifiers();
  1312. if (const ArrayType *AT = getASTContext().getAsArrayType(T)) {
  1313. // If there were any Quals, getAsArrayType() pushed them onto the array
  1314. // element type.
  1315. if (QMM == QMM_Mangle)
  1316. Out << 'A';
  1317. else if (QMM == QMM_Escape || QMM == QMM_Result)
  1318. Out << "$$B";
  1319. mangleArrayType(AT);
  1320. return;
  1321. }
  1322. bool IsPointer = T->isAnyPointerType() || T->isMemberPointerType() ||
  1323. T->isReferenceType() || T->isBlockPointerType();
  1324. switch (QMM) {
  1325. case QMM_Drop:
  1326. break;
  1327. case QMM_Mangle:
  1328. if (const FunctionType *FT = dyn_cast<FunctionType>(T)) {
  1329. Out << '6';
  1330. mangleFunctionType(FT);
  1331. return;
  1332. }
  1333. mangleQualifiers(Quals, false);
  1334. break;
  1335. case QMM_Escape:
  1336. if (!IsPointer && Quals) {
  1337. Out << "$$C";
  1338. mangleQualifiers(Quals, false);
  1339. }
  1340. break;
  1341. case QMM_Result:
  1342. if ((!IsPointer && Quals) || isa<TagType>(T)) {
  1343. Out << '?';
  1344. mangleQualifiers(Quals, false);
  1345. }
  1346. break;
  1347. }
  1348. const Type *ty = T.getTypePtr();
  1349. switch (ty->getTypeClass()) {
  1350. #define ABSTRACT_TYPE(CLASS, PARENT)
  1351. #define NON_CANONICAL_TYPE(CLASS, PARENT) \
  1352. case Type::CLASS: \
  1353. llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
  1354. return;
  1355. #define TYPE(CLASS, PARENT) \
  1356. case Type::CLASS: \
  1357. mangleType(cast<CLASS##Type>(ty), Quals, Range); \
  1358. break;
  1359. #include "clang/AST/TypeNodes.def"
  1360. #undef ABSTRACT_TYPE
  1361. #undef NON_CANONICAL_TYPE
  1362. #undef TYPE
  1363. }
  1364. }
  1365. void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T, Qualifiers,
  1366. SourceRange Range) {
  1367. // <type> ::= <builtin-type>
  1368. // <builtin-type> ::= X # void
  1369. // ::= C # signed char
  1370. // ::= D # char
  1371. // ::= E # unsigned char
  1372. // ::= F # short
  1373. // ::= G # unsigned short (or wchar_t if it's not a builtin)
  1374. // ::= H # int
  1375. // ::= I # unsigned int
  1376. // ::= J # long
  1377. // ::= K # unsigned long
  1378. // L # <none>
  1379. // ::= M # float
  1380. // ::= N # double
  1381. // ::= O # long double (__float80 is mangled differently)
  1382. // ::= _J # long long, __int64
  1383. // ::= _K # unsigned long long, __int64
  1384. // ::= _L # __int128
  1385. // ::= _M # unsigned __int128
  1386. // ::= _N # bool
  1387. // _O # <array in parameter>
  1388. // ::= _T # __float80 (Intel)
  1389. // ::= _W # wchar_t
  1390. // ::= _Z # __float80 (Digital Mars)
  1391. switch (T->getKind()) {
  1392. case BuiltinType::Void: Out << 'X'; break;
  1393. case BuiltinType::SChar: Out << 'C'; break;
  1394. case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'D'; break;
  1395. case BuiltinType::UChar: Out << 'E'; break;
  1396. case BuiltinType::Short: Out << 'F'; break;
  1397. case BuiltinType::UShort: Out << 'G'; break;
  1398. case BuiltinType::Int: Out << 'H'; break;
  1399. case BuiltinType::UInt: Out << 'I'; break;
  1400. case BuiltinType::Long: Out << 'J'; break;
  1401. case BuiltinType::ULong: Out << 'K'; break;
  1402. case BuiltinType::Float: Out << 'M'; break;
  1403. case BuiltinType::LitFloat: // HLSL Change
  1404. case BuiltinType::Double: Out << 'N'; break;
  1405. // TODO: Determine size and mangle accordingly
  1406. case BuiltinType::LongDouble: Out << 'O'; break;
  1407. case BuiltinType::LitInt: // HLSL Change
  1408. case BuiltinType::LongLong: Out << "_J"; break;
  1409. case BuiltinType::ULongLong: Out << "_K"; break;
  1410. case BuiltinType::Int128: Out << "_L"; break;
  1411. case BuiltinType::UInt128: Out << "_M"; break;
  1412. case BuiltinType::Bool: Out << "_N"; break;
  1413. case BuiltinType::Char16: Out << "_S"; break;
  1414. case BuiltinType::Char32: Out << "_U"; break;
  1415. case BuiltinType::WChar_S:
  1416. case BuiltinType::WChar_U: Out << "_W"; break;
  1417. #define BUILTIN_TYPE(Id, SingletonId)
  1418. #define PLACEHOLDER_TYPE(Id, SingletonId) \
  1419. case BuiltinType::Id:
  1420. #include "clang/AST/BuiltinTypes.def"
  1421. case BuiltinType::Dependent:
  1422. llvm_unreachable("placeholder types shouldn't get to name mangling");
  1423. case BuiltinType::ObjCId: Out << "PAUobjc_object@@"; break;
  1424. case BuiltinType::ObjCClass: Out << "PAUobjc_class@@"; break;
  1425. case BuiltinType::ObjCSel: Out << "PAUobjc_selector@@"; break;
  1426. case BuiltinType::OCLImage1d: Out << "PAUocl_image1d@@"; break;
  1427. case BuiltinType::OCLImage1dArray: Out << "PAUocl_image1darray@@"; break;
  1428. case BuiltinType::OCLImage1dBuffer: Out << "PAUocl_image1dbuffer@@"; break;
  1429. case BuiltinType::OCLImage2d: Out << "PAUocl_image2d@@"; break;
  1430. case BuiltinType::OCLImage2dArray: Out << "PAUocl_image2darray@@"; break;
  1431. case BuiltinType::OCLImage3d: Out << "PAUocl_image3d@@"; break;
  1432. case BuiltinType::OCLSampler: Out << "PAUocl_sampler@@"; break;
  1433. case BuiltinType::OCLEvent: Out << "PAUocl_event@@"; break;
  1434. case BuiltinType::NullPtr: Out << "$$T"; break;
  1435. // HLSL Change Starts
  1436. case BuiltinType::Min10Float:
  1437. Out << "$min10f@";
  1438. break;
  1439. case BuiltinType::Min12Int:
  1440. Out << "$min12i@";
  1441. break;
  1442. case BuiltinType::Half:
  1443. Out << "$f16@";
  1444. break;
  1445. // HLSL Change Ends
  1446. }
  1447. }
  1448. // <type> ::= <function-type>
  1449. void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T, Qualifiers,
  1450. SourceRange) {
  1451. // Structors only appear in decls, so at this point we know it's not a
  1452. // structor type.
  1453. // FIXME: This may not be lambda-friendly.
  1454. if (T->getTypeQuals() || T->getRefQualifier() != RQ_None) {
  1455. Out << "$$A8@@";
  1456. mangleFunctionType(T, /*D=*/nullptr, /*ForceThisQuals=*/true);
  1457. } else {
  1458. Out << "$$A6";
  1459. mangleFunctionType(T);
  1460. }
  1461. }
  1462. void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
  1463. Qualifiers, SourceRange) {
  1464. llvm_unreachable("Can't mangle K&R function prototypes");
  1465. }
  1466. void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T,
  1467. const FunctionDecl *D,
  1468. bool ForceThisQuals) {
  1469. // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
  1470. // <return-type> <argument-list> <throw-spec>
  1471. const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
  1472. SourceRange Range;
  1473. if (D) Range = D->getSourceRange();
  1474. bool IsStructor = false, HasThisQuals = ForceThisQuals, IsCtorClosure = false;
  1475. CallingConv CC = T->getCallConv();
  1476. if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(D)) {
  1477. if (MD->isInstance())
  1478. HasThisQuals = true;
  1479. if (isa<CXXDestructorDecl>(MD)) {
  1480. IsStructor = true;
  1481. } else if (isa<CXXConstructorDecl>(MD)) {
  1482. IsStructor = true;
  1483. IsCtorClosure = (StructorType == Ctor_CopyingClosure ||
  1484. StructorType == Ctor_DefaultClosure) &&
  1485. getStructor(MD) == Structor;
  1486. if (IsCtorClosure)
  1487. CC = getASTContext().getDefaultCallingConvention(
  1488. /*IsVariadic=*/false, /*IsCXXMethod=*/true);
  1489. }
  1490. }
  1491. // If this is a C++ instance method, mangle the CVR qualifiers for the
  1492. // this pointer.
  1493. if (HasThisQuals) {
  1494. Qualifiers Quals = Qualifiers::fromCVRMask(Proto->getTypeQuals());
  1495. manglePointerExtQualifiers(Quals, /*PointeeType=*/QualType());
  1496. mangleRefQualifier(Proto->getRefQualifier());
  1497. mangleQualifiers(Quals, /*IsMember=*/false);
  1498. }
  1499. mangleCallingConvention(CC);
  1500. // <return-type> ::= <type>
  1501. // ::= @ # structors (they have no declared return type)
  1502. if (IsStructor) {
  1503. if (isa<CXXDestructorDecl>(D) && D == Structor &&
  1504. StructorType == Dtor_Deleting) {
  1505. // The scalar deleting destructor takes an extra int argument.
  1506. // However, the FunctionType generated has 0 arguments.
  1507. // FIXME: This is a temporary hack.
  1508. // Maybe should fix the FunctionType creation instead?
  1509. Out << (PointersAre64Bit ? "PEAXI@Z" : "PAXI@Z");
  1510. return;
  1511. }
  1512. if (IsCtorClosure) {
  1513. // Default constructor closure and copy constructor closure both return
  1514. // void.
  1515. Out << 'X';
  1516. if (StructorType == Ctor_DefaultClosure) {
  1517. // Default constructor closure always has no arguments.
  1518. Out << 'X';
  1519. } else if (StructorType == Ctor_CopyingClosure) {
  1520. // Copy constructor closure always takes an unqualified reference.
  1521. mangleArgumentType(getASTContext().getLValueReferenceType(
  1522. Proto->getParamType(0)
  1523. ->getAs<LValueReferenceType>()
  1524. ->getPointeeType(),
  1525. /*SpelledAsLValue=*/true),
  1526. Range);
  1527. Out << '@';
  1528. } else {
  1529. llvm_unreachable("unexpected constructor closure!");
  1530. }
  1531. Out << 'Z';
  1532. return;
  1533. }
  1534. Out << '@';
  1535. } else {
  1536. QualType ResultType = Proto->getReturnType();
  1537. if (const auto *AT =
  1538. dyn_cast_or_null<AutoType>(ResultType->getContainedAutoType())) {
  1539. Out << '?';
  1540. mangleQualifiers(ResultType.getLocalQualifiers(), /*IsMember=*/false);
  1541. Out << '?';
  1542. mangleSourceName(AT->isDecltypeAuto() ? "<decltype-auto>" : "<auto>");
  1543. Out << '@';
  1544. } else {
  1545. if (ResultType->isVoidType())
  1546. ResultType = ResultType.getUnqualifiedType();
  1547. mangleType(ResultType, Range, QMM_Result);
  1548. }
  1549. }
  1550. // <argument-list> ::= X # void
  1551. // ::= <type>+ @
  1552. // ::= <type>* Z # varargs
  1553. if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
  1554. Out << 'X';
  1555. } else {
  1556. // Happens for function pointer type arguments for example.
  1557. for (const QualType &Arg : Proto->param_types())
  1558. mangleArgumentType(Arg, Range);
  1559. // <builtin-type> ::= Z # ellipsis
  1560. if (Proto->isVariadic())
  1561. Out << 'Z';
  1562. else
  1563. Out << '@';
  1564. }
  1565. mangleThrowSpecification(Proto);
  1566. }
  1567. void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
  1568. // <function-class> ::= <member-function> E? # E designates a 64-bit 'this'
  1569. // # pointer. in 64-bit mode *all*
  1570. // # 'this' pointers are 64-bit.
  1571. // ::= <global-function>
  1572. // <member-function> ::= A # private: near
  1573. // ::= B # private: far
  1574. // ::= C # private: static near
  1575. // ::= D # private: static far
  1576. // ::= E # private: virtual near
  1577. // ::= F # private: virtual far
  1578. // ::= I # protected: near
  1579. // ::= J # protected: far
  1580. // ::= K # protected: static near
  1581. // ::= L # protected: static far
  1582. // ::= M # protected: virtual near
  1583. // ::= N # protected: virtual far
  1584. // ::= Q # public: near
  1585. // ::= R # public: far
  1586. // ::= S # public: static near
  1587. // ::= T # public: static far
  1588. // ::= U # public: virtual near
  1589. // ::= V # public: virtual far
  1590. // <global-function> ::= Y # global near
  1591. // ::= Z # global far
  1592. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  1593. switch (MD->getAccess()) {
  1594. case AS_none:
  1595. llvm_unreachable("Unsupported access specifier");
  1596. case AS_private:
  1597. if (MD->isStatic())
  1598. Out << 'C';
  1599. else if (MD->isVirtual())
  1600. Out << 'E';
  1601. else
  1602. Out << 'A';
  1603. break;
  1604. case AS_protected:
  1605. if (MD->isStatic())
  1606. Out << 'K';
  1607. else if (MD->isVirtual())
  1608. Out << 'M';
  1609. else
  1610. Out << 'I';
  1611. break;
  1612. case AS_public:
  1613. if (MD->isStatic())
  1614. Out << 'S';
  1615. else if (MD->isVirtual())
  1616. Out << 'U';
  1617. else
  1618. Out << 'Q';
  1619. }
  1620. } else {
  1621. Out << 'Y';
  1622. }
  1623. }
  1624. void MicrosoftCXXNameMangler::mangleCallingConvention(CallingConv CC) {
  1625. // <calling-convention> ::= A # __cdecl
  1626. // ::= B # __export __cdecl
  1627. // ::= C # __pascal
  1628. // ::= D # __export __pascal
  1629. // ::= E # __thiscall
  1630. // ::= F # __export __thiscall
  1631. // ::= G # __stdcall
  1632. // ::= H # __export __stdcall
  1633. // ::= I # __fastcall
  1634. // ::= J # __export __fastcall
  1635. // ::= Q # __vectorcall
  1636. // The 'export' calling conventions are from a bygone era
  1637. // (*cough*Win16*cough*) when functions were declared for export with
  1638. // that keyword. (It didn't actually export them, it just made them so
  1639. // that they could be in a DLL and somebody from another module could call
  1640. // them.)
  1641. switch (CC) {
  1642. default:
  1643. llvm_unreachable("Unsupported CC for mangling");
  1644. case CC_X86_64Win64:
  1645. case CC_X86_64SysV:
  1646. case CC_C: Out << 'A'; break;
  1647. case CC_X86Pascal: Out << 'C'; break;
  1648. case CC_X86ThisCall: Out << 'E'; break;
  1649. case CC_X86StdCall: Out << 'G'; break;
  1650. case CC_X86FastCall: Out << 'I'; break;
  1651. case CC_X86VectorCall: Out << 'Q'; break;
  1652. }
  1653. }
  1654. void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T) {
  1655. mangleCallingConvention(T->getCallConv());
  1656. }
  1657. void MicrosoftCXXNameMangler::mangleThrowSpecification(
  1658. const FunctionProtoType *FT) {
  1659. // <throw-spec> ::= Z # throw(...) (default)
  1660. // ::= @ # throw() or __declspec/__attribute__((nothrow))
  1661. // ::= <type>+
  1662. // NOTE: Since the Microsoft compiler ignores throw specifications, they are
  1663. // all actually mangled as 'Z'. (They're ignored because their associated
  1664. // functionality isn't implemented, and probably never will be.)
  1665. Out << 'Z';
  1666. }
  1667. void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
  1668. Qualifiers, SourceRange Range) {
  1669. // Probably should be mangled as a template instantiation; need to see what
  1670. // VC does first.
  1671. DiagnosticsEngine &Diags = Context.getDiags();
  1672. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1673. "cannot mangle this unresolved dependent type yet");
  1674. Diags.Report(Range.getBegin(), DiagID)
  1675. << Range;
  1676. }
  1677. // <type> ::= <union-type> | <struct-type> | <class-type> | <enum-type>
  1678. // <union-type> ::= T <name>
  1679. // <struct-type> ::= U <name>
  1680. // <class-type> ::= V <name>
  1681. // <enum-type> ::= W4 <name>
  1682. void MicrosoftCXXNameMangler::mangleType(const EnumType *T, Qualifiers,
  1683. SourceRange) {
  1684. mangleType(cast<TagType>(T)->getDecl());
  1685. }
  1686. void MicrosoftCXXNameMangler::mangleType(const RecordType *T, Qualifiers,
  1687. SourceRange) {
  1688. mangleType(cast<TagType>(T)->getDecl());
  1689. }
  1690. void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) {
  1691. switch (TD->getTagKind()) {
  1692. case TTK_Union:
  1693. Out << 'T';
  1694. break;
  1695. case TTK_Struct:
  1696. case TTK_Interface:
  1697. Out << 'U';
  1698. break;
  1699. case TTK_Class:
  1700. Out << 'V';
  1701. break;
  1702. case TTK_Enum:
  1703. Out << "W4";
  1704. break;
  1705. }
  1706. mangleName(TD);
  1707. }
  1708. // <type> ::= <array-type>
  1709. // <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
  1710. // [Y <dimension-count> <dimension>+]
  1711. // <element-type> # as global, E is never required
  1712. // It's supposed to be the other way around, but for some strange reason, it
  1713. // isn't. Today this behavior is retained for the sole purpose of backwards
  1714. // compatibility.
  1715. void MicrosoftCXXNameMangler::mangleDecayedArrayType(const ArrayType *T) {
  1716. // This isn't a recursive mangling, so now we have to do it all in this
  1717. // one call.
  1718. manglePointerCVQualifiers(T->getElementType().getQualifiers());
  1719. mangleType(T->getElementType(), SourceRange());
  1720. }
  1721. void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T, Qualifiers,
  1722. SourceRange) {
  1723. llvm_unreachable("Should have been special cased");
  1724. }
  1725. void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T, Qualifiers,
  1726. SourceRange) {
  1727. llvm_unreachable("Should have been special cased");
  1728. }
  1729. void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
  1730. Qualifiers, SourceRange) {
  1731. llvm_unreachable("Should have been special cased");
  1732. }
  1733. void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
  1734. Qualifiers, SourceRange) {
  1735. llvm_unreachable("Should have been special cased");
  1736. }
  1737. void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) {
  1738. QualType ElementTy(T, 0);
  1739. SmallVector<llvm::APInt, 3> Dimensions;
  1740. for (;;) {
  1741. if (ElementTy->isConstantArrayType()) {
  1742. const ConstantArrayType *CAT =
  1743. getASTContext().getAsConstantArrayType(ElementTy);
  1744. Dimensions.push_back(CAT->getSize());
  1745. ElementTy = CAT->getElementType();
  1746. } else if (ElementTy->isIncompleteArrayType()) {
  1747. const IncompleteArrayType *IAT =
  1748. getASTContext().getAsIncompleteArrayType(ElementTy);
  1749. Dimensions.push_back(llvm::APInt(32, 0));
  1750. ElementTy = IAT->getElementType();
  1751. } else if (ElementTy->isVariableArrayType()) {
  1752. const VariableArrayType *VAT =
  1753. getASTContext().getAsVariableArrayType(ElementTy);
  1754. Dimensions.push_back(llvm::APInt(32, 0));
  1755. ElementTy = VAT->getElementType();
  1756. } else if (ElementTy->isDependentSizedArrayType()) {
  1757. // The dependent expression has to be folded into a constant (TODO).
  1758. const DependentSizedArrayType *DSAT =
  1759. getASTContext().getAsDependentSizedArrayType(ElementTy);
  1760. DiagnosticsEngine &Diags = Context.getDiags();
  1761. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1762. "cannot mangle this dependent-length array yet");
  1763. Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
  1764. << DSAT->getBracketsRange();
  1765. return;
  1766. } else {
  1767. break;
  1768. }
  1769. }
  1770. Out << 'Y';
  1771. // <dimension-count> ::= <number> # number of extra dimensions
  1772. mangleNumber(Dimensions.size());
  1773. for (const llvm::APInt &Dimension : Dimensions)
  1774. mangleNumber(Dimension.getLimitedValue());
  1775. mangleType(ElementTy, SourceRange(), QMM_Escape);
  1776. }
  1777. // <type> ::= <pointer-to-member-type>
  1778. // <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
  1779. // <class name> <type>
  1780. void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T, Qualifiers Quals,
  1781. SourceRange Range) {
  1782. QualType PointeeType = T->getPointeeType();
  1783. manglePointerCVQualifiers(Quals);
  1784. manglePointerExtQualifiers(Quals, PointeeType);
  1785. if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
  1786. Out << '8';
  1787. mangleName(T->getClass()->castAs<RecordType>()->getDecl());
  1788. mangleFunctionType(FPT, nullptr, true);
  1789. } else {
  1790. mangleQualifiers(PointeeType.getQualifiers(), true);
  1791. mangleName(T->getClass()->castAs<RecordType>()->getDecl());
  1792. mangleType(PointeeType, Range, QMM_Drop);
  1793. }
  1794. }
  1795. void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
  1796. Qualifiers, SourceRange Range) {
  1797. DiagnosticsEngine &Diags = Context.getDiags();
  1798. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1799. "cannot mangle this template type parameter type yet");
  1800. Diags.Report(Range.getBegin(), DiagID)
  1801. << Range;
  1802. }
  1803. void MicrosoftCXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T,
  1804. Qualifiers, SourceRange Range) {
  1805. DiagnosticsEngine &Diags = Context.getDiags();
  1806. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1807. "cannot mangle this substituted parameter pack yet");
  1808. Diags.Report(Range.getBegin(), DiagID)
  1809. << Range;
  1810. }
  1811. // <type> ::= <pointer-type>
  1812. // <pointer-type> ::= E? <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
  1813. // # the E is required for 64-bit non-static pointers
  1814. void MicrosoftCXXNameMangler::mangleType(const PointerType *T, Qualifiers Quals,
  1815. SourceRange Range) {
  1816. QualType PointeeType = T->getPointeeType();
  1817. manglePointerCVQualifiers(Quals);
  1818. manglePointerExtQualifiers(Quals, PointeeType);
  1819. mangleType(PointeeType, Range);
  1820. }
  1821. void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
  1822. Qualifiers Quals, SourceRange Range) {
  1823. QualType PointeeType = T->getPointeeType();
  1824. manglePointerCVQualifiers(Quals);
  1825. manglePointerExtQualifiers(Quals, PointeeType);
  1826. // Object pointers never have qualifiers.
  1827. Out << 'A';
  1828. mangleType(PointeeType, Range);
  1829. }
  1830. // <type> ::= <reference-type>
  1831. // <reference-type> ::= A E? <cvr-qualifiers> <type>
  1832. // # the E is required for 64-bit non-static lvalue references
  1833. void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
  1834. Qualifiers Quals, SourceRange Range) {
  1835. QualType PointeeType = T->getPointeeType();
  1836. Out << (Quals.hasVolatile() ? 'B' : 'A');
  1837. manglePointerExtQualifiers(Quals, PointeeType);
  1838. mangleType(PointeeType, Range);
  1839. }
  1840. // <type> ::= <r-value-reference-type>
  1841. // <r-value-reference-type> ::= $$Q E? <cvr-qualifiers> <type>
  1842. // # the E is required for 64-bit non-static rvalue references
  1843. void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
  1844. Qualifiers Quals, SourceRange Range) {
  1845. QualType PointeeType = T->getPointeeType();
  1846. Out << (Quals.hasVolatile() ? "$$R" : "$$Q");
  1847. manglePointerExtQualifiers(Quals, PointeeType);
  1848. mangleType(PointeeType, Range);
  1849. }
  1850. void MicrosoftCXXNameMangler::mangleType(const ComplexType *T, Qualifiers,
  1851. SourceRange Range) {
  1852. DiagnosticsEngine &Diags = Context.getDiags();
  1853. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1854. "cannot mangle this complex number type yet");
  1855. Diags.Report(Range.getBegin(), DiagID)
  1856. << Range;
  1857. }
  1858. void MicrosoftCXXNameMangler::mangleType(const VectorType *T, Qualifiers Quals,
  1859. SourceRange Range) {
  1860. const BuiltinType *ET = T->getElementType()->getAs<BuiltinType>();
  1861. assert(ET && "vectors with non-builtin elements are unsupported");
  1862. uint64_t Width = getASTContext().getTypeSize(T);
  1863. // Pattern match exactly the typedefs in our intrinsic headers. Anything that
  1864. // doesn't match the Intel types uses a custom mangling below.
  1865. bool IsBuiltin = true;
  1866. llvm::Triple::ArchType AT =
  1867. getASTContext().getTargetInfo().getTriple().getArch();
  1868. if (AT == llvm::Triple::x86 || AT == llvm::Triple::x86_64) {
  1869. if (Width == 64 && ET->getKind() == BuiltinType::LongLong) {
  1870. Out << "T__m64";
  1871. } else if (Width >= 128) {
  1872. if (ET->getKind() == BuiltinType::Float)
  1873. Out << "T__m" << Width;
  1874. else if (ET->getKind() == BuiltinType::LongLong)
  1875. Out << "T__m" << Width << 'i';
  1876. else if (ET->getKind() == BuiltinType::Double)
  1877. Out << "U__m" << Width << 'd';
  1878. else
  1879. IsBuiltin = false;
  1880. } else {
  1881. IsBuiltin = false;
  1882. }
  1883. } else {
  1884. IsBuiltin = false;
  1885. }
  1886. if (!IsBuiltin) {
  1887. // The MS ABI doesn't have a special mangling for vector types, so we define
  1888. // our own mangling to handle uses of __vector_size__ on user-specified
  1889. // types, and for extensions like __v4sf.
  1890. Out << "T__clang_vec" << T->getNumElements() << '_';
  1891. mangleType(ET, Quals, Range);
  1892. }
  1893. Out << "@@";
  1894. }
  1895. void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T, Qualifiers,
  1896. SourceRange Range) {
  1897. DiagnosticsEngine &Diags = Context.getDiags();
  1898. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1899. "cannot mangle this extended vector type yet");
  1900. Diags.Report(Range.getBegin(), DiagID)
  1901. << Range;
  1902. }
  1903. void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T,
  1904. Qualifiers, SourceRange Range) {
  1905. DiagnosticsEngine &Diags = Context.getDiags();
  1906. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1907. "cannot mangle this dependent-sized extended vector type yet");
  1908. Diags.Report(Range.getBegin(), DiagID)
  1909. << Range;
  1910. }
  1911. void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T, Qualifiers,
  1912. SourceRange) {
  1913. // ObjC interfaces have structs underlying them.
  1914. Out << 'U';
  1915. mangleName(T->getDecl());
  1916. }
  1917. void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T, Qualifiers,
  1918. SourceRange Range) {
  1919. // We don't allow overloading by different protocol qualification,
  1920. // so mangling them isn't necessary.
  1921. mangleType(T->getBaseType(), Range);
  1922. }
  1923. void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
  1924. Qualifiers Quals, SourceRange Range) {
  1925. QualType PointeeType = T->getPointeeType();
  1926. manglePointerCVQualifiers(Quals);
  1927. manglePointerExtQualifiers(Quals, PointeeType);
  1928. Out << "_E";
  1929. mangleFunctionType(PointeeType->castAs<FunctionProtoType>());
  1930. }
  1931. void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *,
  1932. Qualifiers, SourceRange) {
  1933. llvm_unreachable("Cannot mangle injected class name type.");
  1934. }
  1935. void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T,
  1936. Qualifiers, SourceRange Range) {
  1937. DiagnosticsEngine &Diags = Context.getDiags();
  1938. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1939. "cannot mangle this template specialization type yet");
  1940. Diags.Report(Range.getBegin(), DiagID)
  1941. << Range;
  1942. }
  1943. void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T, Qualifiers,
  1944. SourceRange Range) {
  1945. DiagnosticsEngine &Diags = Context.getDiags();
  1946. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1947. "cannot mangle this dependent name type yet");
  1948. Diags.Report(Range.getBegin(), DiagID)
  1949. << Range;
  1950. }
  1951. void MicrosoftCXXNameMangler::mangleType(
  1952. const DependentTemplateSpecializationType *T, Qualifiers,
  1953. SourceRange Range) {
  1954. DiagnosticsEngine &Diags = Context.getDiags();
  1955. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1956. "cannot mangle this dependent template specialization type yet");
  1957. Diags.Report(Range.getBegin(), DiagID)
  1958. << Range;
  1959. }
  1960. void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T, Qualifiers,
  1961. SourceRange Range) {
  1962. DiagnosticsEngine &Diags = Context.getDiags();
  1963. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1964. "cannot mangle this pack expansion yet");
  1965. Diags.Report(Range.getBegin(), DiagID)
  1966. << Range;
  1967. }
  1968. void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T, Qualifiers,
  1969. SourceRange Range) {
  1970. DiagnosticsEngine &Diags = Context.getDiags();
  1971. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1972. "cannot mangle this typeof(type) yet");
  1973. Diags.Report(Range.getBegin(), DiagID)
  1974. << Range;
  1975. }
  1976. void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T, Qualifiers,
  1977. SourceRange Range) {
  1978. DiagnosticsEngine &Diags = Context.getDiags();
  1979. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1980. "cannot mangle this typeof(expression) yet");
  1981. Diags.Report(Range.getBegin(), DiagID)
  1982. << Range;
  1983. }
  1984. void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T, Qualifiers,
  1985. SourceRange Range) {
  1986. DiagnosticsEngine &Diags = Context.getDiags();
  1987. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1988. "cannot mangle this decltype() yet");
  1989. Diags.Report(Range.getBegin(), DiagID)
  1990. << Range;
  1991. }
  1992. void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T,
  1993. Qualifiers, SourceRange Range) {
  1994. DiagnosticsEngine &Diags = Context.getDiags();
  1995. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1996. "cannot mangle this unary transform type yet");
  1997. Diags.Report(Range.getBegin(), DiagID)
  1998. << Range;
  1999. }
  2000. void MicrosoftCXXNameMangler::mangleType(const AutoType *T, Qualifiers,
  2001. SourceRange Range) {
  2002. assert(T->getDeducedType().isNull() && "expecting a dependent type!");
  2003. DiagnosticsEngine &Diags = Context.getDiags();
  2004. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2005. "cannot mangle this 'auto' type yet");
  2006. Diags.Report(Range.getBegin(), DiagID)
  2007. << Range;
  2008. }
  2009. void MicrosoftCXXNameMangler::mangleType(const AtomicType *T, Qualifiers,
  2010. SourceRange Range) {
  2011. DiagnosticsEngine &Diags = Context.getDiags();
  2012. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2013. "cannot mangle this C11 atomic type yet");
  2014. Diags.Report(Range.getBegin(), DiagID)
  2015. << Range;
  2016. }
  2017. void MicrosoftMangleContextImpl::mangleCXXName(const NamedDecl *D,
  2018. raw_ostream &Out) {
  2019. assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
  2020. "Invalid mangleName() call, argument is not a variable or function!");
  2021. assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
  2022. "Invalid mangleName() call on 'structor decl!");
  2023. PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
  2024. getASTContext().getSourceManager(),
  2025. "Mangling declaration");
  2026. MicrosoftCXXNameMangler Mangler(*this, Out);
  2027. return Mangler.mangle(D);
  2028. }
  2029. // <this-adjustment> ::= <no-adjustment> | <static-adjustment> |
  2030. // <virtual-adjustment>
  2031. // <no-adjustment> ::= A # private near
  2032. // ::= B # private far
  2033. // ::= I # protected near
  2034. // ::= J # protected far
  2035. // ::= Q # public near
  2036. // ::= R # public far
  2037. // <static-adjustment> ::= G <static-offset> # private near
  2038. // ::= H <static-offset> # private far
  2039. // ::= O <static-offset> # protected near
  2040. // ::= P <static-offset> # protected far
  2041. // ::= W <static-offset> # public near
  2042. // ::= X <static-offset> # public far
  2043. // <virtual-adjustment> ::= $0 <virtual-shift> <static-offset> # private near
  2044. // ::= $1 <virtual-shift> <static-offset> # private far
  2045. // ::= $2 <virtual-shift> <static-offset> # protected near
  2046. // ::= $3 <virtual-shift> <static-offset> # protected far
  2047. // ::= $4 <virtual-shift> <static-offset> # public near
  2048. // ::= $5 <virtual-shift> <static-offset> # public far
  2049. // <virtual-shift> ::= <vtordisp-shift> | <vtordispex-shift>
  2050. // <vtordisp-shift> ::= <offset-to-vtordisp>
  2051. // <vtordispex-shift> ::= <offset-to-vbptr> <vbase-offset-offset>
  2052. // <offset-to-vtordisp>
  2053. static void mangleThunkThisAdjustment(const CXXMethodDecl *MD,
  2054. const ThisAdjustment &Adjustment,
  2055. MicrosoftCXXNameMangler &Mangler,
  2056. raw_ostream &Out) {
  2057. if (!Adjustment.Virtual.isEmpty()) {
  2058. Out << '$';
  2059. char AccessSpec;
  2060. switch (MD->getAccess()) {
  2061. case AS_none:
  2062. llvm_unreachable("Unsupported access specifier");
  2063. case AS_private:
  2064. AccessSpec = '0';
  2065. break;
  2066. case AS_protected:
  2067. AccessSpec = '2';
  2068. break;
  2069. case AS_public:
  2070. AccessSpec = '4';
  2071. }
  2072. if (Adjustment.Virtual.Microsoft.VBPtrOffset) {
  2073. Out << 'R' << AccessSpec;
  2074. Mangler.mangleNumber(
  2075. static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBPtrOffset));
  2076. Mangler.mangleNumber(
  2077. static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBOffsetOffset));
  2078. Mangler.mangleNumber(
  2079. static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
  2080. Mangler.mangleNumber(static_cast<uint32_t>(Adjustment.NonVirtual));
  2081. } else {
  2082. Out << AccessSpec;
  2083. Mangler.mangleNumber(
  2084. static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
  2085. Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
  2086. }
  2087. } else if (Adjustment.NonVirtual != 0) {
  2088. switch (MD->getAccess()) {
  2089. case AS_none:
  2090. llvm_unreachable("Unsupported access specifier");
  2091. case AS_private:
  2092. Out << 'G';
  2093. break;
  2094. case AS_protected:
  2095. Out << 'O';
  2096. break;
  2097. case AS_public:
  2098. Out << 'W';
  2099. }
  2100. Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
  2101. } else {
  2102. switch (MD->getAccess()) {
  2103. case AS_none:
  2104. llvm_unreachable("Unsupported access specifier");
  2105. case AS_private:
  2106. Out << 'A';
  2107. break;
  2108. case AS_protected:
  2109. Out << 'I';
  2110. break;
  2111. case AS_public:
  2112. Out << 'Q';
  2113. }
  2114. }
  2115. }
  2116. void
  2117. MicrosoftMangleContextImpl::mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
  2118. raw_ostream &Out) {
  2119. MicrosoftVTableContext *VTContext =
  2120. cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
  2121. const MicrosoftVTableContext::MethodVFTableLocation &ML =
  2122. VTContext->getMethodVFTableLocation(GlobalDecl(MD));
  2123. MicrosoftCXXNameMangler Mangler(*this, Out);
  2124. Mangler.getStream() << "\01?";
  2125. Mangler.mangleVirtualMemPtrThunk(MD, ML);
  2126. }
  2127. void MicrosoftMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
  2128. const ThunkInfo &Thunk,
  2129. raw_ostream &Out) {
  2130. MicrosoftCXXNameMangler Mangler(*this, Out);
  2131. Out << "\01?";
  2132. Mangler.mangleName(MD);
  2133. mangleThunkThisAdjustment(MD, Thunk.This, Mangler, Out);
  2134. if (!Thunk.Return.isEmpty())
  2135. assert(Thunk.Method != nullptr &&
  2136. "Thunk info should hold the overridee decl");
  2137. const CXXMethodDecl *DeclForFPT = Thunk.Method ? Thunk.Method : MD;
  2138. Mangler.mangleFunctionType(
  2139. DeclForFPT->getType()->castAs<FunctionProtoType>(), MD);
  2140. }
  2141. void MicrosoftMangleContextImpl::mangleCXXDtorThunk(
  2142. const CXXDestructorDecl *DD, CXXDtorType Type,
  2143. const ThisAdjustment &Adjustment, raw_ostream &Out) {
  2144. // FIXME: Actually, the dtor thunk should be emitted for vector deleting
  2145. // dtors rather than scalar deleting dtors. Just use the vector deleting dtor
  2146. // mangling manually until we support both deleting dtor types.
  2147. assert(Type == Dtor_Deleting);
  2148. MicrosoftCXXNameMangler Mangler(*this, Out, DD, Type);
  2149. Out << "\01??_E";
  2150. Mangler.mangleName(DD->getParent());
  2151. mangleThunkThisAdjustment(DD, Adjustment, Mangler, Out);
  2152. Mangler.mangleFunctionType(DD->getType()->castAs<FunctionProtoType>(), DD);
  2153. }
  2154. void MicrosoftMangleContextImpl::mangleCXXVFTable(
  2155. const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
  2156. raw_ostream &Out) {
  2157. // <mangled-name> ::= ?_7 <class-name> <storage-class>
  2158. // <cvr-qualifiers> [<name>] @
  2159. // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
  2160. // is always '6' for vftables.
  2161. MicrosoftCXXNameMangler Mangler(*this, Out);
  2162. Mangler.getStream() << "\01??_7";
  2163. Mangler.mangleName(Derived);
  2164. Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
  2165. for (const CXXRecordDecl *RD : BasePath)
  2166. Mangler.mangleName(RD);
  2167. Mangler.getStream() << '@';
  2168. }
  2169. void MicrosoftMangleContextImpl::mangleCXXVBTable(
  2170. const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
  2171. raw_ostream &Out) {
  2172. // <mangled-name> ::= ?_8 <class-name> <storage-class>
  2173. // <cvr-qualifiers> [<name>] @
  2174. // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
  2175. // is always '7' for vbtables.
  2176. MicrosoftCXXNameMangler Mangler(*this, Out);
  2177. Mangler.getStream() << "\01??_8";
  2178. Mangler.mangleName(Derived);
  2179. Mangler.getStream() << "7B"; // '7' for vbtable, 'B' for const.
  2180. for (const CXXRecordDecl *RD : BasePath)
  2181. Mangler.mangleName(RD);
  2182. Mangler.getStream() << '@';
  2183. }
  2184. void MicrosoftMangleContextImpl::mangleCXXRTTI(QualType T, raw_ostream &Out) {
  2185. MicrosoftCXXNameMangler Mangler(*this, Out);
  2186. Mangler.getStream() << "\01??_R0";
  2187. Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
  2188. Mangler.getStream() << "@8";
  2189. }
  2190. void MicrosoftMangleContextImpl::mangleCXXRTTIName(QualType T,
  2191. raw_ostream &Out) {
  2192. MicrosoftCXXNameMangler Mangler(*this, Out);
  2193. Mangler.getStream() << '.';
  2194. Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
  2195. }
  2196. void MicrosoftMangleContextImpl::mangleCXXCatchHandlerType(QualType T,
  2197. uint32_t Flags,
  2198. raw_ostream &Out) {
  2199. MicrosoftCXXNameMangler Mangler(*this, Out);
  2200. Mangler.getStream() << "llvm.eh.handlertype.";
  2201. Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
  2202. Mangler.getStream() << '.' << Flags;
  2203. }
  2204. void MicrosoftMangleContextImpl::mangleCXXVirtualDisplacementMap(
  2205. const CXXRecordDecl *SrcRD, const CXXRecordDecl *DstRD, raw_ostream &Out) {
  2206. MicrosoftCXXNameMangler Mangler(*this, Out);
  2207. Mangler.getStream() << "\01??_K";
  2208. Mangler.mangleName(SrcRD);
  2209. Mangler.getStream() << "$C";
  2210. Mangler.mangleName(DstRD);
  2211. }
  2212. void MicrosoftMangleContextImpl::mangleCXXThrowInfo(QualType T,
  2213. bool IsConst,
  2214. bool IsVolatile,
  2215. uint32_t NumEntries,
  2216. raw_ostream &Out) {
  2217. MicrosoftCXXNameMangler Mangler(*this, Out);
  2218. Mangler.getStream() << "_TI";
  2219. if (IsConst)
  2220. Mangler.getStream() << 'C';
  2221. if (IsVolatile)
  2222. Mangler.getStream() << 'V';
  2223. Mangler.getStream() << NumEntries;
  2224. Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
  2225. }
  2226. void MicrosoftMangleContextImpl::mangleCXXCatchableTypeArray(
  2227. QualType T, uint32_t NumEntries, raw_ostream &Out) {
  2228. MicrosoftCXXNameMangler Mangler(*this, Out);
  2229. Mangler.getStream() << "_CTA";
  2230. Mangler.getStream() << NumEntries;
  2231. Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
  2232. }
  2233. void MicrosoftMangleContextImpl::mangleCXXCatchableType(
  2234. QualType T, const CXXConstructorDecl *CD, CXXCtorType CT, uint32_t Size,
  2235. uint32_t NVOffset, int32_t VBPtrOffset, uint32_t VBIndex,
  2236. raw_ostream &Out) {
  2237. MicrosoftCXXNameMangler Mangler(*this, Out);
  2238. Mangler.getStream() << "_CT";
  2239. llvm::SmallString<64> RTTIMangling;
  2240. {
  2241. llvm::raw_svector_ostream Stream(RTTIMangling);
  2242. mangleCXXRTTI(T, Stream);
  2243. }
  2244. Mangler.getStream() << RTTIMangling.substr(1);
  2245. // VS2015 CTP6 omits the copy-constructor in the mangled name. This name is,
  2246. // in fact, superfluous but I'm not sure the change was made consciously.
  2247. // TODO: Revisit this when VS2015 gets released.
  2248. llvm::SmallString<64> CopyCtorMangling;
  2249. if (CD) {
  2250. llvm::raw_svector_ostream Stream(CopyCtorMangling);
  2251. mangleCXXCtor(CD, CT, Stream);
  2252. }
  2253. Mangler.getStream() << CopyCtorMangling.substr(1);
  2254. Mangler.getStream() << Size;
  2255. if (VBPtrOffset == -1) {
  2256. if (NVOffset) {
  2257. Mangler.getStream() << NVOffset;
  2258. }
  2259. } else {
  2260. Mangler.getStream() << NVOffset;
  2261. Mangler.getStream() << VBPtrOffset;
  2262. Mangler.getStream() << VBIndex;
  2263. }
  2264. }
  2265. void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassDescriptor(
  2266. const CXXRecordDecl *Derived, uint32_t NVOffset, int32_t VBPtrOffset,
  2267. uint32_t VBTableOffset, uint32_t Flags, raw_ostream &Out) {
  2268. MicrosoftCXXNameMangler Mangler(*this, Out);
  2269. Mangler.getStream() << "\01??_R1";
  2270. Mangler.mangleNumber(NVOffset);
  2271. Mangler.mangleNumber(VBPtrOffset);
  2272. Mangler.mangleNumber(VBTableOffset);
  2273. Mangler.mangleNumber(Flags);
  2274. Mangler.mangleName(Derived);
  2275. Mangler.getStream() << "8";
  2276. }
  2277. void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassArray(
  2278. const CXXRecordDecl *Derived, raw_ostream &Out) {
  2279. MicrosoftCXXNameMangler Mangler(*this, Out);
  2280. Mangler.getStream() << "\01??_R2";
  2281. Mangler.mangleName(Derived);
  2282. Mangler.getStream() << "8";
  2283. }
  2284. void MicrosoftMangleContextImpl::mangleCXXRTTIClassHierarchyDescriptor(
  2285. const CXXRecordDecl *Derived, raw_ostream &Out) {
  2286. MicrosoftCXXNameMangler Mangler(*this, Out);
  2287. Mangler.getStream() << "\01??_R3";
  2288. Mangler.mangleName(Derived);
  2289. Mangler.getStream() << "8";
  2290. }
  2291. void MicrosoftMangleContextImpl::mangleCXXRTTICompleteObjectLocator(
  2292. const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
  2293. raw_ostream &Out) {
  2294. // <mangled-name> ::= ?_R4 <class-name> <storage-class>
  2295. // <cvr-qualifiers> [<name>] @
  2296. // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
  2297. // is always '6' for vftables.
  2298. MicrosoftCXXNameMangler Mangler(*this, Out);
  2299. Mangler.getStream() << "\01??_R4";
  2300. Mangler.mangleName(Derived);
  2301. Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
  2302. for (const CXXRecordDecl *RD : BasePath)
  2303. Mangler.mangleName(RD);
  2304. Mangler.getStream() << '@';
  2305. }
  2306. void MicrosoftMangleContextImpl::mangleSEHFilterExpression(
  2307. const NamedDecl *EnclosingDecl, raw_ostream &Out) {
  2308. MicrosoftCXXNameMangler Mangler(*this, Out);
  2309. // The function body is in the same comdat as the function with the handler,
  2310. // so the numbering here doesn't have to be the same across TUs.
  2311. //
  2312. // <mangled-name> ::= ?filt$ <filter-number> @0
  2313. Mangler.getStream() << "\01?filt$" << SEHFilterIds[EnclosingDecl]++ << "@0@";
  2314. Mangler.mangleName(EnclosingDecl);
  2315. }
  2316. void MicrosoftMangleContextImpl::mangleSEHFinallyBlock(
  2317. const NamedDecl *EnclosingDecl, raw_ostream &Out) {
  2318. MicrosoftCXXNameMangler Mangler(*this, Out);
  2319. // The function body is in the same comdat as the function with the handler,
  2320. // so the numbering here doesn't have to be the same across TUs.
  2321. //
  2322. // <mangled-name> ::= ?fin$ <filter-number> @0
  2323. Mangler.getStream() << "\01?fin$" << SEHFinallyIds[EnclosingDecl]++ << "@0@";
  2324. Mangler.mangleName(EnclosingDecl);
  2325. }
  2326. void MicrosoftMangleContextImpl::mangleTypeName(QualType T, raw_ostream &Out) {
  2327. // This is just a made up unique string for the purposes of tbaa. undname
  2328. // does *not* know how to demangle it.
  2329. MicrosoftCXXNameMangler Mangler(*this, Out);
  2330. Mangler.getStream() << '?';
  2331. Mangler.mangleType(T, SourceRange());
  2332. }
  2333. void MicrosoftMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
  2334. CXXCtorType Type,
  2335. raw_ostream &Out) {
  2336. MicrosoftCXXNameMangler mangler(*this, Out, D, Type);
  2337. mangler.mangle(D);
  2338. }
  2339. void MicrosoftMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
  2340. CXXDtorType Type,
  2341. raw_ostream &Out) {
  2342. MicrosoftCXXNameMangler mangler(*this, Out, D, Type);
  2343. mangler.mangle(D);
  2344. }
  2345. void MicrosoftMangleContextImpl::mangleReferenceTemporary(const VarDecl *VD,
  2346. unsigned,
  2347. raw_ostream &) {
  2348. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  2349. "cannot mangle this reference temporary yet");
  2350. getDiags().Report(VD->getLocation(), DiagID);
  2351. }
  2352. void MicrosoftMangleContextImpl::mangleThreadSafeStaticGuardVariable(
  2353. const VarDecl *VD, unsigned GuardNum, raw_ostream &Out) {
  2354. MicrosoftCXXNameMangler Mangler(*this, Out);
  2355. Mangler.getStream() << "\01?$TSS" << GuardNum << '@';
  2356. Mangler.mangleNestedName(VD);
  2357. }
  2358. void MicrosoftMangleContextImpl::mangleStaticGuardVariable(const VarDecl *VD,
  2359. raw_ostream &Out) {
  2360. // <guard-name> ::= ?_B <postfix> @5 <scope-depth>
  2361. // ::= ?__J <postfix> @5 <scope-depth>
  2362. // ::= ?$S <guard-num> @ <postfix> @4IA
  2363. // The first mangling is what MSVC uses to guard static locals in inline
  2364. // functions. It uses a different mangling in external functions to support
  2365. // guarding more than 32 variables. MSVC rejects inline functions with more
  2366. // than 32 static locals. We don't fully implement the second mangling
  2367. // because those guards are not externally visible, and instead use LLVM's
  2368. // default renaming when creating a new guard variable.
  2369. MicrosoftCXXNameMangler Mangler(*this, Out);
  2370. bool Visible = VD->isExternallyVisible();
  2371. if (Visible) {
  2372. Mangler.getStream() << (VD->getTLSKind() ? "\01??__J" : "\01??_B");
  2373. } else {
  2374. Mangler.getStream() << "\01?$S1@";
  2375. }
  2376. unsigned ScopeDepth = 0;
  2377. if (Visible && !getNextDiscriminator(VD, ScopeDepth))
  2378. // If we do not have a discriminator and are emitting a guard variable for
  2379. // use at global scope, then mangling the nested name will not be enough to
  2380. // remove ambiguities.
  2381. Mangler.mangle(VD, "");
  2382. else
  2383. Mangler.mangleNestedName(VD);
  2384. Mangler.getStream() << (Visible ? "@5" : "@4IA");
  2385. if (ScopeDepth)
  2386. Mangler.mangleNumber(ScopeDepth);
  2387. }
  2388. void MicrosoftMangleContextImpl::mangleInitFiniStub(const VarDecl *D,
  2389. raw_ostream &Out,
  2390. char CharCode) {
  2391. MicrosoftCXXNameMangler Mangler(*this, Out);
  2392. Mangler.getStream() << "\01??__" << CharCode;
  2393. Mangler.mangleName(D);
  2394. if (D->isStaticDataMember()) {
  2395. Mangler.mangleVariableEncoding(D);
  2396. Mangler.getStream() << '@';
  2397. }
  2398. // This is the function class mangling. These stubs are global, non-variadic,
  2399. // cdecl functions that return void and take no args.
  2400. Mangler.getStream() << "YAXXZ";
  2401. }
  2402. void MicrosoftMangleContextImpl::mangleDynamicInitializer(const VarDecl *D,
  2403. raw_ostream &Out) {
  2404. // <initializer-name> ::= ?__E <name> YAXXZ
  2405. mangleInitFiniStub(D, Out, 'E');
  2406. }
  2407. void
  2408. MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
  2409. raw_ostream &Out) {
  2410. // <destructor-name> ::= ?__F <name> YAXXZ
  2411. mangleInitFiniStub(D, Out, 'F');
  2412. }
  2413. void MicrosoftMangleContextImpl::mangleStringLiteral(const StringLiteral *SL,
  2414. raw_ostream &Out) {
  2415. // <char-type> ::= 0 # char
  2416. // ::= 1 # wchar_t
  2417. // ::= ??? # char16_t/char32_t will need a mangling too...
  2418. //
  2419. // <literal-length> ::= <non-negative integer> # the length of the literal
  2420. //
  2421. // <encoded-crc> ::= <hex digit>+ @ # crc of the literal including
  2422. // # null-terminator
  2423. //
  2424. // <encoded-string> ::= <simple character> # uninteresting character
  2425. // ::= '?$' <hex digit> <hex digit> # these two nibbles
  2426. // # encode the byte for the
  2427. // # character
  2428. // ::= '?' [a-z] # \xe1 - \xfa
  2429. // ::= '?' [A-Z] # \xc1 - \xda
  2430. // ::= '?' [0-9] # [,/\:. \n\t'-]
  2431. //
  2432. // <literal> ::= '??_C@_' <char-type> <literal-length> <encoded-crc>
  2433. // <encoded-string> '@'
  2434. MicrosoftCXXNameMangler Mangler(*this, Out);
  2435. Mangler.getStream() << "\01??_C@_";
  2436. // <char-type>: The "kind" of string literal is encoded into the mangled name.
  2437. if (SL->isWide())
  2438. Mangler.getStream() << '1';
  2439. else
  2440. Mangler.getStream() << '0';
  2441. // <literal-length>: The next part of the mangled name consists of the length
  2442. // of the string.
  2443. // The StringLiteral does not consider the NUL terminator byte(s) but the
  2444. // mangling does.
  2445. // N.B. The length is in terms of bytes, not characters.
  2446. Mangler.mangleNumber(SL->getByteLength() + SL->getCharByteWidth());
  2447. // We will use the "Rocksoft^tm Model CRC Algorithm" to describe the
  2448. // properties of our CRC:
  2449. // Width : 32
  2450. // Poly : 04C11DB7
  2451. // Init : FFFFFFFF
  2452. // RefIn : True
  2453. // RefOut : True
  2454. // XorOut : 00000000
  2455. // Check : 340BC6D9
  2456. uint32_t CRC = 0xFFFFFFFFU;
  2457. auto UpdateCRC = [&CRC](char Byte) {
  2458. for (unsigned i = 0; i < 8; ++i) {
  2459. bool Bit = CRC & 0x80000000U;
  2460. if (Byte & (1U << i))
  2461. Bit = !Bit;
  2462. CRC <<= 1;
  2463. if (Bit)
  2464. CRC ^= 0x04C11DB7U;
  2465. }
  2466. };
  2467. auto GetLittleEndianByte = [&Mangler, &SL](unsigned Index) {
  2468. unsigned CharByteWidth = SL->getCharByteWidth();
  2469. uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
  2470. unsigned OffsetInCodeUnit = Index % CharByteWidth;
  2471. return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
  2472. };
  2473. auto GetBigEndianByte = [&Mangler, &SL](unsigned Index) {
  2474. unsigned CharByteWidth = SL->getCharByteWidth();
  2475. uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
  2476. unsigned OffsetInCodeUnit = (CharByteWidth - 1) - (Index % CharByteWidth);
  2477. return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
  2478. };
  2479. // CRC all the bytes of the StringLiteral.
  2480. for (unsigned I = 0, E = SL->getByteLength(); I != E; ++I)
  2481. UpdateCRC(GetLittleEndianByte(I));
  2482. // The NUL terminator byte(s) were not present earlier,
  2483. // we need to manually process those bytes into the CRC.
  2484. for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth();
  2485. ++NullTerminator)
  2486. UpdateCRC('\x00');
  2487. // The literature refers to the process of reversing the bits in the final CRC
  2488. // output as "reflection".
  2489. CRC = llvm::reverseBits(CRC);
  2490. // <encoded-crc>: The CRC is encoded utilizing the standard number mangling
  2491. // scheme.
  2492. Mangler.mangleNumber(CRC);
  2493. // <encoded-string>: The mangled name also contains the first 32 _characters_
  2494. // (including null-terminator bytes) of the StringLiteral.
  2495. // Each character is encoded by splitting them into bytes and then encoding
  2496. // the constituent bytes.
  2497. auto MangleByte = [&Mangler](char Byte) {
  2498. // There are five different manglings for characters:
  2499. // - [a-zA-Z0-9_$]: A one-to-one mapping.
  2500. // - ?[a-z]: The range from \xe1 to \xfa.
  2501. // - ?[A-Z]: The range from \xc1 to \xda.
  2502. // - ?[0-9]: The set of [,/\:. \n\t'-].
  2503. // - ?$XX: A fallback which maps nibbles.
  2504. if (isIdentifierBody(Byte, /*AllowDollar=*/true)) {
  2505. Mangler.getStream() << Byte;
  2506. } else if (isLetter(Byte & 0x7f)) {
  2507. Mangler.getStream() << '?' << static_cast<char>(Byte & 0x7f);
  2508. } else {
  2509. const char SpecialChars[] = {',', '/', '\\', ':', '.',
  2510. ' ', '\n', '\t', '\'', '-'};
  2511. const char *Pos =
  2512. std::find(std::begin(SpecialChars), std::end(SpecialChars), Byte);
  2513. if (Pos != std::end(SpecialChars)) {
  2514. Mangler.getStream() << '?' << (Pos - std::begin(SpecialChars));
  2515. } else {
  2516. Mangler.getStream() << "?$";
  2517. Mangler.getStream() << static_cast<char>('A' + ((Byte >> 4) & 0xf));
  2518. Mangler.getStream() << static_cast<char>('A' + (Byte & 0xf));
  2519. }
  2520. }
  2521. };
  2522. // Enforce our 32 character max.
  2523. unsigned NumCharsToMangle = std::min(32U, SL->getLength());
  2524. for (unsigned I = 0, E = NumCharsToMangle * SL->getCharByteWidth(); I != E;
  2525. ++I)
  2526. if (SL->isWide())
  2527. MangleByte(GetBigEndianByte(I));
  2528. else
  2529. MangleByte(GetLittleEndianByte(I));
  2530. // Encode the NUL terminator if there is room.
  2531. if (NumCharsToMangle < 32)
  2532. for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth();
  2533. ++NullTerminator)
  2534. MangleByte(0);
  2535. Mangler.getStream() << '@';
  2536. }
  2537. void MicrosoftMangleContextImpl::mangleCXXVTableBitSet(const CXXRecordDecl *RD,
  2538. raw_ostream &Out) {
  2539. if (!RD->isExternallyVisible()) {
  2540. // This part of the identifier needs to be unique across all translation
  2541. // units in the linked program. The scheme fails if multiple translation
  2542. // units are compiled using the same relative source file path, or if
  2543. // multiple translation units are built from the same source file.
  2544. SourceManager &SM = getASTContext().getSourceManager();
  2545. Out << "[" << SM.getFileEntryForID(SM.getMainFileID())->getName() << "]";
  2546. }
  2547. MicrosoftCXXNameMangler mangler(*this, Out);
  2548. mangler.mangleName(RD);
  2549. }
  2550. MicrosoftMangleContext *
  2551. MicrosoftMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
  2552. return new MicrosoftMangleContextImpl(Context, Diags);
  2553. }