RecordLayoutBuilder.cpp 123 KB

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