SwiftCallingConv.cpp 28 KB

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