VTableBuilder.cpp 137 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750
  1. //===--- VTableBuilder.cpp - C++ vtable layout builder --------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This contains code dealing with generation of the layout of virtual tables.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/VTableBuilder.h"
  13. #include "clang/AST/ASTContext.h"
  14. #include "clang/AST/ASTDiagnostic.h"
  15. #include "clang/AST/CXXInheritance.h"
  16. #include "clang/AST/RecordLayout.h"
  17. #include "clang/Basic/TargetInfo.h"
  18. #include "llvm/ADT/SetOperations.h"
  19. #include "llvm/ADT/SmallPtrSet.h"
  20. #include "llvm/Support/Format.h"
  21. #include "llvm/Support/raw_ostream.h"
  22. #include <algorithm>
  23. #include <cstdio>
  24. using namespace clang;
  25. #define DUMP_OVERRIDERS 0
  26. namespace {
  27. /// BaseOffset - Represents an offset from a derived class to a direct or
  28. /// indirect base class.
  29. struct BaseOffset {
  30. /// DerivedClass - The derived class.
  31. const CXXRecordDecl *DerivedClass;
  32. /// VirtualBase - If the path from the derived class to the base class
  33. /// involves virtual base classes, this holds the declaration of the last
  34. /// virtual base in this path (i.e. closest to the base class).
  35. const CXXRecordDecl *VirtualBase;
  36. /// NonVirtualOffset - The offset from the derived class to the base class.
  37. /// (Or the offset from the virtual base class to the base class, if the
  38. /// path from the derived class to the base class involves a virtual base
  39. /// class.
  40. CharUnits NonVirtualOffset;
  41. BaseOffset() : DerivedClass(nullptr), VirtualBase(nullptr),
  42. NonVirtualOffset(CharUnits::Zero()) { }
  43. BaseOffset(const CXXRecordDecl *DerivedClass,
  44. const CXXRecordDecl *VirtualBase, CharUnits NonVirtualOffset)
  45. : DerivedClass(DerivedClass), VirtualBase(VirtualBase),
  46. NonVirtualOffset(NonVirtualOffset) { }
  47. bool isEmpty() const { return NonVirtualOffset.isZero() && !VirtualBase; }
  48. };
  49. /// FinalOverriders - Contains the final overrider member functions for all
  50. /// member functions in the base subobjects of a class.
  51. class FinalOverriders {
  52. public:
  53. /// OverriderInfo - Information about a final overrider.
  54. struct OverriderInfo {
  55. /// Method - The method decl of the overrider.
  56. const CXXMethodDecl *Method;
  57. /// VirtualBase - The virtual base class subobject of this overrider.
  58. /// Note that this records the closest derived virtual base class subobject.
  59. const CXXRecordDecl *VirtualBase;
  60. /// Offset - the base offset of the overrider's parent in the layout class.
  61. CharUnits Offset;
  62. OverriderInfo() : Method(nullptr), VirtualBase(nullptr),
  63. Offset(CharUnits::Zero()) { }
  64. };
  65. private:
  66. /// MostDerivedClass - The most derived class for which the final overriders
  67. /// are stored.
  68. const CXXRecordDecl *MostDerivedClass;
  69. /// MostDerivedClassOffset - If we're building final overriders for a
  70. /// construction vtable, this holds the offset from the layout class to the
  71. /// most derived class.
  72. const CharUnits MostDerivedClassOffset;
  73. /// LayoutClass - The class we're using for layout information. Will be
  74. /// different than the most derived class if the final overriders are for a
  75. /// construction vtable.
  76. const CXXRecordDecl *LayoutClass;
  77. ASTContext &Context;
  78. /// MostDerivedClassLayout - the AST record layout of the most derived class.
  79. const ASTRecordLayout &MostDerivedClassLayout;
  80. /// MethodBaseOffsetPairTy - Uniquely identifies a member function
  81. /// in a base subobject.
  82. typedef std::pair<const CXXMethodDecl *, CharUnits> MethodBaseOffsetPairTy;
  83. typedef llvm::DenseMap<MethodBaseOffsetPairTy,
  84. OverriderInfo> OverridersMapTy;
  85. /// OverridersMap - The final overriders for all virtual member functions of
  86. /// all the base subobjects of the most derived class.
  87. OverridersMapTy OverridersMap;
  88. /// SubobjectsToOffsetsMapTy - A mapping from a base subobject (represented
  89. /// as a record decl and a subobject number) and its offsets in the most
  90. /// derived class as well as the layout class.
  91. typedef llvm::DenseMap<std::pair<const CXXRecordDecl *, unsigned>,
  92. CharUnits> SubobjectOffsetMapTy;
  93. typedef llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCountMapTy;
  94. /// ComputeBaseOffsets - Compute the offsets for all base subobjects of the
  95. /// given base.
  96. void ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
  97. CharUnits OffsetInLayoutClass,
  98. SubobjectOffsetMapTy &SubobjectOffsets,
  99. SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
  100. SubobjectCountMapTy &SubobjectCounts);
  101. typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
  102. /// dump - dump the final overriders for a base subobject, and all its direct
  103. /// and indirect base subobjects.
  104. void dump(raw_ostream &Out, BaseSubobject Base,
  105. VisitedVirtualBasesSetTy& VisitedVirtualBases);
  106. public:
  107. FinalOverriders(const CXXRecordDecl *MostDerivedClass,
  108. CharUnits MostDerivedClassOffset,
  109. const CXXRecordDecl *LayoutClass);
  110. /// getOverrider - Get the final overrider for the given method declaration in
  111. /// the subobject with the given base offset.
  112. OverriderInfo getOverrider(const CXXMethodDecl *MD,
  113. CharUnits BaseOffset) const {
  114. assert(OverridersMap.count(std::make_pair(MD, BaseOffset)) &&
  115. "Did not find overrider!");
  116. return OverridersMap.lookup(std::make_pair(MD, BaseOffset));
  117. }
  118. /// dump - dump the final overriders.
  119. void dump() {
  120. VisitedVirtualBasesSetTy VisitedVirtualBases;
  121. dump(llvm::errs(), BaseSubobject(MostDerivedClass, CharUnits::Zero()),
  122. VisitedVirtualBases);
  123. }
  124. };
  125. FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass,
  126. CharUnits MostDerivedClassOffset,
  127. const CXXRecordDecl *LayoutClass)
  128. : MostDerivedClass(MostDerivedClass),
  129. MostDerivedClassOffset(MostDerivedClassOffset), LayoutClass(LayoutClass),
  130. Context(MostDerivedClass->getASTContext()),
  131. MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) {
  132. // Compute base offsets.
  133. SubobjectOffsetMapTy SubobjectOffsets;
  134. SubobjectOffsetMapTy SubobjectLayoutClassOffsets;
  135. SubobjectCountMapTy SubobjectCounts;
  136. ComputeBaseOffsets(BaseSubobject(MostDerivedClass, CharUnits::Zero()),
  137. /*IsVirtual=*/false,
  138. MostDerivedClassOffset,
  139. SubobjectOffsets, SubobjectLayoutClassOffsets,
  140. SubobjectCounts);
  141. // Get the final overriders.
  142. CXXFinalOverriderMap FinalOverriders;
  143. MostDerivedClass->getFinalOverriders(FinalOverriders);
  144. for (const auto &Overrider : FinalOverriders) {
  145. const CXXMethodDecl *MD = Overrider.first;
  146. const OverridingMethods &Methods = Overrider.second;
  147. for (const auto &M : Methods) {
  148. unsigned SubobjectNumber = M.first;
  149. assert(SubobjectOffsets.count(std::make_pair(MD->getParent(),
  150. SubobjectNumber)) &&
  151. "Did not find subobject offset!");
  152. CharUnits BaseOffset = SubobjectOffsets[std::make_pair(MD->getParent(),
  153. SubobjectNumber)];
  154. assert(M.second.size() == 1 && "Final overrider is not unique!");
  155. const UniqueVirtualMethod &Method = M.second.front();
  156. const CXXRecordDecl *OverriderRD = Method.Method->getParent();
  157. assert(SubobjectLayoutClassOffsets.count(
  158. std::make_pair(OverriderRD, Method.Subobject))
  159. && "Did not find subobject offset!");
  160. CharUnits OverriderOffset =
  161. SubobjectLayoutClassOffsets[std::make_pair(OverriderRD,
  162. Method.Subobject)];
  163. OverriderInfo& Overrider = OverridersMap[std::make_pair(MD, BaseOffset)];
  164. assert(!Overrider.Method && "Overrider should not exist yet!");
  165. Overrider.Offset = OverriderOffset;
  166. Overrider.Method = Method.Method;
  167. Overrider.VirtualBase = Method.InVirtualSubobject;
  168. }
  169. }
  170. #if DUMP_OVERRIDERS
  171. // And dump them (for now).
  172. dump();
  173. #endif
  174. }
  175. static BaseOffset ComputeBaseOffset(const ASTContext &Context,
  176. const CXXRecordDecl *DerivedRD,
  177. const CXXBasePath &Path) {
  178. CharUnits NonVirtualOffset = CharUnits::Zero();
  179. unsigned NonVirtualStart = 0;
  180. const CXXRecordDecl *VirtualBase = nullptr;
  181. // First, look for the virtual base class.
  182. for (int I = Path.size(), E = 0; I != E; --I) {
  183. const CXXBasePathElement &Element = Path[I - 1];
  184. if (Element.Base->isVirtual()) {
  185. NonVirtualStart = I;
  186. QualType VBaseType = Element.Base->getType();
  187. VirtualBase = VBaseType->getAsCXXRecordDecl();
  188. break;
  189. }
  190. }
  191. // Now compute the non-virtual offset.
  192. for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) {
  193. const CXXBasePathElement &Element = Path[I];
  194. // Check the base class offset.
  195. const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
  196. const CXXRecordDecl *Base = Element.Base->getType()->getAsCXXRecordDecl();
  197. NonVirtualOffset += Layout.getBaseClassOffset(Base);
  198. }
  199. // FIXME: This should probably use CharUnits or something. Maybe we should
  200. // even change the base offsets in ASTRecordLayout to be specified in
  201. // CharUnits.
  202. return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset);
  203. }
  204. static BaseOffset ComputeBaseOffset(const ASTContext &Context,
  205. const CXXRecordDecl *BaseRD,
  206. const CXXRecordDecl *DerivedRD) {
  207. CXXBasePaths Paths(/*FindAmbiguities=*/false,
  208. /*RecordPaths=*/true, /*DetectVirtual=*/false);
  209. if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
  210. llvm_unreachable("Class must be derived from the passed in base class!");
  211. return ComputeBaseOffset(Context, DerivedRD, Paths.front());
  212. }
  213. static BaseOffset
  214. ComputeReturnAdjustmentBaseOffset(ASTContext &Context,
  215. const CXXMethodDecl *DerivedMD,
  216. const CXXMethodDecl *BaseMD) {
  217. const FunctionType *BaseFT = BaseMD->getType()->getAs<FunctionType>();
  218. const FunctionType *DerivedFT = DerivedMD->getType()->getAs<FunctionType>();
  219. // Canonicalize the return types.
  220. CanQualType CanDerivedReturnType =
  221. Context.getCanonicalType(DerivedFT->getReturnType());
  222. CanQualType CanBaseReturnType =
  223. Context.getCanonicalType(BaseFT->getReturnType());
  224. assert(CanDerivedReturnType->getTypeClass() ==
  225. CanBaseReturnType->getTypeClass() &&
  226. "Types must have same type class!");
  227. if (CanDerivedReturnType == CanBaseReturnType) {
  228. // No adjustment needed.
  229. return BaseOffset();
  230. }
  231. if (isa<ReferenceType>(CanDerivedReturnType)) {
  232. CanDerivedReturnType =
  233. CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType();
  234. CanBaseReturnType =
  235. CanBaseReturnType->getAs<ReferenceType>()->getPointeeType();
  236. } else if (isa<PointerType>(CanDerivedReturnType)) {
  237. CanDerivedReturnType =
  238. CanDerivedReturnType->getAs<PointerType>()->getPointeeType();
  239. CanBaseReturnType =
  240. CanBaseReturnType->getAs<PointerType>()->getPointeeType();
  241. } else {
  242. llvm_unreachable("Unexpected return type!");
  243. }
  244. // We need to compare unqualified types here; consider
  245. // const T *Base::foo();
  246. // T *Derived::foo();
  247. if (CanDerivedReturnType.getUnqualifiedType() ==
  248. CanBaseReturnType.getUnqualifiedType()) {
  249. // No adjustment needed.
  250. return BaseOffset();
  251. }
  252. const CXXRecordDecl *DerivedRD =
  253. cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl());
  254. const CXXRecordDecl *BaseRD =
  255. cast<CXXRecordDecl>(cast<RecordType>(CanBaseReturnType)->getDecl());
  256. return ComputeBaseOffset(Context, BaseRD, DerivedRD);
  257. }
  258. void
  259. FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
  260. CharUnits OffsetInLayoutClass,
  261. SubobjectOffsetMapTy &SubobjectOffsets,
  262. SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
  263. SubobjectCountMapTy &SubobjectCounts) {
  264. const CXXRecordDecl *RD = Base.getBase();
  265. unsigned SubobjectNumber = 0;
  266. if (!IsVirtual)
  267. SubobjectNumber = ++SubobjectCounts[RD];
  268. // Set up the subobject to offset mapping.
  269. assert(!SubobjectOffsets.count(std::make_pair(RD, SubobjectNumber))
  270. && "Subobject offset already exists!");
  271. assert(!SubobjectLayoutClassOffsets.count(std::make_pair(RD, SubobjectNumber))
  272. && "Subobject offset already exists!");
  273. SubobjectOffsets[std::make_pair(RD, SubobjectNumber)] = Base.getBaseOffset();
  274. SubobjectLayoutClassOffsets[std::make_pair(RD, SubobjectNumber)] =
  275. OffsetInLayoutClass;
  276. // Traverse our bases.
  277. for (const auto &B : RD->bases()) {
  278. const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
  279. CharUnits BaseOffset;
  280. CharUnits BaseOffsetInLayoutClass;
  281. if (B.isVirtual()) {
  282. // Check if we've visited this virtual base before.
  283. if (SubobjectOffsets.count(std::make_pair(BaseDecl, 0)))
  284. continue;
  285. const ASTRecordLayout &LayoutClassLayout =
  286. Context.getASTRecordLayout(LayoutClass);
  287. BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
  288. BaseOffsetInLayoutClass =
  289. LayoutClassLayout.getVBaseClassOffset(BaseDecl);
  290. } else {
  291. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  292. CharUnits Offset = Layout.getBaseClassOffset(BaseDecl);
  293. BaseOffset = Base.getBaseOffset() + Offset;
  294. BaseOffsetInLayoutClass = OffsetInLayoutClass + Offset;
  295. }
  296. ComputeBaseOffsets(BaseSubobject(BaseDecl, BaseOffset),
  297. B.isVirtual(), BaseOffsetInLayoutClass,
  298. SubobjectOffsets, SubobjectLayoutClassOffsets,
  299. SubobjectCounts);
  300. }
  301. }
  302. void FinalOverriders::dump(raw_ostream &Out, BaseSubobject Base,
  303. VisitedVirtualBasesSetTy &VisitedVirtualBases) {
  304. const CXXRecordDecl *RD = Base.getBase();
  305. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  306. for (const auto &B : RD->bases()) {
  307. const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
  308. // Ignore bases that don't have any virtual member functions.
  309. if (!BaseDecl->isPolymorphic())
  310. continue;
  311. CharUnits BaseOffset;
  312. if (B.isVirtual()) {
  313. if (!VisitedVirtualBases.insert(BaseDecl).second) {
  314. // We've visited this base before.
  315. continue;
  316. }
  317. BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
  318. } else {
  319. BaseOffset = Layout.getBaseClassOffset(BaseDecl) + Base.getBaseOffset();
  320. }
  321. dump(Out, BaseSubobject(BaseDecl, BaseOffset), VisitedVirtualBases);
  322. }
  323. Out << "Final overriders for (";
  324. RD->printQualifiedName(Out);
  325. Out << ", ";
  326. Out << Base.getBaseOffset().getQuantity() << ")\n";
  327. // Now dump the overriders for this base subobject.
  328. for (const auto *MD : RD->methods()) {
  329. if (!MD->isVirtual())
  330. continue;
  331. MD = MD->getCanonicalDecl();
  332. OverriderInfo Overrider = getOverrider(MD, Base.getBaseOffset());
  333. Out << " ";
  334. MD->printQualifiedName(Out);
  335. Out << " - (";
  336. Overrider.Method->printQualifiedName(Out);
  337. Out << ", " << Overrider.Offset.getQuantity() << ')';
  338. BaseOffset Offset;
  339. if (!Overrider.Method->isPure())
  340. Offset = ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
  341. if (!Offset.isEmpty()) {
  342. Out << " [ret-adj: ";
  343. if (Offset.VirtualBase) {
  344. Offset.VirtualBase->printQualifiedName(Out);
  345. Out << " vbase, ";
  346. }
  347. Out << Offset.NonVirtualOffset.getQuantity() << " nv]";
  348. }
  349. Out << "\n";
  350. }
  351. }
  352. /// VCallOffsetMap - Keeps track of vcall offsets when building a vtable.
  353. struct VCallOffsetMap {
  354. typedef std::pair<const CXXMethodDecl *, CharUnits> MethodAndOffsetPairTy;
  355. /// Offsets - Keeps track of methods and their offsets.
  356. // FIXME: This should be a real map and not a vector.
  357. SmallVector<MethodAndOffsetPairTy, 16> Offsets;
  358. /// MethodsCanShareVCallOffset - Returns whether two virtual member functions
  359. /// can share the same vcall offset.
  360. static bool MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
  361. const CXXMethodDecl *RHS);
  362. public:
  363. /// AddVCallOffset - Adds a vcall offset to the map. Returns true if the
  364. /// add was successful, or false if there was already a member function with
  365. /// the same signature in the map.
  366. bool AddVCallOffset(const CXXMethodDecl *MD, CharUnits OffsetOffset);
  367. /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the
  368. /// vtable address point) for the given virtual member function.
  369. CharUnits getVCallOffsetOffset(const CXXMethodDecl *MD);
  370. // empty - Return whether the offset map is empty or not.
  371. bool empty() const { return Offsets.empty(); }
  372. };
  373. static bool HasSameVirtualSignature(const CXXMethodDecl *LHS,
  374. const CXXMethodDecl *RHS) {
  375. const FunctionProtoType *LT =
  376. cast<FunctionProtoType>(LHS->getType().getCanonicalType());
  377. const FunctionProtoType *RT =
  378. cast<FunctionProtoType>(RHS->getType().getCanonicalType());
  379. // Fast-path matches in the canonical types.
  380. if (LT == RT) return true;
  381. // Force the signatures to match. We can't rely on the overrides
  382. // list here because there isn't necessarily an inheritance
  383. // relationship between the two methods.
  384. if (LT->getMethodQuals() != RT->getMethodQuals())
  385. return false;
  386. return LT->getParamTypes() == RT->getParamTypes();
  387. }
  388. bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
  389. const CXXMethodDecl *RHS) {
  390. assert(LHS->isVirtual() && "LHS must be virtual!");
  391. assert(RHS->isVirtual() && "LHS must be virtual!");
  392. // A destructor can share a vcall offset with another destructor.
  393. if (isa<CXXDestructorDecl>(LHS))
  394. return isa<CXXDestructorDecl>(RHS);
  395. // FIXME: We need to check more things here.
  396. // The methods must have the same name.
  397. DeclarationName LHSName = LHS->getDeclName();
  398. DeclarationName RHSName = RHS->getDeclName();
  399. if (LHSName != RHSName)
  400. return false;
  401. // And the same signatures.
  402. return HasSameVirtualSignature(LHS, RHS);
  403. }
  404. bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD,
  405. CharUnits OffsetOffset) {
  406. // Check if we can reuse an offset.
  407. for (const auto &OffsetPair : Offsets) {
  408. if (MethodsCanShareVCallOffset(OffsetPair.first, MD))
  409. return false;
  410. }
  411. // Add the offset.
  412. Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset));
  413. return true;
  414. }
  415. CharUnits VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) {
  416. // Look for an offset.
  417. for (const auto &OffsetPair : Offsets) {
  418. if (MethodsCanShareVCallOffset(OffsetPair.first, MD))
  419. return OffsetPair.second;
  420. }
  421. llvm_unreachable("Should always find a vcall offset offset!");
  422. }
  423. /// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets.
  424. class VCallAndVBaseOffsetBuilder {
  425. public:
  426. typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
  427. VBaseOffsetOffsetsMapTy;
  428. private:
  429. /// MostDerivedClass - The most derived class for which we're building vcall
  430. /// and vbase offsets.
  431. const CXXRecordDecl *MostDerivedClass;
  432. /// LayoutClass - The class we're using for layout information. Will be
  433. /// different than the most derived class if we're building a construction
  434. /// vtable.
  435. const CXXRecordDecl *LayoutClass;
  436. /// Context - The ASTContext which we will use for layout information.
  437. ASTContext &Context;
  438. /// Components - vcall and vbase offset components
  439. typedef SmallVector<VTableComponent, 64> VTableComponentVectorTy;
  440. VTableComponentVectorTy Components;
  441. /// VisitedVirtualBases - Visited virtual bases.
  442. llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
  443. /// VCallOffsets - Keeps track of vcall offsets.
  444. VCallOffsetMap VCallOffsets;
  445. /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets,
  446. /// relative to the address point.
  447. VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
  448. /// FinalOverriders - The final overriders of the most derived class.
  449. /// (Can be null when we're not building a vtable of the most derived class).
  450. const FinalOverriders *Overriders;
  451. /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the
  452. /// given base subobject.
  453. void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
  454. CharUnits RealBaseOffset);
  455. /// AddVCallOffsets - Add vcall offsets for the given base subobject.
  456. void AddVCallOffsets(BaseSubobject Base, CharUnits VBaseOffset);
  457. /// AddVBaseOffsets - Add vbase offsets for the given class.
  458. void AddVBaseOffsets(const CXXRecordDecl *Base,
  459. CharUnits OffsetInLayoutClass);
  460. /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in
  461. /// chars, relative to the vtable address point.
  462. CharUnits getCurrentOffsetOffset() const;
  463. public:
  464. VCallAndVBaseOffsetBuilder(const CXXRecordDecl *MostDerivedClass,
  465. const CXXRecordDecl *LayoutClass,
  466. const FinalOverriders *Overriders,
  467. BaseSubobject Base, bool BaseIsVirtual,
  468. CharUnits OffsetInLayoutClass)
  469. : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass),
  470. Context(MostDerivedClass->getASTContext()), Overriders(Overriders) {
  471. // Add vcall and vbase offsets.
  472. AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass);
  473. }
  474. /// Methods for iterating over the components.
  475. typedef VTableComponentVectorTy::const_reverse_iterator const_iterator;
  476. const_iterator components_begin() const { return Components.rbegin(); }
  477. const_iterator components_end() const { return Components.rend(); }
  478. const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
  479. const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
  480. return VBaseOffsetOffsets;
  481. }
  482. };
  483. void
  484. VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
  485. bool BaseIsVirtual,
  486. CharUnits RealBaseOffset) {
  487. const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
  488. // Itanium C++ ABI 2.5.2:
  489. // ..in classes sharing a virtual table with a primary base class, the vcall
  490. // and vbase offsets added by the derived class all come before the vcall
  491. // and vbase offsets required by the base class, so that the latter may be
  492. // laid out as required by the base class without regard to additions from
  493. // the derived class(es).
  494. // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
  495. // emit them for the primary base first).
  496. if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
  497. bool PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
  498. CharUnits PrimaryBaseOffset;
  499. // Get the base offset of the primary base.
  500. if (PrimaryBaseIsVirtual) {
  501. assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
  502. "Primary vbase should have a zero offset!");
  503. const ASTRecordLayout &MostDerivedClassLayout =
  504. Context.getASTRecordLayout(MostDerivedClass);
  505. PrimaryBaseOffset =
  506. MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
  507. } else {
  508. assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
  509. "Primary base should have a zero offset!");
  510. PrimaryBaseOffset = Base.getBaseOffset();
  511. }
  512. AddVCallAndVBaseOffsets(
  513. BaseSubobject(PrimaryBase,PrimaryBaseOffset),
  514. PrimaryBaseIsVirtual, RealBaseOffset);
  515. }
  516. AddVBaseOffsets(Base.getBase(), RealBaseOffset);
  517. // We only want to add vcall offsets for virtual bases.
  518. if (BaseIsVirtual)
  519. AddVCallOffsets(Base, RealBaseOffset);
  520. }
  521. CharUnits VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const {
  522. // OffsetIndex is the index of this vcall or vbase offset, relative to the
  523. // vtable address point. (We subtract 3 to account for the information just
  524. // above the address point, the RTTI info, the offset to top, and the
  525. // vcall offset itself).
  526. int64_t OffsetIndex = -(int64_t)(3 + Components.size());
  527. CharUnits PointerWidth =
  528. Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
  529. CharUnits OffsetOffset = PointerWidth * OffsetIndex;
  530. return OffsetOffset;
  531. }
  532. void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base,
  533. CharUnits VBaseOffset) {
  534. const CXXRecordDecl *RD = Base.getBase();
  535. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  536. const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
  537. // Handle the primary base first.
  538. // We only want to add vcall offsets if the base is non-virtual; a virtual
  539. // primary base will have its vcall and vbase offsets emitted already.
  540. if (PrimaryBase && !Layout.isPrimaryBaseVirtual()) {
  541. // Get the base offset of the primary base.
  542. assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
  543. "Primary base should have a zero offset!");
  544. AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()),
  545. VBaseOffset);
  546. }
  547. // Add the vcall offsets.
  548. for (const auto *MD : RD->methods()) {
  549. if (!MD->isVirtual())
  550. continue;
  551. MD = MD->getCanonicalDecl();
  552. CharUnits OffsetOffset = getCurrentOffsetOffset();
  553. // Don't add a vcall offset if we already have one for this member function
  554. // signature.
  555. if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
  556. continue;
  557. CharUnits Offset = CharUnits::Zero();
  558. if (Overriders) {
  559. // Get the final overrider.
  560. FinalOverriders::OverriderInfo Overrider =
  561. Overriders->getOverrider(MD, Base.getBaseOffset());
  562. /// The vcall offset is the offset from the virtual base to the object
  563. /// where the function was overridden.
  564. Offset = Overrider.Offset - VBaseOffset;
  565. }
  566. Components.push_back(
  567. VTableComponent::MakeVCallOffset(Offset));
  568. }
  569. // And iterate over all non-virtual bases (ignoring the primary base).
  570. for (const auto &B : RD->bases()) {
  571. if (B.isVirtual())
  572. continue;
  573. const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
  574. if (BaseDecl == PrimaryBase)
  575. continue;
  576. // Get the base offset of this base.
  577. CharUnits BaseOffset = Base.getBaseOffset() +
  578. Layout.getBaseClassOffset(BaseDecl);
  579. AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset),
  580. VBaseOffset);
  581. }
  582. }
  583. void
  584. VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
  585. CharUnits OffsetInLayoutClass) {
  586. const ASTRecordLayout &LayoutClassLayout =
  587. Context.getASTRecordLayout(LayoutClass);
  588. // Add vbase offsets.
  589. for (const auto &B : RD->bases()) {
  590. const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
  591. // Check if this is a virtual base that we haven't visited before.
  592. if (B.isVirtual() && VisitedVirtualBases.insert(BaseDecl).second) {
  593. CharUnits Offset =
  594. LayoutClassLayout.getVBaseClassOffset(BaseDecl) - OffsetInLayoutClass;
  595. // Add the vbase offset offset.
  596. assert(!VBaseOffsetOffsets.count(BaseDecl) &&
  597. "vbase offset offset already exists!");
  598. CharUnits VBaseOffsetOffset = getCurrentOffsetOffset();
  599. VBaseOffsetOffsets.insert(
  600. std::make_pair(BaseDecl, VBaseOffsetOffset));
  601. Components.push_back(
  602. VTableComponent::MakeVBaseOffset(Offset));
  603. }
  604. // Check the base class looking for more vbase offsets.
  605. AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
  606. }
  607. }
  608. /// ItaniumVTableBuilder - Class for building vtable layout information.
  609. class ItaniumVTableBuilder {
  610. public:
  611. /// PrimaryBasesSetVectorTy - A set vector of direct and indirect
  612. /// primary bases.
  613. typedef llvm::SmallSetVector<const CXXRecordDecl *, 8>
  614. PrimaryBasesSetVectorTy;
  615. typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
  616. VBaseOffsetOffsetsMapTy;
  617. typedef VTableLayout::AddressPointsMapTy AddressPointsMapTy;
  618. typedef llvm::DenseMap<GlobalDecl, int64_t> MethodVTableIndicesTy;
  619. private:
  620. /// VTables - Global vtable information.
  621. ItaniumVTableContext &VTables;
  622. /// MostDerivedClass - The most derived class for which we're building this
  623. /// vtable.
  624. const CXXRecordDecl *MostDerivedClass;
  625. /// MostDerivedClassOffset - If we're building a construction vtable, this
  626. /// holds the offset from the layout class to the most derived class.
  627. const CharUnits MostDerivedClassOffset;
  628. /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual
  629. /// base. (This only makes sense when building a construction vtable).
  630. bool MostDerivedClassIsVirtual;
  631. /// LayoutClass - The class we're using for layout information. Will be
  632. /// different than the most derived class if we're building a construction
  633. /// vtable.
  634. const CXXRecordDecl *LayoutClass;
  635. /// Context - The ASTContext which we will use for layout information.
  636. ASTContext &Context;
  637. /// FinalOverriders - The final overriders of the most derived class.
  638. const FinalOverriders Overriders;
  639. /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
  640. /// bases in this vtable.
  641. llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
  642. /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
  643. /// the most derived class.
  644. VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
  645. /// Components - The components of the vtable being built.
  646. SmallVector<VTableComponent, 64> Components;
  647. /// AddressPoints - Address points for the vtable being built.
  648. AddressPointsMapTy AddressPoints;
  649. /// MethodInfo - Contains information about a method in a vtable.
  650. /// (Used for computing 'this' pointer adjustment thunks.
  651. struct MethodInfo {
  652. /// BaseOffset - The base offset of this method.
  653. const CharUnits BaseOffset;
  654. /// BaseOffsetInLayoutClass - The base offset in the layout class of this
  655. /// method.
  656. const CharUnits BaseOffsetInLayoutClass;
  657. /// VTableIndex - The index in the vtable that this method has.
  658. /// (For destructors, this is the index of the complete destructor).
  659. const uint64_t VTableIndex;
  660. MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass,
  661. uint64_t VTableIndex)
  662. : BaseOffset(BaseOffset),
  663. BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
  664. VTableIndex(VTableIndex) { }
  665. MethodInfo()
  666. : BaseOffset(CharUnits::Zero()),
  667. BaseOffsetInLayoutClass(CharUnits::Zero()),
  668. VTableIndex(0) { }
  669. MethodInfo(MethodInfo const&) = default;
  670. };
  671. typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
  672. /// MethodInfoMap - The information for all methods in the vtable we're
  673. /// currently building.
  674. MethodInfoMapTy MethodInfoMap;
  675. /// MethodVTableIndices - Contains the index (relative to the vtable address
  676. /// point) where the function pointer for a virtual function is stored.
  677. MethodVTableIndicesTy MethodVTableIndices;
  678. typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
  679. /// VTableThunks - The thunks by vtable index in the vtable currently being
  680. /// built.
  681. VTableThunksMapTy VTableThunks;
  682. typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
  683. typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
  684. /// Thunks - A map that contains all the thunks needed for all methods in the
  685. /// most derived class for which the vtable is currently being built.
  686. ThunksMapTy Thunks;
  687. /// AddThunk - Add a thunk for the given method.
  688. void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
  689. /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
  690. /// part of the vtable we're currently building.
  691. void ComputeThisAdjustments();
  692. typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
  693. /// PrimaryVirtualBases - All known virtual bases who are a primary base of
  694. /// some other base.
  695. VisitedVirtualBasesSetTy PrimaryVirtualBases;
  696. /// ComputeReturnAdjustment - Compute the return adjustment given a return
  697. /// adjustment base offset.
  698. ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
  699. /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
  700. /// the 'this' pointer from the base subobject to the derived subobject.
  701. BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
  702. BaseSubobject Derived) const;
  703. /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
  704. /// given virtual member function, its offset in the layout class and its
  705. /// final overrider.
  706. ThisAdjustment
  707. ComputeThisAdjustment(const CXXMethodDecl *MD,
  708. CharUnits BaseOffsetInLayoutClass,
  709. FinalOverriders::OverriderInfo Overrider);
  710. /// AddMethod - Add a single virtual member function to the vtable
  711. /// components vector.
  712. void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
  713. /// IsOverriderUsed - Returns whether the overrider will ever be used in this
  714. /// part of the vtable.
  715. ///
  716. /// Itanium C++ ABI 2.5.2:
  717. ///
  718. /// struct A { virtual void f(); };
  719. /// struct B : virtual public A { int i; };
  720. /// struct C : virtual public A { int j; };
  721. /// struct D : public B, public C {};
  722. ///
  723. /// When B and C are declared, A is a primary base in each case, so although
  724. /// vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
  725. /// adjustment is required and no thunk is generated. However, inside D
  726. /// objects, A is no longer a primary base of C, so if we allowed calls to
  727. /// C::f() to use the copy of A's vtable in the C subobject, we would need
  728. /// to adjust this from C* to B::A*, which would require a third-party
  729. /// thunk. Since we require that a call to C::f() first convert to A*,
  730. /// C-in-D's copy of A's vtable is never referenced, so this is not
  731. /// necessary.
  732. bool IsOverriderUsed(const CXXMethodDecl *Overrider,
  733. CharUnits BaseOffsetInLayoutClass,
  734. const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
  735. CharUnits FirstBaseOffsetInLayoutClass) const;
  736. /// AddMethods - Add the methods of this base subobject and all its
  737. /// primary bases to the vtable components vector.
  738. void AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
  739. const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
  740. CharUnits FirstBaseOffsetInLayoutClass,
  741. PrimaryBasesSetVectorTy &PrimaryBases);
  742. // LayoutVTable - Layout the vtable for the given base class, including its
  743. // secondary vtables and any vtables for virtual bases.
  744. void LayoutVTable();
  745. /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the
  746. /// given base subobject, as well as all its secondary vtables.
  747. ///
  748. /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
  749. /// or a direct or indirect base of a virtual base.
  750. ///
  751. /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual
  752. /// in the layout class.
  753. void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
  754. bool BaseIsMorallyVirtual,
  755. bool BaseIsVirtualInLayoutClass,
  756. CharUnits OffsetInLayoutClass);
  757. /// LayoutSecondaryVTables - Layout the secondary vtables for the given base
  758. /// subobject.
  759. ///
  760. /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
  761. /// or a direct or indirect base of a virtual base.
  762. void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
  763. CharUnits OffsetInLayoutClass);
  764. /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
  765. /// class hierarchy.
  766. void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
  767. CharUnits OffsetInLayoutClass,
  768. VisitedVirtualBasesSetTy &VBases);
  769. /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the
  770. /// given base (excluding any primary bases).
  771. void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
  772. VisitedVirtualBasesSetTy &VBases);
  773. /// isBuildingConstructionVTable - Return whether this vtable builder is
  774. /// building a construction vtable.
  775. bool isBuildingConstructorVTable() const {
  776. return MostDerivedClass != LayoutClass;
  777. }
  778. public:
  779. /// Component indices of the first component of each of the vtables in the
  780. /// vtable group.
  781. SmallVector<size_t, 4> VTableIndices;
  782. ItaniumVTableBuilder(ItaniumVTableContext &VTables,
  783. const CXXRecordDecl *MostDerivedClass,
  784. CharUnits MostDerivedClassOffset,
  785. bool MostDerivedClassIsVirtual,
  786. const CXXRecordDecl *LayoutClass)
  787. : VTables(VTables), MostDerivedClass(MostDerivedClass),
  788. MostDerivedClassOffset(MostDerivedClassOffset),
  789. MostDerivedClassIsVirtual(MostDerivedClassIsVirtual),
  790. LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
  791. Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
  792. assert(!Context.getTargetInfo().getCXXABI().isMicrosoft());
  793. LayoutVTable();
  794. if (Context.getLangOpts().DumpVTableLayouts)
  795. dumpLayout(llvm::outs());
  796. }
  797. uint64_t getNumThunks() const {
  798. return Thunks.size();
  799. }
  800. ThunksMapTy::const_iterator thunks_begin() const {
  801. return Thunks.begin();
  802. }
  803. ThunksMapTy::const_iterator thunks_end() const {
  804. return Thunks.end();
  805. }
  806. const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
  807. return VBaseOffsetOffsets;
  808. }
  809. const AddressPointsMapTy &getAddressPoints() const {
  810. return AddressPoints;
  811. }
  812. MethodVTableIndicesTy::const_iterator vtable_indices_begin() const {
  813. return MethodVTableIndices.begin();
  814. }
  815. MethodVTableIndicesTy::const_iterator vtable_indices_end() const {
  816. return MethodVTableIndices.end();
  817. }
  818. ArrayRef<VTableComponent> vtable_components() const { return Components; }
  819. AddressPointsMapTy::const_iterator address_points_begin() const {
  820. return AddressPoints.begin();
  821. }
  822. AddressPointsMapTy::const_iterator address_points_end() const {
  823. return AddressPoints.end();
  824. }
  825. VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
  826. return VTableThunks.begin();
  827. }
  828. VTableThunksMapTy::const_iterator vtable_thunks_end() const {
  829. return VTableThunks.end();
  830. }
  831. /// dumpLayout - Dump the vtable layout.
  832. void dumpLayout(raw_ostream&);
  833. };
  834. void ItaniumVTableBuilder::AddThunk(const CXXMethodDecl *MD,
  835. const ThunkInfo &Thunk) {
  836. assert(!isBuildingConstructorVTable() &&
  837. "Can't add thunks for construction vtable");
  838. SmallVectorImpl<ThunkInfo> &ThunksVector = Thunks[MD];
  839. // Check if we have this thunk already.
  840. if (llvm::find(ThunksVector, Thunk) != ThunksVector.end())
  841. return;
  842. ThunksVector.push_back(Thunk);
  843. }
  844. typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
  845. /// Visit all the methods overridden by the given method recursively,
  846. /// in a depth-first pre-order. The Visitor's visitor method returns a bool
  847. /// indicating whether to continue the recursion for the given overridden
  848. /// method (i.e. returning false stops the iteration).
  849. template <class VisitorTy>
  850. static void
  851. visitAllOverriddenMethods(const CXXMethodDecl *MD, VisitorTy &Visitor) {
  852. assert(MD->isVirtual() && "Method is not virtual!");
  853. for (const CXXMethodDecl *OverriddenMD : MD->overridden_methods()) {
  854. if (!Visitor(OverriddenMD))
  855. continue;
  856. visitAllOverriddenMethods(OverriddenMD, Visitor);
  857. }
  858. }
  859. /// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
  860. /// the overridden methods that the function decl overrides.
  861. static void
  862. ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
  863. OverriddenMethodsSetTy& OverriddenMethods) {
  864. auto OverriddenMethodsCollector = [&](const CXXMethodDecl *MD) {
  865. // Don't recurse on this method if we've already collected it.
  866. return OverriddenMethods.insert(MD).second;
  867. };
  868. visitAllOverriddenMethods(MD, OverriddenMethodsCollector);
  869. }
  870. void ItaniumVTableBuilder::ComputeThisAdjustments() {
  871. // Now go through the method info map and see if any of the methods need
  872. // 'this' pointer adjustments.
  873. for (const auto &MI : MethodInfoMap) {
  874. const CXXMethodDecl *MD = MI.first;
  875. const MethodInfo &MethodInfo = MI.second;
  876. // Ignore adjustments for unused function pointers.
  877. uint64_t VTableIndex = MethodInfo.VTableIndex;
  878. if (Components[VTableIndex].getKind() ==
  879. VTableComponent::CK_UnusedFunctionPointer)
  880. continue;
  881. // Get the final overrider for this method.
  882. FinalOverriders::OverriderInfo Overrider =
  883. Overriders.getOverrider(MD, MethodInfo.BaseOffset);
  884. // Check if we need an adjustment at all.
  885. if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
  886. // When a return thunk is needed by a derived class that overrides a
  887. // virtual base, gcc uses a virtual 'this' adjustment as well.
  888. // While the thunk itself might be needed by vtables in subclasses or
  889. // in construction vtables, there doesn't seem to be a reason for using
  890. // the thunk in this vtable. Still, we do so to match gcc.
  891. if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
  892. continue;
  893. }
  894. ThisAdjustment ThisAdjustment =
  895. ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
  896. if (ThisAdjustment.isEmpty())
  897. continue;
  898. // Add it.
  899. VTableThunks[VTableIndex].This = ThisAdjustment;
  900. if (isa<CXXDestructorDecl>(MD)) {
  901. // Add an adjustment for the deleting destructor as well.
  902. VTableThunks[VTableIndex + 1].This = ThisAdjustment;
  903. }
  904. }
  905. /// Clear the method info map.
  906. MethodInfoMap.clear();
  907. if (isBuildingConstructorVTable()) {
  908. // We don't need to store thunk information for construction vtables.
  909. return;
  910. }
  911. for (const auto &TI : VTableThunks) {
  912. const VTableComponent &Component = Components[TI.first];
  913. const ThunkInfo &Thunk = TI.second;
  914. const CXXMethodDecl *MD;
  915. switch (Component.getKind()) {
  916. default:
  917. llvm_unreachable("Unexpected vtable component kind!");
  918. case VTableComponent::CK_FunctionPointer:
  919. MD = Component.getFunctionDecl();
  920. break;
  921. case VTableComponent::CK_CompleteDtorPointer:
  922. MD = Component.getDestructorDecl();
  923. break;
  924. case VTableComponent::CK_DeletingDtorPointer:
  925. // We've already added the thunk when we saw the complete dtor pointer.
  926. continue;
  927. }
  928. if (MD->getParent() == MostDerivedClass)
  929. AddThunk(MD, Thunk);
  930. }
  931. }
  932. ReturnAdjustment
  933. ItaniumVTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
  934. ReturnAdjustment Adjustment;
  935. if (!Offset.isEmpty()) {
  936. if (Offset.VirtualBase) {
  937. // Get the virtual base offset offset.
  938. if (Offset.DerivedClass == MostDerivedClass) {
  939. // We can get the offset offset directly from our map.
  940. Adjustment.Virtual.Itanium.VBaseOffsetOffset =
  941. VBaseOffsetOffsets.lookup(Offset.VirtualBase).getQuantity();
  942. } else {
  943. Adjustment.Virtual.Itanium.VBaseOffsetOffset =
  944. VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
  945. Offset.VirtualBase).getQuantity();
  946. }
  947. }
  948. Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
  949. }
  950. return Adjustment;
  951. }
  952. BaseOffset ItaniumVTableBuilder::ComputeThisAdjustmentBaseOffset(
  953. BaseSubobject Base, BaseSubobject Derived) const {
  954. const CXXRecordDecl *BaseRD = Base.getBase();
  955. const CXXRecordDecl *DerivedRD = Derived.getBase();
  956. CXXBasePaths Paths(/*FindAmbiguities=*/true,
  957. /*RecordPaths=*/true, /*DetectVirtual=*/true);
  958. if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
  959. llvm_unreachable("Class must be derived from the passed in base class!");
  960. // We have to go through all the paths, and see which one leads us to the
  961. // right base subobject.
  962. for (const CXXBasePath &Path : Paths) {
  963. BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, Path);
  964. CharUnits OffsetToBaseSubobject = Offset.NonVirtualOffset;
  965. if (Offset.VirtualBase) {
  966. // If we have a virtual base class, the non-virtual offset is relative
  967. // to the virtual base class offset.
  968. const ASTRecordLayout &LayoutClassLayout =
  969. Context.getASTRecordLayout(LayoutClass);
  970. /// Get the virtual base offset, relative to the most derived class
  971. /// layout.
  972. OffsetToBaseSubobject +=
  973. LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
  974. } else {
  975. // Otherwise, the non-virtual offset is relative to the derived class
  976. // offset.
  977. OffsetToBaseSubobject += Derived.getBaseOffset();
  978. }
  979. // Check if this path gives us the right base subobject.
  980. if (OffsetToBaseSubobject == Base.getBaseOffset()) {
  981. // Since we're going from the base class _to_ the derived class, we'll
  982. // invert the non-virtual offset here.
  983. Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
  984. return Offset;
  985. }
  986. }
  987. return BaseOffset();
  988. }
  989. ThisAdjustment ItaniumVTableBuilder::ComputeThisAdjustment(
  990. const CXXMethodDecl *MD, CharUnits BaseOffsetInLayoutClass,
  991. FinalOverriders::OverriderInfo Overrider) {
  992. // Ignore adjustments for pure virtual member functions.
  993. if (Overrider.Method->isPure())
  994. return ThisAdjustment();
  995. BaseSubobject OverriddenBaseSubobject(MD->getParent(),
  996. BaseOffsetInLayoutClass);
  997. BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
  998. Overrider.Offset);
  999. // Compute the adjustment offset.
  1000. BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
  1001. OverriderBaseSubobject);
  1002. if (Offset.isEmpty())
  1003. return ThisAdjustment();
  1004. ThisAdjustment Adjustment;
  1005. if (Offset.VirtualBase) {
  1006. // Get the vcall offset map for this virtual base.
  1007. VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
  1008. if (VCallOffsets.empty()) {
  1009. // We don't have vcall offsets for this virtual base, go ahead and
  1010. // build them.
  1011. VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, MostDerivedClass,
  1012. /*Overriders=*/nullptr,
  1013. BaseSubobject(Offset.VirtualBase,
  1014. CharUnits::Zero()),
  1015. /*BaseIsVirtual=*/true,
  1016. /*OffsetInLayoutClass=*/
  1017. CharUnits::Zero());
  1018. VCallOffsets = Builder.getVCallOffsets();
  1019. }
  1020. Adjustment.Virtual.Itanium.VCallOffsetOffset =
  1021. VCallOffsets.getVCallOffsetOffset(MD).getQuantity();
  1022. }
  1023. // Set the non-virtual part of the adjustment.
  1024. Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
  1025. return Adjustment;
  1026. }
  1027. void ItaniumVTableBuilder::AddMethod(const CXXMethodDecl *MD,
  1028. ReturnAdjustment ReturnAdjustment) {
  1029. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
  1030. assert(ReturnAdjustment.isEmpty() &&
  1031. "Destructor can't have return adjustment!");
  1032. // Add both the complete destructor and the deleting destructor.
  1033. Components.push_back(VTableComponent::MakeCompleteDtor(DD));
  1034. Components.push_back(VTableComponent::MakeDeletingDtor(DD));
  1035. } else {
  1036. // Add the return adjustment if necessary.
  1037. if (!ReturnAdjustment.isEmpty())
  1038. VTableThunks[Components.size()].Return = ReturnAdjustment;
  1039. // Add the function.
  1040. Components.push_back(VTableComponent::MakeFunction(MD));
  1041. }
  1042. }
  1043. /// OverridesIndirectMethodInBase - Return whether the given member function
  1044. /// overrides any methods in the set of given bases.
  1045. /// Unlike OverridesMethodInBase, this checks "overriders of overriders".
  1046. /// For example, if we have:
  1047. ///
  1048. /// struct A { virtual void f(); }
  1049. /// struct B : A { virtual void f(); }
  1050. /// struct C : B { virtual void f(); }
  1051. ///
  1052. /// OverridesIndirectMethodInBase will return true if given C::f as the method
  1053. /// and { A } as the set of bases.
  1054. static bool OverridesIndirectMethodInBases(
  1055. const CXXMethodDecl *MD,
  1056. ItaniumVTableBuilder::PrimaryBasesSetVectorTy &Bases) {
  1057. if (Bases.count(MD->getParent()))
  1058. return true;
  1059. for (const CXXMethodDecl *OverriddenMD : MD->overridden_methods()) {
  1060. // Check "indirect overriders".
  1061. if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
  1062. return true;
  1063. }
  1064. return false;
  1065. }
  1066. bool ItaniumVTableBuilder::IsOverriderUsed(
  1067. const CXXMethodDecl *Overrider, CharUnits BaseOffsetInLayoutClass,
  1068. const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
  1069. CharUnits FirstBaseOffsetInLayoutClass) const {
  1070. // If the base and the first base in the primary base chain have the same
  1071. // offsets, then this overrider will be used.
  1072. if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
  1073. return true;
  1074. // We know now that Base (or a direct or indirect base of it) is a primary
  1075. // base in part of the class hierarchy, but not a primary base in the most
  1076. // derived class.
  1077. // If the overrider is the first base in the primary base chain, we know
  1078. // that the overrider will be used.
  1079. if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
  1080. return true;
  1081. ItaniumVTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
  1082. const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
  1083. PrimaryBases.insert(RD);
  1084. // Now traverse the base chain, starting with the first base, until we find
  1085. // the base that is no longer a primary base.
  1086. while (true) {
  1087. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  1088. const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
  1089. if (!PrimaryBase)
  1090. break;
  1091. if (Layout.isPrimaryBaseVirtual()) {
  1092. assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
  1093. "Primary base should always be at offset 0!");
  1094. const ASTRecordLayout &LayoutClassLayout =
  1095. Context.getASTRecordLayout(LayoutClass);
  1096. // Now check if this is the primary base that is not a primary base in the
  1097. // most derived class.
  1098. if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
  1099. FirstBaseOffsetInLayoutClass) {
  1100. // We found it, stop walking the chain.
  1101. break;
  1102. }
  1103. } else {
  1104. assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
  1105. "Primary base should always be at offset 0!");
  1106. }
  1107. if (!PrimaryBases.insert(PrimaryBase))
  1108. llvm_unreachable("Found a duplicate primary base!");
  1109. RD = PrimaryBase;
  1110. }
  1111. // If the final overrider is an override of one of the primary bases,
  1112. // then we know that it will be used.
  1113. return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
  1114. }
  1115. typedef llvm::SmallSetVector<const CXXRecordDecl *, 8> BasesSetVectorTy;
  1116. /// FindNearestOverriddenMethod - Given a method, returns the overridden method
  1117. /// from the nearest base. Returns null if no method was found.
  1118. /// The Bases are expected to be sorted in a base-to-derived order.
  1119. static const CXXMethodDecl *
  1120. FindNearestOverriddenMethod(const CXXMethodDecl *MD,
  1121. BasesSetVectorTy &Bases) {
  1122. OverriddenMethodsSetTy OverriddenMethods;
  1123. ComputeAllOverriddenMethods(MD, OverriddenMethods);
  1124. for (const CXXRecordDecl *PrimaryBase :
  1125. llvm::make_range(Bases.rbegin(), Bases.rend())) {
  1126. // Now check the overridden methods.
  1127. for (const CXXMethodDecl *OverriddenMD : OverriddenMethods) {
  1128. // We found our overridden method.
  1129. if (OverriddenMD->getParent() == PrimaryBase)
  1130. return OverriddenMD;
  1131. }
  1132. }
  1133. return nullptr;
  1134. }
  1135. void ItaniumVTableBuilder::AddMethods(
  1136. BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
  1137. const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
  1138. CharUnits FirstBaseOffsetInLayoutClass,
  1139. PrimaryBasesSetVectorTy &PrimaryBases) {
  1140. // Itanium C++ ABI 2.5.2:
  1141. // The order of the virtual function pointers in a virtual table is the
  1142. // order of declaration of the corresponding member functions in the class.
  1143. //
  1144. // There is an entry for any virtual function declared in a class,
  1145. // whether it is a new function or overrides a base class function,
  1146. // unless it overrides a function from the primary base, and conversion
  1147. // between their return types does not require an adjustment.
  1148. const CXXRecordDecl *RD = Base.getBase();
  1149. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  1150. if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
  1151. CharUnits PrimaryBaseOffset;
  1152. CharUnits PrimaryBaseOffsetInLayoutClass;
  1153. if (Layout.isPrimaryBaseVirtual()) {
  1154. assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
  1155. "Primary vbase should have a zero offset!");
  1156. const ASTRecordLayout &MostDerivedClassLayout =
  1157. Context.getASTRecordLayout(MostDerivedClass);
  1158. PrimaryBaseOffset =
  1159. MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
  1160. const ASTRecordLayout &LayoutClassLayout =
  1161. Context.getASTRecordLayout(LayoutClass);
  1162. PrimaryBaseOffsetInLayoutClass =
  1163. LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
  1164. } else {
  1165. assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
  1166. "Primary base should have a zero offset!");
  1167. PrimaryBaseOffset = Base.getBaseOffset();
  1168. PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
  1169. }
  1170. AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
  1171. PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
  1172. FirstBaseOffsetInLayoutClass, PrimaryBases);
  1173. if (!PrimaryBases.insert(PrimaryBase))
  1174. llvm_unreachable("Found a duplicate primary base!");
  1175. }
  1176. const CXXDestructorDecl *ImplicitVirtualDtor = nullptr;
  1177. typedef llvm::SmallVector<const CXXMethodDecl *, 8> NewVirtualFunctionsTy;
  1178. NewVirtualFunctionsTy NewVirtualFunctions;
  1179. // Now go through all virtual member functions and add them.
  1180. for (const auto *MD : RD->methods()) {
  1181. if (!MD->isVirtual())
  1182. continue;
  1183. MD = MD->getCanonicalDecl();
  1184. // Get the final overrider.
  1185. FinalOverriders::OverriderInfo Overrider =
  1186. Overriders.getOverrider(MD, Base.getBaseOffset());
  1187. // Check if this virtual member function overrides a method in a primary
  1188. // base. If this is the case, and the return type doesn't require adjustment
  1189. // then we can just use the member function from the primary base.
  1190. if (const CXXMethodDecl *OverriddenMD =
  1191. FindNearestOverriddenMethod(MD, PrimaryBases)) {
  1192. if (ComputeReturnAdjustmentBaseOffset(Context, MD,
  1193. OverriddenMD).isEmpty()) {
  1194. // Replace the method info of the overridden method with our own
  1195. // method.
  1196. assert(MethodInfoMap.count(OverriddenMD) &&
  1197. "Did not find the overridden method!");
  1198. MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
  1199. MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
  1200. OverriddenMethodInfo.VTableIndex);
  1201. assert(!MethodInfoMap.count(MD) &&
  1202. "Should not have method info for this method yet!");
  1203. MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
  1204. MethodInfoMap.erase(OverriddenMD);
  1205. // If the overridden method exists in a virtual base class or a direct
  1206. // or indirect base class of a virtual base class, we need to emit a
  1207. // thunk if we ever have a class hierarchy where the base class is not
  1208. // a primary base in the complete object.
  1209. if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
  1210. // Compute the this adjustment.
  1211. ThisAdjustment ThisAdjustment =
  1212. ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
  1213. Overrider);
  1214. if (ThisAdjustment.Virtual.Itanium.VCallOffsetOffset &&
  1215. Overrider.Method->getParent() == MostDerivedClass) {
  1216. // There's no return adjustment from OverriddenMD and MD,
  1217. // but that doesn't mean there isn't one between MD and
  1218. // the final overrider.
  1219. BaseOffset ReturnAdjustmentOffset =
  1220. ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
  1221. ReturnAdjustment ReturnAdjustment =
  1222. ComputeReturnAdjustment(ReturnAdjustmentOffset);
  1223. // This is a virtual thunk for the most derived class, add it.
  1224. AddThunk(Overrider.Method,
  1225. ThunkInfo(ThisAdjustment, ReturnAdjustment));
  1226. }
  1227. }
  1228. continue;
  1229. }
  1230. }
  1231. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
  1232. if (MD->isImplicit()) {
  1233. // Itanium C++ ABI 2.5.2:
  1234. // If a class has an implicitly-defined virtual destructor,
  1235. // its entries come after the declared virtual function pointers.
  1236. assert(!ImplicitVirtualDtor &&
  1237. "Did already see an implicit virtual dtor!");
  1238. ImplicitVirtualDtor = DD;
  1239. continue;
  1240. }
  1241. }
  1242. NewVirtualFunctions.push_back(MD);
  1243. }
  1244. if (ImplicitVirtualDtor)
  1245. NewVirtualFunctions.push_back(ImplicitVirtualDtor);
  1246. for (const CXXMethodDecl *MD : NewVirtualFunctions) {
  1247. // Get the final overrider.
  1248. FinalOverriders::OverriderInfo Overrider =
  1249. Overriders.getOverrider(MD, Base.getBaseOffset());
  1250. // Insert the method info for this method.
  1251. MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
  1252. Components.size());
  1253. assert(!MethodInfoMap.count(MD) &&
  1254. "Should not have method info for this method yet!");
  1255. MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
  1256. // Check if this overrider is going to be used.
  1257. const CXXMethodDecl *OverriderMD = Overrider.Method;
  1258. if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
  1259. FirstBaseInPrimaryBaseChain,
  1260. FirstBaseOffsetInLayoutClass)) {
  1261. Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
  1262. continue;
  1263. }
  1264. // Check if this overrider needs a return adjustment.
  1265. // We don't want to do this for pure virtual member functions.
  1266. BaseOffset ReturnAdjustmentOffset;
  1267. if (!OverriderMD->isPure()) {
  1268. ReturnAdjustmentOffset =
  1269. ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
  1270. }
  1271. ReturnAdjustment ReturnAdjustment =
  1272. ComputeReturnAdjustment(ReturnAdjustmentOffset);
  1273. AddMethod(Overrider.Method, ReturnAdjustment);
  1274. }
  1275. }
  1276. void ItaniumVTableBuilder::LayoutVTable() {
  1277. LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
  1278. CharUnits::Zero()),
  1279. /*BaseIsMorallyVirtual=*/false,
  1280. MostDerivedClassIsVirtual,
  1281. MostDerivedClassOffset);
  1282. VisitedVirtualBasesSetTy VBases;
  1283. // Determine the primary virtual bases.
  1284. DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
  1285. VBases);
  1286. VBases.clear();
  1287. LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
  1288. // -fapple-kext adds an extra entry at end of vtbl.
  1289. bool IsAppleKext = Context.getLangOpts().AppleKext;
  1290. if (IsAppleKext)
  1291. Components.push_back(VTableComponent::MakeVCallOffset(CharUnits::Zero()));
  1292. }
  1293. void ItaniumVTableBuilder::LayoutPrimaryAndSecondaryVTables(
  1294. BaseSubobject Base, bool BaseIsMorallyVirtual,
  1295. bool BaseIsVirtualInLayoutClass, CharUnits OffsetInLayoutClass) {
  1296. assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
  1297. unsigned VTableIndex = Components.size();
  1298. VTableIndices.push_back(VTableIndex);
  1299. // Add vcall and vbase offsets for this vtable.
  1300. VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
  1301. Base, BaseIsVirtualInLayoutClass,
  1302. OffsetInLayoutClass);
  1303. Components.append(Builder.components_begin(), Builder.components_end());
  1304. // Check if we need to add these vcall offsets.
  1305. if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
  1306. VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
  1307. if (VCallOffsets.empty())
  1308. VCallOffsets = Builder.getVCallOffsets();
  1309. }
  1310. // If we're laying out the most derived class we want to keep track of the
  1311. // virtual base class offset offsets.
  1312. if (Base.getBase() == MostDerivedClass)
  1313. VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
  1314. // Add the offset to top.
  1315. CharUnits OffsetToTop = MostDerivedClassOffset - OffsetInLayoutClass;
  1316. Components.push_back(VTableComponent::MakeOffsetToTop(OffsetToTop));
  1317. // Next, add the RTTI.
  1318. Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
  1319. uint64_t AddressPoint = Components.size();
  1320. // Now go through all virtual member functions and add them.
  1321. PrimaryBasesSetVectorTy PrimaryBases;
  1322. AddMethods(Base, OffsetInLayoutClass,
  1323. Base.getBase(), OffsetInLayoutClass,
  1324. PrimaryBases);
  1325. const CXXRecordDecl *RD = Base.getBase();
  1326. if (RD == MostDerivedClass) {
  1327. assert(MethodVTableIndices.empty());
  1328. for (const auto &I : MethodInfoMap) {
  1329. const CXXMethodDecl *MD = I.first;
  1330. const MethodInfo &MI = I.second;
  1331. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
  1332. MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)]
  1333. = MI.VTableIndex - AddressPoint;
  1334. MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)]
  1335. = MI.VTableIndex + 1 - AddressPoint;
  1336. } else {
  1337. MethodVTableIndices[MD] = MI.VTableIndex - AddressPoint;
  1338. }
  1339. }
  1340. }
  1341. // Compute 'this' pointer adjustments.
  1342. ComputeThisAdjustments();
  1343. // Add all address points.
  1344. while (true) {
  1345. AddressPoints.insert(
  1346. std::make_pair(BaseSubobject(RD, OffsetInLayoutClass),
  1347. VTableLayout::AddressPointLocation{
  1348. unsigned(VTableIndices.size() - 1),
  1349. unsigned(AddressPoint - VTableIndex)}));
  1350. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  1351. const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
  1352. if (!PrimaryBase)
  1353. break;
  1354. if (Layout.isPrimaryBaseVirtual()) {
  1355. // Check if this virtual primary base is a primary base in the layout
  1356. // class. If it's not, we don't want to add it.
  1357. const ASTRecordLayout &LayoutClassLayout =
  1358. Context.getASTRecordLayout(LayoutClass);
  1359. if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
  1360. OffsetInLayoutClass) {
  1361. // We don't want to add this class (or any of its primary bases).
  1362. break;
  1363. }
  1364. }
  1365. RD = PrimaryBase;
  1366. }
  1367. // Layout secondary vtables.
  1368. LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
  1369. }
  1370. void
  1371. ItaniumVTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
  1372. bool BaseIsMorallyVirtual,
  1373. CharUnits OffsetInLayoutClass) {
  1374. // Itanium C++ ABI 2.5.2:
  1375. // Following the primary virtual table of a derived class are secondary
  1376. // virtual tables for each of its proper base classes, except any primary
  1377. // base(s) with which it shares its primary virtual table.
  1378. const CXXRecordDecl *RD = Base.getBase();
  1379. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  1380. const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
  1381. for (const auto &B : RD->bases()) {
  1382. // Ignore virtual bases, we'll emit them later.
  1383. if (B.isVirtual())
  1384. continue;
  1385. const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
  1386. // Ignore bases that don't have a vtable.
  1387. if (!BaseDecl->isDynamicClass())
  1388. continue;
  1389. if (isBuildingConstructorVTable()) {
  1390. // Itanium C++ ABI 2.6.4:
  1391. // Some of the base class subobjects may not need construction virtual
  1392. // tables, which will therefore not be present in the construction
  1393. // virtual table group, even though the subobject virtual tables are
  1394. // present in the main virtual table group for the complete object.
  1395. if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
  1396. continue;
  1397. }
  1398. // Get the base offset of this base.
  1399. CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
  1400. CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
  1401. CharUnits BaseOffsetInLayoutClass =
  1402. OffsetInLayoutClass + RelativeBaseOffset;
  1403. // Don't emit a secondary vtable for a primary base. We might however want
  1404. // to emit secondary vtables for other bases of this base.
  1405. if (BaseDecl == PrimaryBase) {
  1406. LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
  1407. BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
  1408. continue;
  1409. }
  1410. // Layout the primary vtable (and any secondary vtables) for this base.
  1411. LayoutPrimaryAndSecondaryVTables(
  1412. BaseSubobject(BaseDecl, BaseOffset),
  1413. BaseIsMorallyVirtual,
  1414. /*BaseIsVirtualInLayoutClass=*/false,
  1415. BaseOffsetInLayoutClass);
  1416. }
  1417. }
  1418. void ItaniumVTableBuilder::DeterminePrimaryVirtualBases(
  1419. const CXXRecordDecl *RD, CharUnits OffsetInLayoutClass,
  1420. VisitedVirtualBasesSetTy &VBases) {
  1421. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  1422. // Check if this base has a primary base.
  1423. if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
  1424. // Check if it's virtual.
  1425. if (Layout.isPrimaryBaseVirtual()) {
  1426. bool IsPrimaryVirtualBase = true;
  1427. if (isBuildingConstructorVTable()) {
  1428. // Check if the base is actually a primary base in the class we use for
  1429. // layout.
  1430. const ASTRecordLayout &LayoutClassLayout =
  1431. Context.getASTRecordLayout(LayoutClass);
  1432. CharUnits PrimaryBaseOffsetInLayoutClass =
  1433. LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
  1434. // We know that the base is not a primary base in the layout class if
  1435. // the base offsets are different.
  1436. if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
  1437. IsPrimaryVirtualBase = false;
  1438. }
  1439. if (IsPrimaryVirtualBase)
  1440. PrimaryVirtualBases.insert(PrimaryBase);
  1441. }
  1442. }
  1443. // Traverse bases, looking for more primary virtual bases.
  1444. for (const auto &B : RD->bases()) {
  1445. const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
  1446. CharUnits BaseOffsetInLayoutClass;
  1447. if (B.isVirtual()) {
  1448. if (!VBases.insert(BaseDecl).second)
  1449. continue;
  1450. const ASTRecordLayout &LayoutClassLayout =
  1451. Context.getASTRecordLayout(LayoutClass);
  1452. BaseOffsetInLayoutClass =
  1453. LayoutClassLayout.getVBaseClassOffset(BaseDecl);
  1454. } else {
  1455. BaseOffsetInLayoutClass =
  1456. OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
  1457. }
  1458. DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
  1459. }
  1460. }
  1461. void ItaniumVTableBuilder::LayoutVTablesForVirtualBases(
  1462. const CXXRecordDecl *RD, VisitedVirtualBasesSetTy &VBases) {
  1463. // Itanium C++ ABI 2.5.2:
  1464. // Then come the virtual base virtual tables, also in inheritance graph
  1465. // order, and again excluding primary bases (which share virtual tables with
  1466. // the classes for which they are primary).
  1467. for (const auto &B : RD->bases()) {
  1468. const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
  1469. // Check if this base needs a vtable. (If it's virtual, not a primary base
  1470. // of some other class, and we haven't visited it before).
  1471. if (B.isVirtual() && BaseDecl->isDynamicClass() &&
  1472. !PrimaryVirtualBases.count(BaseDecl) &&
  1473. VBases.insert(BaseDecl).second) {
  1474. const ASTRecordLayout &MostDerivedClassLayout =
  1475. Context.getASTRecordLayout(MostDerivedClass);
  1476. CharUnits BaseOffset =
  1477. MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
  1478. const ASTRecordLayout &LayoutClassLayout =
  1479. Context.getASTRecordLayout(LayoutClass);
  1480. CharUnits BaseOffsetInLayoutClass =
  1481. LayoutClassLayout.getVBaseClassOffset(BaseDecl);
  1482. LayoutPrimaryAndSecondaryVTables(
  1483. BaseSubobject(BaseDecl, BaseOffset),
  1484. /*BaseIsMorallyVirtual=*/true,
  1485. /*BaseIsVirtualInLayoutClass=*/true,
  1486. BaseOffsetInLayoutClass);
  1487. }
  1488. // We only need to check the base for virtual base vtables if it actually
  1489. // has virtual bases.
  1490. if (BaseDecl->getNumVBases())
  1491. LayoutVTablesForVirtualBases(BaseDecl, VBases);
  1492. }
  1493. }
  1494. /// dumpLayout - Dump the vtable layout.
  1495. void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) {
  1496. // FIXME: write more tests that actually use the dumpLayout output to prevent
  1497. // ItaniumVTableBuilder regressions.
  1498. if (isBuildingConstructorVTable()) {
  1499. Out << "Construction vtable for ('";
  1500. MostDerivedClass->printQualifiedName(Out);
  1501. Out << "', ";
  1502. Out << MostDerivedClassOffset.getQuantity() << ") in '";
  1503. LayoutClass->printQualifiedName(Out);
  1504. } else {
  1505. Out << "Vtable for '";
  1506. MostDerivedClass->printQualifiedName(Out);
  1507. }
  1508. Out << "' (" << Components.size() << " entries).\n";
  1509. // Iterate through the address points and insert them into a new map where
  1510. // they are keyed by the index and not the base object.
  1511. // Since an address point can be shared by multiple subobjects, we use an
  1512. // STL multimap.
  1513. std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
  1514. for (const auto &AP : AddressPoints) {
  1515. const BaseSubobject &Base = AP.first;
  1516. uint64_t Index =
  1517. VTableIndices[AP.second.VTableIndex] + AP.second.AddressPointIndex;
  1518. AddressPointsByIndex.insert(std::make_pair(Index, Base));
  1519. }
  1520. for (unsigned I = 0, E = Components.size(); I != E; ++I) {
  1521. uint64_t Index = I;
  1522. Out << llvm::format("%4d | ", I);
  1523. const VTableComponent &Component = Components[I];
  1524. // Dump the component.
  1525. switch (Component.getKind()) {
  1526. case VTableComponent::CK_VCallOffset:
  1527. Out << "vcall_offset ("
  1528. << Component.getVCallOffset().getQuantity()
  1529. << ")";
  1530. break;
  1531. case VTableComponent::CK_VBaseOffset:
  1532. Out << "vbase_offset ("
  1533. << Component.getVBaseOffset().getQuantity()
  1534. << ")";
  1535. break;
  1536. case VTableComponent::CK_OffsetToTop:
  1537. Out << "offset_to_top ("
  1538. << Component.getOffsetToTop().getQuantity()
  1539. << ")";
  1540. break;
  1541. case VTableComponent::CK_RTTI:
  1542. Component.getRTTIDecl()->printQualifiedName(Out);
  1543. Out << " RTTI";
  1544. break;
  1545. case VTableComponent::CK_FunctionPointer: {
  1546. const CXXMethodDecl *MD = Component.getFunctionDecl();
  1547. std::string Str =
  1548. PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
  1549. MD);
  1550. Out << Str;
  1551. if (MD->isPure())
  1552. Out << " [pure]";
  1553. if (MD->isDeleted())
  1554. Out << " [deleted]";
  1555. ThunkInfo Thunk = VTableThunks.lookup(I);
  1556. if (!Thunk.isEmpty()) {
  1557. // If this function pointer has a return adjustment, dump it.
  1558. if (!Thunk.Return.isEmpty()) {
  1559. Out << "\n [return adjustment: ";
  1560. Out << Thunk.Return.NonVirtual << " non-virtual";
  1561. if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) {
  1562. Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
  1563. Out << " vbase offset offset";
  1564. }
  1565. Out << ']';
  1566. }
  1567. // If this function pointer has a 'this' pointer adjustment, dump it.
  1568. if (!Thunk.This.isEmpty()) {
  1569. Out << "\n [this adjustment: ";
  1570. Out << Thunk.This.NonVirtual << " non-virtual";
  1571. if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
  1572. Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
  1573. Out << " vcall offset offset";
  1574. }
  1575. Out << ']';
  1576. }
  1577. }
  1578. break;
  1579. }
  1580. case VTableComponent::CK_CompleteDtorPointer:
  1581. case VTableComponent::CK_DeletingDtorPointer: {
  1582. bool IsComplete =
  1583. Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
  1584. const CXXDestructorDecl *DD = Component.getDestructorDecl();
  1585. DD->printQualifiedName(Out);
  1586. if (IsComplete)
  1587. Out << "() [complete]";
  1588. else
  1589. Out << "() [deleting]";
  1590. if (DD->isPure())
  1591. Out << " [pure]";
  1592. ThunkInfo Thunk = VTableThunks.lookup(I);
  1593. if (!Thunk.isEmpty()) {
  1594. // If this destructor has a 'this' pointer adjustment, dump it.
  1595. if (!Thunk.This.isEmpty()) {
  1596. Out << "\n [this adjustment: ";
  1597. Out << Thunk.This.NonVirtual << " non-virtual";
  1598. if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
  1599. Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
  1600. Out << " vcall offset offset";
  1601. }
  1602. Out << ']';
  1603. }
  1604. }
  1605. break;
  1606. }
  1607. case VTableComponent::CK_UnusedFunctionPointer: {
  1608. const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
  1609. std::string Str =
  1610. PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
  1611. MD);
  1612. Out << "[unused] " << Str;
  1613. if (MD->isPure())
  1614. Out << " [pure]";
  1615. }
  1616. }
  1617. Out << '\n';
  1618. // Dump the next address point.
  1619. uint64_t NextIndex = Index + 1;
  1620. if (AddressPointsByIndex.count(NextIndex)) {
  1621. if (AddressPointsByIndex.count(NextIndex) == 1) {
  1622. const BaseSubobject &Base =
  1623. AddressPointsByIndex.find(NextIndex)->second;
  1624. Out << " -- (";
  1625. Base.getBase()->printQualifiedName(Out);
  1626. Out << ", " << Base.getBaseOffset().getQuantity();
  1627. Out << ") vtable address --\n";
  1628. } else {
  1629. CharUnits BaseOffset =
  1630. AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
  1631. // We store the class names in a set to get a stable order.
  1632. std::set<std::string> ClassNames;
  1633. for (const auto &I :
  1634. llvm::make_range(AddressPointsByIndex.equal_range(NextIndex))) {
  1635. assert(I.second.getBaseOffset() == BaseOffset &&
  1636. "Invalid base offset!");
  1637. const CXXRecordDecl *RD = I.second.getBase();
  1638. ClassNames.insert(RD->getQualifiedNameAsString());
  1639. }
  1640. for (const std::string &Name : ClassNames) {
  1641. Out << " -- (" << Name;
  1642. Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
  1643. }
  1644. }
  1645. }
  1646. }
  1647. Out << '\n';
  1648. if (isBuildingConstructorVTable())
  1649. return;
  1650. if (MostDerivedClass->getNumVBases()) {
  1651. // We store the virtual base class names and their offsets in a map to get
  1652. // a stable order.
  1653. std::map<std::string, CharUnits> ClassNamesAndOffsets;
  1654. for (const auto &I : VBaseOffsetOffsets) {
  1655. std::string ClassName = I.first->getQualifiedNameAsString();
  1656. CharUnits OffsetOffset = I.second;
  1657. ClassNamesAndOffsets.insert(std::make_pair(ClassName, OffsetOffset));
  1658. }
  1659. Out << "Virtual base offset offsets for '";
  1660. MostDerivedClass->printQualifiedName(Out);
  1661. Out << "' (";
  1662. Out << ClassNamesAndOffsets.size();
  1663. Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
  1664. for (const auto &I : ClassNamesAndOffsets)
  1665. Out << " " << I.first << " | " << I.second.getQuantity() << '\n';
  1666. Out << "\n";
  1667. }
  1668. if (!Thunks.empty()) {
  1669. // We store the method names in a map to get a stable order.
  1670. std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
  1671. for (const auto &I : Thunks) {
  1672. const CXXMethodDecl *MD = I.first;
  1673. std::string MethodName =
  1674. PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
  1675. MD);
  1676. MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
  1677. }
  1678. for (const auto &I : MethodNamesAndDecls) {
  1679. const std::string &MethodName = I.first;
  1680. const CXXMethodDecl *MD = I.second;
  1681. ThunkInfoVectorTy ThunksVector = Thunks[MD];
  1682. llvm::sort(ThunksVector, [](const ThunkInfo &LHS, const ThunkInfo &RHS) {
  1683. assert(LHS.Method == nullptr && RHS.Method == nullptr);
  1684. return std::tie(LHS.This, LHS.Return) < std::tie(RHS.This, RHS.Return);
  1685. });
  1686. Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
  1687. Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
  1688. for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
  1689. const ThunkInfo &Thunk = ThunksVector[I];
  1690. Out << llvm::format("%4d | ", I);
  1691. // If this function pointer has a return pointer adjustment, dump it.
  1692. if (!Thunk.Return.isEmpty()) {
  1693. Out << "return adjustment: " << Thunk.Return.NonVirtual;
  1694. Out << " non-virtual";
  1695. if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) {
  1696. Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
  1697. Out << " vbase offset offset";
  1698. }
  1699. if (!Thunk.This.isEmpty())
  1700. Out << "\n ";
  1701. }
  1702. // If this function pointer has a 'this' pointer adjustment, dump it.
  1703. if (!Thunk.This.isEmpty()) {
  1704. Out << "this adjustment: ";
  1705. Out << Thunk.This.NonVirtual << " non-virtual";
  1706. if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
  1707. Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
  1708. Out << " vcall offset offset";
  1709. }
  1710. }
  1711. Out << '\n';
  1712. }
  1713. Out << '\n';
  1714. }
  1715. }
  1716. // Compute the vtable indices for all the member functions.
  1717. // Store them in a map keyed by the index so we'll get a sorted table.
  1718. std::map<uint64_t, std::string> IndicesMap;
  1719. for (const auto *MD : MostDerivedClass->methods()) {
  1720. // We only want virtual member functions.
  1721. if (!MD->isVirtual())
  1722. continue;
  1723. MD = MD->getCanonicalDecl();
  1724. std::string MethodName =
  1725. PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
  1726. MD);
  1727. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
  1728. GlobalDecl GD(DD, Dtor_Complete);
  1729. assert(MethodVTableIndices.count(GD));
  1730. uint64_t VTableIndex = MethodVTableIndices[GD];
  1731. IndicesMap[VTableIndex] = MethodName + " [complete]";
  1732. IndicesMap[VTableIndex + 1] = MethodName + " [deleting]";
  1733. } else {
  1734. assert(MethodVTableIndices.count(MD));
  1735. IndicesMap[MethodVTableIndices[MD]] = MethodName;
  1736. }
  1737. }
  1738. // Print the vtable indices for all the member functions.
  1739. if (!IndicesMap.empty()) {
  1740. Out << "VTable indices for '";
  1741. MostDerivedClass->printQualifiedName(Out);
  1742. Out << "' (" << IndicesMap.size() << " entries).\n";
  1743. for (const auto &I : IndicesMap) {
  1744. uint64_t VTableIndex = I.first;
  1745. const std::string &MethodName = I.second;
  1746. Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName
  1747. << '\n';
  1748. }
  1749. }
  1750. Out << '\n';
  1751. }
  1752. }
  1753. VTableLayout::VTableLayout(ArrayRef<size_t> VTableIndices,
  1754. ArrayRef<VTableComponent> VTableComponents,
  1755. ArrayRef<VTableThunkTy> VTableThunks,
  1756. const AddressPointsMapTy &AddressPoints)
  1757. : VTableComponents(VTableComponents), VTableThunks(VTableThunks),
  1758. AddressPoints(AddressPoints) {
  1759. if (VTableIndices.size() <= 1)
  1760. assert(VTableIndices.size() == 1 && VTableIndices[0] == 0);
  1761. else
  1762. this->VTableIndices = OwningArrayRef<size_t>(VTableIndices);
  1763. llvm::sort(this->VTableThunks, [](const VTableLayout::VTableThunkTy &LHS,
  1764. const VTableLayout::VTableThunkTy &RHS) {
  1765. assert((LHS.first != RHS.first || LHS.second == RHS.second) &&
  1766. "Different thunks should have unique indices!");
  1767. return LHS.first < RHS.first;
  1768. });
  1769. }
  1770. VTableLayout::~VTableLayout() { }
  1771. ItaniumVTableContext::ItaniumVTableContext(ASTContext &Context)
  1772. : VTableContextBase(/*MS=*/false) {}
  1773. ItaniumVTableContext::~ItaniumVTableContext() {}
  1774. uint64_t ItaniumVTableContext::getMethodVTableIndex(GlobalDecl GD) {
  1775. GD = GD.getCanonicalDecl();
  1776. MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
  1777. if (I != MethodVTableIndices.end())
  1778. return I->second;
  1779. const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
  1780. computeVTableRelatedInformation(RD);
  1781. I = MethodVTableIndices.find(GD);
  1782. assert(I != MethodVTableIndices.end() && "Did not find index!");
  1783. return I->second;
  1784. }
  1785. CharUnits
  1786. ItaniumVTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
  1787. const CXXRecordDecl *VBase) {
  1788. ClassPairTy ClassPair(RD, VBase);
  1789. VirtualBaseClassOffsetOffsetsMapTy::iterator I =
  1790. VirtualBaseClassOffsetOffsets.find(ClassPair);
  1791. if (I != VirtualBaseClassOffsetOffsets.end())
  1792. return I->second;
  1793. VCallAndVBaseOffsetBuilder Builder(RD, RD, /*Overriders=*/nullptr,
  1794. BaseSubobject(RD, CharUnits::Zero()),
  1795. /*BaseIsVirtual=*/false,
  1796. /*OffsetInLayoutClass=*/CharUnits::Zero());
  1797. for (const auto &I : Builder.getVBaseOffsetOffsets()) {
  1798. // Insert all types.
  1799. ClassPairTy ClassPair(RD, I.first);
  1800. VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I.second));
  1801. }
  1802. I = VirtualBaseClassOffsetOffsets.find(ClassPair);
  1803. assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
  1804. return I->second;
  1805. }
  1806. static std::unique_ptr<VTableLayout>
  1807. CreateVTableLayout(const ItaniumVTableBuilder &Builder) {
  1808. SmallVector<VTableLayout::VTableThunkTy, 1>
  1809. VTableThunks(Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
  1810. return std::make_unique<VTableLayout>(
  1811. Builder.VTableIndices, Builder.vtable_components(), VTableThunks,
  1812. Builder.getAddressPoints());
  1813. }
  1814. void
  1815. ItaniumVTableContext::computeVTableRelatedInformation(const CXXRecordDecl *RD) {
  1816. std::unique_ptr<const VTableLayout> &Entry = VTableLayouts[RD];
  1817. // Check if we've computed this information before.
  1818. if (Entry)
  1819. return;
  1820. ItaniumVTableBuilder Builder(*this, RD, CharUnits::Zero(),
  1821. /*MostDerivedClassIsVirtual=*/0, RD);
  1822. Entry = CreateVTableLayout(Builder);
  1823. MethodVTableIndices.insert(Builder.vtable_indices_begin(),
  1824. Builder.vtable_indices_end());
  1825. // Add the known thunks.
  1826. Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
  1827. // If we don't have the vbase information for this class, insert it.
  1828. // getVirtualBaseOffsetOffset will compute it separately without computing
  1829. // the rest of the vtable related information.
  1830. if (!RD->getNumVBases())
  1831. return;
  1832. const CXXRecordDecl *VBase =
  1833. RD->vbases_begin()->getType()->getAsCXXRecordDecl();
  1834. if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
  1835. return;
  1836. for (const auto &I : Builder.getVBaseOffsetOffsets()) {
  1837. // Insert all types.
  1838. ClassPairTy ClassPair(RD, I.first);
  1839. VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I.second));
  1840. }
  1841. }
  1842. std::unique_ptr<VTableLayout>
  1843. ItaniumVTableContext::createConstructionVTableLayout(
  1844. const CXXRecordDecl *MostDerivedClass, CharUnits MostDerivedClassOffset,
  1845. bool MostDerivedClassIsVirtual, const CXXRecordDecl *LayoutClass) {
  1846. ItaniumVTableBuilder Builder(*this, MostDerivedClass, MostDerivedClassOffset,
  1847. MostDerivedClassIsVirtual, LayoutClass);
  1848. return CreateVTableLayout(Builder);
  1849. }
  1850. namespace {
  1851. // Vtables in the Microsoft ABI are different from the Itanium ABI.
  1852. //
  1853. // The main differences are:
  1854. // 1. Separate vftable and vbtable.
  1855. //
  1856. // 2. Each subobject with a vfptr gets its own vftable rather than an address
  1857. // point in a single vtable shared between all the subobjects.
  1858. // Each vftable is represented by a separate section and virtual calls
  1859. // must be done using the vftable which has a slot for the function to be
  1860. // called.
  1861. //
  1862. // 3. Virtual method definitions expect their 'this' parameter to point to the
  1863. // first vfptr whose table provides a compatible overridden method. In many
  1864. // cases, this permits the original vf-table entry to directly call
  1865. // the method instead of passing through a thunk.
  1866. // See example before VFTableBuilder::ComputeThisOffset below.
  1867. //
  1868. // A compatible overridden method is one which does not have a non-trivial
  1869. // covariant-return adjustment.
  1870. //
  1871. // The first vfptr is the one with the lowest offset in the complete-object
  1872. // layout of the defining class, and the method definition will subtract
  1873. // that constant offset from the parameter value to get the real 'this'
  1874. // value. Therefore, if the offset isn't really constant (e.g. if a virtual
  1875. // function defined in a virtual base is overridden in a more derived
  1876. // virtual base and these bases have a reverse order in the complete
  1877. // object), the vf-table may require a this-adjustment thunk.
  1878. //
  1879. // 4. vftables do not contain new entries for overrides that merely require
  1880. // this-adjustment. Together with #3, this keeps vf-tables smaller and
  1881. // eliminates the need for this-adjustment thunks in many cases, at the cost
  1882. // of often requiring redundant work to adjust the "this" pointer.
  1883. //
  1884. // 5. Instead of VTT and constructor vtables, vbtables and vtordisps are used.
  1885. // Vtordisps are emitted into the class layout if a class has
  1886. // a) a user-defined ctor/dtor
  1887. // and
  1888. // b) a method overriding a method in a virtual base.
  1889. //
  1890. // To get a better understanding of this code,
  1891. // you might want to see examples in test/CodeGenCXX/microsoft-abi-vtables-*.cpp
  1892. class VFTableBuilder {
  1893. public:
  1894. typedef llvm::DenseMap<GlobalDecl, MethodVFTableLocation>
  1895. MethodVFTableLocationsTy;
  1896. typedef llvm::iterator_range<MethodVFTableLocationsTy::const_iterator>
  1897. method_locations_range;
  1898. private:
  1899. /// VTables - Global vtable information.
  1900. MicrosoftVTableContext &VTables;
  1901. /// Context - The ASTContext which we will use for layout information.
  1902. ASTContext &Context;
  1903. /// MostDerivedClass - The most derived class for which we're building this
  1904. /// vtable.
  1905. const CXXRecordDecl *MostDerivedClass;
  1906. const ASTRecordLayout &MostDerivedClassLayout;
  1907. const VPtrInfo &WhichVFPtr;
  1908. /// FinalOverriders - The final overriders of the most derived class.
  1909. const FinalOverriders Overriders;
  1910. /// Components - The components of the vftable being built.
  1911. SmallVector<VTableComponent, 64> Components;
  1912. MethodVFTableLocationsTy MethodVFTableLocations;
  1913. /// Does this class have an RTTI component?
  1914. bool HasRTTIComponent = false;
  1915. /// MethodInfo - Contains information about a method in a vtable.
  1916. /// (Used for computing 'this' pointer adjustment thunks.
  1917. struct MethodInfo {
  1918. /// VBTableIndex - The nonzero index in the vbtable that
  1919. /// this method's base has, or zero.
  1920. const uint64_t VBTableIndex;
  1921. /// VFTableIndex - The index in the vftable that this method has.
  1922. const uint64_t VFTableIndex;
  1923. /// Shadowed - Indicates if this vftable slot is shadowed by
  1924. /// a slot for a covariant-return override. If so, it shouldn't be printed
  1925. /// or used for vcalls in the most derived class.
  1926. bool Shadowed;
  1927. /// UsesExtraSlot - Indicates if this vftable slot was created because
  1928. /// any of the overridden slots required a return adjusting thunk.
  1929. bool UsesExtraSlot;
  1930. MethodInfo(uint64_t VBTableIndex, uint64_t VFTableIndex,
  1931. bool UsesExtraSlot = false)
  1932. : VBTableIndex(VBTableIndex), VFTableIndex(VFTableIndex),
  1933. Shadowed(false), UsesExtraSlot(UsesExtraSlot) {}
  1934. MethodInfo()
  1935. : VBTableIndex(0), VFTableIndex(0), Shadowed(false),
  1936. UsesExtraSlot(false) {}
  1937. };
  1938. typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
  1939. /// MethodInfoMap - The information for all methods in the vftable we're
  1940. /// currently building.
  1941. MethodInfoMapTy MethodInfoMap;
  1942. typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
  1943. /// VTableThunks - The thunks by vftable index in the vftable currently being
  1944. /// built.
  1945. VTableThunksMapTy VTableThunks;
  1946. typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
  1947. typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
  1948. /// Thunks - A map that contains all the thunks needed for all methods in the
  1949. /// most derived class for which the vftable is currently being built.
  1950. ThunksMapTy Thunks;
  1951. /// AddThunk - Add a thunk for the given method.
  1952. void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
  1953. SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
  1954. // Check if we have this thunk already.
  1955. if (llvm::find(ThunksVector, Thunk) != ThunksVector.end())
  1956. return;
  1957. ThunksVector.push_back(Thunk);
  1958. }
  1959. /// ComputeThisOffset - Returns the 'this' argument offset for the given
  1960. /// method, relative to the beginning of the MostDerivedClass.
  1961. CharUnits ComputeThisOffset(FinalOverriders::OverriderInfo Overrider);
  1962. void CalculateVtordispAdjustment(FinalOverriders::OverriderInfo Overrider,
  1963. CharUnits ThisOffset, ThisAdjustment &TA);
  1964. /// AddMethod - Add a single virtual member function to the vftable
  1965. /// components vector.
  1966. void AddMethod(const CXXMethodDecl *MD, ThunkInfo TI) {
  1967. if (!TI.isEmpty()) {
  1968. VTableThunks[Components.size()] = TI;
  1969. AddThunk(MD, TI);
  1970. }
  1971. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
  1972. assert(TI.Return.isEmpty() &&
  1973. "Destructor can't have return adjustment!");
  1974. Components.push_back(VTableComponent::MakeDeletingDtor(DD));
  1975. } else {
  1976. Components.push_back(VTableComponent::MakeFunction(MD));
  1977. }
  1978. }
  1979. /// AddMethods - Add the methods of this base subobject and the relevant
  1980. /// subbases to the vftable we're currently laying out.
  1981. void AddMethods(BaseSubobject Base, unsigned BaseDepth,
  1982. const CXXRecordDecl *LastVBase,
  1983. BasesSetVectorTy &VisitedBases);
  1984. void LayoutVFTable() {
  1985. // RTTI data goes before all other entries.
  1986. if (HasRTTIComponent)
  1987. Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
  1988. BasesSetVectorTy VisitedBases;
  1989. AddMethods(BaseSubobject(MostDerivedClass, CharUnits::Zero()), 0, nullptr,
  1990. VisitedBases);
  1991. assert((HasRTTIComponent ? Components.size() - 1 : Components.size()) &&
  1992. "vftable can't be empty");
  1993. assert(MethodVFTableLocations.empty());
  1994. for (const auto &I : MethodInfoMap) {
  1995. const CXXMethodDecl *MD = I.first;
  1996. const MethodInfo &MI = I.second;
  1997. assert(MD == MD->getCanonicalDecl());
  1998. // Skip the methods that the MostDerivedClass didn't override
  1999. // and the entries shadowed by return adjusting thunks.
  2000. if (MD->getParent() != MostDerivedClass || MI.Shadowed)
  2001. continue;
  2002. MethodVFTableLocation Loc(MI.VBTableIndex, WhichVFPtr.getVBaseWithVPtr(),
  2003. WhichVFPtr.NonVirtualOffset, MI.VFTableIndex);
  2004. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
  2005. MethodVFTableLocations[GlobalDecl(DD, Dtor_Deleting)] = Loc;
  2006. } else {
  2007. MethodVFTableLocations[MD] = Loc;
  2008. }
  2009. }
  2010. }
  2011. public:
  2012. VFTableBuilder(MicrosoftVTableContext &VTables,
  2013. const CXXRecordDecl *MostDerivedClass, const VPtrInfo &Which)
  2014. : VTables(VTables),
  2015. Context(MostDerivedClass->getASTContext()),
  2016. MostDerivedClass(MostDerivedClass),
  2017. MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)),
  2018. WhichVFPtr(Which),
  2019. Overriders(MostDerivedClass, CharUnits(), MostDerivedClass) {
  2020. // Provide the RTTI component if RTTIData is enabled. If the vftable would
  2021. // be available externally, we should not provide the RTTI componenent. It
  2022. // is currently impossible to get available externally vftables with either
  2023. // dllimport or extern template instantiations, but eventually we may add a
  2024. // flag to support additional devirtualization that needs this.
  2025. if (Context.getLangOpts().RTTIData)
  2026. HasRTTIComponent = true;
  2027. LayoutVFTable();
  2028. if (Context.getLangOpts().DumpVTableLayouts)
  2029. dumpLayout(llvm::outs());
  2030. }
  2031. uint64_t getNumThunks() const { return Thunks.size(); }
  2032. ThunksMapTy::const_iterator thunks_begin() const { return Thunks.begin(); }
  2033. ThunksMapTy::const_iterator thunks_end() const { return Thunks.end(); }
  2034. method_locations_range vtable_locations() const {
  2035. return method_locations_range(MethodVFTableLocations.begin(),
  2036. MethodVFTableLocations.end());
  2037. }
  2038. ArrayRef<VTableComponent> vtable_components() const { return Components; }
  2039. VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
  2040. return VTableThunks.begin();
  2041. }
  2042. VTableThunksMapTy::const_iterator vtable_thunks_end() const {
  2043. return VTableThunks.end();
  2044. }
  2045. void dumpLayout(raw_ostream &);
  2046. };
  2047. } // end namespace
  2048. // Let's study one class hierarchy as an example:
  2049. // struct A {
  2050. // virtual void f();
  2051. // int x;
  2052. // };
  2053. //
  2054. // struct B : virtual A {
  2055. // virtual void f();
  2056. // };
  2057. //
  2058. // Record layouts:
  2059. // struct A:
  2060. // 0 | (A vftable pointer)
  2061. // 4 | int x
  2062. //
  2063. // struct B:
  2064. // 0 | (B vbtable pointer)
  2065. // 4 | struct A (virtual base)
  2066. // 4 | (A vftable pointer)
  2067. // 8 | int x
  2068. //
  2069. // Let's assume we have a pointer to the A part of an object of dynamic type B:
  2070. // B b;
  2071. // A *a = (A*)&b;
  2072. // a->f();
  2073. //
  2074. // In this hierarchy, f() belongs to the vftable of A, so B::f() expects
  2075. // "this" parameter to point at the A subobject, which is B+4.
  2076. // In the B::f() prologue, it adjusts "this" back to B by subtracting 4,
  2077. // performed as a *static* adjustment.
  2078. //
  2079. // Interesting thing happens when we alter the relative placement of A and B
  2080. // subobjects in a class:
  2081. // struct C : virtual B { };
  2082. //
  2083. // C c;
  2084. // A *a = (A*)&c;
  2085. // a->f();
  2086. //
  2087. // Respective record layout is:
  2088. // 0 | (C vbtable pointer)
  2089. // 4 | struct A (virtual base)
  2090. // 4 | (A vftable pointer)
  2091. // 8 | int x
  2092. // 12 | struct B (virtual base)
  2093. // 12 | (B vbtable pointer)
  2094. //
  2095. // The final overrider of f() in class C is still B::f(), so B+4 should be
  2096. // passed as "this" to that code. However, "a" points at B-8, so the respective
  2097. // vftable entry should hold a thunk that adds 12 to the "this" argument before
  2098. // performing a tail call to B::f().
  2099. //
  2100. // With this example in mind, we can now calculate the 'this' argument offset
  2101. // for the given method, relative to the beginning of the MostDerivedClass.
  2102. CharUnits
  2103. VFTableBuilder::ComputeThisOffset(FinalOverriders::OverriderInfo Overrider) {
  2104. BasesSetVectorTy Bases;
  2105. {
  2106. // Find the set of least derived bases that define the given method.
  2107. OverriddenMethodsSetTy VisitedOverriddenMethods;
  2108. auto InitialOverriddenDefinitionCollector = [&](
  2109. const CXXMethodDecl *OverriddenMD) {
  2110. if (OverriddenMD->size_overridden_methods() == 0)
  2111. Bases.insert(OverriddenMD->getParent());
  2112. // Don't recurse on this method if we've already collected it.
  2113. return VisitedOverriddenMethods.insert(OverriddenMD).second;
  2114. };
  2115. visitAllOverriddenMethods(Overrider.Method,
  2116. InitialOverriddenDefinitionCollector);
  2117. }
  2118. // If there are no overrides then 'this' is located
  2119. // in the base that defines the method.
  2120. if (Bases.size() == 0)
  2121. return Overrider.Offset;
  2122. CXXBasePaths Paths;
  2123. Overrider.Method->getParent()->lookupInBases(
  2124. [&Bases](const CXXBaseSpecifier *Specifier, CXXBasePath &) {
  2125. return Bases.count(Specifier->getType()->getAsCXXRecordDecl());
  2126. },
  2127. Paths);
  2128. // This will hold the smallest this offset among overridees of MD.
  2129. // This implies that an offset of a non-virtual base will dominate an offset
  2130. // of a virtual base to potentially reduce the number of thunks required
  2131. // in the derived classes that inherit this method.
  2132. CharUnits Ret;
  2133. bool First = true;
  2134. const ASTRecordLayout &OverriderRDLayout =
  2135. Context.getASTRecordLayout(Overrider.Method->getParent());
  2136. for (const CXXBasePath &Path : Paths) {
  2137. CharUnits ThisOffset = Overrider.Offset;
  2138. CharUnits LastVBaseOffset;
  2139. // For each path from the overrider to the parents of the overridden
  2140. // methods, traverse the path, calculating the this offset in the most
  2141. // derived class.
  2142. for (const CXXBasePathElement &Element : Path) {
  2143. QualType CurTy = Element.Base->getType();
  2144. const CXXRecordDecl *PrevRD = Element.Class,
  2145. *CurRD = CurTy->getAsCXXRecordDecl();
  2146. const ASTRecordLayout &Layout = Context.getASTRecordLayout(PrevRD);
  2147. if (Element.Base->isVirtual()) {
  2148. // The interesting things begin when you have virtual inheritance.
  2149. // The final overrider will use a static adjustment equal to the offset
  2150. // of the vbase in the final overrider class.
  2151. // For example, if the final overrider is in a vbase B of the most
  2152. // derived class and it overrides a method of the B's own vbase A,
  2153. // it uses A* as "this". In its prologue, it can cast A* to B* with
  2154. // a static offset. This offset is used regardless of the actual
  2155. // offset of A from B in the most derived class, requiring an
  2156. // this-adjusting thunk in the vftable if A and B are laid out
  2157. // differently in the most derived class.
  2158. LastVBaseOffset = ThisOffset =
  2159. Overrider.Offset + OverriderRDLayout.getVBaseClassOffset(CurRD);
  2160. } else {
  2161. ThisOffset += Layout.getBaseClassOffset(CurRD);
  2162. }
  2163. }
  2164. if (isa<CXXDestructorDecl>(Overrider.Method)) {
  2165. if (LastVBaseOffset.isZero()) {
  2166. // If a "Base" class has at least one non-virtual base with a virtual
  2167. // destructor, the "Base" virtual destructor will take the address
  2168. // of the "Base" subobject as the "this" argument.
  2169. ThisOffset = Overrider.Offset;
  2170. } else {
  2171. // A virtual destructor of a virtual base takes the address of the
  2172. // virtual base subobject as the "this" argument.
  2173. ThisOffset = LastVBaseOffset;
  2174. }
  2175. }
  2176. if (Ret > ThisOffset || First) {
  2177. First = false;
  2178. Ret = ThisOffset;
  2179. }
  2180. }
  2181. assert(!First && "Method not found in the given subobject?");
  2182. return Ret;
  2183. }
  2184. // Things are getting even more complex when the "this" adjustment has to
  2185. // use a dynamic offset instead of a static one, or even two dynamic offsets.
  2186. // This is sometimes required when a virtual call happens in the middle of
  2187. // a non-most-derived class construction or destruction.
  2188. //
  2189. // Let's take a look at the following example:
  2190. // struct A {
  2191. // virtual void f();
  2192. // };
  2193. //
  2194. // void foo(A *a) { a->f(); } // Knows nothing about siblings of A.
  2195. //
  2196. // struct B : virtual A {
  2197. // virtual void f();
  2198. // B() {
  2199. // foo(this);
  2200. // }
  2201. // };
  2202. //
  2203. // struct C : virtual B {
  2204. // virtual void f();
  2205. // };
  2206. //
  2207. // Record layouts for these classes are:
  2208. // struct A
  2209. // 0 | (A vftable pointer)
  2210. //
  2211. // struct B
  2212. // 0 | (B vbtable pointer)
  2213. // 4 | (vtordisp for vbase A)
  2214. // 8 | struct A (virtual base)
  2215. // 8 | (A vftable pointer)
  2216. //
  2217. // struct C
  2218. // 0 | (C vbtable pointer)
  2219. // 4 | (vtordisp for vbase A)
  2220. // 8 | struct A (virtual base) // A precedes B!
  2221. // 8 | (A vftable pointer)
  2222. // 12 | struct B (virtual base)
  2223. // 12 | (B vbtable pointer)
  2224. //
  2225. // When one creates an object of type C, the C constructor:
  2226. // - initializes all the vbptrs, then
  2227. // - calls the A subobject constructor
  2228. // (initializes A's vfptr with an address of A vftable), then
  2229. // - calls the B subobject constructor
  2230. // (initializes A's vfptr with an address of B vftable and vtordisp for A),
  2231. // that in turn calls foo(), then
  2232. // - initializes A's vfptr with an address of C vftable and zeroes out the
  2233. // vtordisp
  2234. // FIXME: if a structor knows it belongs to MDC, why doesn't it use a vftable
  2235. // without vtordisp thunks?
  2236. // FIXME: how are vtordisp handled in the presence of nooverride/final?
  2237. //
  2238. // When foo() is called, an object with a layout of class C has a vftable
  2239. // referencing B::f() that assumes a B layout, so the "this" adjustments are
  2240. // incorrect, unless an extra adjustment is done. This adjustment is called
  2241. // "vtordisp adjustment". Vtordisp basically holds the difference between the
  2242. // actual location of a vbase in the layout class and the location assumed by
  2243. // the vftable of the class being constructed/destructed. Vtordisp is only
  2244. // needed if "this" escapes a
  2245. // structor (or we can't prove otherwise).
  2246. // [i.e. vtordisp is a dynamic adjustment for a static adjustment, which is an
  2247. // estimation of a dynamic adjustment]
  2248. //
  2249. // foo() gets a pointer to the A vbase and doesn't know anything about B or C,
  2250. // so it just passes that pointer as "this" in a virtual call.
  2251. // If there was no vtordisp, that would just dispatch to B::f().
  2252. // However, B::f() assumes B+8 is passed as "this",
  2253. // yet the pointer foo() passes along is B-4 (i.e. C+8).
  2254. // An extra adjustment is needed, so we emit a thunk into the B vftable.
  2255. // This vtordisp thunk subtracts the value of vtordisp
  2256. // from the "this" argument (-12) before making a tailcall to B::f().
  2257. //
  2258. // Let's consider an even more complex example:
  2259. // struct D : virtual B, virtual C {
  2260. // D() {
  2261. // foo(this);
  2262. // }
  2263. // };
  2264. //
  2265. // struct D
  2266. // 0 | (D vbtable pointer)
  2267. // 4 | (vtordisp for vbase A)
  2268. // 8 | struct A (virtual base) // A precedes both B and C!
  2269. // 8 | (A vftable pointer)
  2270. // 12 | struct B (virtual base) // B precedes C!
  2271. // 12 | (B vbtable pointer)
  2272. // 16 | struct C (virtual base)
  2273. // 16 | (C vbtable pointer)
  2274. //
  2275. // When D::D() calls foo(), we find ourselves in a thunk that should tailcall
  2276. // to C::f(), which assumes C+8 as its "this" parameter. This time, foo()
  2277. // passes along A, which is C-8. The A vtordisp holds
  2278. // "D.vbptr[index_of_A] - offset_of_A_in_D"
  2279. // and we statically know offset_of_A_in_D, so can get a pointer to D.
  2280. // When we know it, we can make an extra vbtable lookup to locate the C vbase
  2281. // and one extra static adjustment to calculate the expected value of C+8.
  2282. void VFTableBuilder::CalculateVtordispAdjustment(
  2283. FinalOverriders::OverriderInfo Overrider, CharUnits ThisOffset,
  2284. ThisAdjustment &TA) {
  2285. const ASTRecordLayout::VBaseOffsetsMapTy &VBaseMap =
  2286. MostDerivedClassLayout.getVBaseOffsetsMap();
  2287. const ASTRecordLayout::VBaseOffsetsMapTy::const_iterator &VBaseMapEntry =
  2288. VBaseMap.find(WhichVFPtr.getVBaseWithVPtr());
  2289. assert(VBaseMapEntry != VBaseMap.end());
  2290. // If there's no vtordisp or the final overrider is defined in the same vbase
  2291. // as the initial declaration, we don't need any vtordisp adjustment.
  2292. if (!VBaseMapEntry->second.hasVtorDisp() ||
  2293. Overrider.VirtualBase == WhichVFPtr.getVBaseWithVPtr())
  2294. return;
  2295. // OK, now we know we need to use a vtordisp thunk.
  2296. // The implicit vtordisp field is located right before the vbase.
  2297. CharUnits OffsetOfVBaseWithVFPtr = VBaseMapEntry->second.VBaseOffset;
  2298. TA.Virtual.Microsoft.VtordispOffset =
  2299. (OffsetOfVBaseWithVFPtr - WhichVFPtr.FullOffsetInMDC).getQuantity() - 4;
  2300. // A simple vtordisp thunk will suffice if the final overrider is defined
  2301. // in either the most derived class or its non-virtual base.
  2302. if (Overrider.Method->getParent() == MostDerivedClass ||
  2303. !Overrider.VirtualBase)
  2304. return;
  2305. // Otherwise, we need to do use the dynamic offset of the final overrider
  2306. // in order to get "this" adjustment right.
  2307. TA.Virtual.Microsoft.VBPtrOffset =
  2308. (OffsetOfVBaseWithVFPtr + WhichVFPtr.NonVirtualOffset -
  2309. MostDerivedClassLayout.getVBPtrOffset()).getQuantity();
  2310. TA.Virtual.Microsoft.VBOffsetOffset =
  2311. Context.getTypeSizeInChars(Context.IntTy).getQuantity() *
  2312. VTables.getVBTableIndex(MostDerivedClass, Overrider.VirtualBase);
  2313. TA.NonVirtual = (ThisOffset - Overrider.Offset).getQuantity();
  2314. }
  2315. static void GroupNewVirtualOverloads(
  2316. const CXXRecordDecl *RD,
  2317. SmallVector<const CXXMethodDecl *, 10> &VirtualMethods) {
  2318. // Put the virtual methods into VirtualMethods in the proper order:
  2319. // 1) Group overloads by declaration name. New groups are added to the
  2320. // vftable in the order of their first declarations in this class
  2321. // (including overrides, non-virtual methods and any other named decl that
  2322. // might be nested within the class).
  2323. // 2) In each group, new overloads appear in the reverse order of declaration.
  2324. typedef SmallVector<const CXXMethodDecl *, 1> MethodGroup;
  2325. SmallVector<MethodGroup, 10> Groups;
  2326. typedef llvm::DenseMap<DeclarationName, unsigned> VisitedGroupIndicesTy;
  2327. VisitedGroupIndicesTy VisitedGroupIndices;
  2328. for (const auto *D : RD->decls()) {
  2329. const auto *ND = dyn_cast<NamedDecl>(D);
  2330. if (!ND)
  2331. continue;
  2332. VisitedGroupIndicesTy::iterator J;
  2333. bool Inserted;
  2334. std::tie(J, Inserted) = VisitedGroupIndices.insert(
  2335. std::make_pair(ND->getDeclName(), Groups.size()));
  2336. if (Inserted)
  2337. Groups.push_back(MethodGroup());
  2338. if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
  2339. if (MD->isVirtual())
  2340. Groups[J->second].push_back(MD->getCanonicalDecl());
  2341. }
  2342. for (const MethodGroup &Group : Groups)
  2343. VirtualMethods.append(Group.rbegin(), Group.rend());
  2344. }
  2345. static bool isDirectVBase(const CXXRecordDecl *Base, const CXXRecordDecl *RD) {
  2346. for (const auto &B : RD->bases()) {
  2347. if (B.isVirtual() && B.getType()->getAsCXXRecordDecl() == Base)
  2348. return true;
  2349. }
  2350. return false;
  2351. }
  2352. void VFTableBuilder::AddMethods(BaseSubobject Base, unsigned BaseDepth,
  2353. const CXXRecordDecl *LastVBase,
  2354. BasesSetVectorTy &VisitedBases) {
  2355. const CXXRecordDecl *RD = Base.getBase();
  2356. if (!RD->isPolymorphic())
  2357. return;
  2358. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  2359. // See if this class expands a vftable of the base we look at, which is either
  2360. // the one defined by the vfptr base path or the primary base of the current
  2361. // class.
  2362. const CXXRecordDecl *NextBase = nullptr, *NextLastVBase = LastVBase;
  2363. CharUnits NextBaseOffset;
  2364. if (BaseDepth < WhichVFPtr.PathToIntroducingObject.size()) {
  2365. NextBase = WhichVFPtr.PathToIntroducingObject[BaseDepth];
  2366. if (isDirectVBase(NextBase, RD)) {
  2367. NextLastVBase = NextBase;
  2368. NextBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(NextBase);
  2369. } else {
  2370. NextBaseOffset =
  2371. Base.getBaseOffset() + Layout.getBaseClassOffset(NextBase);
  2372. }
  2373. } else if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
  2374. assert(!Layout.isPrimaryBaseVirtual() &&
  2375. "No primary virtual bases in this ABI");
  2376. NextBase = PrimaryBase;
  2377. NextBaseOffset = Base.getBaseOffset();
  2378. }
  2379. if (NextBase) {
  2380. AddMethods(BaseSubobject(NextBase, NextBaseOffset), BaseDepth + 1,
  2381. NextLastVBase, VisitedBases);
  2382. if (!VisitedBases.insert(NextBase))
  2383. llvm_unreachable("Found a duplicate primary base!");
  2384. }
  2385. SmallVector<const CXXMethodDecl*, 10> VirtualMethods;
  2386. // Put virtual methods in the proper order.
  2387. GroupNewVirtualOverloads(RD, VirtualMethods);
  2388. // Now go through all virtual member functions and add them to the current
  2389. // vftable. This is done by
  2390. // - replacing overridden methods in their existing slots, as long as they
  2391. // don't require return adjustment; calculating This adjustment if needed.
  2392. // - adding new slots for methods of the current base not present in any
  2393. // sub-bases;
  2394. // - adding new slots for methods that require Return adjustment.
  2395. // We keep track of the methods visited in the sub-bases in MethodInfoMap.
  2396. for (const CXXMethodDecl *MD : VirtualMethods) {
  2397. FinalOverriders::OverriderInfo FinalOverrider =
  2398. Overriders.getOverrider(MD, Base.getBaseOffset());
  2399. const CXXMethodDecl *FinalOverriderMD = FinalOverrider.Method;
  2400. const CXXMethodDecl *OverriddenMD =
  2401. FindNearestOverriddenMethod(MD, VisitedBases);
  2402. ThisAdjustment ThisAdjustmentOffset;
  2403. bool ReturnAdjustingThunk = false, ForceReturnAdjustmentMangling = false;
  2404. CharUnits ThisOffset = ComputeThisOffset(FinalOverrider);
  2405. ThisAdjustmentOffset.NonVirtual =
  2406. (ThisOffset - WhichVFPtr.FullOffsetInMDC).getQuantity();
  2407. if ((OverriddenMD || FinalOverriderMD != MD) &&
  2408. WhichVFPtr.getVBaseWithVPtr())
  2409. CalculateVtordispAdjustment(FinalOverrider, ThisOffset,
  2410. ThisAdjustmentOffset);
  2411. unsigned VBIndex =
  2412. LastVBase ? VTables.getVBTableIndex(MostDerivedClass, LastVBase) : 0;
  2413. if (OverriddenMD) {
  2414. // If MD overrides anything in this vftable, we need to update the
  2415. // entries.
  2416. MethodInfoMapTy::iterator OverriddenMDIterator =
  2417. MethodInfoMap.find(OverriddenMD);
  2418. // If the overridden method went to a different vftable, skip it.
  2419. if (OverriddenMDIterator == MethodInfoMap.end())
  2420. continue;
  2421. MethodInfo &OverriddenMethodInfo = OverriddenMDIterator->second;
  2422. VBIndex = OverriddenMethodInfo.VBTableIndex;
  2423. // Let's check if the overrider requires any return adjustments.
  2424. // We must create a new slot if the MD's return type is not trivially
  2425. // convertible to the OverriddenMD's one.
  2426. // Once a chain of method overrides adds a return adjusting vftable slot,
  2427. // all subsequent overrides will also use an extra method slot.
  2428. ReturnAdjustingThunk = !ComputeReturnAdjustmentBaseOffset(
  2429. Context, MD, OverriddenMD).isEmpty() ||
  2430. OverriddenMethodInfo.UsesExtraSlot;
  2431. if (!ReturnAdjustingThunk) {
  2432. // No return adjustment needed - just replace the overridden method info
  2433. // with the current info.
  2434. MethodInfo MI(VBIndex, OverriddenMethodInfo.VFTableIndex);
  2435. MethodInfoMap.erase(OverriddenMDIterator);
  2436. assert(!MethodInfoMap.count(MD) &&
  2437. "Should not have method info for this method yet!");
  2438. MethodInfoMap.insert(std::make_pair(MD, MI));
  2439. continue;
  2440. }
  2441. // In case we need a return adjustment, we'll add a new slot for
  2442. // the overrider. Mark the overridden method as shadowed by the new slot.
  2443. OverriddenMethodInfo.Shadowed = true;
  2444. // Force a special name mangling for a return-adjusting thunk
  2445. // unless the method is the final overrider without this adjustment.
  2446. ForceReturnAdjustmentMangling =
  2447. !(MD == FinalOverriderMD && ThisAdjustmentOffset.isEmpty());
  2448. } else if (Base.getBaseOffset() != WhichVFPtr.FullOffsetInMDC ||
  2449. MD->size_overridden_methods()) {
  2450. // Skip methods that don't belong to the vftable of the current class,
  2451. // e.g. each method that wasn't seen in any of the visited sub-bases
  2452. // but overrides multiple methods of other sub-bases.
  2453. continue;
  2454. }
  2455. // If we got here, MD is a method not seen in any of the sub-bases or
  2456. // it requires return adjustment. Insert the method info for this method.
  2457. MethodInfo MI(VBIndex,
  2458. HasRTTIComponent ? Components.size() - 1 : Components.size(),
  2459. ReturnAdjustingThunk);
  2460. assert(!MethodInfoMap.count(MD) &&
  2461. "Should not have method info for this method yet!");
  2462. MethodInfoMap.insert(std::make_pair(MD, MI));
  2463. // Check if this overrider needs a return adjustment.
  2464. // We don't want to do this for pure virtual member functions.
  2465. BaseOffset ReturnAdjustmentOffset;
  2466. ReturnAdjustment ReturnAdjustment;
  2467. if (!FinalOverriderMD->isPure()) {
  2468. ReturnAdjustmentOffset =
  2469. ComputeReturnAdjustmentBaseOffset(Context, FinalOverriderMD, MD);
  2470. }
  2471. if (!ReturnAdjustmentOffset.isEmpty()) {
  2472. ForceReturnAdjustmentMangling = true;
  2473. ReturnAdjustment.NonVirtual =
  2474. ReturnAdjustmentOffset.NonVirtualOffset.getQuantity();
  2475. if (ReturnAdjustmentOffset.VirtualBase) {
  2476. const ASTRecordLayout &DerivedLayout =
  2477. Context.getASTRecordLayout(ReturnAdjustmentOffset.DerivedClass);
  2478. ReturnAdjustment.Virtual.Microsoft.VBPtrOffset =
  2479. DerivedLayout.getVBPtrOffset().getQuantity();
  2480. ReturnAdjustment.Virtual.Microsoft.VBIndex =
  2481. VTables.getVBTableIndex(ReturnAdjustmentOffset.DerivedClass,
  2482. ReturnAdjustmentOffset.VirtualBase);
  2483. }
  2484. }
  2485. AddMethod(FinalOverriderMD,
  2486. ThunkInfo(ThisAdjustmentOffset, ReturnAdjustment,
  2487. ForceReturnAdjustmentMangling ? MD : nullptr));
  2488. }
  2489. }
  2490. static void PrintBasePath(const VPtrInfo::BasePath &Path, raw_ostream &Out) {
  2491. for (const CXXRecordDecl *Elem :
  2492. llvm::make_range(Path.rbegin(), Path.rend())) {
  2493. Out << "'";
  2494. Elem->printQualifiedName(Out);
  2495. Out << "' in ";
  2496. }
  2497. }
  2498. static void dumpMicrosoftThunkAdjustment(const ThunkInfo &TI, raw_ostream &Out,
  2499. bool ContinueFirstLine) {
  2500. const ReturnAdjustment &R = TI.Return;
  2501. bool Multiline = false;
  2502. const char *LinePrefix = "\n ";
  2503. if (!R.isEmpty() || TI.Method) {
  2504. if (!ContinueFirstLine)
  2505. Out << LinePrefix;
  2506. Out << "[return adjustment (to type '"
  2507. << TI.Method->getReturnType().getCanonicalType().getAsString()
  2508. << "'): ";
  2509. if (R.Virtual.Microsoft.VBPtrOffset)
  2510. Out << "vbptr at offset " << R.Virtual.Microsoft.VBPtrOffset << ", ";
  2511. if (R.Virtual.Microsoft.VBIndex)
  2512. Out << "vbase #" << R.Virtual.Microsoft.VBIndex << ", ";
  2513. Out << R.NonVirtual << " non-virtual]";
  2514. Multiline = true;
  2515. }
  2516. const ThisAdjustment &T = TI.This;
  2517. if (!T.isEmpty()) {
  2518. if (Multiline || !ContinueFirstLine)
  2519. Out << LinePrefix;
  2520. Out << "[this adjustment: ";
  2521. if (!TI.This.Virtual.isEmpty()) {
  2522. assert(T.Virtual.Microsoft.VtordispOffset < 0);
  2523. Out << "vtordisp at " << T.Virtual.Microsoft.VtordispOffset << ", ";
  2524. if (T.Virtual.Microsoft.VBPtrOffset) {
  2525. Out << "vbptr at " << T.Virtual.Microsoft.VBPtrOffset
  2526. << " to the left,";
  2527. assert(T.Virtual.Microsoft.VBOffsetOffset > 0);
  2528. Out << LinePrefix << " vboffset at "
  2529. << T.Virtual.Microsoft.VBOffsetOffset << " in the vbtable, ";
  2530. }
  2531. }
  2532. Out << T.NonVirtual << " non-virtual]";
  2533. }
  2534. }
  2535. void VFTableBuilder::dumpLayout(raw_ostream &Out) {
  2536. Out << "VFTable for ";
  2537. PrintBasePath(WhichVFPtr.PathToIntroducingObject, Out);
  2538. Out << "'";
  2539. MostDerivedClass->printQualifiedName(Out);
  2540. Out << "' (" << Components.size()
  2541. << (Components.size() == 1 ? " entry" : " entries") << ").\n";
  2542. for (unsigned I = 0, E = Components.size(); I != E; ++I) {
  2543. Out << llvm::format("%4d | ", I);
  2544. const VTableComponent &Component = Components[I];
  2545. // Dump the component.
  2546. switch (Component.getKind()) {
  2547. case VTableComponent::CK_RTTI:
  2548. Component.getRTTIDecl()->printQualifiedName(Out);
  2549. Out << " RTTI";
  2550. break;
  2551. case VTableComponent::CK_FunctionPointer: {
  2552. const CXXMethodDecl *MD = Component.getFunctionDecl();
  2553. // FIXME: Figure out how to print the real thunk type, since they can
  2554. // differ in the return type.
  2555. std::string Str = PredefinedExpr::ComputeName(
  2556. PredefinedExpr::PrettyFunctionNoVirtual, MD);
  2557. Out << Str;
  2558. if (MD->isPure())
  2559. Out << " [pure]";
  2560. if (MD->isDeleted())
  2561. Out << " [deleted]";
  2562. ThunkInfo Thunk = VTableThunks.lookup(I);
  2563. if (!Thunk.isEmpty())
  2564. dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/false);
  2565. break;
  2566. }
  2567. case VTableComponent::CK_DeletingDtorPointer: {
  2568. const CXXDestructorDecl *DD = Component.getDestructorDecl();
  2569. DD->printQualifiedName(Out);
  2570. Out << "() [scalar deleting]";
  2571. if (DD->isPure())
  2572. Out << " [pure]";
  2573. ThunkInfo Thunk = VTableThunks.lookup(I);
  2574. if (!Thunk.isEmpty()) {
  2575. assert(Thunk.Return.isEmpty() &&
  2576. "No return adjustment needed for destructors!");
  2577. dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/false);
  2578. }
  2579. break;
  2580. }
  2581. default:
  2582. DiagnosticsEngine &Diags = Context.getDiagnostics();
  2583. unsigned DiagID = Diags.getCustomDiagID(
  2584. DiagnosticsEngine::Error,
  2585. "Unexpected vftable component type %0 for component number %1");
  2586. Diags.Report(MostDerivedClass->getLocation(), DiagID)
  2587. << I << Component.getKind();
  2588. }
  2589. Out << '\n';
  2590. }
  2591. Out << '\n';
  2592. if (!Thunks.empty()) {
  2593. // We store the method names in a map to get a stable order.
  2594. std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
  2595. for (const auto &I : Thunks) {
  2596. const CXXMethodDecl *MD = I.first;
  2597. std::string MethodName = PredefinedExpr::ComputeName(
  2598. PredefinedExpr::PrettyFunctionNoVirtual, MD);
  2599. MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
  2600. }
  2601. for (const auto &MethodNameAndDecl : MethodNamesAndDecls) {
  2602. const std::string &MethodName = MethodNameAndDecl.first;
  2603. const CXXMethodDecl *MD = MethodNameAndDecl.second;
  2604. ThunkInfoVectorTy ThunksVector = Thunks[MD];
  2605. llvm::stable_sort(ThunksVector, [](const ThunkInfo &LHS,
  2606. const ThunkInfo &RHS) {
  2607. // Keep different thunks with the same adjustments in the order they
  2608. // were put into the vector.
  2609. return std::tie(LHS.This, LHS.Return) < std::tie(RHS.This, RHS.Return);
  2610. });
  2611. Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
  2612. Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
  2613. for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
  2614. const ThunkInfo &Thunk = ThunksVector[I];
  2615. Out << llvm::format("%4d | ", I);
  2616. dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/true);
  2617. Out << '\n';
  2618. }
  2619. Out << '\n';
  2620. }
  2621. }
  2622. Out.flush();
  2623. }
  2624. static bool setsIntersect(const llvm::SmallPtrSet<const CXXRecordDecl *, 4> &A,
  2625. ArrayRef<const CXXRecordDecl *> B) {
  2626. for (const CXXRecordDecl *Decl : B) {
  2627. if (A.count(Decl))
  2628. return true;
  2629. }
  2630. return false;
  2631. }
  2632. static bool rebucketPaths(VPtrInfoVector &Paths);
  2633. /// Produces MSVC-compatible vbtable data. The symbols produced by this
  2634. /// algorithm match those produced by MSVC 2012 and newer, which is different
  2635. /// from MSVC 2010.
  2636. ///
  2637. /// MSVC 2012 appears to minimize the vbtable names using the following
  2638. /// algorithm. First, walk the class hierarchy in the usual order, depth first,
  2639. /// left to right, to find all of the subobjects which contain a vbptr field.
  2640. /// Visiting each class node yields a list of inheritance paths to vbptrs. Each
  2641. /// record with a vbptr creates an initially empty path.
  2642. ///
  2643. /// To combine paths from child nodes, the paths are compared to check for
  2644. /// ambiguity. Paths are "ambiguous" if multiple paths have the same set of
  2645. /// components in the same order. Each group of ambiguous paths is extended by
  2646. /// appending the class of the base from which it came. If the current class
  2647. /// node produced an ambiguous path, its path is extended with the current class.
  2648. /// After extending paths, MSVC again checks for ambiguity, and extends any
  2649. /// ambiguous path which wasn't already extended. Because each node yields an
  2650. /// unambiguous set of paths, MSVC doesn't need to extend any path more than once
  2651. /// to produce an unambiguous set of paths.
  2652. ///
  2653. /// TODO: Presumably vftables use the same algorithm.
  2654. void MicrosoftVTableContext::computeVTablePaths(bool ForVBTables,
  2655. const CXXRecordDecl *RD,
  2656. VPtrInfoVector &Paths) {
  2657. assert(Paths.empty());
  2658. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  2659. // Base case: this subobject has its own vptr.
  2660. if (ForVBTables ? Layout.hasOwnVBPtr() : Layout.hasOwnVFPtr())
  2661. Paths.push_back(std::make_unique<VPtrInfo>(RD));
  2662. // Recursive case: get all the vbtables from our bases and remove anything
  2663. // that shares a virtual base.
  2664. llvm::SmallPtrSet<const CXXRecordDecl*, 4> VBasesSeen;
  2665. for (const auto &B : RD->bases()) {
  2666. const CXXRecordDecl *Base = B.getType()->getAsCXXRecordDecl();
  2667. if (B.isVirtual() && VBasesSeen.count(Base))
  2668. continue;
  2669. if (!Base->isDynamicClass())
  2670. continue;
  2671. const VPtrInfoVector &BasePaths =
  2672. ForVBTables ? enumerateVBTables(Base) : getVFPtrOffsets(Base);
  2673. for (const std::unique_ptr<VPtrInfo> &BaseInfo : BasePaths) {
  2674. // Don't include the path if it goes through a virtual base that we've
  2675. // already included.
  2676. if (setsIntersect(VBasesSeen, BaseInfo->ContainingVBases))
  2677. continue;
  2678. // Copy the path and adjust it as necessary.
  2679. auto P = std::make_unique<VPtrInfo>(*BaseInfo);
  2680. // We mangle Base into the path if the path would've been ambiguous and it
  2681. // wasn't already extended with Base.
  2682. if (P->MangledPath.empty() || P->MangledPath.back() != Base)
  2683. P->NextBaseToMangle = Base;
  2684. // Keep track of which vtable the derived class is going to extend with
  2685. // new methods or bases. We append to either the vftable of our primary
  2686. // base, or the first non-virtual base that has a vbtable.
  2687. if (P->ObjectWithVPtr == Base &&
  2688. Base == (ForVBTables ? Layout.getBaseSharingVBPtr()
  2689. : Layout.getPrimaryBase()))
  2690. P->ObjectWithVPtr = RD;
  2691. // Keep track of the full adjustment from the MDC to this vtable. The
  2692. // adjustment is captured by an optional vbase and a non-virtual offset.
  2693. if (B.isVirtual())
  2694. P->ContainingVBases.push_back(Base);
  2695. else if (P->ContainingVBases.empty())
  2696. P->NonVirtualOffset += Layout.getBaseClassOffset(Base);
  2697. // Update the full offset in the MDC.
  2698. P->FullOffsetInMDC = P->NonVirtualOffset;
  2699. if (const CXXRecordDecl *VB = P->getVBaseWithVPtr())
  2700. P->FullOffsetInMDC += Layout.getVBaseClassOffset(VB);
  2701. Paths.push_back(std::move(P));
  2702. }
  2703. if (B.isVirtual())
  2704. VBasesSeen.insert(Base);
  2705. // After visiting any direct base, we've transitively visited all of its
  2706. // morally virtual bases.
  2707. for (const auto &VB : Base->vbases())
  2708. VBasesSeen.insert(VB.getType()->getAsCXXRecordDecl());
  2709. }
  2710. // Sort the paths into buckets, and if any of them are ambiguous, extend all
  2711. // paths in ambiguous buckets.
  2712. bool Changed = true;
  2713. while (Changed)
  2714. Changed = rebucketPaths(Paths);
  2715. }
  2716. static bool extendPath(VPtrInfo &P) {
  2717. if (P.NextBaseToMangle) {
  2718. P.MangledPath.push_back(P.NextBaseToMangle);
  2719. P.NextBaseToMangle = nullptr;// Prevent the path from being extended twice.
  2720. return true;
  2721. }
  2722. return false;
  2723. }
  2724. static bool rebucketPaths(VPtrInfoVector &Paths) {
  2725. // What we're essentially doing here is bucketing together ambiguous paths.
  2726. // Any bucket with more than one path in it gets extended by NextBase, which
  2727. // is usually the direct base of the inherited the vbptr. This code uses a
  2728. // sorted vector to implement a multiset to form the buckets. Note that the
  2729. // ordering is based on pointers, but it doesn't change our output order. The
  2730. // current algorithm is designed to match MSVC 2012's names.
  2731. llvm::SmallVector<std::reference_wrapper<VPtrInfo>, 2> PathsSorted;
  2732. PathsSorted.reserve(Paths.size());
  2733. for (auto& P : Paths)
  2734. PathsSorted.push_back(*P);
  2735. llvm::sort(PathsSorted, [](const VPtrInfo &LHS, const VPtrInfo &RHS) {
  2736. return LHS.MangledPath < RHS.MangledPath;
  2737. });
  2738. bool Changed = false;
  2739. for (size_t I = 0, E = PathsSorted.size(); I != E;) {
  2740. // Scan forward to find the end of the bucket.
  2741. size_t BucketStart = I;
  2742. do {
  2743. ++I;
  2744. } while (I != E &&
  2745. PathsSorted[BucketStart].get().MangledPath ==
  2746. PathsSorted[I].get().MangledPath);
  2747. // If this bucket has multiple paths, extend them all.
  2748. if (I - BucketStart > 1) {
  2749. for (size_t II = BucketStart; II != I; ++II)
  2750. Changed |= extendPath(PathsSorted[II]);
  2751. assert(Changed && "no paths were extended to fix ambiguity");
  2752. }
  2753. }
  2754. return Changed;
  2755. }
  2756. MicrosoftVTableContext::~MicrosoftVTableContext() {}
  2757. namespace {
  2758. typedef llvm::SetVector<BaseSubobject, std::vector<BaseSubobject>,
  2759. llvm::DenseSet<BaseSubobject>> FullPathTy;
  2760. }
  2761. // This recursive function finds all paths from a subobject centered at
  2762. // (RD, Offset) to the subobject located at IntroducingObject.
  2763. static void findPathsToSubobject(ASTContext &Context,
  2764. const ASTRecordLayout &MostDerivedLayout,
  2765. const CXXRecordDecl *RD, CharUnits Offset,
  2766. BaseSubobject IntroducingObject,
  2767. FullPathTy &FullPath,
  2768. std::list<FullPathTy> &Paths) {
  2769. if (BaseSubobject(RD, Offset) == IntroducingObject) {
  2770. Paths.push_back(FullPath);
  2771. return;
  2772. }
  2773. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  2774. for (const CXXBaseSpecifier &BS : RD->bases()) {
  2775. const CXXRecordDecl *Base = BS.getType()->getAsCXXRecordDecl();
  2776. CharUnits NewOffset = BS.isVirtual()
  2777. ? MostDerivedLayout.getVBaseClassOffset(Base)
  2778. : Offset + Layout.getBaseClassOffset(Base);
  2779. FullPath.insert(BaseSubobject(Base, NewOffset));
  2780. findPathsToSubobject(Context, MostDerivedLayout, Base, NewOffset,
  2781. IntroducingObject, FullPath, Paths);
  2782. FullPath.pop_back();
  2783. }
  2784. }
  2785. // Return the paths which are not subsets of other paths.
  2786. static void removeRedundantPaths(std::list<FullPathTy> &FullPaths) {
  2787. FullPaths.remove_if([&](const FullPathTy &SpecificPath) {
  2788. for (const FullPathTy &OtherPath : FullPaths) {
  2789. if (&SpecificPath == &OtherPath)
  2790. continue;
  2791. if (llvm::all_of(SpecificPath, [&](const BaseSubobject &BSO) {
  2792. return OtherPath.count(BSO) != 0;
  2793. })) {
  2794. return true;
  2795. }
  2796. }
  2797. return false;
  2798. });
  2799. }
  2800. static CharUnits getOffsetOfFullPath(ASTContext &Context,
  2801. const CXXRecordDecl *RD,
  2802. const FullPathTy &FullPath) {
  2803. const ASTRecordLayout &MostDerivedLayout =
  2804. Context.getASTRecordLayout(RD);
  2805. CharUnits Offset = CharUnits::fromQuantity(-1);
  2806. for (const BaseSubobject &BSO : FullPath) {
  2807. const CXXRecordDecl *Base = BSO.getBase();
  2808. // The first entry in the path is always the most derived record, skip it.
  2809. if (Base == RD) {
  2810. assert(Offset.getQuantity() == -1);
  2811. Offset = CharUnits::Zero();
  2812. continue;
  2813. }
  2814. assert(Offset.getQuantity() != -1);
  2815. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  2816. // While we know which base has to be traversed, we don't know if that base
  2817. // was a virtual base.
  2818. const CXXBaseSpecifier *BaseBS = std::find_if(
  2819. RD->bases_begin(), RD->bases_end(), [&](const CXXBaseSpecifier &BS) {
  2820. return BS.getType()->getAsCXXRecordDecl() == Base;
  2821. });
  2822. Offset = BaseBS->isVirtual() ? MostDerivedLayout.getVBaseClassOffset(Base)
  2823. : Offset + Layout.getBaseClassOffset(Base);
  2824. RD = Base;
  2825. }
  2826. return Offset;
  2827. }
  2828. // We want to select the path which introduces the most covariant overrides. If
  2829. // two paths introduce overrides which the other path doesn't contain, issue a
  2830. // diagnostic.
  2831. static const FullPathTy *selectBestPath(ASTContext &Context,
  2832. const CXXRecordDecl *RD,
  2833. const VPtrInfo &Info,
  2834. std::list<FullPathTy> &FullPaths) {
  2835. // Handle some easy cases first.
  2836. if (FullPaths.empty())
  2837. return nullptr;
  2838. if (FullPaths.size() == 1)
  2839. return &FullPaths.front();
  2840. const FullPathTy *BestPath = nullptr;
  2841. typedef std::set<const CXXMethodDecl *> OverriderSetTy;
  2842. OverriderSetTy LastOverrides;
  2843. for (const FullPathTy &SpecificPath : FullPaths) {
  2844. assert(!SpecificPath.empty());
  2845. OverriderSetTy CurrentOverrides;
  2846. const CXXRecordDecl *TopLevelRD = SpecificPath.begin()->getBase();
  2847. // Find the distance from the start of the path to the subobject with the
  2848. // VPtr.
  2849. CharUnits BaseOffset =
  2850. getOffsetOfFullPath(Context, TopLevelRD, SpecificPath);
  2851. FinalOverriders Overriders(TopLevelRD, CharUnits::Zero(), TopLevelRD);
  2852. for (const CXXMethodDecl *MD : Info.IntroducingObject->methods()) {
  2853. if (!MD->isVirtual())
  2854. continue;
  2855. FinalOverriders::OverriderInfo OI =
  2856. Overriders.getOverrider(MD->getCanonicalDecl(), BaseOffset);
  2857. const CXXMethodDecl *OverridingMethod = OI.Method;
  2858. // Only overriders which have a return adjustment introduce problematic
  2859. // thunks.
  2860. if (ComputeReturnAdjustmentBaseOffset(Context, OverridingMethod, MD)
  2861. .isEmpty())
  2862. continue;
  2863. // It's possible that the overrider isn't in this path. If so, skip it
  2864. // because this path didn't introduce it.
  2865. const CXXRecordDecl *OverridingParent = OverridingMethod->getParent();
  2866. if (llvm::none_of(SpecificPath, [&](const BaseSubobject &BSO) {
  2867. return BSO.getBase() == OverridingParent;
  2868. }))
  2869. continue;
  2870. CurrentOverrides.insert(OverridingMethod);
  2871. }
  2872. OverriderSetTy NewOverrides =
  2873. llvm::set_difference(CurrentOverrides, LastOverrides);
  2874. if (NewOverrides.empty())
  2875. continue;
  2876. OverriderSetTy MissingOverrides =
  2877. llvm::set_difference(LastOverrides, CurrentOverrides);
  2878. if (MissingOverrides.empty()) {
  2879. // This path is a strict improvement over the last path, let's use it.
  2880. BestPath = &SpecificPath;
  2881. std::swap(CurrentOverrides, LastOverrides);
  2882. } else {
  2883. // This path introduces an overrider with a conflicting covariant thunk.
  2884. DiagnosticsEngine &Diags = Context.getDiagnostics();
  2885. const CXXMethodDecl *CovariantMD = *NewOverrides.begin();
  2886. const CXXMethodDecl *ConflictMD = *MissingOverrides.begin();
  2887. Diags.Report(RD->getLocation(), diag::err_vftable_ambiguous_component)
  2888. << RD;
  2889. Diags.Report(CovariantMD->getLocation(), diag::note_covariant_thunk)
  2890. << CovariantMD;
  2891. Diags.Report(ConflictMD->getLocation(), diag::note_covariant_thunk)
  2892. << ConflictMD;
  2893. }
  2894. }
  2895. // Go with the path that introduced the most covariant overrides. If there is
  2896. // no such path, pick the first path.
  2897. return BestPath ? BestPath : &FullPaths.front();
  2898. }
  2899. static void computeFullPathsForVFTables(ASTContext &Context,
  2900. const CXXRecordDecl *RD,
  2901. VPtrInfoVector &Paths) {
  2902. const ASTRecordLayout &MostDerivedLayout = Context.getASTRecordLayout(RD);
  2903. FullPathTy FullPath;
  2904. std::list<FullPathTy> FullPaths;
  2905. for (const std::unique_ptr<VPtrInfo>& Info : Paths) {
  2906. findPathsToSubobject(
  2907. Context, MostDerivedLayout, RD, CharUnits::Zero(),
  2908. BaseSubobject(Info->IntroducingObject, Info->FullOffsetInMDC), FullPath,
  2909. FullPaths);
  2910. FullPath.clear();
  2911. removeRedundantPaths(FullPaths);
  2912. Info->PathToIntroducingObject.clear();
  2913. if (const FullPathTy *BestPath =
  2914. selectBestPath(Context, RD, *Info, FullPaths))
  2915. for (const BaseSubobject &BSO : *BestPath)
  2916. Info->PathToIntroducingObject.push_back(BSO.getBase());
  2917. FullPaths.clear();
  2918. }
  2919. }
  2920. static bool vfptrIsEarlierInMDC(const ASTRecordLayout &Layout,
  2921. const MethodVFTableLocation &LHS,
  2922. const MethodVFTableLocation &RHS) {
  2923. CharUnits L = LHS.VFPtrOffset;
  2924. CharUnits R = RHS.VFPtrOffset;
  2925. if (LHS.VBase)
  2926. L += Layout.getVBaseClassOffset(LHS.VBase);
  2927. if (RHS.VBase)
  2928. R += Layout.getVBaseClassOffset(RHS.VBase);
  2929. return L < R;
  2930. }
  2931. void MicrosoftVTableContext::computeVTableRelatedInformation(
  2932. const CXXRecordDecl *RD) {
  2933. assert(RD->isDynamicClass());
  2934. // Check if we've computed this information before.
  2935. if (VFPtrLocations.count(RD))
  2936. return;
  2937. const VTableLayout::AddressPointsMapTy EmptyAddressPointsMap;
  2938. {
  2939. auto VFPtrs = std::make_unique<VPtrInfoVector>();
  2940. computeVTablePaths(/*ForVBTables=*/false, RD, *VFPtrs);
  2941. computeFullPathsForVFTables(Context, RD, *VFPtrs);
  2942. VFPtrLocations[RD] = std::move(VFPtrs);
  2943. }
  2944. MethodVFTableLocationsTy NewMethodLocations;
  2945. for (const std::unique_ptr<VPtrInfo> &VFPtr : *VFPtrLocations[RD]) {
  2946. VFTableBuilder Builder(*this, RD, *VFPtr);
  2947. VFTableIdTy id(RD, VFPtr->FullOffsetInMDC);
  2948. assert(VFTableLayouts.count(id) == 0);
  2949. SmallVector<VTableLayout::VTableThunkTy, 1> VTableThunks(
  2950. Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
  2951. VFTableLayouts[id] = std::make_unique<VTableLayout>(
  2952. ArrayRef<size_t>{0}, Builder.vtable_components(), VTableThunks,
  2953. EmptyAddressPointsMap);
  2954. Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
  2955. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  2956. for (const auto &Loc : Builder.vtable_locations()) {
  2957. auto Insert = NewMethodLocations.insert(Loc);
  2958. if (!Insert.second) {
  2959. const MethodVFTableLocation &NewLoc = Loc.second;
  2960. MethodVFTableLocation &OldLoc = Insert.first->second;
  2961. if (vfptrIsEarlierInMDC(Layout, NewLoc, OldLoc))
  2962. OldLoc = NewLoc;
  2963. }
  2964. }
  2965. }
  2966. MethodVFTableLocations.insert(NewMethodLocations.begin(),
  2967. NewMethodLocations.end());
  2968. if (Context.getLangOpts().DumpVTableLayouts)
  2969. dumpMethodLocations(RD, NewMethodLocations, llvm::outs());
  2970. }
  2971. void MicrosoftVTableContext::dumpMethodLocations(
  2972. const CXXRecordDecl *RD, const MethodVFTableLocationsTy &NewMethods,
  2973. raw_ostream &Out) {
  2974. // Compute the vtable indices for all the member functions.
  2975. // Store them in a map keyed by the location so we'll get a sorted table.
  2976. std::map<MethodVFTableLocation, std::string> IndicesMap;
  2977. bool HasNonzeroOffset = false;
  2978. for (const auto &I : NewMethods) {
  2979. const CXXMethodDecl *MD = cast<const CXXMethodDecl>(I.first.getDecl());
  2980. assert(MD->isVirtual());
  2981. std::string MethodName = PredefinedExpr::ComputeName(
  2982. PredefinedExpr::PrettyFunctionNoVirtual, MD);
  2983. if (isa<CXXDestructorDecl>(MD)) {
  2984. IndicesMap[I.second] = MethodName + " [scalar deleting]";
  2985. } else {
  2986. IndicesMap[I.second] = MethodName;
  2987. }
  2988. if (!I.second.VFPtrOffset.isZero() || I.second.VBTableIndex != 0)
  2989. HasNonzeroOffset = true;
  2990. }
  2991. // Print the vtable indices for all the member functions.
  2992. if (!IndicesMap.empty()) {
  2993. Out << "VFTable indices for ";
  2994. Out << "'";
  2995. RD->printQualifiedName(Out);
  2996. Out << "' (" << IndicesMap.size()
  2997. << (IndicesMap.size() == 1 ? " entry" : " entries") << ").\n";
  2998. CharUnits LastVFPtrOffset = CharUnits::fromQuantity(-1);
  2999. uint64_t LastVBIndex = 0;
  3000. for (const auto &I : IndicesMap) {
  3001. CharUnits VFPtrOffset = I.first.VFPtrOffset;
  3002. uint64_t VBIndex = I.first.VBTableIndex;
  3003. if (HasNonzeroOffset &&
  3004. (VFPtrOffset != LastVFPtrOffset || VBIndex != LastVBIndex)) {
  3005. assert(VBIndex > LastVBIndex || VFPtrOffset > LastVFPtrOffset);
  3006. Out << " -- accessible via ";
  3007. if (VBIndex)
  3008. Out << "vbtable index " << VBIndex << ", ";
  3009. Out << "vfptr at offset " << VFPtrOffset.getQuantity() << " --\n";
  3010. LastVFPtrOffset = VFPtrOffset;
  3011. LastVBIndex = VBIndex;
  3012. }
  3013. uint64_t VTableIndex = I.first.Index;
  3014. const std::string &MethodName = I.second;
  3015. Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName << '\n';
  3016. }
  3017. Out << '\n';
  3018. }
  3019. Out.flush();
  3020. }
  3021. const VirtualBaseInfo &MicrosoftVTableContext::computeVBTableRelatedInformation(
  3022. const CXXRecordDecl *RD) {
  3023. VirtualBaseInfo *VBI;
  3024. {
  3025. // Get or create a VBI for RD. Don't hold a reference to the DenseMap cell,
  3026. // as it may be modified and rehashed under us.
  3027. std::unique_ptr<VirtualBaseInfo> &Entry = VBaseInfo[RD];
  3028. if (Entry)
  3029. return *Entry;
  3030. Entry = std::make_unique<VirtualBaseInfo>();
  3031. VBI = Entry.get();
  3032. }
  3033. computeVTablePaths(/*ForVBTables=*/true, RD, VBI->VBPtrPaths);
  3034. // First, see if the Derived class shared the vbptr with a non-virtual base.
  3035. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  3036. if (const CXXRecordDecl *VBPtrBase = Layout.getBaseSharingVBPtr()) {
  3037. // If the Derived class shares the vbptr with a non-virtual base, the shared
  3038. // virtual bases come first so that the layout is the same.
  3039. const VirtualBaseInfo &BaseInfo =
  3040. computeVBTableRelatedInformation(VBPtrBase);
  3041. VBI->VBTableIndices.insert(BaseInfo.VBTableIndices.begin(),
  3042. BaseInfo.VBTableIndices.end());
  3043. }
  3044. // New vbases are added to the end of the vbtable.
  3045. // Skip the self entry and vbases visited in the non-virtual base, if any.
  3046. unsigned VBTableIndex = 1 + VBI->VBTableIndices.size();
  3047. for (const auto &VB : RD->vbases()) {
  3048. const CXXRecordDecl *CurVBase = VB.getType()->getAsCXXRecordDecl();
  3049. if (!VBI->VBTableIndices.count(CurVBase))
  3050. VBI->VBTableIndices[CurVBase] = VBTableIndex++;
  3051. }
  3052. return *VBI;
  3053. }
  3054. unsigned MicrosoftVTableContext::getVBTableIndex(const CXXRecordDecl *Derived,
  3055. const CXXRecordDecl *VBase) {
  3056. const VirtualBaseInfo &VBInfo = computeVBTableRelatedInformation(Derived);
  3057. assert(VBInfo.VBTableIndices.count(VBase));
  3058. return VBInfo.VBTableIndices.find(VBase)->second;
  3059. }
  3060. const VPtrInfoVector &
  3061. MicrosoftVTableContext::enumerateVBTables(const CXXRecordDecl *RD) {
  3062. return computeVBTableRelatedInformation(RD).VBPtrPaths;
  3063. }
  3064. const VPtrInfoVector &
  3065. MicrosoftVTableContext::getVFPtrOffsets(const CXXRecordDecl *RD) {
  3066. computeVTableRelatedInformation(RD);
  3067. assert(VFPtrLocations.count(RD) && "Couldn't find vfptr locations");
  3068. return *VFPtrLocations[RD];
  3069. }
  3070. const VTableLayout &
  3071. MicrosoftVTableContext::getVFTableLayout(const CXXRecordDecl *RD,
  3072. CharUnits VFPtrOffset) {
  3073. computeVTableRelatedInformation(RD);
  3074. VFTableIdTy id(RD, VFPtrOffset);
  3075. assert(VFTableLayouts.count(id) && "Couldn't find a VFTable at this offset");
  3076. return *VFTableLayouts[id];
  3077. }
  3078. MethodVFTableLocation
  3079. MicrosoftVTableContext::getMethodVFTableLocation(GlobalDecl GD) {
  3080. assert(cast<CXXMethodDecl>(GD.getDecl())->isVirtual() &&
  3081. "Only use this method for virtual methods or dtors");
  3082. if (isa<CXXDestructorDecl>(GD.getDecl()))
  3083. assert(GD.getDtorType() == Dtor_Deleting);
  3084. GD = GD.getCanonicalDecl();
  3085. MethodVFTableLocationsTy::iterator I = MethodVFTableLocations.find(GD);
  3086. if (I != MethodVFTableLocations.end())
  3087. return I->second;
  3088. const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
  3089. computeVTableRelatedInformation(RD);
  3090. I = MethodVFTableLocations.find(GD);
  3091. assert(I != MethodVFTableLocations.end() && "Did not find index!");
  3092. return I->second;
  3093. }