MicrosoftCXXABI.cpp 183 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527
  1. //===--- MicrosoftCXXABI.cpp - Emit LLVM Code from ASTs for a Module ------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This provides C++ code generation targeting the Microsoft Visual C++ ABI.
  10. // The class in this file generates structures that follow the Microsoft
  11. // Visual C++ ABI, which is actually not very well documented at all outside
  12. // of Microsoft.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "CGCXXABI.h"
  16. #include "CGCleanup.h"
  17. #include "CGVTables.h"
  18. #include "CodeGenModule.h"
  19. #include "CodeGenTypes.h"
  20. #include "TargetInfo.h"
  21. #include "clang/AST/Attr.h"
  22. #include "clang/AST/CXXInheritance.h"
  23. #include "clang/AST/Decl.h"
  24. #include "clang/AST/DeclCXX.h"
  25. #include "clang/AST/StmtCXX.h"
  26. #include "clang/AST/VTableBuilder.h"
  27. #include "clang/CodeGen/ConstantInitBuilder.h"
  28. #include "llvm/ADT/StringExtras.h"
  29. #include "llvm/ADT/StringSet.h"
  30. #include "llvm/IR/Intrinsics.h"
  31. using namespace clang;
  32. using namespace CodeGen;
  33. namespace {
  34. /// Holds all the vbtable globals for a given class.
  35. struct VBTableGlobals {
  36. const VPtrInfoVector *VBTables;
  37. SmallVector<llvm::GlobalVariable *, 2> Globals;
  38. };
  39. class MicrosoftCXXABI : public CGCXXABI {
  40. public:
  41. MicrosoftCXXABI(CodeGenModule &CGM)
  42. : CGCXXABI(CGM), BaseClassDescriptorType(nullptr),
  43. ClassHierarchyDescriptorType(nullptr),
  44. CompleteObjectLocatorType(nullptr), CatchableTypeType(nullptr),
  45. ThrowInfoType(nullptr) {
  46. assert(!(CGM.getLangOpts().isExplicitDefaultVisibilityExportMapping() ||
  47. CGM.getLangOpts().isAllDefaultVisibilityExportMapping()) &&
  48. "visibility export mapping option unimplemented in this ABI");
  49. }
  50. bool HasThisReturn(GlobalDecl GD) const override;
  51. bool hasMostDerivedReturn(GlobalDecl GD) const override;
  52. bool classifyReturnType(CGFunctionInfo &FI) const override;
  53. RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override;
  54. bool isSRetParameterAfterThis() const override { return true; }
  55. bool isThisCompleteObject(GlobalDecl GD) const override {
  56. // The Microsoft ABI doesn't use separate complete-object vs.
  57. // base-object variants of constructors, but it does of destructors.
  58. if (isa<CXXDestructorDecl>(GD.getDecl())) {
  59. switch (GD.getDtorType()) {
  60. case Dtor_Complete:
  61. case Dtor_Deleting:
  62. return true;
  63. case Dtor_Base:
  64. return false;
  65. case Dtor_Comdat: llvm_unreachable("emitting dtor comdat as function?");
  66. }
  67. llvm_unreachable("bad dtor kind");
  68. }
  69. // No other kinds.
  70. return false;
  71. }
  72. size_t getSrcArgforCopyCtor(const CXXConstructorDecl *CD,
  73. FunctionArgList &Args) const override {
  74. assert(Args.size() >= 2 &&
  75. "expected the arglist to have at least two args!");
  76. // The 'most_derived' parameter goes second if the ctor is variadic and
  77. // has v-bases.
  78. if (CD->getParent()->getNumVBases() > 0 &&
  79. CD->getType()->castAs<FunctionProtoType>()->isVariadic())
  80. return 2;
  81. return 1;
  82. }
  83. std::vector<CharUnits> getVBPtrOffsets(const CXXRecordDecl *RD) override {
  84. std::vector<CharUnits> VBPtrOffsets;
  85. const ASTContext &Context = getContext();
  86. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  87. const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
  88. for (const std::unique_ptr<VPtrInfo> &VBT : *VBGlobals.VBTables) {
  89. const ASTRecordLayout &SubobjectLayout =
  90. Context.getASTRecordLayout(VBT->IntroducingObject);
  91. CharUnits Offs = VBT->NonVirtualOffset;
  92. Offs += SubobjectLayout.getVBPtrOffset();
  93. if (VBT->getVBaseWithVPtr())
  94. Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
  95. VBPtrOffsets.push_back(Offs);
  96. }
  97. llvm::array_pod_sort(VBPtrOffsets.begin(), VBPtrOffsets.end());
  98. return VBPtrOffsets;
  99. }
  100. StringRef GetPureVirtualCallName() override { return "_purecall"; }
  101. StringRef GetDeletedVirtualCallName() override { return "_purecall"; }
  102. void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
  103. Address Ptr, QualType ElementType,
  104. const CXXDestructorDecl *Dtor) override;
  105. void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
  106. void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
  107. void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
  108. llvm::GlobalVariable *getMSCompleteObjectLocator(const CXXRecordDecl *RD,
  109. const VPtrInfo &Info);
  110. llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
  111. CatchTypeInfo
  112. getAddrOfCXXCatchHandlerType(QualType Ty, QualType CatchHandlerType) override;
  113. /// MSVC needs an extra flag to indicate a catchall.
  114. CatchTypeInfo getCatchAllTypeInfo() override {
  115. // For -EHa catch(...) must handle HW exception
  116. // Adjective = HT_IsStdDotDot (0x40), only catch C++ exceptions
  117. if (getContext().getLangOpts().EHAsynch)
  118. return CatchTypeInfo{nullptr, 0};
  119. else
  120. return CatchTypeInfo{nullptr, 0x40};
  121. }
  122. bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
  123. void EmitBadTypeidCall(CodeGenFunction &CGF) override;
  124. llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
  125. Address ThisPtr,
  126. llvm::Type *StdTypeInfoPtrTy) override;
  127. bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
  128. QualType SrcRecordTy) override;
  129. llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
  130. QualType SrcRecordTy, QualType DestTy,
  131. QualType DestRecordTy,
  132. llvm::BasicBlock *CastEnd) override;
  133. llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
  134. QualType SrcRecordTy,
  135. QualType DestTy) override;
  136. bool EmitBadCastCall(CodeGenFunction &CGF) override;
  137. bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override {
  138. return false;
  139. }
  140. llvm::Value *
  141. GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
  142. const CXXRecordDecl *ClassDecl,
  143. const CXXRecordDecl *BaseClassDecl) override;
  144. llvm::BasicBlock *
  145. EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
  146. const CXXRecordDecl *RD) override;
  147. llvm::BasicBlock *
  148. EmitDtorCompleteObjectHandler(CodeGenFunction &CGF);
  149. void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
  150. const CXXRecordDecl *RD) override;
  151. void EmitCXXConstructors(const CXXConstructorDecl *D) override;
  152. // Background on MSVC destructors
  153. // ==============================
  154. //
  155. // Both Itanium and MSVC ABIs have destructor variants. The variant names
  156. // roughly correspond in the following way:
  157. // Itanium Microsoft
  158. // Base -> no name, just ~Class
  159. // Complete -> vbase destructor
  160. // Deleting -> scalar deleting destructor
  161. // vector deleting destructor
  162. //
  163. // The base and complete destructors are the same as in Itanium, although the
  164. // complete destructor does not accept a VTT parameter when there are virtual
  165. // bases. A separate mechanism involving vtordisps is used to ensure that
  166. // virtual methods of destroyed subobjects are not called.
  167. //
  168. // The deleting destructors accept an i32 bitfield as a second parameter. Bit
  169. // 1 indicates if the memory should be deleted. Bit 2 indicates if the this
  170. // pointer points to an array. The scalar deleting destructor assumes that
  171. // bit 2 is zero, and therefore does not contain a loop.
  172. //
  173. // For virtual destructors, only one entry is reserved in the vftable, and it
  174. // always points to the vector deleting destructor. The vector deleting
  175. // destructor is the most general, so it can be used to destroy objects in
  176. // place, delete single heap objects, or delete arrays.
  177. //
  178. // A TU defining a non-inline destructor is only guaranteed to emit a base
  179. // destructor, and all of the other variants are emitted on an as-needed basis
  180. // in COMDATs. Because a non-base destructor can be emitted in a TU that
  181. // lacks a definition for the destructor, non-base destructors must always
  182. // delegate to or alias the base destructor.
  183. AddedStructorArgCounts
  184. buildStructorSignature(GlobalDecl GD,
  185. SmallVectorImpl<CanQualType> &ArgTys) override;
  186. /// Non-base dtors should be emitted as delegating thunks in this ABI.
  187. bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
  188. CXXDtorType DT) const override {
  189. return DT != Dtor_Base;
  190. }
  191. void setCXXDestructorDLLStorage(llvm::GlobalValue *GV,
  192. const CXXDestructorDecl *Dtor,
  193. CXXDtorType DT) const override;
  194. llvm::GlobalValue::LinkageTypes
  195. getCXXDestructorLinkage(GVALinkage Linkage, const CXXDestructorDecl *Dtor,
  196. CXXDtorType DT) const override;
  197. void EmitCXXDestructors(const CXXDestructorDecl *D) override;
  198. const CXXRecordDecl *getThisArgumentTypeForMethod(GlobalDecl GD) override {
  199. auto *MD = cast<CXXMethodDecl>(GD.getDecl());
  200. if (MD->isVirtual()) {
  201. GlobalDecl LookupGD = GD;
  202. if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
  203. // Complete dtors take a pointer to the complete object,
  204. // thus don't need adjustment.
  205. if (GD.getDtorType() == Dtor_Complete)
  206. return MD->getParent();
  207. // There's only Dtor_Deleting in vftable but it shares the this
  208. // adjustment with the base one, so look up the deleting one instead.
  209. LookupGD = GlobalDecl(DD, Dtor_Deleting);
  210. }
  211. MethodVFTableLocation ML =
  212. CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
  213. // The vbases might be ordered differently in the final overrider object
  214. // and the complete object, so the "this" argument may sometimes point to
  215. // memory that has no particular type (e.g. past the complete object).
  216. // In this case, we just use a generic pointer type.
  217. // FIXME: might want to have a more precise type in the non-virtual
  218. // multiple inheritance case.
  219. if (ML.VBase || !ML.VFPtrOffset.isZero())
  220. return nullptr;
  221. }
  222. return MD->getParent();
  223. }
  224. Address
  225. adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,
  226. Address This,
  227. bool VirtualCall) override;
  228. void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
  229. FunctionArgList &Params) override;
  230. void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
  231. AddedStructorArgs getImplicitConstructorArgs(CodeGenFunction &CGF,
  232. const CXXConstructorDecl *D,
  233. CXXCtorType Type,
  234. bool ForVirtualBase,
  235. bool Delegating) override;
  236. llvm::Value *getCXXDestructorImplicitParam(CodeGenFunction &CGF,
  237. const CXXDestructorDecl *DD,
  238. CXXDtorType Type,
  239. bool ForVirtualBase,
  240. bool Delegating) override;
  241. void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
  242. CXXDtorType Type, bool ForVirtualBase,
  243. bool Delegating, Address This,
  244. QualType ThisTy) override;
  245. void emitVTableTypeMetadata(const VPtrInfo &Info, const CXXRecordDecl *RD,
  246. llvm::GlobalVariable *VTable);
  247. void emitVTableDefinitions(CodeGenVTables &CGVT,
  248. const CXXRecordDecl *RD) override;
  249. bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
  250. CodeGenFunction::VPtr Vptr) override;
  251. /// Don't initialize vptrs if dynamic class
  252. /// is marked with the 'novtable' attribute.
  253. bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
  254. return !VTableClass->hasAttr<MSNoVTableAttr>();
  255. }
  256. llvm::Constant *
  257. getVTableAddressPoint(BaseSubobject Base,
  258. const CXXRecordDecl *VTableClass) override;
  259. llvm::Value *getVTableAddressPointInStructor(
  260. CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
  261. BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
  262. llvm::Constant *
  263. getVTableAddressPointForConstExpr(BaseSubobject Base,
  264. const CXXRecordDecl *VTableClass) override;
  265. llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
  266. CharUnits VPtrOffset) override;
  267. CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
  268. Address This, llvm::Type *Ty,
  269. SourceLocation Loc) override;
  270. llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
  271. const CXXDestructorDecl *Dtor,
  272. CXXDtorType DtorType, Address This,
  273. DeleteOrMemberCallExpr E) override;
  274. void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
  275. CallArgList &CallArgs) override {
  276. assert(GD.getDtorType() == Dtor_Deleting &&
  277. "Only deleting destructor thunks are available in this ABI");
  278. CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
  279. getContext().IntTy);
  280. }
  281. void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
  282. llvm::GlobalVariable *
  283. getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
  284. llvm::GlobalVariable::LinkageTypes Linkage);
  285. llvm::GlobalVariable *
  286. getAddrOfVirtualDisplacementMap(const CXXRecordDecl *SrcRD,
  287. const CXXRecordDecl *DstRD) {
  288. SmallString<256> OutName;
  289. llvm::raw_svector_ostream Out(OutName);
  290. getMangleContext().mangleCXXVirtualDisplacementMap(SrcRD, DstRD, Out);
  291. StringRef MangledName = OutName.str();
  292. if (auto *VDispMap = CGM.getModule().getNamedGlobal(MangledName))
  293. return VDispMap;
  294. MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
  295. unsigned NumEntries = 1 + SrcRD->getNumVBases();
  296. SmallVector<llvm::Constant *, 4> Map(NumEntries,
  297. llvm::UndefValue::get(CGM.IntTy));
  298. Map[0] = llvm::ConstantInt::get(CGM.IntTy, 0);
  299. bool AnyDifferent = false;
  300. for (const auto &I : SrcRD->vbases()) {
  301. const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
  302. if (!DstRD->isVirtuallyDerivedFrom(VBase))
  303. continue;
  304. unsigned SrcVBIndex = VTContext.getVBTableIndex(SrcRD, VBase);
  305. unsigned DstVBIndex = VTContext.getVBTableIndex(DstRD, VBase);
  306. Map[SrcVBIndex] = llvm::ConstantInt::get(CGM.IntTy, DstVBIndex * 4);
  307. AnyDifferent |= SrcVBIndex != DstVBIndex;
  308. }
  309. // This map would be useless, don't use it.
  310. if (!AnyDifferent)
  311. return nullptr;
  312. llvm::ArrayType *VDispMapTy = llvm::ArrayType::get(CGM.IntTy, Map.size());
  313. llvm::Constant *Init = llvm::ConstantArray::get(VDispMapTy, Map);
  314. llvm::GlobalValue::LinkageTypes Linkage =
  315. SrcRD->isExternallyVisible() && DstRD->isExternallyVisible()
  316. ? llvm::GlobalValue::LinkOnceODRLinkage
  317. : llvm::GlobalValue::InternalLinkage;
  318. auto *VDispMap = new llvm::GlobalVariable(
  319. CGM.getModule(), VDispMapTy, /*isConstant=*/true, Linkage,
  320. /*Initializer=*/Init, MangledName);
  321. return VDispMap;
  322. }
  323. void emitVBTableDefinition(const VPtrInfo &VBT, const CXXRecordDecl *RD,
  324. llvm::GlobalVariable *GV) const;
  325. void setThunkLinkage(llvm::Function *Thunk, bool ForVTable,
  326. GlobalDecl GD, bool ReturnAdjustment) override {
  327. GVALinkage Linkage =
  328. getContext().GetGVALinkageForFunction(cast<FunctionDecl>(GD.getDecl()));
  329. if (Linkage == GVA_Internal)
  330. Thunk->setLinkage(llvm::GlobalValue::InternalLinkage);
  331. else if (ReturnAdjustment)
  332. Thunk->setLinkage(llvm::GlobalValue::WeakODRLinkage);
  333. else
  334. Thunk->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
  335. }
  336. bool exportThunk() override { return false; }
  337. llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
  338. const ThisAdjustment &TA) override;
  339. llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
  340. const ReturnAdjustment &RA) override;
  341. void EmitThreadLocalInitFuncs(
  342. CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
  343. ArrayRef<llvm::Function *> CXXThreadLocalInits,
  344. ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
  345. bool usesThreadWrapperFunction(const VarDecl *VD) const override {
  346. return getContext().getLangOpts().isCompatibleWithMSVC(
  347. LangOptions::MSVC2019_5) &&
  348. (!isEmittedWithConstantInitializer(VD) || mayNeedDestruction(VD));
  349. }
  350. LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
  351. QualType LValType) override;
  352. void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
  353. llvm::GlobalVariable *DeclPtr,
  354. bool PerformInit) override;
  355. void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
  356. llvm::FunctionCallee Dtor,
  357. llvm::Constant *Addr) override;
  358. // ==== Notes on array cookies =========
  359. //
  360. // MSVC seems to only use cookies when the class has a destructor; a
  361. // two-argument usual array deallocation function isn't sufficient.
  362. //
  363. // For example, this code prints "100" and "1":
  364. // struct A {
  365. // char x;
  366. // void *operator new[](size_t sz) {
  367. // printf("%u\n", sz);
  368. // return malloc(sz);
  369. // }
  370. // void operator delete[](void *p, size_t sz) {
  371. // printf("%u\n", sz);
  372. // free(p);
  373. // }
  374. // };
  375. // int main() {
  376. // A *p = new A[100];
  377. // delete[] p;
  378. // }
  379. // Whereas it prints "104" and "104" if you give A a destructor.
  380. bool requiresArrayCookie(const CXXDeleteExpr *expr,
  381. QualType elementType) override;
  382. bool requiresArrayCookie(const CXXNewExpr *expr) override;
  383. CharUnits getArrayCookieSizeImpl(QualType type) override;
  384. Address InitializeArrayCookie(CodeGenFunction &CGF,
  385. Address NewPtr,
  386. llvm::Value *NumElements,
  387. const CXXNewExpr *expr,
  388. QualType ElementType) override;
  389. llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
  390. Address allocPtr,
  391. CharUnits cookieSize) override;
  392. friend struct MSRTTIBuilder;
  393. bool isImageRelative() const {
  394. return CGM.getTarget().getPointerWidth(LangAS::Default) == 64;
  395. }
  396. // 5 routines for constructing the llvm types for MS RTTI structs.
  397. llvm::StructType *getTypeDescriptorType(StringRef TypeInfoString) {
  398. llvm::SmallString<32> TDTypeName("rtti.TypeDescriptor");
  399. TDTypeName += llvm::utostr(TypeInfoString.size());
  400. llvm::StructType *&TypeDescriptorType =
  401. TypeDescriptorTypeMap[TypeInfoString.size()];
  402. if (TypeDescriptorType)
  403. return TypeDescriptorType;
  404. llvm::Type *FieldTypes[] = {
  405. CGM.Int8PtrPtrTy,
  406. CGM.Int8PtrTy,
  407. llvm::ArrayType::get(CGM.Int8Ty, TypeInfoString.size() + 1)};
  408. TypeDescriptorType =
  409. llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, TDTypeName);
  410. return TypeDescriptorType;
  411. }
  412. llvm::Type *getImageRelativeType(llvm::Type *PtrType) {
  413. if (!isImageRelative())
  414. return PtrType;
  415. return CGM.IntTy;
  416. }
  417. llvm::StructType *getBaseClassDescriptorType() {
  418. if (BaseClassDescriptorType)
  419. return BaseClassDescriptorType;
  420. llvm::Type *FieldTypes[] = {
  421. getImageRelativeType(CGM.Int8PtrTy),
  422. CGM.IntTy,
  423. CGM.IntTy,
  424. CGM.IntTy,
  425. CGM.IntTy,
  426. CGM.IntTy,
  427. getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
  428. };
  429. BaseClassDescriptorType = llvm::StructType::create(
  430. CGM.getLLVMContext(), FieldTypes, "rtti.BaseClassDescriptor");
  431. return BaseClassDescriptorType;
  432. }
  433. llvm::StructType *getClassHierarchyDescriptorType() {
  434. if (ClassHierarchyDescriptorType)
  435. return ClassHierarchyDescriptorType;
  436. // Forward-declare RTTIClassHierarchyDescriptor to break a cycle.
  437. ClassHierarchyDescriptorType = llvm::StructType::create(
  438. CGM.getLLVMContext(), "rtti.ClassHierarchyDescriptor");
  439. llvm::Type *FieldTypes[] = {
  440. CGM.IntTy,
  441. CGM.IntTy,
  442. CGM.IntTy,
  443. getImageRelativeType(
  444. getBaseClassDescriptorType()->getPointerTo()->getPointerTo()),
  445. };
  446. ClassHierarchyDescriptorType->setBody(FieldTypes);
  447. return ClassHierarchyDescriptorType;
  448. }
  449. llvm::StructType *getCompleteObjectLocatorType() {
  450. if (CompleteObjectLocatorType)
  451. return CompleteObjectLocatorType;
  452. CompleteObjectLocatorType = llvm::StructType::create(
  453. CGM.getLLVMContext(), "rtti.CompleteObjectLocator");
  454. llvm::Type *FieldTypes[] = {
  455. CGM.IntTy,
  456. CGM.IntTy,
  457. CGM.IntTy,
  458. getImageRelativeType(CGM.Int8PtrTy),
  459. getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
  460. getImageRelativeType(CompleteObjectLocatorType),
  461. };
  462. llvm::ArrayRef<llvm::Type *> FieldTypesRef(FieldTypes);
  463. if (!isImageRelative())
  464. FieldTypesRef = FieldTypesRef.drop_back();
  465. CompleteObjectLocatorType->setBody(FieldTypesRef);
  466. return CompleteObjectLocatorType;
  467. }
  468. llvm::GlobalVariable *getImageBase() {
  469. StringRef Name = "__ImageBase";
  470. if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name))
  471. return GV;
  472. auto *GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty,
  473. /*isConstant=*/true,
  474. llvm::GlobalValue::ExternalLinkage,
  475. /*Initializer=*/nullptr, Name);
  476. CGM.setDSOLocal(GV);
  477. return GV;
  478. }
  479. llvm::Constant *getImageRelativeConstant(llvm::Constant *PtrVal) {
  480. if (!isImageRelative())
  481. return PtrVal;
  482. if (PtrVal->isNullValue())
  483. return llvm::Constant::getNullValue(CGM.IntTy);
  484. llvm::Constant *ImageBaseAsInt =
  485. llvm::ConstantExpr::getPtrToInt(getImageBase(), CGM.IntPtrTy);
  486. llvm::Constant *PtrValAsInt =
  487. llvm::ConstantExpr::getPtrToInt(PtrVal, CGM.IntPtrTy);
  488. llvm::Constant *Diff =
  489. llvm::ConstantExpr::getSub(PtrValAsInt, ImageBaseAsInt,
  490. /*HasNUW=*/true, /*HasNSW=*/true);
  491. return llvm::ConstantExpr::getTrunc(Diff, CGM.IntTy);
  492. }
  493. private:
  494. MicrosoftMangleContext &getMangleContext() {
  495. return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
  496. }
  497. llvm::Constant *getZeroInt() {
  498. return llvm::ConstantInt::get(CGM.IntTy, 0);
  499. }
  500. llvm::Constant *getAllOnesInt() {
  501. return llvm::Constant::getAllOnesValue(CGM.IntTy);
  502. }
  503. CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) override;
  504. void
  505. GetNullMemberPointerFields(const MemberPointerType *MPT,
  506. llvm::SmallVectorImpl<llvm::Constant *> &fields);
  507. /// Shared code for virtual base adjustment. Returns the offset from
  508. /// the vbptr to the virtual base. Optionally returns the address of the
  509. /// vbptr itself.
  510. llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
  511. Address Base,
  512. llvm::Value *VBPtrOffset,
  513. llvm::Value *VBTableOffset,
  514. llvm::Value **VBPtr = nullptr);
  515. llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
  516. Address Base,
  517. int32_t VBPtrOffset,
  518. int32_t VBTableOffset,
  519. llvm::Value **VBPtr = nullptr) {
  520. assert(VBTableOffset % 4 == 0 && "should be byte offset into table of i32s");
  521. llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
  522. *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
  523. return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
  524. }
  525. std::tuple<Address, llvm::Value *, const CXXRecordDecl *>
  526. performBaseAdjustment(CodeGenFunction &CGF, Address Value,
  527. QualType SrcRecordTy);
  528. /// Performs a full virtual base adjustment. Used to dereference
  529. /// pointers to members of virtual bases.
  530. llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const Expr *E,
  531. const CXXRecordDecl *RD, Address Base,
  532. llvm::Value *VirtualBaseAdjustmentOffset,
  533. llvm::Value *VBPtrOffset /* optional */);
  534. /// Emits a full member pointer with the fields common to data and
  535. /// function member pointers.
  536. llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
  537. bool IsMemberFunction,
  538. const CXXRecordDecl *RD,
  539. CharUnits NonVirtualBaseAdjustment,
  540. unsigned VBTableIndex);
  541. bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
  542. llvm::Constant *MP);
  543. /// - Initialize all vbptrs of 'this' with RD as the complete type.
  544. void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
  545. /// Caching wrapper around VBTableBuilder::enumerateVBTables().
  546. const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD);
  547. /// Generate a thunk for calling a virtual member function MD.
  548. llvm::Function *EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
  549. const MethodVFTableLocation &ML);
  550. llvm::Constant *EmitMemberDataPointer(const CXXRecordDecl *RD,
  551. CharUnits offset);
  552. public:
  553. llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
  554. bool isZeroInitializable(const MemberPointerType *MPT) override;
  555. bool isMemberPointerConvertible(const MemberPointerType *MPT) const override {
  556. const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
  557. return RD->hasAttr<MSInheritanceAttr>();
  558. }
  559. llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
  560. llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
  561. CharUnits offset) override;
  562. llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
  563. llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
  564. llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
  565. llvm::Value *L,
  566. llvm::Value *R,
  567. const MemberPointerType *MPT,
  568. bool Inequality) override;
  569. llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
  570. llvm::Value *MemPtr,
  571. const MemberPointerType *MPT) override;
  572. llvm::Value *
  573. EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
  574. Address Base, llvm::Value *MemPtr,
  575. const MemberPointerType *MPT) override;
  576. llvm::Value *EmitNonNullMemberPointerConversion(
  577. const MemberPointerType *SrcTy, const MemberPointerType *DstTy,
  578. CastKind CK, CastExpr::path_const_iterator PathBegin,
  579. CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
  580. CGBuilderTy &Builder);
  581. llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
  582. const CastExpr *E,
  583. llvm::Value *Src) override;
  584. llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
  585. llvm::Constant *Src) override;
  586. llvm::Constant *EmitMemberPointerConversion(
  587. const MemberPointerType *SrcTy, const MemberPointerType *DstTy,
  588. CastKind CK, CastExpr::path_const_iterator PathBegin,
  589. CastExpr::path_const_iterator PathEnd, llvm::Constant *Src);
  590. CGCallee
  591. EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E,
  592. Address This, llvm::Value *&ThisPtrForCall,
  593. llvm::Value *MemPtr,
  594. const MemberPointerType *MPT) override;
  595. void emitCXXStructor(GlobalDecl GD) override;
  596. llvm::StructType *getCatchableTypeType() {
  597. if (CatchableTypeType)
  598. return CatchableTypeType;
  599. llvm::Type *FieldTypes[] = {
  600. CGM.IntTy, // Flags
  601. getImageRelativeType(CGM.Int8PtrTy), // TypeDescriptor
  602. CGM.IntTy, // NonVirtualAdjustment
  603. CGM.IntTy, // OffsetToVBPtr
  604. CGM.IntTy, // VBTableIndex
  605. CGM.IntTy, // Size
  606. getImageRelativeType(CGM.Int8PtrTy) // CopyCtor
  607. };
  608. CatchableTypeType = llvm::StructType::create(
  609. CGM.getLLVMContext(), FieldTypes, "eh.CatchableType");
  610. return CatchableTypeType;
  611. }
  612. llvm::StructType *getCatchableTypeArrayType(uint32_t NumEntries) {
  613. llvm::StructType *&CatchableTypeArrayType =
  614. CatchableTypeArrayTypeMap[NumEntries];
  615. if (CatchableTypeArrayType)
  616. return CatchableTypeArrayType;
  617. llvm::SmallString<23> CTATypeName("eh.CatchableTypeArray.");
  618. CTATypeName += llvm::utostr(NumEntries);
  619. llvm::Type *CTType =
  620. getImageRelativeType(getCatchableTypeType()->getPointerTo());
  621. llvm::Type *FieldTypes[] = {
  622. CGM.IntTy, // NumEntries
  623. llvm::ArrayType::get(CTType, NumEntries) // CatchableTypes
  624. };
  625. CatchableTypeArrayType =
  626. llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, CTATypeName);
  627. return CatchableTypeArrayType;
  628. }
  629. llvm::StructType *getThrowInfoType() {
  630. if (ThrowInfoType)
  631. return ThrowInfoType;
  632. llvm::Type *FieldTypes[] = {
  633. CGM.IntTy, // Flags
  634. getImageRelativeType(CGM.Int8PtrTy), // CleanupFn
  635. getImageRelativeType(CGM.Int8PtrTy), // ForwardCompat
  636. getImageRelativeType(CGM.Int8PtrTy) // CatchableTypeArray
  637. };
  638. ThrowInfoType = llvm::StructType::create(CGM.getLLVMContext(), FieldTypes,
  639. "eh.ThrowInfo");
  640. return ThrowInfoType;
  641. }
  642. llvm::FunctionCallee getThrowFn() {
  643. // _CxxThrowException is passed an exception object and a ThrowInfo object
  644. // which describes the exception.
  645. llvm::Type *Args[] = {CGM.Int8PtrTy, getThrowInfoType()->getPointerTo()};
  646. llvm::FunctionType *FTy =
  647. llvm::FunctionType::get(CGM.VoidTy, Args, /*isVarArg=*/false);
  648. llvm::FunctionCallee Throw =
  649. CGM.CreateRuntimeFunction(FTy, "_CxxThrowException");
  650. // _CxxThrowException is stdcall on 32-bit x86 platforms.
  651. if (CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
  652. if (auto *Fn = dyn_cast<llvm::Function>(Throw.getCallee()))
  653. Fn->setCallingConv(llvm::CallingConv::X86_StdCall);
  654. }
  655. return Throw;
  656. }
  657. llvm::Function *getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
  658. CXXCtorType CT);
  659. llvm::Constant *getCatchableType(QualType T,
  660. uint32_t NVOffset = 0,
  661. int32_t VBPtrOffset = -1,
  662. uint32_t VBIndex = 0);
  663. llvm::GlobalVariable *getCatchableTypeArray(QualType T);
  664. llvm::GlobalVariable *getThrowInfo(QualType T) override;
  665. std::pair<llvm::Value *, const CXXRecordDecl *>
  666. LoadVTablePtr(CodeGenFunction &CGF, Address This,
  667. const CXXRecordDecl *RD) override;
  668. bool
  669. isPermittedToBeHomogeneousAggregate(const CXXRecordDecl *RD) const override;
  670. private:
  671. typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
  672. typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VTablesMapTy;
  673. typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalValue *> VFTablesMapTy;
  674. /// All the vftables that have been referenced.
  675. VFTablesMapTy VFTablesMap;
  676. VTablesMapTy VTablesMap;
  677. /// This set holds the record decls we've deferred vtable emission for.
  678. llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
  679. /// All the vbtables which have been referenced.
  680. llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap;
  681. /// Info on the global variable used to guard initialization of static locals.
  682. /// The BitIndex field is only used for externally invisible declarations.
  683. struct GuardInfo {
  684. GuardInfo() : Guard(nullptr), BitIndex(0) {}
  685. llvm::GlobalVariable *Guard;
  686. unsigned BitIndex;
  687. };
  688. /// Map from DeclContext to the current guard variable. We assume that the
  689. /// AST is visited in source code order.
  690. llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
  691. llvm::DenseMap<const DeclContext *, GuardInfo> ThreadLocalGuardVariableMap;
  692. llvm::DenseMap<const DeclContext *, unsigned> ThreadSafeGuardNumMap;
  693. llvm::DenseMap<size_t, llvm::StructType *> TypeDescriptorTypeMap;
  694. llvm::StructType *BaseClassDescriptorType;
  695. llvm::StructType *ClassHierarchyDescriptorType;
  696. llvm::StructType *CompleteObjectLocatorType;
  697. llvm::DenseMap<QualType, llvm::GlobalVariable *> CatchableTypeArrays;
  698. llvm::StructType *CatchableTypeType;
  699. llvm::DenseMap<uint32_t, llvm::StructType *> CatchableTypeArrayTypeMap;
  700. llvm::StructType *ThrowInfoType;
  701. };
  702. }
  703. CGCXXABI::RecordArgABI
  704. MicrosoftCXXABI::getRecordArgABI(const CXXRecordDecl *RD) const {
  705. // Use the default C calling convention rules for things that can be passed in
  706. // registers, i.e. non-trivially copyable records or records marked with
  707. // [[trivial_abi]].
  708. if (RD->canPassInRegisters())
  709. return RAA_Default;
  710. switch (CGM.getTarget().getTriple().getArch()) {
  711. default:
  712. // FIXME: Implement for other architectures.
  713. return RAA_Indirect;
  714. case llvm::Triple::thumb:
  715. // Pass things indirectly for now because it is simple.
  716. // FIXME: This is incompatible with MSVC for arguments with a dtor and no
  717. // copy ctor.
  718. return RAA_Indirect;
  719. case llvm::Triple::x86: {
  720. // If the argument has *required* alignment greater than four bytes, pass
  721. // it indirectly. Prior to MSVC version 19.14, passing overaligned
  722. // arguments was not supported and resulted in a compiler error. In 19.14
  723. // and later versions, such arguments are now passed indirectly.
  724. TypeInfo Info = getContext().getTypeInfo(RD->getTypeForDecl());
  725. if (Info.isAlignRequired() && Info.Align > 4)
  726. return RAA_Indirect;
  727. // If C++ prohibits us from making a copy, construct the arguments directly
  728. // into argument memory.
  729. return RAA_DirectInMemory;
  730. }
  731. case llvm::Triple::x86_64:
  732. case llvm::Triple::aarch64:
  733. return RAA_Indirect;
  734. }
  735. llvm_unreachable("invalid enum");
  736. }
  737. void MicrosoftCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
  738. const CXXDeleteExpr *DE,
  739. Address Ptr,
  740. QualType ElementType,
  741. const CXXDestructorDecl *Dtor) {
  742. // FIXME: Provide a source location here even though there's no
  743. // CXXMemberCallExpr for dtor call.
  744. bool UseGlobalDelete = DE->isGlobalDelete();
  745. CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
  746. llvm::Value *MDThis = EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, DE);
  747. if (UseGlobalDelete)
  748. CGF.EmitDeleteCall(DE->getOperatorDelete(), MDThis, ElementType);
  749. }
  750. void MicrosoftCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
  751. llvm::Value *Args[] = {
  752. llvm::ConstantPointerNull::get(CGM.Int8PtrTy),
  753. llvm::ConstantPointerNull::get(getThrowInfoType()->getPointerTo())};
  754. llvm::FunctionCallee Fn = getThrowFn();
  755. if (isNoReturn)
  756. CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, Args);
  757. else
  758. CGF.EmitRuntimeCallOrInvoke(Fn, Args);
  759. }
  760. void MicrosoftCXXABI::emitBeginCatch(CodeGenFunction &CGF,
  761. const CXXCatchStmt *S) {
  762. // In the MS ABI, the runtime handles the copy, and the catch handler is
  763. // responsible for destruction.
  764. VarDecl *CatchParam = S->getExceptionDecl();
  765. llvm::BasicBlock *CatchPadBB = CGF.Builder.GetInsertBlock();
  766. llvm::CatchPadInst *CPI =
  767. cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
  768. CGF.CurrentFuncletPad = CPI;
  769. // If this is a catch-all or the catch parameter is unnamed, we don't need to
  770. // emit an alloca to the object.
  771. if (!CatchParam || !CatchParam->getDeclName()) {
  772. CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
  773. return;
  774. }
  775. CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
  776. CPI->setArgOperand(2, var.getObjectAddress(CGF).getPointer());
  777. CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
  778. CGF.EmitAutoVarCleanups(var);
  779. }
  780. /// We need to perform a generic polymorphic operation (like a typeid
  781. /// or a cast), which requires an object with a vfptr. Adjust the
  782. /// address to point to an object with a vfptr.
  783. std::tuple<Address, llvm::Value *, const CXXRecordDecl *>
  784. MicrosoftCXXABI::performBaseAdjustment(CodeGenFunction &CGF, Address Value,
  785. QualType SrcRecordTy) {
  786. Value = CGF.Builder.CreateElementBitCast(Value, CGF.Int8Ty);
  787. const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
  788. const ASTContext &Context = getContext();
  789. // If the class itself has a vfptr, great. This check implicitly
  790. // covers non-virtual base subobjects: a class with its own virtual
  791. // functions would be a candidate to be a primary base.
  792. if (Context.getASTRecordLayout(SrcDecl).hasExtendableVFPtr())
  793. return std::make_tuple(Value, llvm::ConstantInt::get(CGF.Int32Ty, 0),
  794. SrcDecl);
  795. // Okay, one of the vbases must have a vfptr, or else this isn't
  796. // actually a polymorphic class.
  797. const CXXRecordDecl *PolymorphicBase = nullptr;
  798. for (auto &Base : SrcDecl->vbases()) {
  799. const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
  800. if (Context.getASTRecordLayout(BaseDecl).hasExtendableVFPtr()) {
  801. PolymorphicBase = BaseDecl;
  802. break;
  803. }
  804. }
  805. assert(PolymorphicBase && "polymorphic class has no apparent vfptr?");
  806. llvm::Value *Offset =
  807. GetVirtualBaseClassOffset(CGF, Value, SrcDecl, PolymorphicBase);
  808. llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
  809. Value.getElementType(), Value.getPointer(), Offset);
  810. CharUnits VBaseAlign =
  811. CGF.CGM.getVBaseAlignment(Value.getAlignment(), SrcDecl, PolymorphicBase);
  812. return std::make_tuple(Address(Ptr, CGF.Int8Ty, VBaseAlign), Offset,
  813. PolymorphicBase);
  814. }
  815. bool MicrosoftCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
  816. QualType SrcRecordTy) {
  817. const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
  818. return IsDeref &&
  819. !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
  820. }
  821. static llvm::CallBase *emitRTtypeidCall(CodeGenFunction &CGF,
  822. llvm::Value *Argument) {
  823. llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
  824. llvm::FunctionType *FTy =
  825. llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false);
  826. llvm::Value *Args[] = {Argument};
  827. llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(FTy, "__RTtypeid");
  828. return CGF.EmitRuntimeCallOrInvoke(Fn, Args);
  829. }
  830. void MicrosoftCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
  831. llvm::CallBase *Call =
  832. emitRTtypeidCall(CGF, llvm::Constant::getNullValue(CGM.VoidPtrTy));
  833. Call->setDoesNotReturn();
  834. CGF.Builder.CreateUnreachable();
  835. }
  836. llvm::Value *MicrosoftCXXABI::EmitTypeid(CodeGenFunction &CGF,
  837. QualType SrcRecordTy,
  838. Address ThisPtr,
  839. llvm::Type *StdTypeInfoPtrTy) {
  840. std::tie(ThisPtr, std::ignore, std::ignore) =
  841. performBaseAdjustment(CGF, ThisPtr, SrcRecordTy);
  842. llvm::CallBase *Typeid = emitRTtypeidCall(CGF, ThisPtr.getPointer());
  843. return CGF.Builder.CreateBitCast(Typeid, StdTypeInfoPtrTy);
  844. }
  845. bool MicrosoftCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
  846. QualType SrcRecordTy) {
  847. const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
  848. return SrcIsPtr &&
  849. !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
  850. }
  851. llvm::Value *MicrosoftCXXABI::EmitDynamicCastCall(
  852. CodeGenFunction &CGF, Address This, QualType SrcRecordTy,
  853. QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
  854. llvm::Type *DestLTy = CGF.ConvertType(DestTy);
  855. llvm::Value *SrcRTTI =
  856. CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
  857. llvm::Value *DestRTTI =
  858. CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
  859. llvm::Value *Offset;
  860. std::tie(This, Offset, std::ignore) =
  861. performBaseAdjustment(CGF, This, SrcRecordTy);
  862. llvm::Value *ThisPtr = This.getPointer();
  863. Offset = CGF.Builder.CreateTrunc(Offset, CGF.Int32Ty);
  864. // PVOID __RTDynamicCast(
  865. // PVOID inptr,
  866. // LONG VfDelta,
  867. // PVOID SrcType,
  868. // PVOID TargetType,
  869. // BOOL isReference)
  870. llvm::Type *ArgTypes[] = {CGF.Int8PtrTy, CGF.Int32Ty, CGF.Int8PtrTy,
  871. CGF.Int8PtrTy, CGF.Int32Ty};
  872. llvm::FunctionCallee Function = CGF.CGM.CreateRuntimeFunction(
  873. llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
  874. "__RTDynamicCast");
  875. llvm::Value *Args[] = {
  876. ThisPtr, Offset, SrcRTTI, DestRTTI,
  877. llvm::ConstantInt::get(CGF.Int32Ty, DestTy->isReferenceType())};
  878. ThisPtr = CGF.EmitRuntimeCallOrInvoke(Function, Args);
  879. return CGF.Builder.CreateBitCast(ThisPtr, DestLTy);
  880. }
  881. llvm::Value *
  882. MicrosoftCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
  883. QualType SrcRecordTy,
  884. QualType DestTy) {
  885. std::tie(Value, std::ignore, std::ignore) =
  886. performBaseAdjustment(CGF, Value, SrcRecordTy);
  887. // PVOID __RTCastToVoid(
  888. // PVOID inptr)
  889. llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
  890. llvm::FunctionCallee Function = CGF.CGM.CreateRuntimeFunction(
  891. llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
  892. "__RTCastToVoid");
  893. llvm::Value *Args[] = {Value.getPointer()};
  894. return CGF.EmitRuntimeCall(Function, Args);
  895. }
  896. bool MicrosoftCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
  897. return false;
  898. }
  899. llvm::Value *MicrosoftCXXABI::GetVirtualBaseClassOffset(
  900. CodeGenFunction &CGF, Address This, const CXXRecordDecl *ClassDecl,
  901. const CXXRecordDecl *BaseClassDecl) {
  902. const ASTContext &Context = getContext();
  903. int64_t VBPtrChars =
  904. Context.getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity();
  905. llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
  906. CharUnits IntSize = Context.getTypeSizeInChars(Context.IntTy);
  907. CharUnits VBTableChars =
  908. IntSize *
  909. CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
  910. llvm::Value *VBTableOffset =
  911. llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
  912. llvm::Value *VBPtrToNewBase =
  913. GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
  914. VBPtrToNewBase =
  915. CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
  916. return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
  917. }
  918. bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
  919. return isa<CXXConstructorDecl>(GD.getDecl());
  920. }
  921. static bool isDeletingDtor(GlobalDecl GD) {
  922. return isa<CXXDestructorDecl>(GD.getDecl()) &&
  923. GD.getDtorType() == Dtor_Deleting;
  924. }
  925. bool MicrosoftCXXABI::hasMostDerivedReturn(GlobalDecl GD) const {
  926. return isDeletingDtor(GD);
  927. }
  928. static bool isTrivialForMSVC(const CXXRecordDecl *RD) {
  929. // We use the C++14 definition of an aggregate, so we also
  930. // check for:
  931. // No private or protected non static data members.
  932. // No base classes
  933. // No virtual functions
  934. // Additionally, we need to ensure that there is a trivial copy assignment
  935. // operator, a trivial destructor and no user-provided constructors.
  936. if (RD->hasProtectedFields() || RD->hasPrivateFields())
  937. return false;
  938. if (RD->getNumBases() > 0)
  939. return false;
  940. if (RD->isPolymorphic())
  941. return false;
  942. if (RD->hasNonTrivialCopyAssignment())
  943. return false;
  944. for (const CXXConstructorDecl *Ctor : RD->ctors())
  945. if (Ctor->isUserProvided())
  946. return false;
  947. if (RD->hasNonTrivialDestructor())
  948. return false;
  949. return true;
  950. }
  951. bool MicrosoftCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
  952. const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
  953. if (!RD)
  954. return false;
  955. bool isTrivialForABI = RD->canPassInRegisters() && isTrivialForMSVC(RD);
  956. // MSVC always returns structs indirectly from C++ instance methods.
  957. bool isIndirectReturn = !isTrivialForABI || FI.isInstanceMethod();
  958. if (isIndirectReturn) {
  959. CharUnits Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
  960. FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
  961. // MSVC always passes `this` before the `sret` parameter.
  962. FI.getReturnInfo().setSRetAfterThis(FI.isInstanceMethod());
  963. // On AArch64, use the `inreg` attribute if the object is considered to not
  964. // be trivially copyable, or if this is an instance method struct return.
  965. FI.getReturnInfo().setInReg(CGM.getTarget().getTriple().isAArch64());
  966. return true;
  967. }
  968. // Otherwise, use the C ABI rules.
  969. return false;
  970. }
  971. llvm::BasicBlock *
  972. MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
  973. const CXXRecordDecl *RD) {
  974. llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
  975. assert(IsMostDerivedClass &&
  976. "ctor for a class with virtual bases must have an implicit parameter");
  977. llvm::Value *IsCompleteObject =
  978. CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
  979. llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
  980. llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
  981. CGF.Builder.CreateCondBr(IsCompleteObject,
  982. CallVbaseCtorsBB, SkipVbaseCtorsBB);
  983. CGF.EmitBlock(CallVbaseCtorsBB);
  984. // Fill in the vbtable pointers here.
  985. EmitVBPtrStores(CGF, RD);
  986. // CGF will put the base ctor calls in this basic block for us later.
  987. return SkipVbaseCtorsBB;
  988. }
  989. llvm::BasicBlock *
  990. MicrosoftCXXABI::EmitDtorCompleteObjectHandler(CodeGenFunction &CGF) {
  991. llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
  992. assert(IsMostDerivedClass &&
  993. "ctor for a class with virtual bases must have an implicit parameter");
  994. llvm::Value *IsCompleteObject =
  995. CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
  996. llvm::BasicBlock *CallVbaseDtorsBB = CGF.createBasicBlock("Dtor.dtor_vbases");
  997. llvm::BasicBlock *SkipVbaseDtorsBB = CGF.createBasicBlock("Dtor.skip_vbases");
  998. CGF.Builder.CreateCondBr(IsCompleteObject,
  999. CallVbaseDtorsBB, SkipVbaseDtorsBB);
  1000. CGF.EmitBlock(CallVbaseDtorsBB);
  1001. // CGF will put the base dtor calls in this basic block for us later.
  1002. return SkipVbaseDtorsBB;
  1003. }
  1004. void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
  1005. CodeGenFunction &CGF, const CXXRecordDecl *RD) {
  1006. // In most cases, an override for a vbase virtual method can adjust
  1007. // the "this" parameter by applying a constant offset.
  1008. // However, this is not enough while a constructor or a destructor of some
  1009. // class X is being executed if all the following conditions are met:
  1010. // - X has virtual bases, (1)
  1011. // - X overrides a virtual method M of a vbase Y, (2)
  1012. // - X itself is a vbase of the most derived class.
  1013. //
  1014. // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
  1015. // which holds the extra amount of "this" adjustment we must do when we use
  1016. // the X vftables (i.e. during X ctor or dtor).
  1017. // Outside the ctors and dtors, the values of vtorDisps are zero.
  1018. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
  1019. typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
  1020. const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
  1021. CGBuilderTy &Builder = CGF.Builder;
  1022. unsigned AS = getThisAddress(CGF).getAddressSpace();
  1023. llvm::Value *Int8This = nullptr; // Initialize lazily.
  1024. for (const CXXBaseSpecifier &S : RD->vbases()) {
  1025. const CXXRecordDecl *VBase = S.getType()->getAsCXXRecordDecl();
  1026. auto I = VBaseMap.find(VBase);
  1027. assert(I != VBaseMap.end());
  1028. if (!I->second.hasVtorDisp())
  1029. continue;
  1030. llvm::Value *VBaseOffset =
  1031. GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, VBase);
  1032. uint64_t ConstantVBaseOffset = I->second.VBaseOffset.getQuantity();
  1033. // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
  1034. llvm::Value *VtorDispValue = Builder.CreateSub(
  1035. VBaseOffset, llvm::ConstantInt::get(CGM.PtrDiffTy, ConstantVBaseOffset),
  1036. "vtordisp.value");
  1037. VtorDispValue = Builder.CreateTruncOrBitCast(VtorDispValue, CGF.Int32Ty);
  1038. if (!Int8This)
  1039. Int8This = Builder.CreateBitCast(getThisValue(CGF),
  1040. CGF.Int8Ty->getPointerTo(AS));
  1041. llvm::Value *VtorDispPtr =
  1042. Builder.CreateInBoundsGEP(CGF.Int8Ty, Int8This, VBaseOffset);
  1043. // vtorDisp is always the 32-bits before the vbase in the class layout.
  1044. VtorDispPtr = Builder.CreateConstGEP1_32(CGF.Int8Ty, VtorDispPtr, -4);
  1045. VtorDispPtr = Builder.CreateBitCast(
  1046. VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
  1047. Builder.CreateAlignedStore(VtorDispValue, VtorDispPtr,
  1048. CharUnits::fromQuantity(4));
  1049. }
  1050. }
  1051. static bool hasDefaultCXXMethodCC(ASTContext &Context,
  1052. const CXXMethodDecl *MD) {
  1053. CallingConv ExpectedCallingConv = Context.getDefaultCallingConvention(
  1054. /*IsVariadic=*/false, /*IsCXXMethod=*/true);
  1055. CallingConv ActualCallingConv =
  1056. MD->getType()->castAs<FunctionProtoType>()->getCallConv();
  1057. return ExpectedCallingConv == ActualCallingConv;
  1058. }
  1059. void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
  1060. // There's only one constructor type in this ABI.
  1061. CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
  1062. // Exported default constructors either have a simple call-site where they use
  1063. // the typical calling convention and have a single 'this' pointer for an
  1064. // argument -or- they get a wrapper function which appropriately thunks to the
  1065. // real default constructor. This thunk is the default constructor closure.
  1066. if (D->hasAttr<DLLExportAttr>() && D->isDefaultConstructor() &&
  1067. D->isDefined()) {
  1068. if (!hasDefaultCXXMethodCC(getContext(), D) || D->getNumParams() != 0) {
  1069. llvm::Function *Fn = getAddrOfCXXCtorClosure(D, Ctor_DefaultClosure);
  1070. Fn->setLinkage(llvm::GlobalValue::WeakODRLinkage);
  1071. CGM.setGVProperties(Fn, D);
  1072. }
  1073. }
  1074. }
  1075. void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
  1076. const CXXRecordDecl *RD) {
  1077. Address This = getThisAddress(CGF);
  1078. This = CGF.Builder.CreateElementBitCast(This, CGM.Int8Ty, "this.int8");
  1079. const ASTContext &Context = getContext();
  1080. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  1081. const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
  1082. for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
  1083. const std::unique_ptr<VPtrInfo> &VBT = (*VBGlobals.VBTables)[I];
  1084. llvm::GlobalVariable *GV = VBGlobals.Globals[I];
  1085. const ASTRecordLayout &SubobjectLayout =
  1086. Context.getASTRecordLayout(VBT->IntroducingObject);
  1087. CharUnits Offs = VBT->NonVirtualOffset;
  1088. Offs += SubobjectLayout.getVBPtrOffset();
  1089. if (VBT->getVBaseWithVPtr())
  1090. Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
  1091. Address VBPtr = CGF.Builder.CreateConstInBoundsByteGEP(This, Offs);
  1092. llvm::Value *GVPtr =
  1093. CGF.Builder.CreateConstInBoundsGEP2_32(GV->getValueType(), GV, 0, 0);
  1094. VBPtr = CGF.Builder.CreateElementBitCast(VBPtr, GVPtr->getType(),
  1095. "vbptr." + VBT->ObjectWithVPtr->getName());
  1096. CGF.Builder.CreateStore(GVPtr, VBPtr);
  1097. }
  1098. }
  1099. CGCXXABI::AddedStructorArgCounts
  1100. MicrosoftCXXABI::buildStructorSignature(GlobalDecl GD,
  1101. SmallVectorImpl<CanQualType> &ArgTys) {
  1102. AddedStructorArgCounts Added;
  1103. // TODO: 'for base' flag
  1104. if (isa<CXXDestructorDecl>(GD.getDecl()) &&
  1105. GD.getDtorType() == Dtor_Deleting) {
  1106. // The scalar deleting destructor takes an implicit int parameter.
  1107. ArgTys.push_back(getContext().IntTy);
  1108. ++Added.Suffix;
  1109. }
  1110. auto *CD = dyn_cast<CXXConstructorDecl>(GD.getDecl());
  1111. if (!CD)
  1112. return Added;
  1113. // All parameters are already in place except is_most_derived, which goes
  1114. // after 'this' if it's variadic and last if it's not.
  1115. const CXXRecordDecl *Class = CD->getParent();
  1116. const FunctionProtoType *FPT = CD->getType()->castAs<FunctionProtoType>();
  1117. if (Class->getNumVBases()) {
  1118. if (FPT->isVariadic()) {
  1119. ArgTys.insert(ArgTys.begin() + 1, getContext().IntTy);
  1120. ++Added.Prefix;
  1121. } else {
  1122. ArgTys.push_back(getContext().IntTy);
  1123. ++Added.Suffix;
  1124. }
  1125. }
  1126. return Added;
  1127. }
  1128. void MicrosoftCXXABI::setCXXDestructorDLLStorage(llvm::GlobalValue *GV,
  1129. const CXXDestructorDecl *Dtor,
  1130. CXXDtorType DT) const {
  1131. // Deleting destructor variants are never imported or exported. Give them the
  1132. // default storage class.
  1133. if (DT == Dtor_Deleting) {
  1134. GV->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  1135. } else {
  1136. const NamedDecl *ND = Dtor;
  1137. CGM.setDLLImportDLLExport(GV, ND);
  1138. }
  1139. }
  1140. llvm::GlobalValue::LinkageTypes MicrosoftCXXABI::getCXXDestructorLinkage(
  1141. GVALinkage Linkage, const CXXDestructorDecl *Dtor, CXXDtorType DT) const {
  1142. // Internal things are always internal, regardless of attributes. After this,
  1143. // we know the thunk is externally visible.
  1144. if (Linkage == GVA_Internal)
  1145. return llvm::GlobalValue::InternalLinkage;
  1146. switch (DT) {
  1147. case Dtor_Base:
  1148. // The base destructor most closely tracks the user-declared constructor, so
  1149. // we delegate back to the normal declarator case.
  1150. return CGM.getLLVMLinkageForDeclarator(Dtor, Linkage,
  1151. /*IsConstantVariable=*/false);
  1152. case Dtor_Complete:
  1153. // The complete destructor is like an inline function, but it may be
  1154. // imported and therefore must be exported as well. This requires changing
  1155. // the linkage if a DLL attribute is present.
  1156. if (Dtor->hasAttr<DLLExportAttr>())
  1157. return llvm::GlobalValue::WeakODRLinkage;
  1158. if (Dtor->hasAttr<DLLImportAttr>())
  1159. return llvm::GlobalValue::AvailableExternallyLinkage;
  1160. return llvm::GlobalValue::LinkOnceODRLinkage;
  1161. case Dtor_Deleting:
  1162. // Deleting destructors are like inline functions. They have vague linkage
  1163. // and are emitted everywhere they are used. They are internal if the class
  1164. // is internal.
  1165. return llvm::GlobalValue::LinkOnceODRLinkage;
  1166. case Dtor_Comdat:
  1167. llvm_unreachable("MS C++ ABI does not support comdat dtors");
  1168. }
  1169. llvm_unreachable("invalid dtor type");
  1170. }
  1171. void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
  1172. // The TU defining a dtor is only guaranteed to emit a base destructor. All
  1173. // other destructor variants are delegating thunks.
  1174. CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
  1175. // If the class is dllexported, emit the complete (vbase) destructor wherever
  1176. // the base dtor is emitted.
  1177. // FIXME: To match MSVC, this should only be done when the class is exported
  1178. // with -fdllexport-inlines enabled.
  1179. if (D->getParent()->getNumVBases() > 0 && D->hasAttr<DLLExportAttr>())
  1180. CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
  1181. }
  1182. CharUnits
  1183. MicrosoftCXXABI::getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) {
  1184. const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
  1185. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
  1186. // Complete destructors take a pointer to the complete object as a
  1187. // parameter, thus don't need this adjustment.
  1188. if (GD.getDtorType() == Dtor_Complete)
  1189. return CharUnits();
  1190. // There's no Dtor_Base in vftable but it shares the this adjustment with
  1191. // the deleting one, so look it up instead.
  1192. GD = GlobalDecl(DD, Dtor_Deleting);
  1193. }
  1194. MethodVFTableLocation ML =
  1195. CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
  1196. CharUnits Adjustment = ML.VFPtrOffset;
  1197. // Normal virtual instance methods need to adjust from the vfptr that first
  1198. // defined the virtual method to the virtual base subobject, but destructors
  1199. // do not. The vector deleting destructor thunk applies this adjustment for
  1200. // us if necessary.
  1201. if (isa<CXXDestructorDecl>(MD))
  1202. Adjustment = CharUnits::Zero();
  1203. if (ML.VBase) {
  1204. const ASTRecordLayout &DerivedLayout =
  1205. getContext().getASTRecordLayout(MD->getParent());
  1206. Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
  1207. }
  1208. return Adjustment;
  1209. }
  1210. Address MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall(
  1211. CodeGenFunction &CGF, GlobalDecl GD, Address This,
  1212. bool VirtualCall) {
  1213. if (!VirtualCall) {
  1214. // If the call of a virtual function is not virtual, we just have to
  1215. // compensate for the adjustment the virtual function does in its prologue.
  1216. CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
  1217. if (Adjustment.isZero())
  1218. return This;
  1219. This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty);
  1220. assert(Adjustment.isPositive());
  1221. return CGF.Builder.CreateConstByteGEP(This, Adjustment);
  1222. }
  1223. const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
  1224. GlobalDecl LookupGD = GD;
  1225. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
  1226. // Complete dtors take a pointer to the complete object,
  1227. // thus don't need adjustment.
  1228. if (GD.getDtorType() == Dtor_Complete)
  1229. return This;
  1230. // There's only Dtor_Deleting in vftable but it shares the this adjustment
  1231. // with the base one, so look up the deleting one instead.
  1232. LookupGD = GlobalDecl(DD, Dtor_Deleting);
  1233. }
  1234. MethodVFTableLocation ML =
  1235. CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
  1236. CharUnits StaticOffset = ML.VFPtrOffset;
  1237. // Base destructors expect 'this' to point to the beginning of the base
  1238. // subobject, not the first vfptr that happens to contain the virtual dtor.
  1239. // However, we still need to apply the virtual base adjustment.
  1240. if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
  1241. StaticOffset = CharUnits::Zero();
  1242. Address Result = This;
  1243. if (ML.VBase) {
  1244. Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty);
  1245. const CXXRecordDecl *Derived = MD->getParent();
  1246. const CXXRecordDecl *VBase = ML.VBase;
  1247. llvm::Value *VBaseOffset =
  1248. GetVirtualBaseClassOffset(CGF, Result, Derived, VBase);
  1249. llvm::Value *VBasePtr = CGF.Builder.CreateInBoundsGEP(
  1250. Result.getElementType(), Result.getPointer(), VBaseOffset);
  1251. CharUnits VBaseAlign =
  1252. CGF.CGM.getVBaseAlignment(Result.getAlignment(), Derived, VBase);
  1253. Result = Address(VBasePtr, CGF.Int8Ty, VBaseAlign);
  1254. }
  1255. if (!StaticOffset.isZero()) {
  1256. assert(StaticOffset.isPositive());
  1257. Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty);
  1258. if (ML.VBase) {
  1259. // Non-virtual adjustment might result in a pointer outside the allocated
  1260. // object, e.g. if the final overrider class is laid out after the virtual
  1261. // base that declares a method in the most derived class.
  1262. // FIXME: Update the code that emits this adjustment in thunks prologues.
  1263. Result = CGF.Builder.CreateConstByteGEP(Result, StaticOffset);
  1264. } else {
  1265. Result = CGF.Builder.CreateConstInBoundsByteGEP(Result, StaticOffset);
  1266. }
  1267. }
  1268. return Result;
  1269. }
  1270. void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
  1271. QualType &ResTy,
  1272. FunctionArgList &Params) {
  1273. ASTContext &Context = getContext();
  1274. const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
  1275. assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
  1276. if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
  1277. auto *IsMostDerived = ImplicitParamDecl::Create(
  1278. Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(),
  1279. &Context.Idents.get("is_most_derived"), Context.IntTy,
  1280. ImplicitParamDecl::Other);
  1281. // The 'most_derived' parameter goes second if the ctor is variadic and last
  1282. // if it's not. Dtors can't be variadic.
  1283. const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
  1284. if (FPT->isVariadic())
  1285. Params.insert(Params.begin() + 1, IsMostDerived);
  1286. else
  1287. Params.push_back(IsMostDerived);
  1288. getStructorImplicitParamDecl(CGF) = IsMostDerived;
  1289. } else if (isDeletingDtor(CGF.CurGD)) {
  1290. auto *ShouldDelete = ImplicitParamDecl::Create(
  1291. Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(),
  1292. &Context.Idents.get("should_call_delete"), Context.IntTy,
  1293. ImplicitParamDecl::Other);
  1294. Params.push_back(ShouldDelete);
  1295. getStructorImplicitParamDecl(CGF) = ShouldDelete;
  1296. }
  1297. }
  1298. void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
  1299. // Naked functions have no prolog.
  1300. if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
  1301. return;
  1302. // Overridden virtual methods of non-primary bases need to adjust the incoming
  1303. // 'this' pointer in the prologue. In this hierarchy, C::b will subtract
  1304. // sizeof(void*) to adjust from B* to C*:
  1305. // struct A { virtual void a(); };
  1306. // struct B { virtual void b(); };
  1307. // struct C : A, B { virtual void b(); };
  1308. //
  1309. // Leave the value stored in the 'this' alloca unadjusted, so that the
  1310. // debugger sees the unadjusted value. Microsoft debuggers require this, and
  1311. // will apply the ThisAdjustment in the method type information.
  1312. // FIXME: Do something better for DWARF debuggers, which won't expect this,
  1313. // without making our codegen depend on debug info settings.
  1314. llvm::Value *This = loadIncomingCXXThis(CGF);
  1315. const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
  1316. if (!CGF.CurFuncIsThunk && MD->isVirtual()) {
  1317. CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(CGF.CurGD);
  1318. if (!Adjustment.isZero()) {
  1319. unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
  1320. llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
  1321. *thisTy = This->getType();
  1322. This = CGF.Builder.CreateBitCast(This, charPtrTy);
  1323. assert(Adjustment.isPositive());
  1324. This = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, This,
  1325. -Adjustment.getQuantity());
  1326. This = CGF.Builder.CreateBitCast(This, thisTy, "this.adjusted");
  1327. }
  1328. }
  1329. setCXXABIThisValue(CGF, This);
  1330. // If this is a function that the ABI specifies returns 'this', initialize
  1331. // the return slot to 'this' at the start of the function.
  1332. //
  1333. // Unlike the setting of return types, this is done within the ABI
  1334. // implementation instead of by clients of CGCXXABI because:
  1335. // 1) getThisValue is currently protected
  1336. // 2) in theory, an ABI could implement 'this' returns some other way;
  1337. // HasThisReturn only specifies a contract, not the implementation
  1338. if (HasThisReturn(CGF.CurGD))
  1339. CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
  1340. else if (hasMostDerivedReturn(CGF.CurGD))
  1341. CGF.Builder.CreateStore(CGF.EmitCastToVoidPtr(getThisValue(CGF)),
  1342. CGF.ReturnValue);
  1343. if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
  1344. assert(getStructorImplicitParamDecl(CGF) &&
  1345. "no implicit parameter for a constructor with virtual bases?");
  1346. getStructorImplicitParamValue(CGF)
  1347. = CGF.Builder.CreateLoad(
  1348. CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
  1349. "is_most_derived");
  1350. }
  1351. if (isDeletingDtor(CGF.CurGD)) {
  1352. assert(getStructorImplicitParamDecl(CGF) &&
  1353. "no implicit parameter for a deleting destructor?");
  1354. getStructorImplicitParamValue(CGF)
  1355. = CGF.Builder.CreateLoad(
  1356. CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
  1357. "should_call_delete");
  1358. }
  1359. }
  1360. CGCXXABI::AddedStructorArgs MicrosoftCXXABI::getImplicitConstructorArgs(
  1361. CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
  1362. bool ForVirtualBase, bool Delegating) {
  1363. assert(Type == Ctor_Complete || Type == Ctor_Base);
  1364. // Check if we need a 'most_derived' parameter.
  1365. if (!D->getParent()->getNumVBases())
  1366. return AddedStructorArgs{};
  1367. // Add the 'most_derived' argument second if we are variadic or last if not.
  1368. const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
  1369. llvm::Value *MostDerivedArg;
  1370. if (Delegating) {
  1371. MostDerivedArg = getStructorImplicitParamValue(CGF);
  1372. } else {
  1373. MostDerivedArg = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
  1374. }
  1375. if (FPT->isVariadic()) {
  1376. return AddedStructorArgs::prefix({{MostDerivedArg, getContext().IntTy}});
  1377. }
  1378. return AddedStructorArgs::suffix({{MostDerivedArg, getContext().IntTy}});
  1379. }
  1380. llvm::Value *MicrosoftCXXABI::getCXXDestructorImplicitParam(
  1381. CodeGenFunction &CGF, const CXXDestructorDecl *DD, CXXDtorType Type,
  1382. bool ForVirtualBase, bool Delegating) {
  1383. return nullptr;
  1384. }
  1385. void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
  1386. const CXXDestructorDecl *DD,
  1387. CXXDtorType Type, bool ForVirtualBase,
  1388. bool Delegating, Address This,
  1389. QualType ThisTy) {
  1390. // Use the base destructor variant in place of the complete destructor variant
  1391. // if the class has no virtual bases. This effectively implements some of the
  1392. // -mconstructor-aliases optimization, but as part of the MS C++ ABI.
  1393. if (Type == Dtor_Complete && DD->getParent()->getNumVBases() == 0)
  1394. Type = Dtor_Base;
  1395. GlobalDecl GD(DD, Type);
  1396. CGCallee Callee = CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD), GD);
  1397. if (DD->isVirtual()) {
  1398. assert(Type != CXXDtorType::Dtor_Deleting &&
  1399. "The deleting destructor should only be called via a virtual call");
  1400. This = adjustThisArgumentForVirtualFunctionCall(CGF, GlobalDecl(DD, Type),
  1401. This, false);
  1402. }
  1403. llvm::BasicBlock *BaseDtorEndBB = nullptr;
  1404. if (ForVirtualBase && isa<CXXConstructorDecl>(CGF.CurCodeDecl)) {
  1405. BaseDtorEndBB = EmitDtorCompleteObjectHandler(CGF);
  1406. }
  1407. llvm::Value *Implicit =
  1408. getCXXDestructorImplicitParam(CGF, DD, Type, ForVirtualBase,
  1409. Delegating); // = nullptr
  1410. CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy,
  1411. /*ImplicitParam=*/Implicit,
  1412. /*ImplicitParamTy=*/QualType(), nullptr);
  1413. if (BaseDtorEndBB) {
  1414. // Complete object handler should continue to be the remaining
  1415. CGF.Builder.CreateBr(BaseDtorEndBB);
  1416. CGF.EmitBlock(BaseDtorEndBB);
  1417. }
  1418. }
  1419. void MicrosoftCXXABI::emitVTableTypeMetadata(const VPtrInfo &Info,
  1420. const CXXRecordDecl *RD,
  1421. llvm::GlobalVariable *VTable) {
  1422. if (!CGM.getCodeGenOpts().LTOUnit)
  1423. return;
  1424. // TODO: Should VirtualFunctionElimination also be supported here?
  1425. // See similar handling in CodeGenModule::EmitVTableTypeMetadata.
  1426. if (CGM.getCodeGenOpts().WholeProgramVTables) {
  1427. llvm::DenseSet<const CXXRecordDecl *> Visited;
  1428. llvm::GlobalObject::VCallVisibility TypeVis =
  1429. CGM.GetVCallVisibilityLevel(RD, Visited);
  1430. if (TypeVis != llvm::GlobalObject::VCallVisibilityPublic)
  1431. VTable->setVCallVisibilityMetadata(TypeVis);
  1432. }
  1433. // The location of the first virtual function pointer in the virtual table,
  1434. // aka the "address point" on Itanium. This is at offset 0 if RTTI is
  1435. // disabled, or sizeof(void*) if RTTI is enabled.
  1436. CharUnits AddressPoint =
  1437. getContext().getLangOpts().RTTIData
  1438. ? getContext().toCharUnitsFromBits(
  1439. getContext().getTargetInfo().getPointerWidth(LangAS::Default))
  1440. : CharUnits::Zero();
  1441. if (Info.PathToIntroducingObject.empty()) {
  1442. CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD);
  1443. return;
  1444. }
  1445. // Add a bitset entry for the least derived base belonging to this vftable.
  1446. CGM.AddVTableTypeMetadata(VTable, AddressPoint,
  1447. Info.PathToIntroducingObject.back());
  1448. // Add a bitset entry for each derived class that is laid out at the same
  1449. // offset as the least derived base.
  1450. for (unsigned I = Info.PathToIntroducingObject.size() - 1; I != 0; --I) {
  1451. const CXXRecordDecl *DerivedRD = Info.PathToIntroducingObject[I - 1];
  1452. const CXXRecordDecl *BaseRD = Info.PathToIntroducingObject[I];
  1453. const ASTRecordLayout &Layout =
  1454. getContext().getASTRecordLayout(DerivedRD);
  1455. CharUnits Offset;
  1456. auto VBI = Layout.getVBaseOffsetsMap().find(BaseRD);
  1457. if (VBI == Layout.getVBaseOffsetsMap().end())
  1458. Offset = Layout.getBaseClassOffset(BaseRD);
  1459. else
  1460. Offset = VBI->second.VBaseOffset;
  1461. if (!Offset.isZero())
  1462. return;
  1463. CGM.AddVTableTypeMetadata(VTable, AddressPoint, DerivedRD);
  1464. }
  1465. // Finally do the same for the most derived class.
  1466. if (Info.FullOffsetInMDC.isZero())
  1467. CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD);
  1468. }
  1469. void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
  1470. const CXXRecordDecl *RD) {
  1471. MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
  1472. const VPtrInfoVector &VFPtrs = VFTContext.getVFPtrOffsets(RD);
  1473. for (const std::unique_ptr<VPtrInfo>& Info : VFPtrs) {
  1474. llvm::GlobalVariable *VTable = getAddrOfVTable(RD, Info->FullOffsetInMDC);
  1475. if (VTable->hasInitializer())
  1476. continue;
  1477. const VTableLayout &VTLayout =
  1478. VFTContext.getVFTableLayout(RD, Info->FullOffsetInMDC);
  1479. llvm::Constant *RTTI = nullptr;
  1480. if (any_of(VTLayout.vtable_components(),
  1481. [](const VTableComponent &VTC) { return VTC.isRTTIKind(); }))
  1482. RTTI = getMSCompleteObjectLocator(RD, *Info);
  1483. ConstantInitBuilder builder(CGM);
  1484. auto components = builder.beginStruct();
  1485. CGVT.createVTableInitializer(components, VTLayout, RTTI,
  1486. VTable->hasLocalLinkage());
  1487. components.finishAndSetAsInitializer(VTable);
  1488. emitVTableTypeMetadata(*Info, RD, VTable);
  1489. }
  1490. }
  1491. bool MicrosoftCXXABI::isVirtualOffsetNeededForVTableField(
  1492. CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
  1493. return Vptr.NearestVBase != nullptr;
  1494. }
  1495. llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
  1496. CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
  1497. const CXXRecordDecl *NearestVBase) {
  1498. llvm::Constant *VTableAddressPoint = getVTableAddressPoint(Base, VTableClass);
  1499. if (!VTableAddressPoint) {
  1500. assert(Base.getBase()->getNumVBases() &&
  1501. !getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
  1502. }
  1503. return VTableAddressPoint;
  1504. }
  1505. static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
  1506. const CXXRecordDecl *RD, const VPtrInfo &VFPtr,
  1507. SmallString<256> &Name) {
  1508. llvm::raw_svector_ostream Out(Name);
  1509. MangleContext.mangleCXXVFTable(RD, VFPtr.MangledPath, Out);
  1510. }
  1511. llvm::Constant *
  1512. MicrosoftCXXABI::getVTableAddressPoint(BaseSubobject Base,
  1513. const CXXRecordDecl *VTableClass) {
  1514. (void)getAddrOfVTable(VTableClass, Base.getBaseOffset());
  1515. VFTableIdTy ID(VTableClass, Base.getBaseOffset());
  1516. return VFTablesMap[ID];
  1517. }
  1518. llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
  1519. BaseSubobject Base, const CXXRecordDecl *VTableClass) {
  1520. llvm::Constant *VFTable = getVTableAddressPoint(Base, VTableClass);
  1521. assert(VFTable && "Couldn't find a vftable for the given base?");
  1522. return VFTable;
  1523. }
  1524. llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
  1525. CharUnits VPtrOffset) {
  1526. // getAddrOfVTable may return 0 if asked to get an address of a vtable which
  1527. // shouldn't be used in the given record type. We want to cache this result in
  1528. // VFTablesMap, thus a simple zero check is not sufficient.
  1529. VFTableIdTy ID(RD, VPtrOffset);
  1530. VTablesMapTy::iterator I;
  1531. bool Inserted;
  1532. std::tie(I, Inserted) = VTablesMap.insert(std::make_pair(ID, nullptr));
  1533. if (!Inserted)
  1534. return I->second;
  1535. llvm::GlobalVariable *&VTable = I->second;
  1536. MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
  1537. const VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD);
  1538. if (DeferredVFTables.insert(RD).second) {
  1539. // We haven't processed this record type before.
  1540. // Queue up this vtable for possible deferred emission.
  1541. CGM.addDeferredVTable(RD);
  1542. #ifndef NDEBUG
  1543. // Create all the vftables at once in order to make sure each vftable has
  1544. // a unique mangled name.
  1545. llvm::StringSet<> ObservedMangledNames;
  1546. for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
  1547. SmallString<256> Name;
  1548. mangleVFTableName(getMangleContext(), RD, *VFPtrs[J], Name);
  1549. if (!ObservedMangledNames.insert(Name.str()).second)
  1550. llvm_unreachable("Already saw this mangling before?");
  1551. }
  1552. #endif
  1553. }
  1554. const std::unique_ptr<VPtrInfo> *VFPtrI =
  1555. llvm::find_if(VFPtrs, [&](const std::unique_ptr<VPtrInfo> &VPI) {
  1556. return VPI->FullOffsetInMDC == VPtrOffset;
  1557. });
  1558. if (VFPtrI == VFPtrs.end()) {
  1559. VFTablesMap[ID] = nullptr;
  1560. return nullptr;
  1561. }
  1562. const std::unique_ptr<VPtrInfo> &VFPtr = *VFPtrI;
  1563. SmallString<256> VFTableName;
  1564. mangleVFTableName(getMangleContext(), RD, *VFPtr, VFTableName);
  1565. // Classes marked __declspec(dllimport) need vftables generated on the
  1566. // import-side in order to support features like constexpr. No other
  1567. // translation unit relies on the emission of the local vftable, translation
  1568. // units are expected to generate them as needed.
  1569. //
  1570. // Because of this unique behavior, we maintain this logic here instead of
  1571. // getVTableLinkage.
  1572. llvm::GlobalValue::LinkageTypes VFTableLinkage =
  1573. RD->hasAttr<DLLImportAttr>() ? llvm::GlobalValue::LinkOnceODRLinkage
  1574. : CGM.getVTableLinkage(RD);
  1575. bool VFTableComesFromAnotherTU =
  1576. llvm::GlobalValue::isAvailableExternallyLinkage(VFTableLinkage) ||
  1577. llvm::GlobalValue::isExternalLinkage(VFTableLinkage);
  1578. bool VTableAliasIsRequred =
  1579. !VFTableComesFromAnotherTU && getContext().getLangOpts().RTTIData;
  1580. if (llvm::GlobalValue *VFTable =
  1581. CGM.getModule().getNamedGlobal(VFTableName)) {
  1582. VFTablesMap[ID] = VFTable;
  1583. VTable = VTableAliasIsRequred
  1584. ? cast<llvm::GlobalVariable>(
  1585. cast<llvm::GlobalAlias>(VFTable)->getAliaseeObject())
  1586. : cast<llvm::GlobalVariable>(VFTable);
  1587. return VTable;
  1588. }
  1589. const VTableLayout &VTLayout =
  1590. VTContext.getVFTableLayout(RD, VFPtr->FullOffsetInMDC);
  1591. llvm::GlobalValue::LinkageTypes VTableLinkage =
  1592. VTableAliasIsRequred ? llvm::GlobalValue::PrivateLinkage : VFTableLinkage;
  1593. StringRef VTableName = VTableAliasIsRequred ? StringRef() : VFTableName.str();
  1594. llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
  1595. // Create a backing variable for the contents of VTable. The VTable may
  1596. // or may not include space for a pointer to RTTI data.
  1597. llvm::GlobalValue *VFTable;
  1598. VTable = new llvm::GlobalVariable(CGM.getModule(), VTableType,
  1599. /*isConstant=*/true, VTableLinkage,
  1600. /*Initializer=*/nullptr, VTableName);
  1601. VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1602. llvm::Comdat *C = nullptr;
  1603. if (!VFTableComesFromAnotherTU &&
  1604. (llvm::GlobalValue::isWeakForLinker(VFTableLinkage) ||
  1605. (llvm::GlobalValue::isLocalLinkage(VFTableLinkage) &&
  1606. VTableAliasIsRequred)))
  1607. C = CGM.getModule().getOrInsertComdat(VFTableName.str());
  1608. // Only insert a pointer into the VFTable for RTTI data if we are not
  1609. // importing it. We never reference the RTTI data directly so there is no
  1610. // need to make room for it.
  1611. if (VTableAliasIsRequred) {
  1612. llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.Int32Ty, 0),
  1613. llvm::ConstantInt::get(CGM.Int32Ty, 0),
  1614. llvm::ConstantInt::get(CGM.Int32Ty, 1)};
  1615. // Create a GEP which points just after the first entry in the VFTable,
  1616. // this should be the location of the first virtual method.
  1617. llvm::Constant *VTableGEP = llvm::ConstantExpr::getInBoundsGetElementPtr(
  1618. VTable->getValueType(), VTable, GEPIndices);
  1619. if (llvm::GlobalValue::isWeakForLinker(VFTableLinkage)) {
  1620. VFTableLinkage = llvm::GlobalValue::ExternalLinkage;
  1621. if (C)
  1622. C->setSelectionKind(llvm::Comdat::Largest);
  1623. }
  1624. VFTable = llvm::GlobalAlias::create(CGM.Int8PtrTy,
  1625. /*AddressSpace=*/0, VFTableLinkage,
  1626. VFTableName.str(), VTableGEP,
  1627. &CGM.getModule());
  1628. VFTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1629. } else {
  1630. // We don't need a GlobalAlias to be a symbol for the VTable if we won't
  1631. // be referencing any RTTI data.
  1632. // The GlobalVariable will end up being an appropriate definition of the
  1633. // VFTable.
  1634. VFTable = VTable;
  1635. }
  1636. if (C)
  1637. VTable->setComdat(C);
  1638. if (RD->hasAttr<DLLExportAttr>())
  1639. VFTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  1640. VFTablesMap[ID] = VFTable;
  1641. return VTable;
  1642. }
  1643. CGCallee MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
  1644. GlobalDecl GD,
  1645. Address This,
  1646. llvm::Type *Ty,
  1647. SourceLocation Loc) {
  1648. CGBuilderTy &Builder = CGF.Builder;
  1649. Ty = Ty->getPointerTo();
  1650. Address VPtr =
  1651. adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
  1652. auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
  1653. llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty->getPointerTo(),
  1654. MethodDecl->getParent());
  1655. MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
  1656. MethodVFTableLocation ML = VFTContext.getMethodVFTableLocation(GD);
  1657. // Compute the identity of the most derived class whose virtual table is
  1658. // located at the MethodVFTableLocation ML.
  1659. auto getObjectWithVPtr = [&] {
  1660. return llvm::find_if(VFTContext.getVFPtrOffsets(
  1661. ML.VBase ? ML.VBase : MethodDecl->getParent()),
  1662. [&](const std::unique_ptr<VPtrInfo> &Info) {
  1663. return Info->FullOffsetInMDC == ML.VFPtrOffset;
  1664. })
  1665. ->get()
  1666. ->ObjectWithVPtr;
  1667. };
  1668. llvm::Value *VFunc;
  1669. if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
  1670. VFunc = CGF.EmitVTableTypeCheckedLoad(
  1671. getObjectWithVPtr(), VTable, Ty,
  1672. ML.Index *
  1673. CGM.getContext().getTargetInfo().getPointerWidth(LangAS::Default) /
  1674. 8);
  1675. } else {
  1676. if (CGM.getCodeGenOpts().PrepareForLTO)
  1677. CGF.EmitTypeMetadataCodeForVCall(getObjectWithVPtr(), VTable, Loc);
  1678. llvm::Value *VFuncPtr =
  1679. Builder.CreateConstInBoundsGEP1_64(Ty, VTable, ML.Index, "vfn");
  1680. VFunc = Builder.CreateAlignedLoad(Ty, VFuncPtr, CGF.getPointerAlign());
  1681. }
  1682. CGCallee Callee(GD, VFunc);
  1683. return Callee;
  1684. }
  1685. llvm::Value *MicrosoftCXXABI::EmitVirtualDestructorCall(
  1686. CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
  1687. Address This, DeleteOrMemberCallExpr E) {
  1688. auto *CE = E.dyn_cast<const CXXMemberCallExpr *>();
  1689. auto *D = E.dyn_cast<const CXXDeleteExpr *>();
  1690. assert((CE != nullptr) ^ (D != nullptr));
  1691. assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
  1692. assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
  1693. // We have only one destructor in the vftable but can get both behaviors
  1694. // by passing an implicit int parameter.
  1695. GlobalDecl GD(Dtor, Dtor_Deleting);
  1696. const CGFunctionInfo *FInfo =
  1697. &CGM.getTypes().arrangeCXXStructorDeclaration(GD);
  1698. llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
  1699. CGCallee Callee = CGCallee::forVirtual(CE, GD, This, Ty);
  1700. ASTContext &Context = getContext();
  1701. llvm::Value *ImplicitParam = llvm::ConstantInt::get(
  1702. llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
  1703. DtorType == Dtor_Deleting);
  1704. QualType ThisTy;
  1705. if (CE) {
  1706. ThisTy = CE->getObjectType();
  1707. } else {
  1708. ThisTy = D->getDestroyedType();
  1709. }
  1710. This = adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
  1711. RValue RV = CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy,
  1712. ImplicitParam, Context.IntTy, CE);
  1713. return RV.getScalarVal();
  1714. }
  1715. const VBTableGlobals &
  1716. MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) {
  1717. // At this layer, we can key the cache off of a single class, which is much
  1718. // easier than caching each vbtable individually.
  1719. llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry;
  1720. bool Added;
  1721. std::tie(Entry, Added) =
  1722. VBTablesMap.insert(std::make_pair(RD, VBTableGlobals()));
  1723. VBTableGlobals &VBGlobals = Entry->second;
  1724. if (!Added)
  1725. return VBGlobals;
  1726. MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
  1727. VBGlobals.VBTables = &Context.enumerateVBTables(RD);
  1728. // Cache the globals for all vbtables so we don't have to recompute the
  1729. // mangled names.
  1730. llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
  1731. for (VPtrInfoVector::const_iterator I = VBGlobals.VBTables->begin(),
  1732. E = VBGlobals.VBTables->end();
  1733. I != E; ++I) {
  1734. VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage));
  1735. }
  1736. return VBGlobals;
  1737. }
  1738. llvm::Function *
  1739. MicrosoftCXXABI::EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
  1740. const MethodVFTableLocation &ML) {
  1741. assert(!isa<CXXConstructorDecl>(MD) && !isa<CXXDestructorDecl>(MD) &&
  1742. "can't form pointers to ctors or virtual dtors");
  1743. // Calculate the mangled name.
  1744. SmallString<256> ThunkName;
  1745. llvm::raw_svector_ostream Out(ThunkName);
  1746. getMangleContext().mangleVirtualMemPtrThunk(MD, ML, Out);
  1747. // If the thunk has been generated previously, just return it.
  1748. if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
  1749. return cast<llvm::Function>(GV);
  1750. // Create the llvm::Function.
  1751. const CGFunctionInfo &FnInfo =
  1752. CGM.getTypes().arrangeUnprototypedMustTailThunk(MD);
  1753. llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
  1754. llvm::Function *ThunkFn =
  1755. llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
  1756. ThunkName.str(), &CGM.getModule());
  1757. assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
  1758. ThunkFn->setLinkage(MD->isExternallyVisible()
  1759. ? llvm::GlobalValue::LinkOnceODRLinkage
  1760. : llvm::GlobalValue::InternalLinkage);
  1761. if (MD->isExternallyVisible())
  1762. ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
  1763. CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn, /*IsThunk=*/false);
  1764. CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
  1765. // Add the "thunk" attribute so that LLVM knows that the return type is
  1766. // meaningless. These thunks can be used to call functions with differing
  1767. // return types, and the caller is required to cast the prototype
  1768. // appropriately to extract the correct value.
  1769. ThunkFn->addFnAttr("thunk");
  1770. // These thunks can be compared, so they are not unnamed.
  1771. ThunkFn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None);
  1772. // Start codegen.
  1773. CodeGenFunction CGF(CGM);
  1774. CGF.CurGD = GlobalDecl(MD);
  1775. CGF.CurFuncIsThunk = true;
  1776. // Build FunctionArgs, but only include the implicit 'this' parameter
  1777. // declaration.
  1778. FunctionArgList FunctionArgs;
  1779. buildThisParam(CGF, FunctionArgs);
  1780. // Start defining the function.
  1781. CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
  1782. FunctionArgs, MD->getLocation(), SourceLocation());
  1783. ApplyDebugLocation AL(CGF, MD->getLocation());
  1784. setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
  1785. // Load the vfptr and then callee from the vftable. The callee should have
  1786. // adjusted 'this' so that the vfptr is at offset zero.
  1787. llvm::Type *ThunkPtrTy = ThunkTy->getPointerTo();
  1788. llvm::Value *VTable = CGF.GetVTablePtr(
  1789. getThisAddress(CGF), ThunkPtrTy->getPointerTo(), MD->getParent());
  1790. llvm::Value *VFuncPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
  1791. ThunkPtrTy, VTable, ML.Index, "vfn");
  1792. llvm::Value *Callee =
  1793. CGF.Builder.CreateAlignedLoad(ThunkPtrTy, VFuncPtr, CGF.getPointerAlign());
  1794. CGF.EmitMustTailThunk(MD, getThisValue(CGF), {ThunkTy, Callee});
  1795. return ThunkFn;
  1796. }
  1797. void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
  1798. const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
  1799. for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
  1800. const std::unique_ptr<VPtrInfo>& VBT = (*VBGlobals.VBTables)[I];
  1801. llvm::GlobalVariable *GV = VBGlobals.Globals[I];
  1802. if (GV->isDeclaration())
  1803. emitVBTableDefinition(*VBT, RD, GV);
  1804. }
  1805. }
  1806. llvm::GlobalVariable *
  1807. MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
  1808. llvm::GlobalVariable::LinkageTypes Linkage) {
  1809. SmallString<256> OutName;
  1810. llvm::raw_svector_ostream Out(OutName);
  1811. getMangleContext().mangleCXXVBTable(RD, VBT.MangledPath, Out);
  1812. StringRef Name = OutName.str();
  1813. llvm::ArrayType *VBTableType =
  1814. llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ObjectWithVPtr->getNumVBases());
  1815. assert(!CGM.getModule().getNamedGlobal(Name) &&
  1816. "vbtable with this name already exists: mangling bug?");
  1817. CharUnits Alignment =
  1818. CGM.getContext().getTypeAlignInChars(CGM.getContext().IntTy);
  1819. llvm::GlobalVariable *GV = CGM.CreateOrReplaceCXXRuntimeVariable(
  1820. Name, VBTableType, Linkage, Alignment.getAsAlign());
  1821. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1822. if (RD->hasAttr<DLLImportAttr>())
  1823. GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  1824. else if (RD->hasAttr<DLLExportAttr>())
  1825. GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  1826. if (!GV->hasExternalLinkage())
  1827. emitVBTableDefinition(VBT, RD, GV);
  1828. return GV;
  1829. }
  1830. void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo &VBT,
  1831. const CXXRecordDecl *RD,
  1832. llvm::GlobalVariable *GV) const {
  1833. const CXXRecordDecl *ObjectWithVPtr = VBT.ObjectWithVPtr;
  1834. assert(RD->getNumVBases() && ObjectWithVPtr->getNumVBases() &&
  1835. "should only emit vbtables for classes with vbtables");
  1836. const ASTRecordLayout &BaseLayout =
  1837. getContext().getASTRecordLayout(VBT.IntroducingObject);
  1838. const ASTRecordLayout &DerivedLayout = getContext().getASTRecordLayout(RD);
  1839. SmallVector<llvm::Constant *, 4> Offsets(1 + ObjectWithVPtr->getNumVBases(),
  1840. nullptr);
  1841. // The offset from ObjectWithVPtr's vbptr to itself always leads.
  1842. CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset();
  1843. Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity());
  1844. MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
  1845. for (const auto &I : ObjectWithVPtr->vbases()) {
  1846. const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
  1847. CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase);
  1848. assert(!Offset.isNegative());
  1849. // Make it relative to the subobject vbptr.
  1850. CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset;
  1851. if (VBT.getVBaseWithVPtr())
  1852. CompleteVBPtrOffset +=
  1853. DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVPtr());
  1854. Offset -= CompleteVBPtrOffset;
  1855. unsigned VBIndex = Context.getVBTableIndex(ObjectWithVPtr, VBase);
  1856. assert(Offsets[VBIndex] == nullptr && "The same vbindex seen twice?");
  1857. Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity());
  1858. }
  1859. assert(Offsets.size() ==
  1860. cast<llvm::ArrayType>(GV->getValueType())->getNumElements());
  1861. llvm::ArrayType *VBTableType =
  1862. llvm::ArrayType::get(CGM.IntTy, Offsets.size());
  1863. llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets);
  1864. GV->setInitializer(Init);
  1865. if (RD->hasAttr<DLLImportAttr>())
  1866. GV->setLinkage(llvm::GlobalVariable::AvailableExternallyLinkage);
  1867. }
  1868. llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
  1869. Address This,
  1870. const ThisAdjustment &TA) {
  1871. if (TA.isEmpty())
  1872. return This.getPointer();
  1873. This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty);
  1874. llvm::Value *V;
  1875. if (TA.Virtual.isEmpty()) {
  1876. V = This.getPointer();
  1877. } else {
  1878. assert(TA.Virtual.Microsoft.VtordispOffset < 0);
  1879. // Adjust the this argument based on the vtordisp value.
  1880. Address VtorDispPtr =
  1881. CGF.Builder.CreateConstInBoundsByteGEP(This,
  1882. CharUnits::fromQuantity(TA.Virtual.Microsoft.VtordispOffset));
  1883. VtorDispPtr = CGF.Builder.CreateElementBitCast(VtorDispPtr, CGF.Int32Ty);
  1884. llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
  1885. V = CGF.Builder.CreateGEP(This.getElementType(), This.getPointer(),
  1886. CGF.Builder.CreateNeg(VtorDisp));
  1887. // Unfortunately, having applied the vtordisp means that we no
  1888. // longer really have a known alignment for the vbptr step.
  1889. // We'll assume the vbptr is pointer-aligned.
  1890. if (TA.Virtual.Microsoft.VBPtrOffset) {
  1891. // If the final overrider is defined in a virtual base other than the one
  1892. // that holds the vfptr, we have to use a vtordispex thunk which looks up
  1893. // the vbtable of the derived class.
  1894. assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
  1895. assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
  1896. llvm::Value *VBPtr;
  1897. llvm::Value *VBaseOffset = GetVBaseOffsetFromVBPtr(
  1898. CGF, Address(V, CGF.Int8Ty, CGF.getPointerAlign()),
  1899. -TA.Virtual.Microsoft.VBPtrOffset,
  1900. TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
  1901. V = CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, VBPtr, VBaseOffset);
  1902. }
  1903. }
  1904. if (TA.NonVirtual) {
  1905. // Non-virtual adjustment might result in a pointer outside the allocated
  1906. // object, e.g. if the final overrider class is laid out after the virtual
  1907. // base that declares a method in the most derived class.
  1908. V = CGF.Builder.CreateConstGEP1_32(CGF.Int8Ty, V, TA.NonVirtual);
  1909. }
  1910. // Don't need to bitcast back, the call CodeGen will handle this.
  1911. return V;
  1912. }
  1913. llvm::Value *
  1914. MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
  1915. const ReturnAdjustment &RA) {
  1916. if (RA.isEmpty())
  1917. return Ret.getPointer();
  1918. auto OrigTy = Ret.getType();
  1919. Ret = CGF.Builder.CreateElementBitCast(Ret, CGF.Int8Ty);
  1920. llvm::Value *V = Ret.getPointer();
  1921. if (RA.Virtual.Microsoft.VBIndex) {
  1922. assert(RA.Virtual.Microsoft.VBIndex > 0);
  1923. int32_t IntSize = CGF.getIntSize().getQuantity();
  1924. llvm::Value *VBPtr;
  1925. llvm::Value *VBaseOffset =
  1926. GetVBaseOffsetFromVBPtr(CGF, Ret, RA.Virtual.Microsoft.VBPtrOffset,
  1927. IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
  1928. V = CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, VBPtr, VBaseOffset);
  1929. }
  1930. if (RA.NonVirtual)
  1931. V = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, V, RA.NonVirtual);
  1932. // Cast back to the original type.
  1933. return CGF.Builder.CreateBitCast(V, OrigTy);
  1934. }
  1935. bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
  1936. QualType elementType) {
  1937. // Microsoft seems to completely ignore the possibility of a
  1938. // two-argument usual deallocation function.
  1939. return elementType.isDestructedType();
  1940. }
  1941. bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
  1942. // Microsoft seems to completely ignore the possibility of a
  1943. // two-argument usual deallocation function.
  1944. return expr->getAllocatedType().isDestructedType();
  1945. }
  1946. CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
  1947. // The array cookie is always a size_t; we then pad that out to the
  1948. // alignment of the element type.
  1949. ASTContext &Ctx = getContext();
  1950. return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
  1951. Ctx.getTypeAlignInChars(type));
  1952. }
  1953. llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
  1954. Address allocPtr,
  1955. CharUnits cookieSize) {
  1956. Address numElementsPtr =
  1957. CGF.Builder.CreateElementBitCast(allocPtr, CGF.SizeTy);
  1958. return CGF.Builder.CreateLoad(numElementsPtr);
  1959. }
  1960. Address MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
  1961. Address newPtr,
  1962. llvm::Value *numElements,
  1963. const CXXNewExpr *expr,
  1964. QualType elementType) {
  1965. assert(requiresArrayCookie(expr));
  1966. // The size of the cookie.
  1967. CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
  1968. // Compute an offset to the cookie.
  1969. Address cookiePtr = newPtr;
  1970. // Write the number of elements into the appropriate slot.
  1971. Address numElementsPtr
  1972. = CGF.Builder.CreateElementBitCast(cookiePtr, CGF.SizeTy);
  1973. CGF.Builder.CreateStore(numElements, numElementsPtr);
  1974. // Finally, compute a pointer to the actual data buffer by skipping
  1975. // over the cookie completely.
  1976. return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
  1977. }
  1978. static void emitGlobalDtorWithTLRegDtor(CodeGenFunction &CGF, const VarDecl &VD,
  1979. llvm::FunctionCallee Dtor,
  1980. llvm::Constant *Addr) {
  1981. // Create a function which calls the destructor.
  1982. llvm::Constant *DtorStub = CGF.createAtExitStub(VD, Dtor, Addr);
  1983. // extern "C" int __tlregdtor(void (*f)(void));
  1984. llvm::FunctionType *TLRegDtorTy = llvm::FunctionType::get(
  1985. CGF.IntTy, DtorStub->getType(), /*isVarArg=*/false);
  1986. llvm::FunctionCallee TLRegDtor = CGF.CGM.CreateRuntimeFunction(
  1987. TLRegDtorTy, "__tlregdtor", llvm::AttributeList(), /*Local=*/true);
  1988. if (llvm::Function *TLRegDtorFn =
  1989. dyn_cast<llvm::Function>(TLRegDtor.getCallee()))
  1990. TLRegDtorFn->setDoesNotThrow();
  1991. CGF.EmitNounwindRuntimeCall(TLRegDtor, DtorStub);
  1992. }
  1993. void MicrosoftCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
  1994. llvm::FunctionCallee Dtor,
  1995. llvm::Constant *Addr) {
  1996. if (D.isNoDestroy(CGM.getContext()))
  1997. return;
  1998. if (D.getTLSKind())
  1999. return emitGlobalDtorWithTLRegDtor(CGF, D, Dtor, Addr);
  2000. // HLSL doesn't support atexit.
  2001. if (CGM.getLangOpts().HLSL)
  2002. return CGM.AddCXXDtorEntry(Dtor, Addr);
  2003. // The default behavior is to use atexit.
  2004. CGF.registerGlobalDtorWithAtExit(D, Dtor, Addr);
  2005. }
  2006. void MicrosoftCXXABI::EmitThreadLocalInitFuncs(
  2007. CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
  2008. ArrayRef<llvm::Function *> CXXThreadLocalInits,
  2009. ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
  2010. if (CXXThreadLocalInits.empty())
  2011. return;
  2012. CGM.AppendLinkerOptions(CGM.getTarget().getTriple().getArch() ==
  2013. llvm::Triple::x86
  2014. ? "/include:___dyn_tls_init@12"
  2015. : "/include:__dyn_tls_init");
  2016. // This will create a GV in the .CRT$XDU section. It will point to our
  2017. // initialization function. The CRT will call all of these function
  2018. // pointers at start-up time and, eventually, at thread-creation time.
  2019. auto AddToXDU = [&CGM](llvm::Function *InitFunc) {
  2020. llvm::GlobalVariable *InitFuncPtr = new llvm::GlobalVariable(
  2021. CGM.getModule(), InitFunc->getType(), /*isConstant=*/true,
  2022. llvm::GlobalVariable::InternalLinkage, InitFunc,
  2023. Twine(InitFunc->getName(), "$initializer$"));
  2024. InitFuncPtr->setSection(".CRT$XDU");
  2025. // This variable has discardable linkage, we have to add it to @llvm.used to
  2026. // ensure it won't get discarded.
  2027. CGM.addUsedGlobal(InitFuncPtr);
  2028. return InitFuncPtr;
  2029. };
  2030. std::vector<llvm::Function *> NonComdatInits;
  2031. for (size_t I = 0, E = CXXThreadLocalInitVars.size(); I != E; ++I) {
  2032. llvm::GlobalVariable *GV = cast<llvm::GlobalVariable>(
  2033. CGM.GetGlobalValue(CGM.getMangledName(CXXThreadLocalInitVars[I])));
  2034. llvm::Function *F = CXXThreadLocalInits[I];
  2035. // If the GV is already in a comdat group, then we have to join it.
  2036. if (llvm::Comdat *C = GV->getComdat())
  2037. AddToXDU(F)->setComdat(C);
  2038. else
  2039. NonComdatInits.push_back(F);
  2040. }
  2041. if (!NonComdatInits.empty()) {
  2042. llvm::FunctionType *FTy =
  2043. llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
  2044. llvm::Function *InitFunc = CGM.CreateGlobalInitOrCleanUpFunction(
  2045. FTy, "__tls_init", CGM.getTypes().arrangeNullaryFunction(),
  2046. SourceLocation(), /*TLS=*/true);
  2047. CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, NonComdatInits);
  2048. AddToXDU(InitFunc);
  2049. }
  2050. }
  2051. static llvm::GlobalValue *getTlsGuardVar(CodeGenModule &CGM) {
  2052. // __tls_guard comes from the MSVC runtime and reflects
  2053. // whether TLS has been initialized for a particular thread.
  2054. // It is set from within __dyn_tls_init by the runtime.
  2055. // Every library and executable has its own variable.
  2056. llvm::Type *VTy = llvm::Type::getInt8Ty(CGM.getLLVMContext());
  2057. llvm::Constant *TlsGuardConstant =
  2058. CGM.CreateRuntimeVariable(VTy, "__tls_guard");
  2059. llvm::GlobalValue *TlsGuard = cast<llvm::GlobalValue>(TlsGuardConstant);
  2060. TlsGuard->setThreadLocal(true);
  2061. return TlsGuard;
  2062. }
  2063. static llvm::FunctionCallee getDynTlsOnDemandInitFn(CodeGenModule &CGM) {
  2064. // __dyn_tls_on_demand_init comes from the MSVC runtime and triggers
  2065. // dynamic TLS initialization by calling __dyn_tls_init internally.
  2066. llvm::FunctionType *FTy =
  2067. llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()), {},
  2068. /*isVarArg=*/false);
  2069. return CGM.CreateRuntimeFunction(
  2070. FTy, "__dyn_tls_on_demand_init",
  2071. llvm::AttributeList::get(CGM.getLLVMContext(),
  2072. llvm::AttributeList::FunctionIndex,
  2073. llvm::Attribute::NoUnwind),
  2074. /*Local=*/true);
  2075. }
  2076. static void emitTlsGuardCheck(CodeGenFunction &CGF, llvm::GlobalValue *TlsGuard,
  2077. llvm::BasicBlock *DynInitBB,
  2078. llvm::BasicBlock *ContinueBB) {
  2079. llvm::LoadInst *TlsGuardValue =
  2080. CGF.Builder.CreateLoad(Address(TlsGuard, CGF.Int8Ty, CharUnits::One()));
  2081. llvm::Value *CmpResult =
  2082. CGF.Builder.CreateICmpEQ(TlsGuardValue, CGF.Builder.getInt8(0));
  2083. CGF.Builder.CreateCondBr(CmpResult, DynInitBB, ContinueBB);
  2084. }
  2085. static void emitDynamicTlsInitializationCall(CodeGenFunction &CGF,
  2086. llvm::GlobalValue *TlsGuard,
  2087. llvm::BasicBlock *ContinueBB) {
  2088. llvm::FunctionCallee Initializer = getDynTlsOnDemandInitFn(CGF.CGM);
  2089. llvm::Function *InitializerFunction =
  2090. cast<llvm::Function>(Initializer.getCallee());
  2091. llvm::CallInst *CallVal = CGF.Builder.CreateCall(InitializerFunction);
  2092. CallVal->setCallingConv(InitializerFunction->getCallingConv());
  2093. CGF.Builder.CreateBr(ContinueBB);
  2094. }
  2095. static void emitDynamicTlsInitialization(CodeGenFunction &CGF) {
  2096. llvm::BasicBlock *DynInitBB =
  2097. CGF.createBasicBlock("dyntls.dyn_init", CGF.CurFn);
  2098. llvm::BasicBlock *ContinueBB =
  2099. CGF.createBasicBlock("dyntls.continue", CGF.CurFn);
  2100. llvm::GlobalValue *TlsGuard = getTlsGuardVar(CGF.CGM);
  2101. emitTlsGuardCheck(CGF, TlsGuard, DynInitBB, ContinueBB);
  2102. CGF.Builder.SetInsertPoint(DynInitBB);
  2103. emitDynamicTlsInitializationCall(CGF, TlsGuard, ContinueBB);
  2104. CGF.Builder.SetInsertPoint(ContinueBB);
  2105. }
  2106. LValue MicrosoftCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
  2107. const VarDecl *VD,
  2108. QualType LValType) {
  2109. // Dynamic TLS initialization works by checking the state of a
  2110. // guard variable (__tls_guard) to see whether TLS initialization
  2111. // for a thread has happend yet.
  2112. // If not, the initialization is triggered on-demand
  2113. // by calling __dyn_tls_on_demand_init.
  2114. emitDynamicTlsInitialization(CGF);
  2115. // Emit the variable just like any regular global variable.
  2116. llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
  2117. llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
  2118. unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
  2119. V = CGF.Builder.CreateBitCast(V, RealVarTy->getPointerTo(AS));
  2120. CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
  2121. Address Addr(V, RealVarTy, Alignment);
  2122. LValue LV = VD->getType()->isReferenceType()
  2123. ? CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
  2124. AlignmentSource::Decl)
  2125. : CGF.MakeAddrLValue(Addr, LValType, AlignmentSource::Decl);
  2126. return LV;
  2127. }
  2128. static ConstantAddress getInitThreadEpochPtr(CodeGenModule &CGM) {
  2129. StringRef VarName("_Init_thread_epoch");
  2130. CharUnits Align = CGM.getIntAlign();
  2131. if (auto *GV = CGM.getModule().getNamedGlobal(VarName))
  2132. return ConstantAddress(GV, GV->getValueType(), Align);
  2133. auto *GV = new llvm::GlobalVariable(
  2134. CGM.getModule(), CGM.IntTy,
  2135. /*isConstant=*/false, llvm::GlobalVariable::ExternalLinkage,
  2136. /*Initializer=*/nullptr, VarName,
  2137. /*InsertBefore=*/nullptr, llvm::GlobalVariable::GeneralDynamicTLSModel);
  2138. GV->setAlignment(Align.getAsAlign());
  2139. return ConstantAddress(GV, GV->getValueType(), Align);
  2140. }
  2141. static llvm::FunctionCallee getInitThreadHeaderFn(CodeGenModule &CGM) {
  2142. llvm::FunctionType *FTy =
  2143. llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
  2144. CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
  2145. return CGM.CreateRuntimeFunction(
  2146. FTy, "_Init_thread_header",
  2147. llvm::AttributeList::get(CGM.getLLVMContext(),
  2148. llvm::AttributeList::FunctionIndex,
  2149. llvm::Attribute::NoUnwind),
  2150. /*Local=*/true);
  2151. }
  2152. static llvm::FunctionCallee getInitThreadFooterFn(CodeGenModule &CGM) {
  2153. llvm::FunctionType *FTy =
  2154. llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
  2155. CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
  2156. return CGM.CreateRuntimeFunction(
  2157. FTy, "_Init_thread_footer",
  2158. llvm::AttributeList::get(CGM.getLLVMContext(),
  2159. llvm::AttributeList::FunctionIndex,
  2160. llvm::Attribute::NoUnwind),
  2161. /*Local=*/true);
  2162. }
  2163. static llvm::FunctionCallee getInitThreadAbortFn(CodeGenModule &CGM) {
  2164. llvm::FunctionType *FTy =
  2165. llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
  2166. CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
  2167. return CGM.CreateRuntimeFunction(
  2168. FTy, "_Init_thread_abort",
  2169. llvm::AttributeList::get(CGM.getLLVMContext(),
  2170. llvm::AttributeList::FunctionIndex,
  2171. llvm::Attribute::NoUnwind),
  2172. /*Local=*/true);
  2173. }
  2174. namespace {
  2175. struct ResetGuardBit final : EHScopeStack::Cleanup {
  2176. Address Guard;
  2177. unsigned GuardNum;
  2178. ResetGuardBit(Address Guard, unsigned GuardNum)
  2179. : Guard(Guard), GuardNum(GuardNum) {}
  2180. void Emit(CodeGenFunction &CGF, Flags flags) override {
  2181. // Reset the bit in the mask so that the static variable may be
  2182. // reinitialized.
  2183. CGBuilderTy &Builder = CGF.Builder;
  2184. llvm::LoadInst *LI = Builder.CreateLoad(Guard);
  2185. llvm::ConstantInt *Mask =
  2186. llvm::ConstantInt::get(CGF.IntTy, ~(1ULL << GuardNum));
  2187. Builder.CreateStore(Builder.CreateAnd(LI, Mask), Guard);
  2188. }
  2189. };
  2190. struct CallInitThreadAbort final : EHScopeStack::Cleanup {
  2191. llvm::Value *Guard;
  2192. CallInitThreadAbort(Address Guard) : Guard(Guard.getPointer()) {}
  2193. void Emit(CodeGenFunction &CGF, Flags flags) override {
  2194. // Calling _Init_thread_abort will reset the guard's state.
  2195. CGF.EmitNounwindRuntimeCall(getInitThreadAbortFn(CGF.CGM), Guard);
  2196. }
  2197. };
  2198. }
  2199. void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
  2200. llvm::GlobalVariable *GV,
  2201. bool PerformInit) {
  2202. // MSVC only uses guards for static locals.
  2203. if (!D.isStaticLocal()) {
  2204. assert(GV->hasWeakLinkage() || GV->hasLinkOnceLinkage());
  2205. // GlobalOpt is allowed to discard the initializer, so use linkonce_odr.
  2206. llvm::Function *F = CGF.CurFn;
  2207. F->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
  2208. F->setComdat(CGM.getModule().getOrInsertComdat(F->getName()));
  2209. CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
  2210. return;
  2211. }
  2212. bool ThreadlocalStatic = D.getTLSKind();
  2213. bool ThreadsafeStatic = getContext().getLangOpts().ThreadsafeStatics;
  2214. // Thread-safe static variables which aren't thread-specific have a
  2215. // per-variable guard.
  2216. bool HasPerVariableGuard = ThreadsafeStatic && !ThreadlocalStatic;
  2217. CGBuilderTy &Builder = CGF.Builder;
  2218. llvm::IntegerType *GuardTy = CGF.Int32Ty;
  2219. llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
  2220. CharUnits GuardAlign = CharUnits::fromQuantity(4);
  2221. // Get the guard variable for this function if we have one already.
  2222. GuardInfo *GI = nullptr;
  2223. if (ThreadlocalStatic)
  2224. GI = &ThreadLocalGuardVariableMap[D.getDeclContext()];
  2225. else if (!ThreadsafeStatic)
  2226. GI = &GuardVariableMap[D.getDeclContext()];
  2227. llvm::GlobalVariable *GuardVar = GI ? GI->Guard : nullptr;
  2228. unsigned GuardNum;
  2229. if (D.isExternallyVisible()) {
  2230. // Externally visible variables have to be numbered in Sema to properly
  2231. // handle unreachable VarDecls.
  2232. GuardNum = getContext().getStaticLocalNumber(&D);
  2233. assert(GuardNum > 0);
  2234. GuardNum--;
  2235. } else if (HasPerVariableGuard) {
  2236. GuardNum = ThreadSafeGuardNumMap[D.getDeclContext()]++;
  2237. } else {
  2238. // Non-externally visible variables are numbered here in CodeGen.
  2239. GuardNum = GI->BitIndex++;
  2240. }
  2241. if (!HasPerVariableGuard && GuardNum >= 32) {
  2242. if (D.isExternallyVisible())
  2243. ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
  2244. GuardNum %= 32;
  2245. GuardVar = nullptr;
  2246. }
  2247. if (!GuardVar) {
  2248. // Mangle the name for the guard.
  2249. SmallString<256> GuardName;
  2250. {
  2251. llvm::raw_svector_ostream Out(GuardName);
  2252. if (HasPerVariableGuard)
  2253. getMangleContext().mangleThreadSafeStaticGuardVariable(&D, GuardNum,
  2254. Out);
  2255. else
  2256. getMangleContext().mangleStaticGuardVariable(&D, Out);
  2257. }
  2258. // Create the guard variable with a zero-initializer. Just absorb linkage,
  2259. // visibility and dll storage class from the guarded variable.
  2260. GuardVar =
  2261. new llvm::GlobalVariable(CGM.getModule(), GuardTy, /*isConstant=*/false,
  2262. GV->getLinkage(), Zero, GuardName.str());
  2263. GuardVar->setVisibility(GV->getVisibility());
  2264. GuardVar->setDLLStorageClass(GV->getDLLStorageClass());
  2265. GuardVar->setAlignment(GuardAlign.getAsAlign());
  2266. if (GuardVar->isWeakForLinker())
  2267. GuardVar->setComdat(
  2268. CGM.getModule().getOrInsertComdat(GuardVar->getName()));
  2269. if (D.getTLSKind())
  2270. CGM.setTLSMode(GuardVar, D);
  2271. if (GI && !HasPerVariableGuard)
  2272. GI->Guard = GuardVar;
  2273. }
  2274. ConstantAddress GuardAddr(GuardVar, GuardTy, GuardAlign);
  2275. assert(GuardVar->getLinkage() == GV->getLinkage() &&
  2276. "static local from the same function had different linkage");
  2277. if (!HasPerVariableGuard) {
  2278. // Pseudo code for the test:
  2279. // if (!(GuardVar & MyGuardBit)) {
  2280. // GuardVar |= MyGuardBit;
  2281. // ... initialize the object ...;
  2282. // }
  2283. // Test our bit from the guard variable.
  2284. llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1ULL << GuardNum);
  2285. llvm::LoadInst *LI = Builder.CreateLoad(GuardAddr);
  2286. llvm::Value *NeedsInit =
  2287. Builder.CreateICmpEQ(Builder.CreateAnd(LI, Bit), Zero);
  2288. llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
  2289. llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
  2290. CGF.EmitCXXGuardedInitBranch(NeedsInit, InitBlock, EndBlock,
  2291. CodeGenFunction::GuardKind::VariableGuard, &D);
  2292. // Set our bit in the guard variable and emit the initializer and add a global
  2293. // destructor if appropriate.
  2294. CGF.EmitBlock(InitBlock);
  2295. Builder.CreateStore(Builder.CreateOr(LI, Bit), GuardAddr);
  2296. CGF.EHStack.pushCleanup<ResetGuardBit>(EHCleanup, GuardAddr, GuardNum);
  2297. CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
  2298. CGF.PopCleanupBlock();
  2299. Builder.CreateBr(EndBlock);
  2300. // Continue.
  2301. CGF.EmitBlock(EndBlock);
  2302. } else {
  2303. // Pseudo code for the test:
  2304. // if (TSS > _Init_thread_epoch) {
  2305. // _Init_thread_header(&TSS);
  2306. // if (TSS == -1) {
  2307. // ... initialize the object ...;
  2308. // _Init_thread_footer(&TSS);
  2309. // }
  2310. // }
  2311. //
  2312. // The algorithm is almost identical to what can be found in the appendix
  2313. // found in N2325.
  2314. // This BasicBLock determines whether or not we have any work to do.
  2315. llvm::LoadInst *FirstGuardLoad = Builder.CreateLoad(GuardAddr);
  2316. FirstGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
  2317. llvm::LoadInst *InitThreadEpoch =
  2318. Builder.CreateLoad(getInitThreadEpochPtr(CGM));
  2319. llvm::Value *IsUninitialized =
  2320. Builder.CreateICmpSGT(FirstGuardLoad, InitThreadEpoch);
  2321. llvm::BasicBlock *AttemptInitBlock = CGF.createBasicBlock("init.attempt");
  2322. llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
  2323. CGF.EmitCXXGuardedInitBranch(IsUninitialized, AttemptInitBlock, EndBlock,
  2324. CodeGenFunction::GuardKind::VariableGuard, &D);
  2325. // This BasicBlock attempts to determine whether or not this thread is
  2326. // responsible for doing the initialization.
  2327. CGF.EmitBlock(AttemptInitBlock);
  2328. CGF.EmitNounwindRuntimeCall(getInitThreadHeaderFn(CGM),
  2329. GuardAddr.getPointer());
  2330. llvm::LoadInst *SecondGuardLoad = Builder.CreateLoad(GuardAddr);
  2331. SecondGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
  2332. llvm::Value *ShouldDoInit =
  2333. Builder.CreateICmpEQ(SecondGuardLoad, getAllOnesInt());
  2334. llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
  2335. Builder.CreateCondBr(ShouldDoInit, InitBlock, EndBlock);
  2336. // Ok, we ended up getting selected as the initializing thread.
  2337. CGF.EmitBlock(InitBlock);
  2338. CGF.EHStack.pushCleanup<CallInitThreadAbort>(EHCleanup, GuardAddr);
  2339. CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
  2340. CGF.PopCleanupBlock();
  2341. CGF.EmitNounwindRuntimeCall(getInitThreadFooterFn(CGM),
  2342. GuardAddr.getPointer());
  2343. Builder.CreateBr(EndBlock);
  2344. CGF.EmitBlock(EndBlock);
  2345. }
  2346. }
  2347. bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
  2348. // Null-ness for function memptrs only depends on the first field, which is
  2349. // the function pointer. The rest don't matter, so we can zero initialize.
  2350. if (MPT->isMemberFunctionPointer())
  2351. return true;
  2352. // The virtual base adjustment field is always -1 for null, so if we have one
  2353. // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
  2354. // valid field offset.
  2355. const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
  2356. MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
  2357. return (!inheritanceModelHasVBTableOffsetField(Inheritance) &&
  2358. RD->nullFieldOffsetIsZero());
  2359. }
  2360. llvm::Type *
  2361. MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
  2362. const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
  2363. MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
  2364. llvm::SmallVector<llvm::Type *, 4> fields;
  2365. if (MPT->isMemberFunctionPointer())
  2366. fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
  2367. else
  2368. fields.push_back(CGM.IntTy); // FieldOffset
  2369. if (inheritanceModelHasNVOffsetField(MPT->isMemberFunctionPointer(),
  2370. Inheritance))
  2371. fields.push_back(CGM.IntTy);
  2372. if (inheritanceModelHasVBPtrOffsetField(Inheritance))
  2373. fields.push_back(CGM.IntTy);
  2374. if (inheritanceModelHasVBTableOffsetField(Inheritance))
  2375. fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
  2376. if (fields.size() == 1)
  2377. return fields[0];
  2378. return llvm::StructType::get(CGM.getLLVMContext(), fields);
  2379. }
  2380. void MicrosoftCXXABI::
  2381. GetNullMemberPointerFields(const MemberPointerType *MPT,
  2382. llvm::SmallVectorImpl<llvm::Constant *> &fields) {
  2383. assert(fields.empty());
  2384. const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
  2385. MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
  2386. if (MPT->isMemberFunctionPointer()) {
  2387. // FunctionPointerOrVirtualThunk
  2388. fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
  2389. } else {
  2390. if (RD->nullFieldOffsetIsZero())
  2391. fields.push_back(getZeroInt()); // FieldOffset
  2392. else
  2393. fields.push_back(getAllOnesInt()); // FieldOffset
  2394. }
  2395. if (inheritanceModelHasNVOffsetField(MPT->isMemberFunctionPointer(),
  2396. Inheritance))
  2397. fields.push_back(getZeroInt());
  2398. if (inheritanceModelHasVBPtrOffsetField(Inheritance))
  2399. fields.push_back(getZeroInt());
  2400. if (inheritanceModelHasVBTableOffsetField(Inheritance))
  2401. fields.push_back(getAllOnesInt());
  2402. }
  2403. llvm::Constant *
  2404. MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
  2405. llvm::SmallVector<llvm::Constant *, 4> fields;
  2406. GetNullMemberPointerFields(MPT, fields);
  2407. if (fields.size() == 1)
  2408. return fields[0];
  2409. llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
  2410. assert(Res->getType() == ConvertMemberPointerType(MPT));
  2411. return Res;
  2412. }
  2413. llvm::Constant *
  2414. MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
  2415. bool IsMemberFunction,
  2416. const CXXRecordDecl *RD,
  2417. CharUnits NonVirtualBaseAdjustment,
  2418. unsigned VBTableIndex) {
  2419. MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
  2420. // Single inheritance class member pointer are represented as scalars instead
  2421. // of aggregates.
  2422. if (inheritanceModelHasOnlyOneField(IsMemberFunction, Inheritance))
  2423. return FirstField;
  2424. llvm::SmallVector<llvm::Constant *, 4> fields;
  2425. fields.push_back(FirstField);
  2426. if (inheritanceModelHasNVOffsetField(IsMemberFunction, Inheritance))
  2427. fields.push_back(llvm::ConstantInt::get(
  2428. CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
  2429. if (inheritanceModelHasVBPtrOffsetField(Inheritance)) {
  2430. CharUnits Offs = CharUnits::Zero();
  2431. if (VBTableIndex)
  2432. Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
  2433. fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
  2434. }
  2435. // The rest of the fields are adjusted by conversions to a more derived class.
  2436. if (inheritanceModelHasVBTableOffsetField(Inheritance))
  2437. fields.push_back(llvm::ConstantInt::get(CGM.IntTy, VBTableIndex));
  2438. return llvm::ConstantStruct::getAnon(fields);
  2439. }
  2440. llvm::Constant *
  2441. MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
  2442. CharUnits offset) {
  2443. return EmitMemberDataPointer(MPT->getMostRecentCXXRecordDecl(), offset);
  2444. }
  2445. llvm::Constant *MicrosoftCXXABI::EmitMemberDataPointer(const CXXRecordDecl *RD,
  2446. CharUnits offset) {
  2447. if (RD->getMSInheritanceModel() ==
  2448. MSInheritanceModel::Virtual)
  2449. offset -= getContext().getOffsetOfBaseWithVBPtr(RD);
  2450. llvm::Constant *FirstField =
  2451. llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
  2452. return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
  2453. CharUnits::Zero(), /*VBTableIndex=*/0);
  2454. }
  2455. llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
  2456. QualType MPType) {
  2457. const MemberPointerType *DstTy = MPType->castAs<MemberPointerType>();
  2458. const ValueDecl *MPD = MP.getMemberPointerDecl();
  2459. if (!MPD)
  2460. return EmitNullMemberPointer(DstTy);
  2461. ASTContext &Ctx = getContext();
  2462. ArrayRef<const CXXRecordDecl *> MemberPointerPath = MP.getMemberPointerPath();
  2463. llvm::Constant *C;
  2464. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) {
  2465. C = EmitMemberFunctionPointer(MD);
  2466. } else {
  2467. // For a pointer to data member, start off with the offset of the field in
  2468. // the class in which it was declared, and convert from there if necessary.
  2469. // For indirect field decls, get the outermost anonymous field and use the
  2470. // parent class.
  2471. CharUnits FieldOffset = Ctx.toCharUnitsFromBits(Ctx.getFieldOffset(MPD));
  2472. const FieldDecl *FD = dyn_cast<FieldDecl>(MPD);
  2473. if (!FD)
  2474. FD = cast<FieldDecl>(*cast<IndirectFieldDecl>(MPD)->chain_begin());
  2475. const CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getParent());
  2476. RD = RD->getMostRecentNonInjectedDecl();
  2477. C = EmitMemberDataPointer(RD, FieldOffset);
  2478. }
  2479. if (!MemberPointerPath.empty()) {
  2480. const CXXRecordDecl *SrcRD = cast<CXXRecordDecl>(MPD->getDeclContext());
  2481. const Type *SrcRecTy = Ctx.getTypeDeclType(SrcRD).getTypePtr();
  2482. const MemberPointerType *SrcTy =
  2483. Ctx.getMemberPointerType(DstTy->getPointeeType(), SrcRecTy)
  2484. ->castAs<MemberPointerType>();
  2485. bool DerivedMember = MP.isMemberPointerToDerivedMember();
  2486. SmallVector<const CXXBaseSpecifier *, 4> DerivedToBasePath;
  2487. const CXXRecordDecl *PrevRD = SrcRD;
  2488. for (const CXXRecordDecl *PathElem : MemberPointerPath) {
  2489. const CXXRecordDecl *Base = nullptr;
  2490. const CXXRecordDecl *Derived = nullptr;
  2491. if (DerivedMember) {
  2492. Base = PathElem;
  2493. Derived = PrevRD;
  2494. } else {
  2495. Base = PrevRD;
  2496. Derived = PathElem;
  2497. }
  2498. for (const CXXBaseSpecifier &BS : Derived->bases())
  2499. if (BS.getType()->getAsCXXRecordDecl()->getCanonicalDecl() ==
  2500. Base->getCanonicalDecl())
  2501. DerivedToBasePath.push_back(&BS);
  2502. PrevRD = PathElem;
  2503. }
  2504. assert(DerivedToBasePath.size() == MemberPointerPath.size());
  2505. CastKind CK = DerivedMember ? CK_DerivedToBaseMemberPointer
  2506. : CK_BaseToDerivedMemberPointer;
  2507. C = EmitMemberPointerConversion(SrcTy, DstTy, CK, DerivedToBasePath.begin(),
  2508. DerivedToBasePath.end(), C);
  2509. }
  2510. return C;
  2511. }
  2512. llvm::Constant *
  2513. MicrosoftCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
  2514. assert(MD->isInstance() && "Member function must not be static!");
  2515. CharUnits NonVirtualBaseAdjustment = CharUnits::Zero();
  2516. const CXXRecordDecl *RD = MD->getParent()->getMostRecentNonInjectedDecl();
  2517. CodeGenTypes &Types = CGM.getTypes();
  2518. unsigned VBTableIndex = 0;
  2519. llvm::Constant *FirstField;
  2520. const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
  2521. if (!MD->isVirtual()) {
  2522. llvm::Type *Ty;
  2523. // Check whether the function has a computable LLVM signature.
  2524. if (Types.isFuncTypeConvertible(FPT)) {
  2525. // The function has a computable LLVM signature; use the correct type.
  2526. Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
  2527. } else {
  2528. // Use an arbitrary non-function type to tell GetAddrOfFunction that the
  2529. // function type is incomplete.
  2530. Ty = CGM.PtrDiffTy;
  2531. }
  2532. FirstField = CGM.GetAddrOfFunction(MD, Ty);
  2533. } else {
  2534. auto &VTableContext = CGM.getMicrosoftVTableContext();
  2535. MethodVFTableLocation ML = VTableContext.getMethodVFTableLocation(MD);
  2536. FirstField = EmitVirtualMemPtrThunk(MD, ML);
  2537. // Include the vfptr adjustment if the method is in a non-primary vftable.
  2538. NonVirtualBaseAdjustment += ML.VFPtrOffset;
  2539. if (ML.VBase)
  2540. VBTableIndex = VTableContext.getVBTableIndex(RD, ML.VBase) * 4;
  2541. }
  2542. if (VBTableIndex == 0 &&
  2543. RD->getMSInheritanceModel() ==
  2544. MSInheritanceModel::Virtual)
  2545. NonVirtualBaseAdjustment -= getContext().getOffsetOfBaseWithVBPtr(RD);
  2546. // The rest of the fields are common with data member pointers.
  2547. FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
  2548. return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
  2549. NonVirtualBaseAdjustment, VBTableIndex);
  2550. }
  2551. /// Member pointers are the same if they're either bitwise identical *or* both
  2552. /// null. Null-ness for function members is determined by the first field,
  2553. /// while for data member pointers we must compare all fields.
  2554. llvm::Value *
  2555. MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
  2556. llvm::Value *L,
  2557. llvm::Value *R,
  2558. const MemberPointerType *MPT,
  2559. bool Inequality) {
  2560. CGBuilderTy &Builder = CGF.Builder;
  2561. // Handle != comparisons by switching the sense of all boolean operations.
  2562. llvm::ICmpInst::Predicate Eq;
  2563. llvm::Instruction::BinaryOps And, Or;
  2564. if (Inequality) {
  2565. Eq = llvm::ICmpInst::ICMP_NE;
  2566. And = llvm::Instruction::Or;
  2567. Or = llvm::Instruction::And;
  2568. } else {
  2569. Eq = llvm::ICmpInst::ICMP_EQ;
  2570. And = llvm::Instruction::And;
  2571. Or = llvm::Instruction::Or;
  2572. }
  2573. // If this is a single field member pointer (single inheritance), this is a
  2574. // single icmp.
  2575. const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
  2576. MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
  2577. if (inheritanceModelHasOnlyOneField(MPT->isMemberFunctionPointer(),
  2578. Inheritance))
  2579. return Builder.CreateICmp(Eq, L, R);
  2580. // Compare the first field.
  2581. llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
  2582. llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
  2583. llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
  2584. // Compare everything other than the first field.
  2585. llvm::Value *Res = nullptr;
  2586. llvm::StructType *LType = cast<llvm::StructType>(L->getType());
  2587. for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
  2588. llvm::Value *LF = Builder.CreateExtractValue(L, I);
  2589. llvm::Value *RF = Builder.CreateExtractValue(R, I);
  2590. llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
  2591. if (Res)
  2592. Res = Builder.CreateBinOp(And, Res, Cmp);
  2593. else
  2594. Res = Cmp;
  2595. }
  2596. // Check if the first field is 0 if this is a function pointer.
  2597. if (MPT->isMemberFunctionPointer()) {
  2598. // (l1 == r1 && ...) || l0 == 0
  2599. llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
  2600. llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
  2601. Res = Builder.CreateBinOp(Or, Res, IsZero);
  2602. }
  2603. // Combine the comparison of the first field, which must always be true for
  2604. // this comparison to succeeed.
  2605. return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
  2606. }
  2607. llvm::Value *
  2608. MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
  2609. llvm::Value *MemPtr,
  2610. const MemberPointerType *MPT) {
  2611. CGBuilderTy &Builder = CGF.Builder;
  2612. llvm::SmallVector<llvm::Constant *, 4> fields;
  2613. // We only need one field for member functions.
  2614. if (MPT->isMemberFunctionPointer())
  2615. fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
  2616. else
  2617. GetNullMemberPointerFields(MPT, fields);
  2618. assert(!fields.empty());
  2619. llvm::Value *FirstField = MemPtr;
  2620. if (MemPtr->getType()->isStructTy())
  2621. FirstField = Builder.CreateExtractValue(MemPtr, 0);
  2622. llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
  2623. // For function member pointers, we only need to test the function pointer
  2624. // field. The other fields if any can be garbage.
  2625. if (MPT->isMemberFunctionPointer())
  2626. return Res;
  2627. // Otherwise, emit a series of compares and combine the results.
  2628. for (int I = 1, E = fields.size(); I < E; ++I) {
  2629. llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
  2630. llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
  2631. Res = Builder.CreateOr(Res, Next, "memptr.tobool");
  2632. }
  2633. return Res;
  2634. }
  2635. bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
  2636. llvm::Constant *Val) {
  2637. // Function pointers are null if the pointer in the first field is null.
  2638. if (MPT->isMemberFunctionPointer()) {
  2639. llvm::Constant *FirstField = Val->getType()->isStructTy() ?
  2640. Val->getAggregateElement(0U) : Val;
  2641. return FirstField->isNullValue();
  2642. }
  2643. // If it's not a function pointer and it's zero initializable, we can easily
  2644. // check zero.
  2645. if (isZeroInitializable(MPT) && Val->isNullValue())
  2646. return true;
  2647. // Otherwise, break down all the fields for comparison. Hopefully these
  2648. // little Constants are reused, while a big null struct might not be.
  2649. llvm::SmallVector<llvm::Constant *, 4> Fields;
  2650. GetNullMemberPointerFields(MPT, Fields);
  2651. if (Fields.size() == 1) {
  2652. assert(Val->getType()->isIntegerTy());
  2653. return Val == Fields[0];
  2654. }
  2655. unsigned I, E;
  2656. for (I = 0, E = Fields.size(); I != E; ++I) {
  2657. if (Val->getAggregateElement(I) != Fields[I])
  2658. break;
  2659. }
  2660. return I == E;
  2661. }
  2662. llvm::Value *
  2663. MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
  2664. Address This,
  2665. llvm::Value *VBPtrOffset,
  2666. llvm::Value *VBTableOffset,
  2667. llvm::Value **VBPtrOut) {
  2668. CGBuilderTy &Builder = CGF.Builder;
  2669. // Load the vbtable pointer from the vbptr in the instance.
  2670. This = Builder.CreateElementBitCast(This, CGM.Int8Ty);
  2671. llvm::Value *VBPtr = Builder.CreateInBoundsGEP(
  2672. This.getElementType(), This.getPointer(), VBPtrOffset, "vbptr");
  2673. if (VBPtrOut) *VBPtrOut = VBPtr;
  2674. VBPtr = Builder.CreateBitCast(VBPtr,
  2675. CGM.Int32Ty->getPointerTo(0)->getPointerTo(This.getAddressSpace()));
  2676. CharUnits VBPtrAlign;
  2677. if (auto CI = dyn_cast<llvm::ConstantInt>(VBPtrOffset)) {
  2678. VBPtrAlign = This.getAlignment().alignmentAtOffset(
  2679. CharUnits::fromQuantity(CI->getSExtValue()));
  2680. } else {
  2681. VBPtrAlign = CGF.getPointerAlign();
  2682. }
  2683. llvm::Value *VBTable = Builder.CreateAlignedLoad(
  2684. CGM.Int32Ty->getPointerTo(0), VBPtr, VBPtrAlign, "vbtable");
  2685. // Translate from byte offset to table index. It improves analyzability.
  2686. llvm::Value *VBTableIndex = Builder.CreateAShr(
  2687. VBTableOffset, llvm::ConstantInt::get(VBTableOffset->getType(), 2),
  2688. "vbtindex", /*isExact=*/true);
  2689. // Load an i32 offset from the vb-table.
  2690. llvm::Value *VBaseOffs =
  2691. Builder.CreateInBoundsGEP(CGM.Int32Ty, VBTable, VBTableIndex);
  2692. VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
  2693. return Builder.CreateAlignedLoad(CGM.Int32Ty, VBaseOffs,
  2694. CharUnits::fromQuantity(4), "vbase_offs");
  2695. }
  2696. // Returns an adjusted base cast to i8*, since we do more address arithmetic on
  2697. // it.
  2698. llvm::Value *MicrosoftCXXABI::AdjustVirtualBase(
  2699. CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD,
  2700. Address Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) {
  2701. CGBuilderTy &Builder = CGF.Builder;
  2702. Base = Builder.CreateElementBitCast(Base, CGM.Int8Ty);
  2703. llvm::BasicBlock *OriginalBB = nullptr;
  2704. llvm::BasicBlock *SkipAdjustBB = nullptr;
  2705. llvm::BasicBlock *VBaseAdjustBB = nullptr;
  2706. // In the unspecified inheritance model, there might not be a vbtable at all,
  2707. // in which case we need to skip the virtual base lookup. If there is a
  2708. // vbtable, the first entry is a no-op entry that gives back the original
  2709. // base, so look for a virtual base adjustment offset of zero.
  2710. if (VBPtrOffset) {
  2711. OriginalBB = Builder.GetInsertBlock();
  2712. VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
  2713. SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
  2714. llvm::Value *IsVirtual =
  2715. Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
  2716. "memptr.is_vbase");
  2717. Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
  2718. CGF.EmitBlock(VBaseAdjustBB);
  2719. }
  2720. // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
  2721. // know the vbptr offset.
  2722. if (!VBPtrOffset) {
  2723. CharUnits offs = CharUnits::Zero();
  2724. if (!RD->hasDefinition()) {
  2725. DiagnosticsEngine &Diags = CGF.CGM.getDiags();
  2726. unsigned DiagID = Diags.getCustomDiagID(
  2727. DiagnosticsEngine::Error,
  2728. "member pointer representation requires a "
  2729. "complete class type for %0 to perform this expression");
  2730. Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange();
  2731. } else if (RD->getNumVBases())
  2732. offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
  2733. VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
  2734. }
  2735. llvm::Value *VBPtr = nullptr;
  2736. llvm::Value *VBaseOffs =
  2737. GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
  2738. llvm::Value *AdjustedBase =
  2739. Builder.CreateInBoundsGEP(CGM.Int8Ty, VBPtr, VBaseOffs);
  2740. // Merge control flow with the case where we didn't have to adjust.
  2741. if (VBaseAdjustBB) {
  2742. Builder.CreateBr(SkipAdjustBB);
  2743. CGF.EmitBlock(SkipAdjustBB);
  2744. llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
  2745. Phi->addIncoming(Base.getPointer(), OriginalBB);
  2746. Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
  2747. return Phi;
  2748. }
  2749. return AdjustedBase;
  2750. }
  2751. llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress(
  2752. CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
  2753. const MemberPointerType *MPT) {
  2754. assert(MPT->isMemberDataPointer());
  2755. unsigned AS = Base.getAddressSpace();
  2756. llvm::Type *PType =
  2757. CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
  2758. CGBuilderTy &Builder = CGF.Builder;
  2759. const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
  2760. MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
  2761. // Extract the fields we need, regardless of model. We'll apply them if we
  2762. // have them.
  2763. llvm::Value *FieldOffset = MemPtr;
  2764. llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
  2765. llvm::Value *VBPtrOffset = nullptr;
  2766. if (MemPtr->getType()->isStructTy()) {
  2767. // We need to extract values.
  2768. unsigned I = 0;
  2769. FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
  2770. if (inheritanceModelHasVBPtrOffsetField(Inheritance))
  2771. VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
  2772. if (inheritanceModelHasVBTableOffsetField(Inheritance))
  2773. VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
  2774. }
  2775. llvm::Value *Addr;
  2776. if (VirtualBaseAdjustmentOffset) {
  2777. Addr = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset,
  2778. VBPtrOffset);
  2779. } else {
  2780. Addr = Base.getPointer();
  2781. }
  2782. // Cast to char*.
  2783. Addr = Builder.CreateBitCast(Addr, CGF.Int8Ty->getPointerTo(AS));
  2784. // Apply the offset, which we assume is non-null.
  2785. Addr = Builder.CreateInBoundsGEP(CGF.Int8Ty, Addr, FieldOffset,
  2786. "memptr.offset");
  2787. // Cast the address to the appropriate pointer type, adopting the address
  2788. // space of the base pointer.
  2789. return Builder.CreateBitCast(Addr, PType);
  2790. }
  2791. llvm::Value *
  2792. MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
  2793. const CastExpr *E,
  2794. llvm::Value *Src) {
  2795. assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
  2796. E->getCastKind() == CK_BaseToDerivedMemberPointer ||
  2797. E->getCastKind() == CK_ReinterpretMemberPointer);
  2798. // Use constant emission if we can.
  2799. if (isa<llvm::Constant>(Src))
  2800. return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
  2801. // We may be adding or dropping fields from the member pointer, so we need
  2802. // both types and the inheritance models of both records.
  2803. const MemberPointerType *SrcTy =
  2804. E->getSubExpr()->getType()->castAs<MemberPointerType>();
  2805. const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
  2806. bool IsFunc = SrcTy->isMemberFunctionPointer();
  2807. // If the classes use the same null representation, reinterpret_cast is a nop.
  2808. bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
  2809. if (IsReinterpret && IsFunc)
  2810. return Src;
  2811. CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
  2812. CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
  2813. if (IsReinterpret &&
  2814. SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero())
  2815. return Src;
  2816. CGBuilderTy &Builder = CGF.Builder;
  2817. // Branch past the conversion if Src is null.
  2818. llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
  2819. llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
  2820. // C++ 5.2.10p9: The null member pointer value is converted to the null member
  2821. // pointer value of the destination type.
  2822. if (IsReinterpret) {
  2823. // For reinterpret casts, sema ensures that src and dst are both functions
  2824. // or data and have the same size, which means the LLVM types should match.
  2825. assert(Src->getType() == DstNull->getType());
  2826. return Builder.CreateSelect(IsNotNull, Src, DstNull);
  2827. }
  2828. llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
  2829. llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
  2830. llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
  2831. Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
  2832. CGF.EmitBlock(ConvertBB);
  2833. llvm::Value *Dst = EmitNonNullMemberPointerConversion(
  2834. SrcTy, DstTy, E->getCastKind(), E->path_begin(), E->path_end(), Src,
  2835. Builder);
  2836. Builder.CreateBr(ContinueBB);
  2837. // In the continuation, choose between DstNull and Dst.
  2838. CGF.EmitBlock(ContinueBB);
  2839. llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
  2840. Phi->addIncoming(DstNull, OriginalBB);
  2841. Phi->addIncoming(Dst, ConvertBB);
  2842. return Phi;
  2843. }
  2844. llvm::Value *MicrosoftCXXABI::EmitNonNullMemberPointerConversion(
  2845. const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
  2846. CastExpr::path_const_iterator PathBegin,
  2847. CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
  2848. CGBuilderTy &Builder) {
  2849. const CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
  2850. const CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
  2851. MSInheritanceModel SrcInheritance = SrcRD->getMSInheritanceModel();
  2852. MSInheritanceModel DstInheritance = DstRD->getMSInheritanceModel();
  2853. bool IsFunc = SrcTy->isMemberFunctionPointer();
  2854. bool IsConstant = isa<llvm::Constant>(Src);
  2855. // Decompose src.
  2856. llvm::Value *FirstField = Src;
  2857. llvm::Value *NonVirtualBaseAdjustment = getZeroInt();
  2858. llvm::Value *VirtualBaseAdjustmentOffset = getZeroInt();
  2859. llvm::Value *VBPtrOffset = getZeroInt();
  2860. if (!inheritanceModelHasOnlyOneField(IsFunc, SrcInheritance)) {
  2861. // We need to extract values.
  2862. unsigned I = 0;
  2863. FirstField = Builder.CreateExtractValue(Src, I++);
  2864. if (inheritanceModelHasNVOffsetField(IsFunc, SrcInheritance))
  2865. NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
  2866. if (inheritanceModelHasVBPtrOffsetField(SrcInheritance))
  2867. VBPtrOffset = Builder.CreateExtractValue(Src, I++);
  2868. if (inheritanceModelHasVBTableOffsetField(SrcInheritance))
  2869. VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
  2870. }
  2871. bool IsDerivedToBase = (CK == CK_DerivedToBaseMemberPointer);
  2872. const MemberPointerType *DerivedTy = IsDerivedToBase ? SrcTy : DstTy;
  2873. const CXXRecordDecl *DerivedClass = DerivedTy->getMostRecentCXXRecordDecl();
  2874. // For data pointers, we adjust the field offset directly. For functions, we
  2875. // have a separate field.
  2876. llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
  2877. // The virtual inheritance model has a quirk: the virtual base table is always
  2878. // referenced when dereferencing a member pointer even if the member pointer
  2879. // is non-virtual. This is accounted for by adjusting the non-virtual offset
  2880. // to point backwards to the top of the MDC from the first VBase. Undo this
  2881. // adjustment to normalize the member pointer.
  2882. llvm::Value *SrcVBIndexEqZero =
  2883. Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
  2884. if (SrcInheritance == MSInheritanceModel::Virtual) {
  2885. if (int64_t SrcOffsetToFirstVBase =
  2886. getContext().getOffsetOfBaseWithVBPtr(SrcRD).getQuantity()) {
  2887. llvm::Value *UndoSrcAdjustment = Builder.CreateSelect(
  2888. SrcVBIndexEqZero,
  2889. llvm::ConstantInt::get(CGM.IntTy, SrcOffsetToFirstVBase),
  2890. getZeroInt());
  2891. NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, UndoSrcAdjustment);
  2892. }
  2893. }
  2894. // A non-zero vbindex implies that we are dealing with a source member in a
  2895. // floating virtual base in addition to some non-virtual offset. If the
  2896. // vbindex is zero, we are dealing with a source that exists in a non-virtual,
  2897. // fixed, base. The difference between these two cases is that the vbindex +
  2898. // nvoffset *always* point to the member regardless of what context they are
  2899. // evaluated in so long as the vbindex is adjusted. A member inside a fixed
  2900. // base requires explicit nv adjustment.
  2901. llvm::Constant *BaseClassOffset = llvm::ConstantInt::get(
  2902. CGM.IntTy,
  2903. CGM.computeNonVirtualBaseClassOffset(DerivedClass, PathBegin, PathEnd)
  2904. .getQuantity());
  2905. llvm::Value *NVDisp;
  2906. if (IsDerivedToBase)
  2907. NVDisp = Builder.CreateNSWSub(NVAdjustField, BaseClassOffset, "adj");
  2908. else
  2909. NVDisp = Builder.CreateNSWAdd(NVAdjustField, BaseClassOffset, "adj");
  2910. NVAdjustField = Builder.CreateSelect(SrcVBIndexEqZero, NVDisp, getZeroInt());
  2911. // Update the vbindex to an appropriate value in the destination because
  2912. // SrcRD's vbtable might not be a strict prefix of the one in DstRD.
  2913. llvm::Value *DstVBIndexEqZero = SrcVBIndexEqZero;
  2914. if (inheritanceModelHasVBTableOffsetField(DstInheritance) &&
  2915. inheritanceModelHasVBTableOffsetField(SrcInheritance)) {
  2916. if (llvm::GlobalVariable *VDispMap =
  2917. getAddrOfVirtualDisplacementMap(SrcRD, DstRD)) {
  2918. llvm::Value *VBIndex = Builder.CreateExactUDiv(
  2919. VirtualBaseAdjustmentOffset, llvm::ConstantInt::get(CGM.IntTy, 4));
  2920. if (IsConstant) {
  2921. llvm::Constant *Mapping = VDispMap->getInitializer();
  2922. VirtualBaseAdjustmentOffset =
  2923. Mapping->getAggregateElement(cast<llvm::Constant>(VBIndex));
  2924. } else {
  2925. llvm::Value *Idxs[] = {getZeroInt(), VBIndex};
  2926. VirtualBaseAdjustmentOffset = Builder.CreateAlignedLoad(
  2927. CGM.IntTy, Builder.CreateInBoundsGEP(VDispMap->getValueType(),
  2928. VDispMap, Idxs),
  2929. CharUnits::fromQuantity(4));
  2930. }
  2931. DstVBIndexEqZero =
  2932. Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
  2933. }
  2934. }
  2935. // Set the VBPtrOffset to zero if the vbindex is zero. Otherwise, initialize
  2936. // it to the offset of the vbptr.
  2937. if (inheritanceModelHasVBPtrOffsetField(DstInheritance)) {
  2938. llvm::Value *DstVBPtrOffset = llvm::ConstantInt::get(
  2939. CGM.IntTy,
  2940. getContext().getASTRecordLayout(DstRD).getVBPtrOffset().getQuantity());
  2941. VBPtrOffset =
  2942. Builder.CreateSelect(DstVBIndexEqZero, getZeroInt(), DstVBPtrOffset);
  2943. }
  2944. // Likewise, apply a similar adjustment so that dereferencing the member
  2945. // pointer correctly accounts for the distance between the start of the first
  2946. // virtual base and the top of the MDC.
  2947. if (DstInheritance == MSInheritanceModel::Virtual) {
  2948. if (int64_t DstOffsetToFirstVBase =
  2949. getContext().getOffsetOfBaseWithVBPtr(DstRD).getQuantity()) {
  2950. llvm::Value *DoDstAdjustment = Builder.CreateSelect(
  2951. DstVBIndexEqZero,
  2952. llvm::ConstantInt::get(CGM.IntTy, DstOffsetToFirstVBase),
  2953. getZeroInt());
  2954. NVAdjustField = Builder.CreateNSWSub(NVAdjustField, DoDstAdjustment);
  2955. }
  2956. }
  2957. // Recompose dst from the null struct and the adjusted fields from src.
  2958. llvm::Value *Dst;
  2959. if (inheritanceModelHasOnlyOneField(IsFunc, DstInheritance)) {
  2960. Dst = FirstField;
  2961. } else {
  2962. Dst = llvm::UndefValue::get(ConvertMemberPointerType(DstTy));
  2963. unsigned Idx = 0;
  2964. Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
  2965. if (inheritanceModelHasNVOffsetField(IsFunc, DstInheritance))
  2966. Dst = Builder.CreateInsertValue(Dst, NonVirtualBaseAdjustment, Idx++);
  2967. if (inheritanceModelHasVBPtrOffsetField(DstInheritance))
  2968. Dst = Builder.CreateInsertValue(Dst, VBPtrOffset, Idx++);
  2969. if (inheritanceModelHasVBTableOffsetField(DstInheritance))
  2970. Dst = Builder.CreateInsertValue(Dst, VirtualBaseAdjustmentOffset, Idx++);
  2971. }
  2972. return Dst;
  2973. }
  2974. llvm::Constant *
  2975. MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
  2976. llvm::Constant *Src) {
  2977. const MemberPointerType *SrcTy =
  2978. E->getSubExpr()->getType()->castAs<MemberPointerType>();
  2979. const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
  2980. CastKind CK = E->getCastKind();
  2981. return EmitMemberPointerConversion(SrcTy, DstTy, CK, E->path_begin(),
  2982. E->path_end(), Src);
  2983. }
  2984. llvm::Constant *MicrosoftCXXABI::EmitMemberPointerConversion(
  2985. const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
  2986. CastExpr::path_const_iterator PathBegin,
  2987. CastExpr::path_const_iterator PathEnd, llvm::Constant *Src) {
  2988. assert(CK == CK_DerivedToBaseMemberPointer ||
  2989. CK == CK_BaseToDerivedMemberPointer ||
  2990. CK == CK_ReinterpretMemberPointer);
  2991. // If src is null, emit a new null for dst. We can't return src because dst
  2992. // might have a new representation.
  2993. if (MemberPointerConstantIsNull(SrcTy, Src))
  2994. return EmitNullMemberPointer(DstTy);
  2995. // We don't need to do anything for reinterpret_casts of non-null member
  2996. // pointers. We should only get here when the two type representations have
  2997. // the same size.
  2998. if (CK == CK_ReinterpretMemberPointer)
  2999. return Src;
  3000. CGBuilderTy Builder(CGM, CGM.getLLVMContext());
  3001. auto *Dst = cast<llvm::Constant>(EmitNonNullMemberPointerConversion(
  3002. SrcTy, DstTy, CK, PathBegin, PathEnd, Src, Builder));
  3003. return Dst;
  3004. }
  3005. CGCallee MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(
  3006. CodeGenFunction &CGF, const Expr *E, Address This,
  3007. llvm::Value *&ThisPtrForCall, llvm::Value *MemPtr,
  3008. const MemberPointerType *MPT) {
  3009. assert(MPT->isMemberFunctionPointer());
  3010. const FunctionProtoType *FPT =
  3011. MPT->getPointeeType()->castAs<FunctionProtoType>();
  3012. const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
  3013. llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
  3014. CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
  3015. CGBuilderTy &Builder = CGF.Builder;
  3016. MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
  3017. // Extract the fields we need, regardless of model. We'll apply them if we
  3018. // have them.
  3019. llvm::Value *FunctionPointer = MemPtr;
  3020. llvm::Value *NonVirtualBaseAdjustment = nullptr;
  3021. llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
  3022. llvm::Value *VBPtrOffset = nullptr;
  3023. if (MemPtr->getType()->isStructTy()) {
  3024. // We need to extract values.
  3025. unsigned I = 0;
  3026. FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
  3027. if (inheritanceModelHasNVOffsetField(MPT, Inheritance))
  3028. NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
  3029. if (inheritanceModelHasVBPtrOffsetField(Inheritance))
  3030. VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
  3031. if (inheritanceModelHasVBTableOffsetField(Inheritance))
  3032. VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
  3033. }
  3034. if (VirtualBaseAdjustmentOffset) {
  3035. ThisPtrForCall = AdjustVirtualBase(CGF, E, RD, This,
  3036. VirtualBaseAdjustmentOffset, VBPtrOffset);
  3037. } else {
  3038. ThisPtrForCall = This.getPointer();
  3039. }
  3040. if (NonVirtualBaseAdjustment) {
  3041. // Apply the adjustment and cast back to the original struct type.
  3042. llvm::Value *Ptr = Builder.CreateBitCast(ThisPtrForCall, CGF.Int8PtrTy);
  3043. Ptr = Builder.CreateInBoundsGEP(CGF.Int8Ty, Ptr, NonVirtualBaseAdjustment);
  3044. ThisPtrForCall = Builder.CreateBitCast(Ptr, ThisPtrForCall->getType(),
  3045. "this.adjusted");
  3046. }
  3047. FunctionPointer =
  3048. Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
  3049. CGCallee Callee(FPT, FunctionPointer);
  3050. return Callee;
  3051. }
  3052. CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
  3053. return new MicrosoftCXXABI(CGM);
  3054. }
  3055. // MS RTTI Overview:
  3056. // The run time type information emitted by cl.exe contains 5 distinct types of
  3057. // structures. Many of them reference each other.
  3058. //
  3059. // TypeInfo: Static classes that are returned by typeid.
  3060. //
  3061. // CompleteObjectLocator: Referenced by vftables. They contain information
  3062. // required for dynamic casting, including OffsetFromTop. They also contain
  3063. // a reference to the TypeInfo for the type and a reference to the
  3064. // CompleteHierarchyDescriptor for the type.
  3065. //
  3066. // ClassHierarchyDescriptor: Contains information about a class hierarchy.
  3067. // Used during dynamic_cast to walk a class hierarchy. References a base
  3068. // class array and the size of said array.
  3069. //
  3070. // BaseClassArray: Contains a list of classes in a hierarchy. BaseClassArray is
  3071. // somewhat of a misnomer because the most derived class is also in the list
  3072. // as well as multiple copies of virtual bases (if they occur multiple times
  3073. // in the hierarchy.) The BaseClassArray contains one BaseClassDescriptor for
  3074. // every path in the hierarchy, in pre-order depth first order. Note, we do
  3075. // not declare a specific llvm type for BaseClassArray, it's merely an array
  3076. // of BaseClassDescriptor pointers.
  3077. //
  3078. // BaseClassDescriptor: Contains information about a class in a class hierarchy.
  3079. // BaseClassDescriptor is also somewhat of a misnomer for the same reason that
  3080. // BaseClassArray is. It contains information about a class within a
  3081. // hierarchy such as: is this base is ambiguous and what is its offset in the
  3082. // vbtable. The names of the BaseClassDescriptors have all of their fields
  3083. // mangled into them so they can be aggressively deduplicated by the linker.
  3084. static llvm::GlobalVariable *getTypeInfoVTable(CodeGenModule &CGM) {
  3085. StringRef MangledName("??_7type_info@@6B@");
  3086. if (auto VTable = CGM.getModule().getNamedGlobal(MangledName))
  3087. return VTable;
  3088. return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
  3089. /*isConstant=*/true,
  3090. llvm::GlobalVariable::ExternalLinkage,
  3091. /*Initializer=*/nullptr, MangledName);
  3092. }
  3093. namespace {
  3094. /// A Helper struct that stores information about a class in a class
  3095. /// hierarchy. The information stored in these structs struct is used during
  3096. /// the generation of ClassHierarchyDescriptors and BaseClassDescriptors.
  3097. // During RTTI creation, MSRTTIClasses are stored in a contiguous array with
  3098. // implicit depth first pre-order tree connectivity. getFirstChild and
  3099. // getNextSibling allow us to walk the tree efficiently.
  3100. struct MSRTTIClass {
  3101. enum {
  3102. IsPrivateOnPath = 1 | 8,
  3103. IsAmbiguous = 2,
  3104. IsPrivate = 4,
  3105. IsVirtual = 16,
  3106. HasHierarchyDescriptor = 64
  3107. };
  3108. MSRTTIClass(const CXXRecordDecl *RD) : RD(RD) {}
  3109. uint32_t initialize(const MSRTTIClass *Parent,
  3110. const CXXBaseSpecifier *Specifier);
  3111. MSRTTIClass *getFirstChild() { return this + 1; }
  3112. static MSRTTIClass *getNextChild(MSRTTIClass *Child) {
  3113. return Child + 1 + Child->NumBases;
  3114. }
  3115. const CXXRecordDecl *RD, *VirtualRoot;
  3116. uint32_t Flags, NumBases, OffsetInVBase;
  3117. };
  3118. /// Recursively initialize the base class array.
  3119. uint32_t MSRTTIClass::initialize(const MSRTTIClass *Parent,
  3120. const CXXBaseSpecifier *Specifier) {
  3121. Flags = HasHierarchyDescriptor;
  3122. if (!Parent) {
  3123. VirtualRoot = nullptr;
  3124. OffsetInVBase = 0;
  3125. } else {
  3126. if (Specifier->getAccessSpecifier() != AS_public)
  3127. Flags |= IsPrivate | IsPrivateOnPath;
  3128. if (Specifier->isVirtual()) {
  3129. Flags |= IsVirtual;
  3130. VirtualRoot = RD;
  3131. OffsetInVBase = 0;
  3132. } else {
  3133. if (Parent->Flags & IsPrivateOnPath)
  3134. Flags |= IsPrivateOnPath;
  3135. VirtualRoot = Parent->VirtualRoot;
  3136. OffsetInVBase = Parent->OffsetInVBase + RD->getASTContext()
  3137. .getASTRecordLayout(Parent->RD).getBaseClassOffset(RD).getQuantity();
  3138. }
  3139. }
  3140. NumBases = 0;
  3141. MSRTTIClass *Child = getFirstChild();
  3142. for (const CXXBaseSpecifier &Base : RD->bases()) {
  3143. NumBases += Child->initialize(this, &Base) + 1;
  3144. Child = getNextChild(Child);
  3145. }
  3146. return NumBases;
  3147. }
  3148. static llvm::GlobalValue::LinkageTypes getLinkageForRTTI(QualType Ty) {
  3149. switch (Ty->getLinkage()) {
  3150. case NoLinkage:
  3151. case InternalLinkage:
  3152. case UniqueExternalLinkage:
  3153. return llvm::GlobalValue::InternalLinkage;
  3154. case VisibleNoLinkage:
  3155. case ModuleInternalLinkage:
  3156. case ModuleLinkage:
  3157. case ExternalLinkage:
  3158. return llvm::GlobalValue::LinkOnceODRLinkage;
  3159. }
  3160. llvm_unreachable("Invalid linkage!");
  3161. }
  3162. /// An ephemeral helper class for building MS RTTI types. It caches some
  3163. /// calls to the module and information about the most derived class in a
  3164. /// hierarchy.
  3165. struct MSRTTIBuilder {
  3166. enum {
  3167. HasBranchingHierarchy = 1,
  3168. HasVirtualBranchingHierarchy = 2,
  3169. HasAmbiguousBases = 4
  3170. };
  3171. MSRTTIBuilder(MicrosoftCXXABI &ABI, const CXXRecordDecl *RD)
  3172. : CGM(ABI.CGM), Context(CGM.getContext()),
  3173. VMContext(CGM.getLLVMContext()), Module(CGM.getModule()), RD(RD),
  3174. Linkage(getLinkageForRTTI(CGM.getContext().getTagDeclType(RD))),
  3175. ABI(ABI) {}
  3176. llvm::GlobalVariable *getBaseClassDescriptor(const MSRTTIClass &Classes);
  3177. llvm::GlobalVariable *
  3178. getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes);
  3179. llvm::GlobalVariable *getClassHierarchyDescriptor();
  3180. llvm::GlobalVariable *getCompleteObjectLocator(const VPtrInfo &Info);
  3181. CodeGenModule &CGM;
  3182. ASTContext &Context;
  3183. llvm::LLVMContext &VMContext;
  3184. llvm::Module &Module;
  3185. const CXXRecordDecl *RD;
  3186. llvm::GlobalVariable::LinkageTypes Linkage;
  3187. MicrosoftCXXABI &ABI;
  3188. };
  3189. } // namespace
  3190. /// Recursively serializes a class hierarchy in pre-order depth first
  3191. /// order.
  3192. static void serializeClassHierarchy(SmallVectorImpl<MSRTTIClass> &Classes,
  3193. const CXXRecordDecl *RD) {
  3194. Classes.push_back(MSRTTIClass(RD));
  3195. for (const CXXBaseSpecifier &Base : RD->bases())
  3196. serializeClassHierarchy(Classes, Base.getType()->getAsCXXRecordDecl());
  3197. }
  3198. /// Find ambiguity among base classes.
  3199. static void
  3200. detectAmbiguousBases(SmallVectorImpl<MSRTTIClass> &Classes) {
  3201. llvm::SmallPtrSet<const CXXRecordDecl *, 8> VirtualBases;
  3202. llvm::SmallPtrSet<const CXXRecordDecl *, 8> UniqueBases;
  3203. llvm::SmallPtrSet<const CXXRecordDecl *, 8> AmbiguousBases;
  3204. for (MSRTTIClass *Class = &Classes.front(); Class <= &Classes.back();) {
  3205. if ((Class->Flags & MSRTTIClass::IsVirtual) &&
  3206. !VirtualBases.insert(Class->RD).second) {
  3207. Class = MSRTTIClass::getNextChild(Class);
  3208. continue;
  3209. }
  3210. if (!UniqueBases.insert(Class->RD).second)
  3211. AmbiguousBases.insert(Class->RD);
  3212. Class++;
  3213. }
  3214. if (AmbiguousBases.empty())
  3215. return;
  3216. for (MSRTTIClass &Class : Classes)
  3217. if (AmbiguousBases.count(Class.RD))
  3218. Class.Flags |= MSRTTIClass::IsAmbiguous;
  3219. }
  3220. llvm::GlobalVariable *MSRTTIBuilder::getClassHierarchyDescriptor() {
  3221. SmallString<256> MangledName;
  3222. {
  3223. llvm::raw_svector_ostream Out(MangledName);
  3224. ABI.getMangleContext().mangleCXXRTTIClassHierarchyDescriptor(RD, Out);
  3225. }
  3226. // Check to see if we've already declared this ClassHierarchyDescriptor.
  3227. if (auto CHD = Module.getNamedGlobal(MangledName))
  3228. return CHD;
  3229. // Serialize the class hierarchy and initialize the CHD Fields.
  3230. SmallVector<MSRTTIClass, 8> Classes;
  3231. serializeClassHierarchy(Classes, RD);
  3232. Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
  3233. detectAmbiguousBases(Classes);
  3234. int Flags = 0;
  3235. for (auto Class : Classes) {
  3236. if (Class.RD->getNumBases() > 1)
  3237. Flags |= HasBranchingHierarchy;
  3238. // Note: cl.exe does not calculate "HasAmbiguousBases" correctly. We
  3239. // believe the field isn't actually used.
  3240. if (Class.Flags & MSRTTIClass::IsAmbiguous)
  3241. Flags |= HasAmbiguousBases;
  3242. }
  3243. if ((Flags & HasBranchingHierarchy) && RD->getNumVBases() != 0)
  3244. Flags |= HasVirtualBranchingHierarchy;
  3245. // These gep indices are used to get the address of the first element of the
  3246. // base class array.
  3247. llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0),
  3248. llvm::ConstantInt::get(CGM.IntTy, 0)};
  3249. // Forward-declare the class hierarchy descriptor
  3250. auto Type = ABI.getClassHierarchyDescriptorType();
  3251. auto CHD = new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
  3252. /*Initializer=*/nullptr,
  3253. MangledName);
  3254. if (CHD->isWeakForLinker())
  3255. CHD->setComdat(CGM.getModule().getOrInsertComdat(CHD->getName()));
  3256. auto *Bases = getBaseClassArray(Classes);
  3257. // Initialize the base class ClassHierarchyDescriptor.
  3258. llvm::Constant *Fields[] = {
  3259. llvm::ConstantInt::get(CGM.IntTy, 0), // reserved by the runtime
  3260. llvm::ConstantInt::get(CGM.IntTy, Flags),
  3261. llvm::ConstantInt::get(CGM.IntTy, Classes.size()),
  3262. ABI.getImageRelativeConstant(llvm::ConstantExpr::getInBoundsGetElementPtr(
  3263. Bases->getValueType(), Bases,
  3264. llvm::ArrayRef<llvm::Value *>(GEPIndices))),
  3265. };
  3266. CHD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
  3267. return CHD;
  3268. }
  3269. llvm::GlobalVariable *
  3270. MSRTTIBuilder::getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes) {
  3271. SmallString<256> MangledName;
  3272. {
  3273. llvm::raw_svector_ostream Out(MangledName);
  3274. ABI.getMangleContext().mangleCXXRTTIBaseClassArray(RD, Out);
  3275. }
  3276. // Forward-declare the base class array.
  3277. // cl.exe pads the base class array with 1 (in 32 bit mode) or 4 (in 64 bit
  3278. // mode) bytes of padding. We provide a pointer sized amount of padding by
  3279. // adding +1 to Classes.size(). The sections have pointer alignment and are
  3280. // marked pick-any so it shouldn't matter.
  3281. llvm::Type *PtrType = ABI.getImageRelativeType(
  3282. ABI.getBaseClassDescriptorType()->getPointerTo());
  3283. auto *ArrType = llvm::ArrayType::get(PtrType, Classes.size() + 1);
  3284. auto *BCA =
  3285. new llvm::GlobalVariable(Module, ArrType,
  3286. /*isConstant=*/true, Linkage,
  3287. /*Initializer=*/nullptr, MangledName);
  3288. if (BCA->isWeakForLinker())
  3289. BCA->setComdat(CGM.getModule().getOrInsertComdat(BCA->getName()));
  3290. // Initialize the BaseClassArray.
  3291. SmallVector<llvm::Constant *, 8> BaseClassArrayData;
  3292. for (MSRTTIClass &Class : Classes)
  3293. BaseClassArrayData.push_back(
  3294. ABI.getImageRelativeConstant(getBaseClassDescriptor(Class)));
  3295. BaseClassArrayData.push_back(llvm::Constant::getNullValue(PtrType));
  3296. BCA->setInitializer(llvm::ConstantArray::get(ArrType, BaseClassArrayData));
  3297. return BCA;
  3298. }
  3299. llvm::GlobalVariable *
  3300. MSRTTIBuilder::getBaseClassDescriptor(const MSRTTIClass &Class) {
  3301. // Compute the fields for the BaseClassDescriptor. They are computed up front
  3302. // because they are mangled into the name of the object.
  3303. uint32_t OffsetInVBTable = 0;
  3304. int32_t VBPtrOffset = -1;
  3305. if (Class.VirtualRoot) {
  3306. auto &VTableContext = CGM.getMicrosoftVTableContext();
  3307. OffsetInVBTable = VTableContext.getVBTableIndex(RD, Class.VirtualRoot) * 4;
  3308. VBPtrOffset = Context.getASTRecordLayout(RD).getVBPtrOffset().getQuantity();
  3309. }
  3310. SmallString<256> MangledName;
  3311. {
  3312. llvm::raw_svector_ostream Out(MangledName);
  3313. ABI.getMangleContext().mangleCXXRTTIBaseClassDescriptor(
  3314. Class.RD, Class.OffsetInVBase, VBPtrOffset, OffsetInVBTable,
  3315. Class.Flags, Out);
  3316. }
  3317. // Check to see if we've already declared this object.
  3318. if (auto BCD = Module.getNamedGlobal(MangledName))
  3319. return BCD;
  3320. // Forward-declare the base class descriptor.
  3321. auto Type = ABI.getBaseClassDescriptorType();
  3322. auto BCD =
  3323. new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
  3324. /*Initializer=*/nullptr, MangledName);
  3325. if (BCD->isWeakForLinker())
  3326. BCD->setComdat(CGM.getModule().getOrInsertComdat(BCD->getName()));
  3327. // Initialize the BaseClassDescriptor.
  3328. llvm::Constant *Fields[] = {
  3329. ABI.getImageRelativeConstant(
  3330. ABI.getAddrOfRTTIDescriptor(Context.getTypeDeclType(Class.RD))),
  3331. llvm::ConstantInt::get(CGM.IntTy, Class.NumBases),
  3332. llvm::ConstantInt::get(CGM.IntTy, Class.OffsetInVBase),
  3333. llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
  3334. llvm::ConstantInt::get(CGM.IntTy, OffsetInVBTable),
  3335. llvm::ConstantInt::get(CGM.IntTy, Class.Flags),
  3336. ABI.getImageRelativeConstant(
  3337. MSRTTIBuilder(ABI, Class.RD).getClassHierarchyDescriptor()),
  3338. };
  3339. BCD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
  3340. return BCD;
  3341. }
  3342. llvm::GlobalVariable *
  3343. MSRTTIBuilder::getCompleteObjectLocator(const VPtrInfo &Info) {
  3344. SmallString<256> MangledName;
  3345. {
  3346. llvm::raw_svector_ostream Out(MangledName);
  3347. ABI.getMangleContext().mangleCXXRTTICompleteObjectLocator(RD, Info.MangledPath, Out);
  3348. }
  3349. // Check to see if we've already computed this complete object locator.
  3350. if (auto COL = Module.getNamedGlobal(MangledName))
  3351. return COL;
  3352. // Compute the fields of the complete object locator.
  3353. int OffsetToTop = Info.FullOffsetInMDC.getQuantity();
  3354. int VFPtrOffset = 0;
  3355. // The offset includes the vtordisp if one exists.
  3356. if (const CXXRecordDecl *VBase = Info.getVBaseWithVPtr())
  3357. if (Context.getASTRecordLayout(RD)
  3358. .getVBaseOffsetsMap()
  3359. .find(VBase)
  3360. ->second.hasVtorDisp())
  3361. VFPtrOffset = Info.NonVirtualOffset.getQuantity() + 4;
  3362. // Forward-declare the complete object locator.
  3363. llvm::StructType *Type = ABI.getCompleteObjectLocatorType();
  3364. auto COL = new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
  3365. /*Initializer=*/nullptr, MangledName);
  3366. // Initialize the CompleteObjectLocator.
  3367. llvm::Constant *Fields[] = {
  3368. llvm::ConstantInt::get(CGM.IntTy, ABI.isImageRelative()),
  3369. llvm::ConstantInt::get(CGM.IntTy, OffsetToTop),
  3370. llvm::ConstantInt::get(CGM.IntTy, VFPtrOffset),
  3371. ABI.getImageRelativeConstant(
  3372. CGM.GetAddrOfRTTIDescriptor(Context.getTypeDeclType(RD))),
  3373. ABI.getImageRelativeConstant(getClassHierarchyDescriptor()),
  3374. ABI.getImageRelativeConstant(COL),
  3375. };
  3376. llvm::ArrayRef<llvm::Constant *> FieldsRef(Fields);
  3377. if (!ABI.isImageRelative())
  3378. FieldsRef = FieldsRef.drop_back();
  3379. COL->setInitializer(llvm::ConstantStruct::get(Type, FieldsRef));
  3380. if (COL->isWeakForLinker())
  3381. COL->setComdat(CGM.getModule().getOrInsertComdat(COL->getName()));
  3382. return COL;
  3383. }
  3384. static QualType decomposeTypeForEH(ASTContext &Context, QualType T,
  3385. bool &IsConst, bool &IsVolatile,
  3386. bool &IsUnaligned) {
  3387. T = Context.getExceptionObjectType(T);
  3388. // C++14 [except.handle]p3:
  3389. // A handler is a match for an exception object of type E if [...]
  3390. // - the handler is of type cv T or const T& where T is a pointer type and
  3391. // E is a pointer type that can be converted to T by [...]
  3392. // - a qualification conversion
  3393. IsConst = false;
  3394. IsVolatile = false;
  3395. IsUnaligned = false;
  3396. QualType PointeeType = T->getPointeeType();
  3397. if (!PointeeType.isNull()) {
  3398. IsConst = PointeeType.isConstQualified();
  3399. IsVolatile = PointeeType.isVolatileQualified();
  3400. IsUnaligned = PointeeType.getQualifiers().hasUnaligned();
  3401. }
  3402. // Member pointer types like "const int A::*" are represented by having RTTI
  3403. // for "int A::*" and separately storing the const qualifier.
  3404. if (const auto *MPTy = T->getAs<MemberPointerType>())
  3405. T = Context.getMemberPointerType(PointeeType.getUnqualifiedType(),
  3406. MPTy->getClass());
  3407. // Pointer types like "const int * const *" are represented by having RTTI
  3408. // for "const int **" and separately storing the const qualifier.
  3409. if (T->isPointerType())
  3410. T = Context.getPointerType(PointeeType.getUnqualifiedType());
  3411. return T;
  3412. }
  3413. CatchTypeInfo
  3414. MicrosoftCXXABI::getAddrOfCXXCatchHandlerType(QualType Type,
  3415. QualType CatchHandlerType) {
  3416. // TypeDescriptors for exceptions never have qualified pointer types,
  3417. // qualifiers are stored separately in order to support qualification
  3418. // conversions.
  3419. bool IsConst, IsVolatile, IsUnaligned;
  3420. Type =
  3421. decomposeTypeForEH(getContext(), Type, IsConst, IsVolatile, IsUnaligned);
  3422. bool IsReference = CatchHandlerType->isReferenceType();
  3423. uint32_t Flags = 0;
  3424. if (IsConst)
  3425. Flags |= 1;
  3426. if (IsVolatile)
  3427. Flags |= 2;
  3428. if (IsUnaligned)
  3429. Flags |= 4;
  3430. if (IsReference)
  3431. Flags |= 8;
  3432. return CatchTypeInfo{getAddrOfRTTIDescriptor(Type)->stripPointerCasts(),
  3433. Flags};
  3434. }
  3435. /// Gets a TypeDescriptor. Returns a llvm::Constant * rather than a
  3436. /// llvm::GlobalVariable * because different type descriptors have different
  3437. /// types, and need to be abstracted. They are abstracting by casting the
  3438. /// address to an Int8PtrTy.
  3439. llvm::Constant *MicrosoftCXXABI::getAddrOfRTTIDescriptor(QualType Type) {
  3440. SmallString<256> MangledName;
  3441. {
  3442. llvm::raw_svector_ostream Out(MangledName);
  3443. getMangleContext().mangleCXXRTTI(Type, Out);
  3444. }
  3445. // Check to see if we've already declared this TypeDescriptor.
  3446. if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
  3447. return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
  3448. // Note for the future: If we would ever like to do deferred emission of
  3449. // RTTI, check if emitting vtables opportunistically need any adjustment.
  3450. // Compute the fields for the TypeDescriptor.
  3451. SmallString<256> TypeInfoString;
  3452. {
  3453. llvm::raw_svector_ostream Out(TypeInfoString);
  3454. getMangleContext().mangleCXXRTTIName(Type, Out);
  3455. }
  3456. // Declare and initialize the TypeDescriptor.
  3457. llvm::Constant *Fields[] = {
  3458. getTypeInfoVTable(CGM), // VFPtr
  3459. llvm::ConstantPointerNull::get(CGM.Int8PtrTy), // Runtime data
  3460. llvm::ConstantDataArray::getString(CGM.getLLVMContext(), TypeInfoString)};
  3461. llvm::StructType *TypeDescriptorType =
  3462. getTypeDescriptorType(TypeInfoString);
  3463. auto *Var = new llvm::GlobalVariable(
  3464. CGM.getModule(), TypeDescriptorType, /*isConstant=*/false,
  3465. getLinkageForRTTI(Type),
  3466. llvm::ConstantStruct::get(TypeDescriptorType, Fields),
  3467. MangledName);
  3468. if (Var->isWeakForLinker())
  3469. Var->setComdat(CGM.getModule().getOrInsertComdat(Var->getName()));
  3470. return llvm::ConstantExpr::getBitCast(Var, CGM.Int8PtrTy);
  3471. }
  3472. /// Gets or a creates a Microsoft CompleteObjectLocator.
  3473. llvm::GlobalVariable *
  3474. MicrosoftCXXABI::getMSCompleteObjectLocator(const CXXRecordDecl *RD,
  3475. const VPtrInfo &Info) {
  3476. return MSRTTIBuilder(*this, RD).getCompleteObjectLocator(Info);
  3477. }
  3478. void MicrosoftCXXABI::emitCXXStructor(GlobalDecl GD) {
  3479. if (auto *ctor = dyn_cast<CXXConstructorDecl>(GD.getDecl())) {
  3480. // There are no constructor variants, always emit the complete destructor.
  3481. llvm::Function *Fn =
  3482. CGM.codegenCXXStructor(GD.getWithCtorType(Ctor_Complete));
  3483. CGM.maybeSetTrivialComdat(*ctor, *Fn);
  3484. return;
  3485. }
  3486. auto *dtor = cast<CXXDestructorDecl>(GD.getDecl());
  3487. // Emit the base destructor if the base and complete (vbase) destructors are
  3488. // equivalent. This effectively implements -mconstructor-aliases as part of
  3489. // the ABI.
  3490. if (GD.getDtorType() == Dtor_Complete &&
  3491. dtor->getParent()->getNumVBases() == 0)
  3492. GD = GD.getWithDtorType(Dtor_Base);
  3493. // The base destructor is equivalent to the base destructor of its
  3494. // base class if there is exactly one non-virtual base class with a
  3495. // non-trivial destructor, there are no fields with a non-trivial
  3496. // destructor, and the body of the destructor is trivial.
  3497. if (GD.getDtorType() == Dtor_Base && !CGM.TryEmitBaseDestructorAsAlias(dtor))
  3498. return;
  3499. llvm::Function *Fn = CGM.codegenCXXStructor(GD);
  3500. if (Fn->isWeakForLinker())
  3501. Fn->setComdat(CGM.getModule().getOrInsertComdat(Fn->getName()));
  3502. }
  3503. llvm::Function *
  3504. MicrosoftCXXABI::getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
  3505. CXXCtorType CT) {
  3506. assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
  3507. // Calculate the mangled name.
  3508. SmallString<256> ThunkName;
  3509. llvm::raw_svector_ostream Out(ThunkName);
  3510. getMangleContext().mangleName(GlobalDecl(CD, CT), Out);
  3511. // If the thunk has been generated previously, just return it.
  3512. if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
  3513. return cast<llvm::Function>(GV);
  3514. // Create the llvm::Function.
  3515. const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSCtorClosure(CD, CT);
  3516. llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
  3517. const CXXRecordDecl *RD = CD->getParent();
  3518. QualType RecordTy = getContext().getRecordType(RD);
  3519. llvm::Function *ThunkFn = llvm::Function::Create(
  3520. ThunkTy, getLinkageForRTTI(RecordTy), ThunkName.str(), &CGM.getModule());
  3521. ThunkFn->setCallingConv(static_cast<llvm::CallingConv::ID>(
  3522. FnInfo.getEffectiveCallingConvention()));
  3523. if (ThunkFn->isWeakForLinker())
  3524. ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
  3525. bool IsCopy = CT == Ctor_CopyingClosure;
  3526. // Start codegen.
  3527. CodeGenFunction CGF(CGM);
  3528. CGF.CurGD = GlobalDecl(CD, Ctor_Complete);
  3529. // Build FunctionArgs.
  3530. FunctionArgList FunctionArgs;
  3531. // A constructor always starts with a 'this' pointer as its first argument.
  3532. buildThisParam(CGF, FunctionArgs);
  3533. // Following the 'this' pointer is a reference to the source object that we
  3534. // are copying from.
  3535. ImplicitParamDecl SrcParam(
  3536. getContext(), /*DC=*/nullptr, SourceLocation(),
  3537. &getContext().Idents.get("src"),
  3538. getContext().getLValueReferenceType(RecordTy,
  3539. /*SpelledAsLValue=*/true),
  3540. ImplicitParamDecl::Other);
  3541. if (IsCopy)
  3542. FunctionArgs.push_back(&SrcParam);
  3543. // Constructors for classes which utilize virtual bases have an additional
  3544. // parameter which indicates whether or not it is being delegated to by a more
  3545. // derived constructor.
  3546. ImplicitParamDecl IsMostDerived(getContext(), /*DC=*/nullptr,
  3547. SourceLocation(),
  3548. &getContext().Idents.get("is_most_derived"),
  3549. getContext().IntTy, ImplicitParamDecl::Other);
  3550. // Only add the parameter to the list if the class has virtual bases.
  3551. if (RD->getNumVBases() > 0)
  3552. FunctionArgs.push_back(&IsMostDerived);
  3553. // Start defining the function.
  3554. auto NL = ApplyDebugLocation::CreateEmpty(CGF);
  3555. CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
  3556. FunctionArgs, CD->getLocation(), SourceLocation());
  3557. // Create a scope with an artificial location for the body of this function.
  3558. auto AL = ApplyDebugLocation::CreateArtificial(CGF);
  3559. setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
  3560. llvm::Value *This = getThisValue(CGF);
  3561. llvm::Value *SrcVal =
  3562. IsCopy ? CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&SrcParam), "src")
  3563. : nullptr;
  3564. CallArgList Args;
  3565. // Push the this ptr.
  3566. Args.add(RValue::get(This), CD->getThisType());
  3567. // Push the src ptr.
  3568. if (SrcVal)
  3569. Args.add(RValue::get(SrcVal), SrcParam.getType());
  3570. // Add the rest of the default arguments.
  3571. SmallVector<const Stmt *, 4> ArgVec;
  3572. ArrayRef<ParmVarDecl *> params = CD->parameters().drop_front(IsCopy ? 1 : 0);
  3573. for (const ParmVarDecl *PD : params) {
  3574. assert(PD->hasDefaultArg() && "ctor closure lacks default args");
  3575. ArgVec.push_back(PD->getDefaultArg());
  3576. }
  3577. CodeGenFunction::RunCleanupsScope Cleanups(CGF);
  3578. const auto *FPT = CD->getType()->castAs<FunctionProtoType>();
  3579. CGF.EmitCallArgs(Args, FPT, llvm::ArrayRef(ArgVec), CD, IsCopy ? 1 : 0);
  3580. // Insert any ABI-specific implicit constructor arguments.
  3581. AddedStructorArgCounts ExtraArgs =
  3582. addImplicitConstructorArgs(CGF, CD, Ctor_Complete,
  3583. /*ForVirtualBase=*/false,
  3584. /*Delegating=*/false, Args);
  3585. // Call the destructor with our arguments.
  3586. llvm::Constant *CalleePtr =
  3587. CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete));
  3588. CGCallee Callee =
  3589. CGCallee::forDirect(CalleePtr, GlobalDecl(CD, Ctor_Complete));
  3590. const CGFunctionInfo &CalleeInfo = CGM.getTypes().arrangeCXXConstructorCall(
  3591. Args, CD, Ctor_Complete, ExtraArgs.Prefix, ExtraArgs.Suffix);
  3592. CGF.EmitCall(CalleeInfo, Callee, ReturnValueSlot(), Args);
  3593. Cleanups.ForceCleanup();
  3594. // Emit the ret instruction, remove any temporary instructions created for the
  3595. // aid of CodeGen.
  3596. CGF.FinishFunction(SourceLocation());
  3597. return ThunkFn;
  3598. }
  3599. llvm::Constant *MicrosoftCXXABI::getCatchableType(QualType T,
  3600. uint32_t NVOffset,
  3601. int32_t VBPtrOffset,
  3602. uint32_t VBIndex) {
  3603. assert(!T->isReferenceType());
  3604. CXXRecordDecl *RD = T->getAsCXXRecordDecl();
  3605. const CXXConstructorDecl *CD =
  3606. RD ? CGM.getContext().getCopyConstructorForExceptionObject(RD) : nullptr;
  3607. CXXCtorType CT = Ctor_Complete;
  3608. if (CD)
  3609. if (!hasDefaultCXXMethodCC(getContext(), CD) || CD->getNumParams() != 1)
  3610. CT = Ctor_CopyingClosure;
  3611. uint32_t Size = getContext().getTypeSizeInChars(T).getQuantity();
  3612. SmallString<256> MangledName;
  3613. {
  3614. llvm::raw_svector_ostream Out(MangledName);
  3615. getMangleContext().mangleCXXCatchableType(T, CD, CT, Size, NVOffset,
  3616. VBPtrOffset, VBIndex, Out);
  3617. }
  3618. if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
  3619. return getImageRelativeConstant(GV);
  3620. // The TypeDescriptor is used by the runtime to determine if a catch handler
  3621. // is appropriate for the exception object.
  3622. llvm::Constant *TD = getImageRelativeConstant(getAddrOfRTTIDescriptor(T));
  3623. // The runtime is responsible for calling the copy constructor if the
  3624. // exception is caught by value.
  3625. llvm::Constant *CopyCtor;
  3626. if (CD) {
  3627. if (CT == Ctor_CopyingClosure)
  3628. CopyCtor = getAddrOfCXXCtorClosure(CD, Ctor_CopyingClosure);
  3629. else
  3630. CopyCtor = CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete));
  3631. CopyCtor = llvm::ConstantExpr::getBitCast(CopyCtor, CGM.Int8PtrTy);
  3632. } else {
  3633. CopyCtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
  3634. }
  3635. CopyCtor = getImageRelativeConstant(CopyCtor);
  3636. bool IsScalar = !RD;
  3637. bool HasVirtualBases = false;
  3638. bool IsStdBadAlloc = false; // std::bad_alloc is special for some reason.
  3639. QualType PointeeType = T;
  3640. if (T->isPointerType())
  3641. PointeeType = T->getPointeeType();
  3642. if (const CXXRecordDecl *RD = PointeeType->getAsCXXRecordDecl()) {
  3643. HasVirtualBases = RD->getNumVBases() > 0;
  3644. if (IdentifierInfo *II = RD->getIdentifier())
  3645. IsStdBadAlloc = II->isStr("bad_alloc") && RD->isInStdNamespace();
  3646. }
  3647. // Encode the relevant CatchableType properties into the Flags bitfield.
  3648. // FIXME: Figure out how bits 2 or 8 can get set.
  3649. uint32_t Flags = 0;
  3650. if (IsScalar)
  3651. Flags |= 1;
  3652. if (HasVirtualBases)
  3653. Flags |= 4;
  3654. if (IsStdBadAlloc)
  3655. Flags |= 16;
  3656. llvm::Constant *Fields[] = {
  3657. llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
  3658. TD, // TypeDescriptor
  3659. llvm::ConstantInt::get(CGM.IntTy, NVOffset), // NonVirtualAdjustment
  3660. llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset), // OffsetToVBPtr
  3661. llvm::ConstantInt::get(CGM.IntTy, VBIndex), // VBTableIndex
  3662. llvm::ConstantInt::get(CGM.IntTy, Size), // Size
  3663. CopyCtor // CopyCtor
  3664. };
  3665. llvm::StructType *CTType = getCatchableTypeType();
  3666. auto *GV = new llvm::GlobalVariable(
  3667. CGM.getModule(), CTType, /*isConstant=*/true, getLinkageForRTTI(T),
  3668. llvm::ConstantStruct::get(CTType, Fields), MangledName);
  3669. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  3670. GV->setSection(".xdata");
  3671. if (GV->isWeakForLinker())
  3672. GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
  3673. return getImageRelativeConstant(GV);
  3674. }
  3675. llvm::GlobalVariable *MicrosoftCXXABI::getCatchableTypeArray(QualType T) {
  3676. assert(!T->isReferenceType());
  3677. // See if we've already generated a CatchableTypeArray for this type before.
  3678. llvm::GlobalVariable *&CTA = CatchableTypeArrays[T];
  3679. if (CTA)
  3680. return CTA;
  3681. // Ensure that we don't have duplicate entries in our CatchableTypeArray by
  3682. // using a SmallSetVector. Duplicates may arise due to virtual bases
  3683. // occurring more than once in the hierarchy.
  3684. llvm::SmallSetVector<llvm::Constant *, 2> CatchableTypes;
  3685. // C++14 [except.handle]p3:
  3686. // A handler is a match for an exception object of type E if [...]
  3687. // - the handler is of type cv T or cv T& and T is an unambiguous public
  3688. // base class of E, or
  3689. // - the handler is of type cv T or const T& where T is a pointer type and
  3690. // E is a pointer type that can be converted to T by [...]
  3691. // - a standard pointer conversion (4.10) not involving conversions to
  3692. // pointers to private or protected or ambiguous classes
  3693. const CXXRecordDecl *MostDerivedClass = nullptr;
  3694. bool IsPointer = T->isPointerType();
  3695. if (IsPointer)
  3696. MostDerivedClass = T->getPointeeType()->getAsCXXRecordDecl();
  3697. else
  3698. MostDerivedClass = T->getAsCXXRecordDecl();
  3699. // Collect all the unambiguous public bases of the MostDerivedClass.
  3700. if (MostDerivedClass) {
  3701. const ASTContext &Context = getContext();
  3702. const ASTRecordLayout &MostDerivedLayout =
  3703. Context.getASTRecordLayout(MostDerivedClass);
  3704. MicrosoftVTableContext &VTableContext = CGM.getMicrosoftVTableContext();
  3705. SmallVector<MSRTTIClass, 8> Classes;
  3706. serializeClassHierarchy(Classes, MostDerivedClass);
  3707. Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
  3708. detectAmbiguousBases(Classes);
  3709. for (const MSRTTIClass &Class : Classes) {
  3710. // Skip any ambiguous or private bases.
  3711. if (Class.Flags &
  3712. (MSRTTIClass::IsPrivateOnPath | MSRTTIClass::IsAmbiguous))
  3713. continue;
  3714. // Write down how to convert from a derived pointer to a base pointer.
  3715. uint32_t OffsetInVBTable = 0;
  3716. int32_t VBPtrOffset = -1;
  3717. if (Class.VirtualRoot) {
  3718. OffsetInVBTable =
  3719. VTableContext.getVBTableIndex(MostDerivedClass, Class.VirtualRoot)*4;
  3720. VBPtrOffset = MostDerivedLayout.getVBPtrOffset().getQuantity();
  3721. }
  3722. // Turn our record back into a pointer if the exception object is a
  3723. // pointer.
  3724. QualType RTTITy = QualType(Class.RD->getTypeForDecl(), 0);
  3725. if (IsPointer)
  3726. RTTITy = Context.getPointerType(RTTITy);
  3727. CatchableTypes.insert(getCatchableType(RTTITy, Class.OffsetInVBase,
  3728. VBPtrOffset, OffsetInVBTable));
  3729. }
  3730. }
  3731. // C++14 [except.handle]p3:
  3732. // A handler is a match for an exception object of type E if
  3733. // - The handler is of type cv T or cv T& and E and T are the same type
  3734. // (ignoring the top-level cv-qualifiers)
  3735. CatchableTypes.insert(getCatchableType(T));
  3736. // C++14 [except.handle]p3:
  3737. // A handler is a match for an exception object of type E if
  3738. // - the handler is of type cv T or const T& where T is a pointer type and
  3739. // E is a pointer type that can be converted to T by [...]
  3740. // - a standard pointer conversion (4.10) not involving conversions to
  3741. // pointers to private or protected or ambiguous classes
  3742. //
  3743. // C++14 [conv.ptr]p2:
  3744. // A prvalue of type "pointer to cv T," where T is an object type, can be
  3745. // converted to a prvalue of type "pointer to cv void".
  3746. if (IsPointer && T->getPointeeType()->isObjectType())
  3747. CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
  3748. // C++14 [except.handle]p3:
  3749. // A handler is a match for an exception object of type E if [...]
  3750. // - the handler is of type cv T or const T& where T is a pointer or
  3751. // pointer to member type and E is std::nullptr_t.
  3752. //
  3753. // We cannot possibly list all possible pointer types here, making this
  3754. // implementation incompatible with the standard. However, MSVC includes an
  3755. // entry for pointer-to-void in this case. Let's do the same.
  3756. if (T->isNullPtrType())
  3757. CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
  3758. uint32_t NumEntries = CatchableTypes.size();
  3759. llvm::Type *CTType =
  3760. getImageRelativeType(getCatchableTypeType()->getPointerTo());
  3761. llvm::ArrayType *AT = llvm::ArrayType::get(CTType, NumEntries);
  3762. llvm::StructType *CTAType = getCatchableTypeArrayType(NumEntries);
  3763. llvm::Constant *Fields[] = {
  3764. llvm::ConstantInt::get(CGM.IntTy, NumEntries), // NumEntries
  3765. llvm::ConstantArray::get(
  3766. AT, llvm::ArrayRef(CatchableTypes.begin(),
  3767. CatchableTypes.end())) // CatchableTypes
  3768. };
  3769. SmallString<256> MangledName;
  3770. {
  3771. llvm::raw_svector_ostream Out(MangledName);
  3772. getMangleContext().mangleCXXCatchableTypeArray(T, NumEntries, Out);
  3773. }
  3774. CTA = new llvm::GlobalVariable(
  3775. CGM.getModule(), CTAType, /*isConstant=*/true, getLinkageForRTTI(T),
  3776. llvm::ConstantStruct::get(CTAType, Fields), MangledName);
  3777. CTA->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  3778. CTA->setSection(".xdata");
  3779. if (CTA->isWeakForLinker())
  3780. CTA->setComdat(CGM.getModule().getOrInsertComdat(CTA->getName()));
  3781. return CTA;
  3782. }
  3783. llvm::GlobalVariable *MicrosoftCXXABI::getThrowInfo(QualType T) {
  3784. bool IsConst, IsVolatile, IsUnaligned;
  3785. T = decomposeTypeForEH(getContext(), T, IsConst, IsVolatile, IsUnaligned);
  3786. // The CatchableTypeArray enumerates the various (CV-unqualified) types that
  3787. // the exception object may be caught as.
  3788. llvm::GlobalVariable *CTA = getCatchableTypeArray(T);
  3789. // The first field in a CatchableTypeArray is the number of CatchableTypes.
  3790. // This is used as a component of the mangled name which means that we need to
  3791. // know what it is in order to see if we have previously generated the
  3792. // ThrowInfo.
  3793. uint32_t NumEntries =
  3794. cast<llvm::ConstantInt>(CTA->getInitializer()->getAggregateElement(0U))
  3795. ->getLimitedValue();
  3796. SmallString<256> MangledName;
  3797. {
  3798. llvm::raw_svector_ostream Out(MangledName);
  3799. getMangleContext().mangleCXXThrowInfo(T, IsConst, IsVolatile, IsUnaligned,
  3800. NumEntries, Out);
  3801. }
  3802. // Reuse a previously generated ThrowInfo if we have generated an appropriate
  3803. // one before.
  3804. if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
  3805. return GV;
  3806. // The RTTI TypeDescriptor uses an unqualified type but catch clauses must
  3807. // be at least as CV qualified. Encode this requirement into the Flags
  3808. // bitfield.
  3809. uint32_t Flags = 0;
  3810. if (IsConst)
  3811. Flags |= 1;
  3812. if (IsVolatile)
  3813. Flags |= 2;
  3814. if (IsUnaligned)
  3815. Flags |= 4;
  3816. // The cleanup-function (a destructor) must be called when the exception
  3817. // object's lifetime ends.
  3818. llvm::Constant *CleanupFn = llvm::Constant::getNullValue(CGM.Int8PtrTy);
  3819. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  3820. if (CXXDestructorDecl *DtorD = RD->getDestructor())
  3821. if (!DtorD->isTrivial())
  3822. CleanupFn = llvm::ConstantExpr::getBitCast(
  3823. CGM.getAddrOfCXXStructor(GlobalDecl(DtorD, Dtor_Complete)),
  3824. CGM.Int8PtrTy);
  3825. // This is unused as far as we can tell, initialize it to null.
  3826. llvm::Constant *ForwardCompat =
  3827. getImageRelativeConstant(llvm::Constant::getNullValue(CGM.Int8PtrTy));
  3828. llvm::Constant *PointerToCatchableTypes = getImageRelativeConstant(
  3829. llvm::ConstantExpr::getBitCast(CTA, CGM.Int8PtrTy));
  3830. llvm::StructType *TIType = getThrowInfoType();
  3831. llvm::Constant *Fields[] = {
  3832. llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
  3833. getImageRelativeConstant(CleanupFn), // CleanupFn
  3834. ForwardCompat, // ForwardCompat
  3835. PointerToCatchableTypes // CatchableTypeArray
  3836. };
  3837. auto *GV = new llvm::GlobalVariable(
  3838. CGM.getModule(), TIType, /*isConstant=*/true, getLinkageForRTTI(T),
  3839. llvm::ConstantStruct::get(TIType, Fields), MangledName.str());
  3840. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  3841. GV->setSection(".xdata");
  3842. if (GV->isWeakForLinker())
  3843. GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
  3844. return GV;
  3845. }
  3846. void MicrosoftCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
  3847. const Expr *SubExpr = E->getSubExpr();
  3848. assert(SubExpr && "SubExpr cannot be null");
  3849. QualType ThrowType = SubExpr->getType();
  3850. // The exception object lives on the stack and it's address is passed to the
  3851. // runtime function.
  3852. Address AI = CGF.CreateMemTemp(ThrowType);
  3853. CGF.EmitAnyExprToMem(SubExpr, AI, ThrowType.getQualifiers(),
  3854. /*IsInit=*/true);
  3855. // The so-called ThrowInfo is used to describe how the exception object may be
  3856. // caught.
  3857. llvm::GlobalVariable *TI = getThrowInfo(ThrowType);
  3858. // Call into the runtime to throw the exception.
  3859. llvm::Value *Args[] = {
  3860. CGF.Builder.CreateBitCast(AI.getPointer(), CGM.Int8PtrTy),
  3861. TI
  3862. };
  3863. CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(), Args);
  3864. }
  3865. std::pair<llvm::Value *, const CXXRecordDecl *>
  3866. MicrosoftCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
  3867. const CXXRecordDecl *RD) {
  3868. std::tie(This, std::ignore, RD) =
  3869. performBaseAdjustment(CGF, This, QualType(RD->getTypeForDecl(), 0));
  3870. return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
  3871. }
  3872. bool MicrosoftCXXABI::isPermittedToBeHomogeneousAggregate(
  3873. const CXXRecordDecl *RD) const {
  3874. // All aggregates are permitted to be HFA on non-ARM platforms, which mostly
  3875. // affects vectorcall on x64/x86.
  3876. if (!CGM.getTarget().getTriple().isAArch64())
  3877. return true;
  3878. // MSVC Windows on Arm64 has its own rules for determining if a type is HFA
  3879. // that are inconsistent with the AAPCS64 ABI. The following are our best
  3880. // determination of those rules so far, based on observation of MSVC's
  3881. // behavior.
  3882. if (RD->isEmpty())
  3883. return false;
  3884. if (RD->isPolymorphic())
  3885. return false;
  3886. if (RD->hasNonTrivialCopyAssignment())
  3887. return false;
  3888. if (RD->hasNonTrivialDestructor())
  3889. return false;
  3890. if (RD->hasNonTrivialDefaultConstructor())
  3891. return false;
  3892. // These two are somewhat redundant given the caller
  3893. // (ABIInfo::isHomogeneousAggregate) checks the bases and fields, but that
  3894. // caller doesn't consider empty bases/fields to be non-homogenous, but it
  3895. // looks like Microsoft's AArch64 ABI does care about these empty types &
  3896. // anything containing/derived from one is non-homogeneous.
  3897. // Instead we could add another CXXABI entry point to query this property and
  3898. // have ABIInfo::isHomogeneousAggregate use that property.
  3899. // I don't think any other of the features listed above could be true of a
  3900. // base/field while not true of the outer struct. For example, if you have a
  3901. // base/field that has an non-trivial copy assignment/dtor/default ctor, then
  3902. // the outer struct's corresponding operation must be non-trivial.
  3903. for (const CXXBaseSpecifier &B : RD->bases()) {
  3904. if (const CXXRecordDecl *FRD = B.getType()->getAsCXXRecordDecl()) {
  3905. if (!isPermittedToBeHomogeneousAggregate(FRD))
  3906. return false;
  3907. }
  3908. }
  3909. // empty fields seem to be caught by the ABIInfo::isHomogeneousAggregate
  3910. // checking for padding - but maybe there are ways to end up with an empty
  3911. // field without padding? Not that I know of, so don't check fields here &
  3912. // rely on the padding check.
  3913. return true;
  3914. }