CodeGenTypes.cpp 28 KB

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