CodeGenTypes.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. //===--- CodeGenTypes.cpp - Type translation for LLVM CodeGen -------------===//
  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. //
  10. // This is the code that handles AST -> LLVM type lowering.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenTypes.h"
  14. #include "clang/Basic/TargetInfo.h"
  15. #include "clang/AST/AST.h"
  16. #include "llvm/DerivedTypes.h"
  17. #include "llvm/Module.h"
  18. #include "llvm/Target/TargetData.h"
  19. using namespace clang;
  20. using namespace CodeGen;
  21. namespace {
  22. /// RecordOrganizer - This helper class, used by CGRecordLayout, layouts
  23. /// structs and unions. It manages transient information used during layout.
  24. /// FIXME : Handle field aligments. Handle packed structs.
  25. class RecordOrganizer {
  26. public:
  27. explicit RecordOrganizer(CodeGenTypes &Types) :
  28. CGT(Types), STy(NULL), llvmFieldNo(0), Cursor(0),
  29. llvmSize(0) {}
  30. /// addField - Add new field.
  31. void addField(const FieldDecl *FD);
  32. /// addLLVMField - Add llvm struct field that corresponds to llvm type Ty.
  33. /// Increment field count.
  34. void addLLVMField(const llvm::Type *Ty, bool isPaddingField = false);
  35. /// addPaddingFields - Current cursor is not suitable place to add next
  36. /// field. Add required padding fields.
  37. void addPaddingFields(unsigned WaterMark);
  38. /// layoutStructFields - Do the actual work and lay out all fields. Create
  39. /// corresponding llvm struct type. This should be invoked only after
  40. /// all fields are added.
  41. void layoutStructFields(const ASTRecordLayout &RL);
  42. /// layoutUnionFields - Do the actual work and lay out all fields. Create
  43. /// corresponding llvm struct type. This should be invoked only after
  44. /// all fields are added.
  45. void layoutUnionFields();
  46. /// getLLVMType - Return associated llvm struct type. This may be NULL
  47. /// if fields are not laid out.
  48. llvm::Type *getLLVMType() const {
  49. return STy;
  50. }
  51. /// placeBitField - Find a place for FD, which is a bit-field.
  52. void placeBitField(const FieldDecl *FD);
  53. llvm::SmallSet<unsigned, 8> &getPaddingFields() {
  54. return PaddingFields;
  55. }
  56. private:
  57. CodeGenTypes &CGT;
  58. llvm::Type *STy;
  59. unsigned llvmFieldNo;
  60. uint64_t Cursor;
  61. uint64_t llvmSize;
  62. llvm::SmallVector<const FieldDecl *, 8> FieldDecls;
  63. std::vector<const llvm::Type*> LLVMFields;
  64. llvm::SmallSet<unsigned, 8> PaddingFields;
  65. };
  66. }
  67. CodeGenTypes::CodeGenTypes(ASTContext &Ctx, llvm::Module& M,
  68. const llvm::TargetData &TD)
  69. : Context(Ctx), Target(Ctx.Target), TheModule(M), TheTargetData(TD) {
  70. }
  71. CodeGenTypes::~CodeGenTypes() {
  72. for(llvm::DenseMap<const TagDecl *, CGRecordLayout *>::iterator
  73. I = CGRecordLayouts.begin(), E = CGRecordLayouts.end();
  74. I != E; ++I)
  75. delete I->second;
  76. CGRecordLayouts.clear();
  77. }
  78. /// ConvertType - Convert the specified type to its LLVM form.
  79. const llvm::Type *CodeGenTypes::ConvertType(QualType T) {
  80. // See if type is already cached.
  81. llvm::DenseMap<Type *, llvm::PATypeHolder>::iterator
  82. I = TypeCache.find(T.getCanonicalType().getTypePtr());
  83. // If type is found in map and this is not a definition for a opaque
  84. // place holder type then use it. Otherwise, convert type T.
  85. if (I != TypeCache.end())
  86. return I->second.get();
  87. const llvm::Type *ResultType = ConvertNewType(T);
  88. TypeCache.insert(std::make_pair(T.getCanonicalType().getTypePtr(),
  89. llvm::PATypeHolder(ResultType)));
  90. return ResultType;
  91. }
  92. /// ConvertTypeForMem - Convert type T into a llvm::Type. This differs from
  93. /// ConvertType in that it is used to convert to the memory representation for
  94. /// a type. For example, the scalar representation for _Bool is i1, but the
  95. /// memory representation is usually i8 or i32, depending on the target.
  96. const llvm::Type *CodeGenTypes::ConvertTypeForMem(QualType T) {
  97. const llvm::Type *R = ConvertType(T);
  98. // If this is a non-bool type, don't map it.
  99. if (R != llvm::Type::Int1Ty)
  100. return R;
  101. // Otherwise, return an integer of the target-specified size.
  102. return llvm::IntegerType::get((unsigned)Context.getTypeSize(T));
  103. }
  104. /// UpdateCompletedType - When we find the full definition for a TagDecl,
  105. /// replace the 'opaque' type we previously made for it if applicable.
  106. void CodeGenTypes::UpdateCompletedType(const TagDecl *TD) {
  107. llvm::DenseMap<const TagDecl*, llvm::PATypeHolder>::iterator TDTI =
  108. TagDeclTypes.find(TD);
  109. if (TDTI == TagDeclTypes.end()) return;
  110. // Remember the opaque LLVM type for this tagdecl.
  111. llvm::PATypeHolder OpaqueHolder = TDTI->second;
  112. assert(isa<llvm::OpaqueType>(OpaqueHolder.get()) &&
  113. "Updating compilation of an already non-opaque type?");
  114. // Remove it from TagDeclTypes so that it will be regenerated.
  115. TagDeclTypes.erase(TDTI);
  116. // Generate the new type.
  117. const llvm::Type *NT = ConvertTagDeclType(TD);
  118. // Refine the old opaque type to its new definition.
  119. cast<llvm::OpaqueType>(OpaqueHolder.get())->refineAbstractTypeTo(NT);
  120. }
  121. /// Produces a vector containing the all of the instance variables in an
  122. /// Objective-C object, in the order that they appear. Used to create LLVM
  123. /// structures corresponding to Objective-C objects.
  124. void CodeGenTypes::CollectObjCIvarTypes(ObjCInterfaceDecl *ObjCClass,
  125. std::vector<const llvm::Type*> &IvarTypes) {
  126. ObjCInterfaceDecl *SuperClass = ObjCClass->getSuperClass();
  127. if(SuperClass) {
  128. CollectObjCIvarTypes(SuperClass, IvarTypes);
  129. }
  130. for(ObjCInterfaceDecl::ivar_iterator ivar=ObjCClass->ivar_begin() ;
  131. ivar != ObjCClass->ivar_end() ;
  132. ivar++) {
  133. IvarTypes.push_back(ConvertType((*ivar)->getType()));
  134. ObjCIvarInfo[*ivar] = IvarTypes.size() - 1;
  135. }
  136. }
  137. const llvm::Type *CodeGenTypes::ConvertNewType(QualType T) {
  138. const clang::Type &Ty = *T.getCanonicalType();
  139. switch (Ty.getTypeClass()) {
  140. case Type::TypeName: // typedef isn't canonical.
  141. case Type::TypeOfExp: // typeof isn't canonical.
  142. case Type::TypeOfTyp: // typeof isn't canonical.
  143. assert(0 && "Non-canonical type, shouldn't happen");
  144. case Type::Builtin: {
  145. switch (cast<BuiltinType>(Ty).getKind()) {
  146. case BuiltinType::Void:
  147. // LLVM void type can only be used as the result of a function call. Just
  148. // map to the same as char.
  149. return llvm::IntegerType::get(8);
  150. case BuiltinType::Bool:
  151. // Note that we always return bool as i1 for use as a scalar type.
  152. return llvm::Type::Int1Ty;
  153. case BuiltinType::Char_S:
  154. case BuiltinType::Char_U:
  155. case BuiltinType::SChar:
  156. case BuiltinType::UChar:
  157. case BuiltinType::Short:
  158. case BuiltinType::UShort:
  159. case BuiltinType::Int:
  160. case BuiltinType::UInt:
  161. case BuiltinType::Long:
  162. case BuiltinType::ULong:
  163. case BuiltinType::LongLong:
  164. case BuiltinType::ULongLong:
  165. return llvm::IntegerType::get(
  166. static_cast<unsigned>(Context.getTypeSize(T)));
  167. case BuiltinType::Float: return llvm::Type::FloatTy;
  168. case BuiltinType::Double: return llvm::Type::DoubleTy;
  169. case BuiltinType::LongDouble:
  170. // FIXME: mapping long double onto double.
  171. return llvm::Type::DoubleTy;
  172. }
  173. break;
  174. }
  175. case Type::Complex: {
  176. const llvm::Type *EltTy =
  177. ConvertType(cast<ComplexType>(Ty).getElementType());
  178. return llvm::StructType::get(EltTy, EltTy, NULL);
  179. }
  180. case Type::Pointer: {
  181. const PointerType &P = cast<PointerType>(Ty);
  182. QualType ETy = P.getPointeeType();
  183. return llvm::PointerType::get(ConvertType(ETy), ETy.getAddressSpace());
  184. }
  185. case Type::Reference: {
  186. const ReferenceType &R = cast<ReferenceType>(Ty);
  187. return llvm::PointerType::getUnqual(ConvertType(R.getReferenceeType()));
  188. }
  189. case Type::VariableArray: {
  190. const VariableArrayType &A = cast<VariableArrayType>(Ty);
  191. assert(A.getIndexTypeQualifier() == 0 &&
  192. "FIXME: We only handle trivial array types so far!");
  193. // VLAs resolve to the innermost element type; this matches
  194. // the return of alloca, and there isn't any obviously better choice.
  195. return ConvertType(A.getElementType());
  196. }
  197. case Type::IncompleteArray: {
  198. const IncompleteArrayType &A = cast<IncompleteArrayType>(Ty);
  199. assert(A.getIndexTypeQualifier() == 0 &&
  200. "FIXME: We only handle trivial array types so far!");
  201. // int X[] -> [0 x int]
  202. return llvm::ArrayType::get(ConvertType(A.getElementType()), 0);
  203. }
  204. case Type::ConstantArray: {
  205. const ConstantArrayType &A = cast<ConstantArrayType>(Ty);
  206. const llvm::Type *EltTy = ConvertType(A.getElementType());
  207. return llvm::ArrayType::get(EltTy, A.getSize().getZExtValue());
  208. }
  209. case Type::OCUVector:
  210. case Type::Vector: {
  211. const VectorType &VT = cast<VectorType>(Ty);
  212. return llvm::VectorType::get(ConvertType(VT.getElementType()),
  213. VT.getNumElements());
  214. }
  215. case Type::FunctionNoProto:
  216. case Type::FunctionProto: {
  217. const FunctionType &FP = cast<FunctionType>(Ty);
  218. const llvm::Type *ResultType;
  219. if (FP.getResultType()->isVoidType())
  220. ResultType = llvm::Type::VoidTy; // Result of function uses llvm void.
  221. else
  222. ResultType = ConvertType(FP.getResultType());
  223. // FIXME: Convert argument types.
  224. bool isVarArg;
  225. std::vector<const llvm::Type*> ArgTys;
  226. // Struct return passes the struct byref.
  227. if (!ResultType->isFirstClassType() && ResultType != llvm::Type::VoidTy) {
  228. ArgTys.push_back(llvm::PointerType::get(ResultType,
  229. FP.getResultType().getAddressSpace()));
  230. ResultType = llvm::Type::VoidTy;
  231. }
  232. if (const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(&FP)) {
  233. DecodeArgumentTypes(*FTP, ArgTys);
  234. isVarArg = FTP->isVariadic();
  235. } else {
  236. isVarArg = true;
  237. }
  238. return llvm::FunctionType::get(ResultType, ArgTys, isVarArg);
  239. }
  240. case Type::ASQual:
  241. return ConvertType(QualType(cast<ASQualType>(Ty).getBaseType(), 0));
  242. case Type::ObjCInterface: {
  243. // Warning: Use of this is strongly discouraged. Late binding of instance
  244. // variables is supported on some runtimes and so using static binding can
  245. // break code when libraries are updated. Only use this if you have
  246. // previously checked that the ObjCRuntime subclass in use does not support
  247. // late-bound ivars.
  248. ObjCInterfaceType OIT = cast<ObjCInterfaceType>(Ty);
  249. std::vector<const llvm::Type*> IvarTypes;
  250. // Pointer to the class. This is just a placeholder. Operations that
  251. // actually use the isa pointer should cast it to the Class type provided
  252. // by the runtime.
  253. IvarTypes.push_back(llvm::PointerType::getUnqual(llvm::Type::Int8Ty));
  254. CollectObjCIvarTypes(OIT.getDecl(), IvarTypes);
  255. return llvm::StructType::get(IvarTypes);
  256. }
  257. case Type::ObjCQualifiedInterface:
  258. assert(0 && "FIXME: add missing functionality here");
  259. break;
  260. case Type::ObjCQualifiedId:
  261. assert(0 && "FIXME: add missing functionality here");
  262. break;
  263. case Type::Tagged: {
  264. const TagDecl *TD = cast<TagType>(Ty).getDecl();
  265. const llvm::Type *Res = ConvertTagDeclType(TD);
  266. std::string TypeName(TD->getKindName());
  267. TypeName += '.';
  268. // Name the codegen type after the typedef name
  269. // if there is no tag type name available
  270. if (TD->getIdentifier())
  271. TypeName += TD->getName();
  272. else if (const TypedefType *TdT = dyn_cast<TypedefType>(T))
  273. TypeName += TdT->getDecl()->getName();
  274. else
  275. TypeName += "anon";
  276. TheModule.addTypeName(TypeName, Res);
  277. return Res;
  278. }
  279. }
  280. // FIXME: implement.
  281. return llvm::OpaqueType::get();
  282. }
  283. void CodeGenTypes::DecodeArgumentTypes(const FunctionTypeProto &FTP,
  284. std::vector<const llvm::Type*> &ArgTys) {
  285. for (unsigned i = 0, e = FTP.getNumArgs(); i != e; ++i) {
  286. const llvm::Type *Ty = ConvertType(FTP.getArgType(i));
  287. if (Ty->isFirstClassType())
  288. ArgTys.push_back(Ty);
  289. else
  290. // byval arguments are always on the stack, which is addr space #0.
  291. ArgTys.push_back(llvm::PointerType::getUnqual(Ty));
  292. }
  293. }
  294. /// ConvertTagDeclType - Lay out a tagged decl type like struct or union or
  295. /// enum.
  296. const llvm::Type *CodeGenTypes::ConvertTagDeclType(const TagDecl *TD) {
  297. llvm::DenseMap<const TagDecl*, llvm::PATypeHolder>::iterator TDTI =
  298. TagDeclTypes.find(TD);
  299. // If we've already compiled this tag type, use the previous definition.
  300. if (TDTI != TagDeclTypes.end())
  301. return TDTI->second;
  302. // If this is still a forward definition, just define an opaque type to use
  303. // for this tagged decl.
  304. if (!TD->isDefinition()) {
  305. llvm::Type *ResultType = llvm::OpaqueType::get();
  306. TagDeclTypes.insert(std::make_pair(TD, ResultType));
  307. return ResultType;
  308. }
  309. // Okay, this is a definition of a type. Compile the implementation now.
  310. if (TD->getKind() == Decl::Enum) {
  311. // Don't bother storing enums in TagDeclTypes.
  312. return ConvertType(cast<EnumDecl>(TD)->getIntegerType());
  313. }
  314. // This decl could well be recursive. In this case, insert an opaque
  315. // definition of this type, which the recursive uses will get. We will then
  316. // refine this opaque version later.
  317. // Create new OpaqueType now for later use in case this is a recursive
  318. // type. This will later be refined to the actual type.
  319. llvm::PATypeHolder ResultHolder = llvm::OpaqueType::get();
  320. TagDeclTypes.insert(std::make_pair(TD, ResultHolder));
  321. const llvm::Type *ResultType;
  322. const RecordDecl *RD = cast<const RecordDecl>(TD);
  323. if (TD->getKind() == Decl::Struct || TD->getKind() == Decl::Class) {
  324. // Layout fields.
  325. RecordOrganizer RO(*this);
  326. for (unsigned i = 0, e = RD->getNumMembers(); i != e; ++i)
  327. RO.addField(RD->getMember(i));
  328. RO.layoutStructFields(Context.getASTRecordLayout(RD));
  329. // Get llvm::StructType.
  330. CGRecordLayouts[TD] = new CGRecordLayout(RO.getLLVMType(),
  331. RO.getPaddingFields());
  332. ResultType = RO.getLLVMType();
  333. } else if (TD->getKind() == Decl::Union) {
  334. // Just use the largest element of the union, breaking ties with the
  335. // highest aligned member.
  336. if (RD->getNumMembers() != 0) {
  337. RecordOrganizer RO(*this);
  338. for (unsigned i = 0, e = RD->getNumMembers(); i != e; ++i)
  339. RO.addField(RD->getMember(i));
  340. RO.layoutUnionFields();
  341. // Get llvm::StructType.
  342. CGRecordLayouts[TD] = new CGRecordLayout(RO.getLLVMType(),
  343. RO.getPaddingFields());
  344. ResultType = RO.getLLVMType();
  345. } else {
  346. ResultType = llvm::StructType::get(std::vector<const llvm::Type*>());
  347. }
  348. } else {
  349. assert(0 && "FIXME: Unknown tag decl kind!");
  350. }
  351. // Refine our Opaque type to ResultType. This can invalidate ResultType, so
  352. // make sure to read the result out of the holder.
  353. cast<llvm::OpaqueType>(ResultHolder.get())
  354. ->refineAbstractTypeTo(ResultType);
  355. return ResultHolder.get();
  356. }
  357. /// getLLVMFieldNo - Return llvm::StructType element number
  358. /// that corresponds to the field FD.
  359. unsigned CodeGenTypes::getLLVMFieldNo(const FieldDecl *FD) {
  360. llvm::DenseMap<const FieldDecl *, unsigned>::iterator
  361. I = FieldInfo.find(FD);
  362. assert (I != FieldInfo.end() && "Unable to find field info");
  363. return I->second;
  364. }
  365. unsigned CodeGenTypes::getLLVMFieldNo(const ObjCIvarDecl *OID) {
  366. llvm::DenseMap<const ObjCIvarDecl*, unsigned>::iterator
  367. I = ObjCIvarInfo.find(OID);
  368. assert (I != ObjCIvarInfo.end() && "Unable to find field info");
  369. return I->second;
  370. }
  371. /// addFieldInfo - Assign field number to field FD.
  372. void CodeGenTypes::addFieldInfo(const FieldDecl *FD, unsigned No) {
  373. FieldInfo[FD] = No;
  374. }
  375. /// getBitFieldInfo - Return the BitFieldInfo that corresponds to the field FD.
  376. CodeGenTypes::BitFieldInfo CodeGenTypes::getBitFieldInfo(const FieldDecl *FD) {
  377. llvm::DenseMap<const FieldDecl *, BitFieldInfo>::iterator
  378. I = BitFields.find(FD);
  379. assert (I != BitFields.end() && "Unable to find bitfield info");
  380. return I->second;
  381. }
  382. /// addBitFieldInfo - Assign a start bit and a size to field FD.
  383. void CodeGenTypes::addBitFieldInfo(const FieldDecl *FD, unsigned Begin,
  384. unsigned Size) {
  385. BitFields.insert(std::make_pair(FD, BitFieldInfo(Begin, Size)));
  386. }
  387. /// getCGRecordLayout - Return record layout info for the given llvm::Type.
  388. const CGRecordLayout *
  389. CodeGenTypes::getCGRecordLayout(const TagDecl *TD) const {
  390. llvm::DenseMap<const TagDecl*, CGRecordLayout *>::iterator I
  391. = CGRecordLayouts.find(TD);
  392. assert (I != CGRecordLayouts.end()
  393. && "Unable to find record layout information for type");
  394. return I->second;
  395. }
  396. /// addField - Add new field.
  397. void RecordOrganizer::addField(const FieldDecl *FD) {
  398. assert (!STy && "Record fields are already laid out");
  399. FieldDecls.push_back(FD);
  400. }
  401. /// layoutStructFields - Do the actual work and lay out all fields. Create
  402. /// corresponding llvm struct type. This should be invoked only after
  403. /// all fields are added.
  404. /// FIXME : At the moment assume
  405. /// - one to one mapping between AST FieldDecls and
  406. /// llvm::StructType elements.
  407. /// - Ignore bit fields
  408. /// - Ignore field aligments
  409. /// - Ignore packed structs
  410. void RecordOrganizer::layoutStructFields(const ASTRecordLayout &RL) {
  411. // FIXME : Use SmallVector
  412. llvmSize = 0;
  413. llvmFieldNo = 0;
  414. Cursor = 0;
  415. LLVMFields.clear();
  416. for (llvm::SmallVector<const FieldDecl *, 8>::iterator I = FieldDecls.begin(),
  417. E = FieldDecls.end(); I != E; ++I) {
  418. const FieldDecl *FD = *I;
  419. if (FD->isBitField())
  420. placeBitField(FD);
  421. else {
  422. const llvm::Type *Ty = CGT.ConvertType(FD->getType());
  423. addLLVMField(Ty);
  424. CGT.addFieldInfo(FD, llvmFieldNo - 1);
  425. Cursor = llvmSize;
  426. }
  427. }
  428. unsigned StructAlign = RL.getAlignment();
  429. if (llvmSize % StructAlign) {
  430. unsigned StructPadding = StructAlign - (llvmSize % StructAlign);
  431. addPaddingFields(llvmSize + StructPadding);
  432. }
  433. STy = llvm::StructType::get(LLVMFields);
  434. }
  435. /// addPaddingFields - Current cursor is not suitable place to add next field.
  436. /// Add required padding fields.
  437. void RecordOrganizer::addPaddingFields(unsigned WaterMark) {
  438. assert(WaterMark >= llvmSize && "Invalid padding Field");
  439. unsigned RequiredBits = WaterMark - llvmSize;
  440. unsigned RequiredBytes = (RequiredBits + 7) / 8;
  441. for (unsigned i = 0; i != RequiredBytes; ++i)
  442. addLLVMField(llvm::Type::Int8Ty, true);
  443. }
  444. /// addLLVMField - Add llvm struct field that corresponds to llvm type Ty.
  445. /// Increment field count.
  446. void RecordOrganizer::addLLVMField(const llvm::Type *Ty, bool isPaddingField) {
  447. unsigned AlignmentInBits = CGT.getTargetData().getABITypeAlignment(Ty) * 8;
  448. if (llvmSize % AlignmentInBits) {
  449. // At the moment, insert padding fields even if target specific llvm
  450. // type alignment enforces implict padding fields for FD. Later on,
  451. // optimize llvm fields by removing implicit padding fields and
  452. // combining consequetive padding fields.
  453. unsigned Padding = AlignmentInBits - (llvmSize % AlignmentInBits);
  454. addPaddingFields(llvmSize + Padding);
  455. }
  456. unsigned TySize = CGT.getTargetData().getABITypeSizeInBits(Ty);
  457. llvmSize += TySize;
  458. if (isPaddingField)
  459. PaddingFields.insert(llvmFieldNo);
  460. LLVMFields.push_back(Ty);
  461. ++llvmFieldNo;
  462. }
  463. /// layoutUnionFields - Do the actual work and lay out all fields. Create
  464. /// corresponding llvm struct type. This should be invoked only after
  465. /// all fields are added.
  466. void RecordOrganizer::layoutUnionFields() {
  467. unsigned PrimaryEltNo = 0;
  468. std::pair<uint64_t, unsigned> PrimaryElt =
  469. CGT.getContext().getTypeInfo(FieldDecls[0]->getType());
  470. CGT.addFieldInfo(FieldDecls[0], 0);
  471. unsigned Size = FieldDecls.size();
  472. for(unsigned i = 1; i != Size; ++i) {
  473. const FieldDecl *FD = FieldDecls[i];
  474. assert (!FD->isBitField() && "Bit fields are not yet supported");
  475. std::pair<uint64_t, unsigned> EltInfo =
  476. CGT.getContext().getTypeInfo(FD->getType());
  477. // Use largest element, breaking ties with the hightest aligned member.
  478. if (EltInfo.first > PrimaryElt.first ||
  479. (EltInfo.first == PrimaryElt.first &&
  480. EltInfo.second > PrimaryElt.second)) {
  481. PrimaryElt = EltInfo;
  482. PrimaryEltNo = i;
  483. }
  484. // In union, each field gets first slot.
  485. CGT.addFieldInfo(FD, 0);
  486. }
  487. std::vector<const llvm::Type*> Fields;
  488. const llvm::Type *Ty = CGT.ConvertType(FieldDecls[PrimaryEltNo]->getType());
  489. Fields.push_back(Ty);
  490. STy = llvm::StructType::get(Fields);
  491. }
  492. /// placeBitField - Find a place for FD, which is a bit-field.
  493. /// This function searches for the last aligned field. If the bit-field fits in
  494. /// it, it is reused. Otherwise, the bit-field is placed in a new field.
  495. void RecordOrganizer::placeBitField(const FieldDecl *FD) {
  496. assert (FD->isBitField() && "FD is not a bit-field");
  497. Expr *BitWidth = FD->getBitWidth();
  498. llvm::APSInt FieldSize(32);
  499. bool isBitField =
  500. BitWidth->isIntegerConstantExpr(FieldSize, CGT.getContext());
  501. assert (isBitField && "Invalid BitField size expression");
  502. uint64_t BitFieldSize = FieldSize.getZExtValue();
  503. const llvm::Type *Ty = CGT.ConvertType(FD->getType());
  504. uint64_t TySize = CGT.getTargetData().getABITypeSizeInBits(Ty);
  505. unsigned Idx = Cursor / TySize;
  506. unsigned BitsLeft = TySize - (Cursor % TySize);
  507. if (BitsLeft >= BitFieldSize) {
  508. // The bitfield fits in the last aligned field.
  509. // This is : struct { char a; int CurrentField:10;};
  510. // where 'CurrentField' shares first field with 'a'.
  511. CGT.addFieldInfo(FD, Idx);
  512. CGT.addBitFieldInfo(FD, TySize - BitsLeft, BitFieldSize);
  513. Cursor += BitFieldSize;
  514. } else {
  515. // Place the bitfield in a new LLVM field.
  516. // This is : struct { char a; short CurrentField:10;};
  517. // where 'CurrentField' needs a new llvm field.
  518. CGT.addFieldInfo(FD, Idx + 1);
  519. CGT.addBitFieldInfo(FD, 0, BitFieldSize);
  520. Cursor = (Idx + 1) * TySize + BitFieldSize;
  521. }
  522. if (Cursor > llvmSize)
  523. addPaddingFields(Cursor);
  524. }