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, QualType SrcTy,
411 QualType DestTy) 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,
415 CGF.ConvertType(DestTy));
418 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
420 /// isEmptyField - Return true iff a the field is "empty", that is it
421 /// is an unnamed bit-field or an (array of) empty record(s).
422 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
424 if (FD->isUnnamedBitfield())
427 QualType FT = FD->getType();
429 // Constant arrays of empty records count as empty, strip them off.
430 // Constant arrays of zero length always count as empty.
432 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
433 if (AT->getSize() == 0)
435 FT = AT->getElementType();
438 const RecordType *RT = FT->getAs<RecordType>();
442 // C++ record fields are never empty, at least in the Itanium ABI.
444 // FIXME: We should use a predicate for whether this behavior is true in the
446 if (isa<CXXRecordDecl>(RT->getDecl()))
449 return isEmptyRecord(Context, FT, AllowArrays);
452 /// isEmptyRecord - Return true iff a structure contains only empty
453 /// fields. Note that a structure with a flexible array member is not
454 /// considered empty.
455 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
456 const RecordType *RT = T->getAs<RecordType>();
459 const RecordDecl *RD = RT->getDecl();
460 if (RD->hasFlexibleArrayMember())
463 // If this is a C++ record, check the bases first.
464 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
465 for (const auto &I : CXXRD->bases())
466 if (!isEmptyRecord(Context, I.getType(), true))
469 for (const auto *I : RD->fields())
470 if (!isEmptyField(Context, I, AllowArrays))
475 /// isSingleElementStruct - Determine if a structure is a "single
476 /// element struct", i.e. it has exactly one non-empty field or
477 /// exactly one field which is itself a single element
478 /// struct. Structures with flexible array members are never
479 /// considered single element structs.
481 /// \return The field declaration for the single non-empty field, if
483 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
484 const RecordType *RT = T->getAs<RecordType>();
488 const RecordDecl *RD = RT->getDecl();
489 if (RD->hasFlexibleArrayMember())
492 const Type *Found = nullptr;
494 // If this is a C++ record, check the bases first.
495 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
496 for (const auto &I : CXXRD->bases()) {
497 // Ignore empty records.
498 if (isEmptyRecord(Context, I.getType(), true))
501 // If we already found an element then this isn't a single-element struct.
505 // If this is non-empty and not a single element struct, the composite
506 // cannot be a single element struct.
507 Found = isSingleElementStruct(I.getType(), Context);
513 // Check for single element.
514 for (const auto *FD : RD->fields()) {
515 QualType FT = FD->getType();
517 // Ignore empty fields.
518 if (isEmptyField(Context, FD, true))
521 // If we already found an element then this isn't a single-element
526 // Treat single element arrays as the element.
527 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
528 if (AT->getSize().getZExtValue() != 1)
530 FT = AT->getElementType();
533 if (!isAggregateTypeForABI(FT)) {
534 Found = FT.getTypePtr();
536 Found = isSingleElementStruct(FT, Context);
542 // We don't consider a struct a single-element struct if it has
543 // padding beyond the element type.
544 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
551 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
552 const ABIArgInfo &AI) {
553 // This default implementation defers to the llvm backend's va_arg
554 // instruction. It can handle only passing arguments directly
555 // (typically only handled in the backend for primitive types), or
556 // aggregates passed indirectly by pointer (NOTE: if the "byval"
557 // flag has ABI impact in the callee, this implementation cannot
560 // Only a few cases are covered here at the moment -- those needed
561 // by the default abi.
564 if (AI.isIndirect()) {
565 assert(!AI.getPaddingType() &&
566 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
568 !AI.getIndirectRealign() &&
569 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
571 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
572 CharUnits TyAlignForABI = TyInfo.second;
575 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
577 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
578 return Address(Addr, TyAlignForABI);
580 assert((AI.isDirect() || AI.isExtend()) &&
581 "Unexpected ArgInfo Kind in generic VAArg emitter!");
583 assert(!AI.getInReg() &&
584 "Unexpected InReg seen in arginfo in generic VAArg emitter!");
585 assert(!AI.getPaddingType() &&
586 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
587 assert(!AI.getDirectOffset() &&
588 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
589 assert(!AI.getCoerceToType() &&
590 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
592 Address Temp = CGF.CreateMemTemp(Ty, "varet");
593 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
594 CGF.Builder.CreateStore(Val, Temp);
599 /// DefaultABIInfo - The default implementation for ABI specific
600 /// details. This implementation provides information which results in
601 /// self-consistent and sensible LLVM IR generation, but does not
602 /// conform to any particular ABI.
603 class DefaultABIInfo : public ABIInfo {
605 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
607 ABIArgInfo classifyReturnType(QualType RetTy) const;
608 ABIArgInfo classifyArgumentType(QualType RetTy) const;
610 void computeInfo(CGFunctionInfo &FI) const override {
611 if (!getCXXABI().classifyReturnType(FI))
612 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
613 for (auto &I : FI.arguments())
614 I.info = classifyArgumentType(I.type);
617 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
618 QualType Ty) const override {
619 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
623 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
625 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
626 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
629 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
630 Ty = useFirstFieldIfTransparentUnion(Ty);
632 if (isAggregateTypeForABI(Ty)) {
633 // Records with non-trivial destructors/copy-constructors should not be
635 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
636 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
638 return getNaturalAlignIndirect(Ty);
641 // Treat an enum type as its underlying type.
642 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
643 Ty = EnumTy->getDecl()->getIntegerType();
645 return (Ty->isPromotableIntegerType() ?
646 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
649 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
650 if (RetTy->isVoidType())
651 return ABIArgInfo::getIgnore();
653 if (isAggregateTypeForABI(RetTy))
654 return getNaturalAlignIndirect(RetTy);
656 // Treat an enum type as its underlying type.
657 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
658 RetTy = EnumTy->getDecl()->getIntegerType();
660 return (RetTy->isPromotableIntegerType() ?
661 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
664 //===----------------------------------------------------------------------===//
665 // WebAssembly ABI Implementation
667 // This is a very simple ABI that relies a lot on DefaultABIInfo.
668 //===----------------------------------------------------------------------===//
670 class WebAssemblyABIInfo final : public DefaultABIInfo {
672 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
673 : DefaultABIInfo(CGT) {}
676 ABIArgInfo classifyReturnType(QualType RetTy) const;
677 ABIArgInfo classifyArgumentType(QualType Ty) const;
679 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
680 // non-virtual, but computeInfo and EmitVAArg are virtual, so we
682 void computeInfo(CGFunctionInfo &FI) const override {
683 if (!getCXXABI().classifyReturnType(FI))
684 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
685 for (auto &Arg : FI.arguments())
686 Arg.info = classifyArgumentType(Arg.type);
689 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
690 QualType Ty) const override;
693 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
695 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
696 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
699 /// \brief Classify argument of given type \p Ty.
700 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
701 Ty = useFirstFieldIfTransparentUnion(Ty);
703 if (isAggregateTypeForABI(Ty)) {
704 // Records with non-trivial destructors/copy-constructors should not be
706 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
707 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
708 // Ignore empty structs/unions.
709 if (isEmptyRecord(getContext(), Ty, true))
710 return ABIArgInfo::getIgnore();
711 // Lower single-element structs to just pass a regular value. TODO: We
712 // could do reasonable-size multiple-element structs too, using getExpand(),
713 // though watch out for things like bitfields.
714 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
715 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
718 // Otherwise just do the default thing.
719 return DefaultABIInfo::classifyArgumentType(Ty);
722 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
723 if (isAggregateTypeForABI(RetTy)) {
724 // Records with non-trivial destructors/copy-constructors should not be
725 // returned by value.
726 if (!getRecordArgABI(RetTy, getCXXABI())) {
727 // Ignore empty structs/unions.
728 if (isEmptyRecord(getContext(), RetTy, true))
729 return ABIArgInfo::getIgnore();
730 // Lower single-element structs to just return a regular value. TODO: We
731 // could do reasonable-size multiple-element structs too, using
732 // ABIArgInfo::getDirect().
733 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
734 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
738 // Otherwise just do the default thing.
739 return DefaultABIInfo::classifyReturnType(RetTy);
742 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
744 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect=*/ false,
745 getContext().getTypeInfoInChars(Ty),
746 CharUnits::fromQuantity(4),
747 /*AllowHigherAlign=*/ true);
750 //===----------------------------------------------------------------------===//
751 // le32/PNaCl bitcode ABI Implementation
753 // This is a simplified version of the x86_32 ABI. Arguments and return values
754 // are always passed on the stack.
755 //===----------------------------------------------------------------------===//
757 class PNaClABIInfo : public ABIInfo {
759 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
761 ABIArgInfo classifyReturnType(QualType RetTy) const;
762 ABIArgInfo classifyArgumentType(QualType RetTy) const;
764 void computeInfo(CGFunctionInfo &FI) const override;
765 Address EmitVAArg(CodeGenFunction &CGF,
766 Address VAListAddr, QualType Ty) const override;
769 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
771 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
772 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
775 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
776 if (!getCXXABI().classifyReturnType(FI))
777 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
779 for (auto &I : FI.arguments())
780 I.info = classifyArgumentType(I.type);
783 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
785 // The PNaCL ABI is a bit odd, in that varargs don't use normal
786 // function classification. Structs get passed directly for varargs
787 // functions, through a rewriting transform in
788 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
789 // this target to actually support a va_arg instructions with an
790 // aggregate type, unlike other targets.
791 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
794 /// \brief Classify argument of given type \p Ty.
795 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
796 if (isAggregateTypeForABI(Ty)) {
797 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
798 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
799 return getNaturalAlignIndirect(Ty);
800 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
801 // Treat an enum type as its underlying type.
802 Ty = EnumTy->getDecl()->getIntegerType();
803 } else if (Ty->isFloatingType()) {
804 // Floating-point types don't go inreg.
805 return ABIArgInfo::getDirect();
808 return (Ty->isPromotableIntegerType() ?
809 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
812 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
813 if (RetTy->isVoidType())
814 return ABIArgInfo::getIgnore();
816 // In the PNaCl ABI we always return records/structures on the stack.
817 if (isAggregateTypeForABI(RetTy))
818 return getNaturalAlignIndirect(RetTy);
820 // Treat an enum type as its underlying type.
821 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
822 RetTy = EnumTy->getDecl()->getIntegerType();
824 return (RetTy->isPromotableIntegerType() ?
825 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
828 /// IsX86_MMXType - Return true if this is an MMX type.
829 bool IsX86_MMXType(llvm::Type *IRType) {
830 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
831 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
832 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
833 IRType->getScalarSizeInBits() != 64;
836 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
837 StringRef Constraint,
839 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
840 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
841 // Invalid MMX constraint
845 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
848 // No operation needed
852 /// Returns true if this type can be passed in SSE registers with the
853 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
854 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
855 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
856 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
858 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
859 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
860 // registers specially.
861 unsigned VecSize = Context.getTypeSize(VT);
862 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
868 /// Returns true if this aggregate is small enough to be passed in SSE registers
869 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
870 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
871 return NumMembers <= 4;
874 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
875 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
876 auto AI = ABIArgInfo::getDirect(T);
878 AI.setCanBeFlattened(false);
882 //===----------------------------------------------------------------------===//
883 // X86-32 ABI Implementation
884 //===----------------------------------------------------------------------===//
886 /// \brief Similar to llvm::CCState, but for Clang.
888 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
892 unsigned FreeSSERegs;
896 // Vectorcall only allows the first 6 parameters to be passed in registers.
897 VectorcallMaxParamNumAsReg = 6
900 /// X86_32ABIInfo - The X86-32 ABI information.
901 class X86_32ABIInfo : public SwiftABIInfo {
907 static const unsigned MinABIStackAlignInBytes = 4;
909 bool IsDarwinVectorABI;
910 bool IsRetSmallStructInRegABI;
911 bool IsWin32StructABI;
914 unsigned DefaultNumRegisterParameters;
916 static bool isRegisterSize(unsigned Size) {
917 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
920 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
921 // FIXME: Assumes vectorcall is in use.
922 return isX86VectorTypeForVectorCall(getContext(), Ty);
925 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
926 uint64_t NumMembers) const override {
927 // FIXME: Assumes vectorcall is in use.
928 return isX86VectorCallAggregateSmallEnough(NumMembers);
931 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
933 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
934 /// such that the argument will be passed in memory.
935 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
937 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
939 /// \brief Return the alignment to use for the given type on the stack.
940 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
942 Class classify(QualType Ty) const;
943 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
944 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
945 ABIArgInfo reclassifyHvaArgType(QualType RetTy, CCState &State,
946 const ABIArgInfo& current) const;
947 /// \brief Updates the number of available free registers, returns
948 /// true if any registers were allocated.
949 bool updateFreeRegs(QualType Ty, CCState &State) const;
951 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
952 bool &NeedsPadding) const;
953 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
955 bool canExpandIndirectArgument(QualType Ty) const;
957 /// \brief Rewrite the function info so that all memory arguments use
959 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
961 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
962 CharUnits &StackOffset, ABIArgInfo &Info,
963 QualType Type) const;
964 void computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
965 bool &UsedInAlloca) const;
969 void computeInfo(CGFunctionInfo &FI) const override;
970 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
971 QualType Ty) const override;
973 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
974 bool RetSmallStructInRegABI, bool Win32StructABI,
975 unsigned NumRegisterParameters, bool SoftFloatABI)
976 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
977 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
978 IsWin32StructABI(Win32StructABI),
979 IsSoftFloatABI(SoftFloatABI),
980 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
981 DefaultNumRegisterParameters(NumRegisterParameters) {}
983 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
984 ArrayRef<llvm::Type*> scalars,
985 bool asReturnValue) const override {
986 // LLVM's x86-32 lowering currently only assigns up to three
987 // integer registers and three fp registers. Oddly, it'll use up to
988 // four vector registers for vectors, but those can overlap with the
990 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
993 bool isSwiftErrorInRegister() const override {
994 // x86-32 lowering does not support passing swifterror in a register.
999 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1001 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1002 bool RetSmallStructInRegABI, bool Win32StructABI,
1003 unsigned NumRegisterParameters, bool SoftFloatABI)
1004 : TargetCodeGenInfo(new X86_32ABIInfo(
1005 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1006 NumRegisterParameters, SoftFloatABI)) {}
1008 static bool isStructReturnInRegABI(
1009 const llvm::Triple &Triple, const CodeGenOptions &Opts);
1011 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1012 CodeGen::CodeGenModule &CGM) const override;
1014 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1015 // Darwin uses different dwarf register numbers for EH.
1016 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
1020 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1021 llvm::Value *Address) const override;
1023 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1024 StringRef Constraint,
1025 llvm::Type* Ty) const override {
1026 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1029 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1030 std::string &Constraints,
1031 std::vector<llvm::Type *> &ResultRegTypes,
1032 std::vector<llvm::Type *> &ResultTruncRegTypes,
1033 std::vector<LValue> &ResultRegDests,
1034 std::string &AsmString,
1035 unsigned NumOutputs) const override;
1038 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
1039 unsigned Sig = (0xeb << 0) | // jmp rel8
1040 (0x06 << 8) | // .+0x08
1043 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1046 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1047 return "movl\t%ebp, %ebp"
1048 "\t\t## marker for objc_retainAutoreleaseReturnValue";
1054 /// Rewrite input constraint references after adding some output constraints.
1055 /// In the case where there is one output and one input and we add one output,
1056 /// we need to replace all operand references greater than or equal to 1:
1059 /// The result will be:
1062 static void rewriteInputConstraintReferences(unsigned FirstIn,
1063 unsigned NumNewOuts,
1064 std::string &AsmString) {
1066 llvm::raw_string_ostream OS(Buf);
1068 while (Pos < AsmString.size()) {
1069 size_t DollarStart = AsmString.find('$', Pos);
1070 if (DollarStart == std::string::npos)
1071 DollarStart = AsmString.size();
1072 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1073 if (DollarEnd == std::string::npos)
1074 DollarEnd = AsmString.size();
1075 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1077 size_t NumDollars = DollarEnd - DollarStart;
1078 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1079 // We have an operand reference.
1080 size_t DigitStart = Pos;
1081 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1082 if (DigitEnd == std::string::npos)
1083 DigitEnd = AsmString.size();
1084 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1085 unsigned OperandIndex;
1086 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1087 if (OperandIndex >= FirstIn)
1088 OperandIndex += NumNewOuts;
1096 AsmString = std::move(OS.str());
1099 /// Add output constraints for EAX:EDX because they are return registers.
1100 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1101 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1102 std::vector<llvm::Type *> &ResultRegTypes,
1103 std::vector<llvm::Type *> &ResultTruncRegTypes,
1104 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1105 unsigned NumOutputs) const {
1106 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1108 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1110 if (!Constraints.empty())
1112 if (RetWidth <= 32) {
1113 Constraints += "={eax}";
1114 ResultRegTypes.push_back(CGF.Int32Ty);
1116 // Use the 'A' constraint for EAX:EDX.
1117 Constraints += "=A";
1118 ResultRegTypes.push_back(CGF.Int64Ty);
1121 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1122 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1123 ResultTruncRegTypes.push_back(CoerceTy);
1125 // Coerce the integer by bitcasting the return slot pointer.
1126 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1127 CoerceTy->getPointerTo()));
1128 ResultRegDests.push_back(ReturnSlot);
1130 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1133 /// shouldReturnTypeInRegister - Determine if the given type should be
1134 /// returned in a register (for the Darwin and MCU ABI).
1135 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1136 ASTContext &Context) const {
1137 uint64_t Size = Context.getTypeSize(Ty);
1139 // For i386, type must be register sized.
1140 // For the MCU ABI, it only needs to be <= 8-byte
1141 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1144 if (Ty->isVectorType()) {
1145 // 64- and 128- bit vectors inside structures are not returned in
1147 if (Size == 64 || Size == 128)
1153 // If this is a builtin, pointer, enum, complex type, member pointer, or
1154 // member function pointer it is ok.
1155 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
1156 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
1157 Ty->isBlockPointerType() || Ty->isMemberPointerType())
1160 // Arrays are treated like records.
1161 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
1162 return shouldReturnTypeInRegister(AT->getElementType(), Context);
1164 // Otherwise, it must be a record type.
1165 const RecordType *RT = Ty->getAs<RecordType>();
1166 if (!RT) return false;
1168 // FIXME: Traverse bases here too.
1170 // Structure types are passed in register if all fields would be
1171 // passed in a register.
1172 for (const auto *FD : RT->getDecl()->fields()) {
1173 // Empty fields are ignored.
1174 if (isEmptyField(Context, FD, true))
1177 // Check fields recursively.
1178 if (!shouldReturnTypeInRegister(FD->getType(), Context))
1184 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1185 // Treat complex types as the element type.
1186 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1187 Ty = CTy->getElementType();
1189 // Check for a type which we know has a simple scalar argument-passing
1190 // convention without any padding. (We're specifically looking for 32
1191 // and 64-bit integer and integer-equivalents, float, and double.)
1192 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1193 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1196 uint64_t Size = Context.getTypeSize(Ty);
1197 return Size == 32 || Size == 64;
1200 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1202 for (const auto *FD : RD->fields()) {
1203 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1204 // argument is smaller than 32-bits, expanding the struct will create
1205 // alignment padding.
1206 if (!is32Or64BitBasicType(FD->getType(), Context))
1209 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1210 // how to expand them yet, and the predicate for telling if a bitfield still
1211 // counts as "basic" is more complicated than what we were doing previously.
1212 if (FD->isBitField())
1215 Size += Context.getTypeSize(FD->getType());
1220 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1222 // Don't do this if there are any non-empty bases.
1223 for (const CXXBaseSpecifier &Base : RD->bases()) {
1224 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1228 if (!addFieldSizes(Context, RD, Size))
1233 /// Test whether an argument type which is to be passed indirectly (on the
1234 /// stack) would have the equivalent layout if it was expanded into separate
1235 /// arguments. If so, we prefer to do the latter to avoid inhibiting
1237 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1238 // We can only expand structure types.
1239 const RecordType *RT = Ty->getAs<RecordType>();
1242 const RecordDecl *RD = RT->getDecl();
1244 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1245 if (!IsWin32StructABI) {
1246 // On non-Windows, we have to conservatively match our old bitcode
1247 // prototypes in order to be ABI-compatible at the bitcode level.
1248 if (!CXXRD->isCLike())
1251 // Don't do this for dynamic classes.
1252 if (CXXRD->isDynamicClass())
1255 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
1258 if (!addFieldSizes(getContext(), RD, Size))
1262 // We can do this if there was no alignment padding.
1263 return Size == getContext().getTypeSize(Ty);
1266 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
1267 // If the return value is indirect, then the hidden argument is consuming one
1268 // integer register.
1269 if (State.FreeRegs) {
1272 return getNaturalAlignIndirectInReg(RetTy);
1274 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
1277 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1278 CCState &State) const {
1279 if (RetTy->isVoidType())
1280 return ABIArgInfo::getIgnore();
1282 const Type *Base = nullptr;
1283 uint64_t NumElts = 0;
1284 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1285 State.CC == llvm::CallingConv::X86_RegCall) &&
1286 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1287 // The LLVM struct type for such an aggregate should lower properly.
1288 return ABIArgInfo::getDirect();
1291 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
1292 // On Darwin, some vectors are returned in registers.
1293 if (IsDarwinVectorABI) {
1294 uint64_t Size = getContext().getTypeSize(RetTy);
1296 // 128-bit vectors are a special case; they are returned in
1297 // registers and we need to make sure to pick a type the LLVM
1298 // backend will like.
1300 return ABIArgInfo::getDirect(llvm::VectorType::get(
1301 llvm::Type::getInt64Ty(getVMContext()), 2));
1303 // Always return in register if it fits in a general purpose
1304 // register, or if it is 64 bits and has a single element.
1305 if ((Size == 8 || Size == 16 || Size == 32) ||
1306 (Size == 64 && VT->getNumElements() == 1))
1307 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1310 return getIndirectReturnResult(RetTy, State);
1313 return ABIArgInfo::getDirect();
1316 if (isAggregateTypeForABI(RetTy)) {
1317 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
1318 // Structures with flexible arrays are always indirect.
1319 if (RT->getDecl()->hasFlexibleArrayMember())
1320 return getIndirectReturnResult(RetTy, State);
1323 // If specified, structs and unions are always indirect.
1324 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
1325 return getIndirectReturnResult(RetTy, State);
1327 // Ignore empty structs/unions.
1328 if (isEmptyRecord(getContext(), RetTy, true))
1329 return ABIArgInfo::getIgnore();
1331 // Small structures which are register sized are generally returned
1333 if (shouldReturnTypeInRegister(RetTy, getContext())) {
1334 uint64_t Size = getContext().getTypeSize(RetTy);
1336 // As a special-case, if the struct is a "single-element" struct, and
1337 // the field is of type "float" or "double", return it in a
1338 // floating-point register. (MSVC does not apply this special case.)
1339 // We apply a similar transformation for pointer types to improve the
1340 // quality of the generated IR.
1341 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
1342 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
1343 || SeltTy->hasPointerRepresentation())
1344 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1346 // FIXME: We should be able to narrow this integer in cases with dead
1348 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
1351 return getIndirectReturnResult(RetTy, State);
1354 // Treat an enum type as its underlying type.
1355 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1356 RetTy = EnumTy->getDecl()->getIntegerType();
1358 return (RetTy->isPromotableIntegerType() ?
1359 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1362 static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1363 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1366 static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1367 const RecordType *RT = Ty->getAs<RecordType>();
1370 const RecordDecl *RD = RT->getDecl();
1372 // If this is a C++ record, check the bases first.
1373 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1374 for (const auto &I : CXXRD->bases())
1375 if (!isRecordWithSSEVectorType(Context, I.getType()))
1378 for (const auto *i : RD->fields()) {
1379 QualType FT = i->getType();
1381 if (isSSEVectorType(Context, FT))
1384 if (isRecordWithSSEVectorType(Context, FT))
1391 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1392 unsigned Align) const {
1393 // Otherwise, if the alignment is less than or equal to the minimum ABI
1394 // alignment, just use the default; the backend will handle this.
1395 if (Align <= MinABIStackAlignInBytes)
1396 return 0; // Use default alignment.
1398 // On non-Darwin, the stack type alignment is always 4.
1399 if (!IsDarwinVectorABI) {
1400 // Set explicit alignment, since we may need to realign the top.
1401 return MinABIStackAlignInBytes;
1404 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
1405 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1406 isRecordWithSSEVectorType(getContext(), Ty)))
1409 return MinABIStackAlignInBytes;
1412 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
1413 CCState &State) const {
1415 if (State.FreeRegs) {
1416 --State.FreeRegs; // Non-byval indirects just use one pointer.
1418 return getNaturalAlignIndirectInReg(Ty);
1420 return getNaturalAlignIndirect(Ty, false);
1423 // Compute the byval alignment.
1424 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1425 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1426 if (StackAlign == 0)
1427 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
1429 // If the stack alignment is less than the type alignment, realign the
1431 bool Realign = TypeAlign > StackAlign;
1432 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1433 /*ByVal=*/true, Realign);
1436 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1437 const Type *T = isSingleElementStruct(Ty, getContext());
1439 T = Ty.getTypePtr();
1441 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1442 BuiltinType::Kind K = BT->getKind();
1443 if (K == BuiltinType::Float || K == BuiltinType::Double)
1449 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
1450 if (!IsSoftFloatABI) {
1451 Class C = classify(Ty);
1456 unsigned Size = getContext().getTypeSize(Ty);
1457 unsigned SizeInRegs = (Size + 31) / 32;
1459 if (SizeInRegs == 0)
1463 if (SizeInRegs > State.FreeRegs) {
1468 // The MCU psABI allows passing parameters in-reg even if there are
1469 // earlier parameters that are passed on the stack. Also,
1470 // it does not allow passing >8-byte structs in-register,
1471 // even if there are 3 free registers available.
1472 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1476 State.FreeRegs -= SizeInRegs;
1480 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1482 bool &NeedsPadding) const {
1483 // On Windows, aggregates other than HFAs are never passed in registers, and
1484 // they do not consume register slots. Homogenous floating-point aggregates
1485 // (HFAs) have already been dealt with at this point.
1486 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1489 NeedsPadding = false;
1492 if (!updateFreeRegs(Ty, State))
1498 if (State.CC == llvm::CallingConv::X86_FastCall ||
1499 State.CC == llvm::CallingConv::X86_VectorCall ||
1500 State.CC == llvm::CallingConv::X86_RegCall) {
1501 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
1502 NeedsPadding = true;
1510 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1511 if (!updateFreeRegs(Ty, State))
1517 if (State.CC == llvm::CallingConv::X86_FastCall ||
1518 State.CC == llvm::CallingConv::X86_VectorCall ||
1519 State.CC == llvm::CallingConv::X86_RegCall) {
1520 if (getContext().getTypeSize(Ty) > 32)
1523 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1524 Ty->isReferenceType());
1531 X86_32ABIInfo::reclassifyHvaArgType(QualType Ty, CCState &State,
1532 const ABIArgInfo ¤t) const {
1533 // Assumes vectorCall calling convention.
1534 const Type *Base = nullptr;
1535 uint64_t NumElts = 0;
1537 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
1538 isHomogeneousAggregate(Ty, Base, NumElts)) {
1539 if (State.FreeSSERegs >= NumElts) {
1540 // HVA types get passed directly in registers if there is room.
1541 State.FreeSSERegs -= NumElts;
1542 return getDirectX86Hva();
1544 // If there's no room, the HVA gets passed as normal indirect
1546 return getIndirectResult(Ty, /*ByVal=*/false, State);
1551 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1552 CCState &State) const {
1553 // FIXME: Set alignment on indirect arguments.
1555 Ty = useFirstFieldIfTransparentUnion(Ty);
1557 // Check with the C++ ABI first.
1558 const RecordType *RT = Ty->getAs<RecordType>();
1560 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1561 if (RAA == CGCXXABI::RAA_Indirect) {
1562 return getIndirectResult(Ty, false, State);
1563 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1564 // The field index doesn't matter, we'll fix it up later.
1565 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1569 // vectorcall adds the concept of a homogenous vector aggregate, similar
1570 // to other targets, regcall uses some of the HVA rules.
1571 const Type *Base = nullptr;
1572 uint64_t NumElts = 0;
1573 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1574 State.CC == llvm::CallingConv::X86_RegCall) &&
1575 isHomogeneousAggregate(Ty, Base, NumElts)) {
1577 if (State.CC == llvm::CallingConv::X86_RegCall) {
1578 if (State.FreeSSERegs >= NumElts) {
1579 State.FreeSSERegs -= NumElts;
1580 if (Ty->isBuiltinType() || Ty->isVectorType())
1581 return ABIArgInfo::getDirect();
1582 return ABIArgInfo::getExpand();
1585 return getIndirectResult(Ty, /*ByVal=*/false, State);
1586 } else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1587 if (State.FreeSSERegs >= NumElts && (Ty->isBuiltinType() || Ty->isVectorType())) {
1588 // Actual floating-point types get registers first time through if
1589 // there is registers available
1590 State.FreeSSERegs -= NumElts;
1591 return ABIArgInfo::getDirect();
1592 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
1593 // HVA Types only get registers after everything else has been
1594 // set, so it gets set as indirect for now.
1595 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty));
1600 if (isAggregateTypeForABI(Ty)) {
1601 // Structures with flexible arrays are always indirect.
1602 // FIXME: This should not be byval!
1603 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1604 return getIndirectResult(Ty, true, State);
1606 // Ignore empty structs/unions on non-Windows.
1607 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
1608 return ABIArgInfo::getIgnore();
1610 llvm::LLVMContext &LLVMContext = getVMContext();
1611 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1612 bool NeedsPadding = false;
1614 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
1615 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
1616 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
1617 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1619 return ABIArgInfo::getDirectInReg(Result);
1621 return ABIArgInfo::getDirect(Result);
1623 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
1625 // Expand small (<= 128-bit) record types when we know that the stack layout
1626 // of those arguments will match the struct. This is important because the
1627 // LLVM backend isn't smart enough to remove byval, which inhibits many
1629 // Don't do this for the MCU if there are still free integer registers
1630 // (see X86_64 ABI for full explanation).
1631 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1632 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
1633 return ABIArgInfo::getExpandWithPadding(
1634 State.CC == llvm::CallingConv::X86_FastCall ||
1635 State.CC == llvm::CallingConv::X86_VectorCall ||
1636 State.CC == llvm::CallingConv::X86_RegCall,
1639 return getIndirectResult(Ty, true, State);
1642 if (const VectorType *VT = Ty->getAs<VectorType>()) {
1643 // On Darwin, some vectors are passed in memory, we handle this by passing
1644 // it as an i8/i16/i32/i64.
1645 if (IsDarwinVectorABI) {
1646 uint64_t Size = getContext().getTypeSize(Ty);
1647 if ((Size == 8 || Size == 16 || Size == 32) ||
1648 (Size == 64 && VT->getNumElements() == 1))
1649 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1653 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1654 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
1656 return ABIArgInfo::getDirect();
1660 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1661 Ty = EnumTy->getDecl()->getIntegerType();
1663 bool InReg = shouldPrimitiveUseInReg(Ty, State);
1665 if (Ty->isPromotableIntegerType()) {
1667 return ABIArgInfo::getExtendInReg();
1668 return ABIArgInfo::getExtend();
1672 return ABIArgInfo::getDirectInReg();
1673 return ABIArgInfo::getDirect();
1676 void X86_32ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1677 bool &UsedInAlloca) const {
1678 // Vectorcall only allows the first 6 parameters to be passed in registers,
1679 // and homogeneous vector aggregates are only put into registers as a second
1682 CCState ZeroState = State;
1683 ZeroState.FreeRegs = ZeroState.FreeSSERegs = 0;
1684 // HVAs must be done as a second priority for registers, so the deferred
1685 // items are dealt with by going through the pattern a second time.
1686 for (auto &I : FI.arguments()) {
1687 if (Count < VectorcallMaxParamNumAsReg)
1688 I.info = classifyArgumentType(I.type, State);
1690 // Parameters after the 6th cannot be passed in registers,
1691 // so pretend there are no registers left for them.
1692 I.info = classifyArgumentType(I.type, ZeroState);
1693 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1697 // Go through the arguments a second time to get HVAs registers if there
1698 // are still some available.
1699 for (auto &I : FI.arguments()) {
1700 if (Count < VectorcallMaxParamNumAsReg)
1701 I.info = reclassifyHvaArgType(I.type, State, I.info);
1706 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
1707 CCState State(FI.getCallingConvention());
1710 else if (State.CC == llvm::CallingConv::X86_FastCall)
1712 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1714 State.FreeSSERegs = 6;
1715 } else if (FI.getHasRegParm())
1716 State.FreeRegs = FI.getRegParm();
1717 else if (State.CC == llvm::CallingConv::X86_RegCall) {
1719 State.FreeSSERegs = 8;
1721 State.FreeRegs = DefaultNumRegisterParameters;
1723 if (!getCXXABI().classifyReturnType(FI)) {
1724 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
1725 } else if (FI.getReturnInfo().isIndirect()) {
1726 // The C++ ABI is not aware of register usage, so we have to check if the
1727 // return value was sret and put it in a register ourselves if appropriate.
1728 if (State.FreeRegs) {
1729 --State.FreeRegs; // The sret parameter consumes a register.
1731 FI.getReturnInfo().setInReg(true);
1735 // The chain argument effectively gives us another free register.
1736 if (FI.isChainCall())
1739 bool UsedInAlloca = false;
1740 if (State.CC == llvm::CallingConv::X86_VectorCall) {
1741 computeVectorCallArgs(FI, State, UsedInAlloca);
1743 // If not vectorcall, revert to normal behavior.
1744 for (auto &I : FI.arguments()) {
1745 I.info = classifyArgumentType(I.type, State);
1746 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1750 // If we needed to use inalloca for any argument, do a second pass and rewrite
1751 // all the memory arguments to use inalloca.
1753 rewriteWithInAlloca(FI);
1757 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1758 CharUnits &StackOffset, ABIArgInfo &Info,
1759 QualType Type) const {
1760 // Arguments are always 4-byte-aligned.
1761 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1763 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
1764 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1765 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
1766 StackOffset += getContext().getTypeSizeInChars(Type);
1768 // Insert padding bytes to respect alignment.
1769 CharUnits FieldEnd = StackOffset;
1770 StackOffset = FieldEnd.alignTo(FieldAlign);
1771 if (StackOffset != FieldEnd) {
1772 CharUnits NumBytes = StackOffset - FieldEnd;
1773 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1774 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
1775 FrameFields.push_back(Ty);
1779 static bool isArgInAlloca(const ABIArgInfo &Info) {
1780 // Leave ignored and inreg arguments alone.
1781 switch (Info.getKind()) {
1782 case ABIArgInfo::InAlloca:
1784 case ABIArgInfo::Indirect:
1785 assert(Info.getIndirectByVal());
1787 case ABIArgInfo::Ignore:
1789 case ABIArgInfo::Direct:
1790 case ABIArgInfo::Extend:
1791 if (Info.getInReg())
1794 case ABIArgInfo::Expand:
1795 case ABIArgInfo::CoerceAndExpand:
1796 // These are aggregate types which are never passed in registers when
1797 // inalloca is involved.
1800 llvm_unreachable("invalid enum");
1803 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1804 assert(IsWin32StructABI && "inalloca only supported on win32");
1806 // Build a packed struct type for all of the arguments in memory.
1807 SmallVector<llvm::Type *, 6> FrameFields;
1809 // The stack alignment is always 4.
1810 CharUnits StackAlign = CharUnits::fromQuantity(4);
1812 CharUnits StackOffset;
1813 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1815 // Put 'this' into the struct before 'sret', if necessary.
1817 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1818 ABIArgInfo &Ret = FI.getReturnInfo();
1819 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1820 isArgInAlloca(I->info)) {
1821 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1825 // Put the sret parameter into the inalloca struct if it's in memory.
1826 if (Ret.isIndirect() && !Ret.getInReg()) {
1827 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1828 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
1829 // On Windows, the hidden sret parameter is always returned in eax.
1830 Ret.setInAllocaSRet(IsWin32StructABI);
1833 // Skip the 'this' parameter in ecx.
1837 // Put arguments passed in memory into the struct.
1838 for (; I != E; ++I) {
1839 if (isArgInAlloca(I->info))
1840 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1843 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1848 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1849 Address VAListAddr, QualType Ty) const {
1851 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
1853 // x86-32 changes the alignment of certain arguments on the stack.
1855 // Just messing with TypeInfo like this works because we never pass
1856 // anything indirectly.
1857 TypeInfo.second = CharUnits::fromQuantity(
1858 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
1860 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1861 TypeInfo, CharUnits::fromQuantity(4),
1862 /*AllowHigherAlign*/ true);
1865 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1866 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1867 assert(Triple.getArch() == llvm::Triple::x86);
1869 switch (Opts.getStructReturnConvention()) {
1870 case CodeGenOptions::SRCK_Default:
1872 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1874 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1878 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
1881 switch (Triple.getOS()) {
1882 case llvm::Triple::DragonFly:
1883 case llvm::Triple::FreeBSD:
1884 case llvm::Triple::OpenBSD:
1885 case llvm::Triple::Bitrig:
1886 case llvm::Triple::Win32:
1893 void X86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
1894 llvm::GlobalValue *GV,
1895 CodeGen::CodeGenModule &CGM) const {
1896 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
1897 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1898 // Get the LLVM function.
1899 llvm::Function *Fn = cast<llvm::Function>(GV);
1901 // Now add the 'alignstack' attribute with a value of 16.
1902 llvm::AttrBuilder B;
1903 B.addStackAlignmentAttr(16);
1905 llvm::AttributeList::FunctionIndex,
1906 llvm::AttributeList::get(CGM.getLLVMContext(),
1907 llvm::AttributeList::FunctionIndex, B));
1909 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1910 llvm::Function *Fn = cast<llvm::Function>(GV);
1911 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1916 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1917 CodeGen::CodeGenFunction &CGF,
1918 llvm::Value *Address) const {
1919 CodeGen::CGBuilderTy &Builder = CGF.Builder;
1921 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
1923 // 0-7 are the eight integer registers; the order is different
1924 // on Darwin (for EH), but the range is the same.
1926 AssignToArrayRange(Builder, Address, Four8, 0, 8);
1928 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
1929 // 12-16 are st(0..4). Not sure why we stop at 4.
1930 // These have size 16, which is sizeof(long double) on
1931 // platforms with 8-byte alignment for that type.
1932 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
1933 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
1936 // 9 is %eflags, which doesn't get a size on Darwin for some
1938 Builder.CreateAlignedStore(
1939 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1942 // 11-16 are st(0..5). Not sure why we stop at 5.
1943 // These have size 12, which is sizeof(long double) on
1944 // platforms with 4-byte alignment for that type.
1945 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
1946 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1952 //===----------------------------------------------------------------------===//
1953 // X86-64 ABI Implementation
1954 //===----------------------------------------------------------------------===//
1958 /// The AVX ABI level for X86 targets.
1959 enum class X86AVXABILevel {
1965 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1966 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1968 case X86AVXABILevel::AVX512:
1970 case X86AVXABILevel::AVX:
1972 case X86AVXABILevel::None:
1975 llvm_unreachable("Unknown AVXLevel");
1978 /// X86_64ABIInfo - The X86_64 ABI information.
1979 class X86_64ABIInfo : public SwiftABIInfo {
1991 /// merge - Implement the X86_64 ABI merging algorithm.
1993 /// Merge an accumulating classification \arg Accum with a field
1994 /// classification \arg Field.
1996 /// \param Accum - The accumulating classification. This should
1997 /// always be either NoClass or the result of a previous merge
1998 /// call. In addition, this should never be Memory (the caller
1999 /// should just return Memory for the aggregate).
2000 static Class merge(Class Accum, Class Field);
2002 /// postMerge - Implement the X86_64 ABI post merging algorithm.
2004 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2005 /// final MEMORY or SSE classes when necessary.
2007 /// \param AggregateSize - The size of the current aggregate in
2008 /// the classification process.
2010 /// \param Lo - The classification for the parts of the type
2011 /// residing in the low word of the containing object.
2013 /// \param Hi - The classification for the parts of the type
2014 /// residing in the higher words of the containing object.
2016 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2018 /// classify - Determine the x86_64 register classes in which the
2019 /// given type T should be passed.
2021 /// \param Lo - The classification for the parts of the type
2022 /// residing in the low word of the containing object.
2024 /// \param Hi - The classification for the parts of the type
2025 /// residing in the high word of the containing object.
2027 /// \param OffsetBase - The bit offset of this type in the
2028 /// containing object. Some parameters are classified different
2029 /// depending on whether they straddle an eightbyte boundary.
2031 /// \param isNamedArg - Whether the argument in question is a "named"
2032 /// argument, as used in AMD64-ABI 3.5.7.
2034 /// If a word is unused its result will be NoClass; if a type should
2035 /// be passed in Memory then at least the classification of \arg Lo
2038 /// The \arg Lo class will be NoClass iff the argument is ignored.
2040 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2041 /// also be ComplexX87.
2042 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2043 bool isNamedArg) const;
2045 llvm::Type *GetByteVectorType(QualType Ty) const;
2046 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2047 unsigned IROffset, QualType SourceTy,
2048 unsigned SourceOffset) const;
2049 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2050 unsigned IROffset, QualType SourceTy,
2051 unsigned SourceOffset) const;
2053 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2054 /// such that the argument will be returned in memory.
2055 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
2057 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2058 /// such that the argument will be passed in memory.
2060 /// \param freeIntRegs - The number of free integer registers remaining
2062 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
2064 ABIArgInfo classifyReturnType(QualType RetTy) const;
2066 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2067 unsigned &neededInt, unsigned &neededSSE,
2068 bool isNamedArg) const;
2070 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2071 unsigned &NeededSSE) const;
2073 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2074 unsigned &NeededSSE) const;
2076 bool IsIllegalVectorType(QualType Ty) const;
2078 /// The 0.98 ABI revision clarified a lot of ambiguities,
2079 /// unfortunately in ways that were not always consistent with
2080 /// certain previous compilers. In particular, platforms which
2081 /// required strict binary compatibility with older versions of GCC
2082 /// may need to exempt themselves.
2083 bool honorsRevision0_98() const {
2084 return !getTarget().getTriple().isOSDarwin();
2087 /// GCC classifies <1 x long long> as SSE but compatibility with older clang
2088 // compilers require us to classify it as INTEGER.
2089 bool classifyIntegerMMXAsSSE() const {
2090 const llvm::Triple &Triple = getTarget().getTriple();
2091 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2093 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2098 X86AVXABILevel AVXLevel;
2099 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2101 bool Has64BitPointers;
2104 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
2105 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2106 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
2109 bool isPassedUsingAVXType(QualType type) const {
2110 unsigned neededInt, neededSSE;
2111 // The freeIntRegs argument doesn't matter here.
2112 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2113 /*isNamedArg*/true);
2114 if (info.isDirect()) {
2115 llvm::Type *ty = info.getCoerceToType();
2116 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2117 return (vectorTy->getBitWidth() > 128);
2122 void computeInfo(CGFunctionInfo &FI) const override;
2124 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2125 QualType Ty) const override;
2126 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2127 QualType Ty) const override;
2129 bool has64BitPointers() const {
2130 return Has64BitPointers;
2133 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
2134 ArrayRef<llvm::Type*> scalars,
2135 bool asReturnValue) const override {
2136 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2138 bool isSwiftErrorInRegister() const override {
2143 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
2144 class WinX86_64ABIInfo : public SwiftABIInfo {
2146 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
2147 : SwiftABIInfo(CGT),
2148 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
2150 void computeInfo(CGFunctionInfo &FI) const override;
2152 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2153 QualType Ty) const override;
2155 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2156 // FIXME: Assumes vectorcall is in use.
2157 return isX86VectorTypeForVectorCall(getContext(), Ty);
2160 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2161 uint64_t NumMembers) const override {
2162 // FIXME: Assumes vectorcall is in use.
2163 return isX86VectorCallAggregateSmallEnough(NumMembers);
2166 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
2167 ArrayRef<llvm::Type *> scalars,
2168 bool asReturnValue) const override {
2169 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2172 bool isSwiftErrorInRegister() const override {
2177 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2178 bool IsVectorCall, bool IsRegCall) const;
2179 ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
2180 const ABIArgInfo ¤t) const;
2181 void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs,
2182 bool IsVectorCall, bool IsRegCall) const;
2187 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2189 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2190 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
2192 const X86_64ABIInfo &getABIInfo() const {
2193 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2196 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2200 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2201 llvm::Value *Address) const override {
2202 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2204 // 0-15 are the 16 integer registers.
2206 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2210 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
2211 StringRef Constraint,
2212 llvm::Type* Ty) const override {
2213 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2216 bool isNoProtoCallVariadic(const CallArgList &args,
2217 const FunctionNoProtoType *fnType) const override {
2218 // The default CC on x86-64 sets %al to the number of SSA
2219 // registers used, and GCC sets this when calling an unprototyped
2220 // function, so we override the default behavior. However, don't do
2221 // that when AVX types are involved: the ABI explicitly states it is
2222 // undefined, and it doesn't work in practice because of how the ABI
2223 // defines varargs anyway.
2224 if (fnType->getCallConv() == CC_C) {
2225 bool HasAVXType = false;
2226 for (CallArgList::const_iterator
2227 it = args.begin(), ie = args.end(); it != ie; ++it) {
2228 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2238 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
2242 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
2244 if (getABIInfo().has64BitPointers())
2245 Sig = (0xeb << 0) | // jmp rel8
2246 (0x0a << 8) | // .+0x0c
2250 Sig = (0xeb << 0) | // jmp rel8
2251 (0x06 << 8) | // .+0x08
2254 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2257 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2258 CodeGen::CodeGenModule &CGM) const override {
2259 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2260 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2261 llvm::Function *Fn = cast<llvm::Function>(GV);
2262 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2268 class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
2270 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2271 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
2273 void getDependentLibraryOption(llvm::StringRef Lib,
2274 llvm::SmallString<24> &Opt) const override {
2276 // If the argument contains a space, enclose it in quotes.
2277 if (Lib.find(" ") != StringRef::npos)
2278 Opt += "\"" + Lib.str() + "\"";
2284 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
2285 // If the argument does not end in .lib, automatically add the suffix.
2286 // If the argument contains a space, enclose it in quotes.
2287 // This matches the behavior of MSVC.
2288 bool Quote = (Lib.find(" ") != StringRef::npos);
2289 std::string ArgStr = Quote ? "\"" : "";
2291 if (!Lib.endswith_lower(".lib"))
2293 ArgStr += Quote ? "\"" : "";
2297 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2299 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2300 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2301 unsigned NumRegisterParameters)
2302 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
2303 Win32StructABI, NumRegisterParameters, false) {}
2305 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2306 CodeGen::CodeGenModule &CGM) const override;
2308 void getDependentLibraryOption(llvm::StringRef Lib,
2309 llvm::SmallString<24> &Opt) const override {
2310 Opt = "/DEFAULTLIB:";
2311 Opt += qualifyWindowsLibrary(Lib);
2314 void getDetectMismatchOption(llvm::StringRef Name,
2315 llvm::StringRef Value,
2316 llvm::SmallString<32> &Opt) const override {
2317 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2321 static void addStackProbeSizeTargetAttribute(const Decl *D,
2322 llvm::GlobalValue *GV,
2323 CodeGen::CodeGenModule &CGM) {
2324 if (D && isa<FunctionDecl>(D)) {
2325 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
2326 llvm::Function *Fn = cast<llvm::Function>(GV);
2328 Fn->addFnAttr("stack-probe-size",
2329 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
2334 void WinX86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
2335 llvm::GlobalValue *GV,
2336 CodeGen::CodeGenModule &CGM) const {
2337 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2339 addStackProbeSizeTargetAttribute(D, GV, CGM);
2342 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2344 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2345 X86AVXABILevel AVXLevel)
2346 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
2348 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2349 CodeGen::CodeGenModule &CGM) const override;
2351 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2355 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2356 llvm::Value *Address) const override {
2357 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2359 // 0-15 are the 16 integer registers.
2361 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2365 void getDependentLibraryOption(llvm::StringRef Lib,
2366 llvm::SmallString<24> &Opt) const override {
2367 Opt = "/DEFAULTLIB:";
2368 Opt += qualifyWindowsLibrary(Lib);
2371 void getDetectMismatchOption(llvm::StringRef Name,
2372 llvm::StringRef Value,
2373 llvm::SmallString<32> &Opt) const override {
2374 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2378 void WinX86_64TargetCodeGenInfo::setTargetAttributes(const Decl *D,
2379 llvm::GlobalValue *GV,
2380 CodeGen::CodeGenModule &CGM) const {
2381 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2383 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2384 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2385 llvm::Function *Fn = cast<llvm::Function>(GV);
2386 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2390 addStackProbeSizeTargetAttribute(D, GV, CGM);
2394 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2396 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2398 // (a) If one of the classes is Memory, the whole argument is passed in
2401 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2404 // (c) If the size of the aggregate exceeds two eightbytes and the first
2405 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2406 // argument is passed in memory. NOTE: This is necessary to keep the
2407 // ABI working for processors that don't support the __m256 type.
2409 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2411 // Some of these are enforced by the merging logic. Others can arise
2412 // only with unions; for example:
2413 // union { _Complex double; unsigned; }
2415 // Note that clauses (b) and (c) were added in 0.98.
2419 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2421 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2423 if (Hi == SSEUp && Lo != SSE)
2427 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
2428 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2429 // classified recursively so that always two fields are
2430 // considered. The resulting class is calculated according to
2431 // the classes of the fields in the eightbyte:
2433 // (a) If both classes are equal, this is the resulting class.
2435 // (b) If one of the classes is NO_CLASS, the resulting class is
2438 // (c) If one of the classes is MEMORY, the result is the MEMORY
2441 // (d) If one of the classes is INTEGER, the result is the
2444 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2445 // MEMORY is used as class.
2447 // (f) Otherwise class SSE is used.
2449 // Accum should never be memory (we should have returned) or
2450 // ComplexX87 (because this cannot be passed in a structure).
2451 assert((Accum != Memory && Accum != ComplexX87) &&
2452 "Invalid accumulated classification during merge.");
2453 if (Accum == Field || Field == NoClass)
2455 if (Field == Memory)
2457 if (Accum == NoClass)
2459 if (Accum == Integer || Field == Integer)
2461 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2462 Accum == X87 || Accum == X87Up)
2467 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
2468 Class &Lo, Class &Hi, bool isNamedArg) const {
2469 // FIXME: This code can be simplified by introducing a simple value class for
2470 // Class pairs with appropriate constructor methods for the various
2473 // FIXME: Some of the split computations are wrong; unaligned vectors
2474 // shouldn't be passed in registers for example, so there is no chance they
2475 // can straddle an eightbyte. Verify & simplify.
2479 Class &Current = OffsetBase < 64 ? Lo : Hi;
2482 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
2483 BuiltinType::Kind k = BT->getKind();
2485 if (k == BuiltinType::Void) {
2487 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2490 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2492 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
2494 } else if (k == BuiltinType::LongDouble) {
2495 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2496 if (LDF == &llvm::APFloat::IEEEquad()) {
2499 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
2502 } else if (LDF == &llvm::APFloat::IEEEdouble()) {
2505 llvm_unreachable("unexpected long double representation!");
2507 // FIXME: _Decimal32 and _Decimal64 are SSE.
2508 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
2512 if (const EnumType *ET = Ty->getAs<EnumType>()) {
2513 // Classify the underlying integer type.
2514 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
2518 if (Ty->hasPointerRepresentation()) {
2523 if (Ty->isMemberPointerType()) {
2524 if (Ty->isMemberFunctionPointerType()) {
2525 if (Has64BitPointers) {
2526 // If Has64BitPointers, this is an {i64, i64}, so classify both
2530 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2531 // straddles an eightbyte boundary, Hi should be classified as well.
2532 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2533 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2534 if (EB_FuncPtr != EB_ThisAdj) {
2546 if (const VectorType *VT = Ty->getAs<VectorType>()) {
2547 uint64_t Size = getContext().getTypeSize(VT);
2548 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2549 // gcc passes the following as integer:
2550 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2551 // 2 bytes - <2 x char>, <1 x short>
2552 // 1 byte - <1 x char>
2555 // If this type crosses an eightbyte boundary, it should be
2557 uint64_t EB_Lo = (OffsetBase) / 64;
2558 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2561 } else if (Size == 64) {
2562 QualType ElementType = VT->getElementType();
2564 // gcc passes <1 x double> in memory. :(
2565 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
2568 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2569 // pass them as integer. For platforms where clang is the de facto
2570 // platform compiler, we must continue to use integer.
2571 if (!classifyIntegerMMXAsSSE() &&
2572 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2573 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2574 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2575 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
2580 // If this type crosses an eightbyte boundary, it should be
2582 if (OffsetBase && OffsetBase != 64)
2584 } else if (Size == 128 ||
2585 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
2586 // Arguments of 256-bits are split into four eightbyte chunks. The
2587 // least significant one belongs to class SSE and all the others to class
2588 // SSEUP. The original Lo and Hi design considers that types can't be
2589 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2590 // This design isn't correct for 256-bits, but since there're no cases
2591 // where the upper parts would need to be inspected, avoid adding
2592 // complexity and just consider Hi to match the 64-256 part.
2594 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2595 // registers if they are "named", i.e. not part of the "..." of a
2596 // variadic function.
2598 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2599 // split into eight eightbyte chunks, one SSE and seven SSEUP.
2606 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
2607 QualType ET = getContext().getCanonicalType(CT->getElementType());
2609 uint64_t Size = getContext().getTypeSize(Ty);
2610 if (ET->isIntegralOrEnumerationType()) {
2613 else if (Size <= 128)
2615 } else if (ET == getContext().FloatTy) {
2617 } else if (ET == getContext().DoubleTy) {
2619 } else if (ET == getContext().LongDoubleTy) {
2620 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2621 if (LDF == &llvm::APFloat::IEEEquad())
2623 else if (LDF == &llvm::APFloat::x87DoubleExtended())
2624 Current = ComplexX87;
2625 else if (LDF == &llvm::APFloat::IEEEdouble())
2628 llvm_unreachable("unexpected long double representation!");
2631 // If this complex type crosses an eightbyte boundary then it
2633 uint64_t EB_Real = (OffsetBase) / 64;
2634 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
2635 if (Hi == NoClass && EB_Real != EB_Imag)
2641 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2642 // Arrays are treated like structures.
2644 uint64_t Size = getContext().getTypeSize(Ty);
2646 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2647 // than eight eightbytes, ..., it has class MEMORY.
2651 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2652 // fields, it has class MEMORY.
2654 // Only need to check alignment of array base.
2655 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
2658 // Otherwise implement simplified merge. We could be smarter about
2659 // this, but it isn't worth it and would be harder to verify.
2661 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
2662 uint64_t ArraySize = AT->getSize().getZExtValue();
2664 // The only case a 256-bit wide vector could be used is when the array
2665 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2666 // to work for sizes wider than 128, early check and fallback to memory.
2669 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
2672 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2673 Class FieldLo, FieldHi;
2674 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
2675 Lo = merge(Lo, FieldLo);
2676 Hi = merge(Hi, FieldHi);
2677 if (Lo == Memory || Hi == Memory)
2681 postMerge(Size, Lo, Hi);
2682 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
2686 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2687 uint64_t Size = getContext().getTypeSize(Ty);
2689 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2690 // than eight eightbytes, ..., it has class MEMORY.
2694 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2695 // copy constructor or a non-trivial destructor, it is passed by invisible
2697 if (getRecordArgABI(RT, getCXXABI()))
2700 const RecordDecl *RD = RT->getDecl();
2702 // Assume variable sized types are passed in memory.
2703 if (RD->hasFlexibleArrayMember())
2706 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2708 // Reset Lo class, this will be recomputed.
2711 // If this is a C++ record, classify the bases first.
2712 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
2713 for (const auto &I : CXXRD->bases()) {
2714 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
2715 "Unexpected base class!");
2716 const CXXRecordDecl *Base =
2717 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
2719 // Classify this field.
2721 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2722 // single eightbyte, each is classified separately. Each eightbyte gets
2723 // initialized to class NO_CLASS.
2724 Class FieldLo, FieldHi;
2726 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
2727 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
2728 Lo = merge(Lo, FieldLo);
2729 Hi = merge(Hi, FieldHi);
2730 if (Lo == Memory || Hi == Memory) {
2731 postMerge(Size, Lo, Hi);
2737 // Classify the fields one at a time, merging the results.
2739 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2740 i != e; ++i, ++idx) {
2741 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2742 bool BitField = i->isBitField();
2744 // Ignore padding bit-fields.
2745 if (BitField && i->isUnnamedBitfield())
2748 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2749 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
2751 // The only case a 256-bit wide vector could be used is when the struct
2752 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2753 // to work for sizes wider than 128, early check and fallback to memory.
2755 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2756 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
2758 postMerge(Size, Lo, Hi);
2761 // Note, skip this test for bit-fields, see below.
2762 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
2764 postMerge(Size, Lo, Hi);
2768 // Classify this field.
2770 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2771 // exceeds a single eightbyte, each is classified
2772 // separately. Each eightbyte gets initialized to class
2774 Class FieldLo, FieldHi;
2776 // Bit-fields require special handling, they do not force the
2777 // structure to be passed in memory even if unaligned, and
2778 // therefore they can straddle an eightbyte.
2780 assert(!i->isUnnamedBitfield());
2781 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2782 uint64_t Size = i->getBitWidthValue(getContext());
2784 uint64_t EB_Lo = Offset / 64;
2785 uint64_t EB_Hi = (Offset + Size - 1) / 64;
2788 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2793 FieldHi = EB_Hi ? Integer : NoClass;
2796 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
2797 Lo = merge(Lo, FieldLo);
2798 Hi = merge(Hi, FieldHi);
2799 if (Lo == Memory || Hi == Memory)
2803 postMerge(Size, Lo, Hi);
2807 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
2808 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2810 if (!isAggregateTypeForABI(Ty)) {
2811 // Treat an enum type as its underlying type.
2812 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2813 Ty = EnumTy->getDecl()->getIntegerType();
2815 return (Ty->isPromotableIntegerType() ?
2816 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2819 return getNaturalAlignIndirect(Ty);
2822 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2823 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2824 uint64_t Size = getContext().getTypeSize(VecTy);
2825 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
2826 if (Size <= 64 || Size > LargestVector)
2833 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2834 unsigned freeIntRegs) const {
2835 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2838 // This assumption is optimistic, as there could be free registers available
2839 // when we need to pass this argument in memory, and LLVM could try to pass
2840 // the argument in the free register. This does not seem to happen currently,
2841 // but this code would be much safer if we could mark the argument with
2842 // 'onstack'. See PR12193.
2843 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
2844 // Treat an enum type as its underlying type.
2845 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2846 Ty = EnumTy->getDecl()->getIntegerType();
2848 return (Ty->isPromotableIntegerType() ?
2849 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2852 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
2853 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
2855 // Compute the byval alignment. We specify the alignment of the byval in all
2856 // cases so that the mid-level optimizer knows the alignment of the byval.
2857 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
2859 // Attempt to avoid passing indirect results using byval when possible. This
2860 // is important for good codegen.
2862 // We do this by coercing the value into a scalar type which the backend can
2863 // handle naturally (i.e., without using byval).
2865 // For simplicity, we currently only do this when we have exhausted all of the
2866 // free integer registers. Doing this when there are free integer registers
2867 // would require more care, as we would have to ensure that the coerced value
2868 // did not claim the unused register. That would require either reording the
2869 // arguments to the function (so that any subsequent inreg values came first),
2870 // or only doing this optimization when there were no following arguments that
2873 // We currently expect it to be rare (particularly in well written code) for
2874 // arguments to be passed on the stack when there are still free integer
2875 // registers available (this would typically imply large structs being passed
2876 // by value), so this seems like a fair tradeoff for now.
2878 // We can revisit this if the backend grows support for 'onstack' parameter
2879 // attributes. See PR12193.
2880 if (freeIntRegs == 0) {
2881 uint64_t Size = getContext().getTypeSize(Ty);
2883 // If this type fits in an eightbyte, coerce it into the matching integral
2884 // type, which will end up on the stack (with alignment 8).
2885 if (Align == 8 && Size <= 64)
2886 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2890 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
2893 /// The ABI specifies that a value should be passed in a full vector XMM/YMM
2894 /// register. Pick an LLVM IR type that will be passed as a vector register.
2895 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
2896 // Wrapper structs/arrays that only contain vectors are passed just like
2897 // vectors; strip them off if present.
2898 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2899 Ty = QualType(InnerTy, 0);
2901 llvm::Type *IRType = CGT.ConvertType(Ty);
2902 if (isa<llvm::VectorType>(IRType) ||
2903 IRType->getTypeID() == llvm::Type::FP128TyID)
2906 // We couldn't find the preferred IR vector type for 'Ty'.
2907 uint64_t Size = getContext().getTypeSize(Ty);
2908 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
2910 // Return a LLVM IR vector type based on the size of 'Ty'.
2911 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2915 /// BitsContainNoUserData - Return true if the specified [start,end) bit range
2916 /// is known to either be off the end of the specified type or being in
2917 /// alignment padding. The user type specified is known to be at most 128 bits
2918 /// in size, and have passed through X86_64ABIInfo::classify with a successful
2919 /// classification that put one of the two halves in the INTEGER class.
2921 /// It is conservatively correct to return false.
2922 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2923 unsigned EndBit, ASTContext &Context) {
2924 // If the bytes being queried are off the end of the type, there is no user
2925 // data hiding here. This handles analysis of builtins, vectors and other
2926 // types that don't contain interesting padding.
2927 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2928 if (TySize <= StartBit)
2931 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2932 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2933 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2935 // Check each element to see if the element overlaps with the queried range.
2936 for (unsigned i = 0; i != NumElts; ++i) {
2937 // If the element is after the span we care about, then we're done..
2938 unsigned EltOffset = i*EltSize;
2939 if (EltOffset >= EndBit) break;
2941 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2942 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2943 EndBit-EltOffset, Context))
2946 // If it overlaps no elements, then it is safe to process as padding.
2950 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2951 const RecordDecl *RD = RT->getDecl();
2952 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2954 // If this is a C++ record, check the bases first.
2955 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
2956 for (const auto &I : CXXRD->bases()) {
2957 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
2958 "Unexpected base class!");
2959 const CXXRecordDecl *Base =
2960 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
2962 // If the base is after the span we care about, ignore it.
2963 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
2964 if (BaseOffset >= EndBit) continue;
2966 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
2967 if (!BitsContainNoUserData(I.getType(), BaseStart,
2968 EndBit-BaseOffset, Context))
2973 // Verify that no field has data that overlaps the region of interest. Yes
2974 // this could be sped up a lot by being smarter about queried fields,
2975 // however we're only looking at structs up to 16 bytes, so we don't care
2978 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2979 i != e; ++i, ++idx) {
2980 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
2982 // If we found a field after the region we care about, then we're done.
2983 if (FieldOffset >= EndBit) break;
2985 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2986 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2991 // If nothing in this record overlapped the area of interest, then we're
2999 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3000 /// float member at the specified offset. For example, {int,{float}} has a
3001 /// float at offset 4. It is conservatively correct for this routine to return
3003 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
3004 const llvm::DataLayout &TD) {
3005 // Base case if we find a float.
3006 if (IROffset == 0 && IRType->isFloatTy())
3009 // If this is a struct, recurse into the field at the specified offset.
3010 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3011 const llvm::StructLayout *SL = TD.getStructLayout(STy);
3012 unsigned Elt = SL->getElementContainingOffset(IROffset);
3013 IROffset -= SL->getElementOffset(Elt);
3014 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3017 // If this is an array, recurse into the field at the specified offset.
3018 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3019 llvm::Type *EltTy = ATy->getElementType();
3020 unsigned EltSize = TD.getTypeAllocSize(EltTy);
3021 IROffset -= IROffset/EltSize*EltSize;
3022 return ContainsFloatAtOffset(EltTy, IROffset, TD);
3029 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3030 /// low 8 bytes of an XMM register, corresponding to the SSE class.
3031 llvm::Type *X86_64ABIInfo::
3032 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3033 QualType SourceTy, unsigned SourceOffset) const {
3034 // The only three choices we have are either double, <2 x float>, or float. We
3035 // pass as float if the last 4 bytes is just padding. This happens for
3036 // structs that contain 3 floats.
3037 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3038 SourceOffset*8+64, getContext()))
3039 return llvm::Type::getFloatTy(getVMContext());
3041 // We want to pass as <2 x float> if the LLVM IR type contains a float at
3042 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
3044 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3045 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
3046 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
3048 return llvm::Type::getDoubleTy(getVMContext());
3052 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3053 /// an 8-byte GPR. This means that we either have a scalar or we are talking
3054 /// about the high or low part of an up-to-16-byte struct. This routine picks
3055 /// the best LLVM IR type to represent this, which may be i64 or may be anything
3056 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3059 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3060 /// the source type. IROffset is an offset in bytes into the LLVM IR type that
3061 /// the 8-byte value references. PrefType may be null.
3063 /// SourceTy is the source-level type for the entire argument. SourceOffset is
3064 /// an offset into this that we're processing (which is always either 0 or 8).
3066 llvm::Type *X86_64ABIInfo::
3067 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3068 QualType SourceTy, unsigned SourceOffset) const {
3069 // If we're dealing with an un-offset LLVM IR type, then it means that we're
3070 // returning an 8-byte unit starting with it. See if we can safely use it.
3071 if (IROffset == 0) {
3072 // Pointers and int64's always fill the 8-byte unit.
3073 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3074 IRType->isIntegerTy(64))
3077 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3078 // goodness in the source type is just tail padding. This is allowed to
3079 // kick in for struct {double,int} on the int, but not on
3080 // struct{double,int,int} because we wouldn't return the second int. We
3081 // have to do this analysis on the source type because we can't depend on
3082 // unions being lowered a specific way etc.
3083 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
3084 IRType->isIntegerTy(32) ||
3085 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3086 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3087 cast<llvm::IntegerType>(IRType)->getBitWidth();
3089 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3090 SourceOffset*8+64, getContext()))
3095 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3096 // If this is a struct, recurse into the field at the specified offset.
3097 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
3098 if (IROffset < SL->getSizeInBytes()) {
3099 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3100 IROffset -= SL->getElementOffset(FieldIdx);
3102 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3103 SourceTy, SourceOffset);
3107 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3108 llvm::Type *EltTy = ATy->getElementType();
3109 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
3110 unsigned EltOffset = IROffset/EltSize*EltSize;
3111 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3115 // Okay, we don't have any better idea of what to pass, so we pass this in an
3116 // integer register that isn't too big to fit the rest of the struct.
3117 unsigned TySizeInBytes =
3118 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
3120 assert(TySizeInBytes != SourceOffset && "Empty field?");
3122 // It is always safe to classify this as an integer type up to i64 that
3123 // isn't larger than the structure.
3124 return llvm::IntegerType::get(getVMContext(),
3125 std::min(TySizeInBytes-SourceOffset, 8U)*8);
3129 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3130 /// be used as elements of a two register pair to pass or return, return a
3131 /// first class aggregate to represent them. For example, if the low part of
3132 /// a by-value argument should be passed as i32* and the high part as float,
3133 /// return {i32*, float}.
3135 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
3136 const llvm::DataLayout &TD) {
3137 // In order to correctly satisfy the ABI, we need to the high part to start
3138 // at offset 8. If the high and low parts we inferred are both 4-byte types
3139 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3140 // the second element at offset 8. Check for this:
3141 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3142 unsigned HiAlign = TD.getABITypeAlignment(Hi);
3143 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
3144 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
3146 // To handle this, we have to increase the size of the low part so that the
3147 // second element will start at an 8 byte offset. We can't increase the size
3148 // of the second element because it might make us access off the end of the
3151 // There are usually two sorts of types the ABI generation code can produce
3152 // for the low part of a pair that aren't 8 bytes in size: float or
3153 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
3155 // Promote these to a larger type.
3156 if (Lo->isFloatTy())
3157 Lo = llvm::Type::getDoubleTy(Lo->getContext());
3159 assert((Lo->isIntegerTy() || Lo->isPointerTy())
3160 && "Invalid/unknown lo type");
3161 Lo = llvm::Type::getInt64Ty(Lo->getContext());
3165 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
3168 // Verify that the second element is at an 8-byte offset.
3169 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3170 "Invalid x86-64 argument pair!");
3174 ABIArgInfo X86_64ABIInfo::
3175 classifyReturnType(QualType RetTy) const {
3176 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3177 // classification algorithm.
3178 X86_64ABIInfo::Class Lo, Hi;
3179 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
3181 // Check some invariants.
3182 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3183 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3185 llvm::Type *ResType = nullptr;
3189 return ABIArgInfo::getIgnore();
3190 // If the low part is just padding, it takes no register, leave ResType
3192 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3193 "Unknown missing lo part");
3198 llvm_unreachable("Invalid classification for lo word.");
3200 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3203 return getIndirectReturnResult(RetTy);
3205 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3206 // available register of the sequence %rax, %rdx is used.
3208 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3210 // If we have a sign or zero extended integer, make sure to return Extend
3211 // so that the parameter gets the right LLVM IR attributes.
3212 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3213 // Treat an enum type as its underlying type.
3214 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3215 RetTy = EnumTy->getDecl()->getIntegerType();
3217 if (RetTy->isIntegralOrEnumerationType() &&
3218 RetTy->isPromotableIntegerType())
3219 return ABIArgInfo::getExtend();
3223 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3224 // available SSE register of the sequence %xmm0, %xmm1 is used.
3226 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3229 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3230 // returned on the X87 stack in %st0 as 80-bit x87 number.
3232 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
3235 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3236 // part of the value is returned in %st0 and the imaginary part in
3239 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
3240 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
3241 llvm::Type::getX86_FP80Ty(getVMContext()),
3246 llvm::Type *HighPart = nullptr;
3248 // Memory was handled previously and X87 should
3249 // never occur as a hi class.
3252 llvm_unreachable("Invalid classification for hi word.");
3254 case ComplexX87: // Previously handled.
3259 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3260 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3261 return ABIArgInfo::getDirect(HighPart, 8);
3264 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3265 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3266 return ABIArgInfo::getDirect(HighPart, 8);
3269 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
3270 // is passed in the next available eightbyte chunk if the last used
3273 // SSEUP should always be preceded by SSE, just widen.
3275 assert(Lo == SSE && "Unexpected SSEUp classification.");
3276 ResType = GetByteVectorType(RetTy);
3279 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3280 // returned together with the previous X87 value in %st0.
3282 // If X87Up is preceded by X87, we don't need to do
3283 // anything. However, in some cases with unions it may not be
3284 // preceded by X87. In such situations we follow gcc and pass the
3285 // extra bits in an SSE reg.
3287 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3288 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3289 return ABIArgInfo::getDirect(HighPart, 8);
3294 // If a high part was specified, merge it together with the low part. It is
3295 // known to pass in the high eightbyte of the result. We do this by forming a
3296 // first class struct aggregate with the high and low part: {low, high}
3298 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3300 return ABIArgInfo::getDirect(ResType);
3303 ABIArgInfo X86_64ABIInfo::classifyArgumentType(
3304 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3308 Ty = useFirstFieldIfTransparentUnion(Ty);
3310 X86_64ABIInfo::Class Lo, Hi;
3311 classify(Ty, 0, Lo, Hi, isNamedArg);
3313 // Check some invariants.
3314 // FIXME: Enforce these by construction.
3315 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3316 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3320 llvm::Type *ResType = nullptr;
3324 return ABIArgInfo::getIgnore();
3325 // If the low part is just padding, it takes no register, leave ResType
3327 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3328 "Unknown missing lo part");
3331 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3335 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3336 // COMPLEX_X87, it is passed in memory.
3339 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
3341 return getIndirectResult(Ty, freeIntRegs);
3345 llvm_unreachable("Invalid classification for lo word.");
3347 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3348 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3353 // Pick an 8-byte type based on the preferred type.
3354 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
3356 // If we have a sign or zero extended integer, make sure to return Extend
3357 // so that the parameter gets the right LLVM IR attributes.
3358 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3359 // Treat an enum type as its underlying type.
3360 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3361 Ty = EnumTy->getDecl()->getIntegerType();
3363 if (Ty->isIntegralOrEnumerationType() &&
3364 Ty->isPromotableIntegerType())
3365 return ABIArgInfo::getExtend();
3370 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3371 // available SSE register is used, the registers are taken in the
3372 // order from %xmm0 to %xmm7.
3374 llvm::Type *IRType = CGT.ConvertType(Ty);
3375 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
3381 llvm::Type *HighPart = nullptr;
3383 // Memory was handled previously, ComplexX87 and X87 should
3384 // never occur as hi classes, and X87Up must be preceded by X87,
3385 // which is passed in memory.
3389 llvm_unreachable("Invalid classification for hi word.");
3391 case NoClass: break;
3395 // Pick an 8-byte type based on the preferred type.
3396 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3398 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3399 return ABIArgInfo::getDirect(HighPart, 8);
3402 // X87Up generally doesn't occur here (long double is passed in
3403 // memory), except in situations involving unions.
3406 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3408 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3409 return ABIArgInfo::getDirect(HighPart, 8);
3414 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3415 // eightbyte is passed in the upper half of the last used SSE
3416 // register. This only happens when 128-bit vectors are passed.
3418 assert(Lo == SSE && "Unexpected SSEUp classification");
3419 ResType = GetByteVectorType(Ty);
3423 // If a high part was specified, merge it together with the low part. It is
3424 // known to pass in the high eightbyte of the result. We do this by forming a
3425 // first class struct aggregate with the high and low part: {low, high}
3427 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3429 return ABIArgInfo::getDirect(ResType);
3433 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3434 unsigned &NeededSSE) const {
3435 auto RT = Ty->getAs<RecordType>();
3436 assert(RT && "classifyRegCallStructType only valid with struct types");
3438 if (RT->getDecl()->hasFlexibleArrayMember())
3439 return getIndirectReturnResult(Ty);
3442 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3443 if (CXXRD->isDynamicClass()) {
3444 NeededInt = NeededSSE = 0;
3445 return getIndirectReturnResult(Ty);
3448 for (const auto &I : CXXRD->bases())
3449 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3451 NeededInt = NeededSSE = 0;
3452 return getIndirectReturnResult(Ty);
3457 for (const auto *FD : RT->getDecl()->fields()) {
3458 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3459 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3461 NeededInt = NeededSSE = 0;
3462 return getIndirectReturnResult(Ty);
3465 unsigned LocalNeededInt, LocalNeededSSE;
3466 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3467 LocalNeededSSE, true)
3469 NeededInt = NeededSSE = 0;
3470 return getIndirectReturnResult(Ty);
3472 NeededInt += LocalNeededInt;
3473 NeededSSE += LocalNeededSSE;
3477 return ABIArgInfo::getDirect();
3480 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3481 unsigned &NeededInt,
3482 unsigned &NeededSSE) const {
3487 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3490 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3492 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
3494 // Keep track of the number of assigned registers.
3495 unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3496 unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3497 unsigned NeededInt, NeededSSE;
3499 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3500 !FI.getReturnType()->getTypePtr()->isUnionType()) {
3501 FI.getReturnInfo() =
3502 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3503 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3504 FreeIntRegs -= NeededInt;
3505 FreeSSERegs -= NeededSSE;
3507 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3509 } else if (!getCXXABI().classifyReturnType(FI))
3510 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3512 // If the return value is indirect, then the hidden argument is consuming one
3513 // integer register.
3514 if (FI.getReturnInfo().isIndirect())
3517 // The chain argument effectively gives us another free register.
3518 if (FI.isChainCall())
3521 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
3522 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3523 // get assigned (in left-to-right order) for passing as follows...
3525 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3526 it != ie; ++it, ++ArgNo) {
3527 bool IsNamedArg = ArgNo < NumRequiredArgs;
3529 if (IsRegCall && it->type->isStructureOrClassType())
3530 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3532 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3533 NeededSSE, IsNamedArg);
3535 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3536 // eightbyte of an argument, the whole argument is passed on the
3537 // stack. If registers have already been assigned for some
3538 // eightbytes of such an argument, the assignments get reverted.
3539 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3540 FreeIntRegs -= NeededInt;
3541 FreeSSERegs -= NeededSSE;
3543 it->info = getIndirectResult(it->type, FreeIntRegs);
3548 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3549 Address VAListAddr, QualType Ty) {
3550 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3551 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
3552 llvm::Value *overflow_arg_area =
3553 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3555 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3556 // byte boundary if alignment needed by type exceeds 8 byte boundary.
3557 // It isn't stated explicitly in the standard, but in practice we use
3558 // alignment greater than 16 where necessary.
3559 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3560 if (Align > CharUnits::fromQuantity(8)) {
3561 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3565 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
3566 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
3568 CGF.Builder.CreateBitCast(overflow_arg_area,
3569 llvm::PointerType::getUnqual(LTy));
3571 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3572 // l->overflow_arg_area + sizeof(type).
3573 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3574 // an 8 byte boundary.
3576 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
3577 llvm::Value *Offset =
3578 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
3579 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3580 "overflow_arg_area.next");
3581 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3583 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
3584 return Address(Res, Align);
3587 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3588 QualType Ty) const {
3589 // Assume that va_list type is correct; should be pointer to LLVM type:
3593 // i8* overflow_arg_area;
3594 // i8* reg_save_area;
3596 unsigned neededInt, neededSSE;
3598 Ty = getContext().getCanonicalType(Ty);
3599 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
3600 /*isNamedArg*/false);
3602 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3603 // in the registers. If not go to step 7.
3604 if (!neededInt && !neededSSE)
3605 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
3607 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3608 // general purpose registers needed to pass type and num_fp to hold
3609 // the number of floating point registers needed.
3611 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3612 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3613 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3615 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3616 // register save space).
3618 llvm::Value *InRegs = nullptr;
3619 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3620 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
3623 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3625 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
3626 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3627 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
3632 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3634 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3635 llvm::Value *FitsInFP =
3636 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3637 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
3638 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3641 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3642 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3643 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3644 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3646 // Emit code to load the value if it was passed in registers.
3648 CGF.EmitBlock(InRegBlock);
3650 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3651 // an offset of l->gp_offset and/or l->fp_offset. This may require
3652 // copying to a temporary location in case the parameter is passed
3653 // in different register classes or requires an alignment greater
3654 // than 8 for general purpose registers and 16 for XMM registers.
3656 // FIXME: This really results in shameful code when we end up needing to
3657 // collect arguments from different places; often what should result in a
3658 // simple assembling of a structure from scattered addresses has many more
3659 // loads than necessary. Can we clean this up?
3660 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
3661 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3662 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3665 Address RegAddr = Address::invalid();
3666 if (neededInt && neededSSE) {
3668 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
3669 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
3670 Address Tmp = CGF.CreateMemTemp(Ty);
3671 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3672 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
3673 llvm::Type *TyLo = ST->getElementType(0);
3674 llvm::Type *TyHi = ST->getElementType(1);
3675 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
3676 "Unexpected ABI info for mixed regs");
3677 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3678 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
3679 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3680 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
3681 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3682 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
3684 // Copy the first element.
3685 // FIXME: Our choice of alignment here and below is probably pessimistic.
3686 llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3687 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
3688 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
3689 CGF.Builder.CreateStore(V,
3690 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3692 // Copy the second element.
3693 V = CGF.Builder.CreateAlignedLoad(
3694 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
3695 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
3696 CharUnits Offset = CharUnits::fromQuantity(
3697 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3698 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3700 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
3701 } else if (neededInt) {
3702 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3703 CharUnits::fromQuantity(8));
3704 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
3706 // Copy to a temporary if necessary to ensure the appropriate alignment.
3707 std::pair<CharUnits, CharUnits> SizeAlign =
3708 getContext().getTypeInfoInChars(Ty);
3709 uint64_t TySize = SizeAlign.first.getQuantity();
3710 CharUnits TyAlign = SizeAlign.second;
3712 // Copy into a temporary if the type is more aligned than the
3713 // register save area.
3714 if (TyAlign.getQuantity() > 8) {
3715 Address Tmp = CGF.CreateMemTemp(Ty);
3716 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
3720 } else if (neededSSE == 1) {
3721 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3722 CharUnits::fromQuantity(16));
3723 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
3725 assert(neededSSE == 2 && "Invalid number of needed registers!");
3726 // SSE registers are spaced 16 bytes apart in the register save
3727 // area, we need to collect the two eightbytes together.
3728 // The ABI isn't explicit about this, but it seems reasonable
3729 // to assume that the slots are 16-byte aligned, since the stack is
3730 // naturally 16-byte aligned and the prologue is expected to store
3731 // all the SSE registers to the RSA.
3732 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3733 CharUnits::fromQuantity(16));
3735 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3736 CharUnits::fromQuantity(16));
3737 llvm::Type *DoubleTy = CGF.DoubleTy;
3738 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
3740 Address Tmp = CGF.CreateMemTemp(Ty);
3741 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3742 V = CGF.Builder.CreateLoad(
3743 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3744 CGF.Builder.CreateStore(V,
3745 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3746 V = CGF.Builder.CreateLoad(
3747 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3748 CGF.Builder.CreateStore(V,
3749 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3751 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
3754 // AMD64-ABI 3.5.7p5: Step 5. Set:
3755 // l->gp_offset = l->gp_offset + num_gp * 8
3756 // l->fp_offset = l->fp_offset + num_fp * 16.
3758 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
3759 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3763 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
3764 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3767 CGF.EmitBranch(ContBlock);
3769 // Emit code to load the value if it was passed in memory.
3771 CGF.EmitBlock(InMemBlock);
3772 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
3774 // Return the appropriate result.
3776 CGF.EmitBlock(ContBlock);
3777 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3782 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3783 QualType Ty) const {
3784 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3785 CGF.getContext().getTypeInfoInChars(Ty),
3786 CharUnits::fromQuantity(8),
3787 /*allowHigherAlign*/ false);
3791 WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
3792 const ABIArgInfo ¤t) const {
3793 // Assumes vectorCall calling convention.
3794 const Type *Base = nullptr;
3795 uint64_t NumElts = 0;
3797 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
3798 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
3799 FreeSSERegs -= NumElts;
3800 return getDirectX86Hva();
3805 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3806 bool IsReturnType, bool IsVectorCall,
3807 bool IsRegCall) const {
3809 if (Ty->isVoidType())
3810 return ABIArgInfo::getIgnore();
3812 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3813 Ty = EnumTy->getDecl()->getIntegerType();
3815 TypeInfo Info = getContext().getTypeInfo(Ty);
3816 uint64_t Width = Info.Width;
3817 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
3819 const RecordType *RT = Ty->getAs<RecordType>();
3821 if (!IsReturnType) {
3822 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
3823 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
3826 if (RT->getDecl()->hasFlexibleArrayMember())
3827 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
3831 const Type *Base = nullptr;
3832 uint64_t NumElts = 0;
3833 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3835 if ((IsVectorCall || IsRegCall) &&
3836 isHomogeneousAggregate(Ty, Base, NumElts)) {
3838 if (FreeSSERegs >= NumElts) {
3839 FreeSSERegs -= NumElts;
3840 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3841 return ABIArgInfo::getDirect();
3842 return ABIArgInfo::getExpand();
3844 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3845 } else if (IsVectorCall) {
3846 if (FreeSSERegs >= NumElts &&
3847 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
3848 FreeSSERegs -= NumElts;
3849 return ABIArgInfo::getDirect();
3850 } else if (IsReturnType) {
3851 return ABIArgInfo::getExpand();
3852 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
3853 // HVAs are delayed and reclassified in the 2nd step.
3854 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3859 if (Ty->isMemberPointerType()) {
3860 // If the member pointer is represented by an LLVM int or ptr, pass it
3862 llvm::Type *LLTy = CGT.ConvertType(Ty);
3863 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3864 return ABIArgInfo::getDirect();
3867 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
3868 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3869 // not 1, 2, 4, or 8 bytes, must be passed by reference."
3870 if (Width > 64 || !llvm::isPowerOf2_64(Width))
3871 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
3873 // Otherwise, coerce it to a small integer.
3874 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
3877 // Bool type is always extended to the ABI, other builtin types are not
3879 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3880 if (BT && BT->getKind() == BuiltinType::Bool)
3881 return ABIArgInfo::getExtend();
3883 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3884 // passes them indirectly through memory.
3885 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3886 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3887 if (LDF == &llvm::APFloat::x87DoubleExtended())
3888 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3891 return ABIArgInfo::getDirect();
3894 void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI,
3895 unsigned FreeSSERegs,
3897 bool IsRegCall) const {
3899 for (auto &I : FI.arguments()) {
3900 if (Count < VectorcallMaxParamNumAsReg)
3901 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
3903 // Since these cannot be passed in registers, pretend no registers
3905 unsigned ZeroSSERegsAvail = 0;
3906 I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false,
3907 IsVectorCall, IsRegCall);
3913 for (auto &I : FI.arguments()) {
3914 if (Count < VectorcallMaxParamNumAsReg)
3915 I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info);
3920 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3922 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
3923 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
3925 unsigned FreeSSERegs = 0;
3927 // We can use up to 4 SSE return registers with vectorcall.
3929 } else if (IsRegCall) {
3930 // RegCall gives us 16 SSE registers.
3934 if (!getCXXABI().classifyReturnType(FI))
3935 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
3936 IsVectorCall, IsRegCall);
3939 // We can use up to 6 SSE register parameters with vectorcall.
3941 } else if (IsRegCall) {
3942 // RegCall gives us 16 SSE registers, we can reuse the return registers.
3947 computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall);
3949 for (auto &I : FI.arguments())
3950 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
3955 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3956 QualType Ty) const {
3958 bool IsIndirect = false;
3960 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3961 // not 1, 2, 4, or 8 bytes, must be passed by reference."
3962 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
3963 uint64_t Width = getContext().getTypeSize(Ty);
3964 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
3967 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
3968 CGF.getContext().getTypeInfoInChars(Ty),
3969 CharUnits::fromQuantity(8),
3970 /*allowHigherAlign*/ false);
3975 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3976 class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
3977 bool IsSoftFloatABI;
3979 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
3980 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
3982 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3983 QualType Ty) const override;
3986 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3988 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
3989 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
3991 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
3992 // This is recovered from gcc output.
3993 return 1; // r1 is the dedicated stack pointer
3996 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3997 llvm::Value *Address) const override;
4002 // TODO: this implementation is now likely redundant with
4003 // DefaultABIInfo::EmitVAArg.
4004 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4005 QualType Ty) const {
4006 const unsigned OverflowLimit = 8;
4007 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4008 // TODO: Implement this. For now ignore.
4010 return Address::invalid(); // FIXME?
4013 // struct __va_list_tag {
4014 // unsigned char gpr;
4015 // unsigned char fpr;
4016 // unsigned short reserved;
4017 // void *overflow_arg_area;
4018 // void *reg_save_area;
4021 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
4023 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
4024 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
4026 // All aggregates are passed indirectly? That doesn't seem consistent
4027 // with the argument-lowering code.
4028 bool isIndirect = Ty->isAggregateType();
4030 CGBuilderTy &Builder = CGF.Builder;
4032 // The calling convention either uses 1-2 GPRs or 1 FPR.
4033 Address NumRegsAddr = Address::invalid();
4034 if (isInt || IsSoftFloatABI) {
4035 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
4037 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
4040 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4042 // "Align" the register count when TY is i64.
4043 if (isI64 || (isF64 && IsSoftFloatABI)) {
4044 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4045 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4049 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
4051 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4052 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4053 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4055 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4057 llvm::Type *DirectTy = CGF.ConvertType(Ty);
4058 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
4060 // Case 1: consume registers.
4061 Address RegAddr = Address::invalid();
4063 CGF.EmitBlock(UsingRegs);
4065 Address RegSaveAreaPtr =
4066 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
4067 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4068 CharUnits::fromQuantity(8));
4069 assert(RegAddr.getElementType() == CGF.Int8Ty);
4071 // Floating-point registers start after the general-purpose registers.
4072 if (!(isInt || IsSoftFloatABI)) {
4073 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4074 CharUnits::fromQuantity(32));
4077 // Get the address of the saved value by scaling the number of
4078 // registers we've used by the number of
4079 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
4080 llvm::Value *RegOffset =
4081 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4082 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4083 RegAddr.getPointer(), RegOffset),
4084 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4085 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4087 // Increase the used-register count.
4089 Builder.CreateAdd(NumRegs,
4090 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
4091 Builder.CreateStore(NumRegs, NumRegsAddr);
4093 CGF.EmitBranch(Cont);
4096 // Case 2: consume space in the overflow area.
4097 Address MemAddr = Address::invalid();
4099 CGF.EmitBlock(UsingOverflow);
4101 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4103 // Everything in the overflow area is rounded up to a size of at least 4.
4104 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4108 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
4109 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
4111 Size = CGF.getPointerSize();
4114 Address OverflowAreaAddr =
4115 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
4116 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
4118 // Round up address of argument to alignment
4119 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4120 if (Align > OverflowAreaAlign) {
4121 llvm::Value *Ptr = OverflowArea.getPointer();
4122 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4126 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4128 // Increase the overflow area.
4129 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4130 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4131 CGF.EmitBranch(Cont);
4134 CGF.EmitBlock(Cont);
4136 // Merge the cases with a phi.
4137 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4140 // Load the pointer if the argument was passed indirectly.
4142 Result = Address(Builder.CreateLoad(Result, "aggr"),
4143 getContext().getTypeAlignInChars(Ty));
4150 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4151 llvm::Value *Address) const {
4152 // This is calculated from the LLVM and GCC tables and verified
4153 // against gcc output. AFAIK all ABIs use the same encoding.
4155 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4157 llvm::IntegerType *i8 = CGF.Int8Ty;
4158 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4159 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4160 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4162 // 0-31: r0-31, the 4-byte general-purpose registers
4163 AssignToArrayRange(Builder, Address, Four8, 0, 31);
4165 // 32-63: fp0-31, the 8-byte floating-point registers
4166 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4168 // 64-76 are various 4-byte special-purpose registers:
4175 AssignToArrayRange(Builder, Address, Four8, 64, 76);
4177 // 77-108: v0-31, the 16-byte vector registers
4178 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4185 AssignToArrayRange(Builder, Address, Four8, 109, 113);
4193 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
4194 class PPC64_SVR4_ABIInfo : public ABIInfo {
4202 static const unsigned GPRBits = 64;
4205 bool IsSoftFloatABI;
4207 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4208 // will be passed in a QPX register.
4209 bool IsQPXVectorTy(const Type *Ty) const {
4213 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4214 unsigned NumElements = VT->getNumElements();
4215 if (NumElements == 1)
4218 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4219 if (getContext().getTypeSize(Ty) <= 256)
4221 } else if (VT->getElementType()->
4222 isSpecificBuiltinType(BuiltinType::Float)) {
4223 if (getContext().getTypeSize(Ty) <= 128)
4231 bool IsQPXVectorTy(QualType Ty) const {
4232 return IsQPXVectorTy(Ty.getTypePtr());
4236 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4238 : ABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
4239 IsSoftFloatABI(SoftFloatABI) {}
4241 bool isPromotableTypeForABI(QualType Ty) const;
4242 CharUnits getParamTypeAlignment(QualType Ty) const;
4244 ABIArgInfo classifyReturnType(QualType RetTy) const;
4245 ABIArgInfo classifyArgumentType(QualType Ty) const;
4247 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4248 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4249 uint64_t Members) const override;
4251 // TODO: We can add more logic to computeInfo to improve performance.
4252 // Example: For aggregate arguments that fit in a register, we could
4253 // use getDirectInReg (as is done below for structs containing a single
4254 // floating-point value) to avoid pushing them to memory on function
4255 // entry. This would require changing the logic in PPCISelLowering
4256 // when lowering the parameters in the caller and args in the callee.
4257 void computeInfo(CGFunctionInfo &FI) const override {
4258 if (!getCXXABI().classifyReturnType(FI))
4259 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4260 for (auto &I : FI.arguments()) {
4261 // We rely on the default argument classification for the most part.
4262 // One exception: An aggregate containing a single floating-point
4263 // or vector item must be passed in a register if one is available.
4264 const Type *T = isSingleElementStruct(I.type, getContext());
4266 const BuiltinType *BT = T->getAs<BuiltinType>();
4267 if (IsQPXVectorTy(T) ||
4268 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
4269 (BT && BT->isFloatingPoint())) {
4271 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
4275 I.info = classifyArgumentType(I.type);
4279 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4280 QualType Ty) const override;
4283 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
4286 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
4287 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4289 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX,
4292 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4293 // This is recovered from gcc output.
4294 return 1; // r1 is the dedicated stack pointer
4297 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4298 llvm::Value *Address) const override;
4301 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4303 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4305 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4306 // This is recovered from gcc output.
4307 return 1; // r1 is the dedicated stack pointer
4310 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4311 llvm::Value *Address) const override;
4316 // Return true if the ABI requires Ty to be passed sign- or zero-
4317 // extended to 64 bits.
4319 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4320 // Treat an enum type as its underlying type.
4321 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4322 Ty = EnumTy->getDecl()->getIntegerType();
4324 // Promotable integer types are required to be promoted by the ABI.
4325 if (Ty->isPromotableIntegerType())
4328 // In addition to the usual promotable integer types, we also need to
4329 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4330 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4331 switch (BT->getKind()) {
4332 case BuiltinType::Int:
4333 case BuiltinType::UInt:
4342 /// isAlignedParamType - Determine whether a type requires 16-byte or
4343 /// higher alignment in the parameter area. Always returns at least 8.
4344 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4345 // Complex types are passed just like their elements.
4346 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4347 Ty = CTy->getElementType();
4349 // Only vector types of size 16 bytes need alignment (larger types are
4350 // passed via reference, smaller types are not aligned).
4351 if (IsQPXVectorTy(Ty)) {
4352 if (getContext().getTypeSize(Ty) > 128)
4353 return CharUnits::fromQuantity(32);
4355 return CharUnits::fromQuantity(16);
4356 } else if (Ty->isVectorType()) {
4357 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
4360 // For single-element float/vector structs, we consider the whole type
4361 // to have the same alignment requirements as its single element.
4362 const Type *AlignAsType = nullptr;
4363 const Type *EltType = isSingleElementStruct(Ty, getContext());
4365 const BuiltinType *BT = EltType->getAs<BuiltinType>();
4366 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
4367 getContext().getTypeSize(EltType) == 128) ||
4368 (BT && BT->isFloatingPoint()))
4369 AlignAsType = EltType;
4372 // Likewise for ELFv2 homogeneous aggregates.
4373 const Type *Base = nullptr;
4374 uint64_t Members = 0;
4375 if (!AlignAsType && Kind == ELFv2 &&
4376 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4379 // With special case aggregates, only vector base types need alignment.
4380 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4381 if (getContext().getTypeSize(AlignAsType) > 128)
4382 return CharUnits::fromQuantity(32);
4384 return CharUnits::fromQuantity(16);
4385 } else if (AlignAsType) {
4386 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
4389 // Otherwise, we only need alignment for any aggregate type that
4390 // has an alignment requirement of >= 16 bytes.
4391 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4392 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
4393 return CharUnits::fromQuantity(32);
4394 return CharUnits::fromQuantity(16);
4397 return CharUnits::fromQuantity(8);
4400 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4401 /// aggregate. Base is set to the base element type, and Members is set
4402 /// to the number of base elements.
4403 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4404 uint64_t &Members) const {
4405 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4406 uint64_t NElements = AT->getSize().getZExtValue();
4409 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4411 Members *= NElements;
4412 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4413 const RecordDecl *RD = RT->getDecl();
4414 if (RD->hasFlexibleArrayMember())
4419 // If this is a C++ record, check the bases first.
4420 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4421 for (const auto &I : CXXRD->bases()) {
4422 // Ignore empty records.
4423 if (isEmptyRecord(getContext(), I.getType(), true))
4426 uint64_t FldMembers;
4427 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4430 Members += FldMembers;
4434 for (const auto *FD : RD->fields()) {
4435 // Ignore (non-zero arrays of) empty records.
4436 QualType FT = FD->getType();
4437 while (const ConstantArrayType *AT =
4438 getContext().getAsConstantArrayType(FT)) {
4439 if (AT->getSize().getZExtValue() == 0)
4441 FT = AT->getElementType();
4443 if (isEmptyRecord(getContext(), FT, true))
4446 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4447 if (getContext().getLangOpts().CPlusPlus &&
4448 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4451 uint64_t FldMembers;
4452 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4455 Members = (RD->isUnion() ?
4456 std::max(Members, FldMembers) : Members + FldMembers);
4462 // Ensure there is no padding.
4463 if (getContext().getTypeSize(Base) * Members !=
4464 getContext().getTypeSize(Ty))
4468 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4470 Ty = CT->getElementType();
4473 // Most ABIs only support float, double, and some vector type widths.
4474 if (!isHomogeneousAggregateBaseType(Ty))
4477 // The base type must be the same for all members. Types that
4478 // agree in both total size and mode (float vs. vector) are
4479 // treated as being equivalent here.
4480 const Type *TyPtr = Ty.getTypePtr();
4483 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4484 // so make sure to widen it explicitly.
4485 if (const VectorType *VT = Base->getAs<VectorType>()) {
4486 QualType EltTy = VT->getElementType();
4487 unsigned NumElements =
4488 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4490 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4495 if (Base->isVectorType() != TyPtr->isVectorType() ||
4496 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4499 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4502 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4503 // Homogeneous aggregates for ELFv2 must have base types of float,
4504 // double, long double, or 128-bit vectors.
4505 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4506 if (BT->getKind() == BuiltinType::Float ||
4507 BT->getKind() == BuiltinType::Double ||
4508 BT->getKind() == BuiltinType::LongDouble) {
4514 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4515 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
4521 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4522 const Type *Base, uint64_t Members) const {
4523 // Vector types require one register, floating point types require one
4524 // or two registers depending on their size.
4526 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
4528 // Homogeneous Aggregates may occupy at most 8 registers.
4529 return Members * NumRegs <= 8;
4533 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
4534 Ty = useFirstFieldIfTransparentUnion(Ty);
4536 if (Ty->isAnyComplexType())
4537 return ABIArgInfo::getDirect();
4539 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4540 // or via reference (larger than 16 bytes).
4541 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
4542 uint64_t Size = getContext().getTypeSize(Ty);
4544 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4545 else if (Size < 128) {
4546 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4547 return ABIArgInfo::getDirect(CoerceTy);
4551 if (isAggregateTypeForABI(Ty)) {
4552 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
4553 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4555 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4556 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
4558 // ELFv2 homogeneous aggregates are passed as array types.
4559 const Type *Base = nullptr;
4560 uint64_t Members = 0;
4561 if (Kind == ELFv2 &&
4562 isHomogeneousAggregate(Ty, Base, Members)) {
4563 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4564 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4565 return ABIArgInfo::getDirect(CoerceTy);
4568 // If an aggregate may end up fully in registers, we do not
4569 // use the ByVal method, but pass the aggregate as array.
4570 // This is usually beneficial since we avoid forcing the
4571 // back-end to store the argument to memory.
4572 uint64_t Bits = getContext().getTypeSize(Ty);
4573 if (Bits > 0 && Bits <= 8 * GPRBits) {
4574 llvm::Type *CoerceTy;
4576 // Types up to 8 bytes are passed as integer type (which will be
4577 // properly aligned in the argument save area doubleword).
4578 if (Bits <= GPRBits)
4580 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
4581 // Larger types are passed as arrays, with the base type selected
4582 // according to the required alignment in the save area.
4584 uint64_t RegBits = ABIAlign * 8;
4585 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
4586 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4587 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4590 return ABIArgInfo::getDirect(CoerceTy);
4593 // All other aggregates are passed ByVal.
4594 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4596 /*Realign=*/TyAlign > ABIAlign);
4599 return (isPromotableTypeForABI(Ty) ?
4600 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4604 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4605 if (RetTy->isVoidType())
4606 return ABIArgInfo::getIgnore();
4608 if (RetTy->isAnyComplexType())
4609 return ABIArgInfo::getDirect();
4611 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4612 // or via reference (larger than 16 bytes).
4613 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
4614 uint64_t Size = getContext().getTypeSize(RetTy);
4616 return getNaturalAlignIndirect(RetTy);
4617 else if (Size < 128) {
4618 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4619 return ABIArgInfo::getDirect(CoerceTy);
4623 if (isAggregateTypeForABI(RetTy)) {
4624 // ELFv2 homogeneous aggregates are returned as array types.
4625 const Type *Base = nullptr;
4626 uint64_t Members = 0;
4627 if (Kind == ELFv2 &&
4628 isHomogeneousAggregate(RetTy, Base, Members)) {
4629 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4630 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4631 return ABIArgInfo::getDirect(CoerceTy);
4634 // ELFv2 small aggregates are returned in up to two registers.
4635 uint64_t Bits = getContext().getTypeSize(RetTy);
4636 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4638 return ABIArgInfo::getIgnore();
4640 llvm::Type *CoerceTy;
4641 if (Bits > GPRBits) {
4642 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
4643 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
4646 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
4647 return ABIArgInfo::getDirect(CoerceTy);
4650 // All other aggregates are returned indirectly.
4651 return getNaturalAlignIndirect(RetTy);
4654 return (isPromotableTypeForABI(RetTy) ?
4655 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4658 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
4659 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4660 QualType Ty) const {
4661 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4662 TypeInfo.second = getParamTypeAlignment(Ty);
4664 CharUnits SlotSize = CharUnits::fromQuantity(8);
4666 // If we have a complex type and the base type is smaller than 8 bytes,
4667 // the ABI calls for the real and imaginary parts to be right-adjusted
4668 // in separate doublewords. However, Clang expects us to produce a
4669 // pointer to a structure with the two parts packed tightly. So generate
4670 // loads of the real and imaginary parts relative to the va_list pointer,
4671 // and store them to a temporary structure.
4672 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4673 CharUnits EltSize = TypeInfo.first / 2;
4674 if (EltSize < SlotSize) {
4675 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4676 SlotSize * 2, SlotSize,
4677 SlotSize, /*AllowHigher*/ true);
4679 Address RealAddr = Addr;
4680 Address ImagAddr = RealAddr;
4681 if (CGF.CGM.getDataLayout().isBigEndian()) {
4682 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4683 SlotSize - EltSize);
4684 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4685 2 * SlotSize - EltSize);
4687 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4690 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4691 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4692 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4693 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4694 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4696 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4697 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4703 // Otherwise, just use the general rule.
4704 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4705 TypeInfo, SlotSize, /*AllowHigher*/ true);
4709 PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4710 llvm::Value *Address) {
4711 // This is calculated from the LLVM and GCC tables and verified
4712 // against gcc output. AFAIK all ABIs use the same encoding.
4714 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4716 llvm::IntegerType *i8 = CGF.Int8Ty;
4717 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4718 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4719 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4721 // 0-31: r0-31, the 8-byte general-purpose registers
4722 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4724 // 32-63: fp0-31, the 8-byte floating-point registers
4725 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4727 // 64-67 are various 8-byte special-purpose registers:
4732 AssignToArrayRange(Builder, Address, Eight8, 64, 67);
4734 // 68-76 are various 4-byte special-purpose registers:
4737 AssignToArrayRange(Builder, Address, Four8, 68, 76);
4739 // 77-108: v0-31, the 16-byte vector registers
4740 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4750 AssignToArrayRange(Builder, Address, Eight8, 109, 116);
4756 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4757 CodeGen::CodeGenFunction &CGF,
4758 llvm::Value *Address) const {
4760 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4764 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4765 llvm::Value *Address) const {
4767 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4770 //===----------------------------------------------------------------------===//
4771 // AArch64 ABI Implementation
4772 //===----------------------------------------------------------------------===//
4776 class AArch64ABIInfo : public SwiftABIInfo {
4787 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4788 : SwiftABIInfo(CGT), Kind(Kind) {}
4791 ABIKind getABIKind() const { return Kind; }
4792 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4794 ABIArgInfo classifyReturnType(QualType RetTy) const;
4795 ABIArgInfo classifyArgumentType(QualType RetTy) const;
4796 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4797 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4798 uint64_t Members) const override;
4800 bool isIllegalVectorType(QualType Ty) const;
4802 void computeInfo(CGFunctionInfo &FI) const override {
4803 if (!getCXXABI().classifyReturnType(FI))
4804 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4806 for (auto &it : FI.arguments())
4807 it.info = classifyArgumentType(it.type);
4810 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4811 CodeGenFunction &CGF) const;
4813 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4814 CodeGenFunction &CGF) const;
4816 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4817 QualType Ty) const override {
4818 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4819 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
4822 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
4823 ArrayRef<llvm::Type*> scalars,
4824 bool asReturnValue) const override {
4825 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4827 bool isSwiftErrorInRegister() const override {
4832 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
4834 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4835 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
4837 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
4838 return "mov\tfp, fp\t\t# marker for objc_retainAutoreleaseReturnValue";
4841 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4845 bool doesReturnSlotInterfereWithArgs() const override { return false; }
4849 ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
4850 Ty = useFirstFieldIfTransparentUnion(Ty);
4852 // Handle illegal vector types here.
4853 if (isIllegalVectorType(Ty)) {
4854 uint64_t Size = getContext().getTypeSize(Ty);
4855 // Android promotes <2 x i8> to i16, not i32
4856 if (isAndroid() && (Size <= 16)) {
4857 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
4858 return ABIArgInfo::getDirect(ResType);
4861 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
4862 return ABIArgInfo::getDirect(ResType);
4865 llvm::Type *ResType =
4866 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
4867 return ABIArgInfo::getDirect(ResType);
4870 llvm::Type *ResType =
4871 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
4872 return ABIArgInfo::getDirect(ResType);
4874 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4877 if (!isAggregateTypeForABI(Ty)) {
4878 // Treat an enum type as its underlying type.
4879 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4880 Ty = EnumTy->getDecl()->getIntegerType();
4882 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4883 ? ABIArgInfo::getExtend()
4884 : ABIArgInfo::getDirect());
4887 // Structures with either a non-trivial destructor or a non-trivial
4888 // copy constructor are always indirect.
4889 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
4890 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4891 CGCXXABI::RAA_DirectInMemory);
4894 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4895 // elsewhere for GNU compatibility.
4896 if (isEmptyRecord(getContext(), Ty, true)) {
4897 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4898 return ABIArgInfo::getIgnore();
4900 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4903 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
4904 const Type *Base = nullptr;
4905 uint64_t Members = 0;
4906 if (isHomogeneousAggregate(Ty, Base, Members)) {
4907 return ABIArgInfo::getDirect(
4908 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
4911 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4912 uint64_t Size = getContext().getTypeSize(Ty);
4914 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
4915 // same size and alignment.
4916 if (getTarget().isRenderScriptTarget()) {
4917 return coerceToIntArray(Ty, getContext(), getVMContext());
4919 unsigned Alignment = getContext().getTypeAlign(Ty);
4920 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
4922 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4923 // For aggregates with 16-byte alignment, we use i128.
4924 if (Alignment < 128 && Size == 128) {
4925 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4926 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4928 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4931 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4934 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
4935 if (RetTy->isVoidType())
4936 return ABIArgInfo::getIgnore();
4938 // Large vector types should be returned via memory.
4939 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
4940 return getNaturalAlignIndirect(RetTy);
4942 if (!isAggregateTypeForABI(RetTy)) {
4943 // Treat an enum type as its underlying type.
4944 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4945 RetTy = EnumTy->getDecl()->getIntegerType();
4947 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4948 ? ABIArgInfo::getExtend()
4949 : ABIArgInfo::getDirect());
4952 if (isEmptyRecord(getContext(), RetTy, true))
4953 return ABIArgInfo::getIgnore();
4955 const Type *Base = nullptr;
4956 uint64_t Members = 0;
4957 if (isHomogeneousAggregate(RetTy, Base, Members))
4958 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4959 return ABIArgInfo::getDirect();
4961 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4962 uint64_t Size = getContext().getTypeSize(RetTy);
4964 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
4965 // same size and alignment.
4966 if (getTarget().isRenderScriptTarget()) {
4967 return coerceToIntArray(RetTy, getContext(), getVMContext());
4969 unsigned Alignment = getContext().getTypeAlign(RetTy);
4970 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
4972 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4973 // For aggregates with 16-byte alignment, we use i128.
4974 if (Alignment < 128 && Size == 128) {
4975 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4976 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4978 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4981 return getNaturalAlignIndirect(RetTy);
4984 /// isIllegalVectorType - check whether the vector type is legal for AArch64.
4985 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
4986 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4987 // Check whether VT is legal.
4988 unsigned NumElements = VT->getNumElements();
4989 uint64_t Size = getContext().getTypeSize(VT);
4990 // NumElements should be power of 2.
4991 if (!llvm::isPowerOf2_32(NumElements))
4993 return Size != 64 && (Size != 128 || NumElements == 1);
4998 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4999 // Homogeneous aggregates for AAPCS64 must have base types of a floating
5000 // point type or a short-vector type. This is the same as the 32-bit ABI,
5001 // but with the difference that any floating-point type is allowed,
5002 // including __fp16.
5003 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5004 if (BT->isFloatingPoint())
5006 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5007 unsigned VecSize = getContext().getTypeSize(VT);
5008 if (VecSize == 64 || VecSize == 128)
5014 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5015 uint64_t Members) const {
5016 return Members <= 4;
5019 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
5021 CodeGenFunction &CGF) const {
5022 ABIArgInfo AI = classifyArgumentType(Ty);
5023 bool IsIndirect = AI.isIndirect();
5025 llvm::Type *BaseTy = CGF.ConvertType(Ty);
5027 BaseTy = llvm::PointerType::getUnqual(BaseTy);
5028 else if (AI.getCoerceToType())
5029 BaseTy = AI.getCoerceToType();
5031 unsigned NumRegs = 1;
5032 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5033 BaseTy = ArrTy->getElementType();
5034 NumRegs = ArrTy->getNumElements();
5036 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5038 // The AArch64 va_list type and handling is specified in the Procedure Call
5039 // Standard, section B.4:
5049 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5050 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5051 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5052 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5054 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5055 CharUnits TyAlign = TyInfo.second;
5057 Address reg_offs_p = Address::invalid();
5058 llvm::Value *reg_offs = nullptr;
5060 CharUnits reg_top_offset;
5061 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
5063 // 3 is the field number of __gr_offs
5065 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5067 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5068 reg_top_index = 1; // field number for __gr_top
5069 reg_top_offset = CharUnits::fromQuantity(8);
5070 RegSize = llvm::alignTo(RegSize, 8);
5072 // 4 is the field number of __vr_offs.
5074 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
5076 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5077 reg_top_index = 2; // field number for __vr_top
5078 reg_top_offset = CharUnits::fromQuantity(16);
5079 RegSize = 16 * NumRegs;
5082 //=======================================
5083 // Find out where argument was passed
5084 //=======================================
5086 // If reg_offs >= 0 we're already using the stack for this type of
5087 // argument. We don't want to keep updating reg_offs (in case it overflows,
5088 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5089 // whatever they get).
5090 llvm::Value *UsingStack = nullptr;
5091 UsingStack = CGF.Builder.CreateICmpSGE(
5092 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5094 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5096 // Otherwise, at least some kind of argument could go in these registers, the
5097 // question is whether this particular type is too big.
5098 CGF.EmitBlock(MaybeRegBlock);
5100 // Integer arguments may need to correct register alignment (for example a
5101 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5102 // align __gr_offs to calculate the potential address.
5103 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5104 int Align = TyAlign.getQuantity();
5106 reg_offs = CGF.Builder.CreateAdd(
5107 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5109 reg_offs = CGF.Builder.CreateAnd(
5110 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5114 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
5115 // The fact that this is done unconditionally reflects the fact that
5116 // allocating an argument to the stack also uses up all the remaining
5117 // registers of the appropriate kind.
5118 llvm::Value *NewOffset = nullptr;
5119 NewOffset = CGF.Builder.CreateAdd(
5120 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5121 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5123 // Now we're in a position to decide whether this argument really was in
5124 // registers or not.
5125 llvm::Value *InRegs = nullptr;
5126 InRegs = CGF.Builder.CreateICmpSLE(
5127 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5129 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5131 //=======================================
5132 // Argument was in registers
5133 //=======================================
5135 // Now we emit the code for if the argument was originally passed in
5136 // registers. First start the appropriate block:
5137 CGF.EmitBlock(InRegBlock);
5139 llvm::Value *reg_top = nullptr;
5140 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
5141 reg_top_offset, "reg_top_p");
5142 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
5143 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5144 CharUnits::fromQuantity(IsFPR ? 16 : 8));
5145 Address RegAddr = Address::invalid();
5146 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
5149 // If it's been passed indirectly (actually a struct), whatever we find from
5150 // stored registers or on the stack will actually be a struct **.
5151 MemTy = llvm::PointerType::getUnqual(MemTy);
5154 const Type *Base = nullptr;
5155 uint64_t NumMembers = 0;
5156 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
5157 if (IsHFA && NumMembers > 1) {
5158 // Homogeneous aggregates passed in registers will have their elements split
5159 // and stored 16-bytes apart regardless of size (they're notionally in qN,
5160 // qN+1, ...). We reload and store into a temporary local variable
5162 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
5163 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
5164 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5165 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
5166 Address Tmp = CGF.CreateTempAlloca(HFATy,
5167 std::max(TyAlign, BaseTyInfo.second));
5169 // On big-endian platforms, the value will be right-aligned in its slot.
5171 if (CGF.CGM.getDataLayout().isBigEndian() &&
5172 BaseTyInfo.first.getQuantity() < 16)
5173 Offset = 16 - BaseTyInfo.first.getQuantity();
5175 for (unsigned i = 0; i < NumMembers; ++i) {
5176 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5178 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5179 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5182 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
5184 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5185 CGF.Builder.CreateStore(Elem, StoreAddr);
5188 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
5190 // Otherwise the object is contiguous in memory.
5192 // It might be right-aligned in its slot.
5193 CharUnits SlotSize = BaseAddr.getAlignment();
5194 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
5195 (IsHFA || !isAggregateTypeForABI(Ty)) &&
5196 TyInfo.first < SlotSize) {
5197 CharUnits Offset = SlotSize - TyInfo.first;
5198 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
5201 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
5204 CGF.EmitBranch(ContBlock);
5206 //=======================================
5207 // Argument was on the stack
5208 //=======================================
5209 CGF.EmitBlock(OnStackBlock);
5211 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
5212 CharUnits::Zero(), "stack_p");
5213 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
5215 // Again, stack arguments may need realignment. In this case both integer and
5216 // floating-point ones might be affected.
5217 if (!IsIndirect && TyAlign.getQuantity() > 8) {
5218 int Align = TyAlign.getQuantity();
5220 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
5222 OnStackPtr = CGF.Builder.CreateAdd(
5223 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
5225 OnStackPtr = CGF.Builder.CreateAnd(
5226 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
5229 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
5231 Address OnStackAddr(OnStackPtr,
5232 std::max(CharUnits::fromQuantity(8), TyAlign));
5234 // All stack slots are multiples of 8 bytes.
5235 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5236 CharUnits StackSize;
5238 StackSize = StackSlotSize;
5240 StackSize = TyInfo.first.alignTo(StackSlotSize);
5242 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
5243 llvm::Value *NewStack =
5244 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
5246 // Write the new value of __stack for the next call to va_arg
5247 CGF.Builder.CreateStore(NewStack, stack_p);
5249 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
5250 TyInfo.first < StackSlotSize) {
5251 CharUnits Offset = StackSlotSize - TyInfo.first;
5252 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
5255 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
5257 CGF.EmitBranch(ContBlock);
5259 //=======================================
5261 //=======================================
5262 CGF.EmitBlock(ContBlock);
5264 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5265 OnStackAddr, OnStackBlock, "vaargs.addr");
5268 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
5274 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5275 CodeGenFunction &CGF) const {
5276 // The backend's lowering doesn't support va_arg for aggregates or
5277 // illegal vector types. Lower VAArg here for these cases and use
5278 // the LLVM va_arg instruction for everything else.
5279 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
5280 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
5282 CharUnits SlotSize = CharUnits::fromQuantity(8);
5284 // Empty records are ignored for parameter passing purposes.
5285 if (isEmptyRecord(getContext(), Ty, true)) {
5286 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5287 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5291 // The size of the actual thing passed, which might end up just
5292 // being a pointer for indirect types.
5293 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5295 // Arguments bigger than 16 bytes which aren't homogeneous
5296 // aggregates should be passed indirectly.
5297 bool IsIndirect = false;
5298 if (TyInfo.first.getQuantity() > 16) {
5299 const Type *Base = nullptr;
5300 uint64_t Members = 0;
5301 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
5304 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5305 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
5308 //===----------------------------------------------------------------------===//
5309 // ARM ABI Implementation
5310 //===----------------------------------------------------------------------===//
5314 class ARMABIInfo : public SwiftABIInfo {
5327 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5328 : SwiftABIInfo(CGT), Kind(_Kind) {
5332 bool isEABI() const {
5333 switch (getTarget().getTriple().getEnvironment()) {
5334 case llvm::Triple::Android:
5335 case llvm::Triple::EABI:
5336 case llvm::Triple::EABIHF:
5337 case llvm::Triple::GNUEABI:
5338 case llvm::Triple::GNUEABIHF:
5339 case llvm::Triple::MuslEABI:
5340 case llvm::Triple::MuslEABIHF:
5347 bool isEABIHF() const {
5348 switch (getTarget().getTriple().getEnvironment()) {
5349 case llvm::Triple::EABIHF:
5350 case llvm::Triple::GNUEABIHF:
5351 case llvm::Triple::MuslEABIHF:
5358 ABIKind getABIKind() const { return Kind; }
5361 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
5362 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
5363 bool isIllegalVectorType(QualType Ty) const;
5365 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5366 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5367 uint64_t Members) const override;
5369 void computeInfo(CGFunctionInfo &FI) const override;
5371 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5372 QualType Ty) const override;
5374 llvm::CallingConv::ID getLLVMDefaultCC() const;
5375 llvm::CallingConv::ID getABIDefaultCC() const;
5378 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5379 ArrayRef<llvm::Type*> scalars,
5380 bool asReturnValue) const override {
5381 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5383 bool isSwiftErrorInRegister() const override {
5388 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5390 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5391 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
5393 const ARMABIInfo &getABIInfo() const {
5394 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5397 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5401 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
5402 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
5405 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5406 llvm::Value *Address) const override {
5407 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
5409 // 0-15 are the 16 integer registers.
5410 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
5414 unsigned getSizeOfUnwindException() const override {
5415 if (getABIInfo().isEABI()) return 88;
5416 return TargetCodeGenInfo::getSizeOfUnwindException();
5419 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5420 CodeGen::CodeGenModule &CGM) const override {
5421 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5425 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5430 switch (Attr->getInterrupt()) {
5431 case ARMInterruptAttr::Generic: Kind = ""; break;
5432 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5433 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5434 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5435 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5436 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5439 llvm::Function *Fn = cast<llvm::Function>(GV);
5441 Fn->addFnAttr("interrupt", Kind);
5443 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5444 if (ABI == ARMABIInfo::APCS)
5447 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5448 // however this is not necessarily true on taking any interrupt. Instruct
5449 // the backend to perform a realignment as part of the function prologue.
5450 llvm::AttrBuilder B;
5451 B.addStackAlignmentAttr(8);
5453 llvm::AttributeList::FunctionIndex,
5454 llvm::AttributeList::get(CGM.getLLVMContext(),
5455 llvm::AttributeList::FunctionIndex, B));
5459 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
5461 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5462 : ARMTargetCodeGenInfo(CGT, K) {}
5464 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5465 CodeGen::CodeGenModule &CGM) const override;
5467 void getDependentLibraryOption(llvm::StringRef Lib,
5468 llvm::SmallString<24> &Opt) const override {
5469 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5472 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5473 llvm::SmallString<32> &Opt) const override {
5474 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5478 void WindowsARMTargetCodeGenInfo::setTargetAttributes(
5479 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5480 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5481 addStackProbeSizeTargetAttribute(D, GV, CGM);
5485 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
5486 if (!getCXXABI().classifyReturnType(FI))
5487 FI.getReturnInfo() =
5488 classifyReturnType(FI.getReturnType(), FI.isVariadic());
5490 for (auto &I : FI.arguments())
5491 I.info = classifyArgumentType(I.type, FI.isVariadic());
5493 // Always honor user-specified calling convention.
5494 if (FI.getCallingConvention() != llvm::CallingConv::C)
5497 llvm::CallingConv::ID cc = getRuntimeCC();
5498 if (cc != llvm::CallingConv::C)
5499 FI.setEffectiveCallingConvention(cc);
5502 /// Return the default calling convention that LLVM will use.
5503 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5504 // The default calling convention that LLVM will infer.
5505 if (isEABIHF() || getTarget().getTriple().isWatchABI())
5506 return llvm::CallingConv::ARM_AAPCS_VFP;
5508 return llvm::CallingConv::ARM_AAPCS;
5510 return llvm::CallingConv::ARM_APCS;
5513 /// Return the calling convention that our ABI would like us to use
5514 /// as the C calling convention.
5515 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
5516 switch (getABIKind()) {
5517 case APCS: return llvm::CallingConv::ARM_APCS;
5518 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5519 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
5520 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
5522 llvm_unreachable("bad ABI kind");
5525 void ARMABIInfo::setCCs() {
5526 assert(getRuntimeCC() == llvm::CallingConv::C);
5528 // Don't muddy up the IR with a ton of explicit annotations if
5529 // they'd just match what LLVM will infer from the triple.
5530 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5531 if (abiCC != getLLVMDefaultCC())
5534 // AAPCS apparently requires runtime support functions to be soft-float, but
5535 // that's almost certainly for historic reasons (Thumb1 not supporting VFP
5536 // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
5537 switch (getABIKind()) {
5540 if (abiCC != getLLVMDefaultCC())
5545 BuiltinCC = llvm::CallingConv::ARM_AAPCS;
5550 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5551 bool isVariadic) const {
5552 // 6.1.2.1 The following argument types are VFP CPRCs:
5553 // A single-precision floating-point type (including promoted
5554 // half-precision types); A double-precision floating-point type;
5555 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5556 // with a Base Type of a single- or double-precision floating-point type,
5557 // 64-bit containerized vectors or 128-bit containerized vectors with one
5558 // to four Elements.
5559 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
5561 Ty = useFirstFieldIfTransparentUnion(Ty);
5563 // Handle illegal vector types here.
5564 if (isIllegalVectorType(Ty)) {
5565 uint64_t Size = getContext().getTypeSize(Ty);
5567 llvm::Type *ResType =
5568 llvm::Type::getInt32Ty(getVMContext());
5569 return ABIArgInfo::getDirect(ResType);
5572 llvm::Type *ResType = llvm::VectorType::get(
5573 llvm::Type::getInt32Ty(getVMContext()), 2);
5574 return ABIArgInfo::getDirect(ResType);
5577 llvm::Type *ResType = llvm::VectorType::get(
5578 llvm::Type::getInt32Ty(getVMContext()), 4);
5579 return ABIArgInfo::getDirect(ResType);
5581 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5584 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5585 // unspecified. This is not done for OpenCL as it handles the half type
5586 // natively, and does not need to interwork with AAPCS code.
5587 if (Ty->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
5588 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5589 llvm::Type::getFloatTy(getVMContext()) :
5590 llvm::Type::getInt32Ty(getVMContext());
5591 return ABIArgInfo::getDirect(ResType);
5594 if (!isAggregateTypeForABI(Ty)) {
5595 // Treat an enum type as its underlying type.
5596 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
5597 Ty = EnumTy->getDecl()->getIntegerType();
5600 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5601 : ABIArgInfo::getDirect());
5604 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5605 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
5608 // Ignore empty records.
5609 if (isEmptyRecord(getContext(), Ty, true))
5610 return ABIArgInfo::getIgnore();
5612 if (IsEffectivelyAAPCS_VFP) {
5613 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5614 // into VFP registers.
5615 const Type *Base = nullptr;
5616 uint64_t Members = 0;
5617 if (isHomogeneousAggregate(Ty, Base, Members)) {
5618 assert(Base && "Base class should be set for homogeneous aggregate");
5619 // Base can be a floating-point or a vector.
5620 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
5622 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5623 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5624 // this convention even for a variadic function: the backend will use GPRs
5626 const Type *Base = nullptr;
5627 uint64_t Members = 0;
5628 if (isHomogeneousAggregate(Ty, Base, Members)) {
5629 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5631 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5632 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5636 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5637 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5638 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5639 // bigger than 128-bits, they get placed in space allocated by the caller,
5640 // and a pointer is passed.
5641 return ABIArgInfo::getIndirect(
5642 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
5645 // Support byval for ARM.
5646 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5647 // most 8-byte. We realign the indirect argument if type alignment is bigger
5648 // than ABI alignment.
5649 uint64_t ABIAlign = 4;
5650 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5651 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5652 getABIKind() == ARMABIInfo::AAPCS)
5653 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
5655 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
5656 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
5657 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5659 /*Realign=*/TyAlign > ABIAlign);
5662 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
5663 // same size and alignment.
5664 if (getTarget().isRenderScriptTarget()) {
5665 return coerceToIntArray(Ty, getContext(), getVMContext());
5668 // Otherwise, pass by coercing to a structure of the appropriate size.
5671 // FIXME: Try to match the types of the arguments more accurately where
5673 if (getContext().getTypeAlign(Ty) <= 32) {
5674 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5675 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
5677 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5678 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
5681 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
5684 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
5685 llvm::LLVMContext &VMContext) {
5686 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5687 // is called integer-like if its size is less than or equal to one word, and
5688 // the offset of each of its addressable sub-fields is zero.
5690 uint64_t Size = Context.getTypeSize(Ty);
5692 // Check that the type fits in a word.
5696 // FIXME: Handle vector types!
5697 if (Ty->isVectorType())
5700 // Float types are never treated as "integer like".
5701 if (Ty->isRealFloatingType())
5704 // If this is a builtin or pointer type then it is ok.
5705 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
5708 // Small complex integer types are "integer like".
5709 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5710 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
5712 // Single element and zero sized arrays should be allowed, by the definition
5713 // above, but they are not.
5715 // Otherwise, it must be a record type.
5716 const RecordType *RT = Ty->getAs<RecordType>();
5717 if (!RT) return false;
5719 // Ignore records with flexible arrays.
5720 const RecordDecl *RD = RT->getDecl();
5721 if (RD->hasFlexibleArrayMember())
5724 // Check that all sub-fields are at offset 0, and are themselves "integer
5726 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5728 bool HadField = false;
5730 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5731 i != e; ++i, ++idx) {
5732 const FieldDecl *FD = *i;
5734 // Bit-fields are not addressable, we only need to verify they are "integer
5735 // like". We still have to disallow a subsequent non-bitfield, for example:
5736 // struct { int : 0; int x }
5737 // is non-integer like according to gcc.
5738 if (FD->isBitField()) {
5742 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5748 // Check if this field is at offset 0.
5749 if (Layout.getFieldOffset(idx) != 0)
5752 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5755 // Only allow at most one field in a structure. This doesn't match the
5756 // wording above, but follows gcc in situations with a field following an
5758 if (!RD->isUnion()) {
5769 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5770 bool isVariadic) const {
5771 bool IsEffectivelyAAPCS_VFP =
5772 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
5774 if (RetTy->isVoidType())
5775 return ABIArgInfo::getIgnore();
5777 // Large vector types should be returned via memory.
5778 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
5779 return getNaturalAlignIndirect(RetTy);
5782 // __fp16 gets returned as if it were an int or float, but with the top 16
5783 // bits unspecified. This is not done for OpenCL as it handles the half type
5784 // natively, and does not need to interwork with AAPCS code.
5785 if (RetTy->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
5786 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5787 llvm::Type::getFloatTy(getVMContext()) :
5788 llvm::Type::getInt32Ty(getVMContext());
5789 return ABIArgInfo::getDirect(ResType);
5792 if (!isAggregateTypeForABI(RetTy)) {
5793 // Treat an enum type as its underlying type.
5794 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5795 RetTy = EnumTy->getDecl()->getIntegerType();
5797 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5798 : ABIArgInfo::getDirect();
5801 // Are we following APCS?
5802 if (getABIKind() == APCS) {
5803 if (isEmptyRecord(getContext(), RetTy, false))
5804 return ABIArgInfo::getIgnore();
5806 // Complex types are all returned as packed integers.
5808 // FIXME: Consider using 2 x vector types if the back end handles them
5810 if (RetTy->isAnyComplexType())
5811 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5812 getVMContext(), getContext().getTypeSize(RetTy)));
5814 // Integer like structures are returned in r0.
5815 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
5816 // Return in the smallest viable integer type.
5817 uint64_t Size = getContext().getTypeSize(RetTy);
5819 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5821 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5822 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5825 // Otherwise return in memory.
5826 return getNaturalAlignIndirect(RetTy);
5829 // Otherwise this is an AAPCS variant.
5831 if (isEmptyRecord(getContext(), RetTy, true))
5832 return ABIArgInfo::getIgnore();
5834 // Check for homogeneous aggregates with AAPCS-VFP.
5835 if (IsEffectivelyAAPCS_VFP) {
5836 const Type *Base = nullptr;
5837 uint64_t Members = 0;
5838 if (isHomogeneousAggregate(RetTy, Base, Members)) {
5839 assert(Base && "Base class should be set for homogeneous aggregate");
5840 // Homogeneous Aggregates are returned directly.
5841 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
5845 // Aggregates <= 4 bytes are returned in r0; other aggregates
5846 // are returned indirectly.
5847 uint64_t Size = getContext().getTypeSize(RetTy);
5849 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
5850 // same size and alignment.
5851 if (getTarget().isRenderScriptTarget()) {
5852 return coerceToIntArray(RetTy, getContext(), getVMContext());
5854 if (getDataLayout().isBigEndian())
5855 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
5856 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5858 // Return in the smallest viable integer type.
5860 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5862 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5863 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5864 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
5865 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
5866 llvm::Type *CoerceTy =
5867 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
5868 return ABIArgInfo::getDirect(CoerceTy);
5871 return getNaturalAlignIndirect(RetTy);
5874 /// isIllegalVector - check whether Ty is an illegal vector type.
5875 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
5876 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
5878 // Android shipped using Clang 3.1, which supported a slightly different
5879 // vector ABI. The primary differences were that 3-element vector types
5880 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
5881 // accepts that legacy behavior for Android only.
5882 // Check whether VT is legal.
5883 unsigned NumElements = VT->getNumElements();
5884 // NumElements should be power of 2 or equal to 3.
5885 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
5888 // Check whether VT is legal.
5889 unsigned NumElements = VT->getNumElements();
5890 uint64_t Size = getContext().getTypeSize(VT);
5891 // NumElements should be power of 2.
5892 if (!llvm::isPowerOf2_32(NumElements))
5894 // Size should be greater than 32 bits.
5901 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5902 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5903 // double, or 64-bit or 128-bit vectors.
5904 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5905 if (BT->getKind() == BuiltinType::Float ||
5906 BT->getKind() == BuiltinType::Double ||
5907 BT->getKind() == BuiltinType::LongDouble)
5909 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5910 unsigned VecSize = getContext().getTypeSize(VT);
5911 if (VecSize == 64 || VecSize == 128)
5917 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5918 uint64_t Members) const {
5919 return Members <= 4;
5922 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5923 QualType Ty) const {
5924 CharUnits SlotSize = CharUnits::fromQuantity(4);
5926 // Empty records are ignored for parameter passing purposes.
5927 if (isEmptyRecord(getContext(), Ty, true)) {
5928 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
5929 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5933 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5934 CharUnits TyAlignForABI = TyInfo.second;
5936 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5937 bool IsIndirect = false;
5938 const Type *Base = nullptr;
5939 uint64_t Members = 0;
5940 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
5943 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
5944 // allocated by the caller.
5945 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
5946 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5947 !isHomogeneousAggregate(Ty, Base, Members)) {
5950 // Otherwise, bound the type's ABI alignment.
5951 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5952 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
5953 // Our callers should be prepared to handle an under-aligned address.
5954 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5955 getABIKind() == ARMABIInfo::AAPCS) {
5956 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5957 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
5958 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5959 // ARMv7k allows type alignment up to 16 bytes.
5960 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5961 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
5963 TyAlignForABI = CharUnits::fromQuantity(4);
5965 TyInfo.second = TyAlignForABI;
5967 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
5968 SlotSize, /*AllowHigherAlign*/ true);
5971 //===----------------------------------------------------------------------===//
5972 // NVPTX ABI Implementation
5973 //===----------------------------------------------------------------------===//
5977 class NVPTXABIInfo : public ABIInfo {
5979 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5981 ABIArgInfo classifyReturnType(QualType RetTy) const;
5982 ABIArgInfo classifyArgumentType(QualType Ty) const;
5984 void computeInfo(CGFunctionInfo &FI) const override;
5985 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5986 QualType Ty) const override;
5989 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
5991 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5992 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
5994 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5995 CodeGen::CodeGenModule &M) const override;
5997 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5998 // resulting MDNode to the nvvm.annotations MDNode.
5999 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
6002 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
6003 if (RetTy->isVoidType())
6004 return ABIArgInfo::getIgnore();
6006 // note: this is different from default ABI
6007 if (!RetTy->isScalarType())
6008 return ABIArgInfo::getDirect();
6010 // Treat an enum type as its underlying type.
6011 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6012 RetTy = EnumTy->getDecl()->getIntegerType();
6014 return (RetTy->isPromotableIntegerType() ?
6015 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6018 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
6019 // Treat an enum type as its underlying type.
6020 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6021 Ty = EnumTy->getDecl()->getIntegerType();
6023 // Return aggregates type as indirect by value
6024 if (isAggregateTypeForABI(Ty))
6025 return getNaturalAlignIndirect(Ty, /* byval */ true);
6027 return (Ty->isPromotableIntegerType() ?
6028 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6031 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
6032 if (!getCXXABI().classifyReturnType(FI))
6033 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6034 for (auto &I : FI.arguments())
6035 I.info = classifyArgumentType(I.type);
6037 // Always honor user-specified calling convention.
6038 if (FI.getCallingConvention() != llvm::CallingConv::C)
6041 FI.setEffectiveCallingConvention(getRuntimeCC());
6044 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6045 QualType Ty) const {
6046 llvm_unreachable("NVPTX does not support varargs");
6049 void NVPTXTargetCodeGenInfo::
6050 setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6051 CodeGen::CodeGenModule &M) const{
6052 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6055 llvm::Function *F = cast<llvm::Function>(GV);
6057 // Perform special handling in OpenCL mode
6058 if (M.getLangOpts().OpenCL) {
6059 // Use OpenCL function attributes to check for kernel functions
6060 // By default, all functions are device functions
6061 if (FD->hasAttr<OpenCLKernelAttr>()) {
6062 // OpenCL __kernel functions get kernel metadata
6063 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6064 addNVVMMetadata(F, "kernel", 1);
6065 // And kernel functions are not subject to inlining
6066 F->addFnAttr(llvm::Attribute::NoInline);
6070 // Perform special handling in CUDA mode.
6071 if (M.getLangOpts().CUDA) {
6072 // CUDA __global__ functions get a kernel metadata entry. Since
6073 // __global__ functions cannot be called from the device, we do not
6074 // need to set the noinline attribute.
6075 if (FD->hasAttr<CUDAGlobalAttr>()) {
6076 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6077 addNVVMMetadata(F, "kernel", 1);
6079 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
6080 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
6081 llvm::APSInt MaxThreads(32);
6082 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
6084 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
6086 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
6087 // not specified in __launch_bounds__ or if the user specified a 0 value,
6088 // we don't have to add a PTX directive.
6089 if (Attr->getMinBlocks()) {
6090 llvm::APSInt MinBlocks(32);
6091 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
6093 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
6094 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
6100 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
6102 llvm::Module *M = F->getParent();
6103 llvm::LLVMContext &Ctx = M->getContext();
6105 // Get "nvvm.annotations" metadata node
6106 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
6108 llvm::Metadata *MDVals[] = {
6109 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
6110 llvm::ConstantAsMetadata::get(
6111 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
6112 // Append metadata to nvvm.annotations
6113 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6117 //===----------------------------------------------------------------------===//
6118 // SystemZ ABI Implementation
6119 //===----------------------------------------------------------------------===//
6123 class SystemZABIInfo : public SwiftABIInfo {
6127 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
6128 : SwiftABIInfo(CGT), HasVector(HV) {}
6130 bool isPromotableIntegerType(QualType Ty) const;
6131 bool isCompoundType(QualType Ty) const;
6132 bool isVectorArgumentType(QualType Ty) const;
6133 bool isFPArgumentType(QualType Ty) const;
6134 QualType GetSingleElementType(QualType Ty) const;
6136 ABIArgInfo classifyReturnType(QualType RetTy) const;
6137 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
6139 void computeInfo(CGFunctionInfo &FI) const override {
6140 if (!getCXXABI().classifyReturnType(FI))
6141 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6142 for (auto &I : FI.arguments())
6143 I.info = classifyArgumentType(I.type);
6146 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6147 QualType Ty) const override;
6149 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
6150 ArrayRef<llvm::Type*> scalars,
6151 bool asReturnValue) const override {
6152 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6154 bool isSwiftErrorInRegister() const override {
6159 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
6161 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
6162 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
6167 bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
6168 // Treat an enum type as its underlying type.
6169 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6170 Ty = EnumTy->getDecl()->getIntegerType();
6172 // Promotable integer types are required to be promoted by the ABI.
6173 if (Ty->isPromotableIntegerType())
6176 // 32-bit values must also be promoted.
6177 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6178 switch (BT->getKind()) {
6179 case BuiltinType::Int:
6180 case BuiltinType::UInt:
6188 bool SystemZABIInfo::isCompoundType(QualType Ty) const {
6189 return (Ty->isAnyComplexType() ||
6190 Ty->isVectorType() ||
6191 isAggregateTypeForABI(Ty));
6194 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
6195 return (HasVector &&
6196 Ty->isVectorType() &&
6197 getContext().getTypeSize(Ty) <= 128);
6200 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
6201 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6202 switch (BT->getKind()) {
6203 case BuiltinType::Float:
6204 case BuiltinType::Double:
6213 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
6214 if (const RecordType *RT = Ty->getAsStructureType()) {
6215 const RecordDecl *RD = RT->getDecl();
6218 // If this is a C++ record, check the bases first.
6219 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6220 for (const auto &I : CXXRD->bases()) {
6221 QualType Base = I.getType();
6223 // Empty bases don't affect things either way.
6224 if (isEmptyRecord(getContext(), Base, true))
6227 if (!Found.isNull())
6229 Found = GetSingleElementType(Base);
6232 // Check the fields.
6233 for (const auto *FD : RD->fields()) {
6234 // For compatibility with GCC, ignore empty bitfields in C++ mode.
6235 // Unlike isSingleElementStruct(), empty structure and array fields
6236 // do count. So do anonymous bitfields that aren't zero-sized.
6237 if (getContext().getLangOpts().CPlusPlus &&
6238 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
6241 // Unlike isSingleElementStruct(), arrays do not count.
6242 // Nested structures still do though.
6243 if (!Found.isNull())
6245 Found = GetSingleElementType(FD->getType());
6248 // Unlike isSingleElementStruct(), trailing padding is allowed.
6249 // An 8-byte aligned struct s { float f; } is passed as a double.
6250 if (!Found.isNull())
6257 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6258 QualType Ty) const {
6259 // Assume that va_list type is correct; should be pointer to LLVM type:
6263 // i8 *__overflow_arg_area;
6264 // i8 *__reg_save_area;
6267 // Every non-vector argument occupies 8 bytes and is passed by preference
6268 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
6269 // always passed on the stack.
6270 Ty = getContext().getCanonicalType(Ty);
6271 auto TyInfo = getContext().getTypeInfoInChars(Ty);
6272 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
6273 llvm::Type *DirectTy = ArgTy;
6274 ABIArgInfo AI = classifyArgumentType(Ty);
6275 bool IsIndirect = AI.isIndirect();
6276 bool InFPRs = false;
6277 bool IsVector = false;
6278 CharUnits UnpaddedSize;
6279 CharUnits DirectAlign;
6281 DirectTy = llvm::PointerType::getUnqual(DirectTy);
6282 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
6284 if (AI.getCoerceToType())
6285 ArgTy = AI.getCoerceToType();
6286 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
6287 IsVector = ArgTy->isVectorTy();
6288 UnpaddedSize = TyInfo.first;
6289 DirectAlign = TyInfo.second;
6291 CharUnits PaddedSize = CharUnits::fromQuantity(8);
6292 if (IsVector && UnpaddedSize > PaddedSize)
6293 PaddedSize = CharUnits::fromQuantity(16);
6294 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
6296 CharUnits Padding = (PaddedSize - UnpaddedSize);
6298 llvm::Type *IndexTy = CGF.Int64Ty;
6299 llvm::Value *PaddedSizeV =
6300 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
6303 // Work out the address of a vector argument on the stack.
6304 // Vector arguments are always passed in the high bits of a
6305 // single (8 byte) or double (16 byte) stack slot.
6306 Address OverflowArgAreaPtr =
6307 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
6308 "overflow_arg_area_ptr");
6309 Address OverflowArgArea =
6310 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6313 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
6315 // Update overflow_arg_area_ptr pointer
6316 llvm::Value *NewOverflowArgArea =
6317 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6318 "overflow_arg_area");
6319 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6324 assert(PaddedSize.getQuantity() == 8);
6326 unsigned MaxRegs, RegCountField, RegSaveIndex;
6327 CharUnits RegPadding;
6329 MaxRegs = 4; // Maximum of 4 FPR arguments
6330 RegCountField = 1; // __fpr
6331 RegSaveIndex = 16; // save offset for f0
6332 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
6334 MaxRegs = 5; // Maximum of 5 GPR arguments
6335 RegCountField = 0; // __gpr
6336 RegSaveIndex = 2; // save offset for r2
6337 RegPadding = Padding; // values are passed in the low bits of a GPR
6340 Address RegCountPtr = CGF.Builder.CreateStructGEP(
6341 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
6343 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
6344 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
6345 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
6348 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6349 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
6350 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6351 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
6353 // Emit code to load the value if it was passed in registers.
6354 CGF.EmitBlock(InRegBlock);
6356 // Work out the address of an argument register.
6357 llvm::Value *ScaledRegCount =
6358 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
6359 llvm::Value *RegBase =
6360 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
6361 + RegPadding.getQuantity());
6362 llvm::Value *RegOffset =
6363 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
6364 Address RegSaveAreaPtr =
6365 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
6366 "reg_save_area_ptr");
6367 llvm::Value *RegSaveArea =
6368 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
6369 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
6373 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
6375 // Update the register count
6376 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
6377 llvm::Value *NewRegCount =
6378 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
6379 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
6380 CGF.EmitBranch(ContBlock);
6382 // Emit code to load the value if it was passed in memory.
6383 CGF.EmitBlock(InMemBlock);
6385 // Work out the address of a stack argument.
6386 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
6387 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
6388 Address OverflowArgArea =
6389 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6391 Address RawMemAddr =
6392 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6394 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
6396 // Update overflow_arg_area_ptr pointer
6397 llvm::Value *NewOverflowArgArea =
6398 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6399 "overflow_arg_area");
6400 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6401 CGF.EmitBranch(ContBlock);
6403 // Return the appropriate result.
6404 CGF.EmitBlock(ContBlock);
6405 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6406 MemAddr, InMemBlock, "va_arg.addr");
6409 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6415 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6416 if (RetTy->isVoidType())
6417 return ABIArgInfo::getIgnore();
6418 if (isVectorArgumentType(RetTy))
6419 return ABIArgInfo::getDirect();
6420 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
6421 return getNaturalAlignIndirect(RetTy);
6422 return (isPromotableIntegerType(RetTy) ?
6423 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6426 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6427 // Handle the generic C++ ABI.
6428 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6429 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6431 // Integers and enums are extended to full register width.
6432 if (isPromotableIntegerType(Ty))
6433 return ABIArgInfo::getExtend();
6435 // Handle vector types and vector-like structure types. Note that
6436 // as opposed to float-like structure types, we do not allow any
6437 // padding for vector-like structures, so verify the sizes match.
6438 uint64_t Size = getContext().getTypeSize(Ty);
6439 QualType SingleElementTy = GetSingleElementType(Ty);
6440 if (isVectorArgumentType(SingleElementTy) &&
6441 getContext().getTypeSize(SingleElementTy) == Size)
6442 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6444 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
6445 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
6446 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6448 // Handle small structures.
6449 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6450 // Structures with flexible arrays have variable length, so really
6451 // fail the size test above.
6452 const RecordDecl *RD = RT->getDecl();
6453 if (RD->hasFlexibleArrayMember())
6454 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6456 // The structure is passed as an unextended integer, a float, or a double.
6458 if (isFPArgumentType(SingleElementTy)) {
6459 assert(Size == 32 || Size == 64);
6461 PassTy = llvm::Type::getFloatTy(getVMContext());
6463 PassTy = llvm::Type::getDoubleTy(getVMContext());
6465 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6466 return ABIArgInfo::getDirect(PassTy);
6469 // Non-structure compounds are passed indirectly.
6470 if (isCompoundType(Ty))
6471 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6473 return ABIArgInfo::getDirect(nullptr);
6476 //===----------------------------------------------------------------------===//
6477 // MSP430 ABI Implementation
6478 //===----------------------------------------------------------------------===//
6482 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6484 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6485 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
6486 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6487 CodeGen::CodeGenModule &M) const override;
6492 void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
6493 llvm::GlobalValue *GV,
6494 CodeGen::CodeGenModule &M) const {
6495 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
6496 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6497 // Handle 'interrupt' attribute:
6498 llvm::Function *F = cast<llvm::Function>(GV);
6500 // Step 1: Set ISR calling convention.
6501 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6503 // Step 2: Add attributes goodness.
6504 F->addFnAttr(llvm::Attribute::NoInline);
6506 // Step 3: Emit ISR vector alias.
6507 unsigned Num = attr->getNumber() / 2;
6508 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6509 "__isr_" + Twine(Num), F);
6514 //===----------------------------------------------------------------------===//
6515 // MIPS ABI Implementation. This works for both little-endian and
6516 // big-endian variants.
6517 //===----------------------------------------------------------------------===//
6520 class MipsABIInfo : public ABIInfo {
6522 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6523 void CoerceToIntArgs(uint64_t TySize,
6524 SmallVectorImpl<llvm::Type *> &ArgList) const;
6525 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
6526 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
6527 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
6529 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
6530 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
6531 StackAlignInBytes(IsO32 ? 8 : 16) {}
6533 ABIArgInfo classifyReturnType(QualType RetTy) const;
6534 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
6535 void computeInfo(CGFunctionInfo &FI) const override;
6536 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6537 QualType Ty) const override;
6538 bool shouldSignExtUnsignedType(QualType Ty) const override;
6541 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
6542 unsigned SizeOfUnwindException;
6544 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6545 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
6546 SizeOfUnwindException(IsO32 ? 24 : 32) {}
6548 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
6552 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6553 CodeGen::CodeGenModule &CGM) const override {
6554 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6556 llvm::Function *Fn = cast<llvm::Function>(GV);
6557 if (FD->hasAttr<Mips16Attr>()) {
6558 Fn->addFnAttr("mips16");
6560 else if (FD->hasAttr<NoMips16Attr>()) {
6561 Fn->addFnAttr("nomips16");
6564 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6569 switch (Attr->getInterrupt()) {
6570 case MipsInterruptAttr::eic: Kind = "eic"; break;
6571 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6572 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6573 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6574 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6575 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6576 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6577 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6578 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6581 Fn->addFnAttr("interrupt", Kind);
6585 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6586 llvm::Value *Address) const override;
6588 unsigned getSizeOfUnwindException() const override {
6589 return SizeOfUnwindException;
6594 void MipsABIInfo::CoerceToIntArgs(
6595 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
6596 llvm::IntegerType *IntTy =
6597 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
6599 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6600 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6601 ArgList.push_back(IntTy);
6603 // If necessary, add one more integer type to ArgList.
6604 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6607 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
6610 // In N32/64, an aligned double precision floating point field is passed in
6612 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
6613 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6616 CoerceToIntArgs(TySize, ArgList);
6617 return llvm::StructType::get(getVMContext(), ArgList);
6620 if (Ty->isComplexType())
6621 return CGT.ConvertType(Ty);
6623 const RecordType *RT = Ty->getAs<RecordType>();
6625 // Unions/vectors are passed in integer registers.
6626 if (!RT || !RT->isStructureOrClassType()) {
6627 CoerceToIntArgs(TySize, ArgList);
6628 return llvm::StructType::get(getVMContext(), ArgList);
6631 const RecordDecl *RD = RT->getDecl();
6632 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6633 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
6635 uint64_t LastOffset = 0;
6637 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6639 // Iterate over fields in the struct/class and check if there are any aligned
6641 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6642 i != e; ++i, ++idx) {
6643 const QualType Ty = i->getType();
6644 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6646 if (!BT || BT->getKind() != BuiltinType::Double)
6649 uint64_t Offset = Layout.getFieldOffset(idx);
6650 if (Offset % 64) // Ignore doubles that are not aligned.
6653 // Add ((Offset - LastOffset) / 64) args of type i64.
6654 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6655 ArgList.push_back(I64);
6658 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6659 LastOffset = Offset + 64;
6662 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6663 ArgList.append(IntArgList.begin(), IntArgList.end());
6665 return llvm::StructType::get(getVMContext(), ArgList);
6668 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6669 uint64_t Offset) const {
6670 if (OrigOffset + MinABIStackAlignInBytes > Offset)
6673 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
6677 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
6678 Ty = useFirstFieldIfTransparentUnion(Ty);
6680 uint64_t OrigOffset = Offset;
6681 uint64_t TySize = getContext().getTypeSize(Ty);
6682 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
6684 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6685 (uint64_t)StackAlignInBytes);
6686 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6687 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
6689 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
6690 // Ignore empty aggregates.
6692 return ABIArgInfo::getIgnore();
6694 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
6695 Offset = OrigOffset + MinABIStackAlignInBytes;
6696 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6699 // If we have reached here, aggregates are passed directly by coercing to
6700 // another structure type. Padding is inserted if the offset of the
6701 // aggregate is unaligned.
6702 ABIArgInfo ArgInfo =
6703 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6704 getPaddingType(OrigOffset, CurrOffset));
6705 ArgInfo.setInReg(true);
6709 // Treat an enum type as its underlying type.
6710 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6711 Ty = EnumTy->getDecl()->getIntegerType();
6713 // All integral types are promoted to the GPR width.
6714 if (Ty->isIntegralOrEnumerationType())
6715 return ABIArgInfo::getExtend();
6717 return ABIArgInfo::getDirect(
6718 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
6722 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
6723 const RecordType *RT = RetTy->getAs<RecordType>();
6724 SmallVector<llvm::Type*, 8> RTList;
6726 if (RT && RT->isStructureOrClassType()) {
6727 const RecordDecl *RD = RT->getDecl();
6728 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6729 unsigned FieldCnt = Layout.getFieldCount();
6731 // N32/64 returns struct/classes in floating point registers if the
6732 // following conditions are met:
6733 // 1. The size of the struct/class is no larger than 128-bit.
6734 // 2. The struct/class has one or two fields all of which are floating
6736 // 3. The offset of the first field is zero (this follows what gcc does).
6738 // Any other composite results are returned in integer registers.
6740 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6741 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6742 for (; b != e; ++b) {
6743 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
6745 if (!BT || !BT->isFloatingPoint())
6748 RTList.push_back(CGT.ConvertType(b->getType()));
6752 return llvm::StructType::get(getVMContext(), RTList,
6753 RD->hasAttr<PackedAttr>());
6759 CoerceToIntArgs(Size, RTList);
6760 return llvm::StructType::get(getVMContext(), RTList);
6763 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
6764 uint64_t Size = getContext().getTypeSize(RetTy);
6766 if (RetTy->isVoidType())
6767 return ABIArgInfo::getIgnore();
6769 // O32 doesn't treat zero-sized structs differently from other structs.
6770 // However, N32/N64 ignores zero sized return values.
6771 if (!IsO32 && Size == 0)
6772 return ABIArgInfo::getIgnore();
6774 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
6776 if (RetTy->isAnyComplexType())
6777 return ABIArgInfo::getDirect();
6779 // O32 returns integer vectors in registers and N32/N64 returns all small
6780 // aggregates in registers.
6782 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6783 ABIArgInfo ArgInfo =
6784 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6785 ArgInfo.setInReg(true);
6790 return getNaturalAlignIndirect(RetTy);
6793 // Treat an enum type as its underlying type.
6794 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6795 RetTy = EnumTy->getDecl()->getIntegerType();
6797 return (RetTy->isPromotableIntegerType() ?
6798 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6801 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
6802 ABIArgInfo &RetInfo = FI.getReturnInfo();
6803 if (!getCXXABI().classifyReturnType(FI))
6804 RetInfo = classifyReturnType(FI.getReturnType());
6806 // Check if a pointer to an aggregate is passed as a hidden argument.
6807 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
6809 for (auto &I : FI.arguments())
6810 I.info = classifyArgumentType(I.type, Offset);
6813 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6814 QualType OrigTy) const {
6815 QualType Ty = OrigTy;
6817 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6818 // Pointers are also promoted in the same way but this only matters for N32.
6819 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
6820 unsigned PtrWidth = getTarget().getPointerWidth(0);
6821 bool DidPromote = false;
6822 if ((Ty->isIntegerType() &&
6823 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
6824 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
6826 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6827 Ty->isSignedIntegerType());
6830 auto TyInfo = getContext().getTypeInfoInChars(Ty);
6832 // The alignment of things in the argument area is never larger than
6833 // StackAlignInBytes.
6835 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6837 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6838 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6840 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6841 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6844 // If there was a promotion, "unpromote" into a temporary.
6845 // TODO: can we just use a pointer into a subset of the original slot?
6847 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6848 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6850 // Truncate down to the right width.
6851 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
6853 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
6854 if (OrigTy->isPointerType())
6855 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
6857 CGF.Builder.CreateStore(V, Temp);
6864 bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
6865 int TySize = getContext().getTypeSize(Ty);
6867 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
6868 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
6875 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6876 llvm::Value *Address) const {
6877 // This information comes from gcc's implementation, which seems to
6878 // as canonical as it gets.
6880 // Everything on MIPS is 4 bytes. Double-precision FP registers
6881 // are aliased to pairs of single-precision FP registers.
6882 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
6884 // 0-31 are the general purpose registers, $0 - $31.
6885 // 32-63 are the floating-point registers, $f0 - $f31.
6886 // 64 and 65 are the multiply/divide registers, $hi and $lo.
6887 // 66 is the (notional, I think) register for signal-handler return.
6888 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
6890 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
6891 // They are one bit wide and ignored here.
6893 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
6894 // (coprocessor 1 is the FP unit)
6895 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
6896 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
6897 // 176-181 are the DSP accumulator registers.
6898 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
6902 //===----------------------------------------------------------------------===//
6903 // AVR ABI Implementation.
6904 //===----------------------------------------------------------------------===//
6907 class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
6909 AVRTargetCodeGenInfo(CodeGenTypes &CGT)
6910 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) { }
6912 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6913 CodeGen::CodeGenModule &CGM) const override {
6914 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
6916 auto *Fn = cast<llvm::Function>(GV);
6918 if (FD->getAttr<AVRInterruptAttr>())
6919 Fn->addFnAttr("interrupt");
6921 if (FD->getAttr<AVRSignalAttr>())
6922 Fn->addFnAttr("signal");
6927 //===----------------------------------------------------------------------===//
6928 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
6929 // Currently subclassed only to implement custom OpenCL C function attribute
6931 //===----------------------------------------------------------------------===//
6935 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
6937 TCETargetCodeGenInfo(CodeGenTypes &CGT)
6938 : DefaultTargetCodeGenInfo(CGT) {}
6940 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6941 CodeGen::CodeGenModule &M) const override;
6944 void TCETargetCodeGenInfo::setTargetAttributes(
6945 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
6946 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6949 llvm::Function *F = cast<llvm::Function>(GV);
6951 if (M.getLangOpts().OpenCL) {
6952 if (FD->hasAttr<OpenCLKernelAttr>()) {
6953 // OpenCL C Kernel functions are not subject to inlining
6954 F->addFnAttr(llvm::Attribute::NoInline);
6955 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
6957 // Convert the reqd_work_group_size() attributes to metadata.
6958 llvm::LLVMContext &Context = F->getContext();
6959 llvm::NamedMDNode *OpenCLMetadata =
6960 M.getModule().getOrInsertNamedMetadata(
6961 "opencl.kernel_wg_size_info");
6963 SmallVector<llvm::Metadata *, 5> Operands;
6964 Operands.push_back(llvm::ConstantAsMetadata::get(F));
6967 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6968 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
6970 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6971 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
6973 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6974 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
6976 // Add a boolean constant operand for "required" (true) or "hint"
6977 // (false) for implementing the work_group_size_hint attr later.
6978 // Currently always true as the hint is not yet implemented.
6980 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
6981 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
6989 //===----------------------------------------------------------------------===//
6990 // Hexagon ABI Implementation
6991 //===----------------------------------------------------------------------===//
6995 class HexagonABIInfo : public ABIInfo {
6999 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7003 ABIArgInfo classifyReturnType(QualType RetTy) const;
7004 ABIArgInfo classifyArgumentType(QualType RetTy) const;
7006 void computeInfo(CGFunctionInfo &FI) const override;
7008 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7009 QualType Ty) const override;
7012 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
7014 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
7015 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
7017 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
7024 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
7025 if (!getCXXABI().classifyReturnType(FI))
7026 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7027 for (auto &I : FI.arguments())
7028 I.info = classifyArgumentType(I.type);
7031 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
7032 if (!isAggregateTypeForABI(Ty)) {
7033 // Treat an enum type as its underlying type.
7034 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7035 Ty = EnumTy->getDecl()->getIntegerType();
7037 return (Ty->isPromotableIntegerType() ?
7038 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
7041 // Ignore empty records.
7042 if (isEmptyRecord(getContext(), Ty, true))
7043 return ABIArgInfo::getIgnore();
7045 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7046 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7048 uint64_t Size = getContext().getTypeSize(Ty);
7050 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
7051 // Pass in the smallest viable integer type.
7053 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7055 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7057 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7059 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7062 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
7063 if (RetTy->isVoidType())
7064 return ABIArgInfo::getIgnore();
7066 // Large vector types should be returned via memory.
7067 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
7068 return getNaturalAlignIndirect(RetTy);
7070 if (!isAggregateTypeForABI(RetTy)) {
7071 // Treat an enum type as its underlying type.
7072 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7073 RetTy = EnumTy->getDecl()->getIntegerType();
7075 return (RetTy->isPromotableIntegerType() ?
7076 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
7079 if (isEmptyRecord(getContext(), RetTy, true))
7080 return ABIArgInfo::getIgnore();
7082 // Aggregates <= 8 bytes are returned in r0; other aggregates
7083 // are returned indirectly.
7084 uint64_t Size = getContext().getTypeSize(RetTy);
7086 // Return in the smallest viable integer type.
7088 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7090 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7092 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7093 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7096 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
7099 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7100 QualType Ty) const {
7101 // FIXME: Someone needs to audit that this handle alignment correctly.
7102 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7103 getContext().getTypeInfoInChars(Ty),
7104 CharUnits::fromQuantity(4),
7105 /*AllowHigherAlign*/ true);
7108 //===----------------------------------------------------------------------===//
7109 // Lanai ABI Implementation
7110 //===----------------------------------------------------------------------===//
7113 class LanaiABIInfo : public DefaultABIInfo {
7115 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7117 bool shouldUseInReg(QualType Ty, CCState &State) const;
7119 void computeInfo(CGFunctionInfo &FI) const override {
7120 CCState State(FI.getCallingConvention());
7121 // Lanai uses 4 registers to pass arguments unless the function has the
7122 // regparm attribute set.
7123 if (FI.getHasRegParm()) {
7124 State.FreeRegs = FI.getRegParm();
7129 if (!getCXXABI().classifyReturnType(FI))
7130 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7131 for (auto &I : FI.arguments())
7132 I.info = classifyArgumentType(I.type, State);
7135 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
7136 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
7138 } // end anonymous namespace
7140 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
7141 unsigned Size = getContext().getTypeSize(Ty);
7142 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
7144 if (SizeInRegs == 0)
7147 if (SizeInRegs > State.FreeRegs) {
7152 State.FreeRegs -= SizeInRegs;
7157 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
7158 CCState &State) const {
7160 if (State.FreeRegs) {
7161 --State.FreeRegs; // Non-byval indirects just use one pointer.
7162 return getNaturalAlignIndirectInReg(Ty);
7164 return getNaturalAlignIndirect(Ty, false);
7167 // Compute the byval alignment.
7168 const unsigned MinABIStackAlignInBytes = 4;
7169 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
7170 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
7171 /*Realign=*/TypeAlign >
7172 MinABIStackAlignInBytes);
7175 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
7176 CCState &State) const {
7177 // Check with the C++ ABI first.
7178 const RecordType *RT = Ty->getAs<RecordType>();
7180 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
7181 if (RAA == CGCXXABI::RAA_Indirect) {
7182 return getIndirectResult(Ty, /*ByVal=*/false, State);
7183 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
7184 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
7188 if (isAggregateTypeForABI(Ty)) {
7189 // Structures with flexible arrays are always indirect.
7190 if (RT && RT->getDecl()->hasFlexibleArrayMember())
7191 return getIndirectResult(Ty, /*ByVal=*/true, State);
7193 // Ignore empty structs/unions.
7194 if (isEmptyRecord(getContext(), Ty, true))
7195 return ABIArgInfo::getIgnore();
7197 llvm::LLVMContext &LLVMContext = getVMContext();
7198 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
7199 if (SizeInRegs <= State.FreeRegs) {
7200 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
7201 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
7202 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
7203 State.FreeRegs -= SizeInRegs;
7204 return ABIArgInfo::getDirectInReg(Result);
7208 return getIndirectResult(Ty, true, State);
7211 // Treat an enum type as its underlying type.
7212 if (const auto *EnumTy = Ty->getAs<EnumType>())
7213 Ty = EnumTy->getDecl()->getIntegerType();
7215 bool InReg = shouldUseInReg(Ty, State);
7216 if (Ty->isPromotableIntegerType()) {
7218 return ABIArgInfo::getDirectInReg();
7219 return ABIArgInfo::getExtend();
7222 return ABIArgInfo::getDirectInReg();
7223 return ABIArgInfo::getDirect();
7227 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
7229 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7230 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
7234 //===----------------------------------------------------------------------===//
7235 // AMDGPU ABI Implementation
7236 //===----------------------------------------------------------------------===//
7240 class AMDGPUABIInfo final : public DefaultABIInfo {
7242 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7245 ABIArgInfo classifyArgumentType(QualType Ty) const;
7247 void computeInfo(CGFunctionInfo &FI) const override;
7250 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
7251 if (!getCXXABI().classifyReturnType(FI))
7252 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7254 unsigned CC = FI.getCallingConvention();
7255 for (auto &Arg : FI.arguments())
7256 if (CC == llvm::CallingConv::AMDGPU_KERNEL)
7257 Arg.info = classifyArgumentType(Arg.type);
7259 Arg.info = DefaultABIInfo::classifyArgumentType(Arg.type);
7262 /// \brief Classify argument of given type \p Ty.
7263 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty) const {
7264 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7266 return DefaultABIInfo::classifyArgumentType(Ty);
7269 // Coerce single element structs to its element.
7270 if (StrTy->getNumElements() == 1) {
7271 return ABIArgInfo::getDirect();
7274 // If we set CanBeFlattened to true, CodeGen will expand the struct to its
7275 // individual elements, which confuses the Clover OpenCL backend; therefore we
7276 // have to set it to false here. Other args of getDirect() are just defaults.
7277 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
7280 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
7282 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
7283 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {}
7284 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7285 CodeGen::CodeGenModule &M) const override;
7286 unsigned getOpenCLKernelCallingConv() const override;
7288 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
7289 llvm::PointerType *T, QualType QT) const override;
7293 static void appendOpenCLVersionMD (CodeGen::CodeGenModule &CGM);
7295 void AMDGPUTargetCodeGenInfo::setTargetAttributes(
7297 llvm::GlobalValue *GV,
7298 CodeGen::CodeGenModule &M) const {
7299 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7303 llvm::Function *F = cast<llvm::Function>(GV);
7305 const auto *ReqdWGS = M.getLangOpts().OpenCL ?
7306 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
7307 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
7308 if (ReqdWGS || FlatWGS) {
7309 unsigned Min = FlatWGS ? FlatWGS->getMin() : 0;
7310 unsigned Max = FlatWGS ? FlatWGS->getMax() : 0;
7311 if (ReqdWGS && Min == 0 && Max == 0)
7312 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
7315 assert(Min <= Max && "Min must be less than or equal Max");
7317 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
7318 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
7320 assert(Max == 0 && "Max must be zero");
7323 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
7324 unsigned Min = Attr->getMin();
7325 unsigned Max = Attr->getMax();
7328 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
7330 std::string AttrVal = llvm::utostr(Min);
7332 AttrVal = AttrVal + "," + llvm::utostr(Max);
7333 F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
7335 assert(Max == 0 && "Max must be zero");
7338 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
7339 unsigned NumSGPR = Attr->getNumSGPR();
7342 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
7345 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
7346 uint32_t NumVGPR = Attr->getNumVGPR();
7349 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
7352 appendOpenCLVersionMD(M);
7355 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7356 return llvm::CallingConv::AMDGPU_KERNEL;
7359 // Currently LLVM assumes null pointers always have value 0,
7360 // which results in incorrectly transformed IR. Therefore, instead of
7361 // emitting null pointers in private and local address spaces, a null
7362 // pointer in generic address space is emitted which is casted to a
7363 // pointer in local or private address space.
7364 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
7365 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
7366 QualType QT) const {
7367 if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
7368 return llvm::ConstantPointerNull::get(PT);
7370 auto &Ctx = CGM.getContext();
7371 auto NPT = llvm::PointerType::get(PT->getElementType(),
7372 Ctx.getTargetAddressSpace(LangAS::opencl_generic));
7373 return llvm::ConstantExpr::getAddrSpaceCast(
7374 llvm::ConstantPointerNull::get(NPT), PT);
7377 //===----------------------------------------------------------------------===//
7378 // SPARC v8 ABI Implementation.
7379 // Based on the SPARC Compliance Definition version 2.4.1.
7381 // Ensures that complex values are passed in registers.
7384 class SparcV8ABIInfo : public DefaultABIInfo {
7386 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7389 ABIArgInfo classifyReturnType(QualType RetTy) const;
7390 void computeInfo(CGFunctionInfo &FI) const override;
7392 } // end anonymous namespace
7396 SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
7397 if (Ty->isAnyComplexType()) {
7398 return ABIArgInfo::getDirect();
7401 return DefaultABIInfo::classifyReturnType(Ty);
7405 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7407 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7408 for (auto &Arg : FI.arguments())
7409 Arg.info = classifyArgumentType(Arg.type);
7413 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
7415 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
7416 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
7418 } // end anonymous namespace
7420 //===----------------------------------------------------------------------===//
7421 // SPARC v9 ABI Implementation.
7422 // Based on the SPARC Compliance Definition version 2.4.1.
7424 // Function arguments a mapped to a nominal "parameter array" and promoted to
7425 // registers depending on their type. Each argument occupies 8 or 16 bytes in
7426 // the array, structs larger than 16 bytes are passed indirectly.
7428 // One case requires special care:
7435 // When a struct mixed is passed by value, it only occupies 8 bytes in the
7436 // parameter array, but the int is passed in an integer register, and the float
7437 // is passed in a floating point register. This is represented as two arguments
7438 // with the LLVM IR inreg attribute:
7440 // declare void f(i32 inreg %i, float inreg %f)
7442 // The code generator will only allocate 4 bytes from the parameter array for
7443 // the inreg arguments. All other arguments are allocated a multiple of 8
7447 class SparcV9ABIInfo : public ABIInfo {
7449 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7452 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
7453 void computeInfo(CGFunctionInfo &FI) const override;
7454 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7455 QualType Ty) const override;
7457 // Coercion type builder for structs passed in registers. The coercion type
7458 // serves two purposes:
7460 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
7462 // 2. Expose aligned floating point elements as first-level elements, so the
7463 // code generator knows to pass them in floating point registers.
7465 // We also compute the InReg flag which indicates that the struct contains
7466 // aligned 32-bit floats.
7468 struct CoerceBuilder {
7469 llvm::LLVMContext &Context;
7470 const llvm::DataLayout &DL;
7471 SmallVector<llvm::Type*, 8> Elems;
7475 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
7476 : Context(c), DL(dl), Size(0), InReg(false) {}
7478 // Pad Elems with integers until Size is ToSize.
7479 void pad(uint64_t ToSize) {
7480 assert(ToSize >= Size && "Cannot remove elements");
7484 // Finish the current 64-bit word.
7485 uint64_t Aligned = llvm::alignTo(Size, 64);
7486 if (Aligned > Size && Aligned <= ToSize) {
7487 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
7491 // Add whole 64-bit words.
7492 while (Size + 64 <= ToSize) {
7493 Elems.push_back(llvm::Type::getInt64Ty(Context));
7497 // Final in-word padding.
7498 if (Size < ToSize) {
7499 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
7504 // Add a floating point element at Offset.
7505 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
7506 // Unaligned floats are treated as integers.
7509 // The InReg flag is only required if there are any floats < 64 bits.
7513 Elems.push_back(Ty);
7514 Size = Offset + Bits;
7517 // Add a struct type to the coercion type, starting at Offset (in bits).
7518 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
7519 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
7520 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
7521 llvm::Type *ElemTy = StrTy->getElementType(i);
7522 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
7523 switch (ElemTy->getTypeID()) {
7524 case llvm::Type::StructTyID:
7525 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
7527 case llvm::Type::FloatTyID:
7528 addFloat(ElemOffset, ElemTy, 32);
7530 case llvm::Type::DoubleTyID:
7531 addFloat(ElemOffset, ElemTy, 64);
7533 case llvm::Type::FP128TyID:
7534 addFloat(ElemOffset, ElemTy, 128);
7536 case llvm::Type::PointerTyID:
7537 if (ElemOffset % 64 == 0) {
7539 Elems.push_back(ElemTy);
7549 // Check if Ty is a usable substitute for the coercion type.
7550 bool isUsableType(llvm::StructType *Ty) const {
7551 return llvm::makeArrayRef(Elems) == Ty->elements();
7554 // Get the coercion type as a literal struct type.
7555 llvm::Type *getType() const {
7556 if (Elems.size() == 1)
7557 return Elems.front();
7559 return llvm::StructType::get(Context, Elems);
7563 } // end anonymous namespace
7566 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
7567 if (Ty->isVoidType())
7568 return ABIArgInfo::getIgnore();
7570 uint64_t Size = getContext().getTypeSize(Ty);
7572 // Anything too big to fit in registers is passed with an explicit indirect
7573 // pointer / sret pointer.
7574 if (Size > SizeLimit)
7575 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7577 // Treat an enum type as its underlying type.
7578 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7579 Ty = EnumTy->getDecl()->getIntegerType();
7581 // Integer types smaller than a register are extended.
7582 if (Size < 64 && Ty->isIntegerType())
7583 return ABIArgInfo::getExtend();
7585 // Other non-aggregates go in registers.
7586 if (!isAggregateTypeForABI(Ty))
7587 return ABIArgInfo::getDirect();
7589 // If a C++ object has either a non-trivial copy constructor or a non-trivial
7590 // destructor, it is passed with an explicit indirect pointer / sret pointer.
7591 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7592 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7594 // This is a small aggregate type that should be passed in registers.
7595 // Build a coercion type from the LLVM struct type.
7596 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7598 return ABIArgInfo::getDirect();
7600 CoerceBuilder CB(getVMContext(), getDataLayout());
7601 CB.addStruct(0, StrTy);
7602 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
7604 // Try to use the original type for coercion.
7605 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
7608 return ABIArgInfo::getDirectInReg(CoerceTy);
7610 return ABIArgInfo::getDirect(CoerceTy);
7613 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7614 QualType Ty) const {
7615 ABIArgInfo AI = classifyType(Ty, 16 * 8);
7616 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7617 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7618 AI.setCoerceToType(ArgTy);
7620 CharUnits SlotSize = CharUnits::fromQuantity(8);
7622 CGBuilderTy &Builder = CGF.Builder;
7623 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
7624 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
7626 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
7628 Address ArgAddr = Address::invalid();
7630 switch (AI.getKind()) {
7631 case ABIArgInfo::Expand:
7632 case ABIArgInfo::CoerceAndExpand:
7633 case ABIArgInfo::InAlloca:
7634 llvm_unreachable("Unsupported ABI kind for va_arg");
7636 case ABIArgInfo::Extend: {
7638 CharUnits Offset = SlotSize - TypeInfo.first;
7639 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
7643 case ABIArgInfo::Direct: {
7644 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
7645 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
7650 case ABIArgInfo::Indirect:
7652 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
7653 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
7657 case ABIArgInfo::Ignore:
7658 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
7662 llvm::Value *NextPtr =
7663 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
7664 Builder.CreateStore(NextPtr, VAListAddr);
7666 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
7669 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7670 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
7671 for (auto &I : FI.arguments())
7672 I.info = classifyType(I.type, 16 * 8);
7676 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
7678 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
7679 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
7681 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
7685 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7686 llvm::Value *Address) const override;
7688 } // end anonymous namespace
7691 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7692 llvm::Value *Address) const {
7693 // This is calculated from the LLVM and GCC tables and verified
7694 // against gcc output. AFAIK all ABIs use the same encoding.
7696 CodeGen::CGBuilderTy &Builder = CGF.Builder;
7698 llvm::IntegerType *i8 = CGF.Int8Ty;
7699 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
7700 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
7702 // 0-31: the 8-byte general-purpose registers
7703 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
7705 // 32-63: f0-31, the 4-byte floating-point registers
7706 AssignToArrayRange(Builder, Address, Four8, 32, 63);
7716 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
7718 // 72-87: d0-15, the 8-byte floating-point registers
7719 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
7725 //===----------------------------------------------------------------------===//
7726 // XCore ABI Implementation
7727 //===----------------------------------------------------------------------===//
7731 /// A SmallStringEnc instance is used to build up the TypeString by passing
7732 /// it by reference between functions that append to it.
7733 typedef llvm::SmallString<128> SmallStringEnc;
7735 /// TypeStringCache caches the meta encodings of Types.
7737 /// The reason for caching TypeStrings is two fold:
7738 /// 1. To cache a type's encoding for later uses;
7739 /// 2. As a means to break recursive member type inclusion.
7741 /// A cache Entry can have a Status of:
7742 /// NonRecursive: The type encoding is not recursive;
7743 /// Recursive: The type encoding is recursive;
7744 /// Incomplete: An incomplete TypeString;
7745 /// IncompleteUsed: An incomplete TypeString that has been used in a
7746 /// Recursive type encoding.
7748 /// A NonRecursive entry will have all of its sub-members expanded as fully
7749 /// as possible. Whilst it may contain types which are recursive, the type
7750 /// itself is not recursive and thus its encoding may be safely used whenever
7751 /// the type is encountered.
7753 /// A Recursive entry will have all of its sub-members expanded as fully as
7754 /// possible. The type itself is recursive and it may contain other types which
7755 /// are recursive. The Recursive encoding must not be used during the expansion
7756 /// of a recursive type's recursive branch. For simplicity the code uses
7757 /// IncompleteCount to reject all usage of Recursive encodings for member types.
7759 /// An Incomplete entry is always a RecordType and only encodes its
7760 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
7761 /// are placed into the cache during type expansion as a means to identify and
7762 /// handle recursive inclusion of types as sub-members. If there is recursion
7763 /// the entry becomes IncompleteUsed.
7765 /// During the expansion of a RecordType's members:
7767 /// If the cache contains a NonRecursive encoding for the member type, the
7768 /// cached encoding is used;
7770 /// If the cache contains a Recursive encoding for the member type, the
7771 /// cached encoding is 'Swapped' out, as it may be incorrect, and...
7773 /// If the member is a RecordType, an Incomplete encoding is placed into the
7774 /// cache to break potential recursive inclusion of itself as a sub-member;
7776 /// Once a member RecordType has been expanded, its temporary incomplete
7777 /// entry is removed from the cache. If a Recursive encoding was swapped out
7778 /// it is swapped back in;
7780 /// If an incomplete entry is used to expand a sub-member, the incomplete
7781 /// entry is marked as IncompleteUsed. The cache keeps count of how many
7782 /// IncompleteUsed entries it currently contains in IncompleteUsedCount;
7784 /// If a member's encoding is found to be a NonRecursive or Recursive viz:
7785 /// IncompleteUsedCount==0, the member's encoding is added to the cache.
7786 /// Else the member is part of a recursive type and thus the recursion has
7787 /// been exited too soon for the encoding to be correct for the member.
7789 class TypeStringCache {
7790 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
7792 std::string Str; // The encoded TypeString for the type.
7793 enum Status State; // Information about the encoding in 'Str'.
7794 std::string Swapped; // A temporary place holder for a Recursive encoding
7795 // during the expansion of RecordType's members.
7797 std::map<const IdentifierInfo *, struct Entry> Map;
7798 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
7799 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
7801 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
7802 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
7803 bool removeIncomplete(const IdentifierInfo *ID);
7804 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
7806 StringRef lookupStr(const IdentifierInfo *ID);
7809 /// TypeString encodings for enum & union fields must be order.
7810 /// FieldEncoding is a helper for this ordering process.
7811 class FieldEncoding {
7815 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
7816 StringRef str() { return Enc; }
7817 bool operator<(const FieldEncoding &rhs) const {
7818 if (HasName != rhs.HasName) return HasName;
7819 return Enc < rhs.Enc;
7823 class XCoreABIInfo : public DefaultABIInfo {
7825 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7826 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7827 QualType Ty) const override;
7830 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
7831 mutable TypeStringCache TSC;
7833 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
7834 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
7835 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7836 CodeGen::CodeGenModule &M) const override;
7839 } // End anonymous namespace.
7841 // TODO: this implementation is likely now redundant with the default
7843 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7844 QualType Ty) const {
7845 CGBuilderTy &Builder = CGF.Builder;
7848 CharUnits SlotSize = CharUnits::fromQuantity(4);
7849 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
7851 // Handle the argument.
7852 ABIArgInfo AI = classifyArgumentType(Ty);
7853 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
7854 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7855 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7856 AI.setCoerceToType(ArgTy);
7857 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
7859 Address Val = Address::invalid();
7860 CharUnits ArgSize = CharUnits::Zero();
7861 switch (AI.getKind()) {
7862 case ABIArgInfo::Expand:
7863 case ABIArgInfo::CoerceAndExpand:
7864 case ABIArgInfo::InAlloca:
7865 llvm_unreachable("Unsupported ABI kind for va_arg");
7866 case ABIArgInfo::Ignore:
7867 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
7868 ArgSize = CharUnits::Zero();
7870 case ABIArgInfo::Extend:
7871 case ABIArgInfo::Direct:
7872 Val = Builder.CreateBitCast(AP, ArgPtrTy);
7873 ArgSize = CharUnits::fromQuantity(
7874 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
7875 ArgSize = ArgSize.alignTo(SlotSize);
7877 case ABIArgInfo::Indirect:
7878 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
7879 Val = Address(Builder.CreateLoad(Val), TypeAlign);
7884 // Increment the VAList.
7885 if (!ArgSize.isZero()) {
7887 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
7888 Builder.CreateStore(APN, VAListAddr);
7894 /// During the expansion of a RecordType, an incomplete TypeString is placed
7895 /// into the cache as a means to identify and break recursion.
7896 /// If there is a Recursive encoding in the cache, it is swapped out and will
7897 /// be reinserted by removeIncomplete().
7898 /// All other types of encoding should have been used rather than arriving here.
7899 void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
7900 std::string StubEnc) {
7904 assert( (E.Str.empty() || E.State == Recursive) &&
7905 "Incorrectly use of addIncomplete");
7906 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
7907 E.Swapped.swap(E.Str); // swap out the Recursive
7908 E.Str.swap(StubEnc);
7909 E.State = Incomplete;
7913 /// Once the RecordType has been expanded, the temporary incomplete TypeString
7914 /// must be removed from the cache.
7915 /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
7916 /// Returns true if the RecordType was defined recursively.
7917 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
7920 auto I = Map.find(ID);
7921 assert(I != Map.end() && "Entry not present");
7922 Entry &E = I->second;
7923 assert( (E.State == Incomplete ||
7924 E.State == IncompleteUsed) &&
7925 "Entry must be an incomplete type");
7926 bool IsRecursive = false;
7927 if (E.State == IncompleteUsed) {
7928 // We made use of our Incomplete encoding, thus we are recursive.
7930 --IncompleteUsedCount;
7932 if (E.Swapped.empty())
7935 // Swap the Recursive back.
7936 E.Swapped.swap(E.Str);
7938 E.State = Recursive;
7944 /// Add the encoded TypeString to the cache only if it is NonRecursive or
7945 /// Recursive (viz: all sub-members were expanded as fully as possible).
7946 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
7948 if (!ID || IncompleteUsedCount)
7949 return; // No key or it is is an incomplete sub-type so don't add.
7951 if (IsRecursive && !E.Str.empty()) {
7952 assert(E.State==Recursive && E.Str.size() == Str.size() &&
7953 "This is not the same Recursive entry");
7954 // The parent container was not recursive after all, so we could have used
7955 // this Recursive sub-member entry after all, but we assumed the worse when
7956 // we started viz: IncompleteCount!=0.
7959 assert(E.Str.empty() && "Entry already present");
7961 E.State = IsRecursive? Recursive : NonRecursive;
7964 /// Return a cached TypeString encoding for the ID. If there isn't one, or we
7965 /// are recursively expanding a type (IncompleteCount != 0) and the cached
7966 /// encoding is Recursive, return an empty StringRef.
7967 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
7969 return StringRef(); // We have no key.
7970 auto I = Map.find(ID);
7972 return StringRef(); // We have no encoding.
7973 Entry &E = I->second;
7974 if (E.State == Recursive && IncompleteCount)
7975 return StringRef(); // We don't use Recursive encodings for member types.
7977 if (E.State == Incomplete) {
7978 // The incomplete type is being used to break out of recursion.
7979 E.State = IncompleteUsed;
7980 ++IncompleteUsedCount;
7985 /// The XCore ABI includes a type information section that communicates symbol
7986 /// type information to the linker. The linker uses this information to verify
7987 /// safety/correctness of things such as array bound and pointers et al.
7988 /// The ABI only requires C (and XC) language modules to emit TypeStrings.
7989 /// This type information (TypeString) is emitted into meta data for all global
7990 /// symbols: definitions, declarations, functions & variables.
7992 /// The TypeString carries type, qualifier, name, size & value details.
7993 /// Please see 'Tools Development Guide' section 2.16.2 for format details:
7994 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
7995 /// The output is tested by test/CodeGen/xcore-stringtype.c.
7997 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7998 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
8000 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
8001 void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8002 CodeGen::CodeGenModule &CGM) const {
8004 if (getTypeString(Enc, D, CGM, TSC)) {
8005 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
8006 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
8007 llvm::MDString::get(Ctx, Enc.str())};
8008 llvm::NamedMDNode *MD =
8009 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
8010 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
8014 //===----------------------------------------------------------------------===//
8015 // SPIR ABI Implementation
8016 //===----------------------------------------------------------------------===//
8019 class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
8021 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8022 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
8023 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8024 CodeGen::CodeGenModule &M) const override;
8025 unsigned getOpenCLKernelCallingConv() const override;
8027 } // End anonymous namespace.
8029 /// Emit SPIR specific metadata: OpenCL and SPIR version.
8030 void SPIRTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8031 CodeGen::CodeGenModule &CGM) const {
8032 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
8033 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(Ctx);
8034 llvm::Module &M = CGM.getModule();
8035 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
8036 // opencl.spir.version named metadata.
8037 llvm::Metadata *SPIRVerElts[] = {
8038 llvm::ConstantAsMetadata::get(
8039 llvm::ConstantInt::get(Int32Ty, CGM.getLangOpts().OpenCLVersion / 100)),
8040 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
8041 Int32Ty, (CGM.getLangOpts().OpenCLVersion / 100 > 1) ? 0 : 2))};
8042 llvm::NamedMDNode *SPIRVerMD =
8043 M.getOrInsertNamedMetadata("opencl.spir.version");
8044 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
8045 appendOpenCLVersionMD(CGM);
8048 static void appendOpenCLVersionMD(CodeGen::CodeGenModule &CGM) {
8049 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
8050 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(Ctx);
8051 llvm::Module &M = CGM.getModule();
8052 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
8053 // opencl.ocl.version named metadata node.
8054 llvm::Metadata *OCLVerElts[] = {
8055 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
8056 Int32Ty, CGM.getLangOpts().OpenCLVersion / 100)),
8057 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
8058 Int32Ty, (CGM.getLangOpts().OpenCLVersion % 100) / 10))};
8059 llvm::NamedMDNode *OCLVerMD =
8060 M.getOrInsertNamedMetadata("opencl.ocl.version");
8061 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
8064 unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
8065 return llvm::CallingConv::SPIR_KERNEL;
8068 static bool appendType(SmallStringEnc &Enc, QualType QType,
8069 const CodeGen::CodeGenModule &CGM,
8070 TypeStringCache &TSC);
8072 /// Helper function for appendRecordType().
8073 /// Builds a SmallVector containing the encoded field types in declaration
8075 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
8076 const RecordDecl *RD,
8077 const CodeGen::CodeGenModule &CGM,
8078 TypeStringCache &TSC) {
8079 for (const auto *Field : RD->fields()) {
8082 Enc += Field->getName();
8084 if (Field->isBitField()) {
8086 llvm::raw_svector_ostream OS(Enc);
8087 OS << Field->getBitWidthValue(CGM.getContext());
8090 if (!appendType(Enc, Field->getType(), CGM, TSC))
8092 if (Field->isBitField())
8095 FE.emplace_back(!Field->getName().empty(), Enc);
8100 /// Appends structure and union types to Enc and adds encoding to cache.
8101 /// Recursively calls appendType (via extractFieldType) for each field.
8102 /// Union types have their fields ordered according to the ABI.
8103 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
8104 const CodeGen::CodeGenModule &CGM,
8105 TypeStringCache &TSC, const IdentifierInfo *ID) {
8106 // Append the cached TypeString if we have one.
8107 StringRef TypeString = TSC.lookupStr(ID);
8108 if (!TypeString.empty()) {
8113 // Start to emit an incomplete TypeString.
8114 size_t Start = Enc.size();
8115 Enc += (RT->isUnionType()? 'u' : 's');
8118 Enc += ID->getName();
8121 // We collect all encoded fields and order as necessary.
8122 bool IsRecursive = false;
8123 const RecordDecl *RD = RT->getDecl()->getDefinition();
8124 if (RD && !RD->field_empty()) {
8125 // An incomplete TypeString stub is placed in the cache for this RecordType
8126 // so that recursive calls to this RecordType will use it whilst building a
8127 // complete TypeString for this RecordType.
8128 SmallVector<FieldEncoding, 16> FE;
8129 std::string StubEnc(Enc.substr(Start).str());
8130 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
8131 TSC.addIncomplete(ID, std::move(StubEnc));
8132 if (!extractFieldType(FE, RD, CGM, TSC)) {
8133 (void) TSC.removeIncomplete(ID);
8136 IsRecursive = TSC.removeIncomplete(ID);
8137 // The ABI requires unions to be sorted but not structures.
8138 // See FieldEncoding::operator< for sort algorithm.
8139 if (RT->isUnionType())
8140 std::sort(FE.begin(), FE.end());
8141 // We can now complete the TypeString.
8142 unsigned E = FE.size();
8143 for (unsigned I = 0; I != E; ++I) {
8150 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
8154 /// Appends enum types to Enc and adds the encoding to the cache.
8155 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
8156 TypeStringCache &TSC,
8157 const IdentifierInfo *ID) {
8158 // Append the cached TypeString if we have one.
8159 StringRef TypeString = TSC.lookupStr(ID);
8160 if (!TypeString.empty()) {
8165 size_t Start = Enc.size();
8168 Enc += ID->getName();
8171 // We collect all encoded enumerations and order them alphanumerically.
8172 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
8173 SmallVector<FieldEncoding, 16> FE;
8174 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
8176 SmallStringEnc EnumEnc;
8178 EnumEnc += I->getName();
8180 I->getInitVal().toString(EnumEnc);
8182 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
8184 std::sort(FE.begin(), FE.end());
8185 unsigned E = FE.size();
8186 for (unsigned I = 0; I != E; ++I) {
8193 TSC.addIfComplete(ID, Enc.substr(Start), false);
8197 /// Appends type's qualifier to Enc.
8198 /// This is done prior to appending the type's encoding.
8199 static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
8200 // Qualifiers are emitted in alphabetical order.
8201 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
8203 if (QT.isConstQualified())
8205 if (QT.isRestrictQualified())
8207 if (QT.isVolatileQualified())
8209 Enc += Table[Lookup];
8212 /// Appends built-in types to Enc.
8213 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
8214 const char *EncType;
8215 switch (BT->getKind()) {
8216 case BuiltinType::Void:
8219 case BuiltinType::Bool:
8222 case BuiltinType::Char_U:
8225 case BuiltinType::UChar:
8228 case BuiltinType::SChar:
8231 case BuiltinType::UShort:
8234 case BuiltinType::Short:
8237 case BuiltinType::UInt:
8240 case BuiltinType::Int:
8243 case BuiltinType::ULong:
8246 case BuiltinType::Long:
8249 case BuiltinType::ULongLong:
8252 case BuiltinType::LongLong:
8255 case BuiltinType::Float:
8258 case BuiltinType::Double:
8261 case BuiltinType::LongDouble:
8271 /// Appends a pointer encoding to Enc before calling appendType for the pointee.
8272 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
8273 const CodeGen::CodeGenModule &CGM,
8274 TypeStringCache &TSC) {
8276 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
8282 /// Appends array encoding to Enc before calling appendType for the element.
8283 static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
8284 const ArrayType *AT,
8285 const CodeGen::CodeGenModule &CGM,
8286 TypeStringCache &TSC, StringRef NoSizeEnc) {
8287 if (AT->getSizeModifier() != ArrayType::Normal)
8290 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
8291 CAT->getSize().toStringUnsigned(Enc);
8293 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
8295 // The Qualifiers should be attached to the type rather than the array.
8296 appendQualifier(Enc, QT);
8297 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
8303 /// Appends a function encoding to Enc, calling appendType for the return type
8304 /// and the arguments.
8305 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
8306 const CodeGen::CodeGenModule &CGM,
8307 TypeStringCache &TSC) {
8309 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
8312 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
8313 // N.B. we are only interested in the adjusted param types.
8314 auto I = FPT->param_type_begin();
8315 auto E = FPT->param_type_end();
8318 if (!appendType(Enc, *I, CGM, TSC))
8324 if (FPT->isVariadic())
8327 if (FPT->isVariadic())
8337 /// Handles the type's qualifier before dispatching a call to handle specific
8339 static bool appendType(SmallStringEnc &Enc, QualType QType,
8340 const CodeGen::CodeGenModule &CGM,
8341 TypeStringCache &TSC) {
8343 QualType QT = QType.getCanonicalType();
8345 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
8346 // The Qualifiers should be attached to the type rather than the array.
8347 // Thus we don't call appendQualifier() here.
8348 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
8350 appendQualifier(Enc, QT);
8352 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
8353 return appendBuiltinType(Enc, BT);
8355 if (const PointerType *PT = QT->getAs<PointerType>())
8356 return appendPointerType(Enc, PT, CGM, TSC);
8358 if (const EnumType *ET = QT->getAs<EnumType>())
8359 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
8361 if (const RecordType *RT = QT->getAsStructureType())
8362 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8364 if (const RecordType *RT = QT->getAsUnionType())
8365 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8367 if (const FunctionType *FT = QT->getAs<FunctionType>())
8368 return appendFunctionType(Enc, FT, CGM, TSC);
8373 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8374 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
8378 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8379 if (FD->getLanguageLinkage() != CLanguageLinkage)
8381 return appendType(Enc, FD->getType(), CGM, TSC);
8384 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8385 if (VD->getLanguageLinkage() != CLanguageLinkage)
8387 QualType QT = VD->getType().getCanonicalType();
8388 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
8389 // Global ArrayTypes are given a size of '*' if the size is unknown.
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 return appendType(Enc, QT, CGM, TSC);
8400 //===----------------------------------------------------------------------===//
8402 //===----------------------------------------------------------------------===//
8404 bool CodeGenModule::supportsCOMDAT() const {
8405 return getTriple().supportsCOMDAT();
8408 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
8409 if (TheTargetCodeGenInfo)
8410 return *TheTargetCodeGenInfo;
8412 // Helper to set the unique_ptr while still keeping the return value.
8413 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
8414 this->TheTargetCodeGenInfo.reset(P);
8418 const llvm::Triple &Triple = getTarget().getTriple();
8419 switch (Triple.getArch()) {
8421 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
8423 case llvm::Triple::le32:
8424 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
8425 case llvm::Triple::mips:
8426 case llvm::Triple::mipsel:
8427 if (Triple.getOS() == llvm::Triple::NaCl)
8428 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
8429 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
8431 case llvm::Triple::mips64:
8432 case llvm::Triple::mips64el:
8433 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
8435 case llvm::Triple::avr:
8436 return SetCGInfo(new AVRTargetCodeGenInfo(Types));
8438 case llvm::Triple::aarch64:
8439 case llvm::Triple::aarch64_be: {
8440 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
8441 if (getTarget().getABI() == "darwinpcs")
8442 Kind = AArch64ABIInfo::DarwinPCS;
8444 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
8447 case llvm::Triple::wasm32:
8448 case llvm::Triple::wasm64:
8449 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
8451 case llvm::Triple::arm:
8452 case llvm::Triple::armeb:
8453 case llvm::Triple::thumb:
8454 case llvm::Triple::thumbeb: {
8455 if (Triple.getOS() == llvm::Triple::Win32) {
8457 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
8460 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
8461 StringRef ABIStr = getTarget().getABI();
8462 if (ABIStr == "apcs-gnu")
8463 Kind = ARMABIInfo::APCS;
8464 else if (ABIStr == "aapcs16")
8465 Kind = ARMABIInfo::AAPCS16_VFP;
8466 else if (CodeGenOpts.FloatABI == "hard" ||
8467 (CodeGenOpts.FloatABI != "soft" &&
8468 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
8469 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
8470 Triple.getEnvironment() == llvm::Triple::EABIHF)))
8471 Kind = ARMABIInfo::AAPCS_VFP;
8473 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
8476 case llvm::Triple::ppc:
8478 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
8479 case llvm::Triple::ppc64:
8480 if (Triple.isOSBinFormatELF()) {
8481 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
8482 if (getTarget().getABI() == "elfv2")
8483 Kind = PPC64_SVR4_ABIInfo::ELFv2;
8484 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
8485 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
8487 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8490 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
8491 case llvm::Triple::ppc64le: {
8492 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
8493 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
8494 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
8495 Kind = PPC64_SVR4_ABIInfo::ELFv1;
8496 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
8497 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
8499 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8503 case llvm::Triple::nvptx:
8504 case llvm::Triple::nvptx64:
8505 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
8507 case llvm::Triple::msp430:
8508 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
8510 case llvm::Triple::systemz: {
8511 bool HasVector = getTarget().getABI() == "vector";
8512 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
8515 case llvm::Triple::tce:
8516 case llvm::Triple::tcele:
8517 return SetCGInfo(new TCETargetCodeGenInfo(Types));
8519 case llvm::Triple::x86: {
8520 bool IsDarwinVectorABI = Triple.isOSDarwin();
8521 bool RetSmallStructInRegABI =
8522 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
8523 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
8525 if (Triple.getOS() == llvm::Triple::Win32) {
8526 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
8527 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8528 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
8530 return SetCGInfo(new X86_32TargetCodeGenInfo(
8531 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8532 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
8533 CodeGenOpts.FloatABI == "soft"));
8537 case llvm::Triple::x86_64: {
8538 StringRef ABI = getTarget().getABI();
8539 X86AVXABILevel AVXLevel =
8541 ? X86AVXABILevel::AVX512
8542 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
8544 switch (Triple.getOS()) {
8545 case llvm::Triple::Win32:
8546 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
8547 case llvm::Triple::PS4:
8548 return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
8550 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
8553 case llvm::Triple::hexagon:
8554 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
8555 case llvm::Triple::lanai:
8556 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
8557 case llvm::Triple::r600:
8558 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
8559 case llvm::Triple::amdgcn:
8560 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
8561 case llvm::Triple::sparc:
8562 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
8563 case llvm::Triple::sparcv9:
8564 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
8565 case llvm::Triple::xcore:
8566 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
8567 case llvm::Triple::spir:
8568 case llvm::Triple::spir64:
8569 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));