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