CGRecordLayoutBuilder.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  1. //===--- CGRecordLayoutBuilder.cpp - CGRecordLayout builder ----*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Builder implementation for CGRecordLayout objects.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CGRecordLayout.h"
  13. #include "CGCXXABI.h"
  14. #include "CodeGenTypes.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/Attr.h"
  17. #include "clang/AST/CXXInheritance.h"
  18. #include "clang/AST/DeclCXX.h"
  19. #include "clang/AST/Expr.h"
  20. #include "clang/AST/RecordLayout.h"
  21. #include "clang/Basic/CodeGenOptions.h"
  22. #include "llvm/IR/DataLayout.h"
  23. #include "llvm/IR/DerivedTypes.h"
  24. #include "llvm/IR/Type.h"
  25. #include "llvm/Support/Debug.h"
  26. #include "llvm/Support/MathExtras.h"
  27. #include "llvm/Support/raw_ostream.h"
  28. using namespace clang;
  29. using namespace CodeGen;
  30. namespace {
  31. /// The CGRecordLowering is responsible for lowering an ASTRecordLayout to an
  32. /// llvm::Type. Some of the lowering is straightforward, some is not. Here we
  33. /// detail some of the complexities and weirdnesses here.
  34. /// * LLVM does not have unions - Unions can, in theory be represented by any
  35. /// llvm::Type with correct size. We choose a field via a specific heuristic
  36. /// and add padding if necessary.
  37. /// * LLVM does not have bitfields - Bitfields are collected into contiguous
  38. /// runs and allocated as a single storage type for the run. ASTRecordLayout
  39. /// contains enough information to determine where the runs break. Microsoft
  40. /// and Itanium follow different rules and use different codepaths.
  41. /// * It is desired that, when possible, bitfields use the appropriate iN type
  42. /// when lowered to llvm types. For example unsigned x : 24 gets lowered to
  43. /// i24. This isn't always possible because i24 has storage size of 32 bit
  44. /// and if it is possible to use that extra byte of padding we must use
  45. /// [i8 x 3] instead of i24. The function clipTailPadding does this.
  46. /// C++ examples that require clipping:
  47. /// struct { int a : 24; char b; }; // a must be clipped, b goes at offset 3
  48. /// struct A { int a : 24; }; // a must be clipped because a struct like B
  49. // could exist: struct B : A { char b; }; // b goes at offset 3
  50. /// * Clang ignores 0 sized bitfields and 0 sized bases but *not* zero sized
  51. /// fields. The existing asserts suggest that LLVM assumes that *every* field
  52. /// has an underlying storage type. Therefore empty structures containing
  53. /// zero sized subobjects such as empty records or zero sized arrays still get
  54. /// a zero sized (empty struct) storage type.
  55. /// * Clang reads the complete type rather than the base type when generating
  56. /// code to access fields. Bitfields in tail position with tail padding may
  57. /// be clipped in the base class but not the complete class (we may discover
  58. /// that the tail padding is not used in the complete class.) However,
  59. /// because LLVM reads from the complete type it can generate incorrect code
  60. /// if we do not clip the tail padding off of the bitfield in the complete
  61. /// layout. This introduces a somewhat awkward extra unnecessary clip stage.
  62. /// The location of the clip is stored internally as a sentinel of type
  63. /// SCISSOR. If LLVM were updated to read base types (which it probably
  64. /// should because locations of things such as VBases are bogus in the llvm
  65. /// type anyway) then we could eliminate the SCISSOR.
  66. /// * Itanium allows nearly empty primary virtual bases. These bases don't get
  67. /// get their own storage because they're laid out as part of another base
  68. /// or at the beginning of the structure. Determining if a VBase actually
  69. /// gets storage awkwardly involves a walk of all bases.
  70. /// * VFPtrs and VBPtrs do *not* make a record NotZeroInitializable.
  71. struct CGRecordLowering {
  72. // MemberInfo is a helper structure that contains information about a record
  73. // member. In additional to the standard member types, there exists a
  74. // sentinel member type that ensures correct rounding.
  75. struct MemberInfo {
  76. CharUnits Offset;
  77. enum InfoKind { VFPtr, VBPtr, Field, Base, VBase, Scissor } Kind;
  78. llvm::Type *Data;
  79. union {
  80. const FieldDecl *FD;
  81. const CXXRecordDecl *RD;
  82. };
  83. MemberInfo(CharUnits Offset, InfoKind Kind, llvm::Type *Data,
  84. const FieldDecl *FD = nullptr)
  85. : Offset(Offset), Kind(Kind), Data(Data), FD(FD) {}
  86. MemberInfo(CharUnits Offset, InfoKind Kind, llvm::Type *Data,
  87. const CXXRecordDecl *RD)
  88. : Offset(Offset), Kind(Kind), Data(Data), RD(RD) {}
  89. // MemberInfos are sorted so we define a < operator.
  90. bool operator <(const MemberInfo& a) const { return Offset < a.Offset; }
  91. };
  92. // The constructor.
  93. CGRecordLowering(CodeGenTypes &Types, const RecordDecl *D, bool Packed);
  94. // Short helper routines.
  95. /// Constructs a MemberInfo instance from an offset and llvm::Type *.
  96. MemberInfo StorageInfo(CharUnits Offset, llvm::Type *Data) {
  97. return MemberInfo(Offset, MemberInfo::Field, Data);
  98. }
  99. /// The Microsoft bitfield layout rule allocates discrete storage
  100. /// units of the field's formal type and only combines adjacent
  101. /// fields of the same formal type. We want to emit a layout with
  102. /// these discrete storage units instead of combining them into a
  103. /// continuous run.
  104. bool isDiscreteBitFieldABI() {
  105. return Context.getTargetInfo().getCXXABI().isMicrosoft() ||
  106. D->isMsStruct(Context);
  107. }
  108. /// Helper function to check if we are targeting AAPCS.
  109. bool isAAPCS() const {
  110. return Context.getTargetInfo().getABI().startswith("aapcs");
  111. }
  112. /// Helper function to check if the target machine is BigEndian.
  113. bool isBE() const { return Context.getTargetInfo().isBigEndian(); }
  114. /// The Itanium base layout rule allows virtual bases to overlap
  115. /// other bases, which complicates layout in specific ways.
  116. ///
  117. /// Note specifically that the ms_struct attribute doesn't change this.
  118. bool isOverlappingVBaseABI() {
  119. return !Context.getTargetInfo().getCXXABI().isMicrosoft();
  120. }
  121. /// Wraps llvm::Type::getIntNTy with some implicit arguments.
  122. llvm::Type *getIntNType(uint64_t NumBits) {
  123. unsigned AlignedBits = llvm::alignTo(NumBits, Context.getCharWidth());
  124. return llvm::Type::getIntNTy(Types.getLLVMContext(), AlignedBits);
  125. }
  126. /// Get the LLVM type sized as one character unit.
  127. llvm::Type *getCharType() {
  128. return llvm::Type::getIntNTy(Types.getLLVMContext(),
  129. Context.getCharWidth());
  130. }
  131. /// Gets an llvm type of size NumChars and alignment 1.
  132. llvm::Type *getByteArrayType(CharUnits NumChars) {
  133. assert(!NumChars.isZero() && "Empty byte arrays aren't allowed.");
  134. llvm::Type *Type = getCharType();
  135. return NumChars == CharUnits::One() ? Type :
  136. (llvm::Type *)llvm::ArrayType::get(Type, NumChars.getQuantity());
  137. }
  138. /// Gets the storage type for a field decl and handles storage
  139. /// for itanium bitfields that are smaller than their declared type.
  140. llvm::Type *getStorageType(const FieldDecl *FD) {
  141. llvm::Type *Type = Types.ConvertTypeForMem(FD->getType());
  142. if (!FD->isBitField()) return Type;
  143. if (isDiscreteBitFieldABI()) return Type;
  144. return getIntNType(std::min(FD->getBitWidthValue(Context),
  145. (unsigned)Context.toBits(getSize(Type))));
  146. }
  147. /// Gets the llvm Basesubobject type from a CXXRecordDecl.
  148. llvm::Type *getStorageType(const CXXRecordDecl *RD) {
  149. return Types.getCGRecordLayout(RD).getBaseSubobjectLLVMType();
  150. }
  151. CharUnits bitsToCharUnits(uint64_t BitOffset) {
  152. return Context.toCharUnitsFromBits(BitOffset);
  153. }
  154. CharUnits getSize(llvm::Type *Type) {
  155. return CharUnits::fromQuantity(DataLayout.getTypeAllocSize(Type));
  156. }
  157. CharUnits getAlignment(llvm::Type *Type) {
  158. return CharUnits::fromQuantity(DataLayout.getABITypeAlignment(Type));
  159. }
  160. bool isZeroInitializable(const FieldDecl *FD) {
  161. return Types.isZeroInitializable(FD->getType());
  162. }
  163. bool isZeroInitializable(const RecordDecl *RD) {
  164. return Types.isZeroInitializable(RD);
  165. }
  166. void appendPaddingBytes(CharUnits Size) {
  167. if (!Size.isZero())
  168. FieldTypes.push_back(getByteArrayType(Size));
  169. }
  170. uint64_t getFieldBitOffset(const FieldDecl *FD) {
  171. return Layout.getFieldOffset(FD->getFieldIndex());
  172. }
  173. // Layout routines.
  174. void setBitFieldInfo(const FieldDecl *FD, CharUnits StartOffset,
  175. llvm::Type *StorageType);
  176. /// Lowers an ASTRecordLayout to a llvm type.
  177. void lower(bool NonVirtualBaseType);
  178. void lowerUnion();
  179. void accumulateFields();
  180. void accumulateBitFields(RecordDecl::field_iterator Field,
  181. RecordDecl::field_iterator FieldEnd);
  182. void computeVolatileBitfields();
  183. void accumulateBases();
  184. void accumulateVPtrs();
  185. void accumulateVBases();
  186. /// Recursively searches all of the bases to find out if a vbase is
  187. /// not the primary vbase of some base class.
  188. bool hasOwnStorage(const CXXRecordDecl *Decl, const CXXRecordDecl *Query);
  189. void calculateZeroInit();
  190. /// Lowers bitfield storage types to I8 arrays for bitfields with tail
  191. /// padding that is or can potentially be used.
  192. void clipTailPadding();
  193. /// Determines if we need a packed llvm struct.
  194. void determinePacked(bool NVBaseType);
  195. /// Inserts padding everywhere it's needed.
  196. void insertPadding();
  197. /// Fills out the structures that are ultimately consumed.
  198. void fillOutputFields();
  199. // Input memoization fields.
  200. CodeGenTypes &Types;
  201. const ASTContext &Context;
  202. const RecordDecl *D;
  203. const CXXRecordDecl *RD;
  204. const ASTRecordLayout &Layout;
  205. const llvm::DataLayout &DataLayout;
  206. // Helpful intermediate data-structures.
  207. std::vector<MemberInfo> Members;
  208. // Output fields, consumed by CodeGenTypes::ComputeRecordLayout.
  209. SmallVector<llvm::Type *, 16> FieldTypes;
  210. llvm::DenseMap<const FieldDecl *, unsigned> Fields;
  211. llvm::DenseMap<const FieldDecl *, CGBitFieldInfo> BitFields;
  212. llvm::DenseMap<const CXXRecordDecl *, unsigned> NonVirtualBases;
  213. llvm::DenseMap<const CXXRecordDecl *, unsigned> VirtualBases;
  214. bool IsZeroInitializable : 1;
  215. bool IsZeroInitializableAsBase : 1;
  216. bool Packed : 1;
  217. private:
  218. CGRecordLowering(const CGRecordLowering &) = delete;
  219. void operator =(const CGRecordLowering &) = delete;
  220. };
  221. } // namespace {
  222. CGRecordLowering::CGRecordLowering(CodeGenTypes &Types, const RecordDecl *D,
  223. bool Packed)
  224. : Types(Types), Context(Types.getContext()), D(D),
  225. RD(dyn_cast<CXXRecordDecl>(D)),
  226. Layout(Types.getContext().getASTRecordLayout(D)),
  227. DataLayout(Types.getDataLayout()), IsZeroInitializable(true),
  228. IsZeroInitializableAsBase(true), Packed(Packed) {}
  229. void CGRecordLowering::setBitFieldInfo(
  230. const FieldDecl *FD, CharUnits StartOffset, llvm::Type *StorageType) {
  231. CGBitFieldInfo &Info = BitFields[FD->getCanonicalDecl()];
  232. Info.IsSigned = FD->getType()->isSignedIntegerOrEnumerationType();
  233. Info.Offset = (unsigned)(getFieldBitOffset(FD) - Context.toBits(StartOffset));
  234. Info.Size = FD->getBitWidthValue(Context);
  235. Info.StorageSize = (unsigned)DataLayout.getTypeAllocSizeInBits(StorageType);
  236. Info.StorageOffset = StartOffset;
  237. if (Info.Size > Info.StorageSize)
  238. Info.Size = Info.StorageSize;
  239. // Reverse the bit offsets for big endian machines. Because we represent
  240. // a bitfield as a single large integer load, we can imagine the bits
  241. // counting from the most-significant-bit instead of the
  242. // least-significant-bit.
  243. if (DataLayout.isBigEndian())
  244. Info.Offset = Info.StorageSize - (Info.Offset + Info.Size);
  245. Info.VolatileStorageSize = 0;
  246. Info.VolatileOffset = 0;
  247. Info.VolatileStorageOffset = CharUnits::Zero();
  248. }
  249. void CGRecordLowering::lower(bool NVBaseType) {
  250. // The lowering process implemented in this function takes a variety of
  251. // carefully ordered phases.
  252. // 1) Store all members (fields and bases) in a list and sort them by offset.
  253. // 2) Add a 1-byte capstone member at the Size of the structure.
  254. // 3) Clip bitfield storages members if their tail padding is or might be
  255. // used by another field or base. The clipping process uses the capstone
  256. // by treating it as another object that occurs after the record.
  257. // 4) Determine if the llvm-struct requires packing. It's important that this
  258. // phase occur after clipping, because clipping changes the llvm type.
  259. // This phase reads the offset of the capstone when determining packedness
  260. // and updates the alignment of the capstone to be equal of the alignment
  261. // of the record after doing so.
  262. // 5) Insert padding everywhere it is needed. This phase requires 'Packed' to
  263. // have been computed and needs to know the alignment of the record in
  264. // order to understand if explicit tail padding is needed.
  265. // 6) Remove the capstone, we don't need it anymore.
  266. // 7) Determine if this record can be zero-initialized. This phase could have
  267. // been placed anywhere after phase 1.
  268. // 8) Format the complete list of members in a way that can be consumed by
  269. // CodeGenTypes::ComputeRecordLayout.
  270. CharUnits Size = NVBaseType ? Layout.getNonVirtualSize() : Layout.getSize();
  271. if (D->isUnion()) {
  272. lowerUnion();
  273. computeVolatileBitfields();
  274. return;
  275. }
  276. accumulateFields();
  277. // RD implies C++.
  278. if (RD) {
  279. accumulateVPtrs();
  280. accumulateBases();
  281. if (Members.empty()) {
  282. appendPaddingBytes(Size);
  283. computeVolatileBitfields();
  284. return;
  285. }
  286. if (!NVBaseType)
  287. accumulateVBases();
  288. }
  289. llvm::stable_sort(Members);
  290. Members.push_back(StorageInfo(Size, getIntNType(8)));
  291. clipTailPadding();
  292. determinePacked(NVBaseType);
  293. insertPadding();
  294. Members.pop_back();
  295. calculateZeroInit();
  296. fillOutputFields();
  297. computeVolatileBitfields();
  298. }
  299. void CGRecordLowering::lowerUnion() {
  300. CharUnits LayoutSize = Layout.getSize();
  301. llvm::Type *StorageType = nullptr;
  302. bool SeenNamedMember = false;
  303. // Iterate through the fields setting bitFieldInfo and the Fields array. Also
  304. // locate the "most appropriate" storage type. The heuristic for finding the
  305. // storage type isn't necessary, the first (non-0-length-bitfield) field's
  306. // type would work fine and be simpler but would be different than what we've
  307. // been doing and cause lit tests to change.
  308. for (const auto *Field : D->fields()) {
  309. if (Field->isBitField()) {
  310. if (Field->isZeroLengthBitField(Context))
  311. continue;
  312. llvm::Type *FieldType = getStorageType(Field);
  313. if (LayoutSize < getSize(FieldType))
  314. FieldType = getByteArrayType(LayoutSize);
  315. setBitFieldInfo(Field, CharUnits::Zero(), FieldType);
  316. }
  317. Fields[Field->getCanonicalDecl()] = 0;
  318. llvm::Type *FieldType = getStorageType(Field);
  319. // Compute zero-initializable status.
  320. // This union might not be zero initialized: it may contain a pointer to
  321. // data member which might have some exotic initialization sequence.
  322. // If this is the case, then we aught not to try and come up with a "better"
  323. // type, it might not be very easy to come up with a Constant which
  324. // correctly initializes it.
  325. if (!SeenNamedMember) {
  326. SeenNamedMember = Field->getIdentifier();
  327. if (!SeenNamedMember)
  328. if (const auto *FieldRD = Field->getType()->getAsRecordDecl())
  329. SeenNamedMember = FieldRD->findFirstNamedDataMember();
  330. if (SeenNamedMember && !isZeroInitializable(Field)) {
  331. IsZeroInitializable = IsZeroInitializableAsBase = false;
  332. StorageType = FieldType;
  333. }
  334. }
  335. // Because our union isn't zero initializable, we won't be getting a better
  336. // storage type.
  337. if (!IsZeroInitializable)
  338. continue;
  339. // Conditionally update our storage type if we've got a new "better" one.
  340. if (!StorageType ||
  341. getAlignment(FieldType) > getAlignment(StorageType) ||
  342. (getAlignment(FieldType) == getAlignment(StorageType) &&
  343. getSize(FieldType) > getSize(StorageType)))
  344. StorageType = FieldType;
  345. }
  346. // If we have no storage type just pad to the appropriate size and return.
  347. if (!StorageType)
  348. return appendPaddingBytes(LayoutSize);
  349. // If our storage size was bigger than our required size (can happen in the
  350. // case of packed bitfields on Itanium) then just use an I8 array.
  351. if (LayoutSize < getSize(StorageType))
  352. StorageType = getByteArrayType(LayoutSize);
  353. FieldTypes.push_back(StorageType);
  354. appendPaddingBytes(LayoutSize - getSize(StorageType));
  355. // Set packed if we need it.
  356. if (LayoutSize % getAlignment(StorageType))
  357. Packed = true;
  358. }
  359. void CGRecordLowering::accumulateFields() {
  360. for (RecordDecl::field_iterator Field = D->field_begin(),
  361. FieldEnd = D->field_end();
  362. Field != FieldEnd;) {
  363. if (Field->isBitField()) {
  364. RecordDecl::field_iterator Start = Field;
  365. // Iterate to gather the list of bitfields.
  366. for (++Field; Field != FieldEnd && Field->isBitField(); ++Field);
  367. accumulateBitFields(Start, Field);
  368. } else if (!Field->isZeroSize(Context)) {
  369. Members.push_back(MemberInfo(
  370. bitsToCharUnits(getFieldBitOffset(*Field)), MemberInfo::Field,
  371. getStorageType(*Field), *Field));
  372. ++Field;
  373. } else {
  374. ++Field;
  375. }
  376. }
  377. }
  378. void
  379. CGRecordLowering::accumulateBitFields(RecordDecl::field_iterator Field,
  380. RecordDecl::field_iterator FieldEnd) {
  381. // Run stores the first element of the current run of bitfields. FieldEnd is
  382. // used as a special value to note that we don't have a current run. A
  383. // bitfield run is a contiguous collection of bitfields that can be stored in
  384. // the same storage block. Zero-sized bitfields and bitfields that would
  385. // cross an alignment boundary break a run and start a new one.
  386. RecordDecl::field_iterator Run = FieldEnd;
  387. // Tail is the offset of the first bit off the end of the current run. It's
  388. // used to determine if the ASTRecordLayout is treating these two bitfields as
  389. // contiguous. StartBitOffset is offset of the beginning of the Run.
  390. uint64_t StartBitOffset, Tail = 0;
  391. if (isDiscreteBitFieldABI()) {
  392. for (; Field != FieldEnd; ++Field) {
  393. uint64_t BitOffset = getFieldBitOffset(*Field);
  394. // Zero-width bitfields end runs.
  395. if (Field->isZeroLengthBitField(Context)) {
  396. Run = FieldEnd;
  397. continue;
  398. }
  399. llvm::Type *Type =
  400. Types.ConvertTypeForMem(Field->getType(), /*ForBitField=*/true);
  401. // If we don't have a run yet, or don't live within the previous run's
  402. // allocated storage then we allocate some storage and start a new run.
  403. if (Run == FieldEnd || BitOffset >= Tail) {
  404. Run = Field;
  405. StartBitOffset = BitOffset;
  406. Tail = StartBitOffset + DataLayout.getTypeAllocSizeInBits(Type);
  407. // Add the storage member to the record. This must be added to the
  408. // record before the bitfield members so that it gets laid out before
  409. // the bitfields it contains get laid out.
  410. Members.push_back(StorageInfo(bitsToCharUnits(StartBitOffset), Type));
  411. }
  412. // Bitfields get the offset of their storage but come afterward and remain
  413. // there after a stable sort.
  414. Members.push_back(MemberInfo(bitsToCharUnits(StartBitOffset),
  415. MemberInfo::Field, nullptr, *Field));
  416. }
  417. return;
  418. }
  419. // Check if OffsetInRecord (the size in bits of the current run) is better
  420. // as a single field run. When OffsetInRecord has legal integer width, and
  421. // its bitfield offset is naturally aligned, it is better to make the
  422. // bitfield a separate storage component so as it can be accessed directly
  423. // with lower cost.
  424. auto IsBetterAsSingleFieldRun = [&](uint64_t OffsetInRecord,
  425. uint64_t StartBitOffset) {
  426. if (!Types.getCodeGenOpts().FineGrainedBitfieldAccesses)
  427. return false;
  428. if (OffsetInRecord < 8 || !llvm::isPowerOf2_64(OffsetInRecord) ||
  429. !DataLayout.fitsInLegalInteger(OffsetInRecord))
  430. return false;
  431. // Make sure StartBitOffset is naturally aligned if it is treated as an
  432. // IType integer.
  433. if (StartBitOffset %
  434. Context.toBits(getAlignment(getIntNType(OffsetInRecord))) !=
  435. 0)
  436. return false;
  437. return true;
  438. };
  439. // The start field is better as a single field run.
  440. bool StartFieldAsSingleRun = false;
  441. for (;;) {
  442. // Check to see if we need to start a new run.
  443. if (Run == FieldEnd) {
  444. // If we're out of fields, return.
  445. if (Field == FieldEnd)
  446. break;
  447. // Any non-zero-length bitfield can start a new run.
  448. if (!Field->isZeroLengthBitField(Context)) {
  449. Run = Field;
  450. StartBitOffset = getFieldBitOffset(*Field);
  451. Tail = StartBitOffset + Field->getBitWidthValue(Context);
  452. StartFieldAsSingleRun = IsBetterAsSingleFieldRun(Tail - StartBitOffset,
  453. StartBitOffset);
  454. }
  455. ++Field;
  456. continue;
  457. }
  458. // If the start field of a new run is better as a single run, or
  459. // if current field (or consecutive fields) is better as a single run, or
  460. // if current field has zero width bitfield and either
  461. // UseZeroLengthBitfieldAlignment or UseBitFieldTypeAlignment is set to
  462. // true, or
  463. // if the offset of current field is inconsistent with the offset of
  464. // previous field plus its offset,
  465. // skip the block below and go ahead to emit the storage.
  466. // Otherwise, try to add bitfields to the run.
  467. if (!StartFieldAsSingleRun && Field != FieldEnd &&
  468. !IsBetterAsSingleFieldRun(Tail - StartBitOffset, StartBitOffset) &&
  469. (!Field->isZeroLengthBitField(Context) ||
  470. (!Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
  471. !Context.getTargetInfo().useBitFieldTypeAlignment())) &&
  472. Tail == getFieldBitOffset(*Field)) {
  473. Tail += Field->getBitWidthValue(Context);
  474. ++Field;
  475. continue;
  476. }
  477. // We've hit a break-point in the run and need to emit a storage field.
  478. llvm::Type *Type = getIntNType(Tail - StartBitOffset);
  479. // Add the storage member to the record and set the bitfield info for all of
  480. // the bitfields in the run. Bitfields get the offset of their storage but
  481. // come afterward and remain there after a stable sort.
  482. Members.push_back(StorageInfo(bitsToCharUnits(StartBitOffset), Type));
  483. for (; Run != Field; ++Run)
  484. Members.push_back(MemberInfo(bitsToCharUnits(StartBitOffset),
  485. MemberInfo::Field, nullptr, *Run));
  486. Run = FieldEnd;
  487. StartFieldAsSingleRun = false;
  488. }
  489. }
  490. void CGRecordLowering::accumulateBases() {
  491. // If we've got a primary virtual base, we need to add it with the bases.
  492. if (Layout.isPrimaryBaseVirtual()) {
  493. const CXXRecordDecl *BaseDecl = Layout.getPrimaryBase();
  494. Members.push_back(MemberInfo(CharUnits::Zero(), MemberInfo::Base,
  495. getStorageType(BaseDecl), BaseDecl));
  496. }
  497. // Accumulate the non-virtual bases.
  498. for (const auto &Base : RD->bases()) {
  499. if (Base.isVirtual())
  500. continue;
  501. // Bases can be zero-sized even if not technically empty if they
  502. // contain only a trailing array member.
  503. const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
  504. if (!BaseDecl->isEmpty() &&
  505. !Context.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
  506. Members.push_back(MemberInfo(Layout.getBaseClassOffset(BaseDecl),
  507. MemberInfo::Base, getStorageType(BaseDecl), BaseDecl));
  508. }
  509. }
  510. /// The AAPCS that defines that, when possible, bit-fields should
  511. /// be accessed using containers of the declared type width:
  512. /// When a volatile bit-field is read, and its container does not overlap with
  513. /// any non-bit-field member or any zero length bit-field member, its container
  514. /// must be read exactly once using the access width appropriate to the type of
  515. /// the container. When a volatile bit-field is written, and its container does
  516. /// not overlap with any non-bit-field member or any zero-length bit-field
  517. /// member, its container must be read exactly once and written exactly once
  518. /// using the access width appropriate to the type of the container. The two
  519. /// accesses are not atomic.
  520. ///
  521. /// Enforcing the width restriction can be disabled using
  522. /// -fno-aapcs-bitfield-width.
  523. void CGRecordLowering::computeVolatileBitfields() {
  524. if (!isAAPCS() || !Types.getCodeGenOpts().AAPCSBitfieldWidth)
  525. return;
  526. for (auto &I : BitFields) {
  527. const FieldDecl *Field = I.first;
  528. CGBitFieldInfo &Info = I.second;
  529. llvm::Type *ResLTy = Types.ConvertTypeForMem(Field->getType());
  530. // If the record alignment is less than the type width, we can't enforce a
  531. // aligned load, bail out.
  532. if ((uint64_t)(Context.toBits(Layout.getAlignment())) <
  533. ResLTy->getPrimitiveSizeInBits())
  534. continue;
  535. // CGRecordLowering::setBitFieldInfo() pre-adjusts the bit-field offsets
  536. // for big-endian targets, but it assumes a container of width
  537. // Info.StorageSize. Since AAPCS uses a different container size (width
  538. // of the type), we first undo that calculation here and redo it once
  539. // the bit-field offset within the new container is calculated.
  540. const unsigned OldOffset =
  541. isBE() ? Info.StorageSize - (Info.Offset + Info.Size) : Info.Offset;
  542. // Offset to the bit-field from the beginning of the struct.
  543. const unsigned AbsoluteOffset =
  544. Context.toBits(Info.StorageOffset) + OldOffset;
  545. // Container size is the width of the bit-field type.
  546. const unsigned StorageSize = ResLTy->getPrimitiveSizeInBits();
  547. // Nothing to do if the access uses the desired
  548. // container width and is naturally aligned.
  549. if (Info.StorageSize == StorageSize && (OldOffset % StorageSize == 0))
  550. continue;
  551. // Offset within the container.
  552. unsigned Offset = AbsoluteOffset & (StorageSize - 1);
  553. // Bail out if an aligned load of the container cannot cover the entire
  554. // bit-field. This can happen for example, if the bit-field is part of a
  555. // packed struct. AAPCS does not define access rules for such cases, we let
  556. // clang to follow its own rules.
  557. if (Offset + Info.Size > StorageSize)
  558. continue;
  559. // Re-adjust offsets for big-endian targets.
  560. if (isBE())
  561. Offset = StorageSize - (Offset + Info.Size);
  562. const CharUnits StorageOffset =
  563. Context.toCharUnitsFromBits(AbsoluteOffset & ~(StorageSize - 1));
  564. const CharUnits End = StorageOffset +
  565. Context.toCharUnitsFromBits(StorageSize) -
  566. CharUnits::One();
  567. const ASTRecordLayout &Layout =
  568. Context.getASTRecordLayout(Field->getParent());
  569. // If we access outside memory outside the record, than bail out.
  570. const CharUnits RecordSize = Layout.getSize();
  571. if (End >= RecordSize)
  572. continue;
  573. // Bail out if performing this load would access non-bit-fields members.
  574. bool Conflict = false;
  575. for (const auto *F : D->fields()) {
  576. // Allow sized bit-fields overlaps.
  577. if (F->isBitField() && !F->isZeroLengthBitField(Context))
  578. continue;
  579. const CharUnits FOffset = Context.toCharUnitsFromBits(
  580. Layout.getFieldOffset(F->getFieldIndex()));
  581. // As C11 defines, a zero sized bit-field defines a barrier, so
  582. // fields after and before it should be race condition free.
  583. // The AAPCS acknowledges it and imposes no restritions when the
  584. // natural container overlaps a zero-length bit-field.
  585. if (F->isZeroLengthBitField(Context)) {
  586. if (End > FOffset && StorageOffset < FOffset) {
  587. Conflict = true;
  588. break;
  589. }
  590. }
  591. const CharUnits FEnd =
  592. FOffset +
  593. Context.toCharUnitsFromBits(
  594. Types.ConvertTypeForMem(F->getType())->getPrimitiveSizeInBits()) -
  595. CharUnits::One();
  596. // If no overlap, continue.
  597. if (End < FOffset || FEnd < StorageOffset)
  598. continue;
  599. // The desired load overlaps a non-bit-field member, bail out.
  600. Conflict = true;
  601. break;
  602. }
  603. if (Conflict)
  604. continue;
  605. // Write the new bit-field access parameters.
  606. // As the storage offset now is defined as the number of elements from the
  607. // start of the structure, we should divide the Offset by the element size.
  608. Info.VolatileStorageOffset =
  609. StorageOffset / Context.toCharUnitsFromBits(StorageSize).getQuantity();
  610. Info.VolatileStorageSize = StorageSize;
  611. Info.VolatileOffset = Offset;
  612. }
  613. }
  614. void CGRecordLowering::accumulateVPtrs() {
  615. if (Layout.hasOwnVFPtr())
  616. Members.push_back(MemberInfo(CharUnits::Zero(), MemberInfo::VFPtr,
  617. llvm::FunctionType::get(getIntNType(32), /*isVarArg=*/true)->
  618. getPointerTo()->getPointerTo()));
  619. if (Layout.hasOwnVBPtr())
  620. Members.push_back(MemberInfo(Layout.getVBPtrOffset(), MemberInfo::VBPtr,
  621. llvm::Type::getInt32PtrTy(Types.getLLVMContext())));
  622. }
  623. void CGRecordLowering::accumulateVBases() {
  624. CharUnits ScissorOffset = Layout.getNonVirtualSize();
  625. // In the itanium ABI, it's possible to place a vbase at a dsize that is
  626. // smaller than the nvsize. Here we check to see if such a base is placed
  627. // before the nvsize and set the scissor offset to that, instead of the
  628. // nvsize.
  629. if (isOverlappingVBaseABI())
  630. for (const auto &Base : RD->vbases()) {
  631. const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
  632. if (BaseDecl->isEmpty())
  633. continue;
  634. // If the vbase is a primary virtual base of some base, then it doesn't
  635. // get its own storage location but instead lives inside of that base.
  636. if (Context.isNearlyEmpty(BaseDecl) && !hasOwnStorage(RD, BaseDecl))
  637. continue;
  638. ScissorOffset = std::min(ScissorOffset,
  639. Layout.getVBaseClassOffset(BaseDecl));
  640. }
  641. Members.push_back(MemberInfo(ScissorOffset, MemberInfo::Scissor, nullptr,
  642. RD));
  643. for (const auto &Base : RD->vbases()) {
  644. const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
  645. if (BaseDecl->isEmpty())
  646. continue;
  647. CharUnits Offset = Layout.getVBaseClassOffset(BaseDecl);
  648. // If the vbase is a primary virtual base of some base, then it doesn't
  649. // get its own storage location but instead lives inside of that base.
  650. if (isOverlappingVBaseABI() &&
  651. Context.isNearlyEmpty(BaseDecl) &&
  652. !hasOwnStorage(RD, BaseDecl)) {
  653. Members.push_back(MemberInfo(Offset, MemberInfo::VBase, nullptr,
  654. BaseDecl));
  655. continue;
  656. }
  657. // If we've got a vtordisp, add it as a storage type.
  658. if (Layout.getVBaseOffsetsMap().find(BaseDecl)->second.hasVtorDisp())
  659. Members.push_back(StorageInfo(Offset - CharUnits::fromQuantity(4),
  660. getIntNType(32)));
  661. Members.push_back(MemberInfo(Offset, MemberInfo::VBase,
  662. getStorageType(BaseDecl), BaseDecl));
  663. }
  664. }
  665. bool CGRecordLowering::hasOwnStorage(const CXXRecordDecl *Decl,
  666. const CXXRecordDecl *Query) {
  667. const ASTRecordLayout &DeclLayout = Context.getASTRecordLayout(Decl);
  668. if (DeclLayout.isPrimaryBaseVirtual() && DeclLayout.getPrimaryBase() == Query)
  669. return false;
  670. for (const auto &Base : Decl->bases())
  671. if (!hasOwnStorage(Base.getType()->getAsCXXRecordDecl(), Query))
  672. return false;
  673. return true;
  674. }
  675. void CGRecordLowering::calculateZeroInit() {
  676. for (std::vector<MemberInfo>::const_iterator Member = Members.begin(),
  677. MemberEnd = Members.end();
  678. IsZeroInitializableAsBase && Member != MemberEnd; ++Member) {
  679. if (Member->Kind == MemberInfo::Field) {
  680. if (!Member->FD || isZeroInitializable(Member->FD))
  681. continue;
  682. IsZeroInitializable = IsZeroInitializableAsBase = false;
  683. } else if (Member->Kind == MemberInfo::Base ||
  684. Member->Kind == MemberInfo::VBase) {
  685. if (isZeroInitializable(Member->RD))
  686. continue;
  687. IsZeroInitializable = false;
  688. if (Member->Kind == MemberInfo::Base)
  689. IsZeroInitializableAsBase = false;
  690. }
  691. }
  692. }
  693. void CGRecordLowering::clipTailPadding() {
  694. std::vector<MemberInfo>::iterator Prior = Members.begin();
  695. CharUnits Tail = getSize(Prior->Data);
  696. for (std::vector<MemberInfo>::iterator Member = Prior + 1,
  697. MemberEnd = Members.end();
  698. Member != MemberEnd; ++Member) {
  699. // Only members with data and the scissor can cut into tail padding.
  700. if (!Member->Data && Member->Kind != MemberInfo::Scissor)
  701. continue;
  702. if (Member->Offset < Tail) {
  703. assert(Prior->Kind == MemberInfo::Field &&
  704. "Only storage fields have tail padding!");
  705. if (!Prior->FD || Prior->FD->isBitField())
  706. Prior->Data = getByteArrayType(bitsToCharUnits(llvm::alignTo(
  707. cast<llvm::IntegerType>(Prior->Data)->getIntegerBitWidth(), 8)));
  708. else {
  709. assert(Prior->FD->hasAttr<NoUniqueAddressAttr>() &&
  710. "should not have reused this field's tail padding");
  711. Prior->Data = getByteArrayType(
  712. Context.getTypeInfoDataSizeInChars(Prior->FD->getType()).Width);
  713. }
  714. }
  715. if (Member->Data)
  716. Prior = Member;
  717. Tail = Prior->Offset + getSize(Prior->Data);
  718. }
  719. }
  720. void CGRecordLowering::determinePacked(bool NVBaseType) {
  721. if (Packed)
  722. return;
  723. CharUnits Alignment = CharUnits::One();
  724. CharUnits NVAlignment = CharUnits::One();
  725. CharUnits NVSize =
  726. !NVBaseType && RD ? Layout.getNonVirtualSize() : CharUnits::Zero();
  727. for (std::vector<MemberInfo>::const_iterator Member = Members.begin(),
  728. MemberEnd = Members.end();
  729. Member != MemberEnd; ++Member) {
  730. if (!Member->Data)
  731. continue;
  732. // If any member falls at an offset that it not a multiple of its alignment,
  733. // then the entire record must be packed.
  734. if (Member->Offset % getAlignment(Member->Data))
  735. Packed = true;
  736. if (Member->Offset < NVSize)
  737. NVAlignment = std::max(NVAlignment, getAlignment(Member->Data));
  738. Alignment = std::max(Alignment, getAlignment(Member->Data));
  739. }
  740. // If the size of the record (the capstone's offset) is not a multiple of the
  741. // record's alignment, it must be packed.
  742. if (Members.back().Offset % Alignment)
  743. Packed = true;
  744. // If the non-virtual sub-object is not a multiple of the non-virtual
  745. // sub-object's alignment, it must be packed. We cannot have a packed
  746. // non-virtual sub-object and an unpacked complete object or vise versa.
  747. if (NVSize % NVAlignment)
  748. Packed = true;
  749. // Update the alignment of the sentinel.
  750. if (!Packed)
  751. Members.back().Data = getIntNType(Context.toBits(Alignment));
  752. }
  753. void CGRecordLowering::insertPadding() {
  754. std::vector<std::pair<CharUnits, CharUnits> > Padding;
  755. CharUnits Size = CharUnits::Zero();
  756. for (std::vector<MemberInfo>::const_iterator Member = Members.begin(),
  757. MemberEnd = Members.end();
  758. Member != MemberEnd; ++Member) {
  759. if (!Member->Data)
  760. continue;
  761. CharUnits Offset = Member->Offset;
  762. assert(Offset >= Size);
  763. // Insert padding if we need to.
  764. if (Offset !=
  765. Size.alignTo(Packed ? CharUnits::One() : getAlignment(Member->Data)))
  766. Padding.push_back(std::make_pair(Size, Offset - Size));
  767. Size = Offset + getSize(Member->Data);
  768. }
  769. if (Padding.empty())
  770. return;
  771. // Add the padding to the Members list and sort it.
  772. for (std::vector<std::pair<CharUnits, CharUnits> >::const_iterator
  773. Pad = Padding.begin(), PadEnd = Padding.end();
  774. Pad != PadEnd; ++Pad)
  775. Members.push_back(StorageInfo(Pad->first, getByteArrayType(Pad->second)));
  776. llvm::stable_sort(Members);
  777. }
  778. void CGRecordLowering::fillOutputFields() {
  779. for (std::vector<MemberInfo>::const_iterator Member = Members.begin(),
  780. MemberEnd = Members.end();
  781. Member != MemberEnd; ++Member) {
  782. if (Member->Data)
  783. FieldTypes.push_back(Member->Data);
  784. if (Member->Kind == MemberInfo::Field) {
  785. if (Member->FD)
  786. Fields[Member->FD->getCanonicalDecl()] = FieldTypes.size() - 1;
  787. // A field without storage must be a bitfield.
  788. if (!Member->Data)
  789. setBitFieldInfo(Member->FD, Member->Offset, FieldTypes.back());
  790. } else if (Member->Kind == MemberInfo::Base)
  791. NonVirtualBases[Member->RD] = FieldTypes.size() - 1;
  792. else if (Member->Kind == MemberInfo::VBase)
  793. VirtualBases[Member->RD] = FieldTypes.size() - 1;
  794. }
  795. }
  796. CGBitFieldInfo CGBitFieldInfo::MakeInfo(CodeGenTypes &Types,
  797. const FieldDecl *FD,
  798. uint64_t Offset, uint64_t Size,
  799. uint64_t StorageSize,
  800. CharUnits StorageOffset) {
  801. // This function is vestigial from CGRecordLayoutBuilder days but is still
  802. // used in GCObjCRuntime.cpp. That usage has a "fixme" attached to it that
  803. // when addressed will allow for the removal of this function.
  804. llvm::Type *Ty = Types.ConvertTypeForMem(FD->getType());
  805. CharUnits TypeSizeInBytes =
  806. CharUnits::fromQuantity(Types.getDataLayout().getTypeAllocSize(Ty));
  807. uint64_t TypeSizeInBits = Types.getContext().toBits(TypeSizeInBytes);
  808. bool IsSigned = FD->getType()->isSignedIntegerOrEnumerationType();
  809. if (Size > TypeSizeInBits) {
  810. // We have a wide bit-field. The extra bits are only used for padding, so
  811. // if we have a bitfield of type T, with size N:
  812. //
  813. // T t : N;
  814. //
  815. // We can just assume that it's:
  816. //
  817. // T t : sizeof(T);
  818. //
  819. Size = TypeSizeInBits;
  820. }
  821. // Reverse the bit offsets for big endian machines. Because we represent
  822. // a bitfield as a single large integer load, we can imagine the bits
  823. // counting from the most-significant-bit instead of the
  824. // least-significant-bit.
  825. if (Types.getDataLayout().isBigEndian()) {
  826. Offset = StorageSize - (Offset + Size);
  827. }
  828. return CGBitFieldInfo(Offset, Size, IsSigned, StorageSize, StorageOffset);
  829. }
  830. std::unique_ptr<CGRecordLayout>
  831. CodeGenTypes::ComputeRecordLayout(const RecordDecl *D, llvm::StructType *Ty) {
  832. CGRecordLowering Builder(*this, D, /*Packed=*/false);
  833. Builder.lower(/*NonVirtualBaseType=*/false);
  834. // If we're in C++, compute the base subobject type.
  835. llvm::StructType *BaseTy = nullptr;
  836. if (isa<CXXRecordDecl>(D) && !D->isUnion() && !D->hasAttr<FinalAttr>()) {
  837. BaseTy = Ty;
  838. if (Builder.Layout.getNonVirtualSize() != Builder.Layout.getSize()) {
  839. CGRecordLowering BaseBuilder(*this, D, /*Packed=*/Builder.Packed);
  840. BaseBuilder.lower(/*NonVirtualBaseType=*/true);
  841. BaseTy = llvm::StructType::create(
  842. getLLVMContext(), BaseBuilder.FieldTypes, "", BaseBuilder.Packed);
  843. addRecordTypeName(D, BaseTy, ".base");
  844. // BaseTy and Ty must agree on their packedness for getLLVMFieldNo to work
  845. // on both of them with the same index.
  846. assert(Builder.Packed == BaseBuilder.Packed &&
  847. "Non-virtual and complete types must agree on packedness");
  848. }
  849. }
  850. // Fill in the struct *after* computing the base type. Filling in the body
  851. // signifies that the type is no longer opaque and record layout is complete,
  852. // but we may need to recursively layout D while laying D out as a base type.
  853. Ty->setBody(Builder.FieldTypes, Builder.Packed);
  854. auto RL = std::make_unique<CGRecordLayout>(
  855. Ty, BaseTy, (bool)Builder.IsZeroInitializable,
  856. (bool)Builder.IsZeroInitializableAsBase);
  857. RL->NonVirtualBases.swap(Builder.NonVirtualBases);
  858. RL->CompleteObjectVirtualBases.swap(Builder.VirtualBases);
  859. // Add all the field numbers.
  860. RL->FieldInfo.swap(Builder.Fields);
  861. // Add bitfield info.
  862. RL->BitFields.swap(Builder.BitFields);
  863. // Dump the layout, if requested.
  864. if (getContext().getLangOpts().DumpRecordLayouts) {
  865. llvm::outs() << "\n*** Dumping IRgen Record Layout\n";
  866. llvm::outs() << "Record: ";
  867. D->dump(llvm::outs());
  868. llvm::outs() << "\nLayout: ";
  869. RL->print(llvm::outs());
  870. }
  871. #ifndef NDEBUG
  872. // Verify that the computed LLVM struct size matches the AST layout size.
  873. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(D);
  874. uint64_t TypeSizeInBits = getContext().toBits(Layout.getSize());
  875. assert(TypeSizeInBits == getDataLayout().getTypeAllocSizeInBits(Ty) &&
  876. "Type size mismatch!");
  877. if (BaseTy) {
  878. CharUnits NonVirtualSize = Layout.getNonVirtualSize();
  879. uint64_t AlignedNonVirtualTypeSizeInBits =
  880. getContext().toBits(NonVirtualSize);
  881. assert(AlignedNonVirtualTypeSizeInBits ==
  882. getDataLayout().getTypeAllocSizeInBits(BaseTy) &&
  883. "Type size mismatch!");
  884. }
  885. // Verify that the LLVM and AST field offsets agree.
  886. llvm::StructType *ST = RL->getLLVMType();
  887. const llvm::StructLayout *SL = getDataLayout().getStructLayout(ST);
  888. const ASTRecordLayout &AST_RL = getContext().getASTRecordLayout(D);
  889. RecordDecl::field_iterator it = D->field_begin();
  890. for (unsigned i = 0, e = AST_RL.getFieldCount(); i != e; ++i, ++it) {
  891. const FieldDecl *FD = *it;
  892. // Ignore zero-sized fields.
  893. if (FD->isZeroSize(getContext()))
  894. continue;
  895. // For non-bit-fields, just check that the LLVM struct offset matches the
  896. // AST offset.
  897. if (!FD->isBitField()) {
  898. unsigned FieldNo = RL->getLLVMFieldNo(FD);
  899. assert(AST_RL.getFieldOffset(i) == SL->getElementOffsetInBits(FieldNo) &&
  900. "Invalid field offset!");
  901. continue;
  902. }
  903. // Ignore unnamed bit-fields.
  904. if (!FD->getDeclName())
  905. continue;
  906. const CGBitFieldInfo &Info = RL->getBitFieldInfo(FD);
  907. llvm::Type *ElementTy = ST->getTypeAtIndex(RL->getLLVMFieldNo(FD));
  908. // Unions have overlapping elements dictating their layout, but for
  909. // non-unions we can verify that this section of the layout is the exact
  910. // expected size.
  911. if (D->isUnion()) {
  912. // For unions we verify that the start is zero and the size
  913. // is in-bounds. However, on BE systems, the offset may be non-zero, but
  914. // the size + offset should match the storage size in that case as it
  915. // "starts" at the back.
  916. if (getDataLayout().isBigEndian())
  917. assert(static_cast<unsigned>(Info.Offset + Info.Size) ==
  918. Info.StorageSize &&
  919. "Big endian union bitfield does not end at the back");
  920. else
  921. assert(Info.Offset == 0 &&
  922. "Little endian union bitfield with a non-zero offset");
  923. assert(Info.StorageSize <= SL->getSizeInBits() &&
  924. "Union not large enough for bitfield storage");
  925. } else {
  926. assert((Info.StorageSize ==
  927. getDataLayout().getTypeAllocSizeInBits(ElementTy) ||
  928. Info.VolatileStorageSize ==
  929. getDataLayout().getTypeAllocSizeInBits(ElementTy)) &&
  930. "Storage size does not match the element type size");
  931. }
  932. assert(Info.Size > 0 && "Empty bitfield!");
  933. assert(static_cast<unsigned>(Info.Offset) + Info.Size <= Info.StorageSize &&
  934. "Bitfield outside of its allocated storage");
  935. }
  936. #endif
  937. return RL;
  938. }
  939. void CGRecordLayout::print(raw_ostream &OS) const {
  940. OS << "<CGRecordLayout\n";
  941. OS << " LLVMType:" << *CompleteObjectType << "\n";
  942. if (BaseSubobjectType)
  943. OS << " NonVirtualBaseLLVMType:" << *BaseSubobjectType << "\n";
  944. OS << " IsZeroInitializable:" << IsZeroInitializable << "\n";
  945. OS << " BitFields:[\n";
  946. // Print bit-field infos in declaration order.
  947. std::vector<std::pair<unsigned, const CGBitFieldInfo*> > BFIs;
  948. for (llvm::DenseMap<const FieldDecl*, CGBitFieldInfo>::const_iterator
  949. it = BitFields.begin(), ie = BitFields.end();
  950. it != ie; ++it) {
  951. const RecordDecl *RD = it->first->getParent();
  952. unsigned Index = 0;
  953. for (RecordDecl::field_iterator
  954. it2 = RD->field_begin(); *it2 != it->first; ++it2)
  955. ++Index;
  956. BFIs.push_back(std::make_pair(Index, &it->second));
  957. }
  958. llvm::array_pod_sort(BFIs.begin(), BFIs.end());
  959. for (unsigned i = 0, e = BFIs.size(); i != e; ++i) {
  960. OS.indent(4);
  961. BFIs[i].second->print(OS);
  962. OS << "\n";
  963. }
  964. OS << "]>\n";
  965. }
  966. LLVM_DUMP_METHOD void CGRecordLayout::dump() const {
  967. print(llvm::errs());
  968. }
  969. void CGBitFieldInfo::print(raw_ostream &OS) const {
  970. OS << "<CGBitFieldInfo"
  971. << " Offset:" << Offset << " Size:" << Size << " IsSigned:" << IsSigned
  972. << " StorageSize:" << StorageSize
  973. << " StorageOffset:" << StorageOffset.getQuantity()
  974. << " VolatileOffset:" << VolatileOffset
  975. << " VolatileStorageSize:" << VolatileStorageSize
  976. << " VolatileStorageOffset:" << VolatileStorageOffset.getQuantity() << ">";
  977. }
  978. LLVM_DUMP_METHOD void CGBitFieldInfo::dump() const {
  979. print(llvm::errs());
  980. }