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