VTableBuilder.cpp 140 KB

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