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 
14 #include "clang/CodeGen/SwiftCallingConv.h"
15 #include "clang/Basic/TargetInfo.h"
16 #include "CodeGenModule.h"
17 #include "TargetInfo.h"
18 
19 using namespace clang;
20 using namespace CodeGen;
21 using namespace swiftcall;
22 
getSwiftABIInfo(CodeGenModule & CGM)23 static const SwiftABIInfo &getSwiftABIInfo(CodeGenModule &CGM) {
24   return cast<SwiftABIInfo>(CGM.getTargetCodeGenInfo().getABIInfo());
25 }
26 
isPowerOf2(unsigned n)27 static 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.
getCommonType(llvm::Type * first,llvm::Type * second)32 static 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 
getTypeStoreSize(CodeGenModule & CGM,llvm::Type * type)56 static CharUnits getTypeStoreSize(CodeGenModule &CGM, llvm::Type *type) {
57   return CharUnits::fromQuantity(CGM.getDataLayout().getTypeStoreSize(type));
58 }
59 
getTypeAllocSize(CodeGenModule & CGM,llvm::Type * type)60 static CharUnits getTypeAllocSize(CodeGenModule &CGM, llvm::Type *type) {
61   return CharUnits::fromQuantity(CGM.getDataLayout().getTypeAllocSize(type));
62 }
63 
addTypedData(QualType type,CharUnits begin)64 void 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 
addTypedData(const RecordDecl * record,CharUnits begin)106 void SwiftAggLowering::addTypedData(const RecordDecl *record, CharUnits begin) {
107   addTypedData(record, begin, CGM.getContext().getASTRecordLayout(record));
108 }
109 
addTypedData(const RecordDecl * record,CharUnits begin,const ASTRecordLayout & layout)110 void 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 
addBitFieldData(const FieldDecl * bitfield,CharUnits recordBegin,uint64_t bitfieldBitBegin)171 void 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 
addTypedData(llvm::Type * type,CharUnits begin)194 void 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 
addTypedData(llvm::Type * type,CharUnits begin,CharUnits end)199 void 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 
addLegalTypedData(llvm::Type * type,CharUnits begin,CharUnits end)232 void 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) {
246         addLegalTypedData(eltTy, begin, begin + eltSize);
247         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 
addEntry(llvm::Type * type,CharUnits begin,CharUnits end)259 void SwiftAggLowering::addEntry(llvm::Type *type,
260                                 CharUnits begin, CharUnits end) {
261   assert((!type ||
262           (!isa<llvm::StructType>(type) && !isa<llvm::ArrayType>(type))) &&
263          "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.
292 restartAfterSplit:
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.
splitVectorEntry(unsigned index)384 void 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;
391   Entries.insert(Entries.begin() + index + 1, numElts - 1, StorageEntry());
392 
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.
getOffsetAtStartOfUnit(CharUnits offset,CharUnits unitSize)406 static 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 
areBytesInSameUnit(CharUnits first,CharUnits second,CharUnits chunkSize)412 static bool areBytesInSameUnit(CharUnits first, CharUnits second,
413                                CharUnits chunkSize) {
414   return getOffsetAtStartOfUnit(first, chunkSize)
415       == getOffsetAtStartOfUnit(second, chunkSize);
416 }
417 
isMergeableEntryType(llvm::Type * type)418 static bool isMergeableEntryType(llvm::Type *type) {
419   // Opaquely-typed memory is always mergeable.
420   if (type == nullptr) return true;
421 
422   // Pointers and integers are always mergeable.  In theory we should not
423   // merge pointers, but (1) it doesn't currently matter in practice because
424   // the chunk size is never greater than the size of a pointer and (2)
425   // Swift IRGen uses integer types for a lot of things that are "really"
426   // just storing pointers (like Optional<SomePointer>).  If we ever have a
427   // target that would otherwise combine pointers, we should put some effort
428   // into fixing those cases in Swift IRGen and then call out pointer types
429   // here.
430 
431   // Floating-point and vector types should never be merged.
432   // Most such types are too large and highly-aligned to ever trigger merging
433   // in practice, but it's important for the rule to cover at least 'half'
434   // and 'float', as well as things like small vectors of 'i1' or 'i8'.
435   return (!type->isFloatingPointTy() && !type->isVectorTy());
436 }
437 
shouldMergeEntries(const StorageEntry & first,const StorageEntry & second,CharUnits chunkSize)438 bool SwiftAggLowering::shouldMergeEntries(const StorageEntry &first,
439                                           const StorageEntry &second,
440                                           CharUnits chunkSize) {
441   // Only merge entries that overlap the same chunk.  We test this first
442   // despite being a bit more expensive because this is the condition that
443   // tends to prevent merging.
444   if (!areBytesInSameUnit(first.End - CharUnits::One(), second.Begin,
445                           chunkSize))
446     return false;
447 
448   return (isMergeableEntryType(first.Type) &&
449           isMergeableEntryType(second.Type));
450 }
451 
finish()452 void SwiftAggLowering::finish() {
453   if (Entries.empty()) {
454     Finished = true;
455     return;
456   }
457 
458   // We logically split the layout down into a series of chunks of this size,
459   // which is generally the size of a pointer.
460   const CharUnits chunkSize = getMaximumVoluntaryIntegerSize(CGM);
461 
462   // First pass: if two entries should be merged, make them both opaque
463   // and stretch one to meet the next.
464   // Also, remember if there are any opaque entries.
465   bool hasOpaqueEntries = (Entries[0].Type == nullptr);
466   for (size_t i = 1, e = Entries.size(); i != e; ++i) {
467     if (shouldMergeEntries(Entries[i - 1], Entries[i], chunkSize)) {
468       Entries[i - 1].Type = nullptr;
469       Entries[i].Type = nullptr;
470       Entries[i - 1].End = Entries[i].Begin;
471       hasOpaqueEntries = true;
472 
473     } else if (Entries[i].Type == nullptr) {
474       hasOpaqueEntries = true;
475     }
476   }
477 
478   // The rest of the algorithm leaves non-opaque entries alone, so if we
479   // have no opaque entries, we're done.
480   if (!hasOpaqueEntries) {
481     Finished = true;
482     return;
483   }
484 
485   // Okay, move the entries to a temporary and rebuild Entries.
486   auto orig = std::move(Entries);
487   assert(Entries.empty());
488 
489   for (size_t i = 0, e = orig.size(); i != e; ++i) {
490     // Just copy over non-opaque entries.
491     if (orig[i].Type != nullptr) {
492       Entries.push_back(orig[i]);
493       continue;
494     }
495 
496     // Scan forward to determine the full extent of the next opaque range.
497     // We know from the first pass that only contiguous ranges will overlap
498     // the same aligned chunk.
499     auto begin = orig[i].Begin;
500     auto end = orig[i].End;
501     while (i + 1 != e &&
502            orig[i + 1].Type == nullptr &&
503            end == orig[i + 1].Begin) {
504       end = orig[i + 1].End;
505       i++;
506     }
507 
508     // Add an entry per intersected chunk.
509     do {
510       // Find the smallest aligned storage unit in the maximal aligned
511       // storage unit containing 'begin' that contains all the bytes in
512       // the intersection between the range and this chunk.
513       CharUnits localBegin = begin;
514       CharUnits chunkBegin = getOffsetAtStartOfUnit(localBegin, chunkSize);
515       CharUnits chunkEnd = chunkBegin + chunkSize;
516       CharUnits localEnd = std::min(end, chunkEnd);
517 
518       // Just do a simple loop over ever-increasing unit sizes.
519       CharUnits unitSize = CharUnits::One();
520       CharUnits unitBegin, unitEnd;
521       for (; ; unitSize *= 2) {
522         assert(unitSize <= chunkSize);
523         unitBegin = getOffsetAtStartOfUnit(localBegin, unitSize);
524         unitEnd = unitBegin + unitSize;
525         if (unitEnd >= localEnd) break;
526       }
527 
528       // Add an entry for this unit.
529       auto entryTy =
530         llvm::IntegerType::get(CGM.getLLVMContext(),
531                                CGM.getContext().toBits(unitSize));
532       Entries.push_back({unitBegin, unitEnd, entryTy});
533 
534       // The next chunk starts where this chunk left off.
535       begin = localEnd;
536     } while (begin != end);
537   }
538 
539   // Okay, finally finished.
540   Finished = true;
541 }
542 
enumerateComponents(EnumerationCallback callback) const543 void SwiftAggLowering::enumerateComponents(EnumerationCallback callback) const {
544   assert(Finished && "haven't yet finished lowering");
545 
546   for (auto &entry : Entries) {
547     callback(entry.Begin, entry.End, entry.Type);
548   }
549 }
550 
551 std::pair<llvm::StructType*, llvm::Type*>
getCoerceAndExpandTypes() const552 SwiftAggLowering::getCoerceAndExpandTypes() const {
553   assert(Finished && "haven't yet finished lowering");
554 
555   auto &ctx = CGM.getLLVMContext();
556 
557   if (Entries.empty()) {
558     auto type = llvm::StructType::get(ctx);
559     return { type, type };
560   }
561 
562   SmallVector<llvm::Type*, 8> elts;
563   CharUnits lastEnd = CharUnits::Zero();
564   bool hasPadding = false;
565   bool packed = false;
566   for (auto &entry : Entries) {
567     if (entry.Begin != lastEnd) {
568       auto paddingSize = entry.Begin - lastEnd;
569       assert(!paddingSize.isNegative());
570 
571       auto padding = llvm::ArrayType::get(llvm::Type::getInt8Ty(ctx),
572                                           paddingSize.getQuantity());
573       elts.push_back(padding);
574       hasPadding = true;
575     }
576 
577     if (!packed && !entry.Begin.isMultipleOf(
578           CharUnits::fromQuantity(
579             CGM.getDataLayout().getABITypeAlignment(entry.Type))))
580       packed = true;
581 
582     elts.push_back(entry.Type);
583 
584     lastEnd = entry.Begin + getTypeAllocSize(CGM, entry.Type);
585     assert(entry.End <= lastEnd);
586   }
587 
588   // We don't need to adjust 'packed' to deal with possible tail padding
589   // because we never do that kind of access through the coercion type.
590   auto coercionType = llvm::StructType::get(ctx, elts, packed);
591 
592   llvm::Type *unpaddedType = coercionType;
593   if (hasPadding) {
594     elts.clear();
595     for (auto &entry : Entries) {
596       elts.push_back(entry.Type);
597     }
598     if (elts.size() == 1) {
599       unpaddedType = elts[0];
600     } else {
601       unpaddedType = llvm::StructType::get(ctx, elts, /*packed*/ false);
602     }
603   } else if (Entries.size() == 1) {
604     unpaddedType = Entries[0].Type;
605   }
606 
607   return { coercionType, unpaddedType };
608 }
609 
shouldPassIndirectly(bool asReturnValue) const610 bool SwiftAggLowering::shouldPassIndirectly(bool asReturnValue) const {
611   assert(Finished && "haven't yet finished lowering");
612 
613   // Empty types don't need to be passed indirectly.
614   if (Entries.empty()) return false;
615 
616   // Avoid copying the array of types when there's just a single element.
617   if (Entries.size() == 1) {
618     return getSwiftABIInfo(CGM).shouldPassIndirectlyForSwift(
619                                                            Entries.back().Type,
620                                                              asReturnValue);
621   }
622 
623   SmallVector<llvm::Type*, 8> componentTys;
624   componentTys.reserve(Entries.size());
625   for (auto &entry : Entries) {
626     componentTys.push_back(entry.Type);
627   }
628   return getSwiftABIInfo(CGM).shouldPassIndirectlyForSwift(componentTys,
629                                                            asReturnValue);
630 }
631 
shouldPassIndirectly(CodeGenModule & CGM,ArrayRef<llvm::Type * > componentTys,bool asReturnValue)632 bool swiftcall::shouldPassIndirectly(CodeGenModule &CGM,
633                                      ArrayRef<llvm::Type*> componentTys,
634                                      bool asReturnValue) {
635   return getSwiftABIInfo(CGM).shouldPassIndirectlyForSwift(componentTys,
636                                                            asReturnValue);
637 }
638 
getMaximumVoluntaryIntegerSize(CodeGenModule & CGM)639 CharUnits swiftcall::getMaximumVoluntaryIntegerSize(CodeGenModule &CGM) {
640   // Currently always the size of an ordinary pointer.
641   return CGM.getContext().toCharUnitsFromBits(
642            CGM.getContext().getTargetInfo().getPointerWidth(0));
643 }
644 
getNaturalAlignment(CodeGenModule & CGM,llvm::Type * type)645 CharUnits swiftcall::getNaturalAlignment(CodeGenModule &CGM, llvm::Type *type) {
646   // For Swift's purposes, this is always just the store size of the type
647   // rounded up to a power of 2.
648   auto size = (unsigned long long) getTypeStoreSize(CGM, type).getQuantity();
649   if (!isPowerOf2(size)) {
650     size = 1ULL << (llvm::findLastSet(size, llvm::ZB_Undefined) + 1);
651   }
652   assert(size >= CGM.getDataLayout().getABITypeAlignment(type));
653   return CharUnits::fromQuantity(size);
654 }
655 
isLegalIntegerType(CodeGenModule & CGM,llvm::IntegerType * intTy)656 bool swiftcall::isLegalIntegerType(CodeGenModule &CGM,
657                                    llvm::IntegerType *intTy) {
658   auto size = intTy->getBitWidth();
659   switch (size) {
660   case 1:
661   case 8:
662   case 16:
663   case 32:
664   case 64:
665     // Just assume that the above are always legal.
666     return true;
667 
668   case 128:
669     return CGM.getContext().getTargetInfo().hasInt128Type();
670 
671   default:
672     return false;
673   }
674 }
675 
isLegalVectorType(CodeGenModule & CGM,CharUnits vectorSize,llvm::VectorType * vectorTy)676 bool swiftcall::isLegalVectorType(CodeGenModule &CGM, CharUnits vectorSize,
677                                   llvm::VectorType *vectorTy) {
678   return isLegalVectorType(CGM, vectorSize, vectorTy->getElementType(),
679                            vectorTy->getNumElements());
680 }
681 
isLegalVectorType(CodeGenModule & CGM,CharUnits vectorSize,llvm::Type * eltTy,unsigned numElts)682 bool swiftcall::isLegalVectorType(CodeGenModule &CGM, CharUnits vectorSize,
683                                   llvm::Type *eltTy, unsigned numElts) {
684   assert(numElts > 1 && "illegal vector length");
685   return getSwiftABIInfo(CGM)
686            .isLegalVectorTypeForSwift(vectorSize, eltTy, numElts);
687 }
688 
689 std::pair<llvm::Type*, unsigned>
splitLegalVectorType(CodeGenModule & CGM,CharUnits vectorSize,llvm::VectorType * vectorTy)690 swiftcall::splitLegalVectorType(CodeGenModule &CGM, CharUnits vectorSize,
691                                 llvm::VectorType *vectorTy) {
692   auto numElts = vectorTy->getNumElements();
693   auto eltTy = vectorTy->getElementType();
694 
695   // Try to split the vector type in half.
696   if (numElts >= 4 && isPowerOf2(numElts)) {
697     if (isLegalVectorType(CGM, vectorSize / 2, eltTy, numElts / 2))
698       return {llvm::VectorType::get(eltTy, numElts / 2), 2};
699   }
700 
701   return {eltTy, numElts};
702 }
703 
legalizeVectorType(CodeGenModule & CGM,CharUnits origVectorSize,llvm::VectorType * origVectorTy,llvm::SmallVectorImpl<llvm::Type * > & components)704 void swiftcall::legalizeVectorType(CodeGenModule &CGM, CharUnits origVectorSize,
705                                    llvm::VectorType *origVectorTy,
706                              llvm::SmallVectorImpl<llvm::Type*> &components) {
707   // If it's already a legal vector type, use it.
708   if (isLegalVectorType(CGM, origVectorSize, origVectorTy)) {
709     components.push_back(origVectorTy);
710     return;
711   }
712 
713   // Try to split the vector into legal subvectors.
714   auto numElts = origVectorTy->getNumElements();
715   auto eltTy = origVectorTy->getElementType();
716   assert(numElts != 1);
717 
718   // The largest size that we're still considering making subvectors of.
719   // Always a power of 2.
720   unsigned logCandidateNumElts = llvm::findLastSet(numElts, llvm::ZB_Undefined);
721   unsigned candidateNumElts = 1U << logCandidateNumElts;
722   assert(candidateNumElts <= numElts && candidateNumElts * 2 > numElts);
723 
724   // Minor optimization: don't check the legality of this exact size twice.
725   if (candidateNumElts == numElts) {
726     logCandidateNumElts--;
727     candidateNumElts >>= 1;
728   }
729 
730   CharUnits eltSize = (origVectorSize / numElts);
731   CharUnits candidateSize = eltSize * candidateNumElts;
732 
733   // The sensibility of this algorithm relies on the fact that we never
734   // have a legal non-power-of-2 vector size without having the power of 2
735   // also be legal.
736   while (logCandidateNumElts > 0) {
737     assert(candidateNumElts == 1U << logCandidateNumElts);
738     assert(candidateNumElts <= numElts);
739     assert(candidateSize == eltSize * candidateNumElts);
740 
741     // Skip illegal vector sizes.
742     if (!isLegalVectorType(CGM, candidateSize, eltTy, candidateNumElts)) {
743       logCandidateNumElts--;
744       candidateNumElts /= 2;
745       candidateSize /= 2;
746       continue;
747     }
748 
749     // Add the right number of vectors of this size.
750     auto numVecs = numElts >> logCandidateNumElts;
751     components.append(numVecs, llvm::VectorType::get(eltTy, candidateNumElts));
752     numElts -= (numVecs << logCandidateNumElts);
753 
754     if (numElts == 0) return;
755 
756     // It's possible that the number of elements remaining will be legal.
757     // This can happen with e.g. <7 x float> when <3 x float> is legal.
758     // This only needs to be separately checked if it's not a power of 2.
759     if (numElts > 2 && !isPowerOf2(numElts) &&
760         isLegalVectorType(CGM, eltSize * numElts, eltTy, numElts)) {
761       components.push_back(llvm::VectorType::get(eltTy, numElts));
762       return;
763     }
764 
765     // Bring vecSize down to something no larger than numElts.
766     do {
767       logCandidateNumElts--;
768       candidateNumElts /= 2;
769       candidateSize /= 2;
770     } while (candidateNumElts > numElts);
771   }
772 
773   // Otherwise, just append a bunch of individual elements.
774   components.append(numElts, eltTy);
775 }
776 
mustPassRecordIndirectly(CodeGenModule & CGM,const RecordDecl * record)777 bool swiftcall::mustPassRecordIndirectly(CodeGenModule &CGM,
778                                          const RecordDecl *record) {
779   // FIXME: should we not rely on the standard computation in Sema, just in
780   // case we want to diverge from the platform ABI (e.g. on targets where
781   // that uses the MSVC rule)?
782   return !record->canPassInRegisters();
783 }
784 
classifyExpandedType(SwiftAggLowering & lowering,bool forReturn,CharUnits alignmentForIndirect)785 static ABIArgInfo classifyExpandedType(SwiftAggLowering &lowering,
786                                        bool forReturn,
787                                        CharUnits alignmentForIndirect) {
788   if (lowering.empty()) {
789     return ABIArgInfo::getIgnore();
790   } else if (lowering.shouldPassIndirectly(forReturn)) {
791     return ABIArgInfo::getIndirect(alignmentForIndirect, /*byval*/ false);
792   } else {
793     auto types = lowering.getCoerceAndExpandTypes();
794     return ABIArgInfo::getCoerceAndExpand(types.first, types.second);
795   }
796 }
797 
classifyType(CodeGenModule & CGM,CanQualType type,bool forReturn)798 static ABIArgInfo classifyType(CodeGenModule &CGM, CanQualType type,
799                                bool forReturn) {
800   if (auto recordType = dyn_cast<RecordType>(type)) {
801     auto record = recordType->getDecl();
802     auto &layout = CGM.getContext().getASTRecordLayout(record);
803 
804     if (mustPassRecordIndirectly(CGM, record))
805       return ABIArgInfo::getIndirect(layout.getAlignment(), /*byval*/ false);
806 
807     SwiftAggLowering lowering(CGM);
808     lowering.addTypedData(recordType->getDecl(), CharUnits::Zero(), layout);
809     lowering.finish();
810 
811     return classifyExpandedType(lowering, forReturn, layout.getAlignment());
812   }
813 
814   // Just assume that all of our target ABIs can support returning at least
815   // two integer or floating-point values.
816   if (isa<ComplexType>(type)) {
817     return (forReturn ? ABIArgInfo::getDirect() : ABIArgInfo::getExpand());
818   }
819 
820   // Vector types may need to be legalized.
821   if (isa<VectorType>(type)) {
822     SwiftAggLowering lowering(CGM);
823     lowering.addTypedData(type, CharUnits::Zero());
824     lowering.finish();
825 
826     CharUnits alignment = CGM.getContext().getTypeAlignInChars(type);
827     return classifyExpandedType(lowering, forReturn, alignment);
828   }
829 
830   // Member pointer types need to be expanded, but it's a simple form of
831   // expansion that 'Direct' can handle.  Note that CanBeFlattened should be
832   // true for this to work.
833 
834   // 'void' needs to be ignored.
835   if (type->isVoidType()) {
836     return ABIArgInfo::getIgnore();
837   }
838 
839   // Everything else can be passed directly.
840   return ABIArgInfo::getDirect();
841 }
842 
classifyReturnType(CodeGenModule & CGM,CanQualType type)843 ABIArgInfo swiftcall::classifyReturnType(CodeGenModule &CGM, CanQualType type) {
844   return classifyType(CGM, type, /*forReturn*/ true);
845 }
846 
classifyArgumentType(CodeGenModule & CGM,CanQualType type)847 ABIArgInfo swiftcall::classifyArgumentType(CodeGenModule &CGM,
848                                            CanQualType type) {
849   return classifyType(CGM, type, /*forReturn*/ false);
850 }
851 
computeABIInfo(CodeGenModule & CGM,CGFunctionInfo & FI)852 void swiftcall::computeABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
853   auto &retInfo = FI.getReturnInfo();
854   retInfo = classifyReturnType(CGM, FI.getReturnType());
855 
856   for (unsigned i = 0, e = FI.arg_size(); i != e; ++i) {
857     auto &argInfo = FI.arg_begin()[i];
858     argInfo.info = classifyArgumentType(CGM, argInfo.type);
859   }
860 }
861 
862 // Is swifterror lowered to a register by the target ABI.
isSwiftErrorLoweredInRegister(CodeGenModule & CGM)863 bool swiftcall::isSwiftErrorLoweredInRegister(CodeGenModule &CGM) {
864   return getSwiftABIInfo(CGM).isSwiftErrorInRegister();
865 }
866