MicrosoftCXXABI.cpp 166 KB

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