SwiftCallingConv.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  1. //===--- SwiftCallingConv.cpp - Lowering for the Swift calling convention -===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Implementation of the abstract lowering for the Swift calling convention.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/CodeGen/SwiftCallingConv.h"
  13. #include "clang/Basic/TargetInfo.h"
  14. #include "CodeGenModule.h"
  15. #include "TargetInfo.h"
  16. using namespace clang;
  17. using namespace CodeGen;
  18. using namespace swiftcall;
  19. static const SwiftABIInfo &getSwiftABIInfo(CodeGenModule &CGM) {
  20. return cast<SwiftABIInfo>(CGM.getTargetCodeGenInfo().getABIInfo());
  21. }
  22. static bool isPowerOf2(unsigned n) {
  23. return n == (n & -n);
  24. }
  25. /// Given two types with the same size, try to find a common type.
  26. static llvm::Type *getCommonType(llvm::Type *first, llvm::Type *second) {
  27. assert(first != second);
  28. // Allow pointers to merge with integers, but prefer the integer type.
  29. if (first->isIntegerTy()) {
  30. if (second->isPointerTy()) return first;
  31. } else if (first->isPointerTy()) {
  32. if (second->isIntegerTy()) return second;
  33. if (second->isPointerTy()) return first;
  34. // Allow two vectors to be merged (given that they have the same size).
  35. // This assumes that we never have two different vector register sets.
  36. } else if (auto firstVecTy = dyn_cast<llvm::VectorType>(first)) {
  37. if (auto secondVecTy = dyn_cast<llvm::VectorType>(second)) {
  38. if (auto commonTy = getCommonType(firstVecTy->getElementType(),
  39. secondVecTy->getElementType())) {
  40. return (commonTy == firstVecTy->getElementType() ? first : second);
  41. }
  42. }
  43. }
  44. return nullptr;
  45. }
  46. static CharUnits getTypeStoreSize(CodeGenModule &CGM, llvm::Type *type) {
  47. return CharUnits::fromQuantity(CGM.getDataLayout().getTypeStoreSize(type));
  48. }
  49. static CharUnits getTypeAllocSize(CodeGenModule &CGM, llvm::Type *type) {
  50. return CharUnits::fromQuantity(CGM.getDataLayout().getTypeAllocSize(type));
  51. }
  52. void SwiftAggLowering::addTypedData(QualType type, CharUnits begin) {
  53. // Deal with various aggregate types as special cases:
  54. // Record types.
  55. if (auto recType = type->getAs<RecordType>()) {
  56. addTypedData(recType->getDecl(), begin);
  57. // Array types.
  58. } else if (type->isArrayType()) {
  59. // Incomplete array types (flexible array members?) don't provide
  60. // data to lay out, and the other cases shouldn't be possible.
  61. auto arrayType = CGM.getContext().getAsConstantArrayType(type);
  62. if (!arrayType) return;
  63. QualType eltType = arrayType->getElementType();
  64. auto eltSize = CGM.getContext().getTypeSizeInChars(eltType);
  65. for (uint64_t i = 0, e = arrayType->getSize().getZExtValue(); i != e; ++i) {
  66. addTypedData(eltType, begin + i * eltSize);
  67. }
  68. // Complex types.
  69. } else if (auto complexType = type->getAs<ComplexType>()) {
  70. auto eltType = complexType->getElementType();
  71. auto eltSize = CGM.getContext().getTypeSizeInChars(eltType);
  72. auto eltLLVMType = CGM.getTypes().ConvertType(eltType);
  73. addTypedData(eltLLVMType, begin, begin + eltSize);
  74. addTypedData(eltLLVMType, begin + eltSize, begin + 2 * eltSize);
  75. // Member pointer types.
  76. } else if (type->getAs<MemberPointerType>()) {
  77. // Just add it all as opaque.
  78. addOpaqueData(begin, begin + CGM.getContext().getTypeSizeInChars(type));
  79. // Everything else is scalar and should not convert as an LLVM aggregate.
  80. } else {
  81. // We intentionally convert as !ForMem because we want to preserve
  82. // that a type was an i1.
  83. auto llvmType = CGM.getTypes().ConvertType(type);
  84. addTypedData(llvmType, begin);
  85. }
  86. }
  87. void SwiftAggLowering::addTypedData(const RecordDecl *record, CharUnits begin) {
  88. addTypedData(record, begin, CGM.getContext().getASTRecordLayout(record));
  89. }
  90. void SwiftAggLowering::addTypedData(const RecordDecl *record, CharUnits begin,
  91. const ASTRecordLayout &layout) {
  92. // Unions are a special case.
  93. if (record->isUnion()) {
  94. for (auto field : record->fields()) {
  95. if (field->isBitField()) {
  96. addBitFieldData(field, begin, 0);
  97. } else {
  98. addTypedData(field->getType(), begin);
  99. }
  100. }
  101. return;
  102. }
  103. // Note that correctness does not rely on us adding things in
  104. // their actual order of layout; it's just somewhat more efficient
  105. // for the builder.
  106. // With that in mind, add "early" C++ data.
  107. auto cxxRecord = dyn_cast<CXXRecordDecl>(record);
  108. if (cxxRecord) {
  109. // - a v-table pointer, if the class adds its own
  110. if (layout.hasOwnVFPtr()) {
  111. addTypedData(CGM.Int8PtrTy, begin);
  112. }
  113. // - non-virtual bases
  114. for (auto &baseSpecifier : cxxRecord->bases()) {
  115. if (baseSpecifier.isVirtual()) continue;
  116. auto baseRecord = baseSpecifier.getType()->getAsCXXRecordDecl();
  117. addTypedData(baseRecord, begin + layout.getBaseClassOffset(baseRecord));
  118. }
  119. // - a vbptr if the class adds its own
  120. if (layout.hasOwnVBPtr()) {
  121. addTypedData(CGM.Int8PtrTy, begin + layout.getVBPtrOffset());
  122. }
  123. }
  124. // Add fields.
  125. for (auto field : record->fields()) {
  126. auto fieldOffsetInBits = layout.getFieldOffset(field->getFieldIndex());
  127. if (field->isBitField()) {
  128. addBitFieldData(field, begin, fieldOffsetInBits);
  129. } else {
  130. addTypedData(field->getType(),
  131. begin + CGM.getContext().toCharUnitsFromBits(fieldOffsetInBits));
  132. }
  133. }
  134. // Add "late" C++ data:
  135. if (cxxRecord) {
  136. // - virtual bases
  137. for (auto &vbaseSpecifier : cxxRecord->vbases()) {
  138. auto baseRecord = vbaseSpecifier.getType()->getAsCXXRecordDecl();
  139. addTypedData(baseRecord, begin + layout.getVBaseClassOffset(baseRecord));
  140. }
  141. }
  142. }
  143. void SwiftAggLowering::addBitFieldData(const FieldDecl *bitfield,
  144. CharUnits recordBegin,
  145. uint64_t bitfieldBitBegin) {
  146. assert(bitfield->isBitField());
  147. auto &ctx = CGM.getContext();
  148. auto width = bitfield->getBitWidthValue(ctx);
  149. // We can ignore zero-width bit-fields.
  150. if (width == 0) return;
  151. // toCharUnitsFromBits rounds down.
  152. CharUnits bitfieldByteBegin = ctx.toCharUnitsFromBits(bitfieldBitBegin);
  153. // Find the offset of the last byte that is partially occupied by the
  154. // bit-field; since we otherwise expect exclusive ends, the end is the
  155. // next byte.
  156. uint64_t bitfieldBitLast = bitfieldBitBegin + width - 1;
  157. CharUnits bitfieldByteEnd =
  158. ctx.toCharUnitsFromBits(bitfieldBitLast) + CharUnits::One();
  159. addOpaqueData(recordBegin + bitfieldByteBegin,
  160. recordBegin + bitfieldByteEnd);
  161. }
  162. void SwiftAggLowering::addTypedData(llvm::Type *type, CharUnits begin) {
  163. assert(type && "didn't provide type for typed data");
  164. addTypedData(type, begin, begin + getTypeStoreSize(CGM, type));
  165. }
  166. void SwiftAggLowering::addTypedData(llvm::Type *type,
  167. CharUnits begin, CharUnits end) {
  168. assert(type && "didn't provide type for typed data");
  169. assert(getTypeStoreSize(CGM, type) == end - begin);
  170. // Legalize vector types.
  171. if (auto vecTy = dyn_cast<llvm::VectorType>(type)) {
  172. SmallVector<llvm::Type*, 4> componentTys;
  173. legalizeVectorType(CGM, end - begin, vecTy, componentTys);
  174. assert(componentTys.size() >= 1);
  175. // Walk the initial components.
  176. for (size_t i = 0, e = componentTys.size(); i != e - 1; ++i) {
  177. llvm::Type *componentTy = componentTys[i];
  178. auto componentSize = getTypeStoreSize(CGM, componentTy);
  179. assert(componentSize < end - begin);
  180. addLegalTypedData(componentTy, begin, begin + componentSize);
  181. begin += componentSize;
  182. }
  183. return addLegalTypedData(componentTys.back(), begin, end);
  184. }
  185. // Legalize integer types.
  186. if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
  187. if (!isLegalIntegerType(CGM, intTy))
  188. return addOpaqueData(begin, end);
  189. }
  190. // All other types should be legal.
  191. return addLegalTypedData(type, begin, end);
  192. }
  193. void SwiftAggLowering::addLegalTypedData(llvm::Type *type,
  194. CharUnits begin, CharUnits end) {
  195. // Require the type to be naturally aligned.
  196. if (!begin.isZero() && !begin.isMultipleOf(getNaturalAlignment(CGM, type))) {
  197. // Try splitting vector types.
  198. if (auto vecTy = dyn_cast<llvm::VectorType>(type)) {
  199. auto split = splitLegalVectorType(CGM, end - begin, vecTy);
  200. auto eltTy = split.first;
  201. auto numElts = split.second;
  202. auto eltSize = (end - begin) / numElts;
  203. assert(eltSize == getTypeStoreSize(CGM, eltTy));
  204. for (size_t i = 0, e = numElts; i != e; ++i) {
  205. addLegalTypedData(eltTy, begin, begin + eltSize);
  206. begin += eltSize;
  207. }
  208. assert(begin == end);
  209. return;
  210. }
  211. return addOpaqueData(begin, end);
  212. }
  213. addEntry(type, begin, end);
  214. }
  215. void SwiftAggLowering::addEntry(llvm::Type *type,
  216. CharUnits begin, CharUnits end) {
  217. assert((!type ||
  218. (!isa<llvm::StructType>(type) && !isa<llvm::ArrayType>(type))) &&
  219. "cannot add aggregate-typed data");
  220. assert(!type || begin.isMultipleOf(getNaturalAlignment(CGM, type)));
  221. // Fast path: we can just add entries to the end.
  222. if (Entries.empty() || Entries.back().End <= begin) {
  223. Entries.push_back({begin, end, type});
  224. return;
  225. }
  226. // Find the first existing entry that ends after the start of the new data.
  227. // TODO: do a binary search if Entries is big enough for it to matter.
  228. size_t index = Entries.size() - 1;
  229. while (index != 0) {
  230. if (Entries[index - 1].End <= begin) break;
  231. --index;
  232. }
  233. // The entry ends after the start of the new data.
  234. // If the entry starts after the end of the new data, there's no conflict.
  235. if (Entries[index].Begin >= end) {
  236. // This insertion is potentially O(n), but the way we generally build
  237. // these layouts makes that unlikely to matter: we'd need a union of
  238. // several very large types.
  239. Entries.insert(Entries.begin() + index, {begin, end, type});
  240. return;
  241. }
  242. // Otherwise, the ranges overlap. The new range might also overlap
  243. // with later ranges.
  244. restartAfterSplit:
  245. // Simplest case: an exact overlap.
  246. if (Entries[index].Begin == begin && Entries[index].End == end) {
  247. // If the types match exactly, great.
  248. if (Entries[index].Type == type) return;
  249. // If either type is opaque, make the entry opaque and return.
  250. if (Entries[index].Type == nullptr) {
  251. return;
  252. } else if (type == nullptr) {
  253. Entries[index].Type = nullptr;
  254. return;
  255. }
  256. // If they disagree in an ABI-agnostic way, just resolve the conflict
  257. // arbitrarily.
  258. if (auto entryType = getCommonType(Entries[index].Type, type)) {
  259. Entries[index].Type = entryType;
  260. return;
  261. }
  262. // Otherwise, make the entry opaque.
  263. Entries[index].Type = nullptr;
  264. return;
  265. }
  266. // Okay, we have an overlapping conflict of some sort.
  267. // If we have a vector type, split it.
  268. if (auto vecTy = dyn_cast_or_null<llvm::VectorType>(type)) {
  269. auto eltTy = vecTy->getElementType();
  270. CharUnits eltSize = (end - begin) / vecTy->getNumElements();
  271. assert(eltSize == getTypeStoreSize(CGM, eltTy));
  272. for (unsigned i = 0, e = vecTy->getNumElements(); i != e; ++i) {
  273. addEntry(eltTy, begin, begin + eltSize);
  274. begin += eltSize;
  275. }
  276. assert(begin == end);
  277. return;
  278. }
  279. // If the entry is a vector type, split it and try again.
  280. if (Entries[index].Type && Entries[index].Type->isVectorTy()) {
  281. splitVectorEntry(index);
  282. goto restartAfterSplit;
  283. }
  284. // Okay, we have no choice but to make the existing entry opaque.
  285. Entries[index].Type = nullptr;
  286. // Stretch the start of the entry to the beginning of the range.
  287. if (begin < Entries[index].Begin) {
  288. Entries[index].Begin = begin;
  289. assert(index == 0 || begin >= Entries[index - 1].End);
  290. }
  291. // Stretch the end of the entry to the end of the range; but if we run
  292. // into the start of the next entry, just leave the range there and repeat.
  293. while (end > Entries[index].End) {
  294. assert(Entries[index].Type == nullptr);
  295. // If the range doesn't overlap the next entry, we're done.
  296. if (index == Entries.size() - 1 || end <= Entries[index + 1].Begin) {
  297. Entries[index].End = end;
  298. break;
  299. }
  300. // Otherwise, stretch to the start of the next entry.
  301. Entries[index].End = Entries[index + 1].Begin;
  302. // Continue with the next entry.
  303. index++;
  304. // This entry needs to be made opaque if it is not already.
  305. if (Entries[index].Type == nullptr)
  306. continue;
  307. // Split vector entries unless we completely subsume them.
  308. if (Entries[index].Type->isVectorTy() &&
  309. end < Entries[index].End) {
  310. splitVectorEntry(index);
  311. }
  312. // Make the entry opaque.
  313. Entries[index].Type = nullptr;
  314. }
  315. }
  316. /// Replace the entry of vector type at offset 'index' with a sequence
  317. /// of its component vectors.
  318. void SwiftAggLowering::splitVectorEntry(unsigned index) {
  319. auto vecTy = cast<llvm::VectorType>(Entries[index].Type);
  320. auto split = splitLegalVectorType(CGM, Entries[index].getWidth(), vecTy);
  321. auto eltTy = split.first;
  322. CharUnits eltSize = getTypeStoreSize(CGM, eltTy);
  323. auto numElts = split.second;
  324. Entries.insert(Entries.begin() + index + 1, numElts - 1, StorageEntry());
  325. CharUnits begin = Entries[index].Begin;
  326. for (unsigned i = 0; i != numElts; ++i) {
  327. Entries[index].Type = eltTy;
  328. Entries[index].Begin = begin;
  329. Entries[index].End = begin + eltSize;
  330. begin += eltSize;
  331. }
  332. }
  333. /// Given a power-of-two unit size, return the offset of the aligned unit
  334. /// of that size which contains the given offset.
  335. ///
  336. /// In other words, round down to the nearest multiple of the unit size.
  337. static CharUnits getOffsetAtStartOfUnit(CharUnits offset, CharUnits unitSize) {
  338. assert(isPowerOf2(unitSize.getQuantity()));
  339. auto unitMask = ~(unitSize.getQuantity() - 1);
  340. return CharUnits::fromQuantity(offset.getQuantity() & unitMask);
  341. }
  342. static bool areBytesInSameUnit(CharUnits first, CharUnits second,
  343. CharUnits chunkSize) {
  344. return getOffsetAtStartOfUnit(first, chunkSize)
  345. == getOffsetAtStartOfUnit(second, chunkSize);
  346. }
  347. static bool isMergeableEntryType(llvm::Type *type) {
  348. // Opaquely-typed memory is always mergeable.
  349. if (type == nullptr) return true;
  350. // Pointers and integers are always mergeable. In theory we should not
  351. // merge pointers, but (1) it doesn't currently matter in practice because
  352. // the chunk size is never greater than the size of a pointer and (2)
  353. // Swift IRGen uses integer types for a lot of things that are "really"
  354. // just storing pointers (like Optional<SomePointer>). If we ever have a
  355. // target that would otherwise combine pointers, we should put some effort
  356. // into fixing those cases in Swift IRGen and then call out pointer types
  357. // here.
  358. // Floating-point and vector types should never be merged.
  359. // Most such types are too large and highly-aligned to ever trigger merging
  360. // in practice, but it's important for the rule to cover at least 'half'
  361. // and 'float', as well as things like small vectors of 'i1' or 'i8'.
  362. return (!type->isFloatingPointTy() && !type->isVectorTy());
  363. }
  364. bool SwiftAggLowering::shouldMergeEntries(const StorageEntry &first,
  365. const StorageEntry &second,
  366. CharUnits chunkSize) {
  367. // Only merge entries that overlap the same chunk. We test this first
  368. // despite being a bit more expensive because this is the condition that
  369. // tends to prevent merging.
  370. if (!areBytesInSameUnit(first.End - CharUnits::One(), second.Begin,
  371. chunkSize))
  372. return false;
  373. return (isMergeableEntryType(first.Type) &&
  374. isMergeableEntryType(second.Type));
  375. }
  376. void SwiftAggLowering::finish() {
  377. if (Entries.empty()) {
  378. Finished = true;
  379. return;
  380. }
  381. // We logically split the layout down into a series of chunks of this size,
  382. // which is generally the size of a pointer.
  383. const CharUnits chunkSize = getMaximumVoluntaryIntegerSize(CGM);
  384. // First pass: if two entries should be merged, make them both opaque
  385. // and stretch one to meet the next.
  386. // Also, remember if there are any opaque entries.
  387. bool hasOpaqueEntries = (Entries[0].Type == nullptr);
  388. for (size_t i = 1, e = Entries.size(); i != e; ++i) {
  389. if (shouldMergeEntries(Entries[i - 1], Entries[i], chunkSize)) {
  390. Entries[i - 1].Type = nullptr;
  391. Entries[i].Type = nullptr;
  392. Entries[i - 1].End = Entries[i].Begin;
  393. hasOpaqueEntries = true;
  394. } else if (Entries[i].Type == nullptr) {
  395. hasOpaqueEntries = true;
  396. }
  397. }
  398. // The rest of the algorithm leaves non-opaque entries alone, so if we
  399. // have no opaque entries, we're done.
  400. if (!hasOpaqueEntries) {
  401. Finished = true;
  402. return;
  403. }
  404. // Okay, move the entries to a temporary and rebuild Entries.
  405. auto orig = std::move(Entries);
  406. assert(Entries.empty());
  407. for (size_t i = 0, e = orig.size(); i != e; ++i) {
  408. // Just copy over non-opaque entries.
  409. if (orig[i].Type != nullptr) {
  410. Entries.push_back(orig[i]);
  411. continue;
  412. }
  413. // Scan forward to determine the full extent of the next opaque range.
  414. // We know from the first pass that only contiguous ranges will overlap
  415. // the same aligned chunk.
  416. auto begin = orig[i].Begin;
  417. auto end = orig[i].End;
  418. while (i + 1 != e &&
  419. orig[i + 1].Type == nullptr &&
  420. end == orig[i + 1].Begin) {
  421. end = orig[i + 1].End;
  422. i++;
  423. }
  424. // Add an entry per intersected chunk.
  425. do {
  426. // Find the smallest aligned storage unit in the maximal aligned
  427. // storage unit containing 'begin' that contains all the bytes in
  428. // the intersection between the range and this chunk.
  429. CharUnits localBegin = begin;
  430. CharUnits chunkBegin = getOffsetAtStartOfUnit(localBegin, chunkSize);
  431. CharUnits chunkEnd = chunkBegin + chunkSize;
  432. CharUnits localEnd = std::min(end, chunkEnd);
  433. // Just do a simple loop over ever-increasing unit sizes.
  434. CharUnits unitSize = CharUnits::One();
  435. CharUnits unitBegin, unitEnd;
  436. for (; ; unitSize *= 2) {
  437. assert(unitSize <= chunkSize);
  438. unitBegin = getOffsetAtStartOfUnit(localBegin, unitSize);
  439. unitEnd = unitBegin + unitSize;
  440. if (unitEnd >= localEnd) break;
  441. }
  442. // Add an entry for this unit.
  443. auto entryTy =
  444. llvm::IntegerType::get(CGM.getLLVMContext(),
  445. CGM.getContext().toBits(unitSize));
  446. Entries.push_back({unitBegin, unitEnd, entryTy});
  447. // The next chunk starts where this chunk left off.
  448. begin = localEnd;
  449. } while (begin != end);
  450. }
  451. // Okay, finally finished.
  452. Finished = true;
  453. }
  454. void SwiftAggLowering::enumerateComponents(EnumerationCallback callback) const {
  455. assert(Finished && "haven't yet finished lowering");
  456. for (auto &entry : Entries) {
  457. callback(entry.Begin, entry.End, entry.Type);
  458. }
  459. }
  460. std::pair<llvm::StructType*, llvm::Type*>
  461. SwiftAggLowering::getCoerceAndExpandTypes() const {
  462. assert(Finished && "haven't yet finished lowering");
  463. auto &ctx = CGM.getLLVMContext();
  464. if (Entries.empty()) {
  465. auto type = llvm::StructType::get(ctx);
  466. return { type, type };
  467. }
  468. SmallVector<llvm::Type*, 8> elts;
  469. CharUnits lastEnd = CharUnits::Zero();
  470. bool hasPadding = false;
  471. bool packed = false;
  472. for (auto &entry : Entries) {
  473. if (entry.Begin != lastEnd) {
  474. auto paddingSize = entry.Begin - lastEnd;
  475. assert(!paddingSize.isNegative());
  476. auto padding = llvm::ArrayType::get(llvm::Type::getInt8Ty(ctx),
  477. paddingSize.getQuantity());
  478. elts.push_back(padding);
  479. hasPadding = true;
  480. }
  481. if (!packed && !entry.Begin.isMultipleOf(
  482. CharUnits::fromQuantity(
  483. CGM.getDataLayout().getABITypeAlignment(entry.Type))))
  484. packed = true;
  485. elts.push_back(entry.Type);
  486. lastEnd = entry.Begin + getTypeAllocSize(CGM, entry.Type);
  487. assert(entry.End <= lastEnd);
  488. }
  489. // We don't need to adjust 'packed' to deal with possible tail padding
  490. // because we never do that kind of access through the coercion type.
  491. auto coercionType = llvm::StructType::get(ctx, elts, packed);
  492. llvm::Type *unpaddedType = coercionType;
  493. if (hasPadding) {
  494. elts.clear();
  495. for (auto &entry : Entries) {
  496. elts.push_back(entry.Type);
  497. }
  498. if (elts.size() == 1) {
  499. unpaddedType = elts[0];
  500. } else {
  501. unpaddedType = llvm::StructType::get(ctx, elts, /*packed*/ false);
  502. }
  503. } else if (Entries.size() == 1) {
  504. unpaddedType = Entries[0].Type;
  505. }
  506. return { coercionType, unpaddedType };
  507. }
  508. bool SwiftAggLowering::shouldPassIndirectly(bool asReturnValue) const {
  509. assert(Finished && "haven't yet finished lowering");
  510. // Empty types don't need to be passed indirectly.
  511. if (Entries.empty()) return false;
  512. // Avoid copying the array of types when there's just a single element.
  513. if (Entries.size() == 1) {
  514. return getSwiftABIInfo(CGM).shouldPassIndirectlyForSwift(
  515. Entries.back().Type,
  516. asReturnValue);
  517. }
  518. SmallVector<llvm::Type*, 8> componentTys;
  519. componentTys.reserve(Entries.size());
  520. for (auto &entry : Entries) {
  521. componentTys.push_back(entry.Type);
  522. }
  523. return getSwiftABIInfo(CGM).shouldPassIndirectlyForSwift(componentTys,
  524. asReturnValue);
  525. }
  526. bool swiftcall::shouldPassIndirectly(CodeGenModule &CGM,
  527. ArrayRef<llvm::Type*> componentTys,
  528. bool asReturnValue) {
  529. return getSwiftABIInfo(CGM).shouldPassIndirectlyForSwift(componentTys,
  530. asReturnValue);
  531. }
  532. CharUnits swiftcall::getMaximumVoluntaryIntegerSize(CodeGenModule &CGM) {
  533. // Currently always the size of an ordinary pointer.
  534. return CGM.getContext().toCharUnitsFromBits(
  535. CGM.getContext().getTargetInfo().getPointerWidth(0));
  536. }
  537. CharUnits swiftcall::getNaturalAlignment(CodeGenModule &CGM, llvm::Type *type) {
  538. // For Swift's purposes, this is always just the store size of the type
  539. // rounded up to a power of 2.
  540. auto size = (unsigned long long) getTypeStoreSize(CGM, type).getQuantity();
  541. if (!isPowerOf2(size)) {
  542. size = 1ULL << (llvm::findLastSet(size, llvm::ZB_Undefined) + 1);
  543. }
  544. assert(size >= CGM.getDataLayout().getABITypeAlignment(type));
  545. return CharUnits::fromQuantity(size);
  546. }
  547. bool swiftcall::isLegalIntegerType(CodeGenModule &CGM,
  548. llvm::IntegerType *intTy) {
  549. auto size = intTy->getBitWidth();
  550. switch (size) {
  551. case 1:
  552. case 8:
  553. case 16:
  554. case 32:
  555. case 64:
  556. // Just assume that the above are always legal.
  557. return true;
  558. case 128:
  559. return CGM.getContext().getTargetInfo().hasInt128Type();
  560. default:
  561. return false;
  562. }
  563. }
  564. bool swiftcall::isLegalVectorType(CodeGenModule &CGM, CharUnits vectorSize,
  565. llvm::VectorType *vectorTy) {
  566. return isLegalVectorType(CGM, vectorSize, vectorTy->getElementType(),
  567. vectorTy->getNumElements());
  568. }
  569. bool swiftcall::isLegalVectorType(CodeGenModule &CGM, CharUnits vectorSize,
  570. llvm::Type *eltTy, unsigned numElts) {
  571. assert(numElts > 1 && "illegal vector length");
  572. return getSwiftABIInfo(CGM)
  573. .isLegalVectorTypeForSwift(vectorSize, eltTy, numElts);
  574. }
  575. std::pair<llvm::Type*, unsigned>
  576. swiftcall::splitLegalVectorType(CodeGenModule &CGM, CharUnits vectorSize,
  577. llvm::VectorType *vectorTy) {
  578. auto numElts = vectorTy->getNumElements();
  579. auto eltTy = vectorTy->getElementType();
  580. // Try to split the vector type in half.
  581. if (numElts >= 4 && isPowerOf2(numElts)) {
  582. if (isLegalVectorType(CGM, vectorSize / 2, eltTy, numElts / 2))
  583. return {llvm::VectorType::get(eltTy, numElts / 2), 2};
  584. }
  585. return {eltTy, numElts};
  586. }
  587. void swiftcall::legalizeVectorType(CodeGenModule &CGM, CharUnits origVectorSize,
  588. llvm::VectorType *origVectorTy,
  589. llvm::SmallVectorImpl<llvm::Type*> &components) {
  590. // If it's already a legal vector type, use it.
  591. if (isLegalVectorType(CGM, origVectorSize, origVectorTy)) {
  592. components.push_back(origVectorTy);
  593. return;
  594. }
  595. // Try to split the vector into legal subvectors.
  596. auto numElts = origVectorTy->getNumElements();
  597. auto eltTy = origVectorTy->getElementType();
  598. assert(numElts != 1);
  599. // The largest size that we're still considering making subvectors of.
  600. // Always a power of 2.
  601. unsigned logCandidateNumElts = llvm::findLastSet(numElts, llvm::ZB_Undefined);
  602. unsigned candidateNumElts = 1U << logCandidateNumElts;
  603. assert(candidateNumElts <= numElts && candidateNumElts * 2 > numElts);
  604. // Minor optimization: don't check the legality of this exact size twice.
  605. if (candidateNumElts == numElts) {
  606. logCandidateNumElts--;
  607. candidateNumElts >>= 1;
  608. }
  609. CharUnits eltSize = (origVectorSize / numElts);
  610. CharUnits candidateSize = eltSize * candidateNumElts;
  611. // The sensibility of this algorithm relies on the fact that we never
  612. // have a legal non-power-of-2 vector size without having the power of 2
  613. // also be legal.
  614. while (logCandidateNumElts > 0) {
  615. assert(candidateNumElts == 1U << logCandidateNumElts);
  616. assert(candidateNumElts <= numElts);
  617. assert(candidateSize == eltSize * candidateNumElts);
  618. // Skip illegal vector sizes.
  619. if (!isLegalVectorType(CGM, candidateSize, eltTy, candidateNumElts)) {
  620. logCandidateNumElts--;
  621. candidateNumElts /= 2;
  622. candidateSize /= 2;
  623. continue;
  624. }
  625. // Add the right number of vectors of this size.
  626. auto numVecs = numElts >> logCandidateNumElts;
  627. components.append(numVecs, llvm::VectorType::get(eltTy, candidateNumElts));
  628. numElts -= (numVecs << logCandidateNumElts);
  629. if (numElts == 0) return;
  630. // It's possible that the number of elements remaining will be legal.
  631. // This can happen with e.g. <7 x float> when <3 x float> is legal.
  632. // This only needs to be separately checked if it's not a power of 2.
  633. if (numElts > 2 && !isPowerOf2(numElts) &&
  634. isLegalVectorType(CGM, eltSize * numElts, eltTy, numElts)) {
  635. components.push_back(llvm::VectorType::get(eltTy, numElts));
  636. return;
  637. }
  638. // Bring vecSize down to something no larger than numElts.
  639. do {
  640. logCandidateNumElts--;
  641. candidateNumElts /= 2;
  642. candidateSize /= 2;
  643. } while (candidateNumElts > numElts);
  644. }
  645. // Otherwise, just append a bunch of individual elements.
  646. components.append(numElts, eltTy);
  647. }
  648. bool swiftcall::mustPassRecordIndirectly(CodeGenModule &CGM,
  649. const RecordDecl *record) {
  650. // FIXME: should we not rely on the standard computation in Sema, just in
  651. // case we want to diverge from the platform ABI (e.g. on targets where
  652. // that uses the MSVC rule)?
  653. return !record->canPassInRegisters();
  654. }
  655. static ABIArgInfo classifyExpandedType(SwiftAggLowering &lowering,
  656. bool forReturn,
  657. CharUnits alignmentForIndirect) {
  658. if (lowering.empty()) {
  659. return ABIArgInfo::getIgnore();
  660. } else if (lowering.shouldPassIndirectly(forReturn)) {
  661. return ABIArgInfo::getIndirect(alignmentForIndirect, /*byval*/ false);
  662. } else {
  663. auto types = lowering.getCoerceAndExpandTypes();
  664. return ABIArgInfo::getCoerceAndExpand(types.first, types.second);
  665. }
  666. }
  667. static ABIArgInfo classifyType(CodeGenModule &CGM, CanQualType type,
  668. bool forReturn) {
  669. if (auto recordType = dyn_cast<RecordType>(type)) {
  670. auto record = recordType->getDecl();
  671. auto &layout = CGM.getContext().getASTRecordLayout(record);
  672. if (mustPassRecordIndirectly(CGM, record))
  673. return ABIArgInfo::getIndirect(layout.getAlignment(), /*byval*/ false);
  674. SwiftAggLowering lowering(CGM);
  675. lowering.addTypedData(recordType->getDecl(), CharUnits::Zero(), layout);
  676. lowering.finish();
  677. return classifyExpandedType(lowering, forReturn, layout.getAlignment());
  678. }
  679. // Just assume that all of our target ABIs can support returning at least
  680. // two integer or floating-point values.
  681. if (isa<ComplexType>(type)) {
  682. return (forReturn ? ABIArgInfo::getDirect() : ABIArgInfo::getExpand());
  683. }
  684. // Vector types may need to be legalized.
  685. if (isa<VectorType>(type)) {
  686. SwiftAggLowering lowering(CGM);
  687. lowering.addTypedData(type, CharUnits::Zero());
  688. lowering.finish();
  689. CharUnits alignment = CGM.getContext().getTypeAlignInChars(type);
  690. return classifyExpandedType(lowering, forReturn, alignment);
  691. }
  692. // Member pointer types need to be expanded, but it's a simple form of
  693. // expansion that 'Direct' can handle. Note that CanBeFlattened should be
  694. // true for this to work.
  695. // 'void' needs to be ignored.
  696. if (type->isVoidType()) {
  697. return ABIArgInfo::getIgnore();
  698. }
  699. // Everything else can be passed directly.
  700. return ABIArgInfo::getDirect();
  701. }
  702. ABIArgInfo swiftcall::classifyReturnType(CodeGenModule &CGM, CanQualType type) {
  703. return classifyType(CGM, type, /*forReturn*/ true);
  704. }
  705. ABIArgInfo swiftcall::classifyArgumentType(CodeGenModule &CGM,
  706. CanQualType type) {
  707. return classifyType(CGM, type, /*forReturn*/ false);
  708. }
  709. void swiftcall::computeABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
  710. auto &retInfo = FI.getReturnInfo();
  711. retInfo = classifyReturnType(CGM, FI.getReturnType());
  712. for (unsigned i = 0, e = FI.arg_size(); i != e; ++i) {
  713. auto &argInfo = FI.arg_begin()[i];
  714. argInfo.info = classifyArgumentType(CGM, argInfo.type);
  715. }
  716. }
  717. // Is swifterror lowered to a register by the target ABI.
  718. bool swiftcall::isSwiftErrorLoweredInRegister(CodeGenModule &CGM) {
  719. return getSwiftABIInfo(CGM).isSwiftErrorInRegister();
  720. }