RecordLayoutBuilder.cpp 144 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726
  1. //=== RecordLayoutBuilder.cpp - Helper class for building record layouts ---==//
  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. #include "clang/AST/ASTContext.h"
  9. #include "clang/AST/ASTDiagnostic.h"
  10. #include "clang/AST/Attr.h"
  11. #include "clang/AST/CXXInheritance.h"
  12. #include "clang/AST/Decl.h"
  13. #include "clang/AST/DeclCXX.h"
  14. #include "clang/AST/DeclObjC.h"
  15. #include "clang/AST/Expr.h"
  16. #include "clang/AST/VTableBuilder.h"
  17. #include "clang/AST/RecordLayout.h"
  18. #include "clang/Basic/TargetInfo.h"
  19. #include "llvm/ADT/SmallSet.h"
  20. #include "llvm/Support/Format.h"
  21. #include "llvm/Support/MathExtras.h"
  22. using namespace clang;
  23. namespace {
  24. /// BaseSubobjectInfo - Represents a single base subobject in a complete class.
  25. /// For a class hierarchy like
  26. ///
  27. /// class A { };
  28. /// class B : A { };
  29. /// class C : A, B { };
  30. ///
  31. /// The BaseSubobjectInfo graph for C will have three BaseSubobjectInfo
  32. /// instances, one for B and two for A.
  33. ///
  34. /// If a base is virtual, it will only have one BaseSubobjectInfo allocated.
  35. struct BaseSubobjectInfo {
  36. /// Class - The class for this base info.
  37. const CXXRecordDecl *Class;
  38. /// IsVirtual - Whether the BaseInfo represents a virtual base or not.
  39. bool IsVirtual;
  40. /// Bases - Information about the base subobjects.
  41. SmallVector<BaseSubobjectInfo*, 4> Bases;
  42. /// PrimaryVirtualBaseInfo - Holds the base info for the primary virtual base
  43. /// of this base info (if one exists).
  44. BaseSubobjectInfo *PrimaryVirtualBaseInfo;
  45. // FIXME: Document.
  46. const BaseSubobjectInfo *Derived;
  47. };
  48. /// Externally provided layout. Typically used when the AST source, such
  49. /// as DWARF, lacks all the information that was available at compile time, such
  50. /// as alignment attributes on fields and pragmas in effect.
  51. struct ExternalLayout {
  52. ExternalLayout() : Size(0), Align(0) {}
  53. /// Overall record size in bits.
  54. uint64_t Size;
  55. /// Overall record alignment in bits.
  56. uint64_t Align;
  57. /// Record field offsets in bits.
  58. llvm::DenseMap<const FieldDecl *, uint64_t> FieldOffsets;
  59. /// Direct, non-virtual base offsets.
  60. llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsets;
  61. /// Virtual base offsets.
  62. llvm::DenseMap<const CXXRecordDecl *, CharUnits> VirtualBaseOffsets;
  63. /// Get the offset of the given field. The external source must provide
  64. /// entries for all fields in the record.
  65. uint64_t getExternalFieldOffset(const FieldDecl *FD) {
  66. assert(FieldOffsets.count(FD) &&
  67. "Field does not have an external offset");
  68. return FieldOffsets[FD];
  69. }
  70. bool getExternalNVBaseOffset(const CXXRecordDecl *RD, CharUnits &BaseOffset) {
  71. auto Known = BaseOffsets.find(RD);
  72. if (Known == BaseOffsets.end())
  73. return false;
  74. BaseOffset = Known->second;
  75. return true;
  76. }
  77. bool getExternalVBaseOffset(const CXXRecordDecl *RD, CharUnits &BaseOffset) {
  78. auto Known = VirtualBaseOffsets.find(RD);
  79. if (Known == VirtualBaseOffsets.end())
  80. return false;
  81. BaseOffset = Known->second;
  82. return true;
  83. }
  84. };
  85. /// EmptySubobjectMap - Keeps track of which empty subobjects exist at different
  86. /// offsets while laying out a C++ class.
  87. class EmptySubobjectMap {
  88. const ASTContext &Context;
  89. uint64_t CharWidth;
  90. /// Class - The class whose empty entries we're keeping track of.
  91. const CXXRecordDecl *Class;
  92. /// EmptyClassOffsets - A map from offsets to empty record decls.
  93. typedef llvm::TinyPtrVector<const CXXRecordDecl *> ClassVectorTy;
  94. typedef llvm::DenseMap<CharUnits, ClassVectorTy> EmptyClassOffsetsMapTy;
  95. EmptyClassOffsetsMapTy EmptyClassOffsets;
  96. /// MaxEmptyClassOffset - The highest offset known to contain an empty
  97. /// base subobject.
  98. CharUnits MaxEmptyClassOffset;
  99. /// ComputeEmptySubobjectSizes - Compute the size of the largest base or
  100. /// member subobject that is empty.
  101. void ComputeEmptySubobjectSizes();
  102. void AddSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset);
  103. void UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
  104. CharUnits Offset, bool PlacingEmptyBase);
  105. void UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
  106. const CXXRecordDecl *Class, CharUnits Offset,
  107. bool PlacingOverlappingField);
  108. void UpdateEmptyFieldSubobjects(const FieldDecl *FD, CharUnits Offset,
  109. bool PlacingOverlappingField);
  110. /// AnyEmptySubobjectsBeyondOffset - Returns whether there are any empty
  111. /// subobjects beyond the given offset.
  112. bool AnyEmptySubobjectsBeyondOffset(CharUnits Offset) const {
  113. return Offset <= MaxEmptyClassOffset;
  114. }
  115. CharUnits
  116. getFieldOffset(const ASTRecordLayout &Layout, unsigned FieldNo) const {
  117. uint64_t FieldOffset = Layout.getFieldOffset(FieldNo);
  118. assert(FieldOffset % CharWidth == 0 &&
  119. "Field offset not at char boundary!");
  120. return Context.toCharUnitsFromBits(FieldOffset);
  121. }
  122. protected:
  123. bool CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
  124. CharUnits Offset) const;
  125. bool CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
  126. CharUnits Offset);
  127. bool CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
  128. const CXXRecordDecl *Class,
  129. CharUnits Offset) const;
  130. bool CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
  131. CharUnits Offset) const;
  132. public:
  133. /// This holds the size of the largest empty subobject (either a base
  134. /// or a member). Will be zero if the record being built doesn't contain
  135. /// any empty classes.
  136. CharUnits SizeOfLargestEmptySubobject;
  137. EmptySubobjectMap(const ASTContext &Context, const CXXRecordDecl *Class)
  138. : Context(Context), CharWidth(Context.getCharWidth()), Class(Class) {
  139. ComputeEmptySubobjectSizes();
  140. }
  141. /// CanPlaceBaseAtOffset - Return whether the given base class can be placed
  142. /// at the given offset.
  143. /// Returns false if placing the record will result in two components
  144. /// (direct or indirect) of the same type having the same offset.
  145. bool CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
  146. CharUnits Offset);
  147. /// CanPlaceFieldAtOffset - Return whether a field can be placed at the given
  148. /// offset.
  149. bool CanPlaceFieldAtOffset(const FieldDecl *FD, CharUnits Offset);
  150. };
  151. void EmptySubobjectMap::ComputeEmptySubobjectSizes() {
  152. // Check the bases.
  153. for (const CXXBaseSpecifier &Base : Class->bases()) {
  154. const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
  155. CharUnits EmptySize;
  156. const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
  157. if (BaseDecl->isEmpty()) {
  158. // If the class decl is empty, get its size.
  159. EmptySize = Layout.getSize();
  160. } else {
  161. // Otherwise, we get the largest empty subobject for the decl.
  162. EmptySize = Layout.getSizeOfLargestEmptySubobject();
  163. }
  164. if (EmptySize > SizeOfLargestEmptySubobject)
  165. SizeOfLargestEmptySubobject = EmptySize;
  166. }
  167. // Check the fields.
  168. for (const FieldDecl *FD : Class->fields()) {
  169. const RecordType *RT =
  170. Context.getBaseElementType(FD->getType())->getAs<RecordType>();
  171. // We only care about record types.
  172. if (!RT)
  173. continue;
  174. CharUnits EmptySize;
  175. const CXXRecordDecl *MemberDecl = RT->getAsCXXRecordDecl();
  176. const ASTRecordLayout &Layout = Context.getASTRecordLayout(MemberDecl);
  177. if (MemberDecl->isEmpty()) {
  178. // If the class decl is empty, get its size.
  179. EmptySize = Layout.getSize();
  180. } else {
  181. // Otherwise, we get the largest empty subobject for the decl.
  182. EmptySize = Layout.getSizeOfLargestEmptySubobject();
  183. }
  184. if (EmptySize > SizeOfLargestEmptySubobject)
  185. SizeOfLargestEmptySubobject = EmptySize;
  186. }
  187. }
  188. bool
  189. EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
  190. CharUnits Offset) const {
  191. // We only need to check empty bases.
  192. if (!RD->isEmpty())
  193. return true;
  194. EmptyClassOffsetsMapTy::const_iterator I = EmptyClassOffsets.find(Offset);
  195. if (I == EmptyClassOffsets.end())
  196. return true;
  197. const ClassVectorTy &Classes = I->second;
  198. if (!llvm::is_contained(Classes, RD))
  199. return true;
  200. // There is already an empty class of the same type at this offset.
  201. return false;
  202. }
  203. void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl *RD,
  204. CharUnits Offset) {
  205. // We only care about empty bases.
  206. if (!RD->isEmpty())
  207. return;
  208. // If we have empty structures inside a union, we can assign both
  209. // the same offset. Just avoid pushing them twice in the list.
  210. ClassVectorTy &Classes = EmptyClassOffsets[Offset];
  211. if (llvm::is_contained(Classes, RD))
  212. return;
  213. Classes.push_back(RD);
  214. // Update the empty class offset.
  215. if (Offset > MaxEmptyClassOffset)
  216. MaxEmptyClassOffset = Offset;
  217. }
  218. bool
  219. EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
  220. CharUnits Offset) {
  221. // We don't have to keep looking past the maximum offset that's known to
  222. // contain an empty class.
  223. if (!AnyEmptySubobjectsBeyondOffset(Offset))
  224. return true;
  225. if (!CanPlaceSubobjectAtOffset(Info->Class, Offset))
  226. return false;
  227. // Traverse all non-virtual bases.
  228. const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
  229. for (const BaseSubobjectInfo *Base : Info->Bases) {
  230. if (Base->IsVirtual)
  231. continue;
  232. CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
  233. if (!CanPlaceBaseSubobjectAtOffset(Base, BaseOffset))
  234. return false;
  235. }
  236. if (Info->PrimaryVirtualBaseInfo) {
  237. BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
  238. if (Info == PrimaryVirtualBaseInfo->Derived) {
  239. if (!CanPlaceBaseSubobjectAtOffset(PrimaryVirtualBaseInfo, Offset))
  240. return false;
  241. }
  242. }
  243. // Traverse all member variables.
  244. unsigned FieldNo = 0;
  245. for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
  246. E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
  247. if (I->isBitField())
  248. continue;
  249. CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
  250. if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
  251. return false;
  252. }
  253. return true;
  254. }
  255. void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
  256. CharUnits Offset,
  257. bool PlacingEmptyBase) {
  258. if (!PlacingEmptyBase && Offset >= SizeOfLargestEmptySubobject) {
  259. // We know that the only empty subobjects that can conflict with empty
  260. // subobject of non-empty bases, are empty bases that can be placed at
  261. // offset zero. Because of this, we only need to keep track of empty base
  262. // subobjects with offsets less than the size of the largest empty
  263. // subobject for our class.
  264. return;
  265. }
  266. AddSubobjectAtOffset(Info->Class, Offset);
  267. // Traverse all non-virtual bases.
  268. const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
  269. for (const BaseSubobjectInfo *Base : Info->Bases) {
  270. if (Base->IsVirtual)
  271. continue;
  272. CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
  273. UpdateEmptyBaseSubobjects(Base, BaseOffset, PlacingEmptyBase);
  274. }
  275. if (Info->PrimaryVirtualBaseInfo) {
  276. BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
  277. if (Info == PrimaryVirtualBaseInfo->Derived)
  278. UpdateEmptyBaseSubobjects(PrimaryVirtualBaseInfo, Offset,
  279. PlacingEmptyBase);
  280. }
  281. // Traverse all member variables.
  282. unsigned FieldNo = 0;
  283. for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
  284. E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
  285. if (I->isBitField())
  286. continue;
  287. CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
  288. UpdateEmptyFieldSubobjects(*I, FieldOffset, PlacingEmptyBase);
  289. }
  290. }
  291. bool EmptySubobjectMap::CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
  292. CharUnits Offset) {
  293. // If we know this class doesn't have any empty subobjects we don't need to
  294. // bother checking.
  295. if (SizeOfLargestEmptySubobject.isZero())
  296. return true;
  297. if (!CanPlaceBaseSubobjectAtOffset(Info, Offset))
  298. return false;
  299. // We are able to place the base at this offset. Make sure to update the
  300. // empty base subobject map.
  301. UpdateEmptyBaseSubobjects(Info, Offset, Info->Class->isEmpty());
  302. return true;
  303. }
  304. bool
  305. EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
  306. const CXXRecordDecl *Class,
  307. CharUnits Offset) const {
  308. // We don't have to keep looking past the maximum offset that's known to
  309. // contain an empty class.
  310. if (!AnyEmptySubobjectsBeyondOffset(Offset))
  311. return true;
  312. if (!CanPlaceSubobjectAtOffset(RD, Offset))
  313. return false;
  314. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  315. // Traverse all non-virtual bases.
  316. for (const CXXBaseSpecifier &Base : RD->bases()) {
  317. if (Base.isVirtual())
  318. continue;
  319. const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
  320. CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
  321. if (!CanPlaceFieldSubobjectAtOffset(BaseDecl, Class, BaseOffset))
  322. return false;
  323. }
  324. if (RD == Class) {
  325. // This is the most derived class, traverse virtual bases as well.
  326. for (const CXXBaseSpecifier &Base : RD->vbases()) {
  327. const CXXRecordDecl *VBaseDecl = Base.getType()->getAsCXXRecordDecl();
  328. CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
  329. if (!CanPlaceFieldSubobjectAtOffset(VBaseDecl, Class, VBaseOffset))
  330. return false;
  331. }
  332. }
  333. // Traverse all member variables.
  334. unsigned FieldNo = 0;
  335. for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
  336. I != E; ++I, ++FieldNo) {
  337. if (I->isBitField())
  338. continue;
  339. CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
  340. if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
  341. return false;
  342. }
  343. return true;
  344. }
  345. bool
  346. EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
  347. CharUnits Offset) const {
  348. // We don't have to keep looking past the maximum offset that's known to
  349. // contain an empty class.
  350. if (!AnyEmptySubobjectsBeyondOffset(Offset))
  351. return true;
  352. QualType T = FD->getType();
  353. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  354. return CanPlaceFieldSubobjectAtOffset(RD, RD, Offset);
  355. // If we have an array type we need to look at every element.
  356. if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
  357. QualType ElemTy = Context.getBaseElementType(AT);
  358. const RecordType *RT = ElemTy->getAs<RecordType>();
  359. if (!RT)
  360. return true;
  361. const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
  362. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  363. uint64_t NumElements = Context.getConstantArrayElementCount(AT);
  364. CharUnits ElementOffset = Offset;
  365. for (uint64_t I = 0; I != NumElements; ++I) {
  366. // We don't have to keep looking past the maximum offset that's known to
  367. // contain an empty class.
  368. if (!AnyEmptySubobjectsBeyondOffset(ElementOffset))
  369. return true;
  370. if (!CanPlaceFieldSubobjectAtOffset(RD, RD, ElementOffset))
  371. return false;
  372. ElementOffset += Layout.getSize();
  373. }
  374. }
  375. return true;
  376. }
  377. bool
  378. EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD,
  379. CharUnits Offset) {
  380. if (!CanPlaceFieldSubobjectAtOffset(FD, Offset))
  381. return false;
  382. // We are able to place the member variable at this offset.
  383. // Make sure to update the empty field subobject map.
  384. UpdateEmptyFieldSubobjects(FD, Offset, FD->hasAttr<NoUniqueAddressAttr>());
  385. return true;
  386. }
  387. void EmptySubobjectMap::UpdateEmptyFieldSubobjects(
  388. const CXXRecordDecl *RD, const CXXRecordDecl *Class, CharUnits Offset,
  389. bool PlacingOverlappingField) {
  390. // We know that the only empty subobjects that can conflict with empty
  391. // field subobjects are subobjects of empty bases and potentially-overlapping
  392. // fields that can be placed at offset zero. Because of this, we only need to
  393. // keep track of empty field subobjects with offsets less than the size of
  394. // the largest empty subobject for our class.
  395. //
  396. // (Proof: we will only consider placing a subobject at offset zero or at
  397. // >= the current dsize. The only cases where the earlier subobject can be
  398. // placed beyond the end of dsize is if it's an empty base or a
  399. // potentially-overlapping field.)
  400. if (!PlacingOverlappingField && Offset >= SizeOfLargestEmptySubobject)
  401. return;
  402. AddSubobjectAtOffset(RD, Offset);
  403. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  404. // Traverse all non-virtual bases.
  405. for (const CXXBaseSpecifier &Base : RD->bases()) {
  406. if (Base.isVirtual())
  407. continue;
  408. const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
  409. CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
  410. UpdateEmptyFieldSubobjects(BaseDecl, Class, BaseOffset,
  411. PlacingOverlappingField);
  412. }
  413. if (RD == Class) {
  414. // This is the most derived class, traverse virtual bases as well.
  415. for (const CXXBaseSpecifier &Base : RD->vbases()) {
  416. const CXXRecordDecl *VBaseDecl = Base.getType()->getAsCXXRecordDecl();
  417. CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
  418. UpdateEmptyFieldSubobjects(VBaseDecl, Class, VBaseOffset,
  419. PlacingOverlappingField);
  420. }
  421. }
  422. // Traverse all member variables.
  423. unsigned FieldNo = 0;
  424. for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
  425. I != E; ++I, ++FieldNo) {
  426. if (I->isBitField())
  427. continue;
  428. CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
  429. UpdateEmptyFieldSubobjects(*I, FieldOffset, PlacingOverlappingField);
  430. }
  431. }
  432. void EmptySubobjectMap::UpdateEmptyFieldSubobjects(
  433. const FieldDecl *FD, CharUnits Offset, bool PlacingOverlappingField) {
  434. QualType T = FD->getType();
  435. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
  436. UpdateEmptyFieldSubobjects(RD, RD, Offset, PlacingOverlappingField);
  437. return;
  438. }
  439. // If we have an array type we need to update every element.
  440. if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
  441. QualType ElemTy = Context.getBaseElementType(AT);
  442. const RecordType *RT = ElemTy->getAs<RecordType>();
  443. if (!RT)
  444. return;
  445. const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
  446. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  447. uint64_t NumElements = Context.getConstantArrayElementCount(AT);
  448. CharUnits ElementOffset = Offset;
  449. for (uint64_t I = 0; I != NumElements; ++I) {
  450. // We know that the only empty subobjects that can conflict with empty
  451. // field subobjects are subobjects of empty bases that can be placed at
  452. // offset zero. Because of this, we only need to keep track of empty field
  453. // subobjects with offsets less than the size of the largest empty
  454. // subobject for our class.
  455. if (!PlacingOverlappingField &&
  456. ElementOffset >= SizeOfLargestEmptySubobject)
  457. return;
  458. UpdateEmptyFieldSubobjects(RD, RD, ElementOffset,
  459. PlacingOverlappingField);
  460. ElementOffset += Layout.getSize();
  461. }
  462. }
  463. }
  464. typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> ClassSetTy;
  465. class ItaniumRecordLayoutBuilder {
  466. protected:
  467. // FIXME: Remove this and make the appropriate fields public.
  468. friend class clang::ASTContext;
  469. const ASTContext &Context;
  470. EmptySubobjectMap *EmptySubobjects;
  471. /// Size - The current size of the record layout.
  472. uint64_t Size;
  473. /// Alignment - The current alignment of the record layout.
  474. CharUnits Alignment;
  475. /// PreferredAlignment - The preferred alignment of the record layout.
  476. CharUnits PreferredAlignment;
  477. /// The alignment if attribute packed is not used.
  478. CharUnits UnpackedAlignment;
  479. /// \brief The maximum of the alignments of top-level members.
  480. CharUnits UnadjustedAlignment;
  481. SmallVector<uint64_t, 16> FieldOffsets;
  482. /// Whether the external AST source has provided a layout for this
  483. /// record.
  484. unsigned UseExternalLayout : 1;
  485. /// Whether we need to infer alignment, even when we have an
  486. /// externally-provided layout.
  487. unsigned InferAlignment : 1;
  488. /// Packed - Whether the record is packed or not.
  489. unsigned Packed : 1;
  490. unsigned IsUnion : 1;
  491. unsigned IsMac68kAlign : 1;
  492. unsigned IsNaturalAlign : 1;
  493. unsigned IsMsStruct : 1;
  494. /// UnfilledBitsInLastUnit - If the last field laid out was a bitfield,
  495. /// this contains the number of bits in the last unit that can be used for
  496. /// an adjacent bitfield if necessary. The unit in question is usually
  497. /// a byte, but larger units are used if IsMsStruct.
  498. unsigned char UnfilledBitsInLastUnit;
  499. /// LastBitfieldStorageUnitSize - If IsMsStruct, represents the size of the
  500. /// storage unit of the previous field if it was a bitfield.
  501. unsigned char LastBitfieldStorageUnitSize;
  502. /// MaxFieldAlignment - The maximum allowed field alignment. This is set by
  503. /// #pragma pack.
  504. CharUnits MaxFieldAlignment;
  505. /// DataSize - The data size of the record being laid out.
  506. uint64_t DataSize;
  507. CharUnits NonVirtualSize;
  508. CharUnits NonVirtualAlignment;
  509. CharUnits PreferredNVAlignment;
  510. /// If we've laid out a field but not included its tail padding in Size yet,
  511. /// this is the size up to the end of that field.
  512. CharUnits PaddedFieldSize;
  513. /// PrimaryBase - the primary base class (if one exists) of the class
  514. /// we're laying out.
  515. const CXXRecordDecl *PrimaryBase;
  516. /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying
  517. /// out is virtual.
  518. bool PrimaryBaseIsVirtual;
  519. /// HasOwnVFPtr - Whether the class provides its own vtable/vftbl
  520. /// pointer, as opposed to inheriting one from a primary base class.
  521. bool HasOwnVFPtr;
  522. /// the flag of field offset changing due to packed attribute.
  523. bool HasPackedField;
  524. /// HandledFirstNonOverlappingEmptyField - An auxiliary field used for AIX.
  525. /// When there are OverlappingEmptyFields existing in the aggregate, the
  526. /// flag shows if the following first non-empty or empty-but-non-overlapping
  527. /// field has been handled, if any.
  528. bool HandledFirstNonOverlappingEmptyField;
  529. typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
  530. /// Bases - base classes and their offsets in the record.
  531. BaseOffsetsMapTy Bases;
  532. // VBases - virtual base classes and their offsets in the record.
  533. ASTRecordLayout::VBaseOffsetsMapTy VBases;
  534. /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are
  535. /// primary base classes for some other direct or indirect base class.
  536. CXXIndirectPrimaryBaseSet IndirectPrimaryBases;
  537. /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in
  538. /// inheritance graph order. Used for determining the primary base class.
  539. const CXXRecordDecl *FirstNearlyEmptyVBase;
  540. /// VisitedVirtualBases - A set of all the visited virtual bases, used to
  541. /// avoid visiting virtual bases more than once.
  542. llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
  543. /// Valid if UseExternalLayout is true.
  544. ExternalLayout External;
  545. ItaniumRecordLayoutBuilder(const ASTContext &Context,
  546. EmptySubobjectMap *EmptySubobjects)
  547. : Context(Context), EmptySubobjects(EmptySubobjects), Size(0),
  548. Alignment(CharUnits::One()), PreferredAlignment(CharUnits::One()),
  549. UnpackedAlignment(CharUnits::One()),
  550. UnadjustedAlignment(CharUnits::One()), UseExternalLayout(false),
  551. InferAlignment(false), Packed(false), IsUnion(false),
  552. IsMac68kAlign(false),
  553. IsNaturalAlign(!Context.getTargetInfo().getTriple().isOSAIX()),
  554. IsMsStruct(false), UnfilledBitsInLastUnit(0),
  555. LastBitfieldStorageUnitSize(0), MaxFieldAlignment(CharUnits::Zero()),
  556. DataSize(0), NonVirtualSize(CharUnits::Zero()),
  557. NonVirtualAlignment(CharUnits::One()),
  558. PreferredNVAlignment(CharUnits::One()),
  559. PaddedFieldSize(CharUnits::Zero()), PrimaryBase(nullptr),
  560. PrimaryBaseIsVirtual(false), HasOwnVFPtr(false), HasPackedField(false),
  561. HandledFirstNonOverlappingEmptyField(false),
  562. FirstNearlyEmptyVBase(nullptr) {}
  563. void Layout(const RecordDecl *D);
  564. void Layout(const CXXRecordDecl *D);
  565. void Layout(const ObjCInterfaceDecl *D);
  566. void LayoutFields(const RecordDecl *D);
  567. void LayoutField(const FieldDecl *D, bool InsertExtraPadding);
  568. void LayoutWideBitField(uint64_t FieldSize, uint64_t StorageUnitSize,
  569. bool FieldPacked, const FieldDecl *D);
  570. void LayoutBitField(const FieldDecl *D);
  571. TargetCXXABI getCXXABI() const {
  572. return Context.getTargetInfo().getCXXABI();
  573. }
  574. /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects.
  575. llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator;
  576. typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *>
  577. BaseSubobjectInfoMapTy;
  578. /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases
  579. /// of the class we're laying out to their base subobject info.
  580. BaseSubobjectInfoMapTy VirtualBaseInfo;
  581. /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the
  582. /// class we're laying out to their base subobject info.
  583. BaseSubobjectInfoMapTy NonVirtualBaseInfo;
  584. /// ComputeBaseSubobjectInfo - Compute the base subobject information for the
  585. /// bases of the given class.
  586. void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD);
  587. /// ComputeBaseSubobjectInfo - Compute the base subobject information for a
  588. /// single class and all of its base classes.
  589. BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
  590. bool IsVirtual,
  591. BaseSubobjectInfo *Derived);
  592. /// DeterminePrimaryBase - Determine the primary base of the given class.
  593. void DeterminePrimaryBase(const CXXRecordDecl *RD);
  594. void SelectPrimaryVBase(const CXXRecordDecl *RD);
  595. void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign);
  596. /// LayoutNonVirtualBases - Determines the primary base class (if any) and
  597. /// lays it out. Will then proceed to lay out all non-virtual base clasess.
  598. void LayoutNonVirtualBases(const CXXRecordDecl *RD);
  599. /// LayoutNonVirtualBase - Lays out a single non-virtual base.
  600. void LayoutNonVirtualBase(const BaseSubobjectInfo *Base);
  601. void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
  602. CharUnits Offset);
  603. /// LayoutVirtualBases - Lays out all the virtual bases.
  604. void LayoutVirtualBases(const CXXRecordDecl *RD,
  605. const CXXRecordDecl *MostDerivedClass);
  606. /// LayoutVirtualBase - Lays out a single virtual base.
  607. void LayoutVirtualBase(const BaseSubobjectInfo *Base);
  608. /// LayoutBase - Will lay out a base and return the offset where it was
  609. /// placed, in chars.
  610. CharUnits LayoutBase(const BaseSubobjectInfo *Base);
  611. /// InitializeLayout - Initialize record layout for the given record decl.
  612. void InitializeLayout(const Decl *D);
  613. /// FinishLayout - Finalize record layout. Adjust record size based on the
  614. /// alignment.
  615. void FinishLayout(const NamedDecl *D);
  616. void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment,
  617. CharUnits PreferredAlignment);
  618. void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment) {
  619. UpdateAlignment(NewAlignment, UnpackedNewAlignment, NewAlignment);
  620. }
  621. void UpdateAlignment(CharUnits NewAlignment) {
  622. UpdateAlignment(NewAlignment, NewAlignment, NewAlignment);
  623. }
  624. /// Retrieve the externally-supplied field offset for the given
  625. /// field.
  626. ///
  627. /// \param Field The field whose offset is being queried.
  628. /// \param ComputedOffset The offset that we've computed for this field.
  629. uint64_t updateExternalFieldOffset(const FieldDecl *Field,
  630. uint64_t ComputedOffset);
  631. void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset,
  632. uint64_t UnpackedOffset, unsigned UnpackedAlign,
  633. bool isPacked, const FieldDecl *D);
  634. DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
  635. CharUnits getSize() const {
  636. assert(Size % Context.getCharWidth() == 0);
  637. return Context.toCharUnitsFromBits(Size);
  638. }
  639. uint64_t getSizeInBits() const { return Size; }
  640. void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); }
  641. void setSize(uint64_t NewSize) { Size = NewSize; }
  642. CharUnits getAligment() const { return Alignment; }
  643. CharUnits getDataSize() const {
  644. assert(DataSize % Context.getCharWidth() == 0);
  645. return Context.toCharUnitsFromBits(DataSize);
  646. }
  647. uint64_t getDataSizeInBits() const { return DataSize; }
  648. void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); }
  649. void setDataSize(uint64_t NewSize) { DataSize = NewSize; }
  650. ItaniumRecordLayoutBuilder(const ItaniumRecordLayoutBuilder &) = delete;
  651. void operator=(const ItaniumRecordLayoutBuilder &) = delete;
  652. };
  653. } // end anonymous namespace
  654. void ItaniumRecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) {
  655. for (const auto &I : RD->bases()) {
  656. assert(!I.getType()->isDependentType() &&
  657. "Cannot layout class with dependent bases.");
  658. const CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
  659. // Check if this is a nearly empty virtual base.
  660. if (I.isVirtual() && Context.isNearlyEmpty(Base)) {
  661. // If it's not an indirect primary base, then we've found our primary
  662. // base.
  663. if (!IndirectPrimaryBases.count(Base)) {
  664. PrimaryBase = Base;
  665. PrimaryBaseIsVirtual = true;
  666. return;
  667. }
  668. // Is this the first nearly empty virtual base?
  669. if (!FirstNearlyEmptyVBase)
  670. FirstNearlyEmptyVBase = Base;
  671. }
  672. SelectPrimaryVBase(Base);
  673. if (PrimaryBase)
  674. return;
  675. }
  676. }
  677. /// DeterminePrimaryBase - Determine the primary base of the given class.
  678. void ItaniumRecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) {
  679. // If the class isn't dynamic, it won't have a primary base.
  680. if (!RD->isDynamicClass())
  681. return;
  682. // Compute all the primary virtual bases for all of our direct and
  683. // indirect bases, and record all their primary virtual base classes.
  684. RD->getIndirectPrimaryBases(IndirectPrimaryBases);
  685. // If the record has a dynamic base class, attempt to choose a primary base
  686. // class. It is the first (in direct base class order) non-virtual dynamic
  687. // base class, if one exists.
  688. for (const auto &I : RD->bases()) {
  689. // Ignore virtual bases.
  690. if (I.isVirtual())
  691. continue;
  692. const CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
  693. if (Base->isDynamicClass()) {
  694. // We found it.
  695. PrimaryBase = Base;
  696. PrimaryBaseIsVirtual = false;
  697. return;
  698. }
  699. }
  700. // Under the Itanium ABI, if there is no non-virtual primary base class,
  701. // try to compute the primary virtual base. The primary virtual base is
  702. // the first nearly empty virtual base that is not an indirect primary
  703. // virtual base class, if one exists.
  704. if (RD->getNumVBases() != 0) {
  705. SelectPrimaryVBase(RD);
  706. if (PrimaryBase)
  707. return;
  708. }
  709. // Otherwise, it is the first indirect primary base class, if one exists.
  710. if (FirstNearlyEmptyVBase) {
  711. PrimaryBase = FirstNearlyEmptyVBase;
  712. PrimaryBaseIsVirtual = true;
  713. return;
  714. }
  715. assert(!PrimaryBase && "Should not get here with a primary base!");
  716. }
  717. BaseSubobjectInfo *ItaniumRecordLayoutBuilder::ComputeBaseSubobjectInfo(
  718. const CXXRecordDecl *RD, bool IsVirtual, BaseSubobjectInfo *Derived) {
  719. BaseSubobjectInfo *Info;
  720. if (IsVirtual) {
  721. // Check if we already have info about this virtual base.
  722. BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD];
  723. if (InfoSlot) {
  724. assert(InfoSlot->Class == RD && "Wrong class for virtual base info!");
  725. return InfoSlot;
  726. }
  727. // We don't, create it.
  728. InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
  729. Info = InfoSlot;
  730. } else {
  731. Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
  732. }
  733. Info->Class = RD;
  734. Info->IsVirtual = IsVirtual;
  735. Info->Derived = nullptr;
  736. Info->PrimaryVirtualBaseInfo = nullptr;
  737. const CXXRecordDecl *PrimaryVirtualBase = nullptr;
  738. BaseSubobjectInfo *PrimaryVirtualBaseInfo = nullptr;
  739. // Check if this base has a primary virtual base.
  740. if (RD->getNumVBases()) {
  741. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  742. if (Layout.isPrimaryBaseVirtual()) {
  743. // This base does have a primary virtual base.
  744. PrimaryVirtualBase = Layout.getPrimaryBase();
  745. assert(PrimaryVirtualBase && "Didn't have a primary virtual base!");
  746. // Now check if we have base subobject info about this primary base.
  747. PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
  748. if (PrimaryVirtualBaseInfo) {
  749. if (PrimaryVirtualBaseInfo->Derived) {
  750. // We did have info about this primary base, and it turns out that it
  751. // has already been claimed as a primary virtual base for another
  752. // base.
  753. PrimaryVirtualBase = nullptr;
  754. } else {
  755. // We can claim this base as our primary base.
  756. Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
  757. PrimaryVirtualBaseInfo->Derived = Info;
  758. }
  759. }
  760. }
  761. }
  762. // Now go through all direct bases.
  763. for (const auto &I : RD->bases()) {
  764. bool IsVirtual = I.isVirtual();
  765. const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
  766. Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info));
  767. }
  768. if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) {
  769. // Traversing the bases must have created the base info for our primary
  770. // virtual base.
  771. PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
  772. assert(PrimaryVirtualBaseInfo &&
  773. "Did not create a primary virtual base!");
  774. // Claim the primary virtual base as our primary virtual base.
  775. Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
  776. PrimaryVirtualBaseInfo->Derived = Info;
  777. }
  778. return Info;
  779. }
  780. void ItaniumRecordLayoutBuilder::ComputeBaseSubobjectInfo(
  781. const CXXRecordDecl *RD) {
  782. for (const auto &I : RD->bases()) {
  783. bool IsVirtual = I.isVirtual();
  784. const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
  785. // Compute the base subobject info for this base.
  786. BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual,
  787. nullptr);
  788. if (IsVirtual) {
  789. // ComputeBaseInfo has already added this base for us.
  790. assert(VirtualBaseInfo.count(BaseDecl) &&
  791. "Did not add virtual base!");
  792. } else {
  793. // Add the base info to the map of non-virtual bases.
  794. assert(!NonVirtualBaseInfo.count(BaseDecl) &&
  795. "Non-virtual base already exists!");
  796. NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info));
  797. }
  798. }
  799. }
  800. void ItaniumRecordLayoutBuilder::EnsureVTablePointerAlignment(
  801. CharUnits UnpackedBaseAlign) {
  802. CharUnits BaseAlign = Packed ? CharUnits::One() : UnpackedBaseAlign;
  803. // The maximum field alignment overrides base align.
  804. if (!MaxFieldAlignment.isZero()) {
  805. BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
  806. UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
  807. }
  808. // Round up the current record size to pointer alignment.
  809. setSize(getSize().alignTo(BaseAlign));
  810. // Update the alignment.
  811. UpdateAlignment(BaseAlign, UnpackedBaseAlign, BaseAlign);
  812. }
  813. void ItaniumRecordLayoutBuilder::LayoutNonVirtualBases(
  814. const CXXRecordDecl *RD) {
  815. // Then, determine the primary base class.
  816. DeterminePrimaryBase(RD);
  817. // Compute base subobject info.
  818. ComputeBaseSubobjectInfo(RD);
  819. // If we have a primary base class, lay it out.
  820. if (PrimaryBase) {
  821. if (PrimaryBaseIsVirtual) {
  822. // If the primary virtual base was a primary virtual base of some other
  823. // base class we'll have to steal it.
  824. BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase);
  825. PrimaryBaseInfo->Derived = nullptr;
  826. // We have a virtual primary base, insert it as an indirect primary base.
  827. IndirectPrimaryBases.insert(PrimaryBase);
  828. assert(!VisitedVirtualBases.count(PrimaryBase) &&
  829. "vbase already visited!");
  830. VisitedVirtualBases.insert(PrimaryBase);
  831. LayoutVirtualBase(PrimaryBaseInfo);
  832. } else {
  833. BaseSubobjectInfo *PrimaryBaseInfo =
  834. NonVirtualBaseInfo.lookup(PrimaryBase);
  835. assert(PrimaryBaseInfo &&
  836. "Did not find base info for non-virtual primary base!");
  837. LayoutNonVirtualBase(PrimaryBaseInfo);
  838. }
  839. // If this class needs a vtable/vf-table and didn't get one from a
  840. // primary base, add it in now.
  841. } else if (RD->isDynamicClass()) {
  842. assert(DataSize == 0 && "Vtable pointer must be at offset zero!");
  843. CharUnits PtrWidth = Context.toCharUnitsFromBits(
  844. Context.getTargetInfo().getPointerWidth(LangAS::Default));
  845. CharUnits PtrAlign = Context.toCharUnitsFromBits(
  846. Context.getTargetInfo().getPointerAlign(LangAS::Default));
  847. EnsureVTablePointerAlignment(PtrAlign);
  848. HasOwnVFPtr = true;
  849. assert(!IsUnion && "Unions cannot be dynamic classes.");
  850. HandledFirstNonOverlappingEmptyField = true;
  851. setSize(getSize() + PtrWidth);
  852. setDataSize(getSize());
  853. }
  854. // Now lay out the non-virtual bases.
  855. for (const auto &I : RD->bases()) {
  856. // Ignore virtual bases.
  857. if (I.isVirtual())
  858. continue;
  859. const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
  860. // Skip the primary base, because we've already laid it out. The
  861. // !PrimaryBaseIsVirtual check is required because we might have a
  862. // non-virtual base of the same type as a primary virtual base.
  863. if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual)
  864. continue;
  865. // Lay out the base.
  866. BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl);
  867. assert(BaseInfo && "Did not find base info for non-virtual base!");
  868. LayoutNonVirtualBase(BaseInfo);
  869. }
  870. }
  871. void ItaniumRecordLayoutBuilder::LayoutNonVirtualBase(
  872. const BaseSubobjectInfo *Base) {
  873. // Layout the base.
  874. CharUnits Offset = LayoutBase(Base);
  875. // Add its base class offset.
  876. assert(!Bases.count(Base->Class) && "base offset already exists!");
  877. Bases.insert(std::make_pair(Base->Class, Offset));
  878. AddPrimaryVirtualBaseOffsets(Base, Offset);
  879. }
  880. void ItaniumRecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(
  881. const BaseSubobjectInfo *Info, CharUnits Offset) {
  882. // This base isn't interesting, it has no virtual bases.
  883. if (!Info->Class->getNumVBases())
  884. return;
  885. // First, check if we have a virtual primary base to add offsets for.
  886. if (Info->PrimaryVirtualBaseInfo) {
  887. assert(Info->PrimaryVirtualBaseInfo->IsVirtual &&
  888. "Primary virtual base is not virtual!");
  889. if (Info->PrimaryVirtualBaseInfo->Derived == Info) {
  890. // Add the offset.
  891. assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) &&
  892. "primary vbase offset already exists!");
  893. VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class,
  894. ASTRecordLayout::VBaseInfo(Offset, false)));
  895. // Traverse the primary virtual base.
  896. AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset);
  897. }
  898. }
  899. // Now go through all direct non-virtual bases.
  900. const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
  901. for (const BaseSubobjectInfo *Base : Info->Bases) {
  902. if (Base->IsVirtual)
  903. continue;
  904. CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
  905. AddPrimaryVirtualBaseOffsets(Base, BaseOffset);
  906. }
  907. }
  908. void ItaniumRecordLayoutBuilder::LayoutVirtualBases(
  909. const CXXRecordDecl *RD, const CXXRecordDecl *MostDerivedClass) {
  910. const CXXRecordDecl *PrimaryBase;
  911. bool PrimaryBaseIsVirtual;
  912. if (MostDerivedClass == RD) {
  913. PrimaryBase = this->PrimaryBase;
  914. PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual;
  915. } else {
  916. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  917. PrimaryBase = Layout.getPrimaryBase();
  918. PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
  919. }
  920. for (const CXXBaseSpecifier &Base : RD->bases()) {
  921. assert(!Base.getType()->isDependentType() &&
  922. "Cannot layout class with dependent bases.");
  923. const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
  924. if (Base.isVirtual()) {
  925. if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) {
  926. bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl);
  927. // Only lay out the virtual base if it's not an indirect primary base.
  928. if (!IndirectPrimaryBase) {
  929. // Only visit virtual bases once.
  930. if (!VisitedVirtualBases.insert(BaseDecl).second)
  931. continue;
  932. const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
  933. assert(BaseInfo && "Did not find virtual base info!");
  934. LayoutVirtualBase(BaseInfo);
  935. }
  936. }
  937. }
  938. if (!BaseDecl->getNumVBases()) {
  939. // This base isn't interesting since it doesn't have any virtual bases.
  940. continue;
  941. }
  942. LayoutVirtualBases(BaseDecl, MostDerivedClass);
  943. }
  944. }
  945. void ItaniumRecordLayoutBuilder::LayoutVirtualBase(
  946. const BaseSubobjectInfo *Base) {
  947. assert(!Base->Derived && "Trying to lay out a primary virtual base!");
  948. // Layout the base.
  949. CharUnits Offset = LayoutBase(Base);
  950. // Add its base class offset.
  951. assert(!VBases.count(Base->Class) && "vbase offset already exists!");
  952. VBases.insert(std::make_pair(Base->Class,
  953. ASTRecordLayout::VBaseInfo(Offset, false)));
  954. AddPrimaryVirtualBaseOffsets(Base, Offset);
  955. }
  956. CharUnits
  957. ItaniumRecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) {
  958. assert(!IsUnion && "Unions cannot have base classes.");
  959. const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class);
  960. CharUnits Offset;
  961. // Query the external layout to see if it provides an offset.
  962. bool HasExternalLayout = false;
  963. if (UseExternalLayout) {
  964. if (Base->IsVirtual)
  965. HasExternalLayout = External.getExternalVBaseOffset(Base->Class, Offset);
  966. else
  967. HasExternalLayout = External.getExternalNVBaseOffset(Base->Class, Offset);
  968. }
  969. auto getBaseOrPreferredBaseAlignFromUnpacked = [&](CharUnits UnpackedAlign) {
  970. // Clang <= 6 incorrectly applied the 'packed' attribute to base classes.
  971. // Per GCC's documentation, it only applies to non-static data members.
  972. return (Packed && ((Context.getLangOpts().getClangABICompat() <=
  973. LangOptions::ClangABI::Ver6) ||
  974. Context.getTargetInfo().getTriple().isPS() ||
  975. Context.getTargetInfo().getTriple().isOSAIX()))
  976. ? CharUnits::One()
  977. : UnpackedAlign;
  978. };
  979. CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlignment();
  980. CharUnits UnpackedPreferredBaseAlign = Layout.getPreferredNVAlignment();
  981. CharUnits BaseAlign =
  982. getBaseOrPreferredBaseAlignFromUnpacked(UnpackedBaseAlign);
  983. CharUnits PreferredBaseAlign =
  984. getBaseOrPreferredBaseAlignFromUnpacked(UnpackedPreferredBaseAlign);
  985. const bool DefaultsToAIXPowerAlignment =
  986. Context.getTargetInfo().defaultsToAIXPowerAlignment();
  987. if (DefaultsToAIXPowerAlignment) {
  988. // AIX `power` alignment does not apply the preferred alignment for
  989. // non-union classes if the source of the alignment (the current base in
  990. // this context) follows introduction of the first subobject with
  991. // exclusively allocated space or zero-extent array.
  992. if (!Base->Class->isEmpty() && !HandledFirstNonOverlappingEmptyField) {
  993. // By handling a base class that is not empty, we're handling the
  994. // "first (inherited) member".
  995. HandledFirstNonOverlappingEmptyField = true;
  996. } else if (!IsNaturalAlign) {
  997. UnpackedPreferredBaseAlign = UnpackedBaseAlign;
  998. PreferredBaseAlign = BaseAlign;
  999. }
  1000. }
  1001. CharUnits UnpackedAlignTo = !DefaultsToAIXPowerAlignment
  1002. ? UnpackedBaseAlign
  1003. : UnpackedPreferredBaseAlign;
  1004. // If we have an empty base class, try to place it at offset 0.
  1005. if (Base->Class->isEmpty() &&
  1006. (!HasExternalLayout || Offset == CharUnits::Zero()) &&
  1007. EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) {
  1008. setSize(std::max(getSize(), Layout.getSize()));
  1009. // On PS4/PS5, don't update the alignment, to preserve compatibility.
  1010. if (!Context.getTargetInfo().getTriple().isPS())
  1011. UpdateAlignment(BaseAlign, UnpackedAlignTo, PreferredBaseAlign);
  1012. return CharUnits::Zero();
  1013. }
  1014. // The maximum field alignment overrides the base align/(AIX-only) preferred
  1015. // base align.
  1016. if (!MaxFieldAlignment.isZero()) {
  1017. BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
  1018. PreferredBaseAlign = std::min(PreferredBaseAlign, MaxFieldAlignment);
  1019. UnpackedAlignTo = std::min(UnpackedAlignTo, MaxFieldAlignment);
  1020. }
  1021. CharUnits AlignTo =
  1022. !DefaultsToAIXPowerAlignment ? BaseAlign : PreferredBaseAlign;
  1023. if (!HasExternalLayout) {
  1024. // Round up the current record size to the base's alignment boundary.
  1025. Offset = getDataSize().alignTo(AlignTo);
  1026. // Try to place the base.
  1027. while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset))
  1028. Offset += AlignTo;
  1029. } else {
  1030. bool Allowed = EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset);
  1031. (void)Allowed;
  1032. assert(Allowed && "Base subobject externally placed at overlapping offset");
  1033. if (InferAlignment && Offset < getDataSize().alignTo(AlignTo)) {
  1034. // The externally-supplied base offset is before the base offset we
  1035. // computed. Assume that the structure is packed.
  1036. Alignment = CharUnits::One();
  1037. InferAlignment = false;
  1038. }
  1039. }
  1040. if (!Base->Class->isEmpty()) {
  1041. // Update the data size.
  1042. setDataSize(Offset + Layout.getNonVirtualSize());
  1043. setSize(std::max(getSize(), getDataSize()));
  1044. } else
  1045. setSize(std::max(getSize(), Offset + Layout.getSize()));
  1046. // Remember max struct/class alignment.
  1047. UpdateAlignment(BaseAlign, UnpackedAlignTo, PreferredBaseAlign);
  1048. return Offset;
  1049. }
  1050. void ItaniumRecordLayoutBuilder::InitializeLayout(const Decl *D) {
  1051. if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
  1052. IsUnion = RD->isUnion();
  1053. IsMsStruct = RD->isMsStruct(Context);
  1054. }
  1055. Packed = D->hasAttr<PackedAttr>();
  1056. // Honor the default struct packing maximum alignment flag.
  1057. if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) {
  1058. MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
  1059. }
  1060. // mac68k alignment supersedes maximum field alignment and attribute aligned,
  1061. // and forces all structures to have 2-byte alignment. The IBM docs on it
  1062. // allude to additional (more complicated) semantics, especially with regard
  1063. // to bit-fields, but gcc appears not to follow that.
  1064. if (D->hasAttr<AlignMac68kAttr>()) {
  1065. assert(
  1066. !D->hasAttr<AlignNaturalAttr>() &&
  1067. "Having both mac68k and natural alignment on a decl is not allowed.");
  1068. IsMac68kAlign = true;
  1069. MaxFieldAlignment = CharUnits::fromQuantity(2);
  1070. Alignment = CharUnits::fromQuantity(2);
  1071. PreferredAlignment = CharUnits::fromQuantity(2);
  1072. } else {
  1073. if (D->hasAttr<AlignNaturalAttr>())
  1074. IsNaturalAlign = true;
  1075. if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>())
  1076. MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
  1077. if (unsigned MaxAlign = D->getMaxAlignment())
  1078. UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign));
  1079. }
  1080. HandledFirstNonOverlappingEmptyField =
  1081. !Context.getTargetInfo().defaultsToAIXPowerAlignment() || IsNaturalAlign;
  1082. // If there is an external AST source, ask it for the various offsets.
  1083. if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
  1084. if (ExternalASTSource *Source = Context.getExternalSource()) {
  1085. UseExternalLayout = Source->layoutRecordType(
  1086. RD, External.Size, External.Align, External.FieldOffsets,
  1087. External.BaseOffsets, External.VirtualBaseOffsets);
  1088. // Update based on external alignment.
  1089. if (UseExternalLayout) {
  1090. if (External.Align > 0) {
  1091. Alignment = Context.toCharUnitsFromBits(External.Align);
  1092. PreferredAlignment = Context.toCharUnitsFromBits(External.Align);
  1093. } else {
  1094. // The external source didn't have alignment information; infer it.
  1095. InferAlignment = true;
  1096. }
  1097. }
  1098. }
  1099. }
  1100. void ItaniumRecordLayoutBuilder::Layout(const RecordDecl *D) {
  1101. InitializeLayout(D);
  1102. LayoutFields(D);
  1103. // Finally, round the size of the total struct up to the alignment of the
  1104. // struct itself.
  1105. FinishLayout(D);
  1106. }
  1107. void ItaniumRecordLayoutBuilder::Layout(const CXXRecordDecl *RD) {
  1108. InitializeLayout(RD);
  1109. // Lay out the vtable and the non-virtual bases.
  1110. LayoutNonVirtualBases(RD);
  1111. LayoutFields(RD);
  1112. NonVirtualSize = Context.toCharUnitsFromBits(
  1113. llvm::alignTo(getSizeInBits(), Context.getTargetInfo().getCharAlign()));
  1114. NonVirtualAlignment = Alignment;
  1115. PreferredNVAlignment = PreferredAlignment;
  1116. // Lay out the virtual bases and add the primary virtual base offsets.
  1117. LayoutVirtualBases(RD, RD);
  1118. // Finally, round the size of the total struct up to the alignment
  1119. // of the struct itself.
  1120. FinishLayout(RD);
  1121. #ifndef NDEBUG
  1122. // Check that we have base offsets for all bases.
  1123. for (const CXXBaseSpecifier &Base : RD->bases()) {
  1124. if (Base.isVirtual())
  1125. continue;
  1126. const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
  1127. assert(Bases.count(BaseDecl) && "Did not find base offset!");
  1128. }
  1129. // And all virtual bases.
  1130. for (const CXXBaseSpecifier &Base : RD->vbases()) {
  1131. const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
  1132. assert(VBases.count(BaseDecl) && "Did not find base offset!");
  1133. }
  1134. #endif
  1135. }
  1136. void ItaniumRecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) {
  1137. if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
  1138. const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD);
  1139. UpdateAlignment(SL.getAlignment());
  1140. // We start laying out ivars not at the end of the superclass
  1141. // structure, but at the next byte following the last field.
  1142. setDataSize(SL.getDataSize());
  1143. setSize(getDataSize());
  1144. }
  1145. InitializeLayout(D);
  1146. // Layout each ivar sequentially.
  1147. for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD;
  1148. IVD = IVD->getNextIvar())
  1149. LayoutField(IVD, false);
  1150. // Finally, round the size of the total struct up to the alignment of the
  1151. // struct itself.
  1152. FinishLayout(D);
  1153. }
  1154. void ItaniumRecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
  1155. // Layout each field, for now, just sequentially, respecting alignment. In
  1156. // the future, this will need to be tweakable by targets.
  1157. bool InsertExtraPadding = D->mayInsertExtraPadding(/*EmitRemark=*/true);
  1158. bool HasFlexibleArrayMember = D->hasFlexibleArrayMember();
  1159. for (auto I = D->field_begin(), End = D->field_end(); I != End; ++I) {
  1160. auto Next(I);
  1161. ++Next;
  1162. LayoutField(*I,
  1163. InsertExtraPadding && (Next != End || !HasFlexibleArrayMember));
  1164. }
  1165. }
  1166. // Rounds the specified size to have it a multiple of the char size.
  1167. static uint64_t
  1168. roundUpSizeToCharAlignment(uint64_t Size,
  1169. const ASTContext &Context) {
  1170. uint64_t CharAlignment = Context.getTargetInfo().getCharAlign();
  1171. return llvm::alignTo(Size, CharAlignment);
  1172. }
  1173. void ItaniumRecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize,
  1174. uint64_t StorageUnitSize,
  1175. bool FieldPacked,
  1176. const FieldDecl *D) {
  1177. assert(Context.getLangOpts().CPlusPlus &&
  1178. "Can only have wide bit-fields in C++!");
  1179. // Itanium C++ ABI 2.4:
  1180. // If sizeof(T)*8 < n, let T' be the largest integral POD type with
  1181. // sizeof(T')*8 <= n.
  1182. QualType IntegralPODTypes[] = {
  1183. Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy,
  1184. Context.UnsignedLongTy, Context.UnsignedLongLongTy
  1185. };
  1186. QualType Type;
  1187. for (const QualType &QT : IntegralPODTypes) {
  1188. uint64_t Size = Context.getTypeSize(QT);
  1189. if (Size > FieldSize)
  1190. break;
  1191. Type = QT;
  1192. }
  1193. assert(!Type.isNull() && "Did not find a type!");
  1194. CharUnits TypeAlign = Context.getTypeAlignInChars(Type);
  1195. // We're not going to use any of the unfilled bits in the last byte.
  1196. UnfilledBitsInLastUnit = 0;
  1197. LastBitfieldStorageUnitSize = 0;
  1198. uint64_t FieldOffset;
  1199. uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
  1200. if (IsUnion) {
  1201. uint64_t RoundedFieldSize = roundUpSizeToCharAlignment(FieldSize,
  1202. Context);
  1203. setDataSize(std::max(getDataSizeInBits(), RoundedFieldSize));
  1204. FieldOffset = 0;
  1205. } else {
  1206. // The bitfield is allocated starting at the next offset aligned
  1207. // appropriately for T', with length n bits.
  1208. FieldOffset = llvm::alignTo(getDataSizeInBits(), Context.toBits(TypeAlign));
  1209. uint64_t NewSizeInBits = FieldOffset + FieldSize;
  1210. setDataSize(
  1211. llvm::alignTo(NewSizeInBits, Context.getTargetInfo().getCharAlign()));
  1212. UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
  1213. }
  1214. // Place this field at the current location.
  1215. FieldOffsets.push_back(FieldOffset);
  1216. CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset,
  1217. Context.toBits(TypeAlign), FieldPacked, D);
  1218. // Update the size.
  1219. setSize(std::max(getSizeInBits(), getDataSizeInBits()));
  1220. // Remember max struct/class alignment.
  1221. UpdateAlignment(TypeAlign);
  1222. }
  1223. static bool isAIXLayout(const ASTContext &Context) {
  1224. return Context.getTargetInfo().getTriple().getOS() == llvm::Triple::AIX;
  1225. }
  1226. void ItaniumRecordLayoutBuilder::LayoutBitField(const FieldDecl *D) {
  1227. bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
  1228. uint64_t FieldSize = D->getBitWidthValue(Context);
  1229. TypeInfo FieldInfo = Context.getTypeInfo(D->getType());
  1230. uint64_t StorageUnitSize = FieldInfo.Width;
  1231. unsigned FieldAlign = FieldInfo.Align;
  1232. bool AlignIsRequired = FieldInfo.isAlignRequired();
  1233. // UnfilledBitsInLastUnit is the difference between the end of the
  1234. // last allocated bitfield (i.e. the first bit offset available for
  1235. // bitfields) and the end of the current data size in bits (i.e. the
  1236. // first bit offset available for non-bitfields). The current data
  1237. // size in bits is always a multiple of the char size; additionally,
  1238. // for ms_struct records it's also a multiple of the
  1239. // LastBitfieldStorageUnitSize (if set).
  1240. // The struct-layout algorithm is dictated by the platform ABI,
  1241. // which in principle could use almost any rules it likes. In
  1242. // practice, UNIXy targets tend to inherit the algorithm described
  1243. // in the System V generic ABI. The basic bitfield layout rule in
  1244. // System V is to place bitfields at the next available bit offset
  1245. // where the entire bitfield would fit in an aligned storage unit of
  1246. // the declared type; it's okay if an earlier or later non-bitfield
  1247. // is allocated in the same storage unit. However, some targets
  1248. // (those that !useBitFieldTypeAlignment(), e.g. ARM APCS) don't
  1249. // require this storage unit to be aligned, and therefore always put
  1250. // the bitfield at the next available bit offset.
  1251. // ms_struct basically requests a complete replacement of the
  1252. // platform ABI's struct-layout algorithm, with the high-level goal
  1253. // of duplicating MSVC's layout. For non-bitfields, this follows
  1254. // the standard algorithm. The basic bitfield layout rule is to
  1255. // allocate an entire unit of the bitfield's declared type
  1256. // (e.g. 'unsigned long'), then parcel it up among successive
  1257. // bitfields whose declared types have the same size, making a new
  1258. // unit as soon as the last can no longer store the whole value.
  1259. // Since it completely replaces the platform ABI's algorithm,
  1260. // settings like !useBitFieldTypeAlignment() do not apply.
  1261. // A zero-width bitfield forces the use of a new storage unit for
  1262. // later bitfields. In general, this occurs by rounding up the
  1263. // current size of the struct as if the algorithm were about to
  1264. // place a non-bitfield of the field's formal type. Usually this
  1265. // does not change the alignment of the struct itself, but it does
  1266. // on some targets (those that useZeroLengthBitfieldAlignment(),
  1267. // e.g. ARM). In ms_struct layout, zero-width bitfields are
  1268. // ignored unless they follow a non-zero-width bitfield.
  1269. // A field alignment restriction (e.g. from #pragma pack) or
  1270. // specification (e.g. from __attribute__((aligned))) changes the
  1271. // formal alignment of the field. For System V, this alters the
  1272. // required alignment of the notional storage unit that must contain
  1273. // the bitfield. For ms_struct, this only affects the placement of
  1274. // new storage units. In both cases, the effect of #pragma pack is
  1275. // ignored on zero-width bitfields.
  1276. // On System V, a packed field (e.g. from #pragma pack or
  1277. // __attribute__((packed))) always uses the next available bit
  1278. // offset.
  1279. // In an ms_struct struct, the alignment of a fundamental type is
  1280. // always equal to its size. This is necessary in order to mimic
  1281. // the i386 alignment rules on targets which might not fully align
  1282. // all types (e.g. Darwin PPC32, where alignof(long long) == 4).
  1283. // First, some simple bookkeeping to perform for ms_struct structs.
  1284. if (IsMsStruct) {
  1285. // The field alignment for integer types is always the size.
  1286. FieldAlign = StorageUnitSize;
  1287. // If the previous field was not a bitfield, or was a bitfield
  1288. // with a different storage unit size, or if this field doesn't fit into
  1289. // the current storage unit, we're done with that storage unit.
  1290. if (LastBitfieldStorageUnitSize != StorageUnitSize ||
  1291. UnfilledBitsInLastUnit < FieldSize) {
  1292. // Also, ignore zero-length bitfields after non-bitfields.
  1293. if (!LastBitfieldStorageUnitSize && !FieldSize)
  1294. FieldAlign = 1;
  1295. UnfilledBitsInLastUnit = 0;
  1296. LastBitfieldStorageUnitSize = 0;
  1297. }
  1298. }
  1299. if (isAIXLayout(Context)) {
  1300. if (StorageUnitSize < Context.getTypeSize(Context.UnsignedIntTy)) {
  1301. // On AIX, [bool, char, short] bitfields have the same alignment
  1302. // as [unsigned].
  1303. StorageUnitSize = Context.getTypeSize(Context.UnsignedIntTy);
  1304. } else if (StorageUnitSize > Context.getTypeSize(Context.UnsignedIntTy) &&
  1305. Context.getTargetInfo().getTriple().isArch32Bit() &&
  1306. FieldSize <= 32) {
  1307. // Under 32-bit compile mode, the bitcontainer is 32 bits if a single
  1308. // long long bitfield has length no greater than 32 bits.
  1309. StorageUnitSize = 32;
  1310. if (!AlignIsRequired)
  1311. FieldAlign = 32;
  1312. }
  1313. if (FieldAlign < StorageUnitSize) {
  1314. // The bitfield alignment should always be greater than or equal to
  1315. // bitcontainer size.
  1316. FieldAlign = StorageUnitSize;
  1317. }
  1318. }
  1319. // If the field is wider than its declared type, it follows
  1320. // different rules in all cases, except on AIX.
  1321. // On AIX, wide bitfield follows the same rules as normal bitfield.
  1322. if (FieldSize > StorageUnitSize && !isAIXLayout(Context)) {
  1323. LayoutWideBitField(FieldSize, StorageUnitSize, FieldPacked, D);
  1324. return;
  1325. }
  1326. // Compute the next available bit offset.
  1327. uint64_t FieldOffset =
  1328. IsUnion ? 0 : (getDataSizeInBits() - UnfilledBitsInLastUnit);
  1329. // Handle targets that don't honor bitfield type alignment.
  1330. if (!IsMsStruct && !Context.getTargetInfo().useBitFieldTypeAlignment()) {
  1331. // Some such targets do honor it on zero-width bitfields.
  1332. if (FieldSize == 0 &&
  1333. Context.getTargetInfo().useZeroLengthBitfieldAlignment()) {
  1334. // Some targets don't honor leading zero-width bitfield.
  1335. if (!IsUnion && FieldOffset == 0 &&
  1336. !Context.getTargetInfo().useLeadingZeroLengthBitfield())
  1337. FieldAlign = 1;
  1338. else {
  1339. // The alignment to round up to is the max of the field's natural
  1340. // alignment and a target-specific fixed value (sometimes zero).
  1341. unsigned ZeroLengthBitfieldBoundary =
  1342. Context.getTargetInfo().getZeroLengthBitfieldBoundary();
  1343. FieldAlign = std::max(FieldAlign, ZeroLengthBitfieldBoundary);
  1344. }
  1345. // If that doesn't apply, just ignore the field alignment.
  1346. } else {
  1347. FieldAlign = 1;
  1348. }
  1349. }
  1350. // Remember the alignment we would have used if the field were not packed.
  1351. unsigned UnpackedFieldAlign = FieldAlign;
  1352. // Ignore the field alignment if the field is packed unless it has zero-size.
  1353. if (!IsMsStruct && FieldPacked && FieldSize != 0)
  1354. FieldAlign = 1;
  1355. // But, if there's an 'aligned' attribute on the field, honor that.
  1356. unsigned ExplicitFieldAlign = D->getMaxAlignment();
  1357. if (ExplicitFieldAlign) {
  1358. FieldAlign = std::max(FieldAlign, ExplicitFieldAlign);
  1359. UnpackedFieldAlign = std::max(UnpackedFieldAlign, ExplicitFieldAlign);
  1360. }
  1361. // But, if there's a #pragma pack in play, that takes precedent over
  1362. // even the 'aligned' attribute, for non-zero-width bitfields.
  1363. unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment);
  1364. if (!MaxFieldAlignment.isZero() && FieldSize) {
  1365. UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
  1366. if (FieldPacked)
  1367. FieldAlign = UnpackedFieldAlign;
  1368. else
  1369. FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
  1370. }
  1371. // But, ms_struct just ignores all of that in unions, even explicit
  1372. // alignment attributes.
  1373. if (IsMsStruct && IsUnion) {
  1374. FieldAlign = UnpackedFieldAlign = 1;
  1375. }
  1376. // For purposes of diagnostics, we're going to simultaneously
  1377. // compute the field offsets that we would have used if we weren't
  1378. // adding any alignment padding or if the field weren't packed.
  1379. uint64_t UnpaddedFieldOffset = FieldOffset;
  1380. uint64_t UnpackedFieldOffset = FieldOffset;
  1381. // Check if we need to add padding to fit the bitfield within an
  1382. // allocation unit with the right size and alignment. The rules are
  1383. // somewhat different here for ms_struct structs.
  1384. if (IsMsStruct) {
  1385. // If it's not a zero-width bitfield, and we can fit the bitfield
  1386. // into the active storage unit (and we haven't already decided to
  1387. // start a new storage unit), just do so, regardless of any other
  1388. // other consideration. Otherwise, round up to the right alignment.
  1389. if (FieldSize == 0 || FieldSize > UnfilledBitsInLastUnit) {
  1390. FieldOffset = llvm::alignTo(FieldOffset, FieldAlign);
  1391. UnpackedFieldOffset =
  1392. llvm::alignTo(UnpackedFieldOffset, UnpackedFieldAlign);
  1393. UnfilledBitsInLastUnit = 0;
  1394. }
  1395. } else {
  1396. // #pragma pack, with any value, suppresses the insertion of padding.
  1397. bool AllowPadding = MaxFieldAlignment.isZero();
  1398. // Compute the real offset.
  1399. if (FieldSize == 0 ||
  1400. (AllowPadding &&
  1401. (FieldOffset & (FieldAlign - 1)) + FieldSize > StorageUnitSize)) {
  1402. FieldOffset = llvm::alignTo(FieldOffset, FieldAlign);
  1403. } else if (ExplicitFieldAlign &&
  1404. (MaxFieldAlignmentInBits == 0 ||
  1405. ExplicitFieldAlign <= MaxFieldAlignmentInBits) &&
  1406. Context.getTargetInfo().useExplicitBitFieldAlignment()) {
  1407. // TODO: figure it out what needs to be done on targets that don't honor
  1408. // bit-field type alignment like ARM APCS ABI.
  1409. FieldOffset = llvm::alignTo(FieldOffset, ExplicitFieldAlign);
  1410. }
  1411. // Repeat the computation for diagnostic purposes.
  1412. if (FieldSize == 0 ||
  1413. (AllowPadding &&
  1414. (UnpackedFieldOffset & (UnpackedFieldAlign - 1)) + FieldSize >
  1415. StorageUnitSize))
  1416. UnpackedFieldOffset =
  1417. llvm::alignTo(UnpackedFieldOffset, UnpackedFieldAlign);
  1418. else if (ExplicitFieldAlign &&
  1419. (MaxFieldAlignmentInBits == 0 ||
  1420. ExplicitFieldAlign <= MaxFieldAlignmentInBits) &&
  1421. Context.getTargetInfo().useExplicitBitFieldAlignment())
  1422. UnpackedFieldOffset =
  1423. llvm::alignTo(UnpackedFieldOffset, ExplicitFieldAlign);
  1424. }
  1425. // If we're using external layout, give the external layout a chance
  1426. // to override this information.
  1427. if (UseExternalLayout)
  1428. FieldOffset = updateExternalFieldOffset(D, FieldOffset);
  1429. // Okay, place the bitfield at the calculated offset.
  1430. FieldOffsets.push_back(FieldOffset);
  1431. // Bookkeeping:
  1432. // Anonymous members don't affect the overall record alignment,
  1433. // except on targets where they do.
  1434. if (!IsMsStruct &&
  1435. !Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
  1436. !D->getIdentifier())
  1437. FieldAlign = UnpackedFieldAlign = 1;
  1438. // On AIX, zero-width bitfields pad out to the natural alignment boundary,
  1439. // but do not increase the alignment greater than the MaxFieldAlignment, or 1
  1440. // if packed.
  1441. if (isAIXLayout(Context) && !FieldSize) {
  1442. if (FieldPacked)
  1443. FieldAlign = 1;
  1444. if (!MaxFieldAlignment.isZero()) {
  1445. UnpackedFieldAlign =
  1446. std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
  1447. FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
  1448. }
  1449. }
  1450. // Diagnose differences in layout due to padding or packing.
  1451. if (!UseExternalLayout)
  1452. CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
  1453. UnpackedFieldAlign, FieldPacked, D);
  1454. // Update DataSize to include the last byte containing (part of) the bitfield.
  1455. // For unions, this is just a max operation, as usual.
  1456. if (IsUnion) {
  1457. // For ms_struct, allocate the entire storage unit --- unless this
  1458. // is a zero-width bitfield, in which case just use a size of 1.
  1459. uint64_t RoundedFieldSize;
  1460. if (IsMsStruct) {
  1461. RoundedFieldSize = (FieldSize ? StorageUnitSize
  1462. : Context.getTargetInfo().getCharWidth());
  1463. // Otherwise, allocate just the number of bytes required to store
  1464. // the bitfield.
  1465. } else {
  1466. RoundedFieldSize = roundUpSizeToCharAlignment(FieldSize, Context);
  1467. }
  1468. setDataSize(std::max(getDataSizeInBits(), RoundedFieldSize));
  1469. // For non-zero-width bitfields in ms_struct structs, allocate a new
  1470. // storage unit if necessary.
  1471. } else if (IsMsStruct && FieldSize) {
  1472. // We should have cleared UnfilledBitsInLastUnit in every case
  1473. // where we changed storage units.
  1474. if (!UnfilledBitsInLastUnit) {
  1475. setDataSize(FieldOffset + StorageUnitSize);
  1476. UnfilledBitsInLastUnit = StorageUnitSize;
  1477. }
  1478. UnfilledBitsInLastUnit -= FieldSize;
  1479. LastBitfieldStorageUnitSize = StorageUnitSize;
  1480. // Otherwise, bump the data size up to include the bitfield,
  1481. // including padding up to char alignment, and then remember how
  1482. // bits we didn't use.
  1483. } else {
  1484. uint64_t NewSizeInBits = FieldOffset + FieldSize;
  1485. uint64_t CharAlignment = Context.getTargetInfo().getCharAlign();
  1486. setDataSize(llvm::alignTo(NewSizeInBits, CharAlignment));
  1487. UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
  1488. // The only time we can get here for an ms_struct is if this is a
  1489. // zero-width bitfield, which doesn't count as anything for the
  1490. // purposes of unfilled bits.
  1491. LastBitfieldStorageUnitSize = 0;
  1492. }
  1493. // Update the size.
  1494. setSize(std::max(getSizeInBits(), getDataSizeInBits()));
  1495. // Remember max struct/class alignment.
  1496. UnadjustedAlignment =
  1497. std::max(UnadjustedAlignment, Context.toCharUnitsFromBits(FieldAlign));
  1498. UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign),
  1499. Context.toCharUnitsFromBits(UnpackedFieldAlign));
  1500. }
  1501. void ItaniumRecordLayoutBuilder::LayoutField(const FieldDecl *D,
  1502. bool InsertExtraPadding) {
  1503. auto *FieldClass = D->getType()->getAsCXXRecordDecl();
  1504. bool PotentiallyOverlapping = D->hasAttr<NoUniqueAddressAttr>() && FieldClass;
  1505. bool IsOverlappingEmptyField =
  1506. PotentiallyOverlapping && FieldClass->isEmpty();
  1507. CharUnits FieldOffset =
  1508. (IsUnion || IsOverlappingEmptyField) ? CharUnits::Zero() : getDataSize();
  1509. const bool DefaultsToAIXPowerAlignment =
  1510. Context.getTargetInfo().defaultsToAIXPowerAlignment();
  1511. bool FoundFirstNonOverlappingEmptyFieldForAIX = false;
  1512. if (DefaultsToAIXPowerAlignment && !HandledFirstNonOverlappingEmptyField) {
  1513. assert(FieldOffset == CharUnits::Zero() &&
  1514. "The first non-overlapping empty field should have been handled.");
  1515. if (!IsOverlappingEmptyField) {
  1516. FoundFirstNonOverlappingEmptyFieldForAIX = true;
  1517. // We're going to handle the "first member" based on
  1518. // `FoundFirstNonOverlappingEmptyFieldForAIX` during the current
  1519. // invocation of this function; record it as handled for future
  1520. // invocations (except for unions, because the current field does not
  1521. // represent all "firsts").
  1522. HandledFirstNonOverlappingEmptyField = !IsUnion;
  1523. }
  1524. }
  1525. if (D->isBitField()) {
  1526. LayoutBitField(D);
  1527. return;
  1528. }
  1529. uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
  1530. // Reset the unfilled bits.
  1531. UnfilledBitsInLastUnit = 0;
  1532. LastBitfieldStorageUnitSize = 0;
  1533. llvm::Triple Target = Context.getTargetInfo().getTriple();
  1534. AlignRequirementKind AlignRequirement = AlignRequirementKind::None;
  1535. CharUnits FieldSize;
  1536. CharUnits FieldAlign;
  1537. // The amount of this class's dsize occupied by the field.
  1538. // This is equal to FieldSize unless we're permitted to pack
  1539. // into the field's tail padding.
  1540. CharUnits EffectiveFieldSize;
  1541. auto setDeclInfo = [&](bool IsIncompleteArrayType) {
  1542. auto TI = Context.getTypeInfoInChars(D->getType());
  1543. FieldAlign = TI.Align;
  1544. // Flexible array members don't have any size, but they have to be
  1545. // aligned appropriately for their element type.
  1546. EffectiveFieldSize = FieldSize =
  1547. IsIncompleteArrayType ? CharUnits::Zero() : TI.Width;
  1548. AlignRequirement = TI.AlignRequirement;
  1549. };
  1550. if (D->getType()->isIncompleteArrayType()) {
  1551. setDeclInfo(true /* IsIncompleteArrayType */);
  1552. } else {
  1553. setDeclInfo(false /* IsIncompleteArrayType */);
  1554. // A potentially-overlapping field occupies its dsize or nvsize, whichever
  1555. // is larger.
  1556. if (PotentiallyOverlapping) {
  1557. const ASTRecordLayout &Layout = Context.getASTRecordLayout(FieldClass);
  1558. EffectiveFieldSize =
  1559. std::max(Layout.getNonVirtualSize(), Layout.getDataSize());
  1560. }
  1561. if (IsMsStruct) {
  1562. // If MS bitfield layout is required, figure out what type is being
  1563. // laid out and align the field to the width of that type.
  1564. // Resolve all typedefs down to their base type and round up the field
  1565. // alignment if necessary.
  1566. QualType T = Context.getBaseElementType(D->getType());
  1567. if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
  1568. CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
  1569. if (!llvm::isPowerOf2_64(TypeSize.getQuantity())) {
  1570. assert(
  1571. !Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment() &&
  1572. "Non PowerOf2 size in MSVC mode");
  1573. // Base types with sizes that aren't a power of two don't work
  1574. // with the layout rules for MS structs. This isn't an issue in
  1575. // MSVC itself since there are no such base data types there.
  1576. // On e.g. x86_32 mingw and linux, long double is 12 bytes though.
  1577. // Any structs involving that data type obviously can't be ABI
  1578. // compatible with MSVC regardless of how it is laid out.
  1579. // Since ms_struct can be mass enabled (via a pragma or via the
  1580. // -mms-bitfields command line parameter), this can trigger for
  1581. // structs that don't actually need MSVC compatibility, so we
  1582. // need to be able to sidestep the ms_struct layout for these types.
  1583. // Since the combination of -mms-bitfields together with structs
  1584. // like max_align_t (which contains a long double) for mingw is
  1585. // quite common (and GCC handles it silently), just handle it
  1586. // silently there. For other targets that have ms_struct enabled
  1587. // (most probably via a pragma or attribute), trigger a diagnostic
  1588. // that defaults to an error.
  1589. if (!Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
  1590. Diag(D->getLocation(), diag::warn_npot_ms_struct);
  1591. }
  1592. if (TypeSize > FieldAlign &&
  1593. llvm::isPowerOf2_64(TypeSize.getQuantity()))
  1594. FieldAlign = TypeSize;
  1595. }
  1596. }
  1597. }
  1598. bool FieldPacked = (Packed && (!FieldClass || FieldClass->isPOD() ||
  1599. FieldClass->hasAttr<PackedAttr>() ||
  1600. Context.getLangOpts().getClangABICompat() <=
  1601. LangOptions::ClangABI::Ver15 ||
  1602. Target.isPS() || Target.isOSDarwin() ||
  1603. Target.isOSAIX())) ||
  1604. D->hasAttr<PackedAttr>();
  1605. // When used as part of a typedef, or together with a 'packed' attribute, the
  1606. // 'aligned' attribute can be used to decrease alignment. In that case, it
  1607. // overrides any computed alignment we have, and there is no need to upgrade
  1608. // the alignment.
  1609. auto alignedAttrCanDecreaseAIXAlignment = [AlignRequirement, FieldPacked] {
  1610. // Enum alignment sources can be safely ignored here, because this only
  1611. // helps decide whether we need the AIX alignment upgrade, which only
  1612. // applies to floating-point types.
  1613. return AlignRequirement == AlignRequirementKind::RequiredByTypedef ||
  1614. (AlignRequirement == AlignRequirementKind::RequiredByRecord &&
  1615. FieldPacked);
  1616. };
  1617. // The AIX `power` alignment rules apply the natural alignment of the
  1618. // "first member" if it is of a floating-point data type (or is an aggregate
  1619. // whose recursively "first" member or element is such a type). The alignment
  1620. // associated with these types for subsequent members use an alignment value
  1621. // where the floating-point data type is considered to have 4-byte alignment.
  1622. //
  1623. // For the purposes of the foregoing: vtable pointers, non-empty base classes,
  1624. // and zero-width bit-fields count as prior members; members of empty class
  1625. // types marked `no_unique_address` are not considered to be prior members.
  1626. CharUnits PreferredAlign = FieldAlign;
  1627. if (DefaultsToAIXPowerAlignment && !alignedAttrCanDecreaseAIXAlignment() &&
  1628. (FoundFirstNonOverlappingEmptyFieldForAIX || IsNaturalAlign)) {
  1629. auto performBuiltinTypeAlignmentUpgrade = [&](const BuiltinType *BTy) {
  1630. if (BTy->getKind() == BuiltinType::Double ||
  1631. BTy->getKind() == BuiltinType::LongDouble) {
  1632. assert(PreferredAlign == CharUnits::fromQuantity(4) &&
  1633. "No need to upgrade the alignment value.");
  1634. PreferredAlign = CharUnits::fromQuantity(8);
  1635. }
  1636. };
  1637. const Type *BaseTy = D->getType()->getBaseElementTypeUnsafe();
  1638. if (const ComplexType *CTy = BaseTy->getAs<ComplexType>()) {
  1639. performBuiltinTypeAlignmentUpgrade(
  1640. CTy->getElementType()->castAs<BuiltinType>());
  1641. } else if (const BuiltinType *BTy = BaseTy->getAs<BuiltinType>()) {
  1642. performBuiltinTypeAlignmentUpgrade(BTy);
  1643. } else if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
  1644. const RecordDecl *RD = RT->getDecl();
  1645. assert(RD && "Expected non-null RecordDecl.");
  1646. const ASTRecordLayout &FieldRecord = Context.getASTRecordLayout(RD);
  1647. PreferredAlign = FieldRecord.getPreferredAlignment();
  1648. }
  1649. }
  1650. // The align if the field is not packed. This is to check if the attribute
  1651. // was unnecessary (-Wpacked).
  1652. CharUnits UnpackedFieldAlign = FieldAlign;
  1653. CharUnits PackedFieldAlign = CharUnits::One();
  1654. CharUnits UnpackedFieldOffset = FieldOffset;
  1655. CharUnits OriginalFieldAlign = UnpackedFieldAlign;
  1656. CharUnits MaxAlignmentInChars =
  1657. Context.toCharUnitsFromBits(D->getMaxAlignment());
  1658. PackedFieldAlign = std::max(PackedFieldAlign, MaxAlignmentInChars);
  1659. PreferredAlign = std::max(PreferredAlign, MaxAlignmentInChars);
  1660. UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars);
  1661. // The maximum field alignment overrides the aligned attribute.
  1662. if (!MaxFieldAlignment.isZero()) {
  1663. PackedFieldAlign = std::min(PackedFieldAlign, MaxFieldAlignment);
  1664. PreferredAlign = std::min(PreferredAlign, MaxFieldAlignment);
  1665. UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment);
  1666. }
  1667. if (!FieldPacked)
  1668. FieldAlign = UnpackedFieldAlign;
  1669. if (DefaultsToAIXPowerAlignment)
  1670. UnpackedFieldAlign = PreferredAlign;
  1671. if (FieldPacked) {
  1672. PreferredAlign = PackedFieldAlign;
  1673. FieldAlign = PackedFieldAlign;
  1674. }
  1675. CharUnits AlignTo =
  1676. !DefaultsToAIXPowerAlignment ? FieldAlign : PreferredAlign;
  1677. // Round up the current record size to the field's alignment boundary.
  1678. FieldOffset = FieldOffset.alignTo(AlignTo);
  1679. UnpackedFieldOffset = UnpackedFieldOffset.alignTo(UnpackedFieldAlign);
  1680. if (UseExternalLayout) {
  1681. FieldOffset = Context.toCharUnitsFromBits(
  1682. updateExternalFieldOffset(D, Context.toBits(FieldOffset)));
  1683. if (!IsUnion && EmptySubobjects) {
  1684. // Record the fact that we're placing a field at this offset.
  1685. bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset);
  1686. (void)Allowed;
  1687. assert(Allowed && "Externally-placed field cannot be placed here");
  1688. }
  1689. } else {
  1690. if (!IsUnion && EmptySubobjects) {
  1691. // Check if we can place the field at this offset.
  1692. while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
  1693. // We couldn't place the field at the offset. Try again at a new offset.
  1694. // We try offset 0 (for an empty field) and then dsize(C) onwards.
  1695. if (FieldOffset == CharUnits::Zero() &&
  1696. getDataSize() != CharUnits::Zero())
  1697. FieldOffset = getDataSize().alignTo(AlignTo);
  1698. else
  1699. FieldOffset += AlignTo;
  1700. }
  1701. }
  1702. }
  1703. // Place this field at the current location.
  1704. FieldOffsets.push_back(Context.toBits(FieldOffset));
  1705. if (!UseExternalLayout)
  1706. CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset,
  1707. Context.toBits(UnpackedFieldOffset),
  1708. Context.toBits(UnpackedFieldAlign), FieldPacked, D);
  1709. if (InsertExtraPadding) {
  1710. CharUnits ASanAlignment = CharUnits::fromQuantity(8);
  1711. CharUnits ExtraSizeForAsan = ASanAlignment;
  1712. if (FieldSize % ASanAlignment)
  1713. ExtraSizeForAsan +=
  1714. ASanAlignment - CharUnits::fromQuantity(FieldSize % ASanAlignment);
  1715. EffectiveFieldSize = FieldSize = FieldSize + ExtraSizeForAsan;
  1716. }
  1717. // Reserve space for this field.
  1718. if (!IsOverlappingEmptyField) {
  1719. uint64_t EffectiveFieldSizeInBits = Context.toBits(EffectiveFieldSize);
  1720. if (IsUnion)
  1721. setDataSize(std::max(getDataSizeInBits(), EffectiveFieldSizeInBits));
  1722. else
  1723. setDataSize(FieldOffset + EffectiveFieldSize);
  1724. PaddedFieldSize = std::max(PaddedFieldSize, FieldOffset + FieldSize);
  1725. setSize(std::max(getSizeInBits(), getDataSizeInBits()));
  1726. } else {
  1727. setSize(std::max(getSizeInBits(),
  1728. (uint64_t)Context.toBits(FieldOffset + FieldSize)));
  1729. }
  1730. // Remember max struct/class ABI-specified alignment.
  1731. UnadjustedAlignment = std::max(UnadjustedAlignment, FieldAlign);
  1732. UpdateAlignment(FieldAlign, UnpackedFieldAlign, PreferredAlign);
  1733. // For checking the alignment of inner fields against
  1734. // the alignment of its parent record.
  1735. if (const RecordDecl *RD = D->getParent()) {
  1736. // Check if packed attribute or pragma pack is present.
  1737. if (RD->hasAttr<PackedAttr>() || !MaxFieldAlignment.isZero())
  1738. if (FieldAlign < OriginalFieldAlign)
  1739. if (D->getType()->isRecordType()) {
  1740. // If the offset is a multiple of the alignment of
  1741. // the type, raise the warning.
  1742. // TODO: Takes no account the alignment of the outer struct
  1743. if (FieldOffset % OriginalFieldAlign != 0)
  1744. Diag(D->getLocation(), diag::warn_unaligned_access)
  1745. << Context.getTypeDeclType(RD) << D->getName() << D->getType();
  1746. }
  1747. }
  1748. if (Packed && !FieldPacked && PackedFieldAlign < FieldAlign)
  1749. Diag(D->getLocation(), diag::warn_unpacked_field) << D;
  1750. }
  1751. void ItaniumRecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
  1752. // In C++, records cannot be of size 0.
  1753. if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) {
  1754. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
  1755. // Compatibility with gcc requires a class (pod or non-pod)
  1756. // which is not empty but of size 0; such as having fields of
  1757. // array of zero-length, remains of Size 0
  1758. if (RD->isEmpty())
  1759. setSize(CharUnits::One());
  1760. }
  1761. else
  1762. setSize(CharUnits::One());
  1763. }
  1764. // If we have any remaining field tail padding, include that in the overall
  1765. // size.
  1766. setSize(std::max(getSizeInBits(), (uint64_t)Context.toBits(PaddedFieldSize)));
  1767. // Finally, round the size of the record up to the alignment of the
  1768. // record itself.
  1769. uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastUnit;
  1770. uint64_t UnpackedSizeInBits =
  1771. llvm::alignTo(getSizeInBits(), Context.toBits(UnpackedAlignment));
  1772. uint64_t RoundedSize = llvm::alignTo(
  1773. getSizeInBits(),
  1774. Context.toBits(!Context.getTargetInfo().defaultsToAIXPowerAlignment()
  1775. ? Alignment
  1776. : PreferredAlignment));
  1777. if (UseExternalLayout) {
  1778. // If we're inferring alignment, and the external size is smaller than
  1779. // our size after we've rounded up to alignment, conservatively set the
  1780. // alignment to 1.
  1781. if (InferAlignment && External.Size < RoundedSize) {
  1782. Alignment = CharUnits::One();
  1783. PreferredAlignment = CharUnits::One();
  1784. InferAlignment = false;
  1785. }
  1786. setSize(External.Size);
  1787. return;
  1788. }
  1789. // Set the size to the final size.
  1790. setSize(RoundedSize);
  1791. unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
  1792. if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
  1793. // Warn if padding was introduced to the struct/class/union.
  1794. if (getSizeInBits() > UnpaddedSize) {
  1795. unsigned PadSize = getSizeInBits() - UnpaddedSize;
  1796. bool InBits = true;
  1797. if (PadSize % CharBitNum == 0) {
  1798. PadSize = PadSize / CharBitNum;
  1799. InBits = false;
  1800. }
  1801. Diag(RD->getLocation(), diag::warn_padded_struct_size)
  1802. << Context.getTypeDeclType(RD)
  1803. << PadSize
  1804. << (InBits ? 1 : 0); // (byte|bit)
  1805. }
  1806. // Warn if we packed it unnecessarily, when the unpacked alignment is not
  1807. // greater than the one after packing, the size in bits doesn't change and
  1808. // the offset of each field is identical.
  1809. if (Packed && UnpackedAlignment <= Alignment &&
  1810. UnpackedSizeInBits == getSizeInBits() && !HasPackedField)
  1811. Diag(D->getLocation(), diag::warn_unnecessary_packed)
  1812. << Context.getTypeDeclType(RD);
  1813. }
  1814. }
  1815. void ItaniumRecordLayoutBuilder::UpdateAlignment(
  1816. CharUnits NewAlignment, CharUnits UnpackedNewAlignment,
  1817. CharUnits PreferredNewAlignment) {
  1818. // The alignment is not modified when using 'mac68k' alignment or when
  1819. // we have an externally-supplied layout that also provides overall alignment.
  1820. if (IsMac68kAlign || (UseExternalLayout && !InferAlignment))
  1821. return;
  1822. if (NewAlignment > Alignment) {
  1823. assert(llvm::isPowerOf2_64(NewAlignment.getQuantity()) &&
  1824. "Alignment not a power of 2");
  1825. Alignment = NewAlignment;
  1826. }
  1827. if (UnpackedNewAlignment > UnpackedAlignment) {
  1828. assert(llvm::isPowerOf2_64(UnpackedNewAlignment.getQuantity()) &&
  1829. "Alignment not a power of 2");
  1830. UnpackedAlignment = UnpackedNewAlignment;
  1831. }
  1832. if (PreferredNewAlignment > PreferredAlignment) {
  1833. assert(llvm::isPowerOf2_64(PreferredNewAlignment.getQuantity()) &&
  1834. "Alignment not a power of 2");
  1835. PreferredAlignment = PreferredNewAlignment;
  1836. }
  1837. }
  1838. uint64_t
  1839. ItaniumRecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field,
  1840. uint64_t ComputedOffset) {
  1841. uint64_t ExternalFieldOffset = External.getExternalFieldOffset(Field);
  1842. if (InferAlignment && ExternalFieldOffset < ComputedOffset) {
  1843. // The externally-supplied field offset is before the field offset we
  1844. // computed. Assume that the structure is packed.
  1845. Alignment = CharUnits::One();
  1846. PreferredAlignment = CharUnits::One();
  1847. InferAlignment = false;
  1848. }
  1849. // Use the externally-supplied field offset.
  1850. return ExternalFieldOffset;
  1851. }
  1852. /// Get diagnostic %select index for tag kind for
  1853. /// field padding diagnostic message.
  1854. /// WARNING: Indexes apply to particular diagnostics only!
  1855. ///
  1856. /// \returns diagnostic %select index.
  1857. static unsigned getPaddingDiagFromTagKind(TagTypeKind Tag) {
  1858. switch (Tag) {
  1859. case TTK_Struct: return 0;
  1860. case TTK_Interface: return 1;
  1861. case TTK_Class: return 2;
  1862. default: llvm_unreachable("Invalid tag kind for field padding diagnostic!");
  1863. }
  1864. }
  1865. void ItaniumRecordLayoutBuilder::CheckFieldPadding(
  1866. uint64_t Offset, uint64_t UnpaddedOffset, uint64_t UnpackedOffset,
  1867. unsigned UnpackedAlign, bool isPacked, const FieldDecl *D) {
  1868. // We let objc ivars without warning, objc interfaces generally are not used
  1869. // for padding tricks.
  1870. if (isa<ObjCIvarDecl>(D))
  1871. return;
  1872. // Don't warn about structs created without a SourceLocation. This can
  1873. // be done by clients of the AST, such as codegen.
  1874. if (D->getLocation().isInvalid())
  1875. return;
  1876. unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
  1877. // Warn if padding was introduced to the struct/class.
  1878. if (!IsUnion && Offset > UnpaddedOffset) {
  1879. unsigned PadSize = Offset - UnpaddedOffset;
  1880. bool InBits = true;
  1881. if (PadSize % CharBitNum == 0) {
  1882. PadSize = PadSize / CharBitNum;
  1883. InBits = false;
  1884. }
  1885. if (D->getIdentifier())
  1886. Diag(D->getLocation(), diag::warn_padded_struct_field)
  1887. << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
  1888. << Context.getTypeDeclType(D->getParent())
  1889. << PadSize
  1890. << (InBits ? 1 : 0) // (byte|bit)
  1891. << D->getIdentifier();
  1892. else
  1893. Diag(D->getLocation(), diag::warn_padded_struct_anon_field)
  1894. << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
  1895. << Context.getTypeDeclType(D->getParent())
  1896. << PadSize
  1897. << (InBits ? 1 : 0); // (byte|bit)
  1898. }
  1899. if (isPacked && Offset != UnpackedOffset) {
  1900. HasPackedField = true;
  1901. }
  1902. }
  1903. static const CXXMethodDecl *computeKeyFunction(ASTContext &Context,
  1904. const CXXRecordDecl *RD) {
  1905. // If a class isn't polymorphic it doesn't have a key function.
  1906. if (!RD->isPolymorphic())
  1907. return nullptr;
  1908. // A class that is not externally visible doesn't have a key function. (Or
  1909. // at least, there's no point to assigning a key function to such a class;
  1910. // this doesn't affect the ABI.)
  1911. if (!RD->isExternallyVisible())
  1912. return nullptr;
  1913. // Template instantiations don't have key functions per Itanium C++ ABI 5.2.6.
  1914. // Same behavior as GCC.
  1915. TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
  1916. if (TSK == TSK_ImplicitInstantiation ||
  1917. TSK == TSK_ExplicitInstantiationDeclaration ||
  1918. TSK == TSK_ExplicitInstantiationDefinition)
  1919. return nullptr;
  1920. bool allowInlineFunctions =
  1921. Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline();
  1922. for (const CXXMethodDecl *MD : RD->methods()) {
  1923. if (!MD->isVirtual())
  1924. continue;
  1925. if (MD->isPure())
  1926. continue;
  1927. // Ignore implicit member functions, they are always marked as inline, but
  1928. // they don't have a body until they're defined.
  1929. if (MD->isImplicit())
  1930. continue;
  1931. if (MD->isInlineSpecified() || MD->isConstexpr())
  1932. continue;
  1933. if (MD->hasInlineBody())
  1934. continue;
  1935. // Ignore inline deleted or defaulted functions.
  1936. if (!MD->isUserProvided())
  1937. continue;
  1938. // In certain ABIs, ignore functions with out-of-line inline definitions.
  1939. if (!allowInlineFunctions) {
  1940. const FunctionDecl *Def;
  1941. if (MD->hasBody(Def) && Def->isInlineSpecified())
  1942. continue;
  1943. }
  1944. if (Context.getLangOpts().CUDA) {
  1945. // While compiler may see key method in this TU, during CUDA
  1946. // compilation we should ignore methods that are not accessible
  1947. // on this side of compilation.
  1948. if (Context.getLangOpts().CUDAIsDevice) {
  1949. // In device mode ignore methods without __device__ attribute.
  1950. if (!MD->hasAttr<CUDADeviceAttr>())
  1951. continue;
  1952. } else {
  1953. // In host mode ignore __device__-only methods.
  1954. if (!MD->hasAttr<CUDAHostAttr>() && MD->hasAttr<CUDADeviceAttr>())
  1955. continue;
  1956. }
  1957. }
  1958. // If the key function is dllimport but the class isn't, then the class has
  1959. // no key function. The DLL that exports the key function won't export the
  1960. // vtable in this case.
  1961. if (MD->hasAttr<DLLImportAttr>() && !RD->hasAttr<DLLImportAttr>() &&
  1962. !Context.getTargetInfo().hasPS4DLLImportExport())
  1963. return nullptr;
  1964. // We found it.
  1965. return MD;
  1966. }
  1967. return nullptr;
  1968. }
  1969. DiagnosticBuilder ItaniumRecordLayoutBuilder::Diag(SourceLocation Loc,
  1970. unsigned DiagID) {
  1971. return Context.getDiagnostics().Report(Loc, DiagID);
  1972. }
  1973. /// Does the target C++ ABI require us to skip over the tail-padding
  1974. /// of the given class (considering it as a base class) when allocating
  1975. /// objects?
  1976. static bool mustSkipTailPadding(TargetCXXABI ABI, const CXXRecordDecl *RD) {
  1977. switch (ABI.getTailPaddingUseRules()) {
  1978. case TargetCXXABI::AlwaysUseTailPadding:
  1979. return false;
  1980. case TargetCXXABI::UseTailPaddingUnlessPOD03:
  1981. // FIXME: To the extent that this is meant to cover the Itanium ABI
  1982. // rules, we should implement the restrictions about over-sized
  1983. // bitfields:
  1984. //
  1985. // http://itanium-cxx-abi.github.io/cxx-abi/abi.html#POD :
  1986. // In general, a type is considered a POD for the purposes of
  1987. // layout if it is a POD type (in the sense of ISO C++
  1988. // [basic.types]). However, a POD-struct or POD-union (in the
  1989. // sense of ISO C++ [class]) with a bitfield member whose
  1990. // declared width is wider than the declared type of the
  1991. // bitfield is not a POD for the purpose of layout. Similarly,
  1992. // an array type is not a POD for the purpose of layout if the
  1993. // element type of the array is not a POD for the purpose of
  1994. // layout.
  1995. //
  1996. // Where references to the ISO C++ are made in this paragraph,
  1997. // the Technical Corrigendum 1 version of the standard is
  1998. // intended.
  1999. return RD->isPOD();
  2000. case TargetCXXABI::UseTailPaddingUnlessPOD11:
  2001. // This is equivalent to RD->getTypeForDecl().isCXX11PODType(),
  2002. // but with a lot of abstraction penalty stripped off. This does
  2003. // assume that these properties are set correctly even in C++98
  2004. // mode; fortunately, that is true because we want to assign
  2005. // consistently semantics to the type-traits intrinsics (or at
  2006. // least as many of them as possible).
  2007. return RD->isTrivial() && RD->isCXX11StandardLayout();
  2008. }
  2009. llvm_unreachable("bad tail-padding use kind");
  2010. }
  2011. static bool isMsLayout(const ASTContext &Context) {
  2012. return Context.getTargetInfo().getCXXABI().isMicrosoft();
  2013. }
  2014. // This section contains an implementation of struct layout that is, up to the
  2015. // included tests, compatible with cl.exe (2013). The layout produced is
  2016. // significantly different than those produced by the Itanium ABI. Here we note
  2017. // the most important differences.
  2018. //
  2019. // * The alignment of bitfields in unions is ignored when computing the
  2020. // alignment of the union.
  2021. // * The existence of zero-width bitfield that occurs after anything other than
  2022. // a non-zero length bitfield is ignored.
  2023. // * There is no explicit primary base for the purposes of layout. All bases
  2024. // with vfptrs are laid out first, followed by all bases without vfptrs.
  2025. // * The Itanium equivalent vtable pointers are split into a vfptr (virtual
  2026. // function pointer) and a vbptr (virtual base pointer). They can each be
  2027. // shared with a, non-virtual bases. These bases need not be the same. vfptrs
  2028. // always occur at offset 0. vbptrs can occur at an arbitrary offset and are
  2029. // placed after the lexicographically last non-virtual base. This placement
  2030. // is always before fields but can be in the middle of the non-virtual bases
  2031. // due to the two-pass layout scheme for non-virtual-bases.
  2032. // * Virtual bases sometimes require a 'vtordisp' field that is laid out before
  2033. // the virtual base and is used in conjunction with virtual overrides during
  2034. // construction and destruction. This is always a 4 byte value and is used as
  2035. // an alternative to constructor vtables.
  2036. // * vtordisps are allocated in a block of memory with size and alignment equal
  2037. // to the alignment of the completed structure (before applying __declspec(
  2038. // align())). The vtordisp always occur at the end of the allocation block,
  2039. // immediately prior to the virtual base.
  2040. // * vfptrs are injected after all bases and fields have been laid out. In
  2041. // order to guarantee proper alignment of all fields, the vfptr injection
  2042. // pushes all bases and fields back by the alignment imposed by those bases
  2043. // and fields. This can potentially add a significant amount of padding.
  2044. // vfptrs are always injected at offset 0.
  2045. // * vbptrs are injected after all bases and fields have been laid out. In
  2046. // order to guarantee proper alignment of all fields, the vfptr injection
  2047. // pushes all bases and fields back by the alignment imposed by those bases
  2048. // and fields. This can potentially add a significant amount of padding.
  2049. // vbptrs are injected immediately after the last non-virtual base as
  2050. // lexicographically ordered in the code. If this site isn't pointer aligned
  2051. // the vbptr is placed at the next properly aligned location. Enough padding
  2052. // is added to guarantee a fit.
  2053. // * The last zero sized non-virtual base can be placed at the end of the
  2054. // struct (potentially aliasing another object), or may alias with the first
  2055. // field, even if they are of the same type.
  2056. // * The last zero size virtual base may be placed at the end of the struct
  2057. // potentially aliasing another object.
  2058. // * The ABI attempts to avoid aliasing of zero sized bases by adding padding
  2059. // between bases or vbases with specific properties. The criteria for
  2060. // additional padding between two bases is that the first base is zero sized
  2061. // or ends with a zero sized subobject and the second base is zero sized or
  2062. // trails with a zero sized base or field (sharing of vfptrs can reorder the
  2063. // layout of the so the leading base is not always the first one declared).
  2064. // This rule does take into account fields that are not records, so padding
  2065. // will occur even if the last field is, e.g. an int. The padding added for
  2066. // bases is 1 byte. The padding added between vbases depends on the alignment
  2067. // of the object but is at least 4 bytes (in both 32 and 64 bit modes).
  2068. // * There is no concept of non-virtual alignment, non-virtual alignment and
  2069. // alignment are always identical.
  2070. // * There is a distinction between alignment and required alignment.
  2071. // __declspec(align) changes the required alignment of a struct. This
  2072. // alignment is _always_ obeyed, even in the presence of #pragma pack. A
  2073. // record inherits required alignment from all of its fields and bases.
  2074. // * __declspec(align) on bitfields has the effect of changing the bitfield's
  2075. // alignment instead of its required alignment. This is the only known way
  2076. // to make the alignment of a struct bigger than 8. Interestingly enough
  2077. // this alignment is also immune to the effects of #pragma pack and can be
  2078. // used to create structures with large alignment under #pragma pack.
  2079. // However, because it does not impact required alignment, such a structure,
  2080. // when used as a field or base, will not be aligned if #pragma pack is
  2081. // still active at the time of use.
  2082. //
  2083. // Known incompatibilities:
  2084. // * all: #pragma pack between fields in a record
  2085. // * 2010 and back: If the last field in a record is a bitfield, every object
  2086. // laid out after the record will have extra padding inserted before it. The
  2087. // extra padding will have size equal to the size of the storage class of the
  2088. // bitfield. 0 sized bitfields don't exhibit this behavior and the extra
  2089. // padding can be avoided by adding a 0 sized bitfield after the non-zero-
  2090. // sized bitfield.
  2091. // * 2012 and back: In 64-bit mode, if the alignment of a record is 16 or
  2092. // greater due to __declspec(align()) then a second layout phase occurs after
  2093. // The locations of the vf and vb pointers are known. This layout phase
  2094. // suffers from the "last field is a bitfield" bug in 2010 and results in
  2095. // _every_ field getting padding put in front of it, potentially including the
  2096. // vfptr, leaving the vfprt at a non-zero location which results in a fault if
  2097. // anything tries to read the vftbl. The second layout phase also treats
  2098. // bitfields as separate entities and gives them each storage rather than
  2099. // packing them. Additionally, because this phase appears to perform a
  2100. // (an unstable) sort on the members before laying them out and because merged
  2101. // bitfields have the same address, the bitfields end up in whatever order
  2102. // the sort left them in, a behavior we could never hope to replicate.
  2103. namespace {
  2104. struct MicrosoftRecordLayoutBuilder {
  2105. struct ElementInfo {
  2106. CharUnits Size;
  2107. CharUnits Alignment;
  2108. };
  2109. typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
  2110. MicrosoftRecordLayoutBuilder(const ASTContext &Context) : Context(Context) {}
  2111. private:
  2112. MicrosoftRecordLayoutBuilder(const MicrosoftRecordLayoutBuilder &) = delete;
  2113. void operator=(const MicrosoftRecordLayoutBuilder &) = delete;
  2114. public:
  2115. void layout(const RecordDecl *RD);
  2116. void cxxLayout(const CXXRecordDecl *RD);
  2117. /// Initializes size and alignment and honors some flags.
  2118. void initializeLayout(const RecordDecl *RD);
  2119. /// Initialized C++ layout, compute alignment and virtual alignment and
  2120. /// existence of vfptrs and vbptrs. Alignment is needed before the vfptr is
  2121. /// laid out.
  2122. void initializeCXXLayout(const CXXRecordDecl *RD);
  2123. void layoutNonVirtualBases(const CXXRecordDecl *RD);
  2124. void layoutNonVirtualBase(const CXXRecordDecl *RD,
  2125. const CXXRecordDecl *BaseDecl,
  2126. const ASTRecordLayout &BaseLayout,
  2127. const ASTRecordLayout *&PreviousBaseLayout);
  2128. void injectVFPtr(const CXXRecordDecl *RD);
  2129. void injectVBPtr(const CXXRecordDecl *RD);
  2130. /// Lays out the fields of the record. Also rounds size up to
  2131. /// alignment.
  2132. void layoutFields(const RecordDecl *RD);
  2133. void layoutField(const FieldDecl *FD);
  2134. void layoutBitField(const FieldDecl *FD);
  2135. /// Lays out a single zero-width bit-field in the record and handles
  2136. /// special cases associated with zero-width bit-fields.
  2137. void layoutZeroWidthBitField(const FieldDecl *FD);
  2138. void layoutVirtualBases(const CXXRecordDecl *RD);
  2139. void finalizeLayout(const RecordDecl *RD);
  2140. /// Gets the size and alignment of a base taking pragma pack and
  2141. /// __declspec(align) into account.
  2142. ElementInfo getAdjustedElementInfo(const ASTRecordLayout &Layout);
  2143. /// Gets the size and alignment of a field taking pragma pack and
  2144. /// __declspec(align) into account. It also updates RequiredAlignment as a
  2145. /// side effect because it is most convenient to do so here.
  2146. ElementInfo getAdjustedElementInfo(const FieldDecl *FD);
  2147. /// Places a field at an offset in CharUnits.
  2148. void placeFieldAtOffset(CharUnits FieldOffset) {
  2149. FieldOffsets.push_back(Context.toBits(FieldOffset));
  2150. }
  2151. /// Places a bitfield at a bit offset.
  2152. void placeFieldAtBitOffset(uint64_t FieldOffset) {
  2153. FieldOffsets.push_back(FieldOffset);
  2154. }
  2155. /// Compute the set of virtual bases for which vtordisps are required.
  2156. void computeVtorDispSet(
  2157. llvm::SmallPtrSetImpl<const CXXRecordDecl *> &HasVtorDispSet,
  2158. const CXXRecordDecl *RD) const;
  2159. const ASTContext &Context;
  2160. /// The size of the record being laid out.
  2161. CharUnits Size;
  2162. /// The non-virtual size of the record layout.
  2163. CharUnits NonVirtualSize;
  2164. /// The data size of the record layout.
  2165. CharUnits DataSize;
  2166. /// The current alignment of the record layout.
  2167. CharUnits Alignment;
  2168. /// The maximum allowed field alignment. This is set by #pragma pack.
  2169. CharUnits MaxFieldAlignment;
  2170. /// The alignment that this record must obey. This is imposed by
  2171. /// __declspec(align()) on the record itself or one of its fields or bases.
  2172. CharUnits RequiredAlignment;
  2173. /// The size of the allocation of the currently active bitfield.
  2174. /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield
  2175. /// is true.
  2176. CharUnits CurrentBitfieldSize;
  2177. /// Offset to the virtual base table pointer (if one exists).
  2178. CharUnits VBPtrOffset;
  2179. /// Minimum record size possible.
  2180. CharUnits MinEmptyStructSize;
  2181. /// The size and alignment info of a pointer.
  2182. ElementInfo PointerInfo;
  2183. /// The primary base class (if one exists).
  2184. const CXXRecordDecl *PrimaryBase;
  2185. /// The class we share our vb-pointer with.
  2186. const CXXRecordDecl *SharedVBPtrBase;
  2187. /// The collection of field offsets.
  2188. SmallVector<uint64_t, 16> FieldOffsets;
  2189. /// Base classes and their offsets in the record.
  2190. BaseOffsetsMapTy Bases;
  2191. /// virtual base classes and their offsets in the record.
  2192. ASTRecordLayout::VBaseOffsetsMapTy VBases;
  2193. /// The number of remaining bits in our last bitfield allocation.
  2194. /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield is
  2195. /// true.
  2196. unsigned RemainingBitsInField;
  2197. bool IsUnion : 1;
  2198. /// True if the last field laid out was a bitfield and was not 0
  2199. /// width.
  2200. bool LastFieldIsNonZeroWidthBitfield : 1;
  2201. /// True if the class has its own vftable pointer.
  2202. bool HasOwnVFPtr : 1;
  2203. /// True if the class has a vbtable pointer.
  2204. bool HasVBPtr : 1;
  2205. /// True if the last sub-object within the type is zero sized or the
  2206. /// object itself is zero sized. This *does not* count members that are not
  2207. /// records. Only used for MS-ABI.
  2208. bool EndsWithZeroSizedObject : 1;
  2209. /// True if this class is zero sized or first base is zero sized or
  2210. /// has this property. Only used for MS-ABI.
  2211. bool LeadsWithZeroSizedBase : 1;
  2212. /// True if the external AST source provided a layout for this record.
  2213. bool UseExternalLayout : 1;
  2214. /// The layout provided by the external AST source. Only active if
  2215. /// UseExternalLayout is true.
  2216. ExternalLayout External;
  2217. };
  2218. } // namespace
  2219. MicrosoftRecordLayoutBuilder::ElementInfo
  2220. MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
  2221. const ASTRecordLayout &Layout) {
  2222. ElementInfo Info;
  2223. Info.Alignment = Layout.getAlignment();
  2224. // Respect pragma pack.
  2225. if (!MaxFieldAlignment.isZero())
  2226. Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
  2227. // Track zero-sized subobjects here where it's already available.
  2228. EndsWithZeroSizedObject = Layout.endsWithZeroSizedObject();
  2229. // Respect required alignment, this is necessary because we may have adjusted
  2230. // the alignment in the case of pragma pack. Note that the required alignment
  2231. // doesn't actually apply to the struct alignment at this point.
  2232. Alignment = std::max(Alignment, Info.Alignment);
  2233. RequiredAlignment = std::max(RequiredAlignment, Layout.getRequiredAlignment());
  2234. Info.Alignment = std::max(Info.Alignment, Layout.getRequiredAlignment());
  2235. Info.Size = Layout.getNonVirtualSize();
  2236. return Info;
  2237. }
  2238. MicrosoftRecordLayoutBuilder::ElementInfo
  2239. MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
  2240. const FieldDecl *FD) {
  2241. // Get the alignment of the field type's natural alignment, ignore any
  2242. // alignment attributes.
  2243. auto TInfo =
  2244. Context.getTypeInfoInChars(FD->getType()->getUnqualifiedDesugaredType());
  2245. ElementInfo Info{TInfo.Width, TInfo.Align};
  2246. // Respect align attributes on the field.
  2247. CharUnits FieldRequiredAlignment =
  2248. Context.toCharUnitsFromBits(FD->getMaxAlignment());
  2249. // Respect align attributes on the type.
  2250. if (Context.isAlignmentRequired(FD->getType()))
  2251. FieldRequiredAlignment = std::max(
  2252. Context.getTypeAlignInChars(FD->getType()), FieldRequiredAlignment);
  2253. // Respect attributes applied to subobjects of the field.
  2254. if (FD->isBitField())
  2255. // For some reason __declspec align impacts alignment rather than required
  2256. // alignment when it is applied to bitfields.
  2257. Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
  2258. else {
  2259. if (auto RT =
  2260. FD->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
  2261. auto const &Layout = Context.getASTRecordLayout(RT->getDecl());
  2262. EndsWithZeroSizedObject = Layout.endsWithZeroSizedObject();
  2263. FieldRequiredAlignment = std::max(FieldRequiredAlignment,
  2264. Layout.getRequiredAlignment());
  2265. }
  2266. // Capture required alignment as a side-effect.
  2267. RequiredAlignment = std::max(RequiredAlignment, FieldRequiredAlignment);
  2268. }
  2269. // Respect pragma pack, attribute pack and declspec align
  2270. if (!MaxFieldAlignment.isZero())
  2271. Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
  2272. if (FD->hasAttr<PackedAttr>())
  2273. Info.Alignment = CharUnits::One();
  2274. Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
  2275. return Info;
  2276. }
  2277. void MicrosoftRecordLayoutBuilder::layout(const RecordDecl *RD) {
  2278. // For C record layout, zero-sized records always have size 4.
  2279. MinEmptyStructSize = CharUnits::fromQuantity(4);
  2280. initializeLayout(RD);
  2281. layoutFields(RD);
  2282. DataSize = Size = Size.alignTo(Alignment);
  2283. RequiredAlignment = std::max(
  2284. RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
  2285. finalizeLayout(RD);
  2286. }
  2287. void MicrosoftRecordLayoutBuilder::cxxLayout(const CXXRecordDecl *RD) {
  2288. // The C++ standard says that empty structs have size 1.
  2289. MinEmptyStructSize = CharUnits::One();
  2290. initializeLayout(RD);
  2291. initializeCXXLayout(RD);
  2292. layoutNonVirtualBases(RD);
  2293. layoutFields(RD);
  2294. injectVBPtr(RD);
  2295. injectVFPtr(RD);
  2296. if (HasOwnVFPtr || (HasVBPtr && !SharedVBPtrBase))
  2297. Alignment = std::max(Alignment, PointerInfo.Alignment);
  2298. auto RoundingAlignment = Alignment;
  2299. if (!MaxFieldAlignment.isZero())
  2300. RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment);
  2301. if (!UseExternalLayout)
  2302. Size = Size.alignTo(RoundingAlignment);
  2303. NonVirtualSize = Size;
  2304. RequiredAlignment = std::max(
  2305. RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
  2306. layoutVirtualBases(RD);
  2307. finalizeLayout(RD);
  2308. }
  2309. void MicrosoftRecordLayoutBuilder::initializeLayout(const RecordDecl *RD) {
  2310. IsUnion = RD->isUnion();
  2311. Size = CharUnits::Zero();
  2312. Alignment = CharUnits::One();
  2313. // In 64-bit mode we always perform an alignment step after laying out vbases.
  2314. // In 32-bit mode we do not. The check to see if we need to perform alignment
  2315. // checks the RequiredAlignment field and performs alignment if it isn't 0.
  2316. RequiredAlignment = Context.getTargetInfo().getTriple().isArch64Bit()
  2317. ? CharUnits::One()
  2318. : CharUnits::Zero();
  2319. // Compute the maximum field alignment.
  2320. MaxFieldAlignment = CharUnits::Zero();
  2321. // Honor the default struct packing maximum alignment flag.
  2322. if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct)
  2323. MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
  2324. // Honor the packing attribute. The MS-ABI ignores pragma pack if its larger
  2325. // than the pointer size.
  2326. if (const MaxFieldAlignmentAttr *MFAA = RD->getAttr<MaxFieldAlignmentAttr>()){
  2327. unsigned PackedAlignment = MFAA->getAlignment();
  2328. if (PackedAlignment <=
  2329. Context.getTargetInfo().getPointerWidth(LangAS::Default))
  2330. MaxFieldAlignment = Context.toCharUnitsFromBits(PackedAlignment);
  2331. }
  2332. // Packed attribute forces max field alignment to be 1.
  2333. if (RD->hasAttr<PackedAttr>())
  2334. MaxFieldAlignment = CharUnits::One();
  2335. // Try to respect the external layout if present.
  2336. UseExternalLayout = false;
  2337. if (ExternalASTSource *Source = Context.getExternalSource())
  2338. UseExternalLayout = Source->layoutRecordType(
  2339. RD, External.Size, External.Align, External.FieldOffsets,
  2340. External.BaseOffsets, External.VirtualBaseOffsets);
  2341. }
  2342. void
  2343. MicrosoftRecordLayoutBuilder::initializeCXXLayout(const CXXRecordDecl *RD) {
  2344. EndsWithZeroSizedObject = false;
  2345. LeadsWithZeroSizedBase = false;
  2346. HasOwnVFPtr = false;
  2347. HasVBPtr = false;
  2348. PrimaryBase = nullptr;
  2349. SharedVBPtrBase = nullptr;
  2350. // Calculate pointer size and alignment. These are used for vfptr and vbprt
  2351. // injection.
  2352. PointerInfo.Size = Context.toCharUnitsFromBits(
  2353. Context.getTargetInfo().getPointerWidth(LangAS::Default));
  2354. PointerInfo.Alignment = Context.toCharUnitsFromBits(
  2355. Context.getTargetInfo().getPointerAlign(LangAS::Default));
  2356. // Respect pragma pack.
  2357. if (!MaxFieldAlignment.isZero())
  2358. PointerInfo.Alignment = std::min(PointerInfo.Alignment, MaxFieldAlignment);
  2359. }
  2360. void
  2361. MicrosoftRecordLayoutBuilder::layoutNonVirtualBases(const CXXRecordDecl *RD) {
  2362. // The MS-ABI lays out all bases that contain leading vfptrs before it lays
  2363. // out any bases that do not contain vfptrs. We implement this as two passes
  2364. // over the bases. This approach guarantees that the primary base is laid out
  2365. // first. We use these passes to calculate some additional aggregated
  2366. // information about the bases, such as required alignment and the presence of
  2367. // zero sized members.
  2368. const ASTRecordLayout *PreviousBaseLayout = nullptr;
  2369. bool HasPolymorphicBaseClass = false;
  2370. // Iterate through the bases and lay out the non-virtual ones.
  2371. for (const CXXBaseSpecifier &Base : RD->bases()) {
  2372. const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
  2373. HasPolymorphicBaseClass |= BaseDecl->isPolymorphic();
  2374. const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
  2375. // Mark and skip virtual bases.
  2376. if (Base.isVirtual()) {
  2377. HasVBPtr = true;
  2378. continue;
  2379. }
  2380. // Check for a base to share a VBPtr with.
  2381. if (!SharedVBPtrBase && BaseLayout.hasVBPtr()) {
  2382. SharedVBPtrBase = BaseDecl;
  2383. HasVBPtr = true;
  2384. }
  2385. // Only lay out bases with extendable VFPtrs on the first pass.
  2386. if (!BaseLayout.hasExtendableVFPtr())
  2387. continue;
  2388. // If we don't have a primary base, this one qualifies.
  2389. if (!PrimaryBase) {
  2390. PrimaryBase = BaseDecl;
  2391. LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
  2392. }
  2393. // Lay out the base.
  2394. layoutNonVirtualBase(RD, BaseDecl, BaseLayout, PreviousBaseLayout);
  2395. }
  2396. // Figure out if we need a fresh VFPtr for this class.
  2397. if (RD->isPolymorphic()) {
  2398. if (!HasPolymorphicBaseClass)
  2399. // This class introduces polymorphism, so we need a vftable to store the
  2400. // RTTI information.
  2401. HasOwnVFPtr = true;
  2402. else if (!PrimaryBase) {
  2403. // We have a polymorphic base class but can't extend its vftable. Add a
  2404. // new vfptr if we would use any vftable slots.
  2405. for (CXXMethodDecl *M : RD->methods()) {
  2406. if (MicrosoftVTableContext::hasVtableSlot(M) &&
  2407. M->size_overridden_methods() == 0) {
  2408. HasOwnVFPtr = true;
  2409. break;
  2410. }
  2411. }
  2412. }
  2413. }
  2414. // If we don't have a primary base then we have a leading object that could
  2415. // itself lead with a zero-sized object, something we track.
  2416. bool CheckLeadingLayout = !PrimaryBase;
  2417. // Iterate through the bases and lay out the non-virtual ones.
  2418. for (const CXXBaseSpecifier &Base : RD->bases()) {
  2419. if (Base.isVirtual())
  2420. continue;
  2421. const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
  2422. const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
  2423. // Only lay out bases without extendable VFPtrs on the second pass.
  2424. if (BaseLayout.hasExtendableVFPtr()) {
  2425. VBPtrOffset = Bases[BaseDecl] + BaseLayout.getNonVirtualSize();
  2426. continue;
  2427. }
  2428. // If this is the first layout, check to see if it leads with a zero sized
  2429. // object. If it does, so do we.
  2430. if (CheckLeadingLayout) {
  2431. CheckLeadingLayout = false;
  2432. LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
  2433. }
  2434. // Lay out the base.
  2435. layoutNonVirtualBase(RD, BaseDecl, BaseLayout, PreviousBaseLayout);
  2436. VBPtrOffset = Bases[BaseDecl] + BaseLayout.getNonVirtualSize();
  2437. }
  2438. // Set our VBPtroffset if we know it at this point.
  2439. if (!HasVBPtr)
  2440. VBPtrOffset = CharUnits::fromQuantity(-1);
  2441. else if (SharedVBPtrBase) {
  2442. const ASTRecordLayout &Layout = Context.getASTRecordLayout(SharedVBPtrBase);
  2443. VBPtrOffset = Bases[SharedVBPtrBase] + Layout.getVBPtrOffset();
  2444. }
  2445. }
  2446. static bool recordUsesEBO(const RecordDecl *RD) {
  2447. if (!isa<CXXRecordDecl>(RD))
  2448. return false;
  2449. if (RD->hasAttr<EmptyBasesAttr>())
  2450. return true;
  2451. if (auto *LVA = RD->getAttr<LayoutVersionAttr>())
  2452. // TODO: Double check with the next version of MSVC.
  2453. if (LVA->getVersion() <= LangOptions::MSVC2015)
  2454. return false;
  2455. // TODO: Some later version of MSVC will change the default behavior of the
  2456. // compiler to enable EBO by default. When this happens, we will need an
  2457. // additional isCompatibleWithMSVC check.
  2458. return false;
  2459. }
  2460. void MicrosoftRecordLayoutBuilder::layoutNonVirtualBase(
  2461. const CXXRecordDecl *RD,
  2462. const CXXRecordDecl *BaseDecl,
  2463. const ASTRecordLayout &BaseLayout,
  2464. const ASTRecordLayout *&PreviousBaseLayout) {
  2465. // Insert padding between two bases if the left first one is zero sized or
  2466. // contains a zero sized subobject and the right is zero sized or one leads
  2467. // with a zero sized base.
  2468. bool MDCUsesEBO = recordUsesEBO(RD);
  2469. if (PreviousBaseLayout && PreviousBaseLayout->endsWithZeroSizedObject() &&
  2470. BaseLayout.leadsWithZeroSizedBase() && !MDCUsesEBO)
  2471. Size++;
  2472. ElementInfo Info = getAdjustedElementInfo(BaseLayout);
  2473. CharUnits BaseOffset;
  2474. // Respect the external AST source base offset, if present.
  2475. bool FoundBase = false;
  2476. if (UseExternalLayout) {
  2477. FoundBase = External.getExternalNVBaseOffset(BaseDecl, BaseOffset);
  2478. if (FoundBase) {
  2479. assert(BaseOffset >= Size && "base offset already allocated");
  2480. Size = BaseOffset;
  2481. }
  2482. }
  2483. if (!FoundBase) {
  2484. if (MDCUsesEBO && BaseDecl->isEmpty()) {
  2485. assert(BaseLayout.getNonVirtualSize() == CharUnits::Zero());
  2486. BaseOffset = CharUnits::Zero();
  2487. } else {
  2488. // Otherwise, lay the base out at the end of the MDC.
  2489. BaseOffset = Size = Size.alignTo(Info.Alignment);
  2490. }
  2491. }
  2492. Bases.insert(std::make_pair(BaseDecl, BaseOffset));
  2493. Size += BaseLayout.getNonVirtualSize();
  2494. PreviousBaseLayout = &BaseLayout;
  2495. }
  2496. void MicrosoftRecordLayoutBuilder::layoutFields(const RecordDecl *RD) {
  2497. LastFieldIsNonZeroWidthBitfield = false;
  2498. for (const FieldDecl *Field : RD->fields())
  2499. layoutField(Field);
  2500. }
  2501. void MicrosoftRecordLayoutBuilder::layoutField(const FieldDecl *FD) {
  2502. if (FD->isBitField()) {
  2503. layoutBitField(FD);
  2504. return;
  2505. }
  2506. LastFieldIsNonZeroWidthBitfield = false;
  2507. ElementInfo Info = getAdjustedElementInfo(FD);
  2508. Alignment = std::max(Alignment, Info.Alignment);
  2509. CharUnits FieldOffset;
  2510. if (UseExternalLayout)
  2511. FieldOffset =
  2512. Context.toCharUnitsFromBits(External.getExternalFieldOffset(FD));
  2513. else if (IsUnion)
  2514. FieldOffset = CharUnits::Zero();
  2515. else
  2516. FieldOffset = Size.alignTo(Info.Alignment);
  2517. placeFieldAtOffset(FieldOffset);
  2518. Size = std::max(Size, FieldOffset + Info.Size);
  2519. }
  2520. void MicrosoftRecordLayoutBuilder::layoutBitField(const FieldDecl *FD) {
  2521. unsigned Width = FD->getBitWidthValue(Context);
  2522. if (Width == 0) {
  2523. layoutZeroWidthBitField(FD);
  2524. return;
  2525. }
  2526. ElementInfo Info = getAdjustedElementInfo(FD);
  2527. // Clamp the bitfield to a containable size for the sake of being able
  2528. // to lay them out. Sema will throw an error.
  2529. if (Width > Context.toBits(Info.Size))
  2530. Width = Context.toBits(Info.Size);
  2531. // Check to see if this bitfield fits into an existing allocation. Note:
  2532. // MSVC refuses to pack bitfields of formal types with different sizes
  2533. // into the same allocation.
  2534. if (!UseExternalLayout && !IsUnion && LastFieldIsNonZeroWidthBitfield &&
  2535. CurrentBitfieldSize == Info.Size && Width <= RemainingBitsInField) {
  2536. placeFieldAtBitOffset(Context.toBits(Size) - RemainingBitsInField);
  2537. RemainingBitsInField -= Width;
  2538. return;
  2539. }
  2540. LastFieldIsNonZeroWidthBitfield = true;
  2541. CurrentBitfieldSize = Info.Size;
  2542. if (UseExternalLayout) {
  2543. auto FieldBitOffset = External.getExternalFieldOffset(FD);
  2544. placeFieldAtBitOffset(FieldBitOffset);
  2545. auto NewSize = Context.toCharUnitsFromBits(
  2546. llvm::alignDown(FieldBitOffset, Context.toBits(Info.Alignment)) +
  2547. Context.toBits(Info.Size));
  2548. Size = std::max(Size, NewSize);
  2549. Alignment = std::max(Alignment, Info.Alignment);
  2550. } else if (IsUnion) {
  2551. placeFieldAtOffset(CharUnits::Zero());
  2552. Size = std::max(Size, Info.Size);
  2553. // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
  2554. } else {
  2555. // Allocate a new block of memory and place the bitfield in it.
  2556. CharUnits FieldOffset = Size.alignTo(Info.Alignment);
  2557. placeFieldAtOffset(FieldOffset);
  2558. Size = FieldOffset + Info.Size;
  2559. Alignment = std::max(Alignment, Info.Alignment);
  2560. RemainingBitsInField = Context.toBits(Info.Size) - Width;
  2561. }
  2562. }
  2563. void
  2564. MicrosoftRecordLayoutBuilder::layoutZeroWidthBitField(const FieldDecl *FD) {
  2565. // Zero-width bitfields are ignored unless they follow a non-zero-width
  2566. // bitfield.
  2567. if (!LastFieldIsNonZeroWidthBitfield) {
  2568. placeFieldAtOffset(IsUnion ? CharUnits::Zero() : Size);
  2569. // TODO: Add a Sema warning that MS ignores alignment for zero
  2570. // sized bitfields that occur after zero-size bitfields or non-bitfields.
  2571. return;
  2572. }
  2573. LastFieldIsNonZeroWidthBitfield = false;
  2574. ElementInfo Info = getAdjustedElementInfo(FD);
  2575. if (IsUnion) {
  2576. placeFieldAtOffset(CharUnits::Zero());
  2577. Size = std::max(Size, Info.Size);
  2578. // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
  2579. } else {
  2580. // Round up the current record size to the field's alignment boundary.
  2581. CharUnits FieldOffset = Size.alignTo(Info.Alignment);
  2582. placeFieldAtOffset(FieldOffset);
  2583. Size = FieldOffset;
  2584. Alignment = std::max(Alignment, Info.Alignment);
  2585. }
  2586. }
  2587. void MicrosoftRecordLayoutBuilder::injectVBPtr(const CXXRecordDecl *RD) {
  2588. if (!HasVBPtr || SharedVBPtrBase)
  2589. return;
  2590. // Inject the VBPointer at the injection site.
  2591. CharUnits InjectionSite = VBPtrOffset;
  2592. // But before we do, make sure it's properly aligned.
  2593. VBPtrOffset = VBPtrOffset.alignTo(PointerInfo.Alignment);
  2594. // Determine where the first field should be laid out after the vbptr.
  2595. CharUnits FieldStart = VBPtrOffset + PointerInfo.Size;
  2596. // Shift everything after the vbptr down, unless we're using an external
  2597. // layout.
  2598. if (UseExternalLayout) {
  2599. // It is possible that there were no fields or bases located after vbptr,
  2600. // so the size was not adjusted before.
  2601. if (Size < FieldStart)
  2602. Size = FieldStart;
  2603. return;
  2604. }
  2605. // Make sure that the amount we push the fields back by is a multiple of the
  2606. // alignment.
  2607. CharUnits Offset = (FieldStart - InjectionSite)
  2608. .alignTo(std::max(RequiredAlignment, Alignment));
  2609. Size += Offset;
  2610. for (uint64_t &FieldOffset : FieldOffsets)
  2611. FieldOffset += Context.toBits(Offset);
  2612. for (BaseOffsetsMapTy::value_type &Base : Bases)
  2613. if (Base.second >= InjectionSite)
  2614. Base.second += Offset;
  2615. }
  2616. void MicrosoftRecordLayoutBuilder::injectVFPtr(const CXXRecordDecl *RD) {
  2617. if (!HasOwnVFPtr)
  2618. return;
  2619. // Make sure that the amount we push the struct back by is a multiple of the
  2620. // alignment.
  2621. CharUnits Offset =
  2622. PointerInfo.Size.alignTo(std::max(RequiredAlignment, Alignment));
  2623. // Push back the vbptr, but increase the size of the object and push back
  2624. // regular fields by the offset only if not using external record layout.
  2625. if (HasVBPtr)
  2626. VBPtrOffset += Offset;
  2627. if (UseExternalLayout) {
  2628. // The class may have size 0 and a vfptr (e.g. it's an interface class). The
  2629. // size was not correctly set before in this case.
  2630. if (Size.isZero())
  2631. Size += Offset;
  2632. return;
  2633. }
  2634. Size += Offset;
  2635. // If we're using an external layout, the fields offsets have already
  2636. // accounted for this adjustment.
  2637. for (uint64_t &FieldOffset : FieldOffsets)
  2638. FieldOffset += Context.toBits(Offset);
  2639. for (BaseOffsetsMapTy::value_type &Base : Bases)
  2640. Base.second += Offset;
  2641. }
  2642. void MicrosoftRecordLayoutBuilder::layoutVirtualBases(const CXXRecordDecl *RD) {
  2643. if (!HasVBPtr)
  2644. return;
  2645. // Vtordisps are always 4 bytes (even in 64-bit mode)
  2646. CharUnits VtorDispSize = CharUnits::fromQuantity(4);
  2647. CharUnits VtorDispAlignment = VtorDispSize;
  2648. // vtordisps respect pragma pack.
  2649. if (!MaxFieldAlignment.isZero())
  2650. VtorDispAlignment = std::min(VtorDispAlignment, MaxFieldAlignment);
  2651. // The alignment of the vtordisp is at least the required alignment of the
  2652. // entire record. This requirement may be present to support vtordisp
  2653. // injection.
  2654. for (const CXXBaseSpecifier &VBase : RD->vbases()) {
  2655. const CXXRecordDecl *BaseDecl = VBase.getType()->getAsCXXRecordDecl();
  2656. const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
  2657. RequiredAlignment =
  2658. std::max(RequiredAlignment, BaseLayout.getRequiredAlignment());
  2659. }
  2660. VtorDispAlignment = std::max(VtorDispAlignment, RequiredAlignment);
  2661. // Compute the vtordisp set.
  2662. llvm::SmallPtrSet<const CXXRecordDecl *, 2> HasVtorDispSet;
  2663. computeVtorDispSet(HasVtorDispSet, RD);
  2664. // Iterate through the virtual bases and lay them out.
  2665. const ASTRecordLayout *PreviousBaseLayout = nullptr;
  2666. for (const CXXBaseSpecifier &VBase : RD->vbases()) {
  2667. const CXXRecordDecl *BaseDecl = VBase.getType()->getAsCXXRecordDecl();
  2668. const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
  2669. bool HasVtordisp = HasVtorDispSet.contains(BaseDecl);
  2670. // Insert padding between two bases if the left first one is zero sized or
  2671. // contains a zero sized subobject and the right is zero sized or one leads
  2672. // with a zero sized base. The padding between virtual bases is 4
  2673. // bytes (in both 32 and 64 bits modes) and always involves rounding up to
  2674. // the required alignment, we don't know why.
  2675. if ((PreviousBaseLayout && PreviousBaseLayout->endsWithZeroSizedObject() &&
  2676. BaseLayout.leadsWithZeroSizedBase() && !recordUsesEBO(RD)) ||
  2677. HasVtordisp) {
  2678. Size = Size.alignTo(VtorDispAlignment) + VtorDispSize;
  2679. Alignment = std::max(VtorDispAlignment, Alignment);
  2680. }
  2681. // Insert the virtual base.
  2682. ElementInfo Info = getAdjustedElementInfo(BaseLayout);
  2683. CharUnits BaseOffset;
  2684. // Respect the external AST source base offset, if present.
  2685. if (UseExternalLayout) {
  2686. if (!External.getExternalVBaseOffset(BaseDecl, BaseOffset))
  2687. BaseOffset = Size;
  2688. } else
  2689. BaseOffset = Size.alignTo(Info.Alignment);
  2690. assert(BaseOffset >= Size && "base offset already allocated");
  2691. VBases.insert(std::make_pair(BaseDecl,
  2692. ASTRecordLayout::VBaseInfo(BaseOffset, HasVtordisp)));
  2693. Size = BaseOffset + BaseLayout.getNonVirtualSize();
  2694. PreviousBaseLayout = &BaseLayout;
  2695. }
  2696. }
  2697. void MicrosoftRecordLayoutBuilder::finalizeLayout(const RecordDecl *RD) {
  2698. // Respect required alignment. Note that in 32-bit mode Required alignment
  2699. // may be 0 and cause size not to be updated.
  2700. DataSize = Size;
  2701. if (!RequiredAlignment.isZero()) {
  2702. Alignment = std::max(Alignment, RequiredAlignment);
  2703. auto RoundingAlignment = Alignment;
  2704. if (!MaxFieldAlignment.isZero())
  2705. RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment);
  2706. RoundingAlignment = std::max(RoundingAlignment, RequiredAlignment);
  2707. Size = Size.alignTo(RoundingAlignment);
  2708. }
  2709. if (Size.isZero()) {
  2710. if (!recordUsesEBO(RD) || !cast<CXXRecordDecl>(RD)->isEmpty()) {
  2711. EndsWithZeroSizedObject = true;
  2712. LeadsWithZeroSizedBase = true;
  2713. }
  2714. // Zero-sized structures have size equal to their alignment if a
  2715. // __declspec(align) came into play.
  2716. if (RequiredAlignment >= MinEmptyStructSize)
  2717. Size = Alignment;
  2718. else
  2719. Size = MinEmptyStructSize;
  2720. }
  2721. if (UseExternalLayout) {
  2722. Size = Context.toCharUnitsFromBits(External.Size);
  2723. if (External.Align)
  2724. Alignment = Context.toCharUnitsFromBits(External.Align);
  2725. }
  2726. }
  2727. // Recursively walks the non-virtual bases of a class and determines if any of
  2728. // them are in the bases with overridden methods set.
  2729. static bool
  2730. RequiresVtordisp(const llvm::SmallPtrSetImpl<const CXXRecordDecl *> &
  2731. BasesWithOverriddenMethods,
  2732. const CXXRecordDecl *RD) {
  2733. if (BasesWithOverriddenMethods.count(RD))
  2734. return true;
  2735. // If any of a virtual bases non-virtual bases (recursively) requires a
  2736. // vtordisp than so does this virtual base.
  2737. for (const CXXBaseSpecifier &Base : RD->bases())
  2738. if (!Base.isVirtual() &&
  2739. RequiresVtordisp(BasesWithOverriddenMethods,
  2740. Base.getType()->getAsCXXRecordDecl()))
  2741. return true;
  2742. return false;
  2743. }
  2744. void MicrosoftRecordLayoutBuilder::computeVtorDispSet(
  2745. llvm::SmallPtrSetImpl<const CXXRecordDecl *> &HasVtordispSet,
  2746. const CXXRecordDecl *RD) const {
  2747. // /vd2 or #pragma vtordisp(2): Always use vtordisps for virtual bases with
  2748. // vftables.
  2749. if (RD->getMSVtorDispMode() == MSVtorDispMode::ForVFTable) {
  2750. for (const CXXBaseSpecifier &Base : RD->vbases()) {
  2751. const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
  2752. const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
  2753. if (Layout.hasExtendableVFPtr())
  2754. HasVtordispSet.insert(BaseDecl);
  2755. }
  2756. return;
  2757. }
  2758. // If any of our bases need a vtordisp for this type, so do we. Check our
  2759. // direct bases for vtordisp requirements.
  2760. for (const CXXBaseSpecifier &Base : RD->bases()) {
  2761. const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
  2762. const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
  2763. for (const auto &bi : Layout.getVBaseOffsetsMap())
  2764. if (bi.second.hasVtorDisp())
  2765. HasVtordispSet.insert(bi.first);
  2766. }
  2767. // We don't introduce any additional vtordisps if either:
  2768. // * A user declared constructor or destructor aren't declared.
  2769. // * #pragma vtordisp(0) or the /vd0 flag are in use.
  2770. if ((!RD->hasUserDeclaredConstructor() && !RD->hasUserDeclaredDestructor()) ||
  2771. RD->getMSVtorDispMode() == MSVtorDispMode::Never)
  2772. return;
  2773. // /vd1 or #pragma vtordisp(1): Try to guess based on whether we think it's
  2774. // possible for a partially constructed object with virtual base overrides to
  2775. // escape a non-trivial constructor.
  2776. assert(RD->getMSVtorDispMode() == MSVtorDispMode::ForVBaseOverride);
  2777. // Compute a set of base classes which define methods we override. A virtual
  2778. // base in this set will require a vtordisp. A virtual base that transitively
  2779. // contains one of these bases as a non-virtual base will also require a
  2780. // vtordisp.
  2781. llvm::SmallPtrSet<const CXXMethodDecl *, 8> Work;
  2782. llvm::SmallPtrSet<const CXXRecordDecl *, 2> BasesWithOverriddenMethods;
  2783. // Seed the working set with our non-destructor, non-pure virtual methods.
  2784. for (const CXXMethodDecl *MD : RD->methods())
  2785. if (MicrosoftVTableContext::hasVtableSlot(MD) &&
  2786. !isa<CXXDestructorDecl>(MD) && !MD->isPure())
  2787. Work.insert(MD);
  2788. while (!Work.empty()) {
  2789. const CXXMethodDecl *MD = *Work.begin();
  2790. auto MethodRange = MD->overridden_methods();
  2791. // If a virtual method has no-overrides it lives in its parent's vtable.
  2792. if (MethodRange.begin() == MethodRange.end())
  2793. BasesWithOverriddenMethods.insert(MD->getParent());
  2794. else
  2795. Work.insert(MethodRange.begin(), MethodRange.end());
  2796. // We've finished processing this element, remove it from the working set.
  2797. Work.erase(MD);
  2798. }
  2799. // For each of our virtual bases, check if it is in the set of overridden
  2800. // bases or if it transitively contains a non-virtual base that is.
  2801. for (const CXXBaseSpecifier &Base : RD->vbases()) {
  2802. const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
  2803. if (!HasVtordispSet.count(BaseDecl) &&
  2804. RequiresVtordisp(BasesWithOverriddenMethods, BaseDecl))
  2805. HasVtordispSet.insert(BaseDecl);
  2806. }
  2807. }
  2808. /// getASTRecordLayout - Get or compute information about the layout of the
  2809. /// specified record (struct/union/class), which indicates its size and field
  2810. /// position information.
  2811. const ASTRecordLayout &
  2812. ASTContext::getASTRecordLayout(const RecordDecl *D) const {
  2813. // These asserts test different things. A record has a definition
  2814. // as soon as we begin to parse the definition. That definition is
  2815. // not a complete definition (which is what isDefinition() tests)
  2816. // until we *finish* parsing the definition.
  2817. if (D->hasExternalLexicalStorage() && !D->getDefinition())
  2818. getExternalSource()->CompleteType(const_cast<RecordDecl*>(D));
  2819. // Complete the redecl chain (if necessary).
  2820. (void)D->getMostRecentDecl();
  2821. D = D->getDefinition();
  2822. assert(D && "Cannot get layout of forward declarations!");
  2823. assert(!D->isInvalidDecl() && "Cannot get layout of invalid decl!");
  2824. assert(D->isCompleteDefinition() && "Cannot layout type before complete!");
  2825. // Look up this layout, if already laid out, return what we have.
  2826. // Note that we can't save a reference to the entry because this function
  2827. // is recursive.
  2828. const ASTRecordLayout *Entry = ASTRecordLayouts[D];
  2829. if (Entry) return *Entry;
  2830. const ASTRecordLayout *NewEntry = nullptr;
  2831. if (isMsLayout(*this)) {
  2832. MicrosoftRecordLayoutBuilder Builder(*this);
  2833. if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
  2834. Builder.cxxLayout(RD);
  2835. NewEntry = new (*this) ASTRecordLayout(
  2836. *this, Builder.Size, Builder.Alignment, Builder.Alignment,
  2837. Builder.Alignment, Builder.RequiredAlignment, Builder.HasOwnVFPtr,
  2838. Builder.HasOwnVFPtr || Builder.PrimaryBase, Builder.VBPtrOffset,
  2839. Builder.DataSize, Builder.FieldOffsets, Builder.NonVirtualSize,
  2840. Builder.Alignment, Builder.Alignment, CharUnits::Zero(),
  2841. Builder.PrimaryBase, false, Builder.SharedVBPtrBase,
  2842. Builder.EndsWithZeroSizedObject, Builder.LeadsWithZeroSizedBase,
  2843. Builder.Bases, Builder.VBases);
  2844. } else {
  2845. Builder.layout(D);
  2846. NewEntry = new (*this) ASTRecordLayout(
  2847. *this, Builder.Size, Builder.Alignment, Builder.Alignment,
  2848. Builder.Alignment, Builder.RequiredAlignment, Builder.Size,
  2849. Builder.FieldOffsets);
  2850. }
  2851. } else {
  2852. if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
  2853. EmptySubobjectMap EmptySubobjects(*this, RD);
  2854. ItaniumRecordLayoutBuilder Builder(*this, &EmptySubobjects);
  2855. Builder.Layout(RD);
  2856. // In certain situations, we are allowed to lay out objects in the
  2857. // tail-padding of base classes. This is ABI-dependent.
  2858. // FIXME: this should be stored in the record layout.
  2859. bool skipTailPadding =
  2860. mustSkipTailPadding(getTargetInfo().getCXXABI(), RD);
  2861. // FIXME: This should be done in FinalizeLayout.
  2862. CharUnits DataSize =
  2863. skipTailPadding ? Builder.getSize() : Builder.getDataSize();
  2864. CharUnits NonVirtualSize =
  2865. skipTailPadding ? DataSize : Builder.NonVirtualSize;
  2866. NewEntry = new (*this) ASTRecordLayout(
  2867. *this, Builder.getSize(), Builder.Alignment,
  2868. Builder.PreferredAlignment, Builder.UnadjustedAlignment,
  2869. /*RequiredAlignment : used by MS-ABI)*/
  2870. Builder.Alignment, Builder.HasOwnVFPtr, RD->isDynamicClass(),
  2871. CharUnits::fromQuantity(-1), DataSize, Builder.FieldOffsets,
  2872. NonVirtualSize, Builder.NonVirtualAlignment,
  2873. Builder.PreferredNVAlignment,
  2874. EmptySubobjects.SizeOfLargestEmptySubobject, Builder.PrimaryBase,
  2875. Builder.PrimaryBaseIsVirtual, nullptr, false, false, Builder.Bases,
  2876. Builder.VBases);
  2877. } else {
  2878. ItaniumRecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/nullptr);
  2879. Builder.Layout(D);
  2880. NewEntry = new (*this) ASTRecordLayout(
  2881. *this, Builder.getSize(), Builder.Alignment,
  2882. Builder.PreferredAlignment, Builder.UnadjustedAlignment,
  2883. /*RequiredAlignment : used by MS-ABI)*/
  2884. Builder.Alignment, Builder.getSize(), Builder.FieldOffsets);
  2885. }
  2886. }
  2887. ASTRecordLayouts[D] = NewEntry;
  2888. if (getLangOpts().DumpRecordLayouts) {
  2889. llvm::outs() << "\n*** Dumping AST Record Layout\n";
  2890. DumpRecordLayout(D, llvm::outs(), getLangOpts().DumpRecordLayoutsSimple);
  2891. }
  2892. return *NewEntry;
  2893. }
  2894. const CXXMethodDecl *ASTContext::getCurrentKeyFunction(const CXXRecordDecl *RD) {
  2895. if (!getTargetInfo().getCXXABI().hasKeyFunctions())
  2896. return nullptr;
  2897. assert(RD->getDefinition() && "Cannot get key function for forward decl!");
  2898. RD = RD->getDefinition();
  2899. // Beware:
  2900. // 1) computing the key function might trigger deserialization, which might
  2901. // invalidate iterators into KeyFunctions
  2902. // 2) 'get' on the LazyDeclPtr might also trigger deserialization and
  2903. // invalidate the LazyDeclPtr within the map itself
  2904. LazyDeclPtr Entry = KeyFunctions[RD];
  2905. const Decl *Result =
  2906. Entry ? Entry.get(getExternalSource()) : computeKeyFunction(*this, RD);
  2907. // Store it back if it changed.
  2908. if (Entry.isOffset() || Entry.isValid() != bool(Result))
  2909. KeyFunctions[RD] = const_cast<Decl*>(Result);
  2910. return cast_or_null<CXXMethodDecl>(Result);
  2911. }
  2912. void ASTContext::setNonKeyFunction(const CXXMethodDecl *Method) {
  2913. assert(Method == Method->getFirstDecl() &&
  2914. "not working with method declaration from class definition");
  2915. // Look up the cache entry. Since we're working with the first
  2916. // declaration, its parent must be the class definition, which is
  2917. // the correct key for the KeyFunctions hash.
  2918. const auto &Map = KeyFunctions;
  2919. auto I = Map.find(Method->getParent());
  2920. // If it's not cached, there's nothing to do.
  2921. if (I == Map.end()) return;
  2922. // If it is cached, check whether it's the target method, and if so,
  2923. // remove it from the cache. Note, the call to 'get' might invalidate
  2924. // the iterator and the LazyDeclPtr object within the map.
  2925. LazyDeclPtr Ptr = I->second;
  2926. if (Ptr.get(getExternalSource()) == Method) {
  2927. // FIXME: remember that we did this for module / chained PCH state?
  2928. KeyFunctions.erase(Method->getParent());
  2929. }
  2930. }
  2931. static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) {
  2932. const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent());
  2933. return Layout.getFieldOffset(FD->getFieldIndex());
  2934. }
  2935. uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const {
  2936. uint64_t OffsetInBits;
  2937. if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
  2938. OffsetInBits = ::getFieldOffset(*this, FD);
  2939. } else {
  2940. const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD);
  2941. OffsetInBits = 0;
  2942. for (const NamedDecl *ND : IFD->chain())
  2943. OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(ND));
  2944. }
  2945. return OffsetInBits;
  2946. }
  2947. uint64_t ASTContext::lookupFieldBitOffset(const ObjCInterfaceDecl *OID,
  2948. const ObjCImplementationDecl *ID,
  2949. const ObjCIvarDecl *Ivar) const {
  2950. Ivar = Ivar->getCanonicalDecl();
  2951. const ObjCInterfaceDecl *Container = Ivar->getContainingInterface();
  2952. // FIXME: We should eliminate the need to have ObjCImplementationDecl passed
  2953. // in here; it should never be necessary because that should be the lexical
  2954. // decl context for the ivar.
  2955. // If we know have an implementation (and the ivar is in it) then
  2956. // look up in the implementation layout.
  2957. const ASTRecordLayout *RL;
  2958. if (ID && declaresSameEntity(ID->getClassInterface(), Container))
  2959. RL = &getASTObjCImplementationLayout(ID);
  2960. else
  2961. RL = &getASTObjCInterfaceLayout(Container);
  2962. // Compute field index.
  2963. //
  2964. // FIXME: The index here is closely tied to how ASTContext::getObjCLayout is
  2965. // implemented. This should be fixed to get the information from the layout
  2966. // directly.
  2967. unsigned Index = 0;
  2968. for (const ObjCIvarDecl *IVD = Container->all_declared_ivar_begin();
  2969. IVD; IVD = IVD->getNextIvar()) {
  2970. if (Ivar == IVD)
  2971. break;
  2972. ++Index;
  2973. }
  2974. assert(Index < RL->getFieldCount() && "Ivar is not inside record layout!");
  2975. return RL->getFieldOffset(Index);
  2976. }
  2977. /// getObjCLayout - Get or compute information about the layout of the
  2978. /// given interface.
  2979. ///
  2980. /// \param Impl - If given, also include the layout of the interface's
  2981. /// implementation. This may differ by including synthesized ivars.
  2982. const ASTRecordLayout &
  2983. ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
  2984. const ObjCImplementationDecl *Impl) const {
  2985. // Retrieve the definition
  2986. if (D->hasExternalLexicalStorage() && !D->getDefinition())
  2987. getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl*>(D));
  2988. D = D->getDefinition();
  2989. assert(D && !D->isInvalidDecl() && D->isThisDeclarationADefinition() &&
  2990. "Invalid interface decl!");
  2991. // Look up this layout, if already laid out, return what we have.
  2992. const ObjCContainerDecl *Key =
  2993. Impl ? (const ObjCContainerDecl*) Impl : (const ObjCContainerDecl*) D;
  2994. if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
  2995. return *Entry;
  2996. // Add in synthesized ivar count if laying out an implementation.
  2997. if (Impl) {
  2998. unsigned SynthCount = CountNonClassIvars(D);
  2999. // If there aren't any synthesized ivars then reuse the interface
  3000. // entry. Note we can't cache this because we simply free all
  3001. // entries later; however we shouldn't look up implementations
  3002. // frequently.
  3003. if (SynthCount == 0)
  3004. return getObjCLayout(D, nullptr);
  3005. }
  3006. ItaniumRecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/nullptr);
  3007. Builder.Layout(D);
  3008. const ASTRecordLayout *NewEntry = new (*this) ASTRecordLayout(
  3009. *this, Builder.getSize(), Builder.Alignment, Builder.PreferredAlignment,
  3010. Builder.UnadjustedAlignment,
  3011. /*RequiredAlignment : used by MS-ABI)*/
  3012. Builder.Alignment, Builder.getDataSize(), Builder.FieldOffsets);
  3013. ObjCLayouts[Key] = NewEntry;
  3014. return *NewEntry;
  3015. }
  3016. static void PrintOffset(raw_ostream &OS,
  3017. CharUnits Offset, unsigned IndentLevel) {
  3018. OS << llvm::format("%10" PRId64 " | ", (int64_t)Offset.getQuantity());
  3019. OS.indent(IndentLevel * 2);
  3020. }
  3021. static void PrintBitFieldOffset(raw_ostream &OS, CharUnits Offset,
  3022. unsigned Begin, unsigned Width,
  3023. unsigned IndentLevel) {
  3024. llvm::SmallString<10> Buffer;
  3025. {
  3026. llvm::raw_svector_ostream BufferOS(Buffer);
  3027. BufferOS << Offset.getQuantity() << ':';
  3028. if (Width == 0) {
  3029. BufferOS << '-';
  3030. } else {
  3031. BufferOS << Begin << '-' << (Begin + Width - 1);
  3032. }
  3033. }
  3034. OS << llvm::right_justify(Buffer, 10) << " | ";
  3035. OS.indent(IndentLevel * 2);
  3036. }
  3037. static void PrintIndentNoOffset(raw_ostream &OS, unsigned IndentLevel) {
  3038. OS << " | ";
  3039. OS.indent(IndentLevel * 2);
  3040. }
  3041. static void DumpRecordLayout(raw_ostream &OS, const RecordDecl *RD,
  3042. const ASTContext &C,
  3043. CharUnits Offset,
  3044. unsigned IndentLevel,
  3045. const char* Description,
  3046. bool PrintSizeInfo,
  3047. bool IncludeVirtualBases) {
  3048. const ASTRecordLayout &Layout = C.getASTRecordLayout(RD);
  3049. auto CXXRD = dyn_cast<CXXRecordDecl>(RD);
  3050. PrintOffset(OS, Offset, IndentLevel);
  3051. OS << C.getTypeDeclType(const_cast<RecordDecl *>(RD));
  3052. if (Description)
  3053. OS << ' ' << Description;
  3054. if (CXXRD && CXXRD->isEmpty())
  3055. OS << " (empty)";
  3056. OS << '\n';
  3057. IndentLevel++;
  3058. // Dump bases.
  3059. if (CXXRD) {
  3060. const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
  3061. bool HasOwnVFPtr = Layout.hasOwnVFPtr();
  3062. bool HasOwnVBPtr = Layout.hasOwnVBPtr();
  3063. // Vtable pointer.
  3064. if (CXXRD->isDynamicClass() && !PrimaryBase && !isMsLayout(C)) {
  3065. PrintOffset(OS, Offset, IndentLevel);
  3066. OS << '(' << *RD << " vtable pointer)\n";
  3067. } else if (HasOwnVFPtr) {
  3068. PrintOffset(OS, Offset, IndentLevel);
  3069. // vfptr (for Microsoft C++ ABI)
  3070. OS << '(' << *RD << " vftable pointer)\n";
  3071. }
  3072. // Collect nvbases.
  3073. SmallVector<const CXXRecordDecl *, 4> Bases;
  3074. for (const CXXBaseSpecifier &Base : CXXRD->bases()) {
  3075. assert(!Base.getType()->isDependentType() &&
  3076. "Cannot layout class with dependent bases.");
  3077. if (!Base.isVirtual())
  3078. Bases.push_back(Base.getType()->getAsCXXRecordDecl());
  3079. }
  3080. // Sort nvbases by offset.
  3081. llvm::stable_sort(
  3082. Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
  3083. return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
  3084. });
  3085. // Dump (non-virtual) bases
  3086. for (const CXXRecordDecl *Base : Bases) {
  3087. CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
  3088. DumpRecordLayout(OS, Base, C, BaseOffset, IndentLevel,
  3089. Base == PrimaryBase ? "(primary base)" : "(base)",
  3090. /*PrintSizeInfo=*/false,
  3091. /*IncludeVirtualBases=*/false);
  3092. }
  3093. // vbptr (for Microsoft C++ ABI)
  3094. if (HasOwnVBPtr) {
  3095. PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
  3096. OS << '(' << *RD << " vbtable pointer)\n";
  3097. }
  3098. }
  3099. // Dump fields.
  3100. uint64_t FieldNo = 0;
  3101. for (RecordDecl::field_iterator I = RD->field_begin(),
  3102. E = RD->field_end(); I != E; ++I, ++FieldNo) {
  3103. const FieldDecl &Field = **I;
  3104. uint64_t LocalFieldOffsetInBits = Layout.getFieldOffset(FieldNo);
  3105. CharUnits FieldOffset =
  3106. Offset + C.toCharUnitsFromBits(LocalFieldOffsetInBits);
  3107. // Recursively dump fields of record type.
  3108. if (auto RT = Field.getType()->getAs<RecordType>()) {
  3109. DumpRecordLayout(OS, RT->getDecl(), C, FieldOffset, IndentLevel,
  3110. Field.getName().data(),
  3111. /*PrintSizeInfo=*/false,
  3112. /*IncludeVirtualBases=*/true);
  3113. continue;
  3114. }
  3115. if (Field.isBitField()) {
  3116. uint64_t LocalFieldByteOffsetInBits = C.toBits(FieldOffset - Offset);
  3117. unsigned Begin = LocalFieldOffsetInBits - LocalFieldByteOffsetInBits;
  3118. unsigned Width = Field.getBitWidthValue(C);
  3119. PrintBitFieldOffset(OS, FieldOffset, Begin, Width, IndentLevel);
  3120. } else {
  3121. PrintOffset(OS, FieldOffset, IndentLevel);
  3122. }
  3123. const QualType &FieldType = C.getLangOpts().DumpRecordLayoutsCanonical
  3124. ? Field.getType().getCanonicalType()
  3125. : Field.getType();
  3126. OS << FieldType << ' ' << Field << '\n';
  3127. }
  3128. // Dump virtual bases.
  3129. if (CXXRD && IncludeVirtualBases) {
  3130. const ASTRecordLayout::VBaseOffsetsMapTy &VtorDisps =
  3131. Layout.getVBaseOffsetsMap();
  3132. for (const CXXBaseSpecifier &Base : CXXRD->vbases()) {
  3133. assert(Base.isVirtual() && "Found non-virtual class!");
  3134. const CXXRecordDecl *VBase = Base.getType()->getAsCXXRecordDecl();
  3135. CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
  3136. if (VtorDisps.find(VBase)->second.hasVtorDisp()) {
  3137. PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel);
  3138. OS << "(vtordisp for vbase " << *VBase << ")\n";
  3139. }
  3140. DumpRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel,
  3141. VBase == Layout.getPrimaryBase() ?
  3142. "(primary virtual base)" : "(virtual base)",
  3143. /*PrintSizeInfo=*/false,
  3144. /*IncludeVirtualBases=*/false);
  3145. }
  3146. }
  3147. if (!PrintSizeInfo) return;
  3148. PrintIndentNoOffset(OS, IndentLevel - 1);
  3149. OS << "[sizeof=" << Layout.getSize().getQuantity();
  3150. if (CXXRD && !isMsLayout(C))
  3151. OS << ", dsize=" << Layout.getDataSize().getQuantity();
  3152. OS << ", align=" << Layout.getAlignment().getQuantity();
  3153. if (C.getTargetInfo().defaultsToAIXPowerAlignment())
  3154. OS << ", preferredalign=" << Layout.getPreferredAlignment().getQuantity();
  3155. if (CXXRD) {
  3156. OS << ",\n";
  3157. PrintIndentNoOffset(OS, IndentLevel - 1);
  3158. OS << " nvsize=" << Layout.getNonVirtualSize().getQuantity();
  3159. OS << ", nvalign=" << Layout.getNonVirtualAlignment().getQuantity();
  3160. if (C.getTargetInfo().defaultsToAIXPowerAlignment())
  3161. OS << ", preferrednvalign="
  3162. << Layout.getPreferredNVAlignment().getQuantity();
  3163. }
  3164. OS << "]\n";
  3165. }
  3166. void ASTContext::DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
  3167. bool Simple) const {
  3168. if (!Simple) {
  3169. ::DumpRecordLayout(OS, RD, *this, CharUnits(), 0, nullptr,
  3170. /*PrintSizeInfo*/ true,
  3171. /*IncludeVirtualBases=*/true);
  3172. return;
  3173. }
  3174. // The "simple" format is designed to be parsed by the
  3175. // layout-override testing code. There shouldn't be any external
  3176. // uses of this format --- when LLDB overrides a layout, it sets up
  3177. // the data structures directly --- so feel free to adjust this as
  3178. // you like as long as you also update the rudimentary parser for it
  3179. // in libFrontend.
  3180. const ASTRecordLayout &Info = getASTRecordLayout(RD);
  3181. OS << "Type: " << getTypeDeclType(RD) << "\n";
  3182. OS << "\nLayout: ";
  3183. OS << "<ASTRecordLayout\n";
  3184. OS << " Size:" << toBits(Info.getSize()) << "\n";
  3185. if (!isMsLayout(*this))
  3186. OS << " DataSize:" << toBits(Info.getDataSize()) << "\n";
  3187. OS << " Alignment:" << toBits(Info.getAlignment()) << "\n";
  3188. if (Target->defaultsToAIXPowerAlignment())
  3189. OS << " PreferredAlignment:" << toBits(Info.getPreferredAlignment())
  3190. << "\n";
  3191. OS << " FieldOffsets: [";
  3192. for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) {
  3193. if (i)
  3194. OS << ", ";
  3195. OS << Info.getFieldOffset(i);
  3196. }
  3197. OS << "]>\n";
  3198. }