SwiftCallingConv.cpp 30 KB

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