CodeGenTypes.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  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 "CGCXXABI.h"
  15. #include "CGCall.h"
  16. #include "CGOpenCLRuntime.h"
  17. #include "CGRecordLayout.h"
  18. #include "TargetInfo.h"
  19. #include "clang/AST/ASTContext.h"
  20. #include "clang/AST/DeclCXX.h"
  21. #include "clang/AST/DeclObjC.h"
  22. #include "clang/AST/Expr.h"
  23. #include "clang/AST/RecordLayout.h"
  24. #include "clang/CodeGen/CGFunctionInfo.h"
  25. #include "llvm/IR/DataLayout.h"
  26. #include "llvm/IR/DerivedTypes.h"
  27. #include "llvm/IR/Module.h"
  28. using namespace clang;
  29. using namespace CodeGen;
  30. CodeGenTypes::CodeGenTypes(CodeGenModule &cgm)
  31. : CGM(cgm), Context(cgm.getContext()), TheModule(cgm.getModule()),
  32. Target(cgm.getTarget()), TheCXXABI(cgm.getCXXABI()),
  33. TheABIInfo(cgm.getTargetCodeGenInfo().getABIInfo()) {
  34. SkippedLayout = false;
  35. }
  36. CodeGenTypes::~CodeGenTypes() {
  37. llvm::DeleteContainerSeconds(CGRecordLayouts);
  38. for (llvm::FoldingSet<CGFunctionInfo>::iterator
  39. I = FunctionInfos.begin(), E = FunctionInfos.end(); I != E; )
  40. delete &*I++;
  41. }
  42. void CodeGenTypes::addRecordTypeName(const RecordDecl *RD,
  43. llvm::StructType *Ty,
  44. StringRef suffix) {
  45. SmallString<256> TypeName;
  46. llvm::raw_svector_ostream OS(TypeName);
  47. OS << RD->getKindName() << '.';
  48. // Name the codegen type after the typedef name
  49. // if there is no tag type name available
  50. if (RD->getIdentifier()) {
  51. // FIXME: We should not have to check for a null decl context here.
  52. // Right now we do it because the implicit Obj-C decls don't have one.
  53. if (RD->getDeclContext())
  54. RD->printQualifiedName(OS);
  55. else
  56. RD->printName(OS);
  57. } else if (const TypedefNameDecl *TDD = RD->getTypedefNameForAnonDecl()) {
  58. // FIXME: We should not have to check for a null decl context here.
  59. // Right now we do it because the implicit Obj-C decls don't have one.
  60. if (TDD->getDeclContext())
  61. TDD->printQualifiedName(OS);
  62. else
  63. TDD->printName(OS);
  64. } else
  65. OS << "anon";
  66. if (!suffix.empty())
  67. OS << suffix;
  68. Ty->setName(OS.str());
  69. }
  70. /// ConvertTypeForMem - Convert type T into a llvm::Type. This differs from
  71. /// ConvertType in that it is used to convert to the memory representation for
  72. /// a type. For example, the scalar representation for _Bool is i1, but the
  73. /// memory representation is usually i8 or i32, depending on the target.
  74. llvm::Type *CodeGenTypes::ConvertTypeForMem(QualType T) {
  75. llvm::Type *R = ConvertType(T);
  76. // If this is a non-bool type, don't map it.
  77. if (!R->isIntegerTy(1))
  78. return R;
  79. // Otherwise, return an integer of the target-specified size.
  80. return llvm::IntegerType::get(getLLVMContext(),
  81. (unsigned)Context.getTypeSize(T));
  82. }
  83. /// isRecordLayoutComplete - Return true if the specified type is already
  84. /// completely laid out.
  85. bool CodeGenTypes::isRecordLayoutComplete(const Type *Ty) const {
  86. llvm::DenseMap<const Type*, llvm::StructType *>::const_iterator I =
  87. RecordDeclTypes.find(Ty);
  88. return I != RecordDeclTypes.end() && !I->second->isOpaque();
  89. }
  90. static bool
  91. isSafeToConvert(QualType T, CodeGenTypes &CGT,
  92. llvm::SmallPtrSet<const RecordDecl*, 16> &AlreadyChecked);
  93. /// isSafeToConvert - Return true if it is safe to convert the specified record
  94. /// decl to IR and lay it out, false if doing so would cause us to get into a
  95. /// recursive compilation mess.
  96. static bool
  97. isSafeToConvert(const RecordDecl *RD, CodeGenTypes &CGT,
  98. llvm::SmallPtrSet<const RecordDecl*, 16> &AlreadyChecked) {
  99. // If we have already checked this type (maybe the same type is used by-value
  100. // multiple times in multiple structure fields, don't check again.
  101. if (!AlreadyChecked.insert(RD).second)
  102. return true;
  103. const Type *Key = CGT.getContext().getTagDeclType(RD).getTypePtr();
  104. // If this type is already laid out, converting it is a noop.
  105. if (CGT.isRecordLayoutComplete(Key)) return true;
  106. // If this type is currently being laid out, we can't recursively compile it.
  107. if (CGT.isRecordBeingLaidOut(Key))
  108. return false;
  109. // If this type would require laying out bases that are currently being laid
  110. // out, don't do it. This includes virtual base classes which get laid out
  111. // when a class is translated, even though they aren't embedded by-value into
  112. // the class.
  113. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  114. for (const auto &I : CRD->bases())
  115. if (!isSafeToConvert(I.getType()->getAs<RecordType>()->getDecl(),
  116. CGT, AlreadyChecked))
  117. return false;
  118. }
  119. // If this type would require laying out members that are currently being laid
  120. // out, don't do it.
  121. for (const auto *I : RD->fields())
  122. if (!isSafeToConvert(I->getType(), CGT, AlreadyChecked))
  123. return false;
  124. // If there are no problems, lets do it.
  125. return true;
  126. }
  127. /// isSafeToConvert - Return true if it is safe to convert this field type,
  128. /// which requires the structure elements contained by-value to all be
  129. /// recursively safe to convert.
  130. static bool
  131. isSafeToConvert(QualType T, CodeGenTypes &CGT,
  132. llvm::SmallPtrSet<const RecordDecl*, 16> &AlreadyChecked) {
  133. // Strip off atomic type sugar.
  134. if (const auto *AT = T->getAs<AtomicType>())
  135. T = AT->getValueType();
  136. // If this is a record, check it.
  137. if (const auto *RT = T->getAs<RecordType>())
  138. return isSafeToConvert(RT->getDecl(), CGT, AlreadyChecked);
  139. // If this is an array, check the elements, which are embedded inline.
  140. if (const auto *AT = CGT.getContext().getAsArrayType(T))
  141. return isSafeToConvert(AT->getElementType(), CGT, AlreadyChecked);
  142. // Otherwise, there is no concern about transforming this. We only care about
  143. // things that are contained by-value in a structure that can have another
  144. // structure as a member.
  145. return true;
  146. }
  147. /// isSafeToConvert - Return true if it is safe to convert the specified record
  148. /// decl to IR and lay it out, false if doing so would cause us to get into a
  149. /// recursive compilation mess.
  150. static bool isSafeToConvert(const RecordDecl *RD, CodeGenTypes &CGT) {
  151. // If no structs are being laid out, we can certainly do this one.
  152. if (CGT.noRecordsBeingLaidOut()) return true;
  153. llvm::SmallPtrSet<const RecordDecl*, 16> AlreadyChecked;
  154. return isSafeToConvert(RD, CGT, AlreadyChecked);
  155. }
  156. /// isFuncParamTypeConvertible - Return true if the specified type in a
  157. /// function parameter or result position can be converted to an IR type at this
  158. /// point. This boils down to being whether it is complete, as well as whether
  159. /// we've temporarily deferred expanding the type because we're in a recursive
  160. /// context.
  161. bool CodeGenTypes::isFuncParamTypeConvertible(QualType Ty) {
  162. // Some ABIs cannot have their member pointers represented in IR unless
  163. // certain circumstances have been reached.
  164. if (const auto *MPT = Ty->getAs<MemberPointerType>())
  165. return getCXXABI().isMemberPointerConvertible(MPT);
  166. // If this isn't a tagged type, we can convert it!
  167. const TagType *TT = Ty->getAs<TagType>();
  168. if (!TT) return true;
  169. // Incomplete types cannot be converted.
  170. if (TT->isIncompleteType())
  171. return false;
  172. // If this is an enum, then it is always safe to convert.
  173. const RecordType *RT = dyn_cast<RecordType>(TT);
  174. if (!RT) return true;
  175. // Otherwise, we have to be careful. If it is a struct that we're in the
  176. // process of expanding, then we can't convert the function type. That's ok
  177. // though because we must be in a pointer context under the struct, so we can
  178. // just convert it to a dummy type.
  179. //
  180. // We decide this by checking whether ConvertRecordDeclType returns us an
  181. // opaque type for a struct that we know is defined.
  182. return isSafeToConvert(RT->getDecl(), *this);
  183. }
  184. /// Code to verify a given function type is complete, i.e. the return type
  185. /// and all of the parameter types are complete. Also check to see if we are in
  186. /// a RS_StructPointer context, and if so whether any struct types have been
  187. /// pended. If so, we don't want to ask the ABI lowering code to handle a type
  188. /// that cannot be converted to an IR type.
  189. bool CodeGenTypes::isFuncTypeConvertible(const FunctionType *FT) {
  190. if (!isFuncParamTypeConvertible(FT->getReturnType()))
  191. return false;
  192. if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT))
  193. for (unsigned i = 0, e = FPT->getNumParams(); i != e; i++)
  194. if (!isFuncParamTypeConvertible(FPT->getParamType(i)))
  195. return false;
  196. return true;
  197. }
  198. /// UpdateCompletedType - When we find the full definition for a TagDecl,
  199. /// replace the 'opaque' type we previously made for it if applicable.
  200. void CodeGenTypes::UpdateCompletedType(const TagDecl *TD) {
  201. // If this is an enum being completed, then we flush all non-struct types from
  202. // the cache. This allows function types and other things that may be derived
  203. // from the enum to be recomputed.
  204. if (const EnumDecl *ED = dyn_cast<EnumDecl>(TD)) {
  205. // Only flush the cache if we've actually already converted this type.
  206. if (TypeCache.count(ED->getTypeForDecl())) {
  207. // Okay, we formed some types based on this. We speculated that the enum
  208. // would be lowered to i32, so we only need to flush the cache if this
  209. // didn't happen.
  210. if (!ConvertType(ED->getIntegerType())->isIntegerTy(32))
  211. TypeCache.clear();
  212. }
  213. // If necessary, provide the full definition of a type only used with a
  214. // declaration so far.
  215. if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
  216. DI->completeType(ED);
  217. return;
  218. }
  219. // If we completed a RecordDecl that we previously used and converted to an
  220. // anonymous type, then go ahead and complete it now.
  221. const RecordDecl *RD = cast<RecordDecl>(TD);
  222. if (RD->isDependentType()) return;
  223. // Only complete it if we converted it already. If we haven't converted it
  224. // yet, we'll just do it lazily.
  225. if (RecordDeclTypes.count(Context.getTagDeclType(RD).getTypePtr()))
  226. ConvertRecordDeclType(RD);
  227. // If necessary, provide the full definition of a type only used with a
  228. // declaration so far.
  229. if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
  230. DI->completeType(RD);
  231. }
  232. void CodeGenTypes::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
  233. QualType T = Context.getRecordType(RD);
  234. T = Context.getCanonicalType(T);
  235. const Type *Ty = T.getTypePtr();
  236. if (RecordsWithOpaqueMemberPointers.count(Ty)) {
  237. TypeCache.clear();
  238. RecordsWithOpaqueMemberPointers.clear();
  239. }
  240. }
  241. static llvm::Type *getTypeForFormat(llvm::LLVMContext &VMContext,
  242. const llvm::fltSemantics &format,
  243. bool UseNativeHalf = false) {
  244. if (&format == &llvm::APFloat::IEEEhalf()) {
  245. if (UseNativeHalf)
  246. return llvm::Type::getHalfTy(VMContext);
  247. else
  248. return llvm::Type::getInt16Ty(VMContext);
  249. }
  250. if (&format == &llvm::APFloat::IEEEsingle())
  251. return llvm::Type::getFloatTy(VMContext);
  252. if (&format == &llvm::APFloat::IEEEdouble())
  253. return llvm::Type::getDoubleTy(VMContext);
  254. if (&format == &llvm::APFloat::IEEEquad())
  255. return llvm::Type::getFP128Ty(VMContext);
  256. if (&format == &llvm::APFloat::PPCDoubleDouble())
  257. return llvm::Type::getPPC_FP128Ty(VMContext);
  258. if (&format == &llvm::APFloat::x87DoubleExtended())
  259. return llvm::Type::getX86_FP80Ty(VMContext);
  260. llvm_unreachable("Unknown float format!");
  261. }
  262. llvm::Type *CodeGenTypes::ConvertFunctionType(QualType QFT,
  263. const FunctionDecl *FD) {
  264. assert(QFT.isCanonical());
  265. const Type *Ty = QFT.getTypePtr();
  266. const FunctionType *FT = cast<FunctionType>(QFT.getTypePtr());
  267. // First, check whether we can build the full function type. If the
  268. // function type depends on an incomplete type (e.g. a struct or enum), we
  269. // cannot lower the function type.
  270. if (!isFuncTypeConvertible(FT)) {
  271. // This function's type depends on an incomplete tag type.
  272. // Force conversion of all the relevant record types, to make sure
  273. // we re-convert the FunctionType when appropriate.
  274. if (const RecordType *RT = FT->getReturnType()->getAs<RecordType>())
  275. ConvertRecordDeclType(RT->getDecl());
  276. if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT))
  277. for (unsigned i = 0, e = FPT->getNumParams(); i != e; i++)
  278. if (const RecordType *RT = FPT->getParamType(i)->getAs<RecordType>())
  279. ConvertRecordDeclType(RT->getDecl());
  280. SkippedLayout = true;
  281. // Return a placeholder type.
  282. return llvm::StructType::get(getLLVMContext());
  283. }
  284. // While we're converting the parameter types for a function, we don't want
  285. // to recursively convert any pointed-to structs. Converting directly-used
  286. // structs is ok though.
  287. if (!RecordsBeingLaidOut.insert(Ty).second) {
  288. SkippedLayout = true;
  289. return llvm::StructType::get(getLLVMContext());
  290. }
  291. // The function type can be built; call the appropriate routines to
  292. // build it.
  293. const CGFunctionInfo *FI;
  294. if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
  295. FI = &arrangeFreeFunctionType(
  296. CanQual<FunctionProtoType>::CreateUnsafe(QualType(FPT, 0)), FD);
  297. } else {
  298. const FunctionNoProtoType *FNPT = cast<FunctionNoProtoType>(FT);
  299. FI = &arrangeFreeFunctionType(
  300. CanQual<FunctionNoProtoType>::CreateUnsafe(QualType(FNPT, 0)));
  301. }
  302. llvm::Type *ResultType = nullptr;
  303. // If there is something higher level prodding our CGFunctionInfo, then
  304. // don't recurse into it again.
  305. if (FunctionsBeingProcessed.count(FI)) {
  306. ResultType = llvm::StructType::get(getLLVMContext());
  307. SkippedLayout = true;
  308. } else {
  309. // Otherwise, we're good to go, go ahead and convert it.
  310. ResultType = GetFunctionType(*FI);
  311. }
  312. RecordsBeingLaidOut.erase(Ty);
  313. if (SkippedLayout)
  314. TypeCache.clear();
  315. if (RecordsBeingLaidOut.empty())
  316. while (!DeferredRecords.empty())
  317. ConvertRecordDeclType(DeferredRecords.pop_back_val());
  318. return ResultType;
  319. }
  320. /// ConvertType - Convert the specified type to its LLVM form.
  321. llvm::Type *CodeGenTypes::ConvertType(QualType T) {
  322. T = Context.getCanonicalType(T);
  323. const Type *Ty = T.getTypePtr();
  324. // RecordTypes are cached and processed specially.
  325. if (const RecordType *RT = dyn_cast<RecordType>(Ty))
  326. return ConvertRecordDeclType(RT->getDecl());
  327. // See if type is already cached.
  328. llvm::DenseMap<const Type *, llvm::Type *>::iterator TCI = TypeCache.find(Ty);
  329. // If type is found in map then use it. Otherwise, convert type T.
  330. if (TCI != TypeCache.end())
  331. return TCI->second;
  332. // If we don't have it in the cache, convert it now.
  333. llvm::Type *ResultType = nullptr;
  334. switch (Ty->getTypeClass()) {
  335. case Type::Record: // Handled above.
  336. #define TYPE(Class, Base)
  337. #define ABSTRACT_TYPE(Class, Base)
  338. #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
  339. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  340. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
  341. #include "clang/AST/TypeNodes.def"
  342. llvm_unreachable("Non-canonical or dependent types aren't possible.");
  343. case Type::Builtin: {
  344. switch (cast<BuiltinType>(Ty)->getKind()) {
  345. case BuiltinType::Void:
  346. case BuiltinType::ObjCId:
  347. case BuiltinType::ObjCClass:
  348. case BuiltinType::ObjCSel:
  349. // LLVM void type can only be used as the result of a function call. Just
  350. // map to the same as char.
  351. ResultType = llvm::Type::getInt8Ty(getLLVMContext());
  352. break;
  353. case BuiltinType::Bool:
  354. // Note that we always return bool as i1 for use as a scalar type.
  355. ResultType = llvm::Type::getInt1Ty(getLLVMContext());
  356. break;
  357. case BuiltinType::Char_S:
  358. case BuiltinType::Char_U:
  359. case BuiltinType::SChar:
  360. case BuiltinType::UChar:
  361. case BuiltinType::Short:
  362. case BuiltinType::UShort:
  363. case BuiltinType::Int:
  364. case BuiltinType::UInt:
  365. case BuiltinType::Long:
  366. case BuiltinType::ULong:
  367. case BuiltinType::LongLong:
  368. case BuiltinType::ULongLong:
  369. case BuiltinType::WChar_S:
  370. case BuiltinType::WChar_U:
  371. case BuiltinType::Char16:
  372. case BuiltinType::Char32:
  373. ResultType = llvm::IntegerType::get(getLLVMContext(),
  374. static_cast<unsigned>(Context.getTypeSize(T)));
  375. break;
  376. case BuiltinType::Half:
  377. // Half FP can either be storage-only (lowered to i16) or native.
  378. ResultType =
  379. getTypeForFormat(getLLVMContext(), Context.getFloatTypeSemantics(T),
  380. Context.getLangOpts().NativeHalfType ||
  381. Context.getLangOpts().HalfArgsAndReturns);
  382. break;
  383. case BuiltinType::Float:
  384. case BuiltinType::Double:
  385. case BuiltinType::LongDouble:
  386. case BuiltinType::Float128:
  387. ResultType = getTypeForFormat(getLLVMContext(),
  388. Context.getFloatTypeSemantics(T),
  389. /* UseNativeHalf = */ false);
  390. break;
  391. case BuiltinType::NullPtr:
  392. // Model std::nullptr_t as i8*
  393. ResultType = llvm::Type::getInt8PtrTy(getLLVMContext());
  394. break;
  395. case BuiltinType::UInt128:
  396. case BuiltinType::Int128:
  397. ResultType = llvm::IntegerType::get(getLLVMContext(), 128);
  398. break;
  399. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  400. case BuiltinType::Id:
  401. #include "clang/Basic/OpenCLImageTypes.def"
  402. case BuiltinType::OCLSampler:
  403. case BuiltinType::OCLEvent:
  404. case BuiltinType::OCLClkEvent:
  405. case BuiltinType::OCLQueue:
  406. case BuiltinType::OCLNDRange:
  407. case BuiltinType::OCLReserveID:
  408. ResultType = CGM.getOpenCLRuntime().convertOpenCLSpecificType(Ty);
  409. break;
  410. case BuiltinType::Dependent:
  411. #define BUILTIN_TYPE(Id, SingletonId)
  412. #define PLACEHOLDER_TYPE(Id, SingletonId) \
  413. case BuiltinType::Id:
  414. #include "clang/AST/BuiltinTypes.def"
  415. llvm_unreachable("Unexpected placeholder builtin type!");
  416. }
  417. break;
  418. }
  419. case Type::Auto:
  420. case Type::DeducedTemplateSpecialization:
  421. llvm_unreachable("Unexpected undeduced type!");
  422. case Type::Complex: {
  423. llvm::Type *EltTy = ConvertType(cast<ComplexType>(Ty)->getElementType());
  424. ResultType = llvm::StructType::get(EltTy, EltTy, nullptr);
  425. break;
  426. }
  427. case Type::LValueReference:
  428. case Type::RValueReference: {
  429. const ReferenceType *RTy = cast<ReferenceType>(Ty);
  430. QualType ETy = RTy->getPointeeType();
  431. llvm::Type *PointeeType = ConvertTypeForMem(ETy);
  432. unsigned AS = Context.getTargetAddressSpace(ETy);
  433. ResultType = llvm::PointerType::get(PointeeType, AS);
  434. break;
  435. }
  436. case Type::Pointer: {
  437. const PointerType *PTy = cast<PointerType>(Ty);
  438. QualType ETy = PTy->getPointeeType();
  439. llvm::Type *PointeeType = ConvertTypeForMem(ETy);
  440. if (PointeeType->isVoidTy())
  441. PointeeType = llvm::Type::getInt8Ty(getLLVMContext());
  442. unsigned AS = Context.getTargetAddressSpace(ETy);
  443. ResultType = llvm::PointerType::get(PointeeType, AS);
  444. break;
  445. }
  446. case Type::VariableArray: {
  447. const VariableArrayType *A = cast<VariableArrayType>(Ty);
  448. assert(A->getIndexTypeCVRQualifiers() == 0 &&
  449. "FIXME: We only handle trivial array types so far!");
  450. // VLAs resolve to the innermost element type; this matches
  451. // the return of alloca, and there isn't any obviously better choice.
  452. ResultType = ConvertTypeForMem(A->getElementType());
  453. break;
  454. }
  455. case Type::IncompleteArray: {
  456. const IncompleteArrayType *A = cast<IncompleteArrayType>(Ty);
  457. assert(A->getIndexTypeCVRQualifiers() == 0 &&
  458. "FIXME: We only handle trivial array types so far!");
  459. // int X[] -> [0 x int], unless the element type is not sized. If it is
  460. // unsized (e.g. an incomplete struct) just use [0 x i8].
  461. ResultType = ConvertTypeForMem(A->getElementType());
  462. if (!ResultType->isSized()) {
  463. SkippedLayout = true;
  464. ResultType = llvm::Type::getInt8Ty(getLLVMContext());
  465. }
  466. ResultType = llvm::ArrayType::get(ResultType, 0);
  467. break;
  468. }
  469. case Type::ConstantArray: {
  470. const ConstantArrayType *A = cast<ConstantArrayType>(Ty);
  471. llvm::Type *EltTy = ConvertTypeForMem(A->getElementType());
  472. // Lower arrays of undefined struct type to arrays of i8 just to have a
  473. // concrete type.
  474. if (!EltTy->isSized()) {
  475. SkippedLayout = true;
  476. EltTy = llvm::Type::getInt8Ty(getLLVMContext());
  477. }
  478. ResultType = llvm::ArrayType::get(EltTy, A->getSize().getZExtValue());
  479. break;
  480. }
  481. case Type::ExtVector:
  482. case Type::Vector: {
  483. const VectorType *VT = cast<VectorType>(Ty);
  484. ResultType = llvm::VectorType::get(ConvertType(VT->getElementType()),
  485. VT->getNumElements());
  486. break;
  487. }
  488. case Type::FunctionNoProto:
  489. case Type::FunctionProto:
  490. ResultType = ConvertFunctionType(T);
  491. break;
  492. case Type::ObjCObject:
  493. ResultType = ConvertType(cast<ObjCObjectType>(Ty)->getBaseType());
  494. break;
  495. case Type::ObjCInterface: {
  496. // Objective-C interfaces are always opaque (outside of the
  497. // runtime, which can do whatever it likes); we never refine
  498. // these.
  499. llvm::Type *&T = InterfaceTypes[cast<ObjCInterfaceType>(Ty)];
  500. if (!T)
  501. T = llvm::StructType::create(getLLVMContext());
  502. ResultType = T;
  503. break;
  504. }
  505. case Type::ObjCObjectPointer: {
  506. // Protocol qualifications do not influence the LLVM type, we just return a
  507. // pointer to the underlying interface type. We don't need to worry about
  508. // recursive conversion.
  509. llvm::Type *T =
  510. ConvertTypeForMem(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
  511. ResultType = T->getPointerTo();
  512. break;
  513. }
  514. case Type::Enum: {
  515. const EnumDecl *ED = cast<EnumType>(Ty)->getDecl();
  516. if (ED->isCompleteDefinition() || ED->isFixed())
  517. return ConvertType(ED->getIntegerType());
  518. // Return a placeholder 'i32' type. This can be changed later when the
  519. // type is defined (see UpdateCompletedType), but is likely to be the
  520. // "right" answer.
  521. ResultType = llvm::Type::getInt32Ty(getLLVMContext());
  522. break;
  523. }
  524. case Type::BlockPointer: {
  525. const QualType FTy = cast<BlockPointerType>(Ty)->getPointeeType();
  526. llvm::Type *PointeeType = ConvertTypeForMem(FTy);
  527. unsigned AS = Context.getTargetAddressSpace(FTy);
  528. ResultType = llvm::PointerType::get(PointeeType, AS);
  529. break;
  530. }
  531. case Type::MemberPointer: {
  532. auto *MPTy = cast<MemberPointerType>(Ty);
  533. if (!getCXXABI().isMemberPointerConvertible(MPTy)) {
  534. RecordsWithOpaqueMemberPointers.insert(MPTy->getClass());
  535. ResultType = llvm::StructType::create(getLLVMContext());
  536. } else {
  537. ResultType = getCXXABI().ConvertMemberPointerType(MPTy);
  538. }
  539. break;
  540. }
  541. case Type::Atomic: {
  542. QualType valueType = cast<AtomicType>(Ty)->getValueType();
  543. ResultType = ConvertTypeForMem(valueType);
  544. // Pad out to the inflated size if necessary.
  545. uint64_t valueSize = Context.getTypeSize(valueType);
  546. uint64_t atomicSize = Context.getTypeSize(Ty);
  547. if (valueSize != atomicSize) {
  548. assert(valueSize < atomicSize);
  549. llvm::Type *elts[] = {
  550. ResultType,
  551. llvm::ArrayType::get(CGM.Int8Ty, (atomicSize - valueSize) / 8)
  552. };
  553. ResultType = llvm::StructType::get(getLLVMContext(),
  554. llvm::makeArrayRef(elts));
  555. }
  556. break;
  557. }
  558. case Type::Pipe: {
  559. ResultType = CGM.getOpenCLRuntime().getPipeType();
  560. break;
  561. }
  562. }
  563. assert(ResultType && "Didn't convert a type?");
  564. TypeCache[Ty] = ResultType;
  565. return ResultType;
  566. }
  567. bool CodeGenModule::isPaddedAtomicType(QualType type) {
  568. return isPaddedAtomicType(type->castAs<AtomicType>());
  569. }
  570. bool CodeGenModule::isPaddedAtomicType(const AtomicType *type) {
  571. return Context.getTypeSize(type) != Context.getTypeSize(type->getValueType());
  572. }
  573. /// ConvertRecordDeclType - Lay out a tagged decl type like struct or union.
  574. llvm::StructType *CodeGenTypes::ConvertRecordDeclType(const RecordDecl *RD) {
  575. // TagDecl's are not necessarily unique, instead use the (clang)
  576. // type connected to the decl.
  577. const Type *Key = Context.getTagDeclType(RD).getTypePtr();
  578. llvm::StructType *&Entry = RecordDeclTypes[Key];
  579. // If we don't have a StructType at all yet, create the forward declaration.
  580. if (!Entry) {
  581. Entry = llvm::StructType::create(getLLVMContext());
  582. addRecordTypeName(RD, Entry, "");
  583. }
  584. llvm::StructType *Ty = Entry;
  585. // If this is still a forward declaration, or the LLVM type is already
  586. // complete, there's nothing more to do.
  587. RD = RD->getDefinition();
  588. if (!RD || !RD->isCompleteDefinition() || !Ty->isOpaque())
  589. return Ty;
  590. // If converting this type would cause us to infinitely loop, don't do it!
  591. if (!isSafeToConvert(RD, *this)) {
  592. DeferredRecords.push_back(RD);
  593. return Ty;
  594. }
  595. // Okay, this is a definition of a type. Compile the implementation now.
  596. bool InsertResult = RecordsBeingLaidOut.insert(Key).second;
  597. (void)InsertResult;
  598. assert(InsertResult && "Recursively compiling a struct?");
  599. // Force conversion of non-virtual base classes recursively.
  600. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  601. for (const auto &I : CRD->bases()) {
  602. if (I.isVirtual()) continue;
  603. ConvertRecordDeclType(I.getType()->getAs<RecordType>()->getDecl());
  604. }
  605. }
  606. // Layout fields.
  607. CGRecordLayout *Layout = ComputeRecordLayout(RD, Ty);
  608. CGRecordLayouts[Key] = Layout;
  609. // We're done laying out this struct.
  610. bool EraseResult = RecordsBeingLaidOut.erase(Key); (void)EraseResult;
  611. assert(EraseResult && "struct not in RecordsBeingLaidOut set?");
  612. // If this struct blocked a FunctionType conversion, then recompute whatever
  613. // was derived from that.
  614. // FIXME: This is hugely overconservative.
  615. if (SkippedLayout)
  616. TypeCache.clear();
  617. // If we're done converting the outer-most record, then convert any deferred
  618. // structs as well.
  619. if (RecordsBeingLaidOut.empty())
  620. while (!DeferredRecords.empty())
  621. ConvertRecordDeclType(DeferredRecords.pop_back_val());
  622. return Ty;
  623. }
  624. /// getCGRecordLayout - Return record layout info for the given record decl.
  625. const CGRecordLayout &
  626. CodeGenTypes::getCGRecordLayout(const RecordDecl *RD) {
  627. const Type *Key = Context.getTagDeclType(RD).getTypePtr();
  628. const CGRecordLayout *Layout = CGRecordLayouts.lookup(Key);
  629. if (!Layout) {
  630. // Compute the type information.
  631. ConvertRecordDeclType(RD);
  632. // Now try again.
  633. Layout = CGRecordLayouts.lookup(Key);
  634. }
  635. assert(Layout && "Unable to find record layout information for type");
  636. return *Layout;
  637. }
  638. bool CodeGenTypes::isPointerZeroInitializable(QualType T) {
  639. assert (T->isAnyPointerType() && "Invalid type");
  640. return isZeroInitializable(T);
  641. }
  642. bool CodeGenTypes::isZeroInitializable(QualType T) {
  643. if (T->getAs<PointerType>())
  644. return Context.getTargetNullPointerValue(T) == 0;
  645. if (const auto *AT = Context.getAsArrayType(T)) {
  646. if (isa<IncompleteArrayType>(AT))
  647. return true;
  648. if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
  649. if (Context.getConstantArrayElementCount(CAT) == 0)
  650. return true;
  651. T = Context.getBaseElementType(T);
  652. }
  653. // Records are non-zero-initializable if they contain any
  654. // non-zero-initializable subobjects.
  655. if (const RecordType *RT = T->getAs<RecordType>()) {
  656. auto RD = cast<RecordDecl>(RT->getDecl());
  657. return isZeroInitializable(RD);
  658. }
  659. // We have to ask the ABI about member pointers.
  660. if (const MemberPointerType *MPT = T->getAs<MemberPointerType>())
  661. return getCXXABI().isZeroInitializable(MPT);
  662. // Everything else is okay.
  663. return true;
  664. }
  665. bool CodeGenTypes::isZeroInitializable(const RecordDecl *RD) {
  666. return getCGRecordLayout(RD).isZeroInitializable();
  667. }