1 //===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // These classes wrap the information about a call or function
11 // definition used to handle ABI compliancy.
13 //===----------------------------------------------------------------------===//
15 #include "TargetInfo.h"
19 #include "CodeGenFunction.h"
20 #include "clang/AST/RecordLayout.h"
21 #include "clang/CodeGen/CGFunctionInfo.h"
22 #include "clang/CodeGen/SwiftCallingConv.h"
23 #include "clang/Frontend/CodeGenOptions.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/Type.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include <algorithm> // std::sort
31 using namespace clang;
32 using namespace CodeGen;
34 // Helper for coercing an aggregate argument or return value into an integer
35 // array of the same size (including padding) and alignment. This alternate
36 // coercion happens only for the RenderScript ABI and can be removed after
37 // runtimes that rely on it are no longer supported.
39 // RenderScript assumes that the size of the argument / return value in the IR
40 // is the same as the size of the corresponding qualified type. This helper
41 // coerces the aggregate type into an array of the same size (including
42 // padding). This coercion is used in lieu of expansion of struct members or
43 // other canonical coercions that return a coerced-type of larger size.
45 // Ty - The argument / return value type
46 // Context - The associated ASTContext
47 // LLVMContext - The associated LLVMContext
48 static ABIArgInfo coerceToIntArray(QualType Ty,
50 llvm::LLVMContext &LLVMContext) {
51 // Alignment and Size are measured in bits.
52 const uint64_t Size = Context.getTypeSize(Ty);
53 const uint64_t Alignment = Context.getTypeAlign(Ty);
54 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment);
55 const uint64_t NumElements = (Size + Alignment - 1) / Alignment;
56 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
59 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
64 // Alternatively, we could emit this as a loop in the source.
65 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
67 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
68 Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
72 static bool isAggregateTypeForABI(QualType T) {
73 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
74 T->isMemberFunctionPointerType();
78 ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByRef, bool Realign,
79 llvm::Type *Padding) const {
80 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty),
81 ByRef, Realign, Padding);
85 ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
86 return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
87 /*ByRef*/ false, Realign);
90 Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
92 return Address::invalid();
95 ABIInfo::~ABIInfo() {}
97 /// Does the given lowering require more than the given number of
98 /// registers when expanded?
100 /// This is intended to be the basis of a reasonable basic implementation
101 /// of should{Pass,Return}IndirectlyForSwift.
103 /// For most targets, a limit of four total registers is reasonable; this
104 /// limits the amount of code required in order to move around the value
105 /// in case it wasn't produced immediately prior to the call by the caller
106 /// (or wasn't produced in exactly the right registers) or isn't used
107 /// immediately within the callee. But some targets may need to further
108 /// limit the register count due to an inability to support that many
109 /// return registers.
110 static bool occupiesMoreThan(CodeGenTypes &cgt,
111 ArrayRef<llvm::Type*> scalarTypes,
112 unsigned maxAllRegisters) {
113 unsigned intCount = 0, fpCount = 0;
114 for (llvm::Type *type : scalarTypes) {
115 if (type->isPointerTy()) {
117 } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
118 auto ptrWidth = cgt.getTarget().getPointerWidth(0);
119 intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth;
121 assert(type->isVectorTy() || type->isFloatingPointTy());
126 return (intCount + fpCount > maxAllRegisters);
129 bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
131 unsigned numElts) const {
132 // The default implementation of this assumes that the target guarantees
133 // 128-bit SIMD support but nothing more.
134 return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16);
137 static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
139 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
141 return CGCXXABI::RAA_Default;
142 return CXXABI.getRecordArgABI(RD);
145 static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
147 const RecordType *RT = T->getAs<RecordType>();
149 return CGCXXABI::RAA_Default;
150 return getRecordArgABI(RT, CXXABI);
153 /// Pass transparent unions as if they were the type of the first element. Sema
154 /// should ensure that all elements of the union have the same "machine type".
155 static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
156 if (const RecordType *UT = Ty->getAsUnionType()) {
157 const RecordDecl *UD = UT->getDecl();
158 if (UD->hasAttr<TransparentUnionAttr>()) {
159 assert(!UD->field_empty() && "sema created an empty transparent union");
160 return UD->field_begin()->getType();
166 CGCXXABI &ABIInfo::getCXXABI() const {
167 return CGT.getCXXABI();
170 ASTContext &ABIInfo::getContext() const {
171 return CGT.getContext();
174 llvm::LLVMContext &ABIInfo::getVMContext() const {
175 return CGT.getLLVMContext();
178 const llvm::DataLayout &ABIInfo::getDataLayout() const {
179 return CGT.getDataLayout();
182 const TargetInfo &ABIInfo::getTarget() const {
183 return CGT.getTarget();
186 bool ABIInfo:: isAndroid() const { return getTarget().getTriple().isAndroid(); }
188 bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
192 bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
193 uint64_t Members) const {
197 bool ABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
201 LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
202 raw_ostream &OS = llvm::errs();
203 OS << "(ABIArgInfo Kind=";
206 OS << "Direct Type=";
207 if (llvm::Type *Ty = getCoerceToType())
219 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
222 OS << "Indirect Align=" << getIndirectAlign().getQuantity()
223 << " ByVal=" << getIndirectByVal()
224 << " Realign=" << getIndirectRealign();
229 case CoerceAndExpand:
230 OS << "CoerceAndExpand Type=";
231 getCoerceAndExpandType()->print(OS);
237 // Dynamically round a pointer up to a multiple of the given alignment.
238 static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
241 llvm::Value *PtrAsInt = Ptr;
242 // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
243 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
244 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
245 llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
246 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
247 llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
248 PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
250 Ptr->getName() + ".aligned");
254 /// Emit va_arg for a platform using the common void* representation,
255 /// where arguments are simply emitted in an array of slots on the stack.
257 /// This version implements the core direct-value passing rules.
259 /// \param SlotSize - The size and alignment of a stack slot.
260 /// Each argument will be allocated to a multiple of this number of
261 /// slots, and all the slots will be aligned to this value.
262 /// \param AllowHigherAlign - The slot alignment is not a cap;
263 /// an argument type with an alignment greater than the slot size
264 /// will be emitted on a higher-alignment address, potentially
265 /// leaving one or more empty slots behind as padding. If this
266 /// is false, the returned address might be less-aligned than
268 static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
270 llvm::Type *DirectTy,
271 CharUnits DirectSize,
272 CharUnits DirectAlign,
274 bool AllowHigherAlign) {
275 // Cast the element type to i8* if necessary. Some platforms define
276 // va_list as a struct containing an i8* instead of just an i8*.
277 if (VAListAddr.getElementType() != CGF.Int8PtrTy)
278 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
280 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
282 // If the CC aligns values higher than the slot size, do so if needed.
283 Address Addr = Address::invalid();
284 if (AllowHigherAlign && DirectAlign > SlotSize) {
285 Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
288 Addr = Address(Ptr, SlotSize);
291 // Advance the pointer past the argument, then store that back.
292 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
293 llvm::Value *NextPtr =
294 CGF.Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), FullDirectSize,
296 CGF.Builder.CreateStore(NextPtr, VAListAddr);
298 // If the argument is smaller than a slot, and this is a big-endian
299 // target, the argument will be right-adjusted in its slot.
300 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
301 !DirectTy->isStructTy()) {
302 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
305 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
309 /// Emit va_arg for a platform using the common void* representation,
310 /// where arguments are simply emitted in an array of slots on the stack.
312 /// \param IsIndirect - Values of this type are passed indirectly.
313 /// \param ValueInfo - The size and alignment of this type, generally
314 /// computed with getContext().getTypeInfoInChars(ValueTy).
315 /// \param SlotSizeAndAlign - The size and alignment of a stack slot.
316 /// Each argument will be allocated to a multiple of this number of
317 /// slots, and all the slots will be aligned to this value.
318 /// \param AllowHigherAlign - The slot alignment is not a cap;
319 /// an argument type with an alignment greater than the slot size
320 /// will be emitted on a higher-alignment address, potentially
321 /// leaving one or more empty slots behind as padding.
322 static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
323 QualType ValueTy, bool IsIndirect,
324 std::pair<CharUnits, CharUnits> ValueInfo,
325 CharUnits SlotSizeAndAlign,
326 bool AllowHigherAlign) {
327 // The size and alignment of the value that was passed directly.
328 CharUnits DirectSize, DirectAlign;
330 DirectSize = CGF.getPointerSize();
331 DirectAlign = CGF.getPointerAlign();
333 DirectSize = ValueInfo.first;
334 DirectAlign = ValueInfo.second;
337 // Cast the address we've calculated to the right type.
338 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
340 DirectTy = DirectTy->getPointerTo(0);
342 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
343 DirectSize, DirectAlign,
348 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second);
355 static Address emitMergePHI(CodeGenFunction &CGF,
356 Address Addr1, llvm::BasicBlock *Block1,
357 Address Addr2, llvm::BasicBlock *Block2,
358 const llvm::Twine &Name = "") {
359 assert(Addr1.getType() == Addr2.getType());
360 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
361 PHI->addIncoming(Addr1.getPointer(), Block1);
362 PHI->addIncoming(Addr2.getPointer(), Block2);
363 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
364 return Address(PHI, Align);
367 TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
369 // If someone can figure out a general rule for this, that would be great.
370 // It's probably just doomed to be platform-dependent, though.
371 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
373 // x86-64 FreeBSD, Linux, Darwin
374 // x86-32 FreeBSD, Linux, Darwin
375 // PowerPC Linux, Darwin
376 // ARM Darwin (*not* EABI)
381 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
382 const FunctionNoProtoType *fnType) const {
383 // The following conventions are known to require this to be false:
386 // For everything else, we just prefer false unless we opt out.
391 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
392 llvm::SmallString<24> &Opt) const {
393 // This assumes the user is passing a library name like "rt" instead of a
394 // filename like "librt.a/so", and that they don't care whether it's static or
400 unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
401 return llvm::CallingConv::C;
404 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
405 llvm::PointerType *T, QualType QT) const {
406 return llvm::ConstantPointerNull::get(T);
409 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
410 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, unsigned SrcAddr,
411 unsigned DestAddr, llvm::Type *DestTy, bool isNonNull) const {
412 // Since target may map different address spaces in AST to the same address
413 // space, an address space conversion may end up as a bitcast.
414 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DestTy);
417 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
419 /// isEmptyField - Return true iff a the field is "empty", that is it
420 /// is an unnamed bit-field or an (array of) empty record(s).
421 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
423 if (FD->isUnnamedBitfield())
426 QualType FT = FD->getType();
428 // Constant arrays of empty records count as empty, strip them off.
429 // Constant arrays of zero length always count as empty.
431 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
432 if (AT->getSize() == 0)
434 FT = AT->getElementType();
437 const RecordType *RT = FT->getAs<RecordType>();
441 // C++ record fields are never empty, at least in the Itanium ABI.
443 // FIXME: We should use a predicate for whether this behavior is true in the
445 if (isa<CXXRecordDecl>(RT->getDecl()))
448 return isEmptyRecord(Context, FT, AllowArrays);
451 /// isEmptyRecord - Return true iff a structure contains only empty
452 /// fields. Note that a structure with a flexible array member is not
453 /// considered empty.
454 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
455 const RecordType *RT = T->getAs<RecordType>();
458 const RecordDecl *RD = RT->getDecl();
459 if (RD->hasFlexibleArrayMember())
462 // If this is a C++ record, check the bases first.
463 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
464 for (const auto &I : CXXRD->bases())
465 if (!isEmptyRecord(Context, I.getType(), true))
468 for (const auto *I : RD->fields())
469 if (!isEmptyField(Context, I, AllowArrays))
474 /// isSingleElementStruct - Determine if a structure is a "single
475 /// element struct", i.e. it has exactly one non-empty field or
476 /// exactly one field which is itself a single element
477 /// struct. Structures with flexible array members are never
478 /// considered single element structs.
480 /// \return The field declaration for the single non-empty field, if
482 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
483 const RecordType *RT = T->getAs<RecordType>();
487 const RecordDecl *RD = RT->getDecl();
488 if (RD->hasFlexibleArrayMember())
491 const Type *Found = nullptr;
493 // If this is a C++ record, check the bases first.
494 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
495 for (const auto &I : CXXRD->bases()) {
496 // Ignore empty records.
497 if (isEmptyRecord(Context, I.getType(), true))
500 // If we already found an element then this isn't a single-element struct.
504 // If this is non-empty and not a single element struct, the composite
505 // cannot be a single element struct.
506 Found = isSingleElementStruct(I.getType(), Context);
512 // Check for single element.
513 for (const auto *FD : RD->fields()) {
514 QualType FT = FD->getType();
516 // Ignore empty fields.
517 if (isEmptyField(Context, FD, true))
520 // If we already found an element then this isn't a single-element
525 // Treat single element arrays as the element.
526 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
527 if (AT->getSize().getZExtValue() != 1)
529 FT = AT->getElementType();
532 if (!isAggregateTypeForABI(FT)) {
533 Found = FT.getTypePtr();
535 Found = isSingleElementStruct(FT, Context);
541 // We don't consider a struct a single-element struct if it has
542 // padding beyond the element type.
543 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
550 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
551 const ABIArgInfo &AI) {
552 // This default implementation defers to the llvm backend's va_arg
553 // instruction. It can handle only passing arguments directly
554 // (typically only handled in the backend for primitive types), or
555 // aggregates passed indirectly by pointer (NOTE: if the "byval"
556 // flag has ABI impact in the callee, this implementation cannot
559 // Only a few cases are covered here at the moment -- those needed
560 // by the default abi.
563 if (AI.isIndirect()) {
564 assert(!AI.getPaddingType() &&
565 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
567 !AI.getIndirectRealign() &&
568 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
570 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
571 CharUnits TyAlignForABI = TyInfo.second;
574 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
576 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
577 return Address(Addr, TyAlignForABI);
579 assert((AI.isDirect() || AI.isExtend()) &&
580 "Unexpected ArgInfo Kind in generic VAArg emitter!");
582 assert(!AI.getInReg() &&
583 "Unexpected InReg seen in arginfo in generic VAArg emitter!");
584 assert(!AI.getPaddingType() &&
585 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
586 assert(!AI.getDirectOffset() &&
587 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
588 assert(!AI.getCoerceToType() &&
589 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
591 Address Temp = CGF.CreateMemTemp(Ty, "varet");
592 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
593 CGF.Builder.CreateStore(Val, Temp);
598 /// DefaultABIInfo - The default implementation for ABI specific
599 /// details. This implementation provides information which results in
600 /// self-consistent and sensible LLVM IR generation, but does not
601 /// conform to any particular ABI.
602 class DefaultABIInfo : public ABIInfo {
604 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
606 ABIArgInfo classifyReturnType(QualType RetTy) const;
607 ABIArgInfo classifyArgumentType(QualType RetTy) const;
609 void computeInfo(CGFunctionInfo &FI) const override {
610 if (!getCXXABI().classifyReturnType(FI))
611 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
612 for (auto &I : FI.arguments())
613 I.info = classifyArgumentType(I.type);
616 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
617 QualType Ty) const override {
618 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
622 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
624 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
625 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
628 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
629 Ty = useFirstFieldIfTransparentUnion(Ty);
631 if (isAggregateTypeForABI(Ty)) {
632 // Records with non-trivial destructors/copy-constructors should not be
634 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
635 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
637 return getNaturalAlignIndirect(Ty);
640 // Treat an enum type as its underlying type.
641 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
642 Ty = EnumTy->getDecl()->getIntegerType();
644 return (Ty->isPromotableIntegerType() ?
645 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
648 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
649 if (RetTy->isVoidType())
650 return ABIArgInfo::getIgnore();
652 if (isAggregateTypeForABI(RetTy))
653 return getNaturalAlignIndirect(RetTy);
655 // Treat an enum type as its underlying type.
656 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
657 RetTy = EnumTy->getDecl()->getIntegerType();
659 return (RetTy->isPromotableIntegerType() ?
660 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
663 //===----------------------------------------------------------------------===//
664 // WebAssembly ABI Implementation
666 // This is a very simple ABI that relies a lot on DefaultABIInfo.
667 //===----------------------------------------------------------------------===//
669 class WebAssemblyABIInfo final : public DefaultABIInfo {
671 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
672 : DefaultABIInfo(CGT) {}
675 ABIArgInfo classifyReturnType(QualType RetTy) const;
676 ABIArgInfo classifyArgumentType(QualType Ty) const;
678 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
679 // non-virtual, but computeInfo and EmitVAArg are virtual, so we
681 void computeInfo(CGFunctionInfo &FI) const override {
682 if (!getCXXABI().classifyReturnType(FI))
683 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
684 for (auto &Arg : FI.arguments())
685 Arg.info = classifyArgumentType(Arg.type);
688 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
689 QualType Ty) const override;
692 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
694 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
695 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
698 /// \brief Classify argument of given type \p Ty.
699 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
700 Ty = useFirstFieldIfTransparentUnion(Ty);
702 if (isAggregateTypeForABI(Ty)) {
703 // Records with non-trivial destructors/copy-constructors should not be
705 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
706 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
707 // Ignore empty structs/unions.
708 if (isEmptyRecord(getContext(), Ty, true))
709 return ABIArgInfo::getIgnore();
710 // Lower single-element structs to just pass a regular value. TODO: We
711 // could do reasonable-size multiple-element structs too, using getExpand(),
712 // though watch out for things like bitfields.
713 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
714 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
717 // Otherwise just do the default thing.
718 return DefaultABIInfo::classifyArgumentType(Ty);
721 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
722 if (isAggregateTypeForABI(RetTy)) {
723 // Records with non-trivial destructors/copy-constructors should not be
724 // returned by value.
725 if (!getRecordArgABI(RetTy, getCXXABI())) {
726 // Ignore empty structs/unions.
727 if (isEmptyRecord(getContext(), RetTy, true))
728 return ABIArgInfo::getIgnore();
729 // Lower single-element structs to just return a regular value. TODO: We
730 // could do reasonable-size multiple-element structs too, using
731 // ABIArgInfo::getDirect().
732 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
733 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
737 // Otherwise just do the default thing.
738 return DefaultABIInfo::classifyReturnType(RetTy);
741 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
743 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect=*/ false,
744 getContext().getTypeInfoInChars(Ty),
745 CharUnits::fromQuantity(4),
746 /*AllowHigherAlign=*/ true);
749 //===----------------------------------------------------------------------===//
750 // le32/PNaCl bitcode ABI Implementation
752 // This is a simplified version of the x86_32 ABI. Arguments and return values
753 // are always passed on the stack.
754 //===----------------------------------------------------------------------===//
756 class PNaClABIInfo : public ABIInfo {
758 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
760 ABIArgInfo classifyReturnType(QualType RetTy) const;
761 ABIArgInfo classifyArgumentType(QualType RetTy) const;
763 void computeInfo(CGFunctionInfo &FI) const override;
764 Address EmitVAArg(CodeGenFunction &CGF,
765 Address VAListAddr, QualType Ty) const override;
768 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
770 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
771 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
774 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
775 if (!getCXXABI().classifyReturnType(FI))
776 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
778 for (auto &I : FI.arguments())
779 I.info = classifyArgumentType(I.type);
782 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
784 // The PNaCL ABI is a bit odd, in that varargs don't use normal
785 // function classification. Structs get passed directly for varargs
786 // functions, through a rewriting transform in
787 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
788 // this target to actually support a va_arg instructions with an
789 // aggregate type, unlike other targets.
790 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
793 /// \brief Classify argument of given type \p Ty.
794 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
795 if (isAggregateTypeForABI(Ty)) {
796 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
797 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
798 return getNaturalAlignIndirect(Ty);
799 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
800 // Treat an enum type as its underlying type.
801 Ty = EnumTy->getDecl()->getIntegerType();
802 } else if (Ty->isFloatingType()) {
803 // Floating-point types don't go inreg.
804 return ABIArgInfo::getDirect();
807 return (Ty->isPromotableIntegerType() ?
808 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
811 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
812 if (RetTy->isVoidType())
813 return ABIArgInfo::getIgnore();
815 // In the PNaCl ABI we always return records/structures on the stack.
816 if (isAggregateTypeForABI(RetTy))
817 return getNaturalAlignIndirect(RetTy);
819 // Treat an enum type as its underlying type.
820 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
821 RetTy = EnumTy->getDecl()->getIntegerType();
823 return (RetTy->isPromotableIntegerType() ?
824 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
827 /// IsX86_MMXType - Return true if this is an MMX type.
828 bool IsX86_MMXType(llvm::Type *IRType) {
829 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
830 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
831 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
832 IRType->getScalarSizeInBits() != 64;
835 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
836 StringRef Constraint,
838 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
839 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
840 // Invalid MMX constraint
844 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
847 // No operation needed
851 /// Returns true if this type can be passed in SSE registers with the
852 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
853 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
854 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
855 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
857 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
858 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
859 // registers specially.
860 unsigned VecSize = Context.getTypeSize(VT);
861 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
867 /// Returns true if this aggregate is small enough to be passed in SSE registers
868 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
869 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
870 return NumMembers <= 4;
873 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
874 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
875 auto AI = ABIArgInfo::getDirect(T);
877 AI.setCanBeFlattened(false);
881 //===----------------------------------------------------------------------===//
882 // X86-32 ABI Implementation
883 //===----------------------------------------------------------------------===//
885 /// \brief Similar to llvm::CCState, but for Clang.
887 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
891 unsigned FreeSSERegs;
895 // Vectorcall only allows the first 6 parameters to be passed in registers.
896 VectorcallMaxParamNumAsReg = 6
899 /// X86_32ABIInfo - The X86-32 ABI information.
900 class X86_32ABIInfo : public SwiftABIInfo {
906 static const unsigned MinABIStackAlignInBytes = 4;
908 bool IsDarwinVectorABI;
909 bool IsRetSmallStructInRegABI;
910 bool IsWin32StructABI;
913 unsigned DefaultNumRegisterParameters;
915 static bool isRegisterSize(unsigned Size) {
916 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
919 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
920 // FIXME: Assumes vectorcall is in use.
921 return isX86VectorTypeForVectorCall(getContext(), Ty);
924 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
925 uint64_t NumMembers) const override {
926 // FIXME: Assumes vectorcall is in use.
927 return isX86VectorCallAggregateSmallEnough(NumMembers);
930 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
932 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
933 /// such that the argument will be passed in memory.
934 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
936 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
938 /// \brief Return the alignment to use for the given type on the stack.
939 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
941 Class classify(QualType Ty) const;
942 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
943 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
944 ABIArgInfo reclassifyHvaArgType(QualType RetTy, CCState &State,
945 const ABIArgInfo& current) const;
946 /// \brief Updates the number of available free registers, returns
947 /// true if any registers were allocated.
948 bool updateFreeRegs(QualType Ty, CCState &State) const;
950 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
951 bool &NeedsPadding) const;
952 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
954 bool canExpandIndirectArgument(QualType Ty) const;
956 /// \brief Rewrite the function info so that all memory arguments use
958 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
960 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
961 CharUnits &StackOffset, ABIArgInfo &Info,
962 QualType Type) const;
963 void computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
964 bool &UsedInAlloca) const;
968 void computeInfo(CGFunctionInfo &FI) const override;
969 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
970 QualType Ty) const override;
972 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
973 bool RetSmallStructInRegABI, bool Win32StructABI,
974 unsigned NumRegisterParameters, bool SoftFloatABI)
975 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
976 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
977 IsWin32StructABI(Win32StructABI),
978 IsSoftFloatABI(SoftFloatABI),
979 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
980 DefaultNumRegisterParameters(NumRegisterParameters) {}
982 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
983 ArrayRef<llvm::Type*> scalars,
984 bool asReturnValue) const override {
985 // LLVM's x86-32 lowering currently only assigns up to three
986 // integer registers and three fp registers. Oddly, it'll use up to
987 // four vector registers for vectors, but those can overlap with the
989 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
992 bool isSwiftErrorInRegister() const override {
993 // x86-32 lowering does not support passing swifterror in a register.
998 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1000 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1001 bool RetSmallStructInRegABI, bool Win32StructABI,
1002 unsigned NumRegisterParameters, bool SoftFloatABI)
1003 : TargetCodeGenInfo(new X86_32ABIInfo(
1004 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1005 NumRegisterParameters, SoftFloatABI)) {}
1007 static bool isStructReturnInRegABI(
1008 const llvm::Triple &Triple, const CodeGenOptions &Opts);
1010 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1011 CodeGen::CodeGenModule &CGM) const override;
1013 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1014 // Darwin uses different dwarf register numbers for EH.
1015 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
1019 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1020 llvm::Value *Address) const override;
1022 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1023 StringRef Constraint,
1024 llvm::Type* Ty) const override {
1025 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1028 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1029 std::string &Constraints,
1030 std::vector<llvm::Type *> &ResultRegTypes,
1031 std::vector<llvm::Type *> &ResultTruncRegTypes,
1032 std::vector<LValue> &ResultRegDests,
1033 std::string &AsmString,
1034 unsigned NumOutputs) const override;
1037 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
1038 unsigned Sig = (0xeb << 0) | // jmp rel8
1039 (0x06 << 8) | // .+0x08
1042 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1045 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1046 return "movl\t%ebp, %ebp"
1047 "\t\t## marker for objc_retainAutoreleaseReturnValue";
1053 /// Rewrite input constraint references after adding some output constraints.
1054 /// In the case where there is one output and one input and we add one output,
1055 /// we need to replace all operand references greater than or equal to 1:
1058 /// The result will be:
1061 static void rewriteInputConstraintReferences(unsigned FirstIn,
1062 unsigned NumNewOuts,
1063 std::string &AsmString) {
1065 llvm::raw_string_ostream OS(Buf);
1067 while (Pos < AsmString.size()) {
1068 size_t DollarStart = AsmString.find('$', Pos);
1069 if (DollarStart == std::string::npos)
1070 DollarStart = AsmString.size();
1071 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1072 if (DollarEnd == std::string::npos)
1073 DollarEnd = AsmString.size();
1074 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1076 size_t NumDollars = DollarEnd - DollarStart;
1077 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1078 // We have an operand reference.
1079 size_t DigitStart = Pos;
1080 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1081 if (DigitEnd == std::string::npos)
1082 DigitEnd = AsmString.size();
1083 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1084 unsigned OperandIndex;
1085 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1086 if (OperandIndex >= FirstIn)
1087 OperandIndex += NumNewOuts;
1095 AsmString = std::move(OS.str());
1098 /// Add output constraints for EAX:EDX because they are return registers.
1099 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1100 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1101 std::vector<llvm::Type *> &ResultRegTypes,
1102 std::vector<llvm::Type *> &ResultTruncRegTypes,
1103 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1104 unsigned NumOutputs) const {
1105 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1107 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1109 if (!Constraints.empty())
1111 if (RetWidth <= 32) {
1112 Constraints += "={eax}";
1113 ResultRegTypes.push_back(CGF.Int32Ty);
1115 // Use the 'A' constraint for EAX:EDX.
1116 Constraints += "=A";
1117 ResultRegTypes.push_back(CGF.Int64Ty);
1120 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1121 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1122 ResultTruncRegTypes.push_back(CoerceTy);
1124 // Coerce the integer by bitcasting the return slot pointer.
1125 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1126 CoerceTy->getPointerTo()));
1127 ResultRegDests.push_back(ReturnSlot);
1129 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1132 /// shouldReturnTypeInRegister - Determine if the given type should be
1133 /// returned in a register (for the Darwin and MCU ABI).
1134 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1135 ASTContext &Context) const {
1136 uint64_t Size = Context.getTypeSize(Ty);
1138 // For i386, type must be register sized.
1139 // For the MCU ABI, it only needs to be <= 8-byte
1140 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1143 if (Ty->isVectorType()) {
1144 // 64- and 128- bit vectors inside structures are not returned in
1146 if (Size == 64 || Size == 128)
1152 // If this is a builtin, pointer, enum, complex type, member pointer, or
1153 // member function pointer it is ok.
1154 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
1155 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
1156 Ty->isBlockPointerType() || Ty->isMemberPointerType())
1159 // Arrays are treated like records.
1160 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
1161 return shouldReturnTypeInRegister(AT->getElementType(), Context);
1163 // Otherwise, it must be a record type.
1164 const RecordType *RT = Ty->getAs<RecordType>();
1165 if (!RT) return false;
1167 // FIXME: Traverse bases here too.
1169 // Structure types are passed in register if all fields would be
1170 // passed in a register.
1171 for (const auto *FD : RT->getDecl()->fields()) {
1172 // Empty fields are ignored.
1173 if (isEmptyField(Context, FD, true))
1176 // Check fields recursively.
1177 if (!shouldReturnTypeInRegister(FD->getType(), Context))
1183 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1184 // Treat complex types as the element type.
1185 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1186 Ty = CTy->getElementType();
1188 // Check for a type which we know has a simple scalar argument-passing
1189 // convention without any padding. (We're specifically looking for 32
1190 // and 64-bit integer and integer-equivalents, float, and double.)
1191 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1192 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1195 uint64_t Size = Context.getTypeSize(Ty);
1196 return Size == 32 || Size == 64;
1199 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1201 for (const auto *FD : RD->fields()) {
1202 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1203 // argument is smaller than 32-bits, expanding the struct will create
1204 // alignment padding.
1205 if (!is32Or64BitBasicType(FD->getType(), Context))
1208 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1209 // how to expand them yet, and the predicate for telling if a bitfield still
1210 // counts as "basic" is more complicated than what we were doing previously.
1211 if (FD->isBitField())
1214 Size += Context.getTypeSize(FD->getType());
1219 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1221 // Don't do this if there are any non-empty bases.
1222 for (const CXXBaseSpecifier &Base : RD->bases()) {
1223 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1227 if (!addFieldSizes(Context, RD, Size))
1232 /// Test whether an argument type which is to be passed indirectly (on the
1233 /// stack) would have the equivalent layout if it was expanded into separate
1234 /// arguments. If so, we prefer to do the latter to avoid inhibiting
1236 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1237 // We can only expand structure types.
1238 const RecordType *RT = Ty->getAs<RecordType>();
1241 const RecordDecl *RD = RT->getDecl();
1243 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1244 if (!IsWin32StructABI) {
1245 // On non-Windows, we have to conservatively match our old bitcode
1246 // prototypes in order to be ABI-compatible at the bitcode level.
1247 if (!CXXRD->isCLike())
1250 // Don't do this for dynamic classes.
1251 if (CXXRD->isDynamicClass())
1254 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
1257 if (!addFieldSizes(getContext(), RD, Size))
1261 // We can do this if there was no alignment padding.
1262 return Size == getContext().getTypeSize(Ty);
1265 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
1266 // If the return value is indirect, then the hidden argument is consuming one
1267 // integer register.
1268 if (State.FreeRegs) {
1271 return getNaturalAlignIndirectInReg(RetTy);
1273 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
1276 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1277 CCState &State) const {
1278 if (RetTy->isVoidType())
1279 return ABIArgInfo::getIgnore();
1281 const Type *Base = nullptr;
1282 uint64_t NumElts = 0;
1283 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1284 State.CC == llvm::CallingConv::X86_RegCall) &&
1285 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1286 // The LLVM struct type for such an aggregate should lower properly.
1287 return ABIArgInfo::getDirect();
1290 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
1291 // On Darwin, some vectors are returned in registers.
1292 if (IsDarwinVectorABI) {
1293 uint64_t Size = getContext().getTypeSize(RetTy);
1295 // 128-bit vectors are a special case; they are returned in
1296 // registers and we need to make sure to pick a type the LLVM
1297 // backend will like.
1299 return ABIArgInfo::getDirect(llvm::VectorType::get(
1300 llvm::Type::getInt64Ty(getVMContext()), 2));
1302 // Always return in register if it fits in a general purpose
1303 // register, or if it is 64 bits and has a single element.
1304 if ((Size == 8 || Size == 16 || Size == 32) ||
1305 (Size == 64 && VT->getNumElements() == 1))
1306 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1309 return getIndirectReturnResult(RetTy, State);
1312 return ABIArgInfo::getDirect();
1315 if (isAggregateTypeForABI(RetTy)) {
1316 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
1317 // Structures with flexible arrays are always indirect.
1318 if (RT->getDecl()->hasFlexibleArrayMember())
1319 return getIndirectReturnResult(RetTy, State);
1322 // If specified, structs and unions are always indirect.
1323 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
1324 return getIndirectReturnResult(RetTy, State);
1326 // Ignore empty structs/unions.
1327 if (isEmptyRecord(getContext(), RetTy, true))
1328 return ABIArgInfo::getIgnore();
1330 // Small structures which are register sized are generally returned
1332 if (shouldReturnTypeInRegister(RetTy, getContext())) {
1333 uint64_t Size = getContext().getTypeSize(RetTy);
1335 // As a special-case, if the struct is a "single-element" struct, and
1336 // the field is of type "float" or "double", return it in a
1337 // floating-point register. (MSVC does not apply this special case.)
1338 // We apply a similar transformation for pointer types to improve the
1339 // quality of the generated IR.
1340 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
1341 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
1342 || SeltTy->hasPointerRepresentation())
1343 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1345 // FIXME: We should be able to narrow this integer in cases with dead
1347 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
1350 return getIndirectReturnResult(RetTy, State);
1353 // Treat an enum type as its underlying type.
1354 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1355 RetTy = EnumTy->getDecl()->getIntegerType();
1357 return (RetTy->isPromotableIntegerType() ?
1358 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1361 static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1362 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1365 static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1366 const RecordType *RT = Ty->getAs<RecordType>();
1369 const RecordDecl *RD = RT->getDecl();
1371 // If this is a C++ record, check the bases first.
1372 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1373 for (const auto &I : CXXRD->bases())
1374 if (!isRecordWithSSEVectorType(Context, I.getType()))
1377 for (const auto *i : RD->fields()) {
1378 QualType FT = i->getType();
1380 if (isSSEVectorType(Context, FT))
1383 if (isRecordWithSSEVectorType(Context, FT))
1390 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1391 unsigned Align) const {
1392 // Otherwise, if the alignment is less than or equal to the minimum ABI
1393 // alignment, just use the default; the backend will handle this.
1394 if (Align <= MinABIStackAlignInBytes)
1395 return 0; // Use default alignment.
1397 // On non-Darwin, the stack type alignment is always 4.
1398 if (!IsDarwinVectorABI) {
1399 // Set explicit alignment, since we may need to realign the top.
1400 return MinABIStackAlignInBytes;
1403 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
1404 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1405 isRecordWithSSEVectorType(getContext(), Ty)))
1408 return MinABIStackAlignInBytes;
1411 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
1412 CCState &State) const {
1414 if (State.FreeRegs) {
1415 --State.FreeRegs; // Non-byval indirects just use one pointer.
1417 return getNaturalAlignIndirectInReg(Ty);
1419 return getNaturalAlignIndirect(Ty, false);
1422 // Compute the byval alignment.
1423 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1424 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1425 if (StackAlign == 0)
1426 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
1428 // If the stack alignment is less than the type alignment, realign the
1430 bool Realign = TypeAlign > StackAlign;
1431 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1432 /*ByVal=*/true, Realign);
1435 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1436 const Type *T = isSingleElementStruct(Ty, getContext());
1438 T = Ty.getTypePtr();
1440 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1441 BuiltinType::Kind K = BT->getKind();
1442 if (K == BuiltinType::Float || K == BuiltinType::Double)
1448 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
1449 if (!IsSoftFloatABI) {
1450 Class C = classify(Ty);
1455 unsigned Size = getContext().getTypeSize(Ty);
1456 unsigned SizeInRegs = (Size + 31) / 32;
1458 if (SizeInRegs == 0)
1462 if (SizeInRegs > State.FreeRegs) {
1467 // The MCU psABI allows passing parameters in-reg even if there are
1468 // earlier parameters that are passed on the stack. Also,
1469 // it does not allow passing >8-byte structs in-register,
1470 // even if there are 3 free registers available.
1471 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1475 State.FreeRegs -= SizeInRegs;
1479 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1481 bool &NeedsPadding) const {
1482 // On Windows, aggregates other than HFAs are never passed in registers, and
1483 // they do not consume register slots. Homogenous floating-point aggregates
1484 // (HFAs) have already been dealt with at this point.
1485 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1488 NeedsPadding = false;
1491 if (!updateFreeRegs(Ty, State))
1497 if (State.CC == llvm::CallingConv::X86_FastCall ||
1498 State.CC == llvm::CallingConv::X86_VectorCall ||
1499 State.CC == llvm::CallingConv::X86_RegCall) {
1500 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
1501 NeedsPadding = true;
1509 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1510 if (!updateFreeRegs(Ty, State))
1516 if (State.CC == llvm::CallingConv::X86_FastCall ||
1517 State.CC == llvm::CallingConv::X86_VectorCall ||
1518 State.CC == llvm::CallingConv::X86_RegCall) {
1519 if (getContext().getTypeSize(Ty) > 32)
1522 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1523 Ty->isReferenceType());
1530 X86_32ABIInfo::reclassifyHvaArgType(QualType Ty, CCState &State,
1531 const ABIArgInfo ¤t) const {
1532 // Assumes vectorCall calling convention.
1533 const Type *Base = nullptr;
1534 uint64_t NumElts = 0;
1536 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
1537 isHomogeneousAggregate(Ty, Base, NumElts)) {
1538 if (State.FreeSSERegs >= NumElts) {
1539 // HVA types get passed directly in registers if there is room.
1540 State.FreeSSERegs -= NumElts;
1541 return getDirectX86Hva();
1543 // If there's no room, the HVA gets passed as normal indirect
1545 return getIndirectResult(Ty, /*ByVal=*/false, State);
1550 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1551 CCState &State) const {
1552 // FIXME: Set alignment on indirect arguments.
1554 Ty = useFirstFieldIfTransparentUnion(Ty);
1556 // Check with the C++ ABI first.
1557 const RecordType *RT = Ty->getAs<RecordType>();
1559 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1560 if (RAA == CGCXXABI::RAA_Indirect) {
1561 return getIndirectResult(Ty, false, State);
1562 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1563 // The field index doesn't matter, we'll fix it up later.
1564 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1568 // vectorcall adds the concept of a homogenous vector aggregate, similar
1569 // to other targets, regcall uses some of the HVA rules.
1570 const Type *Base = nullptr;
1571 uint64_t NumElts = 0;
1572 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1573 State.CC == llvm::CallingConv::X86_RegCall) &&
1574 isHomogeneousAggregate(Ty, Base, NumElts)) {
1576 if (State.CC == llvm::CallingConv::X86_RegCall) {
1577 if (State.FreeSSERegs >= NumElts) {
1578 State.FreeSSERegs -= NumElts;
1579 if (Ty->isBuiltinType() || Ty->isVectorType())
1580 return ABIArgInfo::getDirect();
1581 return ABIArgInfo::getExpand();
1584 return getIndirectResult(Ty, /*ByVal=*/false, State);
1585 } else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1586 if (State.FreeSSERegs >= NumElts && (Ty->isBuiltinType() || Ty->isVectorType())) {
1587 // Actual floating-point types get registers first time through if
1588 // there is registers available
1589 State.FreeSSERegs -= NumElts;
1590 return ABIArgInfo::getDirect();
1591 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
1592 // HVA Types only get registers after everything else has been
1593 // set, so it gets set as indirect for now.
1594 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty));
1599 if (isAggregateTypeForABI(Ty)) {
1600 // Structures with flexible arrays are always indirect.
1601 // FIXME: This should not be byval!
1602 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1603 return getIndirectResult(Ty, true, State);
1605 // Ignore empty structs/unions on non-Windows.
1606 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
1607 return ABIArgInfo::getIgnore();
1609 llvm::LLVMContext &LLVMContext = getVMContext();
1610 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1611 bool NeedsPadding = false;
1613 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
1614 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
1615 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
1616 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1618 return ABIArgInfo::getDirectInReg(Result);
1620 return ABIArgInfo::getDirect(Result);
1622 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
1624 // Expand small (<= 128-bit) record types when we know that the stack layout
1625 // of those arguments will match the struct. This is important because the
1626 // LLVM backend isn't smart enough to remove byval, which inhibits many
1628 // Don't do this for the MCU if there are still free integer registers
1629 // (see X86_64 ABI for full explanation).
1630 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1631 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
1632 return ABIArgInfo::getExpandWithPadding(
1633 State.CC == llvm::CallingConv::X86_FastCall ||
1634 State.CC == llvm::CallingConv::X86_VectorCall ||
1635 State.CC == llvm::CallingConv::X86_RegCall,
1638 return getIndirectResult(Ty, true, State);
1641 if (const VectorType *VT = Ty->getAs<VectorType>()) {
1642 // On Darwin, some vectors are passed in memory, we handle this by passing
1643 // it as an i8/i16/i32/i64.
1644 if (IsDarwinVectorABI) {
1645 uint64_t Size = getContext().getTypeSize(Ty);
1646 if ((Size == 8 || Size == 16 || Size == 32) ||
1647 (Size == 64 && VT->getNumElements() == 1))
1648 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1652 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1653 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
1655 return ABIArgInfo::getDirect();
1659 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1660 Ty = EnumTy->getDecl()->getIntegerType();
1662 bool InReg = shouldPrimitiveUseInReg(Ty, State);
1664 if (Ty->isPromotableIntegerType()) {
1666 return ABIArgInfo::getExtendInReg();
1667 return ABIArgInfo::getExtend();
1671 return ABIArgInfo::getDirectInReg();
1672 return ABIArgInfo::getDirect();
1675 void X86_32ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1676 bool &UsedInAlloca) const {
1677 // Vectorcall only allows the first 6 parameters to be passed in registers,
1678 // and homogeneous vector aggregates are only put into registers as a second
1681 CCState ZeroState = State;
1682 ZeroState.FreeRegs = ZeroState.FreeSSERegs = 0;
1683 // HVAs must be done as a second priority for registers, so the deferred
1684 // items are dealt with by going through the pattern a second time.
1685 for (auto &I : FI.arguments()) {
1686 if (Count < VectorcallMaxParamNumAsReg)
1687 I.info = classifyArgumentType(I.type, State);
1689 // Parameters after the 6th cannot be passed in registers,
1690 // so pretend there are no registers left for them.
1691 I.info = classifyArgumentType(I.type, ZeroState);
1692 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1696 // Go through the arguments a second time to get HVAs registers if there
1697 // are still some available.
1698 for (auto &I : FI.arguments()) {
1699 if (Count < VectorcallMaxParamNumAsReg)
1700 I.info = reclassifyHvaArgType(I.type, State, I.info);
1705 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
1706 CCState State(FI.getCallingConvention());
1709 else if (State.CC == llvm::CallingConv::X86_FastCall)
1711 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1713 State.FreeSSERegs = 6;
1714 } else if (FI.getHasRegParm())
1715 State.FreeRegs = FI.getRegParm();
1716 else if (State.CC == llvm::CallingConv::X86_RegCall) {
1718 State.FreeSSERegs = 8;
1720 State.FreeRegs = DefaultNumRegisterParameters;
1722 if (!getCXXABI().classifyReturnType(FI)) {
1723 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
1724 } else if (FI.getReturnInfo().isIndirect()) {
1725 // The C++ ABI is not aware of register usage, so we have to check if the
1726 // return value was sret and put it in a register ourselves if appropriate.
1727 if (State.FreeRegs) {
1728 --State.FreeRegs; // The sret parameter consumes a register.
1730 FI.getReturnInfo().setInReg(true);
1734 // The chain argument effectively gives us another free register.
1735 if (FI.isChainCall())
1738 bool UsedInAlloca = false;
1739 if (State.CC == llvm::CallingConv::X86_VectorCall) {
1740 computeVectorCallArgs(FI, State, UsedInAlloca);
1742 // If not vectorcall, revert to normal behavior.
1743 for (auto &I : FI.arguments()) {
1744 I.info = classifyArgumentType(I.type, State);
1745 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1749 // If we needed to use inalloca for any argument, do a second pass and rewrite
1750 // all the memory arguments to use inalloca.
1752 rewriteWithInAlloca(FI);
1756 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1757 CharUnits &StackOffset, ABIArgInfo &Info,
1758 QualType Type) const {
1759 // Arguments are always 4-byte-aligned.
1760 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1762 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
1763 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1764 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
1765 StackOffset += getContext().getTypeSizeInChars(Type);
1767 // Insert padding bytes to respect alignment.
1768 CharUnits FieldEnd = StackOffset;
1769 StackOffset = FieldEnd.alignTo(FieldAlign);
1770 if (StackOffset != FieldEnd) {
1771 CharUnits NumBytes = StackOffset - FieldEnd;
1772 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1773 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
1774 FrameFields.push_back(Ty);
1778 static bool isArgInAlloca(const ABIArgInfo &Info) {
1779 // Leave ignored and inreg arguments alone.
1780 switch (Info.getKind()) {
1781 case ABIArgInfo::InAlloca:
1783 case ABIArgInfo::Indirect:
1784 assert(Info.getIndirectByVal());
1786 case ABIArgInfo::Ignore:
1788 case ABIArgInfo::Direct:
1789 case ABIArgInfo::Extend:
1790 if (Info.getInReg())
1793 case ABIArgInfo::Expand:
1794 case ABIArgInfo::CoerceAndExpand:
1795 // These are aggregate types which are never passed in registers when
1796 // inalloca is involved.
1799 llvm_unreachable("invalid enum");
1802 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1803 assert(IsWin32StructABI && "inalloca only supported on win32");
1805 // Build a packed struct type for all of the arguments in memory.
1806 SmallVector<llvm::Type *, 6> FrameFields;
1808 // The stack alignment is always 4.
1809 CharUnits StackAlign = CharUnits::fromQuantity(4);
1811 CharUnits StackOffset;
1812 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1814 // Put 'this' into the struct before 'sret', if necessary.
1816 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1817 ABIArgInfo &Ret = FI.getReturnInfo();
1818 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1819 isArgInAlloca(I->info)) {
1820 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1824 // Put the sret parameter into the inalloca struct if it's in memory.
1825 if (Ret.isIndirect() && !Ret.getInReg()) {
1826 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1827 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
1828 // On Windows, the hidden sret parameter is always returned in eax.
1829 Ret.setInAllocaSRet(IsWin32StructABI);
1832 // Skip the 'this' parameter in ecx.
1836 // Put arguments passed in memory into the struct.
1837 for (; I != E; ++I) {
1838 if (isArgInAlloca(I->info))
1839 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1842 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1847 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1848 Address VAListAddr, QualType Ty) const {
1850 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
1852 // x86-32 changes the alignment of certain arguments on the stack.
1854 // Just messing with TypeInfo like this works because we never pass
1855 // anything indirectly.
1856 TypeInfo.second = CharUnits::fromQuantity(
1857 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
1859 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1860 TypeInfo, CharUnits::fromQuantity(4),
1861 /*AllowHigherAlign*/ true);
1864 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1865 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1866 assert(Triple.getArch() == llvm::Triple::x86);
1868 switch (Opts.getStructReturnConvention()) {
1869 case CodeGenOptions::SRCK_Default:
1871 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1873 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1877 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
1880 switch (Triple.getOS()) {
1881 case llvm::Triple::DragonFly:
1882 case llvm::Triple::FreeBSD:
1883 case llvm::Triple::OpenBSD:
1884 case llvm::Triple::Bitrig:
1885 case llvm::Triple::Win32:
1892 void X86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
1893 llvm::GlobalValue *GV,
1894 CodeGen::CodeGenModule &CGM) const {
1895 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
1896 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1897 // Get the LLVM function.
1898 llvm::Function *Fn = cast<llvm::Function>(GV);
1900 // Now add the 'alignstack' attribute with a value of 16.
1901 llvm::AttrBuilder B;
1902 B.addStackAlignmentAttr(16);
1903 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
1905 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1906 llvm::Function *Fn = cast<llvm::Function>(GV);
1907 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1912 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1913 CodeGen::CodeGenFunction &CGF,
1914 llvm::Value *Address) const {
1915 CodeGen::CGBuilderTy &Builder = CGF.Builder;
1917 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
1919 // 0-7 are the eight integer registers; the order is different
1920 // on Darwin (for EH), but the range is the same.
1922 AssignToArrayRange(Builder, Address, Four8, 0, 8);
1924 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
1925 // 12-16 are st(0..4). Not sure why we stop at 4.
1926 // These have size 16, which is sizeof(long double) on
1927 // platforms with 8-byte alignment for that type.
1928 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
1929 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
1932 // 9 is %eflags, which doesn't get a size on Darwin for some
1934 Builder.CreateAlignedStore(
1935 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1938 // 11-16 are st(0..5). Not sure why we stop at 5.
1939 // These have size 12, which is sizeof(long double) on
1940 // platforms with 4-byte alignment for that type.
1941 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
1942 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1948 //===----------------------------------------------------------------------===//
1949 // X86-64 ABI Implementation
1950 //===----------------------------------------------------------------------===//
1954 /// The AVX ABI level for X86 targets.
1955 enum class X86AVXABILevel {
1961 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1962 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1964 case X86AVXABILevel::AVX512:
1966 case X86AVXABILevel::AVX:
1968 case X86AVXABILevel::None:
1971 llvm_unreachable("Unknown AVXLevel");
1974 /// X86_64ABIInfo - The X86_64 ABI information.
1975 class X86_64ABIInfo : public SwiftABIInfo {
1987 /// merge - Implement the X86_64 ABI merging algorithm.
1989 /// Merge an accumulating classification \arg Accum with a field
1990 /// classification \arg Field.
1992 /// \param Accum - The accumulating classification. This should
1993 /// always be either NoClass or the result of a previous merge
1994 /// call. In addition, this should never be Memory (the caller
1995 /// should just return Memory for the aggregate).
1996 static Class merge(Class Accum, Class Field);
1998 /// postMerge - Implement the X86_64 ABI post merging algorithm.
2000 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2001 /// final MEMORY or SSE classes when necessary.
2003 /// \param AggregateSize - The size of the current aggregate in
2004 /// the classification process.
2006 /// \param Lo - The classification for the parts of the type
2007 /// residing in the low word of the containing object.
2009 /// \param Hi - The classification for the parts of the type
2010 /// residing in the higher words of the containing object.
2012 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2014 /// classify - Determine the x86_64 register classes in which the
2015 /// given type T should be passed.
2017 /// \param Lo - The classification for the parts of the type
2018 /// residing in the low word of the containing object.
2020 /// \param Hi - The classification for the parts of the type
2021 /// residing in the high word of the containing object.
2023 /// \param OffsetBase - The bit offset of this type in the
2024 /// containing object. Some parameters are classified different
2025 /// depending on whether they straddle an eightbyte boundary.
2027 /// \param isNamedArg - Whether the argument in question is a "named"
2028 /// argument, as used in AMD64-ABI 3.5.7.
2030 /// If a word is unused its result will be NoClass; if a type should
2031 /// be passed in Memory then at least the classification of \arg Lo
2034 /// The \arg Lo class will be NoClass iff the argument is ignored.
2036 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2037 /// also be ComplexX87.
2038 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2039 bool isNamedArg) const;
2041 llvm::Type *GetByteVectorType(QualType Ty) const;
2042 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2043 unsigned IROffset, QualType SourceTy,
2044 unsigned SourceOffset) const;
2045 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2046 unsigned IROffset, QualType SourceTy,
2047 unsigned SourceOffset) const;
2049 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2050 /// such that the argument will be returned in memory.
2051 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
2053 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2054 /// such that the argument will be passed in memory.
2056 /// \param freeIntRegs - The number of free integer registers remaining
2058 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
2060 ABIArgInfo classifyReturnType(QualType RetTy) const;
2062 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2063 unsigned &neededInt, unsigned &neededSSE,
2064 bool isNamedArg) const;
2066 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2067 unsigned &NeededSSE) const;
2069 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2070 unsigned &NeededSSE) const;
2072 bool IsIllegalVectorType(QualType Ty) const;
2074 /// The 0.98 ABI revision clarified a lot of ambiguities,
2075 /// unfortunately in ways that were not always consistent with
2076 /// certain previous compilers. In particular, platforms which
2077 /// required strict binary compatibility with older versions of GCC
2078 /// may need to exempt themselves.
2079 bool honorsRevision0_98() const {
2080 return !getTarget().getTriple().isOSDarwin();
2083 /// GCC classifies <1 x long long> as SSE but compatibility with older clang
2084 // compilers require us to classify it as INTEGER.
2085 bool classifyIntegerMMXAsSSE() const {
2086 const llvm::Triple &Triple = getTarget().getTriple();
2087 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2089 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2094 X86AVXABILevel AVXLevel;
2095 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2097 bool Has64BitPointers;
2100 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
2101 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2102 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
2105 bool isPassedUsingAVXType(QualType type) const {
2106 unsigned neededInt, neededSSE;
2107 // The freeIntRegs argument doesn't matter here.
2108 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2109 /*isNamedArg*/true);
2110 if (info.isDirect()) {
2111 llvm::Type *ty = info.getCoerceToType();
2112 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2113 return (vectorTy->getBitWidth() > 128);
2118 void computeInfo(CGFunctionInfo &FI) const override;
2120 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2121 QualType Ty) const override;
2122 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2123 QualType Ty) const override;
2125 bool has64BitPointers() const {
2126 return Has64BitPointers;
2129 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
2130 ArrayRef<llvm::Type*> scalars,
2131 bool asReturnValue) const override {
2132 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2134 bool isSwiftErrorInRegister() const override {
2139 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
2140 class WinX86_64ABIInfo : public SwiftABIInfo {
2142 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
2143 : SwiftABIInfo(CGT),
2144 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
2146 void computeInfo(CGFunctionInfo &FI) const override;
2148 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2149 QualType Ty) const override;
2151 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2152 // FIXME: Assumes vectorcall is in use.
2153 return isX86VectorTypeForVectorCall(getContext(), Ty);
2156 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2157 uint64_t NumMembers) const override {
2158 // FIXME: Assumes vectorcall is in use.
2159 return isX86VectorCallAggregateSmallEnough(NumMembers);
2162 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
2163 ArrayRef<llvm::Type *> scalars,
2164 bool asReturnValue) const override {
2165 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2168 bool isSwiftErrorInRegister() const override {
2173 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2174 bool IsVectorCall, bool IsRegCall) const;
2175 ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
2176 const ABIArgInfo ¤t) const;
2177 void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs,
2178 bool IsVectorCall, bool IsRegCall) const;
2183 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2185 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2186 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
2188 const X86_64ABIInfo &getABIInfo() const {
2189 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2192 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2196 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2197 llvm::Value *Address) const override {
2198 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2200 // 0-15 are the 16 integer registers.
2202 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2206 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
2207 StringRef Constraint,
2208 llvm::Type* Ty) const override {
2209 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2212 bool isNoProtoCallVariadic(const CallArgList &args,
2213 const FunctionNoProtoType *fnType) const override {
2214 // The default CC on x86-64 sets %al to the number of SSA
2215 // registers used, and GCC sets this when calling an unprototyped
2216 // function, so we override the default behavior. However, don't do
2217 // that when AVX types are involved: the ABI explicitly states it is
2218 // undefined, and it doesn't work in practice because of how the ABI
2219 // defines varargs anyway.
2220 if (fnType->getCallConv() == CC_C) {
2221 bool HasAVXType = false;
2222 for (CallArgList::const_iterator
2223 it = args.begin(), ie = args.end(); it != ie; ++it) {
2224 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2234 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
2238 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
2240 if (getABIInfo().has64BitPointers())
2241 Sig = (0xeb << 0) | // jmp rel8
2242 (0x0a << 8) | // .+0x0c
2246 Sig = (0xeb << 0) | // jmp rel8
2247 (0x06 << 8) | // .+0x08
2250 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2253 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2254 CodeGen::CodeGenModule &CGM) const override {
2255 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2256 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2257 llvm::Function *Fn = cast<llvm::Function>(GV);
2258 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2264 class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
2266 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2267 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
2269 void getDependentLibraryOption(llvm::StringRef Lib,
2270 llvm::SmallString<24> &Opt) const override {
2272 // If the argument contains a space, enclose it in quotes.
2273 if (Lib.find(" ") != StringRef::npos)
2274 Opt += "\"" + Lib.str() + "\"";
2280 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
2281 // If the argument does not end in .lib, automatically add the suffix.
2282 // If the argument contains a space, enclose it in quotes.
2283 // This matches the behavior of MSVC.
2284 bool Quote = (Lib.find(" ") != StringRef::npos);
2285 std::string ArgStr = Quote ? "\"" : "";
2287 if (!Lib.endswith_lower(".lib"))
2289 ArgStr += Quote ? "\"" : "";
2293 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2295 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2296 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2297 unsigned NumRegisterParameters)
2298 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
2299 Win32StructABI, NumRegisterParameters, false) {}
2301 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2302 CodeGen::CodeGenModule &CGM) const override;
2304 void getDependentLibraryOption(llvm::StringRef Lib,
2305 llvm::SmallString<24> &Opt) const override {
2306 Opt = "/DEFAULTLIB:";
2307 Opt += qualifyWindowsLibrary(Lib);
2310 void getDetectMismatchOption(llvm::StringRef Name,
2311 llvm::StringRef Value,
2312 llvm::SmallString<32> &Opt) const override {
2313 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2317 static void addStackProbeSizeTargetAttribute(const Decl *D,
2318 llvm::GlobalValue *GV,
2319 CodeGen::CodeGenModule &CGM) {
2320 if (D && isa<FunctionDecl>(D)) {
2321 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
2322 llvm::Function *Fn = cast<llvm::Function>(GV);
2324 Fn->addFnAttr("stack-probe-size",
2325 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
2330 void WinX86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
2331 llvm::GlobalValue *GV,
2332 CodeGen::CodeGenModule &CGM) const {
2333 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2335 addStackProbeSizeTargetAttribute(D, GV, CGM);
2338 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2340 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2341 X86AVXABILevel AVXLevel)
2342 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
2344 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2345 CodeGen::CodeGenModule &CGM) const override;
2347 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2351 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2352 llvm::Value *Address) const override {
2353 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2355 // 0-15 are the 16 integer registers.
2357 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2361 void getDependentLibraryOption(llvm::StringRef Lib,
2362 llvm::SmallString<24> &Opt) const override {
2363 Opt = "/DEFAULTLIB:";
2364 Opt += qualifyWindowsLibrary(Lib);
2367 void getDetectMismatchOption(llvm::StringRef Name,
2368 llvm::StringRef Value,
2369 llvm::SmallString<32> &Opt) const override {
2370 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2374 void WinX86_64TargetCodeGenInfo::setTargetAttributes(const Decl *D,
2375 llvm::GlobalValue *GV,
2376 CodeGen::CodeGenModule &CGM) const {
2377 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2379 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2380 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2381 llvm::Function *Fn = cast<llvm::Function>(GV);
2382 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2386 addStackProbeSizeTargetAttribute(D, GV, CGM);
2390 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2392 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2394 // (a) If one of the classes is Memory, the whole argument is passed in
2397 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2400 // (c) If the size of the aggregate exceeds two eightbytes and the first
2401 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2402 // argument is passed in memory. NOTE: This is necessary to keep the
2403 // ABI working for processors that don't support the __m256 type.
2405 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2407 // Some of these are enforced by the merging logic. Others can arise
2408 // only with unions; for example:
2409 // union { _Complex double; unsigned; }
2411 // Note that clauses (b) and (c) were added in 0.98.
2415 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2417 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2419 if (Hi == SSEUp && Lo != SSE)
2423 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
2424 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2425 // classified recursively so that always two fields are
2426 // considered. The resulting class is calculated according to
2427 // the classes of the fields in the eightbyte:
2429 // (a) If both classes are equal, this is the resulting class.
2431 // (b) If one of the classes is NO_CLASS, the resulting class is
2434 // (c) If one of the classes is MEMORY, the result is the MEMORY
2437 // (d) If one of the classes is INTEGER, the result is the
2440 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2441 // MEMORY is used as class.
2443 // (f) Otherwise class SSE is used.
2445 // Accum should never be memory (we should have returned) or
2446 // ComplexX87 (because this cannot be passed in a structure).
2447 assert((Accum != Memory && Accum != ComplexX87) &&
2448 "Invalid accumulated classification during merge.");
2449 if (Accum == Field || Field == NoClass)
2451 if (Field == Memory)
2453 if (Accum == NoClass)
2455 if (Accum == Integer || Field == Integer)
2457 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2458 Accum == X87 || Accum == X87Up)
2463 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
2464 Class &Lo, Class &Hi, bool isNamedArg) const {
2465 // FIXME: This code can be simplified by introducing a simple value class for
2466 // Class pairs with appropriate constructor methods for the various
2469 // FIXME: Some of the split computations are wrong; unaligned vectors
2470 // shouldn't be passed in registers for example, so there is no chance they
2471 // can straddle an eightbyte. Verify & simplify.
2475 Class &Current = OffsetBase < 64 ? Lo : Hi;
2478 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
2479 BuiltinType::Kind k = BT->getKind();
2481 if (k == BuiltinType::Void) {
2483 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2486 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2488 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
2490 } else if (k == BuiltinType::LongDouble) {
2491 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2492 if (LDF == &llvm::APFloat::IEEEquad()) {
2495 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
2498 } else if (LDF == &llvm::APFloat::IEEEdouble()) {
2501 llvm_unreachable("unexpected long double representation!");
2503 // FIXME: _Decimal32 and _Decimal64 are SSE.
2504 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
2508 if (const EnumType *ET = Ty->getAs<EnumType>()) {
2509 // Classify the underlying integer type.
2510 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
2514 if (Ty->hasPointerRepresentation()) {
2519 if (Ty->isMemberPointerType()) {
2520 if (Ty->isMemberFunctionPointerType()) {
2521 if (Has64BitPointers) {
2522 // If Has64BitPointers, this is an {i64, i64}, so classify both
2526 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2527 // straddles an eightbyte boundary, Hi should be classified as well.
2528 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2529 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2530 if (EB_FuncPtr != EB_ThisAdj) {
2542 if (const VectorType *VT = Ty->getAs<VectorType>()) {
2543 uint64_t Size = getContext().getTypeSize(VT);
2544 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2545 // gcc passes the following as integer:
2546 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2547 // 2 bytes - <2 x char>, <1 x short>
2548 // 1 byte - <1 x char>
2551 // If this type crosses an eightbyte boundary, it should be
2553 uint64_t EB_Lo = (OffsetBase) / 64;
2554 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2557 } else if (Size == 64) {
2558 QualType ElementType = VT->getElementType();
2560 // gcc passes <1 x double> in memory. :(
2561 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
2564 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2565 // pass them as integer. For platforms where clang is the de facto
2566 // platform compiler, we must continue to use integer.
2567 if (!classifyIntegerMMXAsSSE() &&
2568 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2569 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2570 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2571 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
2576 // If this type crosses an eightbyte boundary, it should be
2578 if (OffsetBase && OffsetBase != 64)
2580 } else if (Size == 128 ||
2581 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
2582 // Arguments of 256-bits are split into four eightbyte chunks. The
2583 // least significant one belongs to class SSE and all the others to class
2584 // SSEUP. The original Lo and Hi design considers that types can't be
2585 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2586 // This design isn't correct for 256-bits, but since there're no cases
2587 // where the upper parts would need to be inspected, avoid adding
2588 // complexity and just consider Hi to match the 64-256 part.
2590 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2591 // registers if they are "named", i.e. not part of the "..." of a
2592 // variadic function.
2594 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2595 // split into eight eightbyte chunks, one SSE and seven SSEUP.
2602 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
2603 QualType ET = getContext().getCanonicalType(CT->getElementType());
2605 uint64_t Size = getContext().getTypeSize(Ty);
2606 if (ET->isIntegralOrEnumerationType()) {
2609 else if (Size <= 128)
2611 } else if (ET == getContext().FloatTy) {
2613 } else if (ET == getContext().DoubleTy) {
2615 } else if (ET == getContext().LongDoubleTy) {
2616 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2617 if (LDF == &llvm::APFloat::IEEEquad())
2619 else if (LDF == &llvm::APFloat::x87DoubleExtended())
2620 Current = ComplexX87;
2621 else if (LDF == &llvm::APFloat::IEEEdouble())
2624 llvm_unreachable("unexpected long double representation!");
2627 // If this complex type crosses an eightbyte boundary then it
2629 uint64_t EB_Real = (OffsetBase) / 64;
2630 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
2631 if (Hi == NoClass && EB_Real != EB_Imag)
2637 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2638 // Arrays are treated like structures.
2640 uint64_t Size = getContext().getTypeSize(Ty);
2642 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2643 // than eight eightbytes, ..., it has class MEMORY.
2647 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2648 // fields, it has class MEMORY.
2650 // Only need to check alignment of array base.
2651 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
2654 // Otherwise implement simplified merge. We could be smarter about
2655 // this, but it isn't worth it and would be harder to verify.
2657 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
2658 uint64_t ArraySize = AT->getSize().getZExtValue();
2660 // The only case a 256-bit wide vector could be used is when the array
2661 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2662 // to work for sizes wider than 128, early check and fallback to memory.
2665 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
2668 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2669 Class FieldLo, FieldHi;
2670 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
2671 Lo = merge(Lo, FieldLo);
2672 Hi = merge(Hi, FieldHi);
2673 if (Lo == Memory || Hi == Memory)
2677 postMerge(Size, Lo, Hi);
2678 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
2682 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2683 uint64_t Size = getContext().getTypeSize(Ty);
2685 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2686 // than eight eightbytes, ..., it has class MEMORY.
2690 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2691 // copy constructor or a non-trivial destructor, it is passed by invisible
2693 if (getRecordArgABI(RT, getCXXABI()))
2696 const RecordDecl *RD = RT->getDecl();
2698 // Assume variable sized types are passed in memory.
2699 if (RD->hasFlexibleArrayMember())
2702 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2704 // Reset Lo class, this will be recomputed.
2707 // If this is a C++ record, classify the bases first.
2708 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
2709 for (const auto &I : CXXRD->bases()) {
2710 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
2711 "Unexpected base class!");
2712 const CXXRecordDecl *Base =
2713 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
2715 // Classify this field.
2717 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2718 // single eightbyte, each is classified separately. Each eightbyte gets
2719 // initialized to class NO_CLASS.
2720 Class FieldLo, FieldHi;
2722 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
2723 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
2724 Lo = merge(Lo, FieldLo);
2725 Hi = merge(Hi, FieldHi);
2726 if (Lo == Memory || Hi == Memory) {
2727 postMerge(Size, Lo, Hi);
2733 // Classify the fields one at a time, merging the results.
2735 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2736 i != e; ++i, ++idx) {
2737 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2738 bool BitField = i->isBitField();
2740 // Ignore padding bit-fields.
2741 if (BitField && i->isUnnamedBitfield())
2744 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2745 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
2747 // The only case a 256-bit wide vector could be used is when the struct
2748 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2749 // to work for sizes wider than 128, early check and fallback to memory.
2751 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2752 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
2754 postMerge(Size, Lo, Hi);
2757 // Note, skip this test for bit-fields, see below.
2758 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
2760 postMerge(Size, Lo, Hi);
2764 // Classify this field.
2766 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2767 // exceeds a single eightbyte, each is classified
2768 // separately. Each eightbyte gets initialized to class
2770 Class FieldLo, FieldHi;
2772 // Bit-fields require special handling, they do not force the
2773 // structure to be passed in memory even if unaligned, and
2774 // therefore they can straddle an eightbyte.
2776 assert(!i->isUnnamedBitfield());
2777 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2778 uint64_t Size = i->getBitWidthValue(getContext());
2780 uint64_t EB_Lo = Offset / 64;
2781 uint64_t EB_Hi = (Offset + Size - 1) / 64;
2784 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2789 FieldHi = EB_Hi ? Integer : NoClass;
2792 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
2793 Lo = merge(Lo, FieldLo);
2794 Hi = merge(Hi, FieldHi);
2795 if (Lo == Memory || Hi == Memory)
2799 postMerge(Size, Lo, Hi);
2803 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
2804 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2806 if (!isAggregateTypeForABI(Ty)) {
2807 // Treat an enum type as its underlying type.
2808 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2809 Ty = EnumTy->getDecl()->getIntegerType();
2811 return (Ty->isPromotableIntegerType() ?
2812 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2815 return getNaturalAlignIndirect(Ty);
2818 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2819 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2820 uint64_t Size = getContext().getTypeSize(VecTy);
2821 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
2822 if (Size <= 64 || Size > LargestVector)
2829 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2830 unsigned freeIntRegs) const {
2831 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2834 // This assumption is optimistic, as there could be free registers available
2835 // when we need to pass this argument in memory, and LLVM could try to pass
2836 // the argument in the free register. This does not seem to happen currently,
2837 // but this code would be much safer if we could mark the argument with
2838 // 'onstack'. See PR12193.
2839 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
2840 // Treat an enum type as its underlying type.
2841 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2842 Ty = EnumTy->getDecl()->getIntegerType();
2844 return (Ty->isPromotableIntegerType() ?
2845 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2848 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
2849 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
2851 // Compute the byval alignment. We specify the alignment of the byval in all
2852 // cases so that the mid-level optimizer knows the alignment of the byval.
2853 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
2855 // Attempt to avoid passing indirect results using byval when possible. This
2856 // is important for good codegen.
2858 // We do this by coercing the value into a scalar type which the backend can
2859 // handle naturally (i.e., without using byval).
2861 // For simplicity, we currently only do this when we have exhausted all of the
2862 // free integer registers. Doing this when there are free integer registers
2863 // would require more care, as we would have to ensure that the coerced value
2864 // did not claim the unused register. That would require either reording the
2865 // arguments to the function (so that any subsequent inreg values came first),
2866 // or only doing this optimization when there were no following arguments that
2869 // We currently expect it to be rare (particularly in well written code) for
2870 // arguments to be passed on the stack when there are still free integer
2871 // registers available (this would typically imply large structs being passed
2872 // by value), so this seems like a fair tradeoff for now.
2874 // We can revisit this if the backend grows support for 'onstack' parameter
2875 // attributes. See PR12193.
2876 if (freeIntRegs == 0) {
2877 uint64_t Size = getContext().getTypeSize(Ty);
2879 // If this type fits in an eightbyte, coerce it into the matching integral
2880 // type, which will end up on the stack (with alignment 8).
2881 if (Align == 8 && Size <= 64)
2882 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2886 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
2889 /// The ABI specifies that a value should be passed in a full vector XMM/YMM
2890 /// register. Pick an LLVM IR type that will be passed as a vector register.
2891 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
2892 // Wrapper structs/arrays that only contain vectors are passed just like
2893 // vectors; strip them off if present.
2894 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2895 Ty = QualType(InnerTy, 0);
2897 llvm::Type *IRType = CGT.ConvertType(Ty);
2898 if (isa<llvm::VectorType>(IRType) ||
2899 IRType->getTypeID() == llvm::Type::FP128TyID)
2902 // We couldn't find the preferred IR vector type for 'Ty'.
2903 uint64_t Size = getContext().getTypeSize(Ty);
2904 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
2906 // Return a LLVM IR vector type based on the size of 'Ty'.
2907 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2911 /// BitsContainNoUserData - Return true if the specified [start,end) bit range
2912 /// is known to either be off the end of the specified type or being in
2913 /// alignment padding. The user type specified is known to be at most 128 bits
2914 /// in size, and have passed through X86_64ABIInfo::classify with a successful
2915 /// classification that put one of the two halves in the INTEGER class.
2917 /// It is conservatively correct to return false.
2918 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2919 unsigned EndBit, ASTContext &Context) {
2920 // If the bytes being queried are off the end of the type, there is no user
2921 // data hiding here. This handles analysis of builtins, vectors and other
2922 // types that don't contain interesting padding.
2923 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2924 if (TySize <= StartBit)
2927 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2928 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2929 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2931 // Check each element to see if the element overlaps with the queried range.
2932 for (unsigned i = 0; i != NumElts; ++i) {
2933 // If the element is after the span we care about, then we're done..
2934 unsigned EltOffset = i*EltSize;
2935 if (EltOffset >= EndBit) break;
2937 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2938 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2939 EndBit-EltOffset, Context))
2942 // If it overlaps no elements, then it is safe to process as padding.
2946 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2947 const RecordDecl *RD = RT->getDecl();
2948 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2950 // If this is a C++ record, check the bases first.
2951 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
2952 for (const auto &I : CXXRD->bases()) {
2953 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
2954 "Unexpected base class!");
2955 const CXXRecordDecl *Base =
2956 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
2958 // If the base is after the span we care about, ignore it.
2959 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
2960 if (BaseOffset >= EndBit) continue;
2962 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
2963 if (!BitsContainNoUserData(I.getType(), BaseStart,
2964 EndBit-BaseOffset, Context))
2969 // Verify that no field has data that overlaps the region of interest. Yes
2970 // this could be sped up a lot by being smarter about queried fields,
2971 // however we're only looking at structs up to 16 bytes, so we don't care
2974 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2975 i != e; ++i, ++idx) {
2976 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
2978 // If we found a field after the region we care about, then we're done.
2979 if (FieldOffset >= EndBit) break;
2981 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2982 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2987 // If nothing in this record overlapped the area of interest, then we're
2995 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2996 /// float member at the specified offset. For example, {int,{float}} has a
2997 /// float at offset 4. It is conservatively correct for this routine to return
2999 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
3000 const llvm::DataLayout &TD) {
3001 // Base case if we find a float.
3002 if (IROffset == 0 && IRType->isFloatTy())
3005 // If this is a struct, recurse into the field at the specified offset.
3006 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3007 const llvm::StructLayout *SL = TD.getStructLayout(STy);
3008 unsigned Elt = SL->getElementContainingOffset(IROffset);
3009 IROffset -= SL->getElementOffset(Elt);
3010 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3013 // If this is an array, recurse into the field at the specified offset.
3014 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3015 llvm::Type *EltTy = ATy->getElementType();
3016 unsigned EltSize = TD.getTypeAllocSize(EltTy);
3017 IROffset -= IROffset/EltSize*EltSize;
3018 return ContainsFloatAtOffset(EltTy, IROffset, TD);
3025 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3026 /// low 8 bytes of an XMM register, corresponding to the SSE class.
3027 llvm::Type *X86_64ABIInfo::
3028 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3029 QualType SourceTy, unsigned SourceOffset) const {
3030 // The only three choices we have are either double, <2 x float>, or float. We
3031 // pass as float if the last 4 bytes is just padding. This happens for
3032 // structs that contain 3 floats.
3033 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3034 SourceOffset*8+64, getContext()))
3035 return llvm::Type::getFloatTy(getVMContext());
3037 // We want to pass as <2 x float> if the LLVM IR type contains a float at
3038 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
3040 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3041 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
3042 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
3044 return llvm::Type::getDoubleTy(getVMContext());
3048 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3049 /// an 8-byte GPR. This means that we either have a scalar or we are talking
3050 /// about the high or low part of an up-to-16-byte struct. This routine picks
3051 /// the best LLVM IR type to represent this, which may be i64 or may be anything
3052 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3055 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3056 /// the source type. IROffset is an offset in bytes into the LLVM IR type that
3057 /// the 8-byte value references. PrefType may be null.
3059 /// SourceTy is the source-level type for the entire argument. SourceOffset is
3060 /// an offset into this that we're processing (which is always either 0 or 8).
3062 llvm::Type *X86_64ABIInfo::
3063 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3064 QualType SourceTy, unsigned SourceOffset) const {
3065 // If we're dealing with an un-offset LLVM IR type, then it means that we're
3066 // returning an 8-byte unit starting with it. See if we can safely use it.
3067 if (IROffset == 0) {
3068 // Pointers and int64's always fill the 8-byte unit.
3069 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3070 IRType->isIntegerTy(64))
3073 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3074 // goodness in the source type is just tail padding. This is allowed to
3075 // kick in for struct {double,int} on the int, but not on
3076 // struct{double,int,int} because we wouldn't return the second int. We
3077 // have to do this analysis on the source type because we can't depend on
3078 // unions being lowered a specific way etc.
3079 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
3080 IRType->isIntegerTy(32) ||
3081 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3082 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3083 cast<llvm::IntegerType>(IRType)->getBitWidth();
3085 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3086 SourceOffset*8+64, getContext()))
3091 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3092 // If this is a struct, recurse into the field at the specified offset.
3093 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
3094 if (IROffset < SL->getSizeInBytes()) {
3095 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3096 IROffset -= SL->getElementOffset(FieldIdx);
3098 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3099 SourceTy, SourceOffset);
3103 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3104 llvm::Type *EltTy = ATy->getElementType();
3105 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
3106 unsigned EltOffset = IROffset/EltSize*EltSize;
3107 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3111 // Okay, we don't have any better idea of what to pass, so we pass this in an
3112 // integer register that isn't too big to fit the rest of the struct.
3113 unsigned TySizeInBytes =
3114 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
3116 assert(TySizeInBytes != SourceOffset && "Empty field?");
3118 // It is always safe to classify this as an integer type up to i64 that
3119 // isn't larger than the structure.
3120 return llvm::IntegerType::get(getVMContext(),
3121 std::min(TySizeInBytes-SourceOffset, 8U)*8);
3125 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3126 /// be used as elements of a two register pair to pass or return, return a
3127 /// first class aggregate to represent them. For example, if the low part of
3128 /// a by-value argument should be passed as i32* and the high part as float,
3129 /// return {i32*, float}.
3131 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
3132 const llvm::DataLayout &TD) {
3133 // In order to correctly satisfy the ABI, we need to the high part to start
3134 // at offset 8. If the high and low parts we inferred are both 4-byte types
3135 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3136 // the second element at offset 8. Check for this:
3137 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3138 unsigned HiAlign = TD.getABITypeAlignment(Hi);
3139 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
3140 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
3142 // To handle this, we have to increase the size of the low part so that the
3143 // second element will start at an 8 byte offset. We can't increase the size
3144 // of the second element because it might make us access off the end of the
3147 // There are usually two sorts of types the ABI generation code can produce
3148 // for the low part of a pair that aren't 8 bytes in size: float or
3149 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
3151 // Promote these to a larger type.
3152 if (Lo->isFloatTy())
3153 Lo = llvm::Type::getDoubleTy(Lo->getContext());
3155 assert((Lo->isIntegerTy() || Lo->isPointerTy())
3156 && "Invalid/unknown lo type");
3157 Lo = llvm::Type::getInt64Ty(Lo->getContext());
3161 llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
3163 // Verify that the second element is at an 8-byte offset.
3164 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3165 "Invalid x86-64 argument pair!");
3169 ABIArgInfo X86_64ABIInfo::
3170 classifyReturnType(QualType RetTy) const {
3171 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3172 // classification algorithm.
3173 X86_64ABIInfo::Class Lo, Hi;
3174 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
3176 // Check some invariants.
3177 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3178 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3180 llvm::Type *ResType = nullptr;
3184 return ABIArgInfo::getIgnore();
3185 // If the low part is just padding, it takes no register, leave ResType
3187 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3188 "Unknown missing lo part");
3193 llvm_unreachable("Invalid classification for lo word.");
3195 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3198 return getIndirectReturnResult(RetTy);
3200 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3201 // available register of the sequence %rax, %rdx is used.
3203 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3205 // If we have a sign or zero extended integer, make sure to return Extend
3206 // so that the parameter gets the right LLVM IR attributes.
3207 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3208 // Treat an enum type as its underlying type.
3209 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3210 RetTy = EnumTy->getDecl()->getIntegerType();
3212 if (RetTy->isIntegralOrEnumerationType() &&
3213 RetTy->isPromotableIntegerType())
3214 return ABIArgInfo::getExtend();
3218 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3219 // available SSE register of the sequence %xmm0, %xmm1 is used.
3221 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3224 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3225 // returned on the X87 stack in %st0 as 80-bit x87 number.
3227 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
3230 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3231 // part of the value is returned in %st0 and the imaginary part in
3234 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
3235 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
3236 llvm::Type::getX86_FP80Ty(getVMContext()));
3240 llvm::Type *HighPart = nullptr;
3242 // Memory was handled previously and X87 should
3243 // never occur as a hi class.
3246 llvm_unreachable("Invalid classification for hi word.");
3248 case ComplexX87: // Previously handled.
3253 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3254 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3255 return ABIArgInfo::getDirect(HighPart, 8);
3258 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3259 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3260 return ABIArgInfo::getDirect(HighPart, 8);
3263 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
3264 // is passed in the next available eightbyte chunk if the last used
3267 // SSEUP should always be preceded by SSE, just widen.
3269 assert(Lo == SSE && "Unexpected SSEUp classification.");
3270 ResType = GetByteVectorType(RetTy);
3273 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3274 // returned together with the previous X87 value in %st0.
3276 // If X87Up is preceded by X87, we don't need to do
3277 // anything. However, in some cases with unions it may not be
3278 // preceded by X87. In such situations we follow gcc and pass the
3279 // extra bits in an SSE reg.
3281 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3282 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3283 return ABIArgInfo::getDirect(HighPart, 8);
3288 // If a high part was specified, merge it together with the low part. It is
3289 // known to pass in the high eightbyte of the result. We do this by forming a
3290 // first class struct aggregate with the high and low part: {low, high}
3292 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3294 return ABIArgInfo::getDirect(ResType);
3297 ABIArgInfo X86_64ABIInfo::classifyArgumentType(
3298 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3302 Ty = useFirstFieldIfTransparentUnion(Ty);
3304 X86_64ABIInfo::Class Lo, Hi;
3305 classify(Ty, 0, Lo, Hi, isNamedArg);
3307 // Check some invariants.
3308 // FIXME: Enforce these by construction.
3309 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3310 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3314 llvm::Type *ResType = nullptr;
3318 return ABIArgInfo::getIgnore();
3319 // If the low part is just padding, it takes no register, leave ResType
3321 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3322 "Unknown missing lo part");
3325 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3329 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3330 // COMPLEX_X87, it is passed in memory.
3333 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
3335 return getIndirectResult(Ty, freeIntRegs);
3339 llvm_unreachable("Invalid classification for lo word.");
3341 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3342 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3347 // Pick an 8-byte type based on the preferred type.
3348 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
3350 // If we have a sign or zero extended integer, make sure to return Extend
3351 // so that the parameter gets the right LLVM IR attributes.
3352 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3353 // Treat an enum type as its underlying type.
3354 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3355 Ty = EnumTy->getDecl()->getIntegerType();
3357 if (Ty->isIntegralOrEnumerationType() &&
3358 Ty->isPromotableIntegerType())
3359 return ABIArgInfo::getExtend();
3364 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3365 // available SSE register is used, the registers are taken in the
3366 // order from %xmm0 to %xmm7.
3368 llvm::Type *IRType = CGT.ConvertType(Ty);
3369 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
3375 llvm::Type *HighPart = nullptr;
3377 // Memory was handled previously, ComplexX87 and X87 should
3378 // never occur as hi classes, and X87Up must be preceded by X87,
3379 // which is passed in memory.
3383 llvm_unreachable("Invalid classification for hi word.");
3385 case NoClass: break;
3389 // Pick an 8-byte type based on the preferred type.
3390 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3392 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3393 return ABIArgInfo::getDirect(HighPart, 8);
3396 // X87Up generally doesn't occur here (long double is passed in
3397 // memory), except in situations involving unions.
3400 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3402 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3403 return ABIArgInfo::getDirect(HighPart, 8);
3408 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3409 // eightbyte is passed in the upper half of the last used SSE
3410 // register. This only happens when 128-bit vectors are passed.
3412 assert(Lo == SSE && "Unexpected SSEUp classification");
3413 ResType = GetByteVectorType(Ty);
3417 // If a high part was specified, merge it together with the low part. It is
3418 // known to pass in the high eightbyte of the result. We do this by forming a
3419 // first class struct aggregate with the high and low part: {low, high}
3421 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3423 return ABIArgInfo::getDirect(ResType);
3427 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3428 unsigned &NeededSSE) const {
3429 auto RT = Ty->getAs<RecordType>();
3430 assert(RT && "classifyRegCallStructType only valid with struct types");
3432 if (RT->getDecl()->hasFlexibleArrayMember())
3433 return getIndirectReturnResult(Ty);
3436 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3437 if (CXXRD->isDynamicClass()) {
3438 NeededInt = NeededSSE = 0;
3439 return getIndirectReturnResult(Ty);
3442 for (const auto &I : CXXRD->bases())
3443 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3445 NeededInt = NeededSSE = 0;
3446 return getIndirectReturnResult(Ty);
3451 for (const auto *FD : RT->getDecl()->fields()) {
3452 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3453 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3455 NeededInt = NeededSSE = 0;
3456 return getIndirectReturnResult(Ty);
3459 unsigned LocalNeededInt, LocalNeededSSE;
3460 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3461 LocalNeededSSE, true)
3463 NeededInt = NeededSSE = 0;
3464 return getIndirectReturnResult(Ty);
3466 NeededInt += LocalNeededInt;
3467 NeededSSE += LocalNeededSSE;
3471 return ABIArgInfo::getDirect();
3474 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3475 unsigned &NeededInt,
3476 unsigned &NeededSSE) const {
3481 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3484 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3486 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
3488 // Keep track of the number of assigned registers.
3489 unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3490 unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3491 unsigned NeededInt, NeededSSE;
3493 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3494 !FI.getReturnType()->getTypePtr()->isUnionType()) {
3495 FI.getReturnInfo() =
3496 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3497 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3498 FreeIntRegs -= NeededInt;
3499 FreeSSERegs -= NeededSSE;
3501 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3503 } else if (!getCXXABI().classifyReturnType(FI))
3504 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3506 // If the return value is indirect, then the hidden argument is consuming one
3507 // integer register.
3508 if (FI.getReturnInfo().isIndirect())
3511 // The chain argument effectively gives us another free register.
3512 if (FI.isChainCall())
3515 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
3516 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3517 // get assigned (in left-to-right order) for passing as follows...
3519 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3520 it != ie; ++it, ++ArgNo) {
3521 bool IsNamedArg = ArgNo < NumRequiredArgs;
3523 if (IsRegCall && it->type->isStructureOrClassType())
3524 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3526 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3527 NeededSSE, IsNamedArg);
3529 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3530 // eightbyte of an argument, the whole argument is passed on the
3531 // stack. If registers have already been assigned for some
3532 // eightbytes of such an argument, the assignments get reverted.
3533 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3534 FreeIntRegs -= NeededInt;
3535 FreeSSERegs -= NeededSSE;
3537 it->info = getIndirectResult(it->type, FreeIntRegs);
3542 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3543 Address VAListAddr, QualType Ty) {
3544 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3545 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
3546 llvm::Value *overflow_arg_area =
3547 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3549 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3550 // byte boundary if alignment needed by type exceeds 8 byte boundary.
3551 // It isn't stated explicitly in the standard, but in practice we use
3552 // alignment greater than 16 where necessary.
3553 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3554 if (Align > CharUnits::fromQuantity(8)) {
3555 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3559 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
3560 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
3562 CGF.Builder.CreateBitCast(overflow_arg_area,
3563 llvm::PointerType::getUnqual(LTy));
3565 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3566 // l->overflow_arg_area + sizeof(type).
3567 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3568 // an 8 byte boundary.
3570 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
3571 llvm::Value *Offset =
3572 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
3573 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3574 "overflow_arg_area.next");
3575 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3577 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
3578 return Address(Res, Align);
3581 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3582 QualType Ty) const {
3583 // Assume that va_list type is correct; should be pointer to LLVM type:
3587 // i8* overflow_arg_area;
3588 // i8* reg_save_area;
3590 unsigned neededInt, neededSSE;
3592 Ty = getContext().getCanonicalType(Ty);
3593 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
3594 /*isNamedArg*/false);
3596 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3597 // in the registers. If not go to step 7.
3598 if (!neededInt && !neededSSE)
3599 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
3601 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3602 // general purpose registers needed to pass type and num_fp to hold
3603 // the number of floating point registers needed.
3605 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3606 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3607 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3609 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3610 // register save space).
3612 llvm::Value *InRegs = nullptr;
3613 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3614 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
3617 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3619 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
3620 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3621 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
3626 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3628 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3629 llvm::Value *FitsInFP =
3630 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3631 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
3632 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3635 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3636 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3637 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3638 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3640 // Emit code to load the value if it was passed in registers.
3642 CGF.EmitBlock(InRegBlock);
3644 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3645 // an offset of l->gp_offset and/or l->fp_offset. This may require
3646 // copying to a temporary location in case the parameter is passed
3647 // in different register classes or requires an alignment greater
3648 // than 8 for general purpose registers and 16 for XMM registers.
3650 // FIXME: This really results in shameful code when we end up needing to
3651 // collect arguments from different places; often what should result in a
3652 // simple assembling of a structure from scattered addresses has many more
3653 // loads than necessary. Can we clean this up?
3654 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
3655 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3656 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3659 Address RegAddr = Address::invalid();
3660 if (neededInt && neededSSE) {
3662 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
3663 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
3664 Address Tmp = CGF.CreateMemTemp(Ty);
3665 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3666 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
3667 llvm::Type *TyLo = ST->getElementType(0);
3668 llvm::Type *TyHi = ST->getElementType(1);
3669 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
3670 "Unexpected ABI info for mixed regs");
3671 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3672 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
3673 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3674 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
3675 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3676 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
3678 // Copy the first element.
3679 // FIXME: Our choice of alignment here and below is probably pessimistic.
3680 llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3681 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
3682 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
3683 CGF.Builder.CreateStore(V,
3684 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3686 // Copy the second element.
3687 V = CGF.Builder.CreateAlignedLoad(
3688 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
3689 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
3690 CharUnits Offset = CharUnits::fromQuantity(
3691 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3692 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3694 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
3695 } else if (neededInt) {
3696 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3697 CharUnits::fromQuantity(8));
3698 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
3700 // Copy to a temporary if necessary to ensure the appropriate alignment.
3701 std::pair<CharUnits, CharUnits> SizeAlign =
3702 getContext().getTypeInfoInChars(Ty);
3703 uint64_t TySize = SizeAlign.first.getQuantity();
3704 CharUnits TyAlign = SizeAlign.second;
3706 // Copy into a temporary if the type is more aligned than the
3707 // register save area.
3708 if (TyAlign.getQuantity() > 8) {
3709 Address Tmp = CGF.CreateMemTemp(Ty);
3710 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
3714 } else if (neededSSE == 1) {
3715 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3716 CharUnits::fromQuantity(16));
3717 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
3719 assert(neededSSE == 2 && "Invalid number of needed registers!");
3720 // SSE registers are spaced 16 bytes apart in the register save
3721 // area, we need to collect the two eightbytes together.
3722 // The ABI isn't explicit about this, but it seems reasonable
3723 // to assume that the slots are 16-byte aligned, since the stack is
3724 // naturally 16-byte aligned and the prologue is expected to store
3725 // all the SSE registers to the RSA.
3726 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3727 CharUnits::fromQuantity(16));
3729 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3730 CharUnits::fromQuantity(16));
3731 llvm::Type *DoubleTy = CGF.DoubleTy;
3732 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy);
3734 Address Tmp = CGF.CreateMemTemp(Ty);
3735 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3736 V = CGF.Builder.CreateLoad(
3737 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3738 CGF.Builder.CreateStore(V,
3739 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3740 V = CGF.Builder.CreateLoad(
3741 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3742 CGF.Builder.CreateStore(V,
3743 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3745 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
3748 // AMD64-ABI 3.5.7p5: Step 5. Set:
3749 // l->gp_offset = l->gp_offset + num_gp * 8
3750 // l->fp_offset = l->fp_offset + num_fp * 16.
3752 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
3753 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3757 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
3758 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3761 CGF.EmitBranch(ContBlock);
3763 // Emit code to load the value if it was passed in memory.
3765 CGF.EmitBlock(InMemBlock);
3766 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
3768 // Return the appropriate result.
3770 CGF.EmitBlock(ContBlock);
3771 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3776 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3777 QualType Ty) const {
3778 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3779 CGF.getContext().getTypeInfoInChars(Ty),
3780 CharUnits::fromQuantity(8),
3781 /*allowHigherAlign*/ false);
3785 WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
3786 const ABIArgInfo ¤t) const {
3787 // Assumes vectorCall calling convention.
3788 const Type *Base = nullptr;
3789 uint64_t NumElts = 0;
3791 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
3792 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
3793 FreeSSERegs -= NumElts;
3794 return getDirectX86Hva();
3799 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3800 bool IsReturnType, bool IsVectorCall,
3801 bool IsRegCall) const {
3803 if (Ty->isVoidType())
3804 return ABIArgInfo::getIgnore();
3806 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3807 Ty = EnumTy->getDecl()->getIntegerType();
3809 TypeInfo Info = getContext().getTypeInfo(Ty);
3810 uint64_t Width = Info.Width;
3811 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
3813 const RecordType *RT = Ty->getAs<RecordType>();
3815 if (!IsReturnType) {
3816 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
3817 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
3820 if (RT->getDecl()->hasFlexibleArrayMember())
3821 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
3825 const Type *Base = nullptr;
3826 uint64_t NumElts = 0;
3827 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3829 if ((IsVectorCall || IsRegCall) &&
3830 isHomogeneousAggregate(Ty, Base, NumElts)) {
3832 if (FreeSSERegs >= NumElts) {
3833 FreeSSERegs -= NumElts;
3834 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3835 return ABIArgInfo::getDirect();
3836 return ABIArgInfo::getExpand();
3838 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3839 } else if (IsVectorCall) {
3840 if (FreeSSERegs >= NumElts &&
3841 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
3842 FreeSSERegs -= NumElts;
3843 return ABIArgInfo::getDirect();
3844 } else if (IsReturnType) {
3845 return ABIArgInfo::getExpand();
3846 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
3847 // HVAs are delayed and reclassified in the 2nd step.
3848 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3853 if (Ty->isMemberPointerType()) {
3854 // If the member pointer is represented by an LLVM int or ptr, pass it
3856 llvm::Type *LLTy = CGT.ConvertType(Ty);
3857 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3858 return ABIArgInfo::getDirect();
3861 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
3862 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3863 // not 1, 2, 4, or 8 bytes, must be passed by reference."
3864 if (Width > 64 || !llvm::isPowerOf2_64(Width))
3865 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
3867 // Otherwise, coerce it to a small integer.
3868 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
3871 // Bool type is always extended to the ABI, other builtin types are not
3873 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3874 if (BT && BT->getKind() == BuiltinType::Bool)
3875 return ABIArgInfo::getExtend();
3877 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3878 // passes them indirectly through memory.
3879 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3880 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3881 if (LDF == &llvm::APFloat::x87DoubleExtended())
3882 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3885 return ABIArgInfo::getDirect();
3888 void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI,
3889 unsigned FreeSSERegs,
3891 bool IsRegCall) const {
3893 for (auto &I : FI.arguments()) {
3894 if (Count < VectorcallMaxParamNumAsReg)
3895 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
3897 // Since these cannot be passed in registers, pretend no registers
3899 unsigned ZeroSSERegsAvail = 0;
3900 I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false,
3901 IsVectorCall, IsRegCall);
3907 for (auto &I : FI.arguments()) {
3908 if (Count < VectorcallMaxParamNumAsReg)
3909 I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info);
3914 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3916 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
3917 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
3919 unsigned FreeSSERegs = 0;
3921 // We can use up to 4 SSE return registers with vectorcall.
3923 } else if (IsRegCall) {
3924 // RegCall gives us 16 SSE registers.
3928 if (!getCXXABI().classifyReturnType(FI))
3929 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
3930 IsVectorCall, IsRegCall);
3933 // We can use up to 6 SSE register parameters with vectorcall.
3935 } else if (IsRegCall) {
3936 // RegCall gives us 16 SSE registers, we can reuse the return registers.
3941 computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall);
3943 for (auto &I : FI.arguments())
3944 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
3949 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3950 QualType Ty) const {
3952 bool IsIndirect = false;
3954 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3955 // not 1, 2, 4, or 8 bytes, must be passed by reference."
3956 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
3957 uint64_t Width = getContext().getTypeSize(Ty);
3958 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
3961 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
3962 CGF.getContext().getTypeInfoInChars(Ty),
3963 CharUnits::fromQuantity(8),
3964 /*allowHigherAlign*/ false);
3969 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3970 class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
3971 bool IsSoftFloatABI;
3973 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
3974 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
3976 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3977 QualType Ty) const override;
3980 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3982 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
3983 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
3985 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
3986 // This is recovered from gcc output.
3987 return 1; // r1 is the dedicated stack pointer
3990 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3991 llvm::Value *Address) const override;
3996 // TODO: this implementation is now likely redundant with
3997 // DefaultABIInfo::EmitVAArg.
3998 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
3999 QualType Ty) const {
4000 const unsigned OverflowLimit = 8;
4001 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4002 // TODO: Implement this. For now ignore.
4004 return Address::invalid(); // FIXME?
4007 // struct __va_list_tag {
4008 // unsigned char gpr;
4009 // unsigned char fpr;
4010 // unsigned short reserved;
4011 // void *overflow_arg_area;
4012 // void *reg_save_area;
4015 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
4017 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
4018 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
4020 // All aggregates are passed indirectly? That doesn't seem consistent
4021 // with the argument-lowering code.
4022 bool isIndirect = Ty->isAggregateType();
4024 CGBuilderTy &Builder = CGF.Builder;
4026 // The calling convention either uses 1-2 GPRs or 1 FPR.
4027 Address NumRegsAddr = Address::invalid();
4028 if (isInt || IsSoftFloatABI) {
4029 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
4031 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
4034 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4036 // "Align" the register count when TY is i64.
4037 if (isI64 || (isF64 && IsSoftFloatABI)) {
4038 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4039 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4043 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
4045 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4046 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4047 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4049 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4051 llvm::Type *DirectTy = CGF.ConvertType(Ty);
4052 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
4054 // Case 1: consume registers.
4055 Address RegAddr = Address::invalid();
4057 CGF.EmitBlock(UsingRegs);
4059 Address RegSaveAreaPtr =
4060 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
4061 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4062 CharUnits::fromQuantity(8));
4063 assert(RegAddr.getElementType() == CGF.Int8Ty);
4065 // Floating-point registers start after the general-purpose registers.
4066 if (!(isInt || IsSoftFloatABI)) {
4067 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4068 CharUnits::fromQuantity(32));
4071 // Get the address of the saved value by scaling the number of
4072 // registers we've used by the number of
4073 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
4074 llvm::Value *RegOffset =
4075 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4076 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4077 RegAddr.getPointer(), RegOffset),
4078 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4079 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4081 // Increase the used-register count.
4083 Builder.CreateAdd(NumRegs,
4084 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
4085 Builder.CreateStore(NumRegs, NumRegsAddr);
4087 CGF.EmitBranch(Cont);
4090 // Case 2: consume space in the overflow area.
4091 Address MemAddr = Address::invalid();
4093 CGF.EmitBlock(UsingOverflow);
4095 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4097 // Everything in the overflow area is rounded up to a size of at least 4.
4098 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4102 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
4103 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
4105 Size = CGF.getPointerSize();
4108 Address OverflowAreaAddr =
4109 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
4110 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
4112 // Round up address of argument to alignment
4113 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4114 if (Align > OverflowAreaAlign) {
4115 llvm::Value *Ptr = OverflowArea.getPointer();
4116 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4120 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4122 // Increase the overflow area.
4123 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4124 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4125 CGF.EmitBranch(Cont);
4128 CGF.EmitBlock(Cont);
4130 // Merge the cases with a phi.
4131 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4134 // Load the pointer if the argument was passed indirectly.
4136 Result = Address(Builder.CreateLoad(Result, "aggr"),
4137 getContext().getTypeAlignInChars(Ty));
4144 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4145 llvm::Value *Address) const {
4146 // This is calculated from the LLVM and GCC tables and verified
4147 // against gcc output. AFAIK all ABIs use the same encoding.
4149 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4151 llvm::IntegerType *i8 = CGF.Int8Ty;
4152 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4153 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4154 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4156 // 0-31: r0-31, the 4-byte general-purpose registers
4157 AssignToArrayRange(Builder, Address, Four8, 0, 31);
4159 // 32-63: fp0-31, the 8-byte floating-point registers
4160 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4162 // 64-76 are various 4-byte special-purpose registers:
4169 AssignToArrayRange(Builder, Address, Four8, 64, 76);
4171 // 77-108: v0-31, the 16-byte vector registers
4172 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4179 AssignToArrayRange(Builder, Address, Four8, 109, 113);
4187 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
4188 class PPC64_SVR4_ABIInfo : public ABIInfo {
4196 static const unsigned GPRBits = 64;
4199 bool IsSoftFloatABI;
4201 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4202 // will be passed in a QPX register.
4203 bool IsQPXVectorTy(const Type *Ty) const {
4207 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4208 unsigned NumElements = VT->getNumElements();
4209 if (NumElements == 1)
4212 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4213 if (getContext().getTypeSize(Ty) <= 256)
4215 } else if (VT->getElementType()->
4216 isSpecificBuiltinType(BuiltinType::Float)) {
4217 if (getContext().getTypeSize(Ty) <= 128)
4225 bool IsQPXVectorTy(QualType Ty) const {
4226 return IsQPXVectorTy(Ty.getTypePtr());
4230 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4232 : ABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
4233 IsSoftFloatABI(SoftFloatABI) {}
4235 bool isPromotableTypeForABI(QualType Ty) const;
4236 CharUnits getParamTypeAlignment(QualType Ty) const;
4238 ABIArgInfo classifyReturnType(QualType RetTy) const;
4239 ABIArgInfo classifyArgumentType(QualType Ty) const;
4241 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4242 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4243 uint64_t Members) const override;
4245 // TODO: We can add more logic to computeInfo to improve performance.
4246 // Example: For aggregate arguments that fit in a register, we could
4247 // use getDirectInReg (as is done below for structs containing a single
4248 // floating-point value) to avoid pushing them to memory on function
4249 // entry. This would require changing the logic in PPCISelLowering
4250 // when lowering the parameters in the caller and args in the callee.
4251 void computeInfo(CGFunctionInfo &FI) const override {
4252 if (!getCXXABI().classifyReturnType(FI))
4253 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4254 for (auto &I : FI.arguments()) {
4255 // We rely on the default argument classification for the most part.
4256 // One exception: An aggregate containing a single floating-point
4257 // or vector item must be passed in a register if one is available.
4258 const Type *T = isSingleElementStruct(I.type, getContext());
4260 const BuiltinType *BT = T->getAs<BuiltinType>();
4261 if (IsQPXVectorTy(T) ||
4262 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
4263 (BT && BT->isFloatingPoint())) {
4265 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
4269 I.info = classifyArgumentType(I.type);
4273 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4274 QualType Ty) const override;
4277 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
4280 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
4281 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4283 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX,
4286 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4287 // This is recovered from gcc output.
4288 return 1; // r1 is the dedicated stack pointer
4291 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4292 llvm::Value *Address) const override;
4295 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4297 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4299 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4300 // This is recovered from gcc output.
4301 return 1; // r1 is the dedicated stack pointer
4304 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4305 llvm::Value *Address) const override;
4310 // Return true if the ABI requires Ty to be passed sign- or zero-
4311 // extended to 64 bits.
4313 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4314 // Treat an enum type as its underlying type.
4315 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4316 Ty = EnumTy->getDecl()->getIntegerType();
4318 // Promotable integer types are required to be promoted by the ABI.
4319 if (Ty->isPromotableIntegerType())
4322 // In addition to the usual promotable integer types, we also need to
4323 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4324 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4325 switch (BT->getKind()) {
4326 case BuiltinType::Int:
4327 case BuiltinType::UInt:
4336 /// isAlignedParamType - Determine whether a type requires 16-byte or
4337 /// higher alignment in the parameter area. Always returns at least 8.
4338 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4339 // Complex types are passed just like their elements.
4340 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4341 Ty = CTy->getElementType();
4343 // Only vector types of size 16 bytes need alignment (larger types are
4344 // passed via reference, smaller types are not aligned).
4345 if (IsQPXVectorTy(Ty)) {
4346 if (getContext().getTypeSize(Ty) > 128)
4347 return CharUnits::fromQuantity(32);
4349 return CharUnits::fromQuantity(16);
4350 } else if (Ty->isVectorType()) {
4351 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
4354 // For single-element float/vector structs, we consider the whole type
4355 // to have the same alignment requirements as its single element.
4356 const Type *AlignAsType = nullptr;
4357 const Type *EltType = isSingleElementStruct(Ty, getContext());
4359 const BuiltinType *BT = EltType->getAs<BuiltinType>();
4360 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
4361 getContext().getTypeSize(EltType) == 128) ||
4362 (BT && BT->isFloatingPoint()))
4363 AlignAsType = EltType;
4366 // Likewise for ELFv2 homogeneous aggregates.
4367 const Type *Base = nullptr;
4368 uint64_t Members = 0;
4369 if (!AlignAsType && Kind == ELFv2 &&
4370 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4373 // With special case aggregates, only vector base types need alignment.
4374 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4375 if (getContext().getTypeSize(AlignAsType) > 128)
4376 return CharUnits::fromQuantity(32);
4378 return CharUnits::fromQuantity(16);
4379 } else if (AlignAsType) {
4380 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
4383 // Otherwise, we only need alignment for any aggregate type that
4384 // has an alignment requirement of >= 16 bytes.
4385 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4386 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
4387 return CharUnits::fromQuantity(32);
4388 return CharUnits::fromQuantity(16);
4391 return CharUnits::fromQuantity(8);
4394 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4395 /// aggregate. Base is set to the base element type, and Members is set
4396 /// to the number of base elements.
4397 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4398 uint64_t &Members) const {
4399 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4400 uint64_t NElements = AT->getSize().getZExtValue();
4403 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4405 Members *= NElements;
4406 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4407 const RecordDecl *RD = RT->getDecl();
4408 if (RD->hasFlexibleArrayMember())
4413 // If this is a C++ record, check the bases first.
4414 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4415 for (const auto &I : CXXRD->bases()) {
4416 // Ignore empty records.
4417 if (isEmptyRecord(getContext(), I.getType(), true))
4420 uint64_t FldMembers;
4421 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4424 Members += FldMembers;
4428 for (const auto *FD : RD->fields()) {
4429 // Ignore (non-zero arrays of) empty records.
4430 QualType FT = FD->getType();
4431 while (const ConstantArrayType *AT =
4432 getContext().getAsConstantArrayType(FT)) {
4433 if (AT->getSize().getZExtValue() == 0)
4435 FT = AT->getElementType();
4437 if (isEmptyRecord(getContext(), FT, true))
4440 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4441 if (getContext().getLangOpts().CPlusPlus &&
4442 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4445 uint64_t FldMembers;
4446 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4449 Members = (RD->isUnion() ?
4450 std::max(Members, FldMembers) : Members + FldMembers);
4456 // Ensure there is no padding.
4457 if (getContext().getTypeSize(Base) * Members !=
4458 getContext().getTypeSize(Ty))
4462 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4464 Ty = CT->getElementType();
4467 // Most ABIs only support float, double, and some vector type widths.
4468 if (!isHomogeneousAggregateBaseType(Ty))
4471 // The base type must be the same for all members. Types that
4472 // agree in both total size and mode (float vs. vector) are
4473 // treated as being equivalent here.
4474 const Type *TyPtr = Ty.getTypePtr();
4477 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4478 // so make sure to widen it explicitly.
4479 if (const VectorType *VT = Base->getAs<VectorType>()) {
4480 QualType EltTy = VT->getElementType();
4481 unsigned NumElements =
4482 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4484 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4489 if (Base->isVectorType() != TyPtr->isVectorType() ||
4490 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4493 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4496 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4497 // Homogeneous aggregates for ELFv2 must have base types of float,
4498 // double, long double, or 128-bit vectors.
4499 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4500 if (BT->getKind() == BuiltinType::Float ||
4501 BT->getKind() == BuiltinType::Double ||
4502 BT->getKind() == BuiltinType::LongDouble) {
4508 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4509 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
4515 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4516 const Type *Base, uint64_t Members) const {
4517 // Vector types require one register, floating point types require one
4518 // or two registers depending on their size.
4520 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
4522 // Homogeneous Aggregates may occupy at most 8 registers.
4523 return Members * NumRegs <= 8;
4527 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
4528 Ty = useFirstFieldIfTransparentUnion(Ty);
4530 if (Ty->isAnyComplexType())
4531 return ABIArgInfo::getDirect();
4533 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4534 // or via reference (larger than 16 bytes).
4535 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
4536 uint64_t Size = getContext().getTypeSize(Ty);
4538 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4539 else if (Size < 128) {
4540 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4541 return ABIArgInfo::getDirect(CoerceTy);
4545 if (isAggregateTypeForABI(Ty)) {
4546 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
4547 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4549 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4550 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
4552 // ELFv2 homogeneous aggregates are passed as array types.
4553 const Type *Base = nullptr;
4554 uint64_t Members = 0;
4555 if (Kind == ELFv2 &&
4556 isHomogeneousAggregate(Ty, Base, Members)) {
4557 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4558 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4559 return ABIArgInfo::getDirect(CoerceTy);
4562 // If an aggregate may end up fully in registers, we do not
4563 // use the ByVal method, but pass the aggregate as array.
4564 // This is usually beneficial since we avoid forcing the
4565 // back-end to store the argument to memory.
4566 uint64_t Bits = getContext().getTypeSize(Ty);
4567 if (Bits > 0 && Bits <= 8 * GPRBits) {
4568 llvm::Type *CoerceTy;
4570 // Types up to 8 bytes are passed as integer type (which will be
4571 // properly aligned in the argument save area doubleword).
4572 if (Bits <= GPRBits)
4574 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
4575 // Larger types are passed as arrays, with the base type selected
4576 // according to the required alignment in the save area.
4578 uint64_t RegBits = ABIAlign * 8;
4579 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
4580 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4581 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4584 return ABIArgInfo::getDirect(CoerceTy);
4587 // All other aggregates are passed ByVal.
4588 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4590 /*Realign=*/TyAlign > ABIAlign);
4593 return (isPromotableTypeForABI(Ty) ?
4594 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4598 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4599 if (RetTy->isVoidType())
4600 return ABIArgInfo::getIgnore();
4602 if (RetTy->isAnyComplexType())
4603 return ABIArgInfo::getDirect();
4605 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4606 // or via reference (larger than 16 bytes).
4607 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
4608 uint64_t Size = getContext().getTypeSize(RetTy);
4610 return getNaturalAlignIndirect(RetTy);
4611 else if (Size < 128) {
4612 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4613 return ABIArgInfo::getDirect(CoerceTy);
4617 if (isAggregateTypeForABI(RetTy)) {
4618 // ELFv2 homogeneous aggregates are returned as array types.
4619 const Type *Base = nullptr;
4620 uint64_t Members = 0;
4621 if (Kind == ELFv2 &&
4622 isHomogeneousAggregate(RetTy, Base, Members)) {
4623 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4624 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4625 return ABIArgInfo::getDirect(CoerceTy);
4628 // ELFv2 small aggregates are returned in up to two registers.
4629 uint64_t Bits = getContext().getTypeSize(RetTy);
4630 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4632 return ABIArgInfo::getIgnore();
4634 llvm::Type *CoerceTy;
4635 if (Bits > GPRBits) {
4636 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
4637 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
4640 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
4641 return ABIArgInfo::getDirect(CoerceTy);
4644 // All other aggregates are returned indirectly.
4645 return getNaturalAlignIndirect(RetTy);
4648 return (isPromotableTypeForABI(RetTy) ?
4649 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4652 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
4653 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4654 QualType Ty) const {
4655 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4656 TypeInfo.second = getParamTypeAlignment(Ty);
4658 CharUnits SlotSize = CharUnits::fromQuantity(8);
4660 // If we have a complex type and the base type is smaller than 8 bytes,
4661 // the ABI calls for the real and imaginary parts to be right-adjusted
4662 // in separate doublewords. However, Clang expects us to produce a
4663 // pointer to a structure with the two parts packed tightly. So generate
4664 // loads of the real and imaginary parts relative to the va_list pointer,
4665 // and store them to a temporary structure.
4666 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4667 CharUnits EltSize = TypeInfo.first / 2;
4668 if (EltSize < SlotSize) {
4669 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4670 SlotSize * 2, SlotSize,
4671 SlotSize, /*AllowHigher*/ true);
4673 Address RealAddr = Addr;
4674 Address ImagAddr = RealAddr;
4675 if (CGF.CGM.getDataLayout().isBigEndian()) {
4676 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4677 SlotSize - EltSize);
4678 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4679 2 * SlotSize - EltSize);
4681 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4684 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4685 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4686 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4687 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4688 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4690 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4691 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4697 // Otherwise, just use the general rule.
4698 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4699 TypeInfo, SlotSize, /*AllowHigher*/ true);
4703 PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4704 llvm::Value *Address) {
4705 // This is calculated from the LLVM and GCC tables and verified
4706 // against gcc output. AFAIK all ABIs use the same encoding.
4708 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4710 llvm::IntegerType *i8 = CGF.Int8Ty;
4711 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4712 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4713 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4715 // 0-31: r0-31, the 8-byte general-purpose registers
4716 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4718 // 32-63: fp0-31, the 8-byte floating-point registers
4719 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4721 // 64-67 are various 8-byte special-purpose registers:
4726 AssignToArrayRange(Builder, Address, Eight8, 64, 67);
4728 // 68-76 are various 4-byte special-purpose registers:
4731 AssignToArrayRange(Builder, Address, Four8, 68, 76);
4733 // 77-108: v0-31, the 16-byte vector registers
4734 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4744 AssignToArrayRange(Builder, Address, Eight8, 109, 116);
4750 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4751 CodeGen::CodeGenFunction &CGF,
4752 llvm::Value *Address) const {
4754 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4758 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4759 llvm::Value *Address) const {
4761 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4764 //===----------------------------------------------------------------------===//
4765 // AArch64 ABI Implementation
4766 //===----------------------------------------------------------------------===//
4770 class AArch64ABIInfo : public SwiftABIInfo {
4781 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4782 : SwiftABIInfo(CGT), Kind(Kind) {}
4785 ABIKind getABIKind() const { return Kind; }
4786 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4788 ABIArgInfo classifyReturnType(QualType RetTy) const;
4789 ABIArgInfo classifyArgumentType(QualType RetTy) const;
4790 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4791 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4792 uint64_t Members) const override;
4794 bool isIllegalVectorType(QualType Ty) const;
4796 void computeInfo(CGFunctionInfo &FI) const override {
4797 if (!getCXXABI().classifyReturnType(FI))
4798 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4800 for (auto &it : FI.arguments())
4801 it.info = classifyArgumentType(it.type);
4804 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4805 CodeGenFunction &CGF) const;
4807 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4808 CodeGenFunction &CGF) const;
4810 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4811 QualType Ty) const override {
4812 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4813 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
4816 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
4817 ArrayRef<llvm::Type*> scalars,
4818 bool asReturnValue) const override {
4819 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4821 bool isSwiftErrorInRegister() const override {
4825 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
4826 unsigned elts) const override;
4829 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
4831 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4832 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
4834 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
4835 return "mov\tfp, fp\t\t# marker for objc_retainAutoreleaseReturnValue";
4838 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4842 bool doesReturnSlotInterfereWithArgs() const override { return false; }
4846 ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
4847 Ty = useFirstFieldIfTransparentUnion(Ty);
4849 // Handle illegal vector types here.
4850 if (isIllegalVectorType(Ty)) {
4851 uint64_t Size = getContext().getTypeSize(Ty);
4852 // Android promotes <2 x i8> to i16, not i32
4853 if (isAndroid() && (Size <= 16)) {
4854 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
4855 return ABIArgInfo::getDirect(ResType);
4858 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
4859 return ABIArgInfo::getDirect(ResType);
4862 llvm::Type *ResType =
4863 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
4864 return ABIArgInfo::getDirect(ResType);
4867 llvm::Type *ResType =
4868 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
4869 return ABIArgInfo::getDirect(ResType);
4871 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4874 if (!isAggregateTypeForABI(Ty)) {
4875 // Treat an enum type as its underlying type.
4876 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4877 Ty = EnumTy->getDecl()->getIntegerType();
4879 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4880 ? ABIArgInfo::getExtend()
4881 : ABIArgInfo::getDirect());
4884 // Structures with either a non-trivial destructor or a non-trivial
4885 // copy constructor are always indirect.
4886 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
4887 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4888 CGCXXABI::RAA_DirectInMemory);
4891 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4892 // elsewhere for GNU compatibility.
4893 uint64_t Size = getContext().getTypeSize(Ty);
4894 bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
4895 if (IsEmpty || Size == 0) {
4896 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4897 return ABIArgInfo::getIgnore();
4899 // GNU C mode. The only argument that gets ignored is an empty one with size
4901 if (IsEmpty && Size == 0)
4902 return ABIArgInfo::getIgnore();
4903 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4906 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
4907 const Type *Base = nullptr;
4908 uint64_t Members = 0;
4909 if (isHomogeneousAggregate(Ty, Base, Members)) {
4910 return ABIArgInfo::getDirect(
4911 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
4914 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4916 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
4917 // same size and alignment.
4918 if (getTarget().isRenderScriptTarget()) {
4919 return coerceToIntArray(Ty, getContext(), getVMContext());
4921 unsigned Alignment = getContext().getTypeAlign(Ty);
4922 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
4924 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4925 // For aggregates with 16-byte alignment, we use i128.
4926 if (Alignment < 128 && Size == 128) {
4927 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4928 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4930 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4933 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4936 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
4937 if (RetTy->isVoidType())
4938 return ABIArgInfo::getIgnore();
4940 // Large vector types should be returned via memory.
4941 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
4942 return getNaturalAlignIndirect(RetTy);
4944 if (!isAggregateTypeForABI(RetTy)) {
4945 // Treat an enum type as its underlying type.
4946 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4947 RetTy = EnumTy->getDecl()->getIntegerType();
4949 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4950 ? ABIArgInfo::getExtend()
4951 : ABIArgInfo::getDirect());
4954 uint64_t Size = getContext().getTypeSize(RetTy);
4955 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
4956 return ABIArgInfo::getIgnore();
4958 const Type *Base = nullptr;
4959 uint64_t Members = 0;
4960 if (isHomogeneousAggregate(RetTy, Base, Members))
4961 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4962 return ABIArgInfo::getDirect();
4964 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4966 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
4967 // same size and alignment.
4968 if (getTarget().isRenderScriptTarget()) {
4969 return coerceToIntArray(RetTy, getContext(), getVMContext());
4971 unsigned Alignment = getContext().getTypeAlign(RetTy);
4972 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
4974 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4975 // For aggregates with 16-byte alignment, we use i128.
4976 if (Alignment < 128 && Size == 128) {
4977 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4978 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4980 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4983 return getNaturalAlignIndirect(RetTy);
4986 /// isIllegalVectorType - check whether the vector type is legal for AArch64.
4987 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
4988 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4989 // Check whether VT is legal.
4990 unsigned NumElements = VT->getNumElements();
4991 uint64_t Size = getContext().getTypeSize(VT);
4992 // NumElements should be power of 2.
4993 if (!llvm::isPowerOf2_32(NumElements))
4995 return Size != 64 && (Size != 128 || NumElements == 1);
5000 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5002 unsigned elts) const {
5003 if (!llvm::isPowerOf2_32(elts))
5005 if (totalSize.getQuantity() != 8 &&
5006 (totalSize.getQuantity() != 16 || elts == 1))
5011 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5012 // Homogeneous aggregates for AAPCS64 must have base types of a floating
5013 // point type or a short-vector type. This is the same as the 32-bit ABI,
5014 // but with the difference that any floating-point type is allowed,
5015 // including __fp16.
5016 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5017 if (BT->isFloatingPoint())
5019 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5020 unsigned VecSize = getContext().getTypeSize(VT);
5021 if (VecSize == 64 || VecSize == 128)
5027 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5028 uint64_t Members) const {
5029 return Members <= 4;
5032 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
5034 CodeGenFunction &CGF) const {
5035 ABIArgInfo AI = classifyArgumentType(Ty);
5036 bool IsIndirect = AI.isIndirect();
5038 llvm::Type *BaseTy = CGF.ConvertType(Ty);
5040 BaseTy = llvm::PointerType::getUnqual(BaseTy);
5041 else if (AI.getCoerceToType())
5042 BaseTy = AI.getCoerceToType();
5044 unsigned NumRegs = 1;
5045 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5046 BaseTy = ArrTy->getElementType();
5047 NumRegs = ArrTy->getNumElements();
5049 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5051 // The AArch64 va_list type and handling is specified in the Procedure Call
5052 // Standard, section B.4:
5062 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5063 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5064 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5065 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5067 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5068 CharUnits TyAlign = TyInfo.second;
5070 Address reg_offs_p = Address::invalid();
5071 llvm::Value *reg_offs = nullptr;
5073 CharUnits reg_top_offset;
5074 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
5076 // 3 is the field number of __gr_offs
5078 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5080 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5081 reg_top_index = 1; // field number for __gr_top
5082 reg_top_offset = CharUnits::fromQuantity(8);
5083 RegSize = llvm::alignTo(RegSize, 8);
5085 // 4 is the field number of __vr_offs.
5087 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
5089 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5090 reg_top_index = 2; // field number for __vr_top
5091 reg_top_offset = CharUnits::fromQuantity(16);
5092 RegSize = 16 * NumRegs;
5095 //=======================================
5096 // Find out where argument was passed
5097 //=======================================
5099 // If reg_offs >= 0 we're already using the stack for this type of
5100 // argument. We don't want to keep updating reg_offs (in case it overflows,
5101 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5102 // whatever they get).
5103 llvm::Value *UsingStack = nullptr;
5104 UsingStack = CGF.Builder.CreateICmpSGE(
5105 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5107 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5109 // Otherwise, at least some kind of argument could go in these registers, the
5110 // question is whether this particular type is too big.
5111 CGF.EmitBlock(MaybeRegBlock);
5113 // Integer arguments may need to correct register alignment (for example a
5114 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5115 // align __gr_offs to calculate the potential address.
5116 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5117 int Align = TyAlign.getQuantity();
5119 reg_offs = CGF.Builder.CreateAdd(
5120 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5122 reg_offs = CGF.Builder.CreateAnd(
5123 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5127 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
5128 // The fact that this is done unconditionally reflects the fact that
5129 // allocating an argument to the stack also uses up all the remaining
5130 // registers of the appropriate kind.
5131 llvm::Value *NewOffset = nullptr;
5132 NewOffset = CGF.Builder.CreateAdd(
5133 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5134 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5136 // Now we're in a position to decide whether this argument really was in
5137 // registers or not.
5138 llvm::Value *InRegs = nullptr;
5139 InRegs = CGF.Builder.CreateICmpSLE(
5140 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5142 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5144 //=======================================
5145 // Argument was in registers
5146 //=======================================
5148 // Now we emit the code for if the argument was originally passed in
5149 // registers. First start the appropriate block:
5150 CGF.EmitBlock(InRegBlock);
5152 llvm::Value *reg_top = nullptr;
5153 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
5154 reg_top_offset, "reg_top_p");
5155 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
5156 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5157 CharUnits::fromQuantity(IsFPR ? 16 : 8));
5158 Address RegAddr = Address::invalid();
5159 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
5162 // If it's been passed indirectly (actually a struct), whatever we find from
5163 // stored registers or on the stack will actually be a struct **.
5164 MemTy = llvm::PointerType::getUnqual(MemTy);
5167 const Type *Base = nullptr;
5168 uint64_t NumMembers = 0;
5169 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
5170 if (IsHFA && NumMembers > 1) {
5171 // Homogeneous aggregates passed in registers will have their elements split
5172 // and stored 16-bytes apart regardless of size (they're notionally in qN,
5173 // qN+1, ...). We reload and store into a temporary local variable
5175 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
5176 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
5177 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5178 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
5179 Address Tmp = CGF.CreateTempAlloca(HFATy,
5180 std::max(TyAlign, BaseTyInfo.second));
5182 // On big-endian platforms, the value will be right-aligned in its slot.
5184 if (CGF.CGM.getDataLayout().isBigEndian() &&
5185 BaseTyInfo.first.getQuantity() < 16)
5186 Offset = 16 - BaseTyInfo.first.getQuantity();
5188 for (unsigned i = 0; i < NumMembers; ++i) {
5189 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5191 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5192 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5195 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
5197 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5198 CGF.Builder.CreateStore(Elem, StoreAddr);
5201 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
5203 // Otherwise the object is contiguous in memory.
5205 // It might be right-aligned in its slot.
5206 CharUnits SlotSize = BaseAddr.getAlignment();
5207 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
5208 (IsHFA || !isAggregateTypeForABI(Ty)) &&
5209 TyInfo.first < SlotSize) {
5210 CharUnits Offset = SlotSize - TyInfo.first;
5211 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
5214 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
5217 CGF.EmitBranch(ContBlock);
5219 //=======================================
5220 // Argument was on the stack
5221 //=======================================
5222 CGF.EmitBlock(OnStackBlock);
5224 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
5225 CharUnits::Zero(), "stack_p");
5226 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
5228 // Again, stack arguments may need realignment. In this case both integer and
5229 // floating-point ones might be affected.
5230 if (!IsIndirect && TyAlign.getQuantity() > 8) {
5231 int Align = TyAlign.getQuantity();
5233 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
5235 OnStackPtr = CGF.Builder.CreateAdd(
5236 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
5238 OnStackPtr = CGF.Builder.CreateAnd(
5239 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
5242 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
5244 Address OnStackAddr(OnStackPtr,
5245 std::max(CharUnits::fromQuantity(8), TyAlign));
5247 // All stack slots are multiples of 8 bytes.
5248 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5249 CharUnits StackSize;
5251 StackSize = StackSlotSize;
5253 StackSize = TyInfo.first.alignTo(StackSlotSize);
5255 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
5256 llvm::Value *NewStack =
5257 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
5259 // Write the new value of __stack for the next call to va_arg
5260 CGF.Builder.CreateStore(NewStack, stack_p);
5262 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
5263 TyInfo.first < StackSlotSize) {
5264 CharUnits Offset = StackSlotSize - TyInfo.first;
5265 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
5268 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
5270 CGF.EmitBranch(ContBlock);
5272 //=======================================
5274 //=======================================
5275 CGF.EmitBlock(ContBlock);
5277 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5278 OnStackAddr, OnStackBlock, "vaargs.addr");
5281 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
5287 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5288 CodeGenFunction &CGF) const {
5289 // The backend's lowering doesn't support va_arg for aggregates or
5290 // illegal vector types. Lower VAArg here for these cases and use
5291 // the LLVM va_arg instruction for everything else.
5292 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
5293 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
5295 CharUnits SlotSize = CharUnits::fromQuantity(8);
5297 // Empty records are ignored for parameter passing purposes.
5298 if (isEmptyRecord(getContext(), Ty, true)) {
5299 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5300 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5304 // The size of the actual thing passed, which might end up just
5305 // being a pointer for indirect types.
5306 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5308 // Arguments bigger than 16 bytes which aren't homogeneous
5309 // aggregates should be passed indirectly.
5310 bool IsIndirect = false;
5311 if (TyInfo.first.getQuantity() > 16) {
5312 const Type *Base = nullptr;
5313 uint64_t Members = 0;
5314 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
5317 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5318 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
5321 //===----------------------------------------------------------------------===//
5322 // ARM ABI Implementation
5323 //===----------------------------------------------------------------------===//
5327 class ARMABIInfo : public SwiftABIInfo {
5340 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5341 : SwiftABIInfo(CGT), Kind(_Kind) {
5345 bool isEABI() const {
5346 switch (getTarget().getTriple().getEnvironment()) {
5347 case llvm::Triple::Android:
5348 case llvm::Triple::EABI:
5349 case llvm::Triple::EABIHF:
5350 case llvm::Triple::GNUEABI:
5351 case llvm::Triple::GNUEABIHF:
5352 case llvm::Triple::MuslEABI:
5353 case llvm::Triple::MuslEABIHF:
5360 bool isEABIHF() const {
5361 switch (getTarget().getTriple().getEnvironment()) {
5362 case llvm::Triple::EABIHF:
5363 case llvm::Triple::GNUEABIHF:
5364 case llvm::Triple::MuslEABIHF:
5371 ABIKind getABIKind() const { return Kind; }
5374 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
5375 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
5376 bool isIllegalVectorType(QualType Ty) const;
5378 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5379 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5380 uint64_t Members) const override;
5382 void computeInfo(CGFunctionInfo &FI) const override;
5384 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5385 QualType Ty) const override;
5387 llvm::CallingConv::ID getLLVMDefaultCC() const;
5388 llvm::CallingConv::ID getABIDefaultCC() const;
5391 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5392 ArrayRef<llvm::Type*> scalars,
5393 bool asReturnValue) const override {
5394 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5396 bool isSwiftErrorInRegister() const override {
5399 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5400 unsigned elts) const override;
5403 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5405 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5406 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
5408 const ARMABIInfo &getABIInfo() const {
5409 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5412 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5416 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
5417 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
5420 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5421 llvm::Value *Address) const override {
5422 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
5424 // 0-15 are the 16 integer registers.
5425 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
5429 unsigned getSizeOfUnwindException() const override {
5430 if (getABIInfo().isEABI()) return 88;
5431 return TargetCodeGenInfo::getSizeOfUnwindException();
5434 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5435 CodeGen::CodeGenModule &CGM) const override {
5436 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5440 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5445 switch (Attr->getInterrupt()) {
5446 case ARMInterruptAttr::Generic: Kind = ""; break;
5447 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5448 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5449 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5450 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5451 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5454 llvm::Function *Fn = cast<llvm::Function>(GV);
5456 Fn->addFnAttr("interrupt", Kind);
5458 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5459 if (ABI == ARMABIInfo::APCS)
5462 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5463 // however this is not necessarily true on taking any interrupt. Instruct
5464 // the backend to perform a realignment as part of the function prologue.
5465 llvm::AttrBuilder B;
5466 B.addStackAlignmentAttr(8);
5467 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
5471 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
5473 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5474 : ARMTargetCodeGenInfo(CGT, K) {}
5476 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5477 CodeGen::CodeGenModule &CGM) const override;
5479 void getDependentLibraryOption(llvm::StringRef Lib,
5480 llvm::SmallString<24> &Opt) const override {
5481 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5484 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5485 llvm::SmallString<32> &Opt) const override {
5486 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5490 void WindowsARMTargetCodeGenInfo::setTargetAttributes(
5491 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5492 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5493 addStackProbeSizeTargetAttribute(D, GV, CGM);
5497 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
5498 if (!getCXXABI().classifyReturnType(FI))
5499 FI.getReturnInfo() =
5500 classifyReturnType(FI.getReturnType(), FI.isVariadic());
5502 for (auto &I : FI.arguments())
5503 I.info = classifyArgumentType(I.type, FI.isVariadic());
5505 // Always honor user-specified calling convention.
5506 if (FI.getCallingConvention() != llvm::CallingConv::C)
5509 llvm::CallingConv::ID cc = getRuntimeCC();
5510 if (cc != llvm::CallingConv::C)
5511 FI.setEffectiveCallingConvention(cc);
5514 /// Return the default calling convention that LLVM will use.
5515 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5516 // The default calling convention that LLVM will infer.
5517 if (isEABIHF() || getTarget().getTriple().isWatchABI())
5518 return llvm::CallingConv::ARM_AAPCS_VFP;
5520 return llvm::CallingConv::ARM_AAPCS;
5522 return llvm::CallingConv::ARM_APCS;
5525 /// Return the calling convention that our ABI would like us to use
5526 /// as the C calling convention.
5527 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
5528 switch (getABIKind()) {
5529 case APCS: return llvm::CallingConv::ARM_APCS;
5530 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5531 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
5532 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
5534 llvm_unreachable("bad ABI kind");
5537 void ARMABIInfo::setCCs() {
5538 assert(getRuntimeCC() == llvm::CallingConv::C);
5540 // Don't muddy up the IR with a ton of explicit annotations if
5541 // they'd just match what LLVM will infer from the triple.
5542 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5543 if (abiCC != getLLVMDefaultCC())
5546 // AAPCS apparently requires runtime support functions to be soft-float, but
5547 // that's almost certainly for historic reasons (Thumb1 not supporting VFP
5548 // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
5549 switch (getABIKind()) {
5552 if (abiCC != getLLVMDefaultCC())
5557 BuiltinCC = llvm::CallingConv::ARM_AAPCS;
5562 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5563 bool isVariadic) const {
5564 // 6.1.2.1 The following argument types are VFP CPRCs:
5565 // A single-precision floating-point type (including promoted
5566 // half-precision types); A double-precision floating-point type;
5567 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5568 // with a Base Type of a single- or double-precision floating-point type,
5569 // 64-bit containerized vectors or 128-bit containerized vectors with one
5570 // to four Elements.
5571 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
5573 Ty = useFirstFieldIfTransparentUnion(Ty);
5575 // Handle illegal vector types here.
5576 if (isIllegalVectorType(Ty)) {
5577 uint64_t Size = getContext().getTypeSize(Ty);
5579 llvm::Type *ResType =
5580 llvm::Type::getInt32Ty(getVMContext());
5581 return ABIArgInfo::getDirect(ResType);
5584 llvm::Type *ResType = llvm::VectorType::get(
5585 llvm::Type::getInt32Ty(getVMContext()), 2);
5586 return ABIArgInfo::getDirect(ResType);
5589 llvm::Type *ResType = llvm::VectorType::get(
5590 llvm::Type::getInt32Ty(getVMContext()), 4);
5591 return ABIArgInfo::getDirect(ResType);
5593 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5596 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5597 // unspecified. This is not done for OpenCL as it handles the half type
5598 // natively, and does not need to interwork with AAPCS code.
5599 if (Ty->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
5600 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5601 llvm::Type::getFloatTy(getVMContext()) :
5602 llvm::Type::getInt32Ty(getVMContext());
5603 return ABIArgInfo::getDirect(ResType);
5606 if (!isAggregateTypeForABI(Ty)) {
5607 // Treat an enum type as its underlying type.
5608 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
5609 Ty = EnumTy->getDecl()->getIntegerType();
5612 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5613 : ABIArgInfo::getDirect());
5616 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5617 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
5620 // Ignore empty records.
5621 if (isEmptyRecord(getContext(), Ty, true))
5622 return ABIArgInfo::getIgnore();
5624 if (IsEffectivelyAAPCS_VFP) {
5625 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5626 // into VFP registers.
5627 const Type *Base = nullptr;
5628 uint64_t Members = 0;
5629 if (isHomogeneousAggregate(Ty, Base, Members)) {
5630 assert(Base && "Base class should be set for homogeneous aggregate");
5631 // Base can be a floating-point or a vector.
5632 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
5634 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5635 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5636 // this convention even for a variadic function: the backend will use GPRs
5638 const Type *Base = nullptr;
5639 uint64_t Members = 0;
5640 if (isHomogeneousAggregate(Ty, Base, Members)) {
5641 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5643 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5644 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5648 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5649 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5650 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5651 // bigger than 128-bits, they get placed in space allocated by the caller,
5652 // and a pointer is passed.
5653 return ABIArgInfo::getIndirect(
5654 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
5657 // Support byval for ARM.
5658 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5659 // most 8-byte. We realign the indirect argument if type alignment is bigger
5660 // than ABI alignment.
5661 uint64_t ABIAlign = 4;
5662 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5663 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5664 getABIKind() == ARMABIInfo::AAPCS)
5665 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
5667 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
5668 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
5669 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5671 /*Realign=*/TyAlign > ABIAlign);
5674 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
5675 // same size and alignment.
5676 if (getTarget().isRenderScriptTarget()) {
5677 return coerceToIntArray(Ty, getContext(), getVMContext());
5680 // Otherwise, pass by coercing to a structure of the appropriate size.
5683 // FIXME: Try to match the types of the arguments more accurately where
5685 if (getContext().getTypeAlign(Ty) <= 32) {
5686 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5687 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
5689 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5690 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
5693 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
5696 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
5697 llvm::LLVMContext &VMContext) {
5698 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5699 // is called integer-like if its size is less than or equal to one word, and
5700 // the offset of each of its addressable sub-fields is zero.
5702 uint64_t Size = Context.getTypeSize(Ty);
5704 // Check that the type fits in a word.
5708 // FIXME: Handle vector types!
5709 if (Ty->isVectorType())
5712 // Float types are never treated as "integer like".
5713 if (Ty->isRealFloatingType())
5716 // If this is a builtin or pointer type then it is ok.
5717 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
5720 // Small complex integer types are "integer like".
5721 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5722 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
5724 // Single element and zero sized arrays should be allowed, by the definition
5725 // above, but they are not.
5727 // Otherwise, it must be a record type.
5728 const RecordType *RT = Ty->getAs<RecordType>();
5729 if (!RT) return false;
5731 // Ignore records with flexible arrays.
5732 const RecordDecl *RD = RT->getDecl();
5733 if (RD->hasFlexibleArrayMember())
5736 // Check that all sub-fields are at offset 0, and are themselves "integer
5738 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5740 bool HadField = false;
5742 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5743 i != e; ++i, ++idx) {
5744 const FieldDecl *FD = *i;
5746 // Bit-fields are not addressable, we only need to verify they are "integer
5747 // like". We still have to disallow a subsequent non-bitfield, for example:
5748 // struct { int : 0; int x }
5749 // is non-integer like according to gcc.
5750 if (FD->isBitField()) {
5754 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5760 // Check if this field is at offset 0.
5761 if (Layout.getFieldOffset(idx) != 0)
5764 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5767 // Only allow at most one field in a structure. This doesn't match the
5768 // wording above, but follows gcc in situations with a field following an
5770 if (!RD->isUnion()) {
5781 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5782 bool isVariadic) const {
5783 bool IsEffectivelyAAPCS_VFP =
5784 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
5786 if (RetTy->isVoidType())
5787 return ABIArgInfo::getIgnore();
5789 // Large vector types should be returned via memory.
5790 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
5791 return getNaturalAlignIndirect(RetTy);
5794 // __fp16 gets returned as if it were an int or float, but with the top 16
5795 // bits unspecified. This is not done for OpenCL as it handles the half type
5796 // natively, and does not need to interwork with AAPCS code.
5797 if (RetTy->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
5798 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5799 llvm::Type::getFloatTy(getVMContext()) :
5800 llvm::Type::getInt32Ty(getVMContext());
5801 return ABIArgInfo::getDirect(ResType);
5804 if (!isAggregateTypeForABI(RetTy)) {
5805 // Treat an enum type as its underlying type.
5806 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5807 RetTy = EnumTy->getDecl()->getIntegerType();
5809 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5810 : ABIArgInfo::getDirect();
5813 // Are we following APCS?
5814 if (getABIKind() == APCS) {
5815 if (isEmptyRecord(getContext(), RetTy, false))
5816 return ABIArgInfo::getIgnore();
5818 // Complex types are all returned as packed integers.
5820 // FIXME: Consider using 2 x vector types if the back end handles them
5822 if (RetTy->isAnyComplexType())
5823 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5824 getVMContext(), getContext().getTypeSize(RetTy)));
5826 // Integer like structures are returned in r0.
5827 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
5828 // Return in the smallest viable integer type.
5829 uint64_t Size = getContext().getTypeSize(RetTy);
5831 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5833 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5834 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5837 // Otherwise return in memory.
5838 return getNaturalAlignIndirect(RetTy);
5841 // Otherwise this is an AAPCS variant.
5843 if (isEmptyRecord(getContext(), RetTy, true))
5844 return ABIArgInfo::getIgnore();
5846 // Check for homogeneous aggregates with AAPCS-VFP.
5847 if (IsEffectivelyAAPCS_VFP) {
5848 const Type *Base = nullptr;
5849 uint64_t Members = 0;
5850 if (isHomogeneousAggregate(RetTy, Base, Members)) {
5851 assert(Base && "Base class should be set for homogeneous aggregate");
5852 // Homogeneous Aggregates are returned directly.
5853 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
5857 // Aggregates <= 4 bytes are returned in r0; other aggregates
5858 // are returned indirectly.
5859 uint64_t Size = getContext().getTypeSize(RetTy);
5861 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
5862 // same size and alignment.
5863 if (getTarget().isRenderScriptTarget()) {
5864 return coerceToIntArray(RetTy, getContext(), getVMContext());
5866 if (getDataLayout().isBigEndian())
5867 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
5868 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5870 // Return in the smallest viable integer type.
5872 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5874 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5875 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5876 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
5877 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
5878 llvm::Type *CoerceTy =
5879 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
5880 return ABIArgInfo::getDirect(CoerceTy);
5883 return getNaturalAlignIndirect(RetTy);
5886 /// isIllegalVector - check whether Ty is an illegal vector type.
5887 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
5888 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
5890 // Android shipped using Clang 3.1, which supported a slightly different
5891 // vector ABI. The primary differences were that 3-element vector types
5892 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
5893 // accepts that legacy behavior for Android only.
5894 // Check whether VT is legal.
5895 unsigned NumElements = VT->getNumElements();
5896 // NumElements should be power of 2 or equal to 3.
5897 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
5900 // Check whether VT is legal.
5901 unsigned NumElements = VT->getNumElements();
5902 uint64_t Size = getContext().getTypeSize(VT);
5903 // NumElements should be power of 2.
5904 if (!llvm::isPowerOf2_32(NumElements))
5906 // Size should be greater than 32 bits.
5913 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
5915 unsigned numElts) const {
5916 if (!llvm::isPowerOf2_32(numElts))
5918 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
5921 if (vectorSize.getQuantity() != 8 &&
5922 (vectorSize.getQuantity() != 16 || numElts == 1))
5927 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5928 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5929 // double, or 64-bit or 128-bit vectors.
5930 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5931 if (BT->getKind() == BuiltinType::Float ||
5932 BT->getKind() == BuiltinType::Double ||
5933 BT->getKind() == BuiltinType::LongDouble)
5935 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5936 unsigned VecSize = getContext().getTypeSize(VT);
5937 if (VecSize == 64 || VecSize == 128)
5943 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5944 uint64_t Members) const {
5945 return Members <= 4;
5948 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5949 QualType Ty) const {
5950 CharUnits SlotSize = CharUnits::fromQuantity(4);
5952 // Empty records are ignored for parameter passing purposes.
5953 if (isEmptyRecord(getContext(), Ty, true)) {
5954 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
5955 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5959 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5960 CharUnits TyAlignForABI = TyInfo.second;
5962 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5963 bool IsIndirect = false;
5964 const Type *Base = nullptr;
5965 uint64_t Members = 0;
5966 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
5969 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
5970 // allocated by the caller.
5971 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
5972 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5973 !isHomogeneousAggregate(Ty, Base, Members)) {
5976 // Otherwise, bound the type's ABI alignment.
5977 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5978 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
5979 // Our callers should be prepared to handle an under-aligned address.
5980 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5981 getABIKind() == ARMABIInfo::AAPCS) {
5982 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5983 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
5984 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5985 // ARMv7k allows type alignment up to 16 bytes.
5986 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5987 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
5989 TyAlignForABI = CharUnits::fromQuantity(4);
5991 TyInfo.second = TyAlignForABI;
5993 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
5994 SlotSize, /*AllowHigherAlign*/ true);
5997 //===----------------------------------------------------------------------===//
5998 // NVPTX ABI Implementation
5999 //===----------------------------------------------------------------------===//
6003 class NVPTXABIInfo : public ABIInfo {
6005 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6007 ABIArgInfo classifyReturnType(QualType RetTy) const;
6008 ABIArgInfo classifyArgumentType(QualType Ty) const;
6010 void computeInfo(CGFunctionInfo &FI) const override;
6011 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6012 QualType Ty) const override;
6015 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
6017 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
6018 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
6020 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6021 CodeGen::CodeGenModule &M) const override;
6023 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
6024 // resulting MDNode to the nvvm.annotations MDNode.
6025 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
6028 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
6029 if (RetTy->isVoidType())
6030 return ABIArgInfo::getIgnore();
6032 // note: this is different from default ABI
6033 if (!RetTy->isScalarType())
6034 return ABIArgInfo::getDirect();
6036 // Treat an enum type as its underlying type.
6037 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6038 RetTy = EnumTy->getDecl()->getIntegerType();
6040 return (RetTy->isPromotableIntegerType() ?
6041 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6044 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
6045 // Treat an enum type as its underlying type.
6046 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6047 Ty = EnumTy->getDecl()->getIntegerType();
6049 // Return aggregates type as indirect by value
6050 if (isAggregateTypeForABI(Ty))
6051 return getNaturalAlignIndirect(Ty, /* byval */ true);
6053 return (Ty->isPromotableIntegerType() ?
6054 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6057 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
6058 if (!getCXXABI().classifyReturnType(FI))
6059 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6060 for (auto &I : FI.arguments())
6061 I.info = classifyArgumentType(I.type);
6063 // Always honor user-specified calling convention.
6064 if (FI.getCallingConvention() != llvm::CallingConv::C)
6067 FI.setEffectiveCallingConvention(getRuntimeCC());
6070 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6071 QualType Ty) const {
6072 llvm_unreachable("NVPTX does not support varargs");
6075 void NVPTXTargetCodeGenInfo::
6076 setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6077 CodeGen::CodeGenModule &M) const{
6078 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6081 llvm::Function *F = cast<llvm::Function>(GV);
6083 // Perform special handling in OpenCL mode
6084 if (M.getLangOpts().OpenCL) {
6085 // Use OpenCL function attributes to check for kernel functions
6086 // By default, all functions are device functions
6087 if (FD->hasAttr<OpenCLKernelAttr>()) {
6088 // OpenCL __kernel functions get kernel metadata
6089 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6090 addNVVMMetadata(F, "kernel", 1);
6091 // And kernel functions are not subject to inlining
6092 F->addFnAttr(llvm::Attribute::NoInline);
6096 // Perform special handling in CUDA mode.
6097 if (M.getLangOpts().CUDA) {
6098 // CUDA __global__ functions get a kernel metadata entry. Since
6099 // __global__ functions cannot be called from the device, we do not
6100 // need to set the noinline attribute.
6101 if (FD->hasAttr<CUDAGlobalAttr>()) {
6102 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6103 addNVVMMetadata(F, "kernel", 1);
6105 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
6106 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
6107 llvm::APSInt MaxThreads(32);
6108 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
6110 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
6112 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
6113 // not specified in __launch_bounds__ or if the user specified a 0 value,
6114 // we don't have to add a PTX directive.
6115 if (Attr->getMinBlocks()) {
6116 llvm::APSInt MinBlocks(32);
6117 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
6119 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
6120 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
6126 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
6128 llvm::Module *M = F->getParent();
6129 llvm::LLVMContext &Ctx = M->getContext();
6131 // Get "nvvm.annotations" metadata node
6132 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
6134 llvm::Metadata *MDVals[] = {
6135 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
6136 llvm::ConstantAsMetadata::get(
6137 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
6138 // Append metadata to nvvm.annotations
6139 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6143 //===----------------------------------------------------------------------===//
6144 // SystemZ ABI Implementation
6145 //===----------------------------------------------------------------------===//
6149 class SystemZABIInfo : public SwiftABIInfo {
6153 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
6154 : SwiftABIInfo(CGT), HasVector(HV) {}
6156 bool isPromotableIntegerType(QualType Ty) const;
6157 bool isCompoundType(QualType Ty) const;
6158 bool isVectorArgumentType(QualType Ty) const;
6159 bool isFPArgumentType(QualType Ty) const;
6160 QualType GetSingleElementType(QualType Ty) const;
6162 ABIArgInfo classifyReturnType(QualType RetTy) const;
6163 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
6165 void computeInfo(CGFunctionInfo &FI) const override {
6166 if (!getCXXABI().classifyReturnType(FI))
6167 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6168 for (auto &I : FI.arguments())
6169 I.info = classifyArgumentType(I.type);
6172 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6173 QualType Ty) const override;
6175 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
6176 ArrayRef<llvm::Type*> scalars,
6177 bool asReturnValue) const override {
6178 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6180 bool isSwiftErrorInRegister() const override {
6185 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
6187 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
6188 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
6193 bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
6194 // Treat an enum type as its underlying type.
6195 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6196 Ty = EnumTy->getDecl()->getIntegerType();
6198 // Promotable integer types are required to be promoted by the ABI.
6199 if (Ty->isPromotableIntegerType())
6202 // 32-bit values must also be promoted.
6203 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6204 switch (BT->getKind()) {
6205 case BuiltinType::Int:
6206 case BuiltinType::UInt:
6214 bool SystemZABIInfo::isCompoundType(QualType Ty) const {
6215 return (Ty->isAnyComplexType() ||
6216 Ty->isVectorType() ||
6217 isAggregateTypeForABI(Ty));
6220 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
6221 return (HasVector &&
6222 Ty->isVectorType() &&
6223 getContext().getTypeSize(Ty) <= 128);
6226 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
6227 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6228 switch (BT->getKind()) {
6229 case BuiltinType::Float:
6230 case BuiltinType::Double:
6239 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
6240 if (const RecordType *RT = Ty->getAsStructureType()) {
6241 const RecordDecl *RD = RT->getDecl();
6244 // If this is a C++ record, check the bases first.
6245 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6246 for (const auto &I : CXXRD->bases()) {
6247 QualType Base = I.getType();
6249 // Empty bases don't affect things either way.
6250 if (isEmptyRecord(getContext(), Base, true))
6253 if (!Found.isNull())
6255 Found = GetSingleElementType(Base);
6258 // Check the fields.
6259 for (const auto *FD : RD->fields()) {
6260 // For compatibility with GCC, ignore empty bitfields in C++ mode.
6261 // Unlike isSingleElementStruct(), empty structure and array fields
6262 // do count. So do anonymous bitfields that aren't zero-sized.
6263 if (getContext().getLangOpts().CPlusPlus &&
6264 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
6267 // Unlike isSingleElementStruct(), arrays do not count.
6268 // Nested structures still do though.
6269 if (!Found.isNull())
6271 Found = GetSingleElementType(FD->getType());
6274 // Unlike isSingleElementStruct(), trailing padding is allowed.
6275 // An 8-byte aligned struct s { float f; } is passed as a double.
6276 if (!Found.isNull())
6283 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6284 QualType Ty) const {
6285 // Assume that va_list type is correct; should be pointer to LLVM type:
6289 // i8 *__overflow_arg_area;
6290 // i8 *__reg_save_area;
6293 // Every non-vector argument occupies 8 bytes and is passed by preference
6294 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
6295 // always passed on the stack.
6296 Ty = getContext().getCanonicalType(Ty);
6297 auto TyInfo = getContext().getTypeInfoInChars(Ty);
6298 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
6299 llvm::Type *DirectTy = ArgTy;
6300 ABIArgInfo AI = classifyArgumentType(Ty);
6301 bool IsIndirect = AI.isIndirect();
6302 bool InFPRs = false;
6303 bool IsVector = false;
6304 CharUnits UnpaddedSize;
6305 CharUnits DirectAlign;
6307 DirectTy = llvm::PointerType::getUnqual(DirectTy);
6308 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
6310 if (AI.getCoerceToType())
6311 ArgTy = AI.getCoerceToType();
6312 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
6313 IsVector = ArgTy->isVectorTy();
6314 UnpaddedSize = TyInfo.first;
6315 DirectAlign = TyInfo.second;
6317 CharUnits PaddedSize = CharUnits::fromQuantity(8);
6318 if (IsVector && UnpaddedSize > PaddedSize)
6319 PaddedSize = CharUnits::fromQuantity(16);
6320 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
6322 CharUnits Padding = (PaddedSize - UnpaddedSize);
6324 llvm::Type *IndexTy = CGF.Int64Ty;
6325 llvm::Value *PaddedSizeV =
6326 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
6329 // Work out the address of a vector argument on the stack.
6330 // Vector arguments are always passed in the high bits of a
6331 // single (8 byte) or double (16 byte) stack slot.
6332 Address OverflowArgAreaPtr =
6333 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
6334 "overflow_arg_area_ptr");
6335 Address OverflowArgArea =
6336 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6339 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
6341 // Update overflow_arg_area_ptr pointer
6342 llvm::Value *NewOverflowArgArea =
6343 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6344 "overflow_arg_area");
6345 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6350 assert(PaddedSize.getQuantity() == 8);
6352 unsigned MaxRegs, RegCountField, RegSaveIndex;
6353 CharUnits RegPadding;
6355 MaxRegs = 4; // Maximum of 4 FPR arguments
6356 RegCountField = 1; // __fpr
6357 RegSaveIndex = 16; // save offset for f0
6358 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
6360 MaxRegs = 5; // Maximum of 5 GPR arguments
6361 RegCountField = 0; // __gpr
6362 RegSaveIndex = 2; // save offset for r2
6363 RegPadding = Padding; // values are passed in the low bits of a GPR
6366 Address RegCountPtr = CGF.Builder.CreateStructGEP(
6367 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
6369 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
6370 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
6371 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
6374 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6375 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
6376 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6377 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
6379 // Emit code to load the value if it was passed in registers.
6380 CGF.EmitBlock(InRegBlock);
6382 // Work out the address of an argument register.
6383 llvm::Value *ScaledRegCount =
6384 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
6385 llvm::Value *RegBase =
6386 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
6387 + RegPadding.getQuantity());
6388 llvm::Value *RegOffset =
6389 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
6390 Address RegSaveAreaPtr =
6391 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
6392 "reg_save_area_ptr");
6393 llvm::Value *RegSaveArea =
6394 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
6395 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
6399 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
6401 // Update the register count
6402 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
6403 llvm::Value *NewRegCount =
6404 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
6405 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
6406 CGF.EmitBranch(ContBlock);
6408 // Emit code to load the value if it was passed in memory.
6409 CGF.EmitBlock(InMemBlock);
6411 // Work out the address of a stack argument.
6412 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
6413 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
6414 Address OverflowArgArea =
6415 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6417 Address RawMemAddr =
6418 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6420 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
6422 // Update overflow_arg_area_ptr pointer
6423 llvm::Value *NewOverflowArgArea =
6424 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6425 "overflow_arg_area");
6426 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6427 CGF.EmitBranch(ContBlock);
6429 // Return the appropriate result.
6430 CGF.EmitBlock(ContBlock);
6431 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6432 MemAddr, InMemBlock, "va_arg.addr");
6435 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6441 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6442 if (RetTy->isVoidType())
6443 return ABIArgInfo::getIgnore();
6444 if (isVectorArgumentType(RetTy))
6445 return ABIArgInfo::getDirect();
6446 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
6447 return getNaturalAlignIndirect(RetTy);
6448 return (isPromotableIntegerType(RetTy) ?
6449 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6452 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6453 // Handle the generic C++ ABI.
6454 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6455 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6457 // Integers and enums are extended to full register width.
6458 if (isPromotableIntegerType(Ty))
6459 return ABIArgInfo::getExtend();
6461 // Handle vector types and vector-like structure types. Note that
6462 // as opposed to float-like structure types, we do not allow any
6463 // padding for vector-like structures, so verify the sizes match.
6464 uint64_t Size = getContext().getTypeSize(Ty);
6465 QualType SingleElementTy = GetSingleElementType(Ty);
6466 if (isVectorArgumentType(SingleElementTy) &&
6467 getContext().getTypeSize(SingleElementTy) == Size)
6468 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6470 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
6471 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
6472 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6474 // Handle small structures.
6475 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6476 // Structures with flexible arrays have variable length, so really
6477 // fail the size test above.
6478 const RecordDecl *RD = RT->getDecl();
6479 if (RD->hasFlexibleArrayMember())
6480 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6482 // The structure is passed as an unextended integer, a float, or a double.
6484 if (isFPArgumentType(SingleElementTy)) {
6485 assert(Size == 32 || Size == 64);
6487 PassTy = llvm::Type::getFloatTy(getVMContext());
6489 PassTy = llvm::Type::getDoubleTy(getVMContext());
6491 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6492 return ABIArgInfo::getDirect(PassTy);
6495 // Non-structure compounds are passed indirectly.
6496 if (isCompoundType(Ty))
6497 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6499 return ABIArgInfo::getDirect(nullptr);
6502 //===----------------------------------------------------------------------===//
6503 // MSP430 ABI Implementation
6504 //===----------------------------------------------------------------------===//
6508 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6510 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6511 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
6512 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6513 CodeGen::CodeGenModule &M) const override;
6518 void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
6519 llvm::GlobalValue *GV,
6520 CodeGen::CodeGenModule &M) const {
6521 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
6522 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6523 // Handle 'interrupt' attribute:
6524 llvm::Function *F = cast<llvm::Function>(GV);
6526 // Step 1: Set ISR calling convention.
6527 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6529 // Step 2: Add attributes goodness.
6530 F->addFnAttr(llvm::Attribute::NoInline);
6532 // Step 3: Emit ISR vector alias.
6533 unsigned Num = attr->getNumber() / 2;
6534 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6535 "__isr_" + Twine(Num), F);
6540 //===----------------------------------------------------------------------===//
6541 // MIPS ABI Implementation. This works for both little-endian and
6542 // big-endian variants.
6543 //===----------------------------------------------------------------------===//
6546 class MipsABIInfo : public ABIInfo {
6548 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6549 void CoerceToIntArgs(uint64_t TySize,
6550 SmallVectorImpl<llvm::Type *> &ArgList) const;
6551 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
6552 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
6553 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
6555 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
6556 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
6557 StackAlignInBytes(IsO32 ? 8 : 16) {}
6559 ABIArgInfo classifyReturnType(QualType RetTy) const;
6560 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
6561 void computeInfo(CGFunctionInfo &FI) const override;
6562 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6563 QualType Ty) const override;
6564 bool shouldSignExtUnsignedType(QualType Ty) const override;
6567 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
6568 unsigned SizeOfUnwindException;
6570 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6571 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
6572 SizeOfUnwindException(IsO32 ? 24 : 32) {}
6574 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
6578 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6579 CodeGen::CodeGenModule &CGM) const override {
6580 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6582 llvm::Function *Fn = cast<llvm::Function>(GV);
6583 if (FD->hasAttr<Mips16Attr>()) {
6584 Fn->addFnAttr("mips16");
6586 else if (FD->hasAttr<NoMips16Attr>()) {
6587 Fn->addFnAttr("nomips16");
6590 if (FD->hasAttr<MicroMipsAttr>())
6591 Fn->addFnAttr("micromips");
6592 else if (FD->hasAttr<NoMicroMipsAttr>())
6593 Fn->addFnAttr("nomicromips");
6595 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6600 switch (Attr->getInterrupt()) {
6601 case MipsInterruptAttr::eic: Kind = "eic"; break;
6602 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6603 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6604 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6605 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6606 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6607 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6608 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6609 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6612 Fn->addFnAttr("interrupt", Kind);
6616 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6617 llvm::Value *Address) const override;
6619 unsigned getSizeOfUnwindException() const override {
6620 return SizeOfUnwindException;
6625 void MipsABIInfo::CoerceToIntArgs(
6626 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
6627 llvm::IntegerType *IntTy =
6628 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
6630 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6631 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6632 ArgList.push_back(IntTy);
6634 // If necessary, add one more integer type to ArgList.
6635 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6638 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
6641 // In N32/64, an aligned double precision floating point field is passed in
6643 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
6644 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6647 CoerceToIntArgs(TySize, ArgList);
6648 return llvm::StructType::get(getVMContext(), ArgList);
6651 if (Ty->isComplexType())
6652 return CGT.ConvertType(Ty);
6654 const RecordType *RT = Ty->getAs<RecordType>();
6656 // Unions/vectors are passed in integer registers.
6657 if (!RT || !RT->isStructureOrClassType()) {
6658 CoerceToIntArgs(TySize, ArgList);
6659 return llvm::StructType::get(getVMContext(), ArgList);
6662 const RecordDecl *RD = RT->getDecl();
6663 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6664 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
6666 uint64_t LastOffset = 0;
6668 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6670 // Iterate over fields in the struct/class and check if there are any aligned
6672 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6673 i != e; ++i, ++idx) {
6674 const QualType Ty = i->getType();
6675 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6677 if (!BT || BT->getKind() != BuiltinType::Double)
6680 uint64_t Offset = Layout.getFieldOffset(idx);
6681 if (Offset % 64) // Ignore doubles that are not aligned.
6684 // Add ((Offset - LastOffset) / 64) args of type i64.
6685 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6686 ArgList.push_back(I64);
6689 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6690 LastOffset = Offset + 64;
6693 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6694 ArgList.append(IntArgList.begin(), IntArgList.end());
6696 return llvm::StructType::get(getVMContext(), ArgList);
6699 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6700 uint64_t Offset) const {
6701 if (OrigOffset + MinABIStackAlignInBytes > Offset)
6704 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
6708 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
6709 Ty = useFirstFieldIfTransparentUnion(Ty);
6711 uint64_t OrigOffset = Offset;
6712 uint64_t TySize = getContext().getTypeSize(Ty);
6713 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
6715 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6716 (uint64_t)StackAlignInBytes);
6717 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6718 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
6720 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
6721 // Ignore empty aggregates.
6723 return ABIArgInfo::getIgnore();
6725 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
6726 Offset = OrigOffset + MinABIStackAlignInBytes;
6727 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6730 // Use indirect if the aggregate cannot fit into registers for
6731 // passing arguments according to the ABI
6732 unsigned Threshold = IsO32 ? 16 : 64;
6734 if(getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(Threshold))
6735 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align), true,
6736 getContext().getTypeAlign(Ty) / 8 > Align);
6738 // If we have reached here, aggregates are passed directly by coercing to
6739 // another structure type. Padding is inserted if the offset of the
6740 // aggregate is unaligned.
6741 ABIArgInfo ArgInfo =
6742 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6743 getPaddingType(OrigOffset, CurrOffset));
6744 ArgInfo.setInReg(true);
6748 // Treat an enum type as its underlying type.
6749 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6750 Ty = EnumTy->getDecl()->getIntegerType();
6752 // All integral types are promoted to the GPR width.
6753 if (Ty->isIntegralOrEnumerationType())
6754 return ABIArgInfo::getExtend();
6756 return ABIArgInfo::getDirect(
6757 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
6761 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
6762 const RecordType *RT = RetTy->getAs<RecordType>();
6763 SmallVector<llvm::Type*, 8> RTList;
6765 if (RT && RT->isStructureOrClassType()) {
6766 const RecordDecl *RD = RT->getDecl();
6767 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6768 unsigned FieldCnt = Layout.getFieldCount();
6770 // N32/64 returns struct/classes in floating point registers if the
6771 // following conditions are met:
6772 // 1. The size of the struct/class is no larger than 128-bit.
6773 // 2. The struct/class has one or two fields all of which are floating
6775 // 3. The offset of the first field is zero (this follows what gcc does).
6777 // Any other composite results are returned in integer registers.
6779 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6780 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6781 for (; b != e; ++b) {
6782 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
6784 if (!BT || !BT->isFloatingPoint())
6787 RTList.push_back(CGT.ConvertType(b->getType()));
6791 return llvm::StructType::get(getVMContext(), RTList,
6792 RD->hasAttr<PackedAttr>());
6798 CoerceToIntArgs(Size, RTList);
6799 return llvm::StructType::get(getVMContext(), RTList);
6802 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
6803 uint64_t Size = getContext().getTypeSize(RetTy);
6805 if (RetTy->isVoidType())
6806 return ABIArgInfo::getIgnore();
6808 // O32 doesn't treat zero-sized structs differently from other structs.
6809 // However, N32/N64 ignores zero sized return values.
6810 if (!IsO32 && Size == 0)
6811 return ABIArgInfo::getIgnore();
6813 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
6815 if (RetTy->isAnyComplexType())
6816 return ABIArgInfo::getDirect();
6818 // O32 returns integer vectors in registers and N32/N64 returns all small
6819 // aggregates in registers.
6821 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6822 ABIArgInfo ArgInfo =
6823 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6824 ArgInfo.setInReg(true);
6829 return getNaturalAlignIndirect(RetTy);
6832 // Treat an enum type as its underlying type.
6833 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6834 RetTy = EnumTy->getDecl()->getIntegerType();
6836 return (RetTy->isPromotableIntegerType() ?
6837 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6840 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
6841 ABIArgInfo &RetInfo = FI.getReturnInfo();
6842 if (!getCXXABI().classifyReturnType(FI))
6843 RetInfo = classifyReturnType(FI.getReturnType());
6845 // Check if a pointer to an aggregate is passed as a hidden argument.
6846 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
6848 for (auto &I : FI.arguments())
6849 I.info = classifyArgumentType(I.type, Offset);
6852 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6853 QualType OrigTy) const {
6854 QualType Ty = OrigTy;
6856 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6857 // Pointers are also promoted in the same way but this only matters for N32.
6858 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
6859 unsigned PtrWidth = getTarget().getPointerWidth(0);
6860 bool DidPromote = false;
6861 if ((Ty->isIntegerType() &&
6862 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
6863 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
6865 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6866 Ty->isSignedIntegerType());
6869 auto TyInfo = getContext().getTypeInfoInChars(Ty);
6871 // The alignment of things in the argument area is never larger than
6872 // StackAlignInBytes.
6874 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6876 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6877 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6879 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6880 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6883 // If there was a promotion, "unpromote" into a temporary.
6884 // TODO: can we just use a pointer into a subset of the original slot?
6886 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6887 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6889 // Truncate down to the right width.
6890 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
6892 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
6893 if (OrigTy->isPointerType())
6894 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
6896 CGF.Builder.CreateStore(V, Temp);
6903 bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
6904 int TySize = getContext().getTypeSize(Ty);
6906 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
6907 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
6914 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6915 llvm::Value *Address) const {
6916 // This information comes from gcc's implementation, which seems to
6917 // as canonical as it gets.
6919 // Everything on MIPS is 4 bytes. Double-precision FP registers
6920 // are aliased to pairs of single-precision FP registers.
6921 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
6923 // 0-31 are the general purpose registers, $0 - $31.
6924 // 32-63 are the floating-point registers, $f0 - $f31.
6925 // 64 and 65 are the multiply/divide registers, $hi and $lo.
6926 // 66 is the (notional, I think) register for signal-handler return.
6927 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
6929 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
6930 // They are one bit wide and ignored here.
6932 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
6933 // (coprocessor 1 is the FP unit)
6934 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
6935 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
6936 // 176-181 are the DSP accumulator registers.
6937 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
6941 //===----------------------------------------------------------------------===//
6942 // AVR ABI Implementation.
6943 //===----------------------------------------------------------------------===//
6946 class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
6948 AVRTargetCodeGenInfo(CodeGenTypes &CGT)
6949 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) { }
6951 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6952 CodeGen::CodeGenModule &CGM) const override {
6953 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
6955 auto *Fn = cast<llvm::Function>(GV);
6957 if (FD->getAttr<AVRInterruptAttr>())
6958 Fn->addFnAttr("interrupt");
6960 if (FD->getAttr<AVRSignalAttr>())
6961 Fn->addFnAttr("signal");
6966 //===----------------------------------------------------------------------===//
6967 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
6968 // Currently subclassed only to implement custom OpenCL C function attribute
6970 //===----------------------------------------------------------------------===//
6974 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
6976 TCETargetCodeGenInfo(CodeGenTypes &CGT)
6977 : DefaultTargetCodeGenInfo(CGT) {}
6979 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6980 CodeGen::CodeGenModule &M) const override;
6983 void TCETargetCodeGenInfo::setTargetAttributes(
6984 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
6985 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6988 llvm::Function *F = cast<llvm::Function>(GV);
6990 if (M.getLangOpts().OpenCL) {
6991 if (FD->hasAttr<OpenCLKernelAttr>()) {
6992 // OpenCL C Kernel functions are not subject to inlining
6993 F->addFnAttr(llvm::Attribute::NoInline);
6994 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
6996 // Convert the reqd_work_group_size() attributes to metadata.
6997 llvm::LLVMContext &Context = F->getContext();
6998 llvm::NamedMDNode *OpenCLMetadata =
6999 M.getModule().getOrInsertNamedMetadata(
7000 "opencl.kernel_wg_size_info");
7002 SmallVector<llvm::Metadata *, 5> Operands;
7003 Operands.push_back(llvm::ConstantAsMetadata::get(F));
7006 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7007 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
7009 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7010 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
7012 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7013 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
7015 // Add a boolean constant operand for "required" (true) or "hint"
7016 // (false) for implementing the work_group_size_hint attr later.
7017 // Currently always true as the hint is not yet implemented.
7019 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
7020 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
7028 //===----------------------------------------------------------------------===//
7029 // Hexagon ABI Implementation
7030 //===----------------------------------------------------------------------===//
7034 class HexagonABIInfo : public ABIInfo {
7038 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7042 ABIArgInfo classifyReturnType(QualType RetTy) const;
7043 ABIArgInfo classifyArgumentType(QualType RetTy) const;
7045 void computeInfo(CGFunctionInfo &FI) const override;
7047 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7048 QualType Ty) const override;
7051 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
7053 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
7054 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
7056 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
7063 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
7064 if (!getCXXABI().classifyReturnType(FI))
7065 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7066 for (auto &I : FI.arguments())
7067 I.info = classifyArgumentType(I.type);
7070 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
7071 if (!isAggregateTypeForABI(Ty)) {
7072 // Treat an enum type as its underlying type.
7073 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7074 Ty = EnumTy->getDecl()->getIntegerType();
7076 return (Ty->isPromotableIntegerType() ?
7077 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
7080 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7081 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7083 // Ignore empty records.
7084 if (isEmptyRecord(getContext(), Ty, true))
7085 return ABIArgInfo::getIgnore();
7087 uint64_t Size = getContext().getTypeSize(Ty);
7089 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
7090 // Pass in the smallest viable integer type.
7092 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7094 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7096 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7098 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7101 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
7102 if (RetTy->isVoidType())
7103 return ABIArgInfo::getIgnore();
7105 // Large vector types should be returned via memory.
7106 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
7107 return getNaturalAlignIndirect(RetTy);
7109 if (!isAggregateTypeForABI(RetTy)) {
7110 // Treat an enum type as its underlying type.
7111 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7112 RetTy = EnumTy->getDecl()->getIntegerType();
7114 return (RetTy->isPromotableIntegerType() ?
7115 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
7118 if (isEmptyRecord(getContext(), RetTy, true))
7119 return ABIArgInfo::getIgnore();
7121 // Aggregates <= 8 bytes are returned in r0; other aggregates
7122 // are returned indirectly.
7123 uint64_t Size = getContext().getTypeSize(RetTy);
7125 // Return in the smallest viable integer type.
7127 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7129 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7131 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7132 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7135 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
7138 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7139 QualType Ty) const {
7140 // FIXME: Someone needs to audit that this handle alignment correctly.
7141 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7142 getContext().getTypeInfoInChars(Ty),
7143 CharUnits::fromQuantity(4),
7144 /*AllowHigherAlign*/ true);
7147 //===----------------------------------------------------------------------===//
7148 // Lanai ABI Implementation
7149 //===----------------------------------------------------------------------===//
7152 class LanaiABIInfo : public DefaultABIInfo {
7154 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7156 bool shouldUseInReg(QualType Ty, CCState &State) const;
7158 void computeInfo(CGFunctionInfo &FI) const override {
7159 CCState State(FI.getCallingConvention());
7160 // Lanai uses 4 registers to pass arguments unless the function has the
7161 // regparm attribute set.
7162 if (FI.getHasRegParm()) {
7163 State.FreeRegs = FI.getRegParm();
7168 if (!getCXXABI().classifyReturnType(FI))
7169 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7170 for (auto &I : FI.arguments())
7171 I.info = classifyArgumentType(I.type, State);
7174 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
7175 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
7177 } // end anonymous namespace
7179 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
7180 unsigned Size = getContext().getTypeSize(Ty);
7181 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
7183 if (SizeInRegs == 0)
7186 if (SizeInRegs > State.FreeRegs) {
7191 State.FreeRegs -= SizeInRegs;
7196 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
7197 CCState &State) const {
7199 if (State.FreeRegs) {
7200 --State.FreeRegs; // Non-byval indirects just use one pointer.
7201 return getNaturalAlignIndirectInReg(Ty);
7203 return getNaturalAlignIndirect(Ty, false);
7206 // Compute the byval alignment.
7207 const unsigned MinABIStackAlignInBytes = 4;
7208 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
7209 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
7210 /*Realign=*/TypeAlign >
7211 MinABIStackAlignInBytes);
7214 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
7215 CCState &State) const {
7216 // Check with the C++ ABI first.
7217 const RecordType *RT = Ty->getAs<RecordType>();
7219 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
7220 if (RAA == CGCXXABI::RAA_Indirect) {
7221 return getIndirectResult(Ty, /*ByVal=*/false, State);
7222 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
7223 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
7227 if (isAggregateTypeForABI(Ty)) {
7228 // Structures with flexible arrays are always indirect.
7229 if (RT && RT->getDecl()->hasFlexibleArrayMember())
7230 return getIndirectResult(Ty, /*ByVal=*/true, State);
7232 // Ignore empty structs/unions.
7233 if (isEmptyRecord(getContext(), Ty, true))
7234 return ABIArgInfo::getIgnore();
7236 llvm::LLVMContext &LLVMContext = getVMContext();
7237 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
7238 if (SizeInRegs <= State.FreeRegs) {
7239 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
7240 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
7241 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
7242 State.FreeRegs -= SizeInRegs;
7243 return ABIArgInfo::getDirectInReg(Result);
7247 return getIndirectResult(Ty, true, State);
7250 // Treat an enum type as its underlying type.
7251 if (const auto *EnumTy = Ty->getAs<EnumType>())
7252 Ty = EnumTy->getDecl()->getIntegerType();
7254 bool InReg = shouldUseInReg(Ty, State);
7255 if (Ty->isPromotableIntegerType()) {
7257 return ABIArgInfo::getDirectInReg();
7258 return ABIArgInfo::getExtend();
7261 return ABIArgInfo::getDirectInReg();
7262 return ABIArgInfo::getDirect();
7266 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
7268 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7269 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
7273 //===----------------------------------------------------------------------===//
7274 // AMDGPU ABI Implementation
7275 //===----------------------------------------------------------------------===//
7279 class AMDGPUABIInfo final : public DefaultABIInfo {
7281 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7284 ABIArgInfo classifyArgumentType(QualType Ty) const;
7286 void computeInfo(CGFunctionInfo &FI) const override;
7289 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
7290 if (!getCXXABI().classifyReturnType(FI))
7291 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7293 unsigned CC = FI.getCallingConvention();
7294 for (auto &Arg : FI.arguments())
7295 if (CC == llvm::CallingConv::AMDGPU_KERNEL)
7296 Arg.info = classifyArgumentType(Arg.type);
7298 Arg.info = DefaultABIInfo::classifyArgumentType(Arg.type);
7301 /// \brief Classify argument of given type \p Ty.
7302 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty) const {
7303 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7305 return DefaultABIInfo::classifyArgumentType(Ty);
7308 // Coerce single element structs to its element.
7309 if (StrTy->getNumElements() == 1) {
7310 return ABIArgInfo::getDirect();
7313 // If we set CanBeFlattened to true, CodeGen will expand the struct to its
7314 // individual elements, which confuses the Clover OpenCL backend; therefore we
7315 // have to set it to false here. Other args of getDirect() are just defaults.
7316 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
7319 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
7321 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
7322 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {}
7323 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7324 CodeGen::CodeGenModule &M) const override;
7325 unsigned getOpenCLKernelCallingConv() const override;
7327 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
7328 llvm::PointerType *T, QualType QT) const override;
7330 unsigned getASTAllocaAddressSpace() const override {
7331 return LangAS::FirstTargetAddressSpace +
7332 getABIInfo().getDataLayout().getAllocaAddrSpace();
7337 static void appendOpenCLVersionMD (CodeGen::CodeGenModule &CGM);
7339 void AMDGPUTargetCodeGenInfo::setTargetAttributes(
7341 llvm::GlobalValue *GV,
7342 CodeGen::CodeGenModule &M) const {
7343 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7347 llvm::Function *F = cast<llvm::Function>(GV);
7349 const auto *ReqdWGS = M.getLangOpts().OpenCL ?
7350 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
7351 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
7352 if (ReqdWGS || FlatWGS) {
7353 unsigned Min = FlatWGS ? FlatWGS->getMin() : 0;
7354 unsigned Max = FlatWGS ? FlatWGS->getMax() : 0;
7355 if (ReqdWGS && Min == 0 && Max == 0)
7356 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
7359 assert(Min <= Max && "Min must be less than or equal Max");
7361 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
7362 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
7364 assert(Max == 0 && "Max must be zero");
7367 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
7368 unsigned Min = Attr->getMin();
7369 unsigned Max = Attr->getMax();
7372 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
7374 std::string AttrVal = llvm::utostr(Min);
7376 AttrVal = AttrVal + "," + llvm::utostr(Max);
7377 F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
7379 assert(Max == 0 && "Max must be zero");
7382 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
7383 unsigned NumSGPR = Attr->getNumSGPR();
7386 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
7389 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
7390 uint32_t NumVGPR = Attr->getNumVGPR();
7393 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
7396 appendOpenCLVersionMD(M);
7399 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7400 return llvm::CallingConv::AMDGPU_KERNEL;
7403 // Currently LLVM assumes null pointers always have value 0,
7404 // which results in incorrectly transformed IR. Therefore, instead of
7405 // emitting null pointers in private and local address spaces, a null
7406 // pointer in generic address space is emitted which is casted to a
7407 // pointer in local or private address space.
7408 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
7409 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
7410 QualType QT) const {
7411 if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
7412 return llvm::ConstantPointerNull::get(PT);
7414 auto &Ctx = CGM.getContext();
7415 auto NPT = llvm::PointerType::get(PT->getElementType(),
7416 Ctx.getTargetAddressSpace(LangAS::opencl_generic));
7417 return llvm::ConstantExpr::getAddrSpaceCast(
7418 llvm::ConstantPointerNull::get(NPT), PT);
7421 //===----------------------------------------------------------------------===//
7422 // SPARC v8 ABI Implementation.
7423 // Based on the SPARC Compliance Definition version 2.4.1.
7425 // Ensures that complex values are passed in registers.
7428 class SparcV8ABIInfo : public DefaultABIInfo {
7430 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7433 ABIArgInfo classifyReturnType(QualType RetTy) const;
7434 void computeInfo(CGFunctionInfo &FI) const override;
7436 } // end anonymous namespace
7440 SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
7441 if (Ty->isAnyComplexType()) {
7442 return ABIArgInfo::getDirect();
7445 return DefaultABIInfo::classifyReturnType(Ty);
7449 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7451 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7452 for (auto &Arg : FI.arguments())
7453 Arg.info = classifyArgumentType(Arg.type);
7457 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
7459 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
7460 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
7462 } // end anonymous namespace
7464 //===----------------------------------------------------------------------===//
7465 // SPARC v9 ABI Implementation.
7466 // Based on the SPARC Compliance Definition version 2.4.1.
7468 // Function arguments a mapped to a nominal "parameter array" and promoted to
7469 // registers depending on their type. Each argument occupies 8 or 16 bytes in
7470 // the array, structs larger than 16 bytes are passed indirectly.
7472 // One case requires special care:
7479 // When a struct mixed is passed by value, it only occupies 8 bytes in the
7480 // parameter array, but the int is passed in an integer register, and the float
7481 // is passed in a floating point register. This is represented as two arguments
7482 // with the LLVM IR inreg attribute:
7484 // declare void f(i32 inreg %i, float inreg %f)
7486 // The code generator will only allocate 4 bytes from the parameter array for
7487 // the inreg arguments. All other arguments are allocated a multiple of 8
7491 class SparcV9ABIInfo : public ABIInfo {
7493 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7496 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
7497 void computeInfo(CGFunctionInfo &FI) const override;
7498 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7499 QualType Ty) const override;
7501 // Coercion type builder for structs passed in registers. The coercion type
7502 // serves two purposes:
7504 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
7506 // 2. Expose aligned floating point elements as first-level elements, so the
7507 // code generator knows to pass them in floating point registers.
7509 // We also compute the InReg flag which indicates that the struct contains
7510 // aligned 32-bit floats.
7512 struct CoerceBuilder {
7513 llvm::LLVMContext &Context;
7514 const llvm::DataLayout &DL;
7515 SmallVector<llvm::Type*, 8> Elems;
7519 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
7520 : Context(c), DL(dl), Size(0), InReg(false) {}
7522 // Pad Elems with integers until Size is ToSize.
7523 void pad(uint64_t ToSize) {
7524 assert(ToSize >= Size && "Cannot remove elements");
7528 // Finish the current 64-bit word.
7529 uint64_t Aligned = llvm::alignTo(Size, 64);
7530 if (Aligned > Size && Aligned <= ToSize) {
7531 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
7535 // Add whole 64-bit words.
7536 while (Size + 64 <= ToSize) {
7537 Elems.push_back(llvm::Type::getInt64Ty(Context));
7541 // Final in-word padding.
7542 if (Size < ToSize) {
7543 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
7548 // Add a floating point element at Offset.
7549 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
7550 // Unaligned floats are treated as integers.
7553 // The InReg flag is only required if there are any floats < 64 bits.
7557 Elems.push_back(Ty);
7558 Size = Offset + Bits;
7561 // Add a struct type to the coercion type, starting at Offset (in bits).
7562 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
7563 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
7564 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
7565 llvm::Type *ElemTy = StrTy->getElementType(i);
7566 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
7567 switch (ElemTy->getTypeID()) {
7568 case llvm::Type::StructTyID:
7569 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
7571 case llvm::Type::FloatTyID:
7572 addFloat(ElemOffset, ElemTy, 32);
7574 case llvm::Type::DoubleTyID:
7575 addFloat(ElemOffset, ElemTy, 64);
7577 case llvm::Type::FP128TyID:
7578 addFloat(ElemOffset, ElemTy, 128);
7580 case llvm::Type::PointerTyID:
7581 if (ElemOffset % 64 == 0) {
7583 Elems.push_back(ElemTy);
7593 // Check if Ty is a usable substitute for the coercion type.
7594 bool isUsableType(llvm::StructType *Ty) const {
7595 return llvm::makeArrayRef(Elems) == Ty->elements();
7598 // Get the coercion type as a literal struct type.
7599 llvm::Type *getType() const {
7600 if (Elems.size() == 1)
7601 return Elems.front();
7603 return llvm::StructType::get(Context, Elems);
7607 } // end anonymous namespace
7610 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
7611 if (Ty->isVoidType())
7612 return ABIArgInfo::getIgnore();
7614 uint64_t Size = getContext().getTypeSize(Ty);
7616 // Anything too big to fit in registers is passed with an explicit indirect
7617 // pointer / sret pointer.
7618 if (Size > SizeLimit)
7619 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7621 // Treat an enum type as its underlying type.
7622 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7623 Ty = EnumTy->getDecl()->getIntegerType();
7625 // Integer types smaller than a register are extended.
7626 if (Size < 64 && Ty->isIntegerType())
7627 return ABIArgInfo::getExtend();
7629 // Other non-aggregates go in registers.
7630 if (!isAggregateTypeForABI(Ty))
7631 return ABIArgInfo::getDirect();
7633 // If a C++ object has either a non-trivial copy constructor or a non-trivial
7634 // destructor, it is passed with an explicit indirect pointer / sret pointer.
7635 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7636 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7638 // This is a small aggregate type that should be passed in registers.
7639 // Build a coercion type from the LLVM struct type.
7640 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7642 return ABIArgInfo::getDirect();
7644 CoerceBuilder CB(getVMContext(), getDataLayout());
7645 CB.addStruct(0, StrTy);
7646 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
7648 // Try to use the original type for coercion.
7649 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
7652 return ABIArgInfo::getDirectInReg(CoerceTy);
7654 return ABIArgInfo::getDirect(CoerceTy);
7657 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7658 QualType Ty) const {
7659 ABIArgInfo AI = classifyType(Ty, 16 * 8);
7660 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7661 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7662 AI.setCoerceToType(ArgTy);
7664 CharUnits SlotSize = CharUnits::fromQuantity(8);
7666 CGBuilderTy &Builder = CGF.Builder;
7667 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
7668 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
7670 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
7672 Address ArgAddr = Address::invalid();
7674 switch (AI.getKind()) {
7675 case ABIArgInfo::Expand:
7676 case ABIArgInfo::CoerceAndExpand:
7677 case ABIArgInfo::InAlloca:
7678 llvm_unreachable("Unsupported ABI kind for va_arg");
7680 case ABIArgInfo::Extend: {
7682 CharUnits Offset = SlotSize - TypeInfo.first;
7683 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
7687 case ABIArgInfo::Direct: {
7688 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
7689 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
7694 case ABIArgInfo::Indirect:
7696 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
7697 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
7701 case ABIArgInfo::Ignore:
7702 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
7706 llvm::Value *NextPtr =
7707 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
7708 Builder.CreateStore(NextPtr, VAListAddr);
7710 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
7713 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7714 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
7715 for (auto &I : FI.arguments())
7716 I.info = classifyType(I.type, 16 * 8);
7720 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
7722 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
7723 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
7725 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
7729 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7730 llvm::Value *Address) const override;
7732 } // end anonymous namespace
7735 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7736 llvm::Value *Address) const {
7737 // This is calculated from the LLVM and GCC tables and verified
7738 // against gcc output. AFAIK all ABIs use the same encoding.
7740 CodeGen::CGBuilderTy &Builder = CGF.Builder;
7742 llvm::IntegerType *i8 = CGF.Int8Ty;
7743 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
7744 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
7746 // 0-31: the 8-byte general-purpose registers
7747 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
7749 // 32-63: f0-31, the 4-byte floating-point registers
7750 AssignToArrayRange(Builder, Address, Four8, 32, 63);
7760 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
7762 // 72-87: d0-15, the 8-byte floating-point registers
7763 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
7769 //===----------------------------------------------------------------------===//
7770 // XCore ABI Implementation
7771 //===----------------------------------------------------------------------===//
7775 /// A SmallStringEnc instance is used to build up the TypeString by passing
7776 /// it by reference between functions that append to it.
7777 typedef llvm::SmallString<128> SmallStringEnc;
7779 /// TypeStringCache caches the meta encodings of Types.
7781 /// The reason for caching TypeStrings is two fold:
7782 /// 1. To cache a type's encoding for later uses;
7783 /// 2. As a means to break recursive member type inclusion.
7785 /// A cache Entry can have a Status of:
7786 /// NonRecursive: The type encoding is not recursive;
7787 /// Recursive: The type encoding is recursive;
7788 /// Incomplete: An incomplete TypeString;
7789 /// IncompleteUsed: An incomplete TypeString that has been used in a
7790 /// Recursive type encoding.
7792 /// A NonRecursive entry will have all of its sub-members expanded as fully
7793 /// as possible. Whilst it may contain types which are recursive, the type
7794 /// itself is not recursive and thus its encoding may be safely used whenever
7795 /// the type is encountered.
7797 /// A Recursive entry will have all of its sub-members expanded as fully as
7798 /// possible. The type itself is recursive and it may contain other types which
7799 /// are recursive. The Recursive encoding must not be used during the expansion
7800 /// of a recursive type's recursive branch. For simplicity the code uses
7801 /// IncompleteCount to reject all usage of Recursive encodings for member types.
7803 /// An Incomplete entry is always a RecordType and only encodes its
7804 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
7805 /// are placed into the cache during type expansion as a means to identify and
7806 /// handle recursive inclusion of types as sub-members. If there is recursion
7807 /// the entry becomes IncompleteUsed.
7809 /// During the expansion of a RecordType's members:
7811 /// If the cache contains a NonRecursive encoding for the member type, the
7812 /// cached encoding is used;
7814 /// If the cache contains a Recursive encoding for the member type, the
7815 /// cached encoding is 'Swapped' out, as it may be incorrect, and...
7817 /// If the member is a RecordType, an Incomplete encoding is placed into the
7818 /// cache to break potential recursive inclusion of itself as a sub-member;
7820 /// Once a member RecordType has been expanded, its temporary incomplete
7821 /// entry is removed from the cache. If a Recursive encoding was swapped out
7822 /// it is swapped back in;
7824 /// If an incomplete entry is used to expand a sub-member, the incomplete
7825 /// entry is marked as IncompleteUsed. The cache keeps count of how many
7826 /// IncompleteUsed entries it currently contains in IncompleteUsedCount;
7828 /// If a member's encoding is found to be a NonRecursive or Recursive viz:
7829 /// IncompleteUsedCount==0, the member's encoding is added to the cache.
7830 /// Else the member is part of a recursive type and thus the recursion has
7831 /// been exited too soon for the encoding to be correct for the member.
7833 class TypeStringCache {
7834 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
7836 std::string Str; // The encoded TypeString for the type.
7837 enum Status State; // Information about the encoding in 'Str'.
7838 std::string Swapped; // A temporary place holder for a Recursive encoding
7839 // during the expansion of RecordType's members.
7841 std::map<const IdentifierInfo *, struct Entry> Map;
7842 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
7843 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
7845 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
7846 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
7847 bool removeIncomplete(const IdentifierInfo *ID);
7848 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
7850 StringRef lookupStr(const IdentifierInfo *ID);
7853 /// TypeString encodings for enum & union fields must be order.
7854 /// FieldEncoding is a helper for this ordering process.
7855 class FieldEncoding {
7859 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
7860 StringRef str() { return Enc; }
7861 bool operator<(const FieldEncoding &rhs) const {
7862 if (HasName != rhs.HasName) return HasName;
7863 return Enc < rhs.Enc;
7867 class XCoreABIInfo : public DefaultABIInfo {
7869 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7870 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7871 QualType Ty) const override;
7874 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
7875 mutable TypeStringCache TSC;
7877 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
7878 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
7879 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7880 CodeGen::CodeGenModule &M) const override;
7883 } // End anonymous namespace.
7885 // TODO: this implementation is likely now redundant with the default
7887 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7888 QualType Ty) const {
7889 CGBuilderTy &Builder = CGF.Builder;
7892 CharUnits SlotSize = CharUnits::fromQuantity(4);
7893 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
7895 // Handle the argument.
7896 ABIArgInfo AI = classifyArgumentType(Ty);
7897 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
7898 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7899 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7900 AI.setCoerceToType(ArgTy);
7901 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
7903 Address Val = Address::invalid();
7904 CharUnits ArgSize = CharUnits::Zero();
7905 switch (AI.getKind()) {
7906 case ABIArgInfo::Expand:
7907 case ABIArgInfo::CoerceAndExpand:
7908 case ABIArgInfo::InAlloca:
7909 llvm_unreachable("Unsupported ABI kind for va_arg");
7910 case ABIArgInfo::Ignore:
7911 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
7912 ArgSize = CharUnits::Zero();
7914 case ABIArgInfo::Extend:
7915 case ABIArgInfo::Direct:
7916 Val = Builder.CreateBitCast(AP, ArgPtrTy);
7917 ArgSize = CharUnits::fromQuantity(
7918 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
7919 ArgSize = ArgSize.alignTo(SlotSize);
7921 case ABIArgInfo::Indirect:
7922 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
7923 Val = Address(Builder.CreateLoad(Val), TypeAlign);
7928 // Increment the VAList.
7929 if (!ArgSize.isZero()) {
7931 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
7932 Builder.CreateStore(APN, VAListAddr);
7938 /// During the expansion of a RecordType, an incomplete TypeString is placed
7939 /// into the cache as a means to identify and break recursion.
7940 /// If there is a Recursive encoding in the cache, it is swapped out and will
7941 /// be reinserted by removeIncomplete().
7942 /// All other types of encoding should have been used rather than arriving here.
7943 void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
7944 std::string StubEnc) {
7948 assert( (E.Str.empty() || E.State == Recursive) &&
7949 "Incorrectly use of addIncomplete");
7950 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
7951 E.Swapped.swap(E.Str); // swap out the Recursive
7952 E.Str.swap(StubEnc);
7953 E.State = Incomplete;
7957 /// Once the RecordType has been expanded, the temporary incomplete TypeString
7958 /// must be removed from the cache.
7959 /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
7960 /// Returns true if the RecordType was defined recursively.
7961 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
7964 auto I = Map.find(ID);
7965 assert(I != Map.end() && "Entry not present");
7966 Entry &E = I->second;
7967 assert( (E.State == Incomplete ||
7968 E.State == IncompleteUsed) &&
7969 "Entry must be an incomplete type");
7970 bool IsRecursive = false;
7971 if (E.State == IncompleteUsed) {
7972 // We made use of our Incomplete encoding, thus we are recursive.
7974 --IncompleteUsedCount;
7976 if (E.Swapped.empty())
7979 // Swap the Recursive back.
7980 E.Swapped.swap(E.Str);
7982 E.State = Recursive;
7988 /// Add the encoded TypeString to the cache only if it is NonRecursive or
7989 /// Recursive (viz: all sub-members were expanded as fully as possible).
7990 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
7992 if (!ID || IncompleteUsedCount)
7993 return; // No key or it is is an incomplete sub-type so don't add.
7995 if (IsRecursive && !E.Str.empty()) {
7996 assert(E.State==Recursive && E.Str.size() == Str.size() &&
7997 "This is not the same Recursive entry");
7998 // The parent container was not recursive after all, so we could have used
7999 // this Recursive sub-member entry after all, but we assumed the worse when
8000 // we started viz: IncompleteCount!=0.
8003 assert(E.Str.empty() && "Entry already present");
8005 E.State = IsRecursive? Recursive : NonRecursive;
8008 /// Return a cached TypeString encoding for the ID. If there isn't one, or we
8009 /// are recursively expanding a type (IncompleteCount != 0) and the cached
8010 /// encoding is Recursive, return an empty StringRef.
8011 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
8013 return StringRef(); // We have no key.
8014 auto I = Map.find(ID);
8016 return StringRef(); // We have no encoding.
8017 Entry &E = I->second;
8018 if (E.State == Recursive && IncompleteCount)
8019 return StringRef(); // We don't use Recursive encodings for member types.
8021 if (E.State == Incomplete) {
8022 // The incomplete type is being used to break out of recursion.
8023 E.State = IncompleteUsed;
8024 ++IncompleteUsedCount;
8029 /// The XCore ABI includes a type information section that communicates symbol
8030 /// type information to the linker. The linker uses this information to verify
8031 /// safety/correctness of things such as array bound and pointers et al.
8032 /// The ABI only requires C (and XC) language modules to emit TypeStrings.
8033 /// This type information (TypeString) is emitted into meta data for all global
8034 /// symbols: definitions, declarations, functions & variables.
8036 /// The TypeString carries type, qualifier, name, size & value details.
8037 /// Please see 'Tools Development Guide' section 2.16.2 for format details:
8038 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
8039 /// The output is tested by test/CodeGen/xcore-stringtype.c.
8041 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8042 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
8044 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
8045 void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8046 CodeGen::CodeGenModule &CGM) const {
8048 if (getTypeString(Enc, D, CGM, TSC)) {
8049 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
8050 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
8051 llvm::MDString::get(Ctx, Enc.str())};
8052 llvm::NamedMDNode *MD =
8053 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
8054 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
8058 //===----------------------------------------------------------------------===//
8059 // SPIR ABI Implementation
8060 //===----------------------------------------------------------------------===//
8063 class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
8065 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8066 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
8067 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8068 CodeGen::CodeGenModule &M) const override;
8069 unsigned getOpenCLKernelCallingConv() const override;
8071 } // End anonymous namespace.
8073 /// Emit SPIR specific metadata: OpenCL and SPIR version.
8074 void SPIRTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8075 CodeGen::CodeGenModule &CGM) const {
8076 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
8077 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(Ctx);
8078 llvm::Module &M = CGM.getModule();
8079 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
8080 // opencl.spir.version named metadata.
8081 llvm::Metadata *SPIRVerElts[] = {
8082 llvm::ConstantAsMetadata::get(
8083 llvm::ConstantInt::get(Int32Ty, CGM.getLangOpts().OpenCLVersion / 100)),
8084 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
8085 Int32Ty, (CGM.getLangOpts().OpenCLVersion / 100 > 1) ? 0 : 2))};
8086 llvm::NamedMDNode *SPIRVerMD =
8087 M.getOrInsertNamedMetadata("opencl.spir.version");
8088 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
8089 appendOpenCLVersionMD(CGM);
8092 static void appendOpenCLVersionMD(CodeGen::CodeGenModule &CGM) {
8093 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
8094 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(Ctx);
8095 llvm::Module &M = CGM.getModule();
8096 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
8097 // opencl.ocl.version named metadata node.
8098 llvm::Metadata *OCLVerElts[] = {
8099 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
8100 Int32Ty, CGM.getLangOpts().OpenCLVersion / 100)),
8101 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
8102 Int32Ty, (CGM.getLangOpts().OpenCLVersion % 100) / 10))};
8103 llvm::NamedMDNode *OCLVerMD =
8104 M.getOrInsertNamedMetadata("opencl.ocl.version");
8105 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
8108 unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
8109 return llvm::CallingConv::SPIR_KERNEL;
8112 static bool appendType(SmallStringEnc &Enc, QualType QType,
8113 const CodeGen::CodeGenModule &CGM,
8114 TypeStringCache &TSC);
8116 /// Helper function for appendRecordType().
8117 /// Builds a SmallVector containing the encoded field types in declaration
8119 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
8120 const RecordDecl *RD,
8121 const CodeGen::CodeGenModule &CGM,
8122 TypeStringCache &TSC) {
8123 for (const auto *Field : RD->fields()) {
8126 Enc += Field->getName();
8128 if (Field->isBitField()) {
8130 llvm::raw_svector_ostream OS(Enc);
8131 OS << Field->getBitWidthValue(CGM.getContext());
8134 if (!appendType(Enc, Field->getType(), CGM, TSC))
8136 if (Field->isBitField())
8139 FE.emplace_back(!Field->getName().empty(), Enc);
8144 /// Appends structure and union types to Enc and adds encoding to cache.
8145 /// Recursively calls appendType (via extractFieldType) for each field.
8146 /// Union types have their fields ordered according to the ABI.
8147 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
8148 const CodeGen::CodeGenModule &CGM,
8149 TypeStringCache &TSC, const IdentifierInfo *ID) {
8150 // Append the cached TypeString if we have one.
8151 StringRef TypeString = TSC.lookupStr(ID);
8152 if (!TypeString.empty()) {
8157 // Start to emit an incomplete TypeString.
8158 size_t Start = Enc.size();
8159 Enc += (RT->isUnionType()? 'u' : 's');
8162 Enc += ID->getName();
8165 // We collect all encoded fields and order as necessary.
8166 bool IsRecursive = false;
8167 const RecordDecl *RD = RT->getDecl()->getDefinition();
8168 if (RD && !RD->field_empty()) {
8169 // An incomplete TypeString stub is placed in the cache for this RecordType
8170 // so that recursive calls to this RecordType will use it whilst building a
8171 // complete TypeString for this RecordType.
8172 SmallVector<FieldEncoding, 16> FE;
8173 std::string StubEnc(Enc.substr(Start).str());
8174 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
8175 TSC.addIncomplete(ID, std::move(StubEnc));
8176 if (!extractFieldType(FE, RD, CGM, TSC)) {
8177 (void) TSC.removeIncomplete(ID);
8180 IsRecursive = TSC.removeIncomplete(ID);
8181 // The ABI requires unions to be sorted but not structures.
8182 // See FieldEncoding::operator< for sort algorithm.
8183 if (RT->isUnionType())
8184 std::sort(FE.begin(), FE.end());
8185 // We can now complete the TypeString.
8186 unsigned E = FE.size();
8187 for (unsigned I = 0; I != E; ++I) {
8194 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
8198 /// Appends enum types to Enc and adds the encoding to the cache.
8199 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
8200 TypeStringCache &TSC,
8201 const IdentifierInfo *ID) {
8202 // Append the cached TypeString if we have one.
8203 StringRef TypeString = TSC.lookupStr(ID);
8204 if (!TypeString.empty()) {
8209 size_t Start = Enc.size();
8212 Enc += ID->getName();
8215 // We collect all encoded enumerations and order them alphanumerically.
8216 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
8217 SmallVector<FieldEncoding, 16> FE;
8218 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
8220 SmallStringEnc EnumEnc;
8222 EnumEnc += I->getName();
8224 I->getInitVal().toString(EnumEnc);
8226 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
8228 std::sort(FE.begin(), FE.end());
8229 unsigned E = FE.size();
8230 for (unsigned I = 0; I != E; ++I) {
8237 TSC.addIfComplete(ID, Enc.substr(Start), false);
8241 /// Appends type's qualifier to Enc.
8242 /// This is done prior to appending the type's encoding.
8243 static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
8244 // Qualifiers are emitted in alphabetical order.
8245 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
8247 if (QT.isConstQualified())
8249 if (QT.isRestrictQualified())
8251 if (QT.isVolatileQualified())
8253 Enc += Table[Lookup];
8256 /// Appends built-in types to Enc.
8257 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
8258 const char *EncType;
8259 switch (BT->getKind()) {
8260 case BuiltinType::Void:
8263 case BuiltinType::Bool:
8266 case BuiltinType::Char_U:
8269 case BuiltinType::UChar:
8272 case BuiltinType::SChar:
8275 case BuiltinType::UShort:
8278 case BuiltinType::Short:
8281 case BuiltinType::UInt:
8284 case BuiltinType::Int:
8287 case BuiltinType::ULong:
8290 case BuiltinType::Long:
8293 case BuiltinType::ULongLong:
8296 case BuiltinType::LongLong:
8299 case BuiltinType::Float:
8302 case BuiltinType::Double:
8305 case BuiltinType::LongDouble:
8315 /// Appends a pointer encoding to Enc before calling appendType for the pointee.
8316 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
8317 const CodeGen::CodeGenModule &CGM,
8318 TypeStringCache &TSC) {
8320 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
8326 /// Appends array encoding to Enc before calling appendType for the element.
8327 static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
8328 const ArrayType *AT,
8329 const CodeGen::CodeGenModule &CGM,
8330 TypeStringCache &TSC, StringRef NoSizeEnc) {
8331 if (AT->getSizeModifier() != ArrayType::Normal)
8334 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
8335 CAT->getSize().toStringUnsigned(Enc);
8337 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
8339 // The Qualifiers should be attached to the type rather than the array.
8340 appendQualifier(Enc, QT);
8341 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
8347 /// Appends a function encoding to Enc, calling appendType for the return type
8348 /// and the arguments.
8349 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
8350 const CodeGen::CodeGenModule &CGM,
8351 TypeStringCache &TSC) {
8353 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
8356 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
8357 // N.B. we are only interested in the adjusted param types.
8358 auto I = FPT->param_type_begin();
8359 auto E = FPT->param_type_end();
8362 if (!appendType(Enc, *I, CGM, TSC))
8368 if (FPT->isVariadic())
8371 if (FPT->isVariadic())
8381 /// Handles the type's qualifier before dispatching a call to handle specific
8383 static bool appendType(SmallStringEnc &Enc, QualType QType,
8384 const CodeGen::CodeGenModule &CGM,
8385 TypeStringCache &TSC) {
8387 QualType QT = QType.getCanonicalType();
8389 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
8390 // The Qualifiers should be attached to the type rather than the array.
8391 // Thus we don't call appendQualifier() here.
8392 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
8394 appendQualifier(Enc, QT);
8396 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
8397 return appendBuiltinType(Enc, BT);
8399 if (const PointerType *PT = QT->getAs<PointerType>())
8400 return appendPointerType(Enc, PT, CGM, TSC);
8402 if (const EnumType *ET = QT->getAs<EnumType>())
8403 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
8405 if (const RecordType *RT = QT->getAsStructureType())
8406 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8408 if (const RecordType *RT = QT->getAsUnionType())
8409 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8411 if (const FunctionType *FT = QT->getAs<FunctionType>())
8412 return appendFunctionType(Enc, FT, CGM, TSC);
8417 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8418 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
8422 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8423 if (FD->getLanguageLinkage() != CLanguageLinkage)
8425 return appendType(Enc, FD->getType(), CGM, TSC);
8428 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8429 if (VD->getLanguageLinkage() != CLanguageLinkage)
8431 QualType QT = VD->getType().getCanonicalType();
8432 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
8433 // Global ArrayTypes are given a size of '*' if the size is unknown.
8434 // The Qualifiers should be attached to the type rather than the array.
8435 // Thus we don't call appendQualifier() here.
8436 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
8438 return appendType(Enc, QT, CGM, TSC);
8444 //===----------------------------------------------------------------------===//
8446 //===----------------------------------------------------------------------===//
8448 bool CodeGenModule::supportsCOMDAT() const {
8449 return getTriple().supportsCOMDAT();
8452 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
8453 if (TheTargetCodeGenInfo)
8454 return *TheTargetCodeGenInfo;
8456 // Helper to set the unique_ptr while still keeping the return value.
8457 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
8458 this->TheTargetCodeGenInfo.reset(P);
8462 const llvm::Triple &Triple = getTarget().getTriple();
8463 switch (Triple.getArch()) {
8465 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
8467 case llvm::Triple::le32:
8468 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
8469 case llvm::Triple::mips:
8470 case llvm::Triple::mipsel:
8471 if (Triple.getOS() == llvm::Triple::NaCl)
8472 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
8473 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
8475 case llvm::Triple::mips64:
8476 case llvm::Triple::mips64el:
8477 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
8479 case llvm::Triple::avr:
8480 return SetCGInfo(new AVRTargetCodeGenInfo(Types));
8482 case llvm::Triple::aarch64:
8483 case llvm::Triple::aarch64_be: {
8484 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
8485 if (getTarget().getABI() == "darwinpcs")
8486 Kind = AArch64ABIInfo::DarwinPCS;
8488 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
8491 case llvm::Triple::wasm32:
8492 case llvm::Triple::wasm64:
8493 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
8495 case llvm::Triple::arm:
8496 case llvm::Triple::armeb:
8497 case llvm::Triple::thumb:
8498 case llvm::Triple::thumbeb: {
8499 if (Triple.getOS() == llvm::Triple::Win32) {
8501 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
8504 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
8505 StringRef ABIStr = getTarget().getABI();
8506 if (ABIStr == "apcs-gnu")
8507 Kind = ARMABIInfo::APCS;
8508 else if (ABIStr == "aapcs16")
8509 Kind = ARMABIInfo::AAPCS16_VFP;
8510 else if (CodeGenOpts.FloatABI == "hard" ||
8511 (CodeGenOpts.FloatABI != "soft" &&
8512 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
8513 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
8514 Triple.getEnvironment() == llvm::Triple::EABIHF)))
8515 Kind = ARMABIInfo::AAPCS_VFP;
8517 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
8520 case llvm::Triple::ppc:
8522 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
8523 case llvm::Triple::ppc64:
8524 if (Triple.isOSBinFormatELF()) {
8525 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
8526 if (getTarget().getABI() == "elfv2")
8527 Kind = PPC64_SVR4_ABIInfo::ELFv2;
8528 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
8529 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
8531 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8534 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
8535 case llvm::Triple::ppc64le: {
8536 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
8537 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
8538 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
8539 Kind = PPC64_SVR4_ABIInfo::ELFv1;
8540 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
8541 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
8543 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8547 case llvm::Triple::nvptx:
8548 case llvm::Triple::nvptx64:
8549 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
8551 case llvm::Triple::msp430:
8552 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
8554 case llvm::Triple::systemz: {
8555 bool HasVector = getTarget().getABI() == "vector";
8556 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
8559 case llvm::Triple::tce:
8560 case llvm::Triple::tcele:
8561 return SetCGInfo(new TCETargetCodeGenInfo(Types));
8563 case llvm::Triple::x86: {
8564 bool IsDarwinVectorABI = Triple.isOSDarwin();
8565 bool RetSmallStructInRegABI =
8566 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
8567 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
8569 if (Triple.getOS() == llvm::Triple::Win32) {
8570 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
8571 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8572 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
8574 return SetCGInfo(new X86_32TargetCodeGenInfo(
8575 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8576 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
8577 CodeGenOpts.FloatABI == "soft"));
8581 case llvm::Triple::x86_64: {
8582 StringRef ABI = getTarget().getABI();
8583 X86AVXABILevel AVXLevel =
8585 ? X86AVXABILevel::AVX512
8586 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
8588 switch (Triple.getOS()) {
8589 case llvm::Triple::Win32:
8590 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
8591 case llvm::Triple::PS4:
8592 return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
8594 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
8597 case llvm::Triple::hexagon:
8598 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
8599 case llvm::Triple::lanai:
8600 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
8601 case llvm::Triple::r600:
8602 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
8603 case llvm::Triple::amdgcn:
8604 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
8605 case llvm::Triple::sparc:
8606 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
8607 case llvm::Triple::sparcv9:
8608 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
8609 case llvm::Triple::xcore:
8610 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
8611 case llvm::Triple::spir:
8612 case llvm::Triple::spir64:
8613 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));