LLVM 24.0.0git
X86.cpp
Go to the documentation of this file.
1//===- X86.cpp ------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "llvm/ABI/TargetInfo.h"
11#include "llvm/ABI/Types.h"
17#include <algorithm>
18#include <cassert>
19#include <cstdint>
20
21namespace llvm {
22namespace abi {
23
25 switch (AVXLevel) {
27 return 512;
29 return 256;
31 return 128;
32 }
33 llvm_unreachable("Unknown AVXLevel");
34}
35
37public:
39
40private:
41 X86AVXABILevel AVXLevel;
42 bool Has64BitPointers;
43 X86ABICompatInfo X86CompatInfo;
44
45 static Class merge(Class Accum, Class Field);
46
47 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
48
49 void classify(const Type *T, uint64_t OffsetBase, Class &Lo, Class &Hi,
50 bool IsNamedArg, bool IsRegCall = false) const;
51
52 const Type *getIntegerTypeAtOffset(const Type *IRType, unsigned IROffset,
53 const Type *SourceTy,
54 unsigned SourceOffset,
55 bool InMemory = false) const;
56
57 const Type *getSSETypeAtOffset(const Type *ABIType, unsigned ABIOffset,
58 const Type *SourceTy,
59 unsigned SourceOffset) const;
60 bool isIllegalVectorType(const Type *Ty) const;
61 bool containsMatrixField(const RecordType *RT) const;
62
63 void computeInfo(FunctionInfo &FI) const override;
64 ArgInfo getIndirectReturnResult(const Type *Ty) const;
65 const Type *getFPTypeAtOffset(const Type *Ty, unsigned Offset) const;
66
67 const Type *getByteVectorType(const Type *Ty) const;
68
69 const Type *createPairType(const Type *Lo, const Type *Hi) const;
70 ArgInfo getIndirectResult(const Type *Ty, unsigned FreeIntRegs) const;
71
72 ArgInfo classifyReturnType(const Type *RetTy) const;
73
74 ArgInfo classifyArgumentType(const Type *Ty, unsigned FreeIntRegs,
75 unsigned &NeededInt, unsigned &NeededSse,
76 bool IsNamedArg, bool IsRegCall = false) const;
77
78 bool shouldExtendReturnType(const IntegerType *RetTy) const;
79
80public:
82 bool Has64BitPtrs, const X86ABICompatInfo &Compat)
83 : TargetInfo(TypeBuilder), AVXLevel(AVXABILevel),
84 Has64BitPointers(Has64BitPtrs), X86CompatInfo(Compat) {}
85
86 bool has64BitPointers() const { return Has64BitPointers; }
87
88 const ABICompatInfo &getABICompatInfo() const override {
89 return X86CompatInfo;
90 }
91
92 const X86ABICompatInfo &getX86ABICompatInfo() const { return X86CompatInfo; }
93};
94
95static bool bitsContainNoUserData(const Type *Ty, unsigned StartBit,
96 unsigned EndBit);
97
98// Gets the "best" type to represent the union.
99static const Type *reduceUnionForX8664(const RecordType *UnionType,
100 TypeBuilder &TB) {
101 assert(UnionType->isUnion() && "Expected union type");
102
103 ArrayRef<FieldInfo> Fields = UnionType->getFields();
104 if (Fields.empty()) {
105 return nullptr;
106 }
107
108 const Type *StorageType = nullptr;
109
110 for (const auto &Field : Fields) {
111 if (Field.IsBitField && Field.IsUnnamedBitfield &&
112 Field.BitFieldWidth == 0) {
113 continue;
114 }
115
116 const Type *FieldType = Field.FieldType;
117
118 if (UnionType->isTransparentUnion() && !StorageType) {
119 StorageType = FieldType;
120 break;
121 }
122
123 // A member that holds no user data supplies no bytes for a coercion to
124 // read, so it must not become the storage type however wide or aligned it
125 // is declared. Clang compares lowered types instead, where an empty class
126 // is a byte array whose i8 leaf lets getIntegerTypeAtOffset narrow the
127 // coercion. A record mapped here holds no fields, so there is no such
128 // leaf and the eightbyte would be sized from the union.
129 if (bitsContainNoUserData(FieldType, 0, FieldType->getABISizeInBits()))
130 continue;
131
132 if (!StorageType ||
133 FieldType->getAlignment() > StorageType->getAlignment() ||
134 (FieldType->getAlignment() == StorageType->getAlignment() &&
135 TypeSize::isKnownGT(FieldType->getSizeInBits(),
136 StorageType->getSizeInBits()))) {
137 StorageType = FieldType;
138 }
139 }
140 return StorageType;
141}
142
143bool X86_64TargetInfo::shouldExtendReturnType(const IntegerType *RetTy) const {
144 // Bools need to be zero-extended to 8 bits for all ABIs.
145 if (RetTy->isBool())
146 return true;
147
148 // Promotable integer types get extended only for Darwin.
149 bool IsDarwin = false; // TODO: Currently not supported by ABI library.
150 if (!IsDarwin)
151 return false;
152
153 return isPromotableInteger(RetTy);
154}
155
156void X86_64TargetInfo::postMerge(unsigned AggregateSize, Class &Lo,
157 Class &Hi) const {
158 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
159 //
160 // (a) If one of the classes is Memory, the whole argument is passed in
161 // memory.
162 //
163 // (b) If X87Up is not preceded by X87, the whole argument is passed in
164 // memory.
165 //
166 // (c) If the size of the aggregate exceeds two eightbytes and the first
167 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
168 // argument is passed in memory. NOTE: This is necessary to keep the
169 // ABI working for processors that don't support the __m256 type.
170 //
171 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
172 //
173 // Some of these are enforced by the merging logic. Others can arise
174 // only with unions; for example:
175 // union { _Complex double; unsigned; }
176 //
177 // Note that clauses (b) and (c) were added in 0.98.
178
179 if (Hi == Memory)
180 Lo = Memory;
181 if (Hi == X87Up && Lo != X87 && getX86ABICompatInfo().HonorsRevision98)
182 Lo = Memory;
183 if (AggregateSize > 128 && (Lo != Sse || Hi != SseUp))
184 Lo = Memory;
185 if (Hi == SseUp && Lo != Sse)
186 Hi = Sse;
187}
188X86_64TargetInfo::Class X86_64TargetInfo::merge(Class Accum, Class Field) {
189 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
190 // classified recursively so that always two fields are
191 // considered. The resulting class is calculated according to
192 // the classes of the fields in the eightbyte:
193 //
194 // (a) If both classes are equal, this is the resulting class.
195 //
196 // (b) If one of the classes is NO_CLASS, the resulting class is
197 // the other class.
198 //
199 // (c) If one of the classes is MEMORY, the result is the MEMORY
200 // class.
201 //
202 // (d) If one of the classes is INTEGER, the result is the
203 // INTEGER.
204 //
205 // (e) If one of the classes is X87, X87Up, COMPLEX_X87 class,
206 // MEMORY is used as class.
207 //
208 // (f) Otherwise class SSE is used.
209
210 // Accum should never be memory (we should have returned) or
211 // ComplexX87 (because this cannot be passed in a structure).
212 assert((Accum != Memory && Accum != ComplexX87) &&
213 "Invalid accumulated classification during merge.");
214
215 if (Accum == Field || Field == NoClass)
216 return Accum;
217 if (Field == Memory)
218 return Memory;
219 if (Accum == NoClass)
220 return Field;
221 if (Accum == Integer || Field == Integer)
222 return Integer;
223 if (Field == X87 || Field == X87Up || Field == ComplexX87 || Accum == X87 ||
224 Accum == X87Up)
225 return Memory;
226
227 return Sse;
228}
229
230// A record with a matrix-extension field is passed in memory. clang has no
231// matrix-specific ABI code: a matrix falls through X86_64ABIInfo::classify to
232// the default MEMORY class. We model matrices as arrays, so this check
233// reproduces that record-with-matrix -> MEMORY result.
234bool X86_64TargetInfo::containsMatrixField(const RecordType *RT) const {
235 for (const auto &Field : RT->getFields()) {
236 const Type *FieldType = Field.FieldType;
237
238 if (const auto *AT = dyn_cast<ArrayType>(FieldType)) {
239 if (AT->isMatrixType())
240 return true;
241 continue;
242 }
243
244 if (const auto *NestedRT = dyn_cast<RecordType>(FieldType))
245 if (containsMatrixField(NestedRT))
246 return true;
247 }
248 return false;
249}
250
251void X86_64TargetInfo::classify(const Type *T, uint64_t OffsetBase, Class &Lo,
252 Class &Hi, bool IsNamedArg,
253 bool IsRegCall) const {
254 Lo = Hi = NoClass;
255 Class &Current = OffsetBase < 64 ? Lo : Hi;
256 Current = Memory;
257
258 if (T->isVoid()) {
259 Current = NoClass;
260 return;
261 }
262
263 if (const auto *IT = dyn_cast<IntegerType>(T)) {
264 auto BitWidth = IT->getSizeInBits().getFixedValue();
265
266 if (BitWidth == 128 ||
267 (IT->isBitInt() && BitWidth > 64 && BitWidth <= 128)) {
268 Lo = Integer;
269 Hi = Integer;
270 } else if (BitWidth <= 64) {
271 Current = Integer;
272 }
273
274 return;
275 }
276
277 if (const auto *FT = dyn_cast<FloatType>(T)) {
278 const auto *FltSem = FT->getSemantics();
279
280 if (FltSem == &llvm::APFloat::IEEEsingle() ||
281 FltSem == &llvm::APFloat::IEEEdouble() ||
282 FltSem == &llvm::APFloat::IEEEhalf() ||
283 FltSem == &llvm::APFloat::BFloat()) {
284 Current = Sse;
285 } else if (FltSem == &llvm::APFloat::IEEEquad()) {
286 Lo = Sse;
287 Hi = SseUp;
288 } else if (FltSem == &llvm::APFloat::x87DoubleExtended()) {
289 Lo = X87;
290 Hi = X87Up;
291 } else {
292 Current = Sse;
293 }
294 return;
295 }
296 if (T->isPointer()) {
297 Current = Integer;
298 return;
299 }
300
301 if (const auto *MPT = dyn_cast<MemberPointerType>(T)) {
302 if (MPT->isFunctionPointer()) {
303 if (Has64BitPointers) {
304 Lo = Hi = Integer;
305 } else {
306 uint64_t EbFuncPtr = OffsetBase / 64;
307 uint64_t EbThisAdj = (OffsetBase + 64 - 1) / 64;
308 if (EbFuncPtr != EbThisAdj) {
309 Lo = Hi = Integer;
310 } else {
311 Current = Integer;
312 }
313 }
314 } else {
315 Current = Integer;
316 }
317 return;
318 }
319
320 if (const auto *VT = dyn_cast<VectorType>(T)) {
321 assert(VT->isFixedLength() && "x86-64 has no scalable vectors");
322 uint64_t Size = VT->getABISizeInBits();
323 const Type *ElementType = VT->getElementType();
324
325 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
326 // gcc passes the following as integer:
327 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
328 // 2 bytes - <2 x char>, <1 x short>
329 // 1 byte - <1 x char>
330 Current = Integer;
331 // If this type crosses an eightbyte boundary, it should be
332 // split.
333 uint64_t EbLo = (OffsetBase) / 64;
334 uint64_t EbHi = (OffsetBase + Size - 1) / 64;
335 if (EbLo != EbHi)
336 Hi = Lo;
337 } else if (Size == 64) {
338 if (const auto *FT = dyn_cast<FloatType>(ElementType)) {
339 // gcc passes <1 x double> in memory. :(
340 if (FT->getSemantics() == &llvm::APFloat::IEEEdouble())
341 return;
342 }
343
344 // gcc passes <1 x long long> as SSE but clang used to unconditionally
345 // pass them as integer. For platforms where clang is the de facto
346 // platform compiler, we must continue to use integer.
347 if (const auto *IT = dyn_cast<IntegerType>(ElementType)) {
348 uint64_t ElemBits = IT->getSizeInBits().getFixedValue();
349 if (!getX86ABICompatInfo().ClassifyIntegerMMXAsSSE && ElemBits == 64 &&
350 !IT->isBitInt()) {
351 Current = Integer;
352 } else {
353 Current = Sse;
354 }
355 } else {
356 Current = Sse;
357 }
358 // If this type crosses an eightbyte boundary, it should be
359 // split.
360 if (OffsetBase && OffsetBase != 64)
361 Hi = Lo;
362 } else if (Size == 128 ||
363 (IsNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
364 if (const auto *IT = dyn_cast<IntegerType>(ElementType)) {
365 uint64_t ElemBits = IT->getSizeInBits().getFixedValue();
366 // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
367 if (getX86ABICompatInfo().PassInt128VectorsInMem && Size != 128 &&
368 ElemBits == 128 && !IT->isBitInt())
369 return;
370 }
371
372 // Arguments of 256-bits are split into four eightbyte chunks. The
373 // least significant one belongs to class SSE and all the others to class
374 // SSEUP. The original Lo and Hi design considers that types can't be
375 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
376 // This design isn't correct for 256-bits, but since there're no cases
377 // where the upper parts would need to be inspected, avoid adding
378 // complexity and just consider Hi to match the 64-256 part.
379 //
380 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
381 // registers if they are "named", i.e. not part of the "..." of a
382 // variadic function.
383 //
384 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
385 // split into eight eightbyte chunks, one SSE and seven SSEUP.
386 Lo = Sse;
387 Hi = SseUp;
388 }
389 return;
390 }
391
392 if (const auto *CT = dyn_cast<ComplexType>(T)) {
393 const Type *ElementType = CT->getElementType();
394 uint64_t Size = T->getABISizeInBits();
395
396 if (isa<IntegerType>(ElementType)) {
397 if (Size <= 64)
398 Current = Integer;
399 else if (Size <= 128)
400 Lo = Hi = Integer;
401 } else if (const auto *EFT = dyn_cast<FloatType>(ElementType)) {
402 const auto *FltSem = EFT->getSemantics();
403 if (FltSem == &llvm::APFloat::IEEEhalf() ||
404 FltSem == &llvm::APFloat::IEEEsingle() ||
405 FltSem == &llvm::APFloat::BFloat())
406 Current = Sse;
407 else if (FltSem == &llvm::APFloat::IEEEquad())
408 Current = Memory;
409 else if (FltSem == &llvm::APFloat::x87DoubleExtended())
410 Current = ComplexX87;
411 else if (FltSem == &llvm::APFloat::IEEEdouble())
412 Lo = Hi = Sse;
413 else
414 llvm_unreachable("Unexpected long double representation!");
415 }
416
417 uint64_t ElementSize = ElementType->getABISizeInBits();
418 // If this complex type crosses an eightbyte boundary then it
419 // should be split.
420 uint64_t EbReal = OffsetBase / 64;
421 uint64_t EbImag = (OffsetBase + ElementSize) / 64;
422 if (Hi == NoClass && EbReal != EbImag)
423 Hi = Lo;
424
425 return;
426 }
427
428 if (const auto *AT = dyn_cast<ArrayType>(T)) {
429 // A matrix type is modeled as an array but, like Clang, is treated as a
430 // non-aggregate scalar: it matches no class here and stays in the Memory
431 // class, so classify*Type later returns it Direct (coerced to its
432 // flattened vector) rather than classifying it field-by-field.
433 if (AT->isMatrixType())
434 return;
435
436 // Arrays are treated like structures.
437 uint64_t Size = AT->getABISizeInBits();
438
439 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
440 // than eight eightbytes, ..., it has class MEMORY.
441 // regcall ABI doesn't have limitation to an object. The only limitation
442 // is the free registers, which will be checked in computeInfo.
443 if (!IsRegCall && Size > 512)
444 return;
445
446 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
447 // fields, it has class MEMORY.
448 //
449 // Only need to check alignment of array base.
450 const Type *ElementType = AT->getElementType();
451 uint64_t ElemAlign = ElementType->getAlignment().value() * 8;
452 if (OffsetBase % ElemAlign)
453 return;
454
455 // Otherwise implement simplified merge. We could be smarter about
456 // this, but it isn't worth it and would be harder to verify.
457 Current = NoClass;
458 uint64_t EltSize = ElementType->getABISizeInBits();
459 uint64_t ArraySize = AT->getNumElements();
460
461 // The only case a 256-bit wide vector could be used is when the array
462 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
463 // to work for sizes wider than 128, early check and fallback to memory.
464 //
465 if (Size > 128 &&
466 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
467 return;
468
469 for (uint64_t I = 0, Offset = OffsetBase; I < ArraySize;
470 ++I, Offset += EltSize) {
471 Class FieldLo, FieldHi;
472 classify(ElementType, Offset, FieldLo, FieldHi, IsNamedArg);
473 Lo = merge(Lo, FieldLo);
474 Hi = merge(Hi, FieldHi);
475 if (Lo == Memory || Hi == Memory)
476 break;
477 }
478 postMerge(Size, Lo, Hi);
479 assert((Hi != SseUp || Lo == Sse) && "Invalid SseUp array classification.");
480 return;
481 }
482
483 if (const auto *RT = dyn_cast<RecordType>(T)) {
484 uint64_t Size = RT->getABISizeInBits();
485
486 if (containsMatrixField(RT)) {
487 Lo = Memory;
488 return;
489 }
490
491 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
492 // than eight eightbytes, ..., it has class MEMORY.
493 if (Size > 512)
494 return;
495
496 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
497 // copy constructor or a non-trivial destructor, it is passed by invisible
498 // reference.
499 if (getRecordArgABI(RT))
500 return;
501
502 // Assume variable sized types are passed in memory.
503 if (RT->hasFlexibleArrayMember())
504 return;
505
506 // Reset Lo class, this will be recomputed.
507 Current = NoClass;
508
509 // If this is a C++ record, classify the bases first.
510 if (RT->isCXXRecord()) {
511 for (const auto &Base : RT->getBaseClasses()) {
512
513 // Classify this field.
514 //
515 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
516 // single eightbyte, each is classified separately. Each eightbyte gets
517 // initialized to class NO_CLASS.
518 Class FieldLo, FieldHi;
519 uint64_t Offset = OffsetBase + Base.OffsetInBits;
520 classify(Base.FieldType, Offset, FieldLo, FieldHi, IsNamedArg);
521 Lo = merge(Lo, FieldLo);
522 Hi = merge(Hi, FieldHi);
523
524 if (getX86ABICompatInfo().ReturnCXXRecordGreaterThan128InMem &&
525 (Size > 128 && (Size != Base.FieldType->getABISizeInBits() ||
527 Lo = Memory;
528
529 if (Lo == Memory || Hi == Memory) {
530 postMerge(Size, Lo, Hi);
531 return;
532 }
533 }
534 }
535
536 // Classify the fields one at a time, merging the results.
537
538 bool IsUnion = RT->isUnion() && !getX86ABICompatInfo().Clang11Compat;
539 for (const auto &Field : RT->getFields()) {
540 uint64_t Offset = OffsetBase + Field.OffsetInBits;
541 bool BitField = Field.IsBitField;
542
543 // Ignore padding bit-fields. Normally only zero-length bit-fields are
544 // padding, but under Clang 23 compatibility every unnamed bit-field is,
545 // faithfully reproducing Clang 23.
546 if (BitField && (getX86ABICompatInfo().ClassifyUnnamedBitFields
547 ? Field.BitFieldWidth == 0
548 : Field.IsUnnamedBitfield))
549 continue;
550
551 uint64_t FieldSize = Field.FieldType->getABISizeInBits();
552 if (Size > 128 && ((!IsUnion && Size != FieldSize) ||
553 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
554 Lo = Memory;
555 postMerge(Size, Lo, Hi);
556 return;
557 }
558
559 bool IsInMemory = Offset % (Field.FieldType->getAlignment().value() * 8);
560 if (!BitField && IsInMemory) {
561 Lo = Memory;
562 postMerge(Size, Lo, Hi);
563 return;
564 }
565
566 Class FieldLo, FieldHi;
567
568 if (BitField) {
569 uint64_t BitFieldSize = Field.BitFieldWidth;
570 uint64_t EbLo = Offset / 64;
571 uint64_t EbHi = (Offset + BitFieldSize - 1) / 64;
572
573 if (EbLo) {
574 assert(EbHi == EbLo && "Invalid classification, type > 16 bytes.");
575 FieldLo = NoClass;
576 FieldHi = Integer;
577 } else {
578 FieldLo = Integer;
579 FieldHi = EbHi ? Integer : NoClass;
580 }
581 } else {
582 classify(Field.FieldType, Offset, FieldLo, FieldHi, IsNamedArg);
583 }
584
585 Lo = merge(Lo, FieldLo);
586 Hi = merge(Hi, FieldHi);
587 if (Lo == Memory || Hi == Memory)
588 break;
589 }
590 postMerge(Size, Lo, Hi);
591 return;
592 }
593
594 Lo = Memory;
595 Hi = NoClass;
596}
597
599X86_64TargetInfo::classifyArgumentType(const Type *Ty, unsigned FreeIntRegs,
600 unsigned &NeededInt, unsigned &NeededSSE,
601 bool IsNamedArg, bool IsRegCall) const {
602
604
606 classify(Ty, 0, Lo, Hi, IsNamedArg, IsRegCall);
607
608 // Check some invariants
609 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
610 assert((Hi != SseUp || Lo == Sse) && "Invalid SseUp classification.");
611
612 NeededInt = 0;
613 NeededSSE = 0;
614 const Type *ResType = nullptr;
615
616 switch (Lo) {
617 case NoClass:
618 if (Hi == NoClass)
619 return ArgInfo::getIgnore();
620 // If the low part is just padding, it takes no register, leave ResType
621 // null.
622 assert((Hi == Sse || Hi == Integer || Hi == X87Up) &&
623 "Unknown missing lo part");
624 break;
625
626 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
627 // on the stack.
628 case Memory:
629 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87Up or
630 // COMPLEX_X87, it is passed in memory.
631 case X87:
632 case ComplexX87:
633 if (getRecordArgABI(Ty) == RAA_Indirect)
634 ++NeededInt;
635 return getIndirectResult(Ty, FreeIntRegs);
636
637 case SseUp:
638 case X87Up:
639 llvm_unreachable("Invalid classification for lo word.");
640
641 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
642 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
643 // and %r9 is used.
644 case Integer:
645 ++NeededInt;
646
647 // Pick an 8-byte type based on the preferred type.
648 ResType = getIntegerTypeAtOffset(Ty, 0, Ty, 0);
649
650 // If we have a sign or zero extended integer, make sure to return Extend
651 // so that the parameter gets the right LLVM IR attributes.
652 if (Hi == NoClass && ResType->isInteger()) {
653 if (Ty->isInteger() && isPromotableInteger(cast<IntegerType>(Ty)))
654 return ArgInfo::getExtend(Ty);
655 }
656
657 if (ResType->isInteger() && ResType->getSizeInBits() == 128) {
658 assert(Hi == Integer);
659 ++NeededInt;
660 return ArgInfo::getDirect(ResType);
661 }
662 break;
663
664 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
665 // available SSE register is used, the registers are taken in the
666 // order from %xmm0 to %xmm7.
667 case Sse:
668 ResType = getSSETypeAtOffset(Ty, 0, Ty, 0);
669 ++NeededSSE;
670 break;
671 }
672
673 const Type *HighPart = nullptr;
674 switch (Hi) {
675 // Memory was handled previously, ComplexX87 and X87 should
676 // never occur as hi classes, and X87Up must be preceded by X87,
677 // which is passed in memory.
678 case Memory:
679 case X87:
680 case ComplexX87:
681 llvm_unreachable("Invalid classification for hi word.");
682
683 case NoClass:
684 break;
685
686 case Integer:
687 ++NeededInt;
688 // Pick an 8-byte type based on the preferred type.
689 HighPart = getIntegerTypeAtOffset(Ty, 8, Ty, 8);
690
691 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
692 return ArgInfo::getDirect(HighPart, 8);
693 break;
694
695 // X87Up generally doesn't occur here (long double is passed in
696 // memory), except in situations involving unions.
697 case X87Up:
698 case Sse:
699 ++NeededSSE;
700 HighPart = getSSETypeAtOffset(Ty, 8, Ty, 8);
701
702 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
703 return ArgInfo::getDirect(HighPart, 8);
704 break;
705
706 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
707 // eightbyte is passed in the upper half of the last used SSE
708 // register. This only happens when 128-bit vectors are passed.
709 case SseUp:
710 assert(Lo == Sse && "Unexpected SseUp classification");
711 ResType = getByteVectorType(Ty);
712 break;
713 }
714
715 // If a high part was specified, merge it together with the low part. It is
716 // known to pass in the high eightbyte of the result. We do this by forming a
717 // first class struct aggregate with the high and low part: {low, high}
718 if (HighPart)
719 ResType = createPairType(ResType, HighPart);
720
721 return ArgInfo::getDirect(ResType);
722}
723
724ArgInfo X86_64TargetInfo::classifyReturnType(const Type *RetTy) const {
725 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
726 // classification algorithm.
727
729 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
730
731 // Check some invariants
732 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
733 assert((Hi != SseUp || Lo == Sse) && "Invalid SseUp classification.");
734
735 const Type *ResType = nullptr;
736 switch (Lo) {
737 case NoClass:
738 if (Hi == NoClass)
739 return ArgInfo::getIgnore();
740 // If the low part is just padding, it takes no register, leave ResType
741 // null.
742 assert((Hi == Sse || Hi == Integer || Hi == X87Up) &&
743 "Unknown missing lo part");
744 break;
745 case SseUp:
746 case X87Up:
747 llvm_unreachable("Invalid classification for lo word.");
748
749 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
750 // hidden argument.
751 case Memory:
752 return getIndirectReturnResult(RetTy);
753
754 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
755 // available register of the sequence %rax, %rdx is used.
756 case Integer:
757 ResType = getIntegerTypeAtOffset(RetTy, 0, RetTy, 0);
758 // If we have a sign or zero extended integer, make sure to return Extend
759 // so that the parameter gets the right LLVM IR attributes.
760 if (Hi == NoClass && ResType->isInteger()) {
761 if (const IntegerType *IntTy = dyn_cast<IntegerType>(RetTy))
762 if (isPromotableInteger(IntTy))
763 return shouldExtendReturnType(IntTy) ? ArgInfo::getExtend(RetTy)
764 : ArgInfo::getDirect(RetTy);
765 }
766 if (ResType->isInteger() && ResType->getSizeInBits() == 128) {
767 assert(Hi == Integer);
768 return ArgInfo::getDirect(ResType);
769 }
770 break;
771
772 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
773 // available SSE register of the sequence %xmm0, %xmm1 is used.
774 case Sse:
775 ResType = getSSETypeAtOffset(RetTy, 0, RetTy, 0);
776 break;
777
778 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
779 // returned on the X87 stack in %st0 as 80-bit x87 number.
780 case X87:
781 ResType = TB.getFloatType(APFloat::x87DoubleExtended(), Align(16));
782 break;
783
784 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
785 // part of the value is returned in %st0 and the imaginary part in
786 // %st1.
787 case ComplexX87:
788 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
789 {
790 const Type *X87Type =
791 TB.getFloatType(APFloat::x87DoubleExtended(), Align(16));
792 FieldInfo Fields[] = {FieldInfo(X87Type, 0), FieldInfo(X87Type, 80)};
793 ResType = TB.getRecordType(Fields, TypeSize::getFixed(160), Align(16),
794 /*UnadjustedAlign=*/Align(16));
795 }
796 break;
797 }
798
799 const Type *HighPart = nullptr;
800 switch (Hi) {
801 // Memory was handled previously and X87 should
802 // never occur as a hi class.
803 case Memory:
804 case X87:
805 llvm_unreachable("Invalid classification for hi word.");
806
807 case ComplexX87:
808 case NoClass:
809 break;
810
811 case Integer:
812 HighPart = getIntegerTypeAtOffset(RetTy, 8, RetTy, 8);
813 if (Lo == NoClass)
814 return ArgInfo::getDirect(HighPart, 8);
815 break;
816
817 case Sse:
818 HighPart = getSSETypeAtOffset(RetTy, 8, RetTy, 8);
819 if (Lo == NoClass)
820 return ArgInfo::getDirect(HighPart, 8);
821 break;
822
823 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
824 // is passed in the next available eightbyte chunk if the last used
825 // vector register.
826 //
827 // SSEUP should always be preceded by SSE, just widen.
828 case SseUp:
829 assert(Lo == Sse && "Unexpected SseUp classification.");
830 ResType = getByteVectorType(RetTy);
831 break;
832
833 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87Up, the value is
834 // returned together with the previous X87 value in %st0.
835 case X87Up:
836 // If X87Up is preceded by X87, we don't need to do
837 // anything. However, in some cases with unions it may not be
838 // preceded by X87. In such situations we follow gcc and pass the
839 // extra bits in an SSE reg.
840 if (Lo != X87) {
841 HighPart = getSSETypeAtOffset(RetTy, 8, RetTy, 8);
842 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
843 return ArgInfo::getDirect(HighPart, 8);
844 }
845 break;
846 }
847
848 // If a high part was specified, merge it together with the low part. It is
849 // known to pass in the high eightbyte of the result. We do this by forming a
850 // first class struct aggregate with the high and low part: {low, high}
851 if (HighPart)
852 ResType = createPairType(ResType, HighPart);
853
854 return ArgInfo::getDirect(ResType);
855}
856
857/// Given a high and low type that can ideally
858/// be used as elements of a two register pair to pass or return, return a
859/// first class aggregate to represent them. For example, if the low part of
860/// a by-value argument should be passed as i32* and the high part as float,
861/// return {i32*, float}.
862const Type *X86_64TargetInfo::createPairType(const Type *Lo,
863 const Type *Hi) const {
864 // In order to correctly satisfy the ABI, we need to the high part to start
865 // at offset 8. If the high and low parts we inferred are both 4-byte types
866 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
867 // the second element at offset 8. Check for this:
868 unsigned LoSize = (unsigned)Lo->getTypeAllocSize();
869 llvm::Align HiAlign = Hi->getAlignment();
870 unsigned HiStart = alignTo(LoSize, HiAlign);
871
872 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
873
874 // To handle this, we have to increase the size of the low part so that the
875 // second element will start at an 8 byte offset. We can't increase the size
876 // of the second element because it might make us access off the end of the
877 // struct.
878 const Type *AdjustedLo = Lo;
879 if (HiStart != 8) {
880 // There are usually two sorts of types the ABI generation code can produce
881 // for the low part of a pair that aren't 8 bytes in size: half, float or
882 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
883 // NaCl).
884 // Promote these to a larger type.
885 if (Lo->isFloat()) {
886 const FloatType *FT = cast<FloatType>(Lo);
887 if (FT->getSemantics() == &APFloat::IEEEhalf() ||
888 FT->getSemantics() == &APFloat::IEEEsingle() ||
889 FT->getSemantics() == &APFloat::BFloat())
890 AdjustedLo = TB.getFloatType(APFloat::IEEEdouble(), Align(8));
891 }
892 // Promote integers and pointers to i64
893 else if (Lo->isInteger() || Lo->isPointer())
894 AdjustedLo = TB.getIntegerType(64, Align(8), /*Signed=*/false);
895 else
896 assert((Lo->isInteger() || Lo->isPointer()) &&
897 "Invalid/unknown low type in pair");
898 unsigned AdjustedLoSize = AdjustedLo->getSizeInBits().getFixedValue() / 8;
899 HiStart = alignTo(AdjustedLoSize, HiAlign);
900 }
901
902 // Create the pair struct
903 FieldInfo Fields[] = {FieldInfo(AdjustedLo, 0), FieldInfo(Hi, HiStart * 8)};
904
905 // Verify the high part is at offset 8
906 assert((8 * 8) == Fields[1].OffsetInBits &&
907 "High part must be at offset 8 bytes");
908
909 uint64_t PairSizeInBits =
910 Fields[1].OffsetInBits + Hi->getSizeInBits().getFixedValue();
911 return TB.getRecordType(Fields, TypeSize::getFixed(PairSizeInBits), Align(8),
912 /*UnadjustedAlign=*/Align(8), StructPacking::Default);
913}
914
915static bool bitsContainNoUserData(const Type *Ty, unsigned StartBit,
916 unsigned EndBit) {
917 // If range is completely beyond type size, it's definitely padding
918 unsigned TySize = Ty->getABISizeInBits();
919 if (TySize <= StartBit)
920 return true;
921
922 // Handle arrays - check each element
923 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
924 const Type *EltTy = AT->getElementType();
925 unsigned EltSize = EltTy->getABISizeInBits();
926
927 for (unsigned I = 0; I < AT->getNumElements(); ++I) {
928 unsigned EltOffset = I * EltSize;
929 if (EltOffset >= EndBit)
930 break;
931
932 unsigned EltStart = (EltOffset < StartBit) ? StartBit - EltOffset : 0;
933 if (!bitsContainNoUserData(EltTy, EltStart, EndBit - EltOffset))
934 return false;
935 }
936 return true;
937 }
938
939 // Handle records - check all fields and base classes. getUnionType places a
940 // union's members at offset zero, so the field loop covers a union too.
941 if (const RecordType *RT = dyn_cast<RecordType>(Ty)) {
942 // Check base classes first (for C++ records)
943 if (RT->isCXXRecord()) {
944 for (unsigned I = 0; I < RT->getNumBaseClasses(); ++I) {
945 const FieldInfo &Base = RT->getBaseClasses()[I];
946 if (Base.OffsetInBits >= EndBit)
947 continue;
948
949 unsigned BaseStart =
950 (Base.OffsetInBits < StartBit) ? StartBit - Base.OffsetInBits : 0;
951 if (!bitsContainNoUserData(Base.FieldType, BaseStart,
952 EndBit - Base.OffsetInBits))
953 return false;
954 }
955 }
956
957 for (unsigned I = 0; I < RT->getNumFields(); ++I) {
958 const FieldInfo &Field = RT->getFields()[I];
959 if (Field.OffsetInBits >= EndBit)
960 break;
961
962 unsigned FieldStart =
963 (Field.OffsetInBits < StartBit) ? StartBit - Field.OffsetInBits : 0;
964 if (!bitsContainNoUserData(Field.FieldType, FieldStart,
965 EndBit - Field.OffsetInBits))
966 return false;
967 }
968 return true;
969 }
970
971 // For any other type - assume all bits are user data
972 return false;
973}
974
975const Type *X86_64TargetInfo::getIntegerTypeAtOffset(const Type *ABIType,
976 unsigned ABIOffset,
977 const Type *SourceTy,
978 unsigned SourceOffset,
979 bool InMemory) const {
980
981 const Type *WorkingType = ABIType;
982 if (InMemory && ABIType->isInteger()) {
983 const auto *IT = cast<IntegerType>(ABIType);
984 unsigned OriginalBitWidth = IT->getSizeInBits().getFixedValue();
985
986 unsigned WidenedBitWidth = OriginalBitWidth;
987 if (OriginalBitWidth <= 8) {
988 WidenedBitWidth = 8;
989 } else {
990 WidenedBitWidth = llvm::bit_ceil(OriginalBitWidth);
991 }
992
993 if (WidenedBitWidth != OriginalBitWidth) {
994 WorkingType = TB.getIntegerType(WidenedBitWidth, ABIType->getAlignment(),
995 IT->isSigned());
996 }
997 }
998 // A bool vector is stored as an integer with one bit per element, at least a
999 // byte wide.
1000 if (InMemory && ABIType->isVector()) {
1001 const auto *VT = cast<VectorType>(ABIType);
1002 const auto *IT = dyn_cast<IntegerType>(VT->getElementType());
1003 if (IT && IT->isBool())
1004 WorkingType = TB.getIntegerType(
1005 std::max<uint64_t>(VT->getNumElements().getFixedValue(), 8),
1006 ABIType->getAlignment(), /*Signed=*/false);
1007 }
1008 // If we're dealing with an un-offset ABI type, then it means that we're
1009 // returning an 8-byte unit starting with it. See if we can safely use it.
1010 if (ABIOffset == 0) {
1011 // Pointers and int64's always fill the 8-byte unit. Return WorkingType,
1012 // which is the in-memory-widened type (e.g. a _BitInt(37) field widened to
1013 // i64): returning the raw ABIType here would coerce the eightbyte to the
1014 // narrow iN instead of the storage integer clang uses.
1015 if ((WorkingType->isPointer() && Has64BitPointers) ||
1016 (WorkingType->isInteger() &&
1017 cast<IntegerType>(WorkingType)->getSizeInBits() == 64))
1018 return WorkingType;
1019
1020 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
1021 // goodness in the source type is just tail padding. This is allowed to
1022 // kick in for struct {double,int} on the int, but not on
1023 // struct{double,int,int} because we wouldn't return the second int. We
1024 // have to do this analysis on the source type because we can't depend on
1025 // unions being lowered a specific way etc.
1026 if ((WorkingType->isInteger() &&
1027 (cast<IntegerType>(WorkingType)->getSizeInBits() == 1 ||
1028 cast<IntegerType>(WorkingType)->getSizeInBits() == 8 ||
1029 cast<IntegerType>(WorkingType)->getSizeInBits() == 16 ||
1030 cast<IntegerType>(WorkingType)->getSizeInBits() == 32)) ||
1031 (WorkingType->isPointer() && !Has64BitPointers)) {
1032
1033 unsigned BitWidth = WorkingType->isPointer()
1034 ? 32
1035 : cast<IntegerType>(WorkingType)->getSizeInBits();
1036
1037 if (bitsContainNoUserData(SourceTy, SourceOffset * 8 + BitWidth,
1038 SourceOffset * 8 + 64))
1039 return WorkingType;
1040 }
1041 }
1042
1043 if (const auto *RTy = dyn_cast<RecordType>(ABIType)) {
1044 if (RTy->isUnion()) {
1045 const Type *ReducedType = reduceUnionForX8664(RTy, TB);
1046 if (ReducedType) {
1047 if (ABIOffset * 8 < ReducedType->getABISizeInBits())
1048 return getIntegerTypeAtOffset(ReducedType, ABIOffset, SourceTy,
1049 SourceOffset, true);
1050 // The storage type stops before this offset, so size the coercion
1051 // from the union itself: a byte when the rest of this eightbyte
1052 // holds no data, and the union's remaining bytes otherwise.
1053 if (bitsContainNoUserData(SourceTy, SourceOffset * 8 + 8,
1054 SourceOffset * 8 + 64))
1055 return TB.getIntegerType(8, Align(1), /*Signed=*/false);
1056 unsigned RemainingBytes =
1057 llvm::divideCeil(SourceTy->getABISizeInBits(), 8) - SourceOffset;
1058 return TB.getIntegerType(std::min(RemainingBytes, 8U) * 8, Align(1),
1059 /*Signed=*/false);
1060 }
1061 }
1062 if (const FieldInfo *Element =
1063 RTy->getElementContainingOffset(ABIOffset * 8)) {
1064
1065 unsigned ElementOffsetBytes = Element->OffsetInBits / 8;
1066 return getIntegerTypeAtOffset(Element->FieldType,
1067 ABIOffset - ElementOffsetBytes, SourceTy,
1068 SourceOffset, true);
1069 }
1070 }
1071
1072 if (const auto *ATy = dyn_cast<ArrayType>(ABIType)) {
1073 const Type *EltTy = ATy->getElementType();
1074 unsigned EltSize = EltTy->getABISizeInBits() / 8;
1075 if (EltSize > 0) {
1076 unsigned EltOffset = (ABIOffset / EltSize) * EltSize;
1077 return getIntegerTypeAtOffset(EltTy, ABIOffset - EltOffset, SourceTy,
1078 SourceOffset, true);
1079 }
1080 }
1081
1082 // If we have a 128-bit integer, we can pass it safely using an i128
1083 // so we return that
1084 if (ABIType->isInteger() && ABIType->getSizeInBits() == 128) {
1085 assert(ABIOffset == 0);
1086 return ABIType;
1087 }
1088
1089 unsigned TySizeInBytes = llvm::divideCeil(SourceTy->getABISizeInBits(), 8);
1090 assert(TySizeInBytes != SourceOffset && "Empty field?");
1091 unsigned AvailableSize = TySizeInBytes - SourceOffset;
1092 return TB.getIntegerType(std::min(AvailableSize, 8U) * 8, Align(1), false);
1093}
1094/// Returns the floating point type at the specified offset within a type, or
1095/// nullptr if no floating point type is found at that offset.
1096const Type *X86_64TargetInfo::getFPTypeAtOffset(const Type *Ty,
1097 unsigned Offset) const {
1098 // Check for direct match at offset 0
1099 if (Offset == 0 && Ty->isFloat())
1100 return Ty;
1101
1102 if (const ComplexType *CT = dyn_cast<ComplexType>(Ty)) {
1103 const Type *ElementType = CT->getElementType();
1104 unsigned ElementSize = ElementType->getABISizeInBits() / 8;
1105
1106 if (Offset == 0 || Offset == ElementSize)
1107 return ElementType;
1108 return nullptr;
1109 }
1110
1111 // Handle struct types by checking each field
1112 if (const RecordType *RT = dyn_cast<RecordType>(Ty)) {
1113 if (const FieldInfo *Element = RT->getElementContainingOffset(Offset * 8)) {
1114 unsigned ElementOffsetBytes = Element->OffsetInBits / 8;
1115 return getFPTypeAtOffset(Element->FieldType, Offset - ElementOffsetBytes);
1116 }
1117 }
1118
1119 // Handle array types
1120 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
1121 const Type *EltTy = AT->getElementType();
1122 unsigned EltSize = EltTy->getABISizeInBits() / 8;
1123 if (EltSize == 0)
1124 return nullptr;
1125 unsigned EltIndex = Offset / EltSize;
1126
1127 return getFPTypeAtOffset(EltTy, Offset - (EltIndex * EltSize));
1128 }
1129
1130 // No floating point type found at this offset
1131 return nullptr;
1132}
1133
1134/// Helper to check if a floating point type matches specific semantics
1135static bool isFloatTypeWithSemantics(const Type *Ty,
1136 const fltSemantics &Semantics) {
1137 if (!Ty->isFloat())
1138 return false;
1139 const FloatType *FT = cast<FloatType>(Ty);
1140 return FT->getSemantics() == &Semantics;
1141}
1142
1143/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
1144/// low 8 bytes of an XMM register, corresponding to the SSE class.
1145const Type *X86_64TargetInfo::getSSETypeAtOffset(const Type *ABIType,
1146 unsigned ABIOffset,
1147 const Type *SourceTy,
1148 unsigned SourceOffset) const {
1149
1150 if (const auto *RTy = dyn_cast<RecordType>(ABIType)) {
1151 if (RTy->isUnion()) {
1152 const Type *ReducedType = reduceUnionForX8664(RTy, TB);
1153 if (ReducedType) {
1154 return getSSETypeAtOffset(ReducedType, ABIOffset, SourceTy,
1155 SourceOffset);
1156 }
1157 }
1158 }
1159
1160 auto Is16bitFpTy = [](const Type *T) {
1163 };
1164
1165 // Get the floating point type at the requested offset
1166 const Type *T0 = getFPTypeAtOffset(ABIType, ABIOffset);
1168 return TB.getFloatType(APFloat::IEEEdouble(), Align(8));
1169
1170 // Calculate remaining source size in bytes
1171 unsigned SourceSize = (SourceTy->getABISizeInBits() / 8) - SourceOffset;
1172
1173 // Try to get adjacent FP type
1174 const Type *T1 = nullptr;
1175 unsigned T0Size = T0->getABISizeInBits() / 8;
1176 if (SourceSize > T0Size)
1177 T1 = getFPTypeAtOffset(ABIType, ABIOffset + T0Size);
1178
1179 if (T1 == nullptr) {
1180 if (Is16bitFpTy(T0) && SourceSize > 4)
1181 T1 = getFPTypeAtOffset(ABIType, ABIOffset + 4);
1182
1183 if (T1 == nullptr)
1184 return T0;
1185 }
1186 // Handle vector cases
1189 return TB.getVectorType(T0, ElementCount::getFixed(2), Align(8));
1190
1191 if (Is16bitFpTy(T0) && Is16bitFpTy(T1)) {
1192 const Type *T2 = nullptr;
1193 if (SourceSize > 4)
1194 T2 = getFPTypeAtOffset(ABIType, ABIOffset + 4);
1195 if (!T2)
1196 return TB.getVectorType(T0, ElementCount::getFixed(2), Align(8));
1197 return TB.getVectorType(T0, ElementCount::getFixed(4), Align(8));
1198 }
1199
1200 // Mixed half-float cases
1201 if (Is16bitFpTy(T0) || Is16bitFpTy(T1))
1202 return TB.getVectorType(TB.getFloatType(APFloat::IEEEhalf(), Align(2)),
1204
1205 // Default to double
1206 return TB.getFloatType(APFloat::IEEEdouble(), Align(8));
1207}
1208
1209/// The ABI specifies that a value should be passed in a full vector XMM/YMM
1210/// register. Pick an LLVM IR type that will be passed as a vector register.
1211const Type *X86_64TargetInfo::getByteVectorType(const Type *Ty) const {
1212 // Wrapper structs/arrays that only contain vectors are passed just like
1213 // vectors; strip them off if present.
1214 if (const Type *InnerTy = isSingleElementStruct(Ty))
1215 Ty = InnerTy;
1216
1217 // Handle vector types
1218 if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
1219 // Don't pass vXi128 vectors in their native type, the backend can't
1220 // legalize them.
1221 if (getX86ABICompatInfo().PassInt128VectorsInMem &&
1222 VT->getElementType()->isInteger() &&
1223 cast<IntegerType>(VT->getElementType())->getSizeInBits() == 128) {
1224 unsigned Size = VT->getABISizeInBits();
1225 return TB.getVectorType(TB.getIntegerType(64, Align(8), /*Signed=*/false),
1227 Align(Size / 8));
1228 }
1229 return VT;
1230 }
1231
1232 // Handle fp128
1234 return Ty;
1235
1236 // We couldn't find the preferred IR vector type for 'Ty'.
1237 unsigned Size = Ty->getABISizeInBits();
1238 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid vector size");
1239
1240 return TB.getVectorType(TB.getFloatType(APFloat::IEEEdouble(), Align(8)),
1242}
1243
1244bool X86_64TargetInfo::isIllegalVectorType(const Type *Ty) const {
1245 if (const auto *VecTy = dyn_cast<VectorType>(Ty)) {
1246 uint64_t Size = VecTy->getABISizeInBits();
1247 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
1248
1249 // Vectors <= 64 bits or > largest supported vector size are illegal
1250 if (Size <= 64 || Size > LargestVector)
1251 return true;
1252
1253 // Check for 128-bit integer element vectors that should be passed in memory
1254 const Type *EltTy = VecTy->getElementType();
1255 if (getX86ABICompatInfo().PassInt128VectorsInMem && EltTy->isInteger()) {
1256 const auto *IntTy = cast<IntegerType>(EltTy);
1257 if (IntTy->getSizeInBits().getFixedValue() == 128 && !IntTy->isBitInt())
1258 return true;
1259 }
1260 }
1261 return false;
1262}
1263
1264ArgInfo X86_64TargetInfo::getIndirectResult(const Type *Ty,
1265 unsigned FreeIntRegs) const {
1266 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1267 // place naturally.
1268 //
1269 // This assumption is optimistic, as there could be free registers available
1270 // when we need to pass this argument in memory, and LLVM could try to pass
1271 // the argument in the free register. This does not seem to happen currently,
1272 // but this code would be much safer if we could mark the argument with
1273 // 'onstack'. See PR12193.
1274 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty) &&
1275 !(Ty->isInteger() && cast<IntegerType>(Ty)->isBitInt())) {
1276 return (Ty->isInteger() && isPromotableInteger(cast<IntegerType>(Ty))
1277 ? ArgInfo::getExtend(Ty)
1278 : ArgInfo::getDirect());
1279 }
1280
1281 // Check if this is a record type that needs special handling
1282 if (auto RecordRAA = getRecordArgABI(Ty))
1284 /*ByVal=*/RecordRAA ==
1286
1287 // Compute the byval alignment. We specify the alignment of the byval in all
1288 // cases so that the mid-level optimizer knows the alignment of the byval.
1289 uint64_t AlignVal = std::max<uint64_t>(Ty->getAlignment().value(), 8u);
1290
1291 // Attempt to avoid passing indirect results using byval when possible. This
1292 // is important for good codegen.
1293 //
1294 // We do this by coercing the value into a scalar type which the backend can
1295 // handle naturally (i.e., without using byval).
1296 //
1297 // For simplicity, we currently only do this when we have exhausted all of the
1298 // free integer registers. Doing this when there are free integer registers
1299 // would require more care, as we would have to ensure that the coerced value
1300 // did not claim the unused register. That would require either reording the
1301 // arguments to the function (so that any subsequent inreg values came first),
1302 // or only doing this optimization when there were no following arguments that
1303 // might be inreg.
1304 //
1305 // We currently expect it to be rare (particularly in well written code) for
1306 // arguments to be passed on the stack when there are still free integer
1307 // registers available (this would typically imply large structs being passed
1308 // by value), so this seems like a fair tradeoff for now.
1309 //
1310 // We can revisit this if the backend grows support for 'onstack' parameter
1311 // attributes. See PR12193.
1312 if (FreeIntRegs == 0) {
1313 uint64_t Size = Ty->getABISizeInBits();
1314
1315 // If this type fits in an eightbyte, coerce it into the matching integral
1316 // type, which will end up on the stack (with alignment 8).
1317 if (AlignVal == 8 && Size <= 64) {
1318 const Type *IntTy =
1319 TB.getIntegerType(Size, llvm::Align(8), /*Signed=*/false);
1320 return ArgInfo::getDirect(IntTy);
1321 }
1322 }
1323
1324 return ArgInfo::getIndirect(llvm::Align(AlignVal), /*ByVal=*/true);
1325}
1326
1327ArgInfo X86_64TargetInfo::getIndirectReturnResult(const Type *Ty) const {
1328 if (!isAggregateTypeForABI(Ty)) {
1329 // Bit-precise integers are returned indirectly regardless of size.
1330 if (const auto *IntTy = dyn_cast<IntegerType>(Ty)) {
1331 if (IntTy->isBitInt())
1333 if (shouldExtendReturnType(IntTy))
1334 return ArgInfo::getExtend(Ty);
1335 }
1336 return ArgInfo::getDirect();
1337 }
1338
1340}
1341
1342void X86_64TargetInfo::computeInfo(FunctionInfo &FI) const {
1343 CallingConv::ID CallingConv = FI.getCallingConvention();
1344
1345 // Only the standard SysV (C) calling convention is classified here. Any other
1346 // convention must be added explicitly once it has been verified against this
1347 // classifier rather than silently taking the SysV path.
1348 switch (CallingConv) {
1349 case CallingConv::C:
1350 break;
1351 default:
1353 "calling convention not supported by the LLVMABI X86_64 classifier");
1354 }
1355
1356 unsigned FreeIntRegs = 6;
1357 unsigned FreeSSERegs = 8;
1358 unsigned NeededInt = 0, NeededSSE = 0;
1359
1361 const Type *RetTy = FI.getReturnType();
1362 FI.getReturnInfo() = classifyReturnType(RetTy);
1363 }
1364
1365 if (FI.getReturnInfo().isIndirect())
1366 --FreeIntRegs;
1367
1368 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
1369
1370 unsigned ArgNo = 0;
1371 for (auto IT = FI.arg_begin(), IE = FI.arg_end(); IT != IE; ++IT, ++ArgNo) {
1372 bool IsNamedArg = ArgNo < NumRequiredArgs;
1373 const Type *ArgTy = IT->ABIType;
1374 NeededInt = 0;
1375 NeededSSE = 0;
1376
1377 ArgInfo AI = classifyArgumentType(ArgTy, FreeIntRegs, NeededInt, NeededSSE,
1378 IsNamedArg);
1379
1380 // AMD64-ABI 3.2.3p3: If there are no registers available for any
1381 // eightbyte of an argument, the whole argument is passed on the
1382 // stack. If registers have already been assigned for some
1383 // eightbytes of such an argument, the assignments get reverted.
1384 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
1385 FreeIntRegs -= NeededInt;
1386 FreeSSERegs -= NeededSSE;
1387 AI.setNeededRegs(NeededInt, NeededSSE);
1388 IT->Info = AI;
1389 } else {
1390 // Not enough registers, pass on stack. The demand the classification
1391 // reports is what the argument ends up occupying, which is nothing.
1392 IT->Info = getIndirectResult(ArgTy, FreeIntRegs);
1393 }
1394 }
1395}
1396
1397std::unique_ptr<TargetInfo>
1399 bool Has64BitPointers, const X86ABICompatInfo &Compat) {
1400 return std::make_unique<X86_64TargetInfo>(TB, AVXLevel, Has64BitPointers,
1401 Compat);
1402}
1403
1404} // namespace abi
1405} // namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::values(clEnumValN(DefaultIT, "arm-default-it", "Generate any type of IT block"), clEnumValN(RestrictedIT, "arm-restrict-it", "Disallow complex IT blocks")))
static LoopDeletionResult merge(LoopDeletionResult A, LoopDeletionResult B)
#define I(x, y, z)
Definition MD5.cpp:57
#define T
#define T1
OptimizedStructLayoutField Field
FunctionLoweringInfo::StatepointRelocationRecord RecordType
Target-specific ABI information and factory functions.
static const fltSemantics & IEEEsingle()
Definition APFloat.h:304
static const fltSemantics & BFloat()
Definition APFloat.h:303
static const fltSemantics & IEEEquad()
Definition APFloat.h:306
static const fltSemantics & IEEEdouble()
Definition APFloat.h:305
static const fltSemantics & x87DoubleExtended()
Definition APFloat.h:307
static const fltSemantics & IEEEhalf()
Definition APFloat.h:302
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:306
Class to represent integer types.
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:348
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
Helper class to encapsulate information about how a specific type should be passed to or returned fro...
static ArgInfo getIgnore()
static ArgInfo getExtend(const Type *T)
static ArgInfo getIndirect(Align Align, bool ByVal, unsigned AddrSpace=0, bool Realign=false)
Realign: the caller couldn't guarantee sufficient alignment - the callee must copy the argument to a ...
static ArgInfo getDirect(const Type *T=nullptr, unsigned Offset=0, MaybeAlign Align=std::nullopt, bool CanBeFlattened=true)
const fltSemantics * getSemantics() const
Definition Types.h:197
bool isUnion() const
Definition Types.h:419
ArrayRef< FieldInfo > getFields() const
Definition Types.h:442
bool isTransparentUnion() const
Definition Types.h:439
LLVM_ABI const Type * isSingleElementStruct(const Type *Ty) const
Returns the scalar a single-element struct reduces to, else null.
virtual unsigned getAllocaAddrSpace() const
Address space in which indirect arguments are allocated (the target's alloca/stack space).
Definition TargetInfo.h:85
LLVM_ABI bool isPromotableInteger(const IntegerType *IT) const
TargetInfo(TypeBuilder &Builder)
Definition TargetInfo.h:70
LLVM_ABI bool maybeCommonClassifyReturnType(FunctionInfo &FI) const
Apply rules for classifying return types that are common to all targets.
LLVM_ABI bool isAggregateTypeForABI(const Type *Ty) const
TypeBuilder & TB
Definition TargetInfo.h:67
LLVM_ABI const Type * useFirstFieldIfTransparentUnion(const Type *Ty) const
If Ty is a transparent union, return its first field type; otherwise return Ty unchanged.
LLVM_ABI ArgInfo getNaturalAlignIndirect(const Type *Ty, unsigned AddrSpace, bool ByVal=true) const
LLVM_ABI RecordArgABI getRecordArgABI(const RecordType *RT) const
TypeBuilder manages the lifecycle of ABI types using bump pointer allocation.
Definition Types.h:471
Represents the ABI-specific view of a type in LLVM.
Definition Types.h:47
TypeSize getTypeAllocSize() const
Definition Types.h:102
TypeSize getSizeInBits() const
Definition Types.h:75
LLVM_ABI uint64_t getABISizeInBits() const
Returns the size in bits that the source language gives this type, including any padding.
Definition Types.cpp:18
Align getAlignment() const
Definition Types.h:95
X86_64TargetInfo(TypeBuilder &TypeBuilder, X86AVXABILevel AVXABILevel, bool Has64BitPtrs, const X86ABICompatInfo &Compat)
Definition X86.cpp:81
bool has64BitPointers() const
Definition X86.cpp:86
const X86ABICompatInfo & getX86ABICompatInfo() const
Definition X86.cpp:92
const ABICompatInfo & getABICompatInfo() const override
Return this target's ABI compatibility flags.
Definition X86.cpp:88
static constexpr bool isKnownGT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:224
This file defines the type system for the LLVMABI library, which mirrors ABI-relevant aspects of fron...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
LLVM_ABI std::unique_ptr< TargetInfo > createX86_64TargetInfo(TypeBuilder &TB, X86AVXABILevel AVXLevel, bool Has64BitPointers, const X86ABICompatInfo &Compat)
Definition X86.cpp:1398
@ IsUnion
Definition Types.h:392
static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel)
Definition X86.cpp:24
X86AVXABILevel
The AVX ABI level for X86 targets.
Definition TargetInfo.h:180
static const Type * reduceUnionForX8664(const RecordType *UnionType, TypeBuilder &TB)
Definition X86.cpp:99
static bool bitsContainNoUserData(const Type *Ty, unsigned StartBit, unsigned EndBit)
Definition X86.cpp:915
static bool isFloatTypeWithSemantics(const Type *Ty, const fltSemantics &Semantics)
Helper to check if a floating point type matches specific semantics.
Definition X86.cpp:1135
@ RAA_Indirect
Pass it as a pointer to temporary memory.
Definition TargetInfo.h:37
@ RAA_DirectInMemory
Pass it on the stack using its defined layout.
Definition TargetInfo.h:34
ElementType
The element type of an SRV or UAV resource.
Definition DXILABI.h:68
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
T bit_ceil(T Value)
Returns the smallest integral power of two no smaller than Value if Value is nonzero.
Definition bit.h:362
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
Flags controlling ABI compatibility behaviour that applies to every target.
Definition TargetInfo.h:43
Flags controlling X86-specific ABI compatibility behaviour.
Definition TargetInfo.h:51