CodeGenTypes.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  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::Char8:
  375. case BuiltinType::Char16:
  376. case BuiltinType::Char32:
  377. case BuiltinType::ShortAccum:
  378. case BuiltinType::Accum:
  379. case BuiltinType::LongAccum:
  380. case BuiltinType::UShortAccum:
  381. case BuiltinType::UAccum:
  382. case BuiltinType::ULongAccum:
  383. case BuiltinType::ShortFract:
  384. case BuiltinType::Fract:
  385. case BuiltinType::LongFract:
  386. case BuiltinType::UShortFract:
  387. case BuiltinType::UFract:
  388. case BuiltinType::ULongFract:
  389. case BuiltinType::SatShortAccum:
  390. case BuiltinType::SatAccum:
  391. case BuiltinType::SatLongAccum:
  392. case BuiltinType::SatUShortAccum:
  393. case BuiltinType::SatUAccum:
  394. case BuiltinType::SatULongAccum:
  395. case BuiltinType::SatShortFract:
  396. case BuiltinType::SatFract:
  397. case BuiltinType::SatLongFract:
  398. case BuiltinType::SatUShortFract:
  399. case BuiltinType::SatUFract:
  400. case BuiltinType::SatULongFract:
  401. ResultType = llvm::IntegerType::get(getLLVMContext(),
  402. static_cast<unsigned>(Context.getTypeSize(T)));
  403. break;
  404. case BuiltinType::Float16:
  405. ResultType =
  406. getTypeForFormat(getLLVMContext(), Context.getFloatTypeSemantics(T),
  407. /* UseNativeHalf = */ true);
  408. break;
  409. case BuiltinType::Half:
  410. // Half FP can either be storage-only (lowered to i16) or native.
  411. ResultType = getTypeForFormat(
  412. getLLVMContext(), Context.getFloatTypeSemantics(T),
  413. Context.getLangOpts().NativeHalfType ||
  414. !Context.getTargetInfo().useFP16ConversionIntrinsics());
  415. break;
  416. case BuiltinType::Float:
  417. case BuiltinType::Double:
  418. case BuiltinType::LongDouble:
  419. case BuiltinType::Float128:
  420. ResultType = getTypeForFormat(getLLVMContext(),
  421. Context.getFloatTypeSemantics(T),
  422. /* UseNativeHalf = */ false);
  423. break;
  424. case BuiltinType::NullPtr:
  425. // Model std::nullptr_t as i8*
  426. ResultType = llvm::Type::getInt8PtrTy(getLLVMContext());
  427. break;
  428. case BuiltinType::UInt128:
  429. case BuiltinType::Int128:
  430. ResultType = llvm::IntegerType::get(getLLVMContext(), 128);
  431. break;
  432. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  433. case BuiltinType::Id:
  434. #include "clang/Basic/OpenCLImageTypes.def"
  435. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  436. case BuiltinType::Id:
  437. #include "clang/Basic/OpenCLExtensionTypes.def"
  438. case BuiltinType::OCLSampler:
  439. case BuiltinType::OCLEvent:
  440. case BuiltinType::OCLClkEvent:
  441. case BuiltinType::OCLQueue:
  442. case BuiltinType::OCLReserveID:
  443. ResultType = CGM.getOpenCLRuntime().convertOpenCLSpecificType(Ty);
  444. break;
  445. case BuiltinType::Dependent:
  446. #define BUILTIN_TYPE(Id, SingletonId)
  447. #define PLACEHOLDER_TYPE(Id, SingletonId) \
  448. case BuiltinType::Id:
  449. #include "clang/AST/BuiltinTypes.def"
  450. llvm_unreachable("Unexpected placeholder builtin type!");
  451. }
  452. break;
  453. }
  454. case Type::Auto:
  455. case Type::DeducedTemplateSpecialization:
  456. llvm_unreachable("Unexpected undeduced type!");
  457. case Type::Complex: {
  458. llvm::Type *EltTy = ConvertType(cast<ComplexType>(Ty)->getElementType());
  459. ResultType = llvm::StructType::get(EltTy, EltTy);
  460. break;
  461. }
  462. case Type::LValueReference:
  463. case Type::RValueReference: {
  464. const ReferenceType *RTy = cast<ReferenceType>(Ty);
  465. QualType ETy = RTy->getPointeeType();
  466. llvm::Type *PointeeType = ConvertTypeForMem(ETy);
  467. unsigned AS = Context.getTargetAddressSpace(ETy);
  468. ResultType = llvm::PointerType::get(PointeeType, AS);
  469. break;
  470. }
  471. case Type::Pointer: {
  472. const PointerType *PTy = cast<PointerType>(Ty);
  473. QualType ETy = PTy->getPointeeType();
  474. llvm::Type *PointeeType = ConvertTypeForMem(ETy);
  475. if (PointeeType->isVoidTy())
  476. PointeeType = llvm::Type::getInt8Ty(getLLVMContext());
  477. unsigned AS = Context.getTargetAddressSpace(ETy);
  478. ResultType = llvm::PointerType::get(PointeeType, AS);
  479. break;
  480. }
  481. case Type::VariableArray: {
  482. const VariableArrayType *A = cast<VariableArrayType>(Ty);
  483. assert(A->getIndexTypeCVRQualifiers() == 0 &&
  484. "FIXME: We only handle trivial array types so far!");
  485. // VLAs resolve to the innermost element type; this matches
  486. // the return of alloca, and there isn't any obviously better choice.
  487. ResultType = ConvertTypeForMem(A->getElementType());
  488. break;
  489. }
  490. case Type::IncompleteArray: {
  491. const IncompleteArrayType *A = cast<IncompleteArrayType>(Ty);
  492. assert(A->getIndexTypeCVRQualifiers() == 0 &&
  493. "FIXME: We only handle trivial array types so far!");
  494. // int X[] -> [0 x int], unless the element type is not sized. If it is
  495. // unsized (e.g. an incomplete struct) just use [0 x i8].
  496. ResultType = ConvertTypeForMem(A->getElementType());
  497. if (!ResultType->isSized()) {
  498. SkippedLayout = true;
  499. ResultType = llvm::Type::getInt8Ty(getLLVMContext());
  500. }
  501. ResultType = llvm::ArrayType::get(ResultType, 0);
  502. break;
  503. }
  504. case Type::ConstantArray: {
  505. const ConstantArrayType *A = cast<ConstantArrayType>(Ty);
  506. llvm::Type *EltTy = ConvertTypeForMem(A->getElementType());
  507. // Lower arrays of undefined struct type to arrays of i8 just to have a
  508. // concrete type.
  509. if (!EltTy->isSized()) {
  510. SkippedLayout = true;
  511. EltTy = llvm::Type::getInt8Ty(getLLVMContext());
  512. }
  513. ResultType = llvm::ArrayType::get(EltTy, A->getSize().getZExtValue());
  514. break;
  515. }
  516. case Type::ExtVector:
  517. case Type::Vector: {
  518. const VectorType *VT = cast<VectorType>(Ty);
  519. ResultType = llvm::VectorType::get(ConvertType(VT->getElementType()),
  520. VT->getNumElements());
  521. break;
  522. }
  523. case Type::FunctionNoProto:
  524. case Type::FunctionProto:
  525. ResultType = ConvertFunctionType(T);
  526. break;
  527. case Type::ObjCObject:
  528. ResultType = ConvertType(cast<ObjCObjectType>(Ty)->getBaseType());
  529. break;
  530. case Type::ObjCInterface: {
  531. // Objective-C interfaces are always opaque (outside of the
  532. // runtime, which can do whatever it likes); we never refine
  533. // these.
  534. llvm::Type *&T = InterfaceTypes[cast<ObjCInterfaceType>(Ty)];
  535. if (!T)
  536. T = llvm::StructType::create(getLLVMContext());
  537. ResultType = T;
  538. break;
  539. }
  540. case Type::ObjCObjectPointer: {
  541. // Protocol qualifications do not influence the LLVM type, we just return a
  542. // pointer to the underlying interface type. We don't need to worry about
  543. // recursive conversion.
  544. llvm::Type *T =
  545. ConvertTypeForMem(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
  546. ResultType = T->getPointerTo();
  547. break;
  548. }
  549. case Type::Enum: {
  550. const EnumDecl *ED = cast<EnumType>(Ty)->getDecl();
  551. if (ED->isCompleteDefinition() || ED->isFixed())
  552. return ConvertType(ED->getIntegerType());
  553. // Return a placeholder 'i32' type. This can be changed later when the
  554. // type is defined (see UpdateCompletedType), but is likely to be the
  555. // "right" answer.
  556. ResultType = llvm::Type::getInt32Ty(getLLVMContext());
  557. break;
  558. }
  559. case Type::BlockPointer: {
  560. const QualType FTy = cast<BlockPointerType>(Ty)->getPointeeType();
  561. llvm::Type *PointeeType = ConvertTypeForMem(FTy);
  562. unsigned AS = Context.getTargetAddressSpace(FTy);
  563. ResultType = llvm::PointerType::get(PointeeType, AS);
  564. break;
  565. }
  566. case Type::MemberPointer: {
  567. auto *MPTy = cast<MemberPointerType>(Ty);
  568. if (!getCXXABI().isMemberPointerConvertible(MPTy)) {
  569. RecordsWithOpaqueMemberPointers.insert(MPTy->getClass());
  570. ResultType = llvm::StructType::create(getLLVMContext());
  571. } else {
  572. ResultType = getCXXABI().ConvertMemberPointerType(MPTy);
  573. }
  574. break;
  575. }
  576. case Type::Atomic: {
  577. QualType valueType = cast<AtomicType>(Ty)->getValueType();
  578. ResultType = ConvertTypeForMem(valueType);
  579. // Pad out to the inflated size if necessary.
  580. uint64_t valueSize = Context.getTypeSize(valueType);
  581. uint64_t atomicSize = Context.getTypeSize(Ty);
  582. if (valueSize != atomicSize) {
  583. assert(valueSize < atomicSize);
  584. llvm::Type *elts[] = {
  585. ResultType,
  586. llvm::ArrayType::get(CGM.Int8Ty, (atomicSize - valueSize) / 8)
  587. };
  588. ResultType = llvm::StructType::get(getLLVMContext(),
  589. llvm::makeArrayRef(elts));
  590. }
  591. break;
  592. }
  593. case Type::Pipe: {
  594. ResultType = CGM.getOpenCLRuntime().getPipeType(cast<PipeType>(Ty));
  595. break;
  596. }
  597. }
  598. assert(ResultType && "Didn't convert a type?");
  599. TypeCache[Ty] = ResultType;
  600. return ResultType;
  601. }
  602. bool CodeGenModule::isPaddedAtomicType(QualType type) {
  603. return isPaddedAtomicType(type->castAs<AtomicType>());
  604. }
  605. bool CodeGenModule::isPaddedAtomicType(const AtomicType *type) {
  606. return Context.getTypeSize(type) != Context.getTypeSize(type->getValueType());
  607. }
  608. /// ConvertRecordDeclType - Lay out a tagged decl type like struct or union.
  609. llvm::StructType *CodeGenTypes::ConvertRecordDeclType(const RecordDecl *RD) {
  610. // TagDecl's are not necessarily unique, instead use the (clang)
  611. // type connected to the decl.
  612. const Type *Key = Context.getTagDeclType(RD).getTypePtr();
  613. llvm::StructType *&Entry = RecordDeclTypes[Key];
  614. // If we don't have a StructType at all yet, create the forward declaration.
  615. if (!Entry) {
  616. Entry = llvm::StructType::create(getLLVMContext());
  617. addRecordTypeName(RD, Entry, "");
  618. }
  619. llvm::StructType *Ty = Entry;
  620. // If this is still a forward declaration, or the LLVM type is already
  621. // complete, there's nothing more to do.
  622. RD = RD->getDefinition();
  623. if (!RD || !RD->isCompleteDefinition() || !Ty->isOpaque())
  624. return Ty;
  625. // If converting this type would cause us to infinitely loop, don't do it!
  626. if (!isSafeToConvert(RD, *this)) {
  627. DeferredRecords.push_back(RD);
  628. return Ty;
  629. }
  630. // Okay, this is a definition of a type. Compile the implementation now.
  631. bool InsertResult = RecordsBeingLaidOut.insert(Key).second;
  632. (void)InsertResult;
  633. assert(InsertResult && "Recursively compiling a struct?");
  634. // Force conversion of non-virtual base classes recursively.
  635. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  636. for (const auto &I : CRD->bases()) {
  637. if (I.isVirtual()) continue;
  638. ConvertRecordDeclType(I.getType()->getAs<RecordType>()->getDecl());
  639. }
  640. }
  641. // Layout fields.
  642. CGRecordLayout *Layout = ComputeRecordLayout(RD, Ty);
  643. CGRecordLayouts[Key] = Layout;
  644. // We're done laying out this struct.
  645. bool EraseResult = RecordsBeingLaidOut.erase(Key); (void)EraseResult;
  646. assert(EraseResult && "struct not in RecordsBeingLaidOut set?");
  647. // If this struct blocked a FunctionType conversion, then recompute whatever
  648. // was derived from that.
  649. // FIXME: This is hugely overconservative.
  650. if (SkippedLayout)
  651. TypeCache.clear();
  652. // If we're done converting the outer-most record, then convert any deferred
  653. // structs as well.
  654. if (RecordsBeingLaidOut.empty())
  655. while (!DeferredRecords.empty())
  656. ConvertRecordDeclType(DeferredRecords.pop_back_val());
  657. return Ty;
  658. }
  659. /// getCGRecordLayout - Return record layout info for the given record decl.
  660. const CGRecordLayout &
  661. CodeGenTypes::getCGRecordLayout(const RecordDecl *RD) {
  662. const Type *Key = Context.getTagDeclType(RD).getTypePtr();
  663. const CGRecordLayout *Layout = CGRecordLayouts.lookup(Key);
  664. if (!Layout) {
  665. // Compute the type information.
  666. ConvertRecordDeclType(RD);
  667. // Now try again.
  668. Layout = CGRecordLayouts.lookup(Key);
  669. }
  670. assert(Layout && "Unable to find record layout information for type");
  671. return *Layout;
  672. }
  673. bool CodeGenTypes::isPointerZeroInitializable(QualType T) {
  674. assert((T->isAnyPointerType() || T->isBlockPointerType()) && "Invalid type");
  675. return isZeroInitializable(T);
  676. }
  677. bool CodeGenTypes::isZeroInitializable(QualType T) {
  678. if (T->getAs<PointerType>())
  679. return Context.getTargetNullPointerValue(T) == 0;
  680. if (const auto *AT = Context.getAsArrayType(T)) {
  681. if (isa<IncompleteArrayType>(AT))
  682. return true;
  683. if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
  684. if (Context.getConstantArrayElementCount(CAT) == 0)
  685. return true;
  686. T = Context.getBaseElementType(T);
  687. }
  688. // Records are non-zero-initializable if they contain any
  689. // non-zero-initializable subobjects.
  690. if (const RecordType *RT = T->getAs<RecordType>()) {
  691. const RecordDecl *RD = RT->getDecl();
  692. return isZeroInitializable(RD);
  693. }
  694. // We have to ask the ABI about member pointers.
  695. if (const MemberPointerType *MPT = T->getAs<MemberPointerType>())
  696. return getCXXABI().isZeroInitializable(MPT);
  697. // Everything else is okay.
  698. return true;
  699. }
  700. bool CodeGenTypes::isZeroInitializable(const RecordDecl *RD) {
  701. return getCGRecordLayout(RD).isZeroInitializable();
  702. }