RecordLayoutBuilder.cpp 132 KB

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