MicrosoftCXXABI.cpp 173 KB

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