SwiftCallingConv.cpp 30 KB

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