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 // OpenCL kernels are called via an explicit runtime API with arguments
402 // set with clSetKernelArg(), not as normal sub-functions.
403 // Return SPIR_KERNEL by default as the kernel calling convention to
404 // ensure the fingerprint is fixed such way that each OpenCL argument
405 // gets one matching argument in the produced kernel function argument
406 // list to enable feasible implementation of clSetKernelArg() with
407 // aggregates etc. In case we would use the default C calling conv here,
408 // clSetKernelArg() might break depending on the target-specific
409 // conventions; different targets might split structs passed as values
410 // to multiple function arguments etc.
411 return llvm::CallingConv::SPIR_KERNEL;
414 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
415 llvm::PointerType *T, QualType QT) const {
416 return llvm::ConstantPointerNull::get(T);
419 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
420 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, unsigned SrcAddr,
421 unsigned DestAddr, llvm::Type *DestTy, bool isNonNull) const {
422 // Since target may map different address spaces in AST to the same address
423 // space, an address space conversion may end up as a bitcast.
424 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DestTy);
427 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
429 /// isEmptyField - Return true iff a the field is "empty", that is it
430 /// is an unnamed bit-field or an (array of) empty record(s).
431 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
433 if (FD->isUnnamedBitfield())
436 QualType FT = FD->getType();
438 // Constant arrays of empty records count as empty, strip them off.
439 // Constant arrays of zero length always count as empty.
441 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
442 if (AT->getSize() == 0)
444 FT = AT->getElementType();
447 const RecordType *RT = FT->getAs<RecordType>();
451 // C++ record fields are never empty, at least in the Itanium ABI.
453 // FIXME: We should use a predicate for whether this behavior is true in the
455 if (isa<CXXRecordDecl>(RT->getDecl()))
458 return isEmptyRecord(Context, FT, AllowArrays);
461 /// isEmptyRecord - Return true iff a structure contains only empty
462 /// fields. Note that a structure with a flexible array member is not
463 /// considered empty.
464 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
465 const RecordType *RT = T->getAs<RecordType>();
468 const RecordDecl *RD = RT->getDecl();
469 if (RD->hasFlexibleArrayMember())
472 // If this is a C++ record, check the bases first.
473 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
474 for (const auto &I : CXXRD->bases())
475 if (!isEmptyRecord(Context, I.getType(), true))
478 for (const auto *I : RD->fields())
479 if (!isEmptyField(Context, I, AllowArrays))
484 /// isSingleElementStruct - Determine if a structure is a "single
485 /// element struct", i.e. it has exactly one non-empty field or
486 /// exactly one field which is itself a single element
487 /// struct. Structures with flexible array members are never
488 /// considered single element structs.
490 /// \return The field declaration for the single non-empty field, if
492 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
493 const RecordType *RT = T->getAs<RecordType>();
497 const RecordDecl *RD = RT->getDecl();
498 if (RD->hasFlexibleArrayMember())
501 const Type *Found = nullptr;
503 // If this is a C++ record, check the bases first.
504 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
505 for (const auto &I : CXXRD->bases()) {
506 // Ignore empty records.
507 if (isEmptyRecord(Context, I.getType(), true))
510 // If we already found an element then this isn't a single-element struct.
514 // If this is non-empty and not a single element struct, the composite
515 // cannot be a single element struct.
516 Found = isSingleElementStruct(I.getType(), Context);
522 // Check for single element.
523 for (const auto *FD : RD->fields()) {
524 QualType FT = FD->getType();
526 // Ignore empty fields.
527 if (isEmptyField(Context, FD, true))
530 // If we already found an element then this isn't a single-element
535 // Treat single element arrays as the element.
536 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
537 if (AT->getSize().getZExtValue() != 1)
539 FT = AT->getElementType();
542 if (!isAggregateTypeForABI(FT)) {
543 Found = FT.getTypePtr();
545 Found = isSingleElementStruct(FT, Context);
551 // We don't consider a struct a single-element struct if it has
552 // padding beyond the element type.
553 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
560 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
561 const ABIArgInfo &AI) {
562 // This default implementation defers to the llvm backend's va_arg
563 // instruction. It can handle only passing arguments directly
564 // (typically only handled in the backend for primitive types), or
565 // aggregates passed indirectly by pointer (NOTE: if the "byval"
566 // flag has ABI impact in the callee, this implementation cannot
569 // Only a few cases are covered here at the moment -- those needed
570 // by the default abi.
573 if (AI.isIndirect()) {
574 assert(!AI.getPaddingType() &&
575 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
577 !AI.getIndirectRealign() &&
578 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
580 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
581 CharUnits TyAlignForABI = TyInfo.second;
584 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
586 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
587 return Address(Addr, TyAlignForABI);
589 assert((AI.isDirect() || AI.isExtend()) &&
590 "Unexpected ArgInfo Kind in generic VAArg emitter!");
592 assert(!AI.getInReg() &&
593 "Unexpected InReg seen in arginfo in generic VAArg emitter!");
594 assert(!AI.getPaddingType() &&
595 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
596 assert(!AI.getDirectOffset() &&
597 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
598 assert(!AI.getCoerceToType() &&
599 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
601 Address Temp = CGF.CreateMemTemp(Ty, "varet");
602 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
603 CGF.Builder.CreateStore(Val, Temp);
608 /// DefaultABIInfo - The default implementation for ABI specific
609 /// details. This implementation provides information which results in
610 /// self-consistent and sensible LLVM IR generation, but does not
611 /// conform to any particular ABI.
612 class DefaultABIInfo : public ABIInfo {
614 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
616 ABIArgInfo classifyReturnType(QualType RetTy) const;
617 ABIArgInfo classifyArgumentType(QualType RetTy) const;
619 void computeInfo(CGFunctionInfo &FI) const override {
620 if (!getCXXABI().classifyReturnType(FI))
621 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
622 for (auto &I : FI.arguments())
623 I.info = classifyArgumentType(I.type);
626 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
627 QualType Ty) const override {
628 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
632 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
634 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
635 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
638 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
639 Ty = useFirstFieldIfTransparentUnion(Ty);
641 if (isAggregateTypeForABI(Ty)) {
642 // Records with non-trivial destructors/copy-constructors should not be
644 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
645 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
647 return getNaturalAlignIndirect(Ty);
650 // Treat an enum type as its underlying type.
651 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
652 Ty = EnumTy->getDecl()->getIntegerType();
654 return (Ty->isPromotableIntegerType() ?
655 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
658 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
659 if (RetTy->isVoidType())
660 return ABIArgInfo::getIgnore();
662 if (isAggregateTypeForABI(RetTy))
663 return getNaturalAlignIndirect(RetTy);
665 // Treat an enum type as its underlying type.
666 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
667 RetTy = EnumTy->getDecl()->getIntegerType();
669 return (RetTy->isPromotableIntegerType() ?
670 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
673 //===----------------------------------------------------------------------===//
674 // WebAssembly ABI Implementation
676 // This is a very simple ABI that relies a lot on DefaultABIInfo.
677 //===----------------------------------------------------------------------===//
679 class WebAssemblyABIInfo final : public DefaultABIInfo {
681 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
682 : DefaultABIInfo(CGT) {}
685 ABIArgInfo classifyReturnType(QualType RetTy) const;
686 ABIArgInfo classifyArgumentType(QualType Ty) const;
688 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
689 // non-virtual, but computeInfo and EmitVAArg are virtual, so we
691 void computeInfo(CGFunctionInfo &FI) const override {
692 if (!getCXXABI().classifyReturnType(FI))
693 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
694 for (auto &Arg : FI.arguments())
695 Arg.info = classifyArgumentType(Arg.type);
698 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
699 QualType Ty) const override;
702 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
704 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
705 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
708 /// \brief Classify argument of given type \p Ty.
709 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
710 Ty = useFirstFieldIfTransparentUnion(Ty);
712 if (isAggregateTypeForABI(Ty)) {
713 // Records with non-trivial destructors/copy-constructors should not be
715 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
716 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
717 // Ignore empty structs/unions.
718 if (isEmptyRecord(getContext(), Ty, true))
719 return ABIArgInfo::getIgnore();
720 // Lower single-element structs to just pass a regular value. TODO: We
721 // could do reasonable-size multiple-element structs too, using getExpand(),
722 // though watch out for things like bitfields.
723 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
724 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
727 // Otherwise just do the default thing.
728 return DefaultABIInfo::classifyArgumentType(Ty);
731 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
732 if (isAggregateTypeForABI(RetTy)) {
733 // Records with non-trivial destructors/copy-constructors should not be
734 // returned by value.
735 if (!getRecordArgABI(RetTy, getCXXABI())) {
736 // Ignore empty structs/unions.
737 if (isEmptyRecord(getContext(), RetTy, true))
738 return ABIArgInfo::getIgnore();
739 // Lower single-element structs to just return a regular value. TODO: We
740 // could do reasonable-size multiple-element structs too, using
741 // ABIArgInfo::getDirect().
742 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
743 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
747 // Otherwise just do the default thing.
748 return DefaultABIInfo::classifyReturnType(RetTy);
751 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
753 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect=*/ false,
754 getContext().getTypeInfoInChars(Ty),
755 CharUnits::fromQuantity(4),
756 /*AllowHigherAlign=*/ true);
759 //===----------------------------------------------------------------------===//
760 // le32/PNaCl bitcode ABI Implementation
762 // This is a simplified version of the x86_32 ABI. Arguments and return values
763 // are always passed on the stack.
764 //===----------------------------------------------------------------------===//
766 class PNaClABIInfo : public ABIInfo {
768 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
770 ABIArgInfo classifyReturnType(QualType RetTy) const;
771 ABIArgInfo classifyArgumentType(QualType RetTy) const;
773 void computeInfo(CGFunctionInfo &FI) const override;
774 Address EmitVAArg(CodeGenFunction &CGF,
775 Address VAListAddr, QualType Ty) const override;
778 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
780 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
781 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
784 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
785 if (!getCXXABI().classifyReturnType(FI))
786 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
788 for (auto &I : FI.arguments())
789 I.info = classifyArgumentType(I.type);
792 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
794 // The PNaCL ABI is a bit odd, in that varargs don't use normal
795 // function classification. Structs get passed directly for varargs
796 // functions, through a rewriting transform in
797 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
798 // this target to actually support a va_arg instructions with an
799 // aggregate type, unlike other targets.
800 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
803 /// \brief Classify argument of given type \p Ty.
804 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
805 if (isAggregateTypeForABI(Ty)) {
806 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
807 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
808 return getNaturalAlignIndirect(Ty);
809 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
810 // Treat an enum type as its underlying type.
811 Ty = EnumTy->getDecl()->getIntegerType();
812 } else if (Ty->isFloatingType()) {
813 // Floating-point types don't go inreg.
814 return ABIArgInfo::getDirect();
817 return (Ty->isPromotableIntegerType() ?
818 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
821 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
822 if (RetTy->isVoidType())
823 return ABIArgInfo::getIgnore();
825 // In the PNaCl ABI we always return records/structures on the stack.
826 if (isAggregateTypeForABI(RetTy))
827 return getNaturalAlignIndirect(RetTy);
829 // Treat an enum type as its underlying type.
830 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
831 RetTy = EnumTy->getDecl()->getIntegerType();
833 return (RetTy->isPromotableIntegerType() ?
834 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
837 /// IsX86_MMXType - Return true if this is an MMX type.
838 bool IsX86_MMXType(llvm::Type *IRType) {
839 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
840 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
841 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
842 IRType->getScalarSizeInBits() != 64;
845 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
846 StringRef Constraint,
848 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
849 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
850 // Invalid MMX constraint
854 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
857 // No operation needed
861 /// Returns true if this type can be passed in SSE registers with the
862 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
863 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
864 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
865 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
867 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
868 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
869 // registers specially.
870 unsigned VecSize = Context.getTypeSize(VT);
871 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
877 /// Returns true if this aggregate is small enough to be passed in SSE registers
878 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
879 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
880 return NumMembers <= 4;
883 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
884 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
885 auto AI = ABIArgInfo::getDirect(T);
887 AI.setCanBeFlattened(false);
891 //===----------------------------------------------------------------------===//
892 // X86-32 ABI Implementation
893 //===----------------------------------------------------------------------===//
895 /// \brief Similar to llvm::CCState, but for Clang.
897 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
901 unsigned FreeSSERegs;
905 // Vectorcall only allows the first 6 parameters to be passed in registers.
906 VectorcallMaxParamNumAsReg = 6
909 /// X86_32ABIInfo - The X86-32 ABI information.
910 class X86_32ABIInfo : public SwiftABIInfo {
916 static const unsigned MinABIStackAlignInBytes = 4;
918 bool IsDarwinVectorABI;
919 bool IsRetSmallStructInRegABI;
920 bool IsWin32StructABI;
923 unsigned DefaultNumRegisterParameters;
925 static bool isRegisterSize(unsigned Size) {
926 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
929 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
930 // FIXME: Assumes vectorcall is in use.
931 return isX86VectorTypeForVectorCall(getContext(), Ty);
934 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
935 uint64_t NumMembers) const override {
936 // FIXME: Assumes vectorcall is in use.
937 return isX86VectorCallAggregateSmallEnough(NumMembers);
940 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
942 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
943 /// such that the argument will be passed in memory.
944 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
946 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
948 /// \brief Return the alignment to use for the given type on the stack.
949 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
951 Class classify(QualType Ty) const;
952 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
953 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
954 ABIArgInfo reclassifyHvaArgType(QualType RetTy, CCState &State,
955 const ABIArgInfo& current) const;
956 /// \brief Updates the number of available free registers, returns
957 /// true if any registers were allocated.
958 bool updateFreeRegs(QualType Ty, CCState &State) const;
960 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
961 bool &NeedsPadding) const;
962 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
964 bool canExpandIndirectArgument(QualType Ty) const;
966 /// \brief Rewrite the function info so that all memory arguments use
968 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
970 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
971 CharUnits &StackOffset, ABIArgInfo &Info,
972 QualType Type) const;
973 void computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
974 bool &UsedInAlloca) const;
978 void computeInfo(CGFunctionInfo &FI) const override;
979 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
980 QualType Ty) const override;
982 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
983 bool RetSmallStructInRegABI, bool Win32StructABI,
984 unsigned NumRegisterParameters, bool SoftFloatABI)
985 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
986 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
987 IsWin32StructABI(Win32StructABI),
988 IsSoftFloatABI(SoftFloatABI),
989 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
990 DefaultNumRegisterParameters(NumRegisterParameters) {}
992 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
993 ArrayRef<llvm::Type*> scalars,
994 bool asReturnValue) const override {
995 // LLVM's x86-32 lowering currently only assigns up to three
996 // integer registers and three fp registers. Oddly, it'll use up to
997 // four vector registers for vectors, but those can overlap with the
999 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1002 bool isSwiftErrorInRegister() const override {
1003 // x86-32 lowering does not support passing swifterror in a register.
1008 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1010 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1011 bool RetSmallStructInRegABI, bool Win32StructABI,
1012 unsigned NumRegisterParameters, bool SoftFloatABI)
1013 : TargetCodeGenInfo(new X86_32ABIInfo(
1014 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1015 NumRegisterParameters, SoftFloatABI)) {}
1017 static bool isStructReturnInRegABI(
1018 const llvm::Triple &Triple, const CodeGenOptions &Opts);
1020 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1021 CodeGen::CodeGenModule &CGM) const override;
1023 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1024 // Darwin uses different dwarf register numbers for EH.
1025 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
1029 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1030 llvm::Value *Address) const override;
1032 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1033 StringRef Constraint,
1034 llvm::Type* Ty) const override {
1035 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1038 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1039 std::string &Constraints,
1040 std::vector<llvm::Type *> &ResultRegTypes,
1041 std::vector<llvm::Type *> &ResultTruncRegTypes,
1042 std::vector<LValue> &ResultRegDests,
1043 std::string &AsmString,
1044 unsigned NumOutputs) const override;
1047 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
1048 unsigned Sig = (0xeb << 0) | // jmp rel8
1049 (0x06 << 8) | // .+0x08
1052 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1055 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1056 return "movl\t%ebp, %ebp"
1057 "\t\t## marker for objc_retainAutoreleaseReturnValue";
1063 /// Rewrite input constraint references after adding some output constraints.
1064 /// In the case where there is one output and one input and we add one output,
1065 /// we need to replace all operand references greater than or equal to 1:
1068 /// The result will be:
1071 static void rewriteInputConstraintReferences(unsigned FirstIn,
1072 unsigned NumNewOuts,
1073 std::string &AsmString) {
1075 llvm::raw_string_ostream OS(Buf);
1077 while (Pos < AsmString.size()) {
1078 size_t DollarStart = AsmString.find('$', Pos);
1079 if (DollarStart == std::string::npos)
1080 DollarStart = AsmString.size();
1081 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1082 if (DollarEnd == std::string::npos)
1083 DollarEnd = AsmString.size();
1084 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1086 size_t NumDollars = DollarEnd - DollarStart;
1087 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1088 // We have an operand reference.
1089 size_t DigitStart = Pos;
1090 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1091 if (DigitEnd == std::string::npos)
1092 DigitEnd = AsmString.size();
1093 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1094 unsigned OperandIndex;
1095 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1096 if (OperandIndex >= FirstIn)
1097 OperandIndex += NumNewOuts;
1105 AsmString = std::move(OS.str());
1108 /// Add output constraints for EAX:EDX because they are return registers.
1109 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1110 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1111 std::vector<llvm::Type *> &ResultRegTypes,
1112 std::vector<llvm::Type *> &ResultTruncRegTypes,
1113 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1114 unsigned NumOutputs) const {
1115 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1117 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1119 if (!Constraints.empty())
1121 if (RetWidth <= 32) {
1122 Constraints += "={eax}";
1123 ResultRegTypes.push_back(CGF.Int32Ty);
1125 // Use the 'A' constraint for EAX:EDX.
1126 Constraints += "=A";
1127 ResultRegTypes.push_back(CGF.Int64Ty);
1130 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1131 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1132 ResultTruncRegTypes.push_back(CoerceTy);
1134 // Coerce the integer by bitcasting the return slot pointer.
1135 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1136 CoerceTy->getPointerTo()));
1137 ResultRegDests.push_back(ReturnSlot);
1139 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1142 /// shouldReturnTypeInRegister - Determine if the given type should be
1143 /// returned in a register (for the Darwin and MCU ABI).
1144 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1145 ASTContext &Context) const {
1146 uint64_t Size = Context.getTypeSize(Ty);
1148 // For i386, type must be register sized.
1149 // For the MCU ABI, it only needs to be <= 8-byte
1150 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1153 if (Ty->isVectorType()) {
1154 // 64- and 128- bit vectors inside structures are not returned in
1156 if (Size == 64 || Size == 128)
1162 // If this is a builtin, pointer, enum, complex type, member pointer, or
1163 // member function pointer it is ok.
1164 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
1165 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
1166 Ty->isBlockPointerType() || Ty->isMemberPointerType())
1169 // Arrays are treated like records.
1170 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
1171 return shouldReturnTypeInRegister(AT->getElementType(), Context);
1173 // Otherwise, it must be a record type.
1174 const RecordType *RT = Ty->getAs<RecordType>();
1175 if (!RT) return false;
1177 // FIXME: Traverse bases here too.
1179 // Structure types are passed in register if all fields would be
1180 // passed in a register.
1181 for (const auto *FD : RT->getDecl()->fields()) {
1182 // Empty fields are ignored.
1183 if (isEmptyField(Context, FD, true))
1186 // Check fields recursively.
1187 if (!shouldReturnTypeInRegister(FD->getType(), Context))
1193 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1194 // Treat complex types as the element type.
1195 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1196 Ty = CTy->getElementType();
1198 // Check for a type which we know has a simple scalar argument-passing
1199 // convention without any padding. (We're specifically looking for 32
1200 // and 64-bit integer and integer-equivalents, float, and double.)
1201 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1202 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1205 uint64_t Size = Context.getTypeSize(Ty);
1206 return Size == 32 || Size == 64;
1209 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1211 for (const auto *FD : RD->fields()) {
1212 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1213 // argument is smaller than 32-bits, expanding the struct will create
1214 // alignment padding.
1215 if (!is32Or64BitBasicType(FD->getType(), Context))
1218 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1219 // how to expand them yet, and the predicate for telling if a bitfield still
1220 // counts as "basic" is more complicated than what we were doing previously.
1221 if (FD->isBitField())
1224 Size += Context.getTypeSize(FD->getType());
1229 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1231 // Don't do this if there are any non-empty bases.
1232 for (const CXXBaseSpecifier &Base : RD->bases()) {
1233 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1237 if (!addFieldSizes(Context, RD, Size))
1242 /// Test whether an argument type which is to be passed indirectly (on the
1243 /// stack) would have the equivalent layout if it was expanded into separate
1244 /// arguments. If so, we prefer to do the latter to avoid inhibiting
1246 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1247 // We can only expand structure types.
1248 const RecordType *RT = Ty->getAs<RecordType>();
1251 const RecordDecl *RD = RT->getDecl();
1253 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1254 if (!IsWin32StructABI) {
1255 // On non-Windows, we have to conservatively match our old bitcode
1256 // prototypes in order to be ABI-compatible at the bitcode level.
1257 if (!CXXRD->isCLike())
1260 // Don't do this for dynamic classes.
1261 if (CXXRD->isDynamicClass())
1264 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
1267 if (!addFieldSizes(getContext(), RD, Size))
1271 // We can do this if there was no alignment padding.
1272 return Size == getContext().getTypeSize(Ty);
1275 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
1276 // If the return value is indirect, then the hidden argument is consuming one
1277 // integer register.
1278 if (State.FreeRegs) {
1281 return getNaturalAlignIndirectInReg(RetTy);
1283 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
1286 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1287 CCState &State) const {
1288 if (RetTy->isVoidType())
1289 return ABIArgInfo::getIgnore();
1291 const Type *Base = nullptr;
1292 uint64_t NumElts = 0;
1293 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1294 State.CC == llvm::CallingConv::X86_RegCall) &&
1295 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1296 // The LLVM struct type for such an aggregate should lower properly.
1297 return ABIArgInfo::getDirect();
1300 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
1301 // On Darwin, some vectors are returned in registers.
1302 if (IsDarwinVectorABI) {
1303 uint64_t Size = getContext().getTypeSize(RetTy);
1305 // 128-bit vectors are a special case; they are returned in
1306 // registers and we need to make sure to pick a type the LLVM
1307 // backend will like.
1309 return ABIArgInfo::getDirect(llvm::VectorType::get(
1310 llvm::Type::getInt64Ty(getVMContext()), 2));
1312 // Always return in register if it fits in a general purpose
1313 // register, or if it is 64 bits and has a single element.
1314 if ((Size == 8 || Size == 16 || Size == 32) ||
1315 (Size == 64 && VT->getNumElements() == 1))
1316 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1319 return getIndirectReturnResult(RetTy, State);
1322 return ABIArgInfo::getDirect();
1325 if (isAggregateTypeForABI(RetTy)) {
1326 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
1327 // Structures with flexible arrays are always indirect.
1328 if (RT->getDecl()->hasFlexibleArrayMember())
1329 return getIndirectReturnResult(RetTy, State);
1332 // If specified, structs and unions are always indirect.
1333 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
1334 return getIndirectReturnResult(RetTy, State);
1336 // Ignore empty structs/unions.
1337 if (isEmptyRecord(getContext(), RetTy, true))
1338 return ABIArgInfo::getIgnore();
1340 // Small structures which are register sized are generally returned
1342 if (shouldReturnTypeInRegister(RetTy, getContext())) {
1343 uint64_t Size = getContext().getTypeSize(RetTy);
1345 // As a special-case, if the struct is a "single-element" struct, and
1346 // the field is of type "float" or "double", return it in a
1347 // floating-point register. (MSVC does not apply this special case.)
1348 // We apply a similar transformation for pointer types to improve the
1349 // quality of the generated IR.
1350 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
1351 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
1352 || SeltTy->hasPointerRepresentation())
1353 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1355 // FIXME: We should be able to narrow this integer in cases with dead
1357 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
1360 return getIndirectReturnResult(RetTy, State);
1363 // Treat an enum type as its underlying type.
1364 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1365 RetTy = EnumTy->getDecl()->getIntegerType();
1367 return (RetTy->isPromotableIntegerType() ?
1368 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1371 static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1372 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1375 static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1376 const RecordType *RT = Ty->getAs<RecordType>();
1379 const RecordDecl *RD = RT->getDecl();
1381 // If this is a C++ record, check the bases first.
1382 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1383 for (const auto &I : CXXRD->bases())
1384 if (!isRecordWithSSEVectorType(Context, I.getType()))
1387 for (const auto *i : RD->fields()) {
1388 QualType FT = i->getType();
1390 if (isSSEVectorType(Context, FT))
1393 if (isRecordWithSSEVectorType(Context, FT))
1400 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1401 unsigned Align) const {
1402 // Otherwise, if the alignment is less than or equal to the minimum ABI
1403 // alignment, just use the default; the backend will handle this.
1404 if (Align <= MinABIStackAlignInBytes)
1405 return 0; // Use default alignment.
1407 // On non-Darwin, the stack type alignment is always 4.
1408 if (!IsDarwinVectorABI) {
1409 // Set explicit alignment, since we may need to realign the top.
1410 return MinABIStackAlignInBytes;
1413 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
1414 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1415 isRecordWithSSEVectorType(getContext(), Ty)))
1418 return MinABIStackAlignInBytes;
1421 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
1422 CCState &State) const {
1424 if (State.FreeRegs) {
1425 --State.FreeRegs; // Non-byval indirects just use one pointer.
1427 return getNaturalAlignIndirectInReg(Ty);
1429 return getNaturalAlignIndirect(Ty, false);
1432 // Compute the byval alignment.
1433 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1434 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1435 if (StackAlign == 0)
1436 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
1438 // If the stack alignment is less than the type alignment, realign the
1440 bool Realign = TypeAlign > StackAlign;
1441 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1442 /*ByVal=*/true, Realign);
1445 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1446 const Type *T = isSingleElementStruct(Ty, getContext());
1448 T = Ty.getTypePtr();
1450 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1451 BuiltinType::Kind K = BT->getKind();
1452 if (K == BuiltinType::Float || K == BuiltinType::Double)
1458 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
1459 if (!IsSoftFloatABI) {
1460 Class C = classify(Ty);
1465 unsigned Size = getContext().getTypeSize(Ty);
1466 unsigned SizeInRegs = (Size + 31) / 32;
1468 if (SizeInRegs == 0)
1472 if (SizeInRegs > State.FreeRegs) {
1477 // The MCU psABI allows passing parameters in-reg even if there are
1478 // earlier parameters that are passed on the stack. Also,
1479 // it does not allow passing >8-byte structs in-register,
1480 // even if there are 3 free registers available.
1481 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1485 State.FreeRegs -= SizeInRegs;
1489 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1491 bool &NeedsPadding) const {
1492 // On Windows, aggregates other than HFAs are never passed in registers, and
1493 // they do not consume register slots. Homogenous floating-point aggregates
1494 // (HFAs) have already been dealt with at this point.
1495 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1498 NeedsPadding = false;
1501 if (!updateFreeRegs(Ty, State))
1507 if (State.CC == llvm::CallingConv::X86_FastCall ||
1508 State.CC == llvm::CallingConv::X86_VectorCall ||
1509 State.CC == llvm::CallingConv::X86_RegCall) {
1510 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
1511 NeedsPadding = true;
1519 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1520 if (!updateFreeRegs(Ty, State))
1526 if (State.CC == llvm::CallingConv::X86_FastCall ||
1527 State.CC == llvm::CallingConv::X86_VectorCall ||
1528 State.CC == llvm::CallingConv::X86_RegCall) {
1529 if (getContext().getTypeSize(Ty) > 32)
1532 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1533 Ty->isReferenceType());
1540 X86_32ABIInfo::reclassifyHvaArgType(QualType Ty, CCState &State,
1541 const ABIArgInfo ¤t) const {
1542 // Assumes vectorCall calling convention.
1543 const Type *Base = nullptr;
1544 uint64_t NumElts = 0;
1546 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
1547 isHomogeneousAggregate(Ty, Base, NumElts)) {
1548 if (State.FreeSSERegs >= NumElts) {
1549 // HVA types get passed directly in registers if there is room.
1550 State.FreeSSERegs -= NumElts;
1551 return getDirectX86Hva();
1553 // If there's no room, the HVA gets passed as normal indirect
1555 return getIndirectResult(Ty, /*ByVal=*/false, State);
1560 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1561 CCState &State) const {
1562 // FIXME: Set alignment on indirect arguments.
1564 Ty = useFirstFieldIfTransparentUnion(Ty);
1566 // Check with the C++ ABI first.
1567 const RecordType *RT = Ty->getAs<RecordType>();
1569 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1570 if (RAA == CGCXXABI::RAA_Indirect) {
1571 return getIndirectResult(Ty, false, State);
1572 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1573 // The field index doesn't matter, we'll fix it up later.
1574 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1578 // vectorcall adds the concept of a homogenous vector aggregate, similar
1579 // to other targets, regcall uses some of the HVA rules.
1580 const Type *Base = nullptr;
1581 uint64_t NumElts = 0;
1582 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1583 State.CC == llvm::CallingConv::X86_RegCall) &&
1584 isHomogeneousAggregate(Ty, Base, NumElts)) {
1586 if (State.CC == llvm::CallingConv::X86_RegCall) {
1587 if (State.FreeSSERegs >= NumElts) {
1588 State.FreeSSERegs -= NumElts;
1589 if (Ty->isBuiltinType() || Ty->isVectorType())
1590 return ABIArgInfo::getDirect();
1591 return ABIArgInfo::getExpand();
1594 return getIndirectResult(Ty, /*ByVal=*/false, State);
1595 } else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1596 if (State.FreeSSERegs >= NumElts && (Ty->isBuiltinType() || Ty->isVectorType())) {
1597 // Actual floating-point types get registers first time through if
1598 // there is registers available
1599 State.FreeSSERegs -= NumElts;
1600 return ABIArgInfo::getDirect();
1601 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
1602 // HVA Types only get registers after everything else has been
1603 // set, so it gets set as indirect for now.
1604 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty));
1609 if (isAggregateTypeForABI(Ty)) {
1610 // Structures with flexible arrays are always indirect.
1611 // FIXME: This should not be byval!
1612 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1613 return getIndirectResult(Ty, true, State);
1615 // Ignore empty structs/unions on non-Windows.
1616 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
1617 return ABIArgInfo::getIgnore();
1619 llvm::LLVMContext &LLVMContext = getVMContext();
1620 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1621 bool NeedsPadding = false;
1623 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
1624 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
1625 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
1626 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1628 return ABIArgInfo::getDirectInReg(Result);
1630 return ABIArgInfo::getDirect(Result);
1632 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
1634 // Expand small (<= 128-bit) record types when we know that the stack layout
1635 // of those arguments will match the struct. This is important because the
1636 // LLVM backend isn't smart enough to remove byval, which inhibits many
1638 // Don't do this for the MCU if there are still free integer registers
1639 // (see X86_64 ABI for full explanation).
1640 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1641 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
1642 return ABIArgInfo::getExpandWithPadding(
1643 State.CC == llvm::CallingConv::X86_FastCall ||
1644 State.CC == llvm::CallingConv::X86_VectorCall ||
1645 State.CC == llvm::CallingConv::X86_RegCall,
1648 return getIndirectResult(Ty, true, State);
1651 if (const VectorType *VT = Ty->getAs<VectorType>()) {
1652 // On Darwin, some vectors are passed in memory, we handle this by passing
1653 // it as an i8/i16/i32/i64.
1654 if (IsDarwinVectorABI) {
1655 uint64_t Size = getContext().getTypeSize(Ty);
1656 if ((Size == 8 || Size == 16 || Size == 32) ||
1657 (Size == 64 && VT->getNumElements() == 1))
1658 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1662 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1663 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
1665 return ABIArgInfo::getDirect();
1669 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1670 Ty = EnumTy->getDecl()->getIntegerType();
1672 bool InReg = shouldPrimitiveUseInReg(Ty, State);
1674 if (Ty->isPromotableIntegerType()) {
1676 return ABIArgInfo::getExtendInReg();
1677 return ABIArgInfo::getExtend();
1681 return ABIArgInfo::getDirectInReg();
1682 return ABIArgInfo::getDirect();
1685 void X86_32ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1686 bool &UsedInAlloca) const {
1687 // Vectorcall only allows the first 6 parameters to be passed in registers,
1688 // and homogeneous vector aggregates are only put into registers as a second
1691 CCState ZeroState = State;
1692 ZeroState.FreeRegs = ZeroState.FreeSSERegs = 0;
1693 // HVAs must be done as a second priority for registers, so the deferred
1694 // items are dealt with by going through the pattern a second time.
1695 for (auto &I : FI.arguments()) {
1696 if (Count < VectorcallMaxParamNumAsReg)
1697 I.info = classifyArgumentType(I.type, State);
1699 // Parameters after the 6th cannot be passed in registers,
1700 // so pretend there are no registers left for them.
1701 I.info = classifyArgumentType(I.type, ZeroState);
1702 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1706 // Go through the arguments a second time to get HVAs registers if there
1707 // are still some available.
1708 for (auto &I : FI.arguments()) {
1709 if (Count < VectorcallMaxParamNumAsReg)
1710 I.info = reclassifyHvaArgType(I.type, State, I.info);
1715 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
1716 CCState State(FI.getCallingConvention());
1719 else if (State.CC == llvm::CallingConv::X86_FastCall)
1721 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1723 State.FreeSSERegs = 6;
1724 } else if (FI.getHasRegParm())
1725 State.FreeRegs = FI.getRegParm();
1726 else if (State.CC == llvm::CallingConv::X86_RegCall) {
1728 State.FreeSSERegs = 8;
1730 State.FreeRegs = DefaultNumRegisterParameters;
1732 if (!getCXXABI().classifyReturnType(FI)) {
1733 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
1734 } else if (FI.getReturnInfo().isIndirect()) {
1735 // The C++ ABI is not aware of register usage, so we have to check if the
1736 // return value was sret and put it in a register ourselves if appropriate.
1737 if (State.FreeRegs) {
1738 --State.FreeRegs; // The sret parameter consumes a register.
1740 FI.getReturnInfo().setInReg(true);
1744 // The chain argument effectively gives us another free register.
1745 if (FI.isChainCall())
1748 bool UsedInAlloca = false;
1749 if (State.CC == llvm::CallingConv::X86_VectorCall) {
1750 computeVectorCallArgs(FI, State, UsedInAlloca);
1752 // If not vectorcall, revert to normal behavior.
1753 for (auto &I : FI.arguments()) {
1754 I.info = classifyArgumentType(I.type, State);
1755 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1759 // If we needed to use inalloca for any argument, do a second pass and rewrite
1760 // all the memory arguments to use inalloca.
1762 rewriteWithInAlloca(FI);
1766 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1767 CharUnits &StackOffset, ABIArgInfo &Info,
1768 QualType Type) const {
1769 // Arguments are always 4-byte-aligned.
1770 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1772 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
1773 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1774 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
1775 StackOffset += getContext().getTypeSizeInChars(Type);
1777 // Insert padding bytes to respect alignment.
1778 CharUnits FieldEnd = StackOffset;
1779 StackOffset = FieldEnd.alignTo(FieldAlign);
1780 if (StackOffset != FieldEnd) {
1781 CharUnits NumBytes = StackOffset - FieldEnd;
1782 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1783 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
1784 FrameFields.push_back(Ty);
1788 static bool isArgInAlloca(const ABIArgInfo &Info) {
1789 // Leave ignored and inreg arguments alone.
1790 switch (Info.getKind()) {
1791 case ABIArgInfo::InAlloca:
1793 case ABIArgInfo::Indirect:
1794 assert(Info.getIndirectByVal());
1796 case ABIArgInfo::Ignore:
1798 case ABIArgInfo::Direct:
1799 case ABIArgInfo::Extend:
1800 if (Info.getInReg())
1803 case ABIArgInfo::Expand:
1804 case ABIArgInfo::CoerceAndExpand:
1805 // These are aggregate types which are never passed in registers when
1806 // inalloca is involved.
1809 llvm_unreachable("invalid enum");
1812 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1813 assert(IsWin32StructABI && "inalloca only supported on win32");
1815 // Build a packed struct type for all of the arguments in memory.
1816 SmallVector<llvm::Type *, 6> FrameFields;
1818 // The stack alignment is always 4.
1819 CharUnits StackAlign = CharUnits::fromQuantity(4);
1821 CharUnits StackOffset;
1822 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1824 // Put 'this' into the struct before 'sret', if necessary.
1826 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1827 ABIArgInfo &Ret = FI.getReturnInfo();
1828 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1829 isArgInAlloca(I->info)) {
1830 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1834 // Put the sret parameter into the inalloca struct if it's in memory.
1835 if (Ret.isIndirect() && !Ret.getInReg()) {
1836 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1837 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
1838 // On Windows, the hidden sret parameter is always returned in eax.
1839 Ret.setInAllocaSRet(IsWin32StructABI);
1842 // Skip the 'this' parameter in ecx.
1846 // Put arguments passed in memory into the struct.
1847 for (; I != E; ++I) {
1848 if (isArgInAlloca(I->info))
1849 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1852 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1857 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1858 Address VAListAddr, QualType Ty) const {
1860 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
1862 // x86-32 changes the alignment of certain arguments on the stack.
1864 // Just messing with TypeInfo like this works because we never pass
1865 // anything indirectly.
1866 TypeInfo.second = CharUnits::fromQuantity(
1867 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
1869 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1870 TypeInfo, CharUnits::fromQuantity(4),
1871 /*AllowHigherAlign*/ true);
1874 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1875 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1876 assert(Triple.getArch() == llvm::Triple::x86);
1878 switch (Opts.getStructReturnConvention()) {
1879 case CodeGenOptions::SRCK_Default:
1881 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1883 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1887 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
1890 switch (Triple.getOS()) {
1891 case llvm::Triple::DragonFly:
1892 case llvm::Triple::FreeBSD:
1893 case llvm::Triple::OpenBSD:
1894 case llvm::Triple::Bitrig:
1895 case llvm::Triple::Win32:
1902 void X86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
1903 llvm::GlobalValue *GV,
1904 CodeGen::CodeGenModule &CGM) const {
1905 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
1906 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1907 // Get the LLVM function.
1908 llvm::Function *Fn = cast<llvm::Function>(GV);
1910 // Now add the 'alignstack' attribute with a value of 16.
1911 llvm::AttrBuilder B;
1912 B.addStackAlignmentAttr(16);
1913 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
1915 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1916 llvm::Function *Fn = cast<llvm::Function>(GV);
1917 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1922 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1923 CodeGen::CodeGenFunction &CGF,
1924 llvm::Value *Address) const {
1925 CodeGen::CGBuilderTy &Builder = CGF.Builder;
1927 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
1929 // 0-7 are the eight integer registers; the order is different
1930 // on Darwin (for EH), but the range is the same.
1932 AssignToArrayRange(Builder, Address, Four8, 0, 8);
1934 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
1935 // 12-16 are st(0..4). Not sure why we stop at 4.
1936 // These have size 16, which is sizeof(long double) on
1937 // platforms with 8-byte alignment for that type.
1938 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
1939 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
1942 // 9 is %eflags, which doesn't get a size on Darwin for some
1944 Builder.CreateAlignedStore(
1945 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1948 // 11-16 are st(0..5). Not sure why we stop at 5.
1949 // These have size 12, which is sizeof(long double) on
1950 // platforms with 4-byte alignment for that type.
1951 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
1952 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1958 //===----------------------------------------------------------------------===//
1959 // X86-64 ABI Implementation
1960 //===----------------------------------------------------------------------===//
1964 /// The AVX ABI level for X86 targets.
1965 enum class X86AVXABILevel {
1971 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1972 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1974 case X86AVXABILevel::AVX512:
1976 case X86AVXABILevel::AVX:
1978 case X86AVXABILevel::None:
1981 llvm_unreachable("Unknown AVXLevel");
1984 /// X86_64ABIInfo - The X86_64 ABI information.
1985 class X86_64ABIInfo : public SwiftABIInfo {
1997 /// merge - Implement the X86_64 ABI merging algorithm.
1999 /// Merge an accumulating classification \arg Accum with a field
2000 /// classification \arg Field.
2002 /// \param Accum - The accumulating classification. This should
2003 /// always be either NoClass or the result of a previous merge
2004 /// call. In addition, this should never be Memory (the caller
2005 /// should just return Memory for the aggregate).
2006 static Class merge(Class Accum, Class Field);
2008 /// postMerge - Implement the X86_64 ABI post merging algorithm.
2010 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2011 /// final MEMORY or SSE classes when necessary.
2013 /// \param AggregateSize - The size of the current aggregate in
2014 /// the classification process.
2016 /// \param Lo - The classification for the parts of the type
2017 /// residing in the low word of the containing object.
2019 /// \param Hi - The classification for the parts of the type
2020 /// residing in the higher words of the containing object.
2022 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2024 /// classify - Determine the x86_64 register classes in which the
2025 /// given type T should be passed.
2027 /// \param Lo - The classification for the parts of the type
2028 /// residing in the low word of the containing object.
2030 /// \param Hi - The classification for the parts of the type
2031 /// residing in the high word of the containing object.
2033 /// \param OffsetBase - The bit offset of this type in the
2034 /// containing object. Some parameters are classified different
2035 /// depending on whether they straddle an eightbyte boundary.
2037 /// \param isNamedArg - Whether the argument in question is a "named"
2038 /// argument, as used in AMD64-ABI 3.5.7.
2040 /// If a word is unused its result will be NoClass; if a type should
2041 /// be passed in Memory then at least the classification of \arg Lo
2044 /// The \arg Lo class will be NoClass iff the argument is ignored.
2046 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2047 /// also be ComplexX87.
2048 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2049 bool isNamedArg) const;
2051 llvm::Type *GetByteVectorType(QualType Ty) const;
2052 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2053 unsigned IROffset, QualType SourceTy,
2054 unsigned SourceOffset) const;
2055 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2056 unsigned IROffset, QualType SourceTy,
2057 unsigned SourceOffset) const;
2059 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2060 /// such that the argument will be returned in memory.
2061 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
2063 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2064 /// such that the argument will be passed in memory.
2066 /// \param freeIntRegs - The number of free integer registers remaining
2068 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
2070 ABIArgInfo classifyReturnType(QualType RetTy) const;
2072 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2073 unsigned &neededInt, unsigned &neededSSE,
2074 bool isNamedArg) const;
2076 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2077 unsigned &NeededSSE) const;
2079 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2080 unsigned &NeededSSE) const;
2082 bool IsIllegalVectorType(QualType Ty) const;
2084 /// The 0.98 ABI revision clarified a lot of ambiguities,
2085 /// unfortunately in ways that were not always consistent with
2086 /// certain previous compilers. In particular, platforms which
2087 /// required strict binary compatibility with older versions of GCC
2088 /// may need to exempt themselves.
2089 bool honorsRevision0_98() const {
2090 return !getTarget().getTriple().isOSDarwin();
2093 /// GCC classifies <1 x long long> as SSE but compatibility with older clang
2094 // compilers require us to classify it as INTEGER.
2095 bool classifyIntegerMMXAsSSE() const {
2096 const llvm::Triple &Triple = getTarget().getTriple();
2097 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2099 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2104 X86AVXABILevel AVXLevel;
2105 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2107 bool Has64BitPointers;
2110 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
2111 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2112 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
2115 bool isPassedUsingAVXType(QualType type) const {
2116 unsigned neededInt, neededSSE;
2117 // The freeIntRegs argument doesn't matter here.
2118 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2119 /*isNamedArg*/true);
2120 if (info.isDirect()) {
2121 llvm::Type *ty = info.getCoerceToType();
2122 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2123 return (vectorTy->getBitWidth() > 128);
2128 void computeInfo(CGFunctionInfo &FI) const override;
2130 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2131 QualType Ty) const override;
2132 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2133 QualType Ty) const override;
2135 bool has64BitPointers() const {
2136 return Has64BitPointers;
2139 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
2140 ArrayRef<llvm::Type*> scalars,
2141 bool asReturnValue) const override {
2142 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2144 bool isSwiftErrorInRegister() const override {
2149 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
2150 class WinX86_64ABIInfo : public SwiftABIInfo {
2152 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
2153 : SwiftABIInfo(CGT),
2154 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
2156 void computeInfo(CGFunctionInfo &FI) const override;
2158 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2159 QualType Ty) const override;
2161 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2162 // FIXME: Assumes vectorcall is in use.
2163 return isX86VectorTypeForVectorCall(getContext(), Ty);
2166 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2167 uint64_t NumMembers) const override {
2168 // FIXME: Assumes vectorcall is in use.
2169 return isX86VectorCallAggregateSmallEnough(NumMembers);
2172 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
2173 ArrayRef<llvm::Type *> scalars,
2174 bool asReturnValue) const override {
2175 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2178 bool isSwiftErrorInRegister() const override {
2183 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2184 bool IsVectorCall, bool IsRegCall) const;
2185 ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
2186 const ABIArgInfo ¤t) const;
2187 void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs,
2188 bool IsVectorCall, bool IsRegCall) const;
2193 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2195 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2196 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
2198 const X86_64ABIInfo &getABIInfo() const {
2199 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2202 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2206 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2207 llvm::Value *Address) const override {
2208 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2210 // 0-15 are the 16 integer registers.
2212 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2216 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
2217 StringRef Constraint,
2218 llvm::Type* Ty) const override {
2219 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2222 bool isNoProtoCallVariadic(const CallArgList &args,
2223 const FunctionNoProtoType *fnType) const override {
2224 // The default CC on x86-64 sets %al to the number of SSA
2225 // registers used, and GCC sets this when calling an unprototyped
2226 // function, so we override the default behavior. However, don't do
2227 // that when AVX types are involved: the ABI explicitly states it is
2228 // undefined, and it doesn't work in practice because of how the ABI
2229 // defines varargs anyway.
2230 if (fnType->getCallConv() == CC_C) {
2231 bool HasAVXType = false;
2232 for (CallArgList::const_iterator
2233 it = args.begin(), ie = args.end(); it != ie; ++it) {
2234 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2244 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
2248 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
2250 if (getABIInfo().has64BitPointers())
2251 Sig = (0xeb << 0) | // jmp rel8
2252 (0x0a << 8) | // .+0x0c
2256 Sig = (0xeb << 0) | // jmp rel8
2257 (0x06 << 8) | // .+0x08
2260 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2263 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2264 CodeGen::CodeGenModule &CGM) const override {
2265 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2266 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2267 llvm::Function *Fn = cast<llvm::Function>(GV);
2268 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2274 class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
2276 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2277 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
2279 void getDependentLibraryOption(llvm::StringRef Lib,
2280 llvm::SmallString<24> &Opt) const override {
2282 // If the argument contains a space, enclose it in quotes.
2283 if (Lib.find(" ") != StringRef::npos)
2284 Opt += "\"" + Lib.str() + "\"";
2290 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
2291 // If the argument does not end in .lib, automatically add the suffix.
2292 // If the argument contains a space, enclose it in quotes.
2293 // This matches the behavior of MSVC.
2294 bool Quote = (Lib.find(" ") != StringRef::npos);
2295 std::string ArgStr = Quote ? "\"" : "";
2297 if (!Lib.endswith_lower(".lib"))
2299 ArgStr += Quote ? "\"" : "";
2303 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2305 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2306 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2307 unsigned NumRegisterParameters)
2308 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
2309 Win32StructABI, NumRegisterParameters, false) {}
2311 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2312 CodeGen::CodeGenModule &CGM) const override;
2314 void getDependentLibraryOption(llvm::StringRef Lib,
2315 llvm::SmallString<24> &Opt) const override {
2316 Opt = "/DEFAULTLIB:";
2317 Opt += qualifyWindowsLibrary(Lib);
2320 void getDetectMismatchOption(llvm::StringRef Name,
2321 llvm::StringRef Value,
2322 llvm::SmallString<32> &Opt) const override {
2323 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2327 static void addStackProbeSizeTargetAttribute(const Decl *D,
2328 llvm::GlobalValue *GV,
2329 CodeGen::CodeGenModule &CGM) {
2330 if (D && isa<FunctionDecl>(D)) {
2331 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
2332 llvm::Function *Fn = cast<llvm::Function>(GV);
2334 Fn->addFnAttr("stack-probe-size",
2335 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
2340 void WinX86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
2341 llvm::GlobalValue *GV,
2342 CodeGen::CodeGenModule &CGM) const {
2343 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2345 addStackProbeSizeTargetAttribute(D, GV, CGM);
2348 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2350 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2351 X86AVXABILevel AVXLevel)
2352 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
2354 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2355 CodeGen::CodeGenModule &CGM) const override;
2357 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2361 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2362 llvm::Value *Address) const override {
2363 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2365 // 0-15 are the 16 integer registers.
2367 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2371 void getDependentLibraryOption(llvm::StringRef Lib,
2372 llvm::SmallString<24> &Opt) const override {
2373 Opt = "/DEFAULTLIB:";
2374 Opt += qualifyWindowsLibrary(Lib);
2377 void getDetectMismatchOption(llvm::StringRef Name,
2378 llvm::StringRef Value,
2379 llvm::SmallString<32> &Opt) const override {
2380 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2384 void WinX86_64TargetCodeGenInfo::setTargetAttributes(const Decl *D,
2385 llvm::GlobalValue *GV,
2386 CodeGen::CodeGenModule &CGM) const {
2387 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2389 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2390 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2391 llvm::Function *Fn = cast<llvm::Function>(GV);
2392 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2396 addStackProbeSizeTargetAttribute(D, GV, CGM);
2400 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2402 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2404 // (a) If one of the classes is Memory, the whole argument is passed in
2407 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2410 // (c) If the size of the aggregate exceeds two eightbytes and the first
2411 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2412 // argument is passed in memory. NOTE: This is necessary to keep the
2413 // ABI working for processors that don't support the __m256 type.
2415 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2417 // Some of these are enforced by the merging logic. Others can arise
2418 // only with unions; for example:
2419 // union { _Complex double; unsigned; }
2421 // Note that clauses (b) and (c) were added in 0.98.
2425 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2427 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2429 if (Hi == SSEUp && Lo != SSE)
2433 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
2434 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2435 // classified recursively so that always two fields are
2436 // considered. The resulting class is calculated according to
2437 // the classes of the fields in the eightbyte:
2439 // (a) If both classes are equal, this is the resulting class.
2441 // (b) If one of the classes is NO_CLASS, the resulting class is
2444 // (c) If one of the classes is MEMORY, the result is the MEMORY
2447 // (d) If one of the classes is INTEGER, the result is the
2450 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2451 // MEMORY is used as class.
2453 // (f) Otherwise class SSE is used.
2455 // Accum should never be memory (we should have returned) or
2456 // ComplexX87 (because this cannot be passed in a structure).
2457 assert((Accum != Memory && Accum != ComplexX87) &&
2458 "Invalid accumulated classification during merge.");
2459 if (Accum == Field || Field == NoClass)
2461 if (Field == Memory)
2463 if (Accum == NoClass)
2465 if (Accum == Integer || Field == Integer)
2467 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2468 Accum == X87 || Accum == X87Up)
2473 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
2474 Class &Lo, Class &Hi, bool isNamedArg) const {
2475 // FIXME: This code can be simplified by introducing a simple value class for
2476 // Class pairs with appropriate constructor methods for the various
2479 // FIXME: Some of the split computations are wrong; unaligned vectors
2480 // shouldn't be passed in registers for example, so there is no chance they
2481 // can straddle an eightbyte. Verify & simplify.
2485 Class &Current = OffsetBase < 64 ? Lo : Hi;
2488 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
2489 BuiltinType::Kind k = BT->getKind();
2491 if (k == BuiltinType::Void) {
2493 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2496 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2498 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
2500 } else if (k == BuiltinType::LongDouble) {
2501 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2502 if (LDF == &llvm::APFloat::IEEEquad()) {
2505 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
2508 } else if (LDF == &llvm::APFloat::IEEEdouble()) {
2511 llvm_unreachable("unexpected long double representation!");
2513 // FIXME: _Decimal32 and _Decimal64 are SSE.
2514 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
2518 if (const EnumType *ET = Ty->getAs<EnumType>()) {
2519 // Classify the underlying integer type.
2520 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
2524 if (Ty->hasPointerRepresentation()) {
2529 if (Ty->isMemberPointerType()) {
2530 if (Ty->isMemberFunctionPointerType()) {
2531 if (Has64BitPointers) {
2532 // If Has64BitPointers, this is an {i64, i64}, so classify both
2536 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2537 // straddles an eightbyte boundary, Hi should be classified as well.
2538 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2539 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2540 if (EB_FuncPtr != EB_ThisAdj) {
2552 if (const VectorType *VT = Ty->getAs<VectorType>()) {
2553 uint64_t Size = getContext().getTypeSize(VT);
2554 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2555 // gcc passes the following as integer:
2556 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2557 // 2 bytes - <2 x char>, <1 x short>
2558 // 1 byte - <1 x char>
2561 // If this type crosses an eightbyte boundary, it should be
2563 uint64_t EB_Lo = (OffsetBase) / 64;
2564 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2567 } else if (Size == 64) {
2568 QualType ElementType = VT->getElementType();
2570 // gcc passes <1 x double> in memory. :(
2571 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
2574 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2575 // pass them as integer. For platforms where clang is the de facto
2576 // platform compiler, we must continue to use integer.
2577 if (!classifyIntegerMMXAsSSE() &&
2578 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2579 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2580 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2581 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
2586 // If this type crosses an eightbyte boundary, it should be
2588 if (OffsetBase && OffsetBase != 64)
2590 } else if (Size == 128 ||
2591 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
2592 // Arguments of 256-bits are split into four eightbyte chunks. The
2593 // least significant one belongs to class SSE and all the others to class
2594 // SSEUP. The original Lo and Hi design considers that types can't be
2595 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2596 // This design isn't correct for 256-bits, but since there're no cases
2597 // where the upper parts would need to be inspected, avoid adding
2598 // complexity and just consider Hi to match the 64-256 part.
2600 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2601 // registers if they are "named", i.e. not part of the "..." of a
2602 // variadic function.
2604 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2605 // split into eight eightbyte chunks, one SSE and seven SSEUP.
2612 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
2613 QualType ET = getContext().getCanonicalType(CT->getElementType());
2615 uint64_t Size = getContext().getTypeSize(Ty);
2616 if (ET->isIntegralOrEnumerationType()) {
2619 else if (Size <= 128)
2621 } else if (ET == getContext().FloatTy) {
2623 } else if (ET == getContext().DoubleTy) {
2625 } else if (ET == getContext().LongDoubleTy) {
2626 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2627 if (LDF == &llvm::APFloat::IEEEquad())
2629 else if (LDF == &llvm::APFloat::x87DoubleExtended())
2630 Current = ComplexX87;
2631 else if (LDF == &llvm::APFloat::IEEEdouble())
2634 llvm_unreachable("unexpected long double representation!");
2637 // If this complex type crosses an eightbyte boundary then it
2639 uint64_t EB_Real = (OffsetBase) / 64;
2640 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
2641 if (Hi == NoClass && EB_Real != EB_Imag)
2647 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2648 // Arrays are treated like structures.
2650 uint64_t Size = getContext().getTypeSize(Ty);
2652 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2653 // than eight eightbytes, ..., it has class MEMORY.
2657 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2658 // fields, it has class MEMORY.
2660 // Only need to check alignment of array base.
2661 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
2664 // Otherwise implement simplified merge. We could be smarter about
2665 // this, but it isn't worth it and would be harder to verify.
2667 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
2668 uint64_t ArraySize = AT->getSize().getZExtValue();
2670 // The only case a 256-bit wide vector could be used is when the array
2671 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2672 // to work for sizes wider than 128, early check and fallback to memory.
2675 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
2678 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2679 Class FieldLo, FieldHi;
2680 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
2681 Lo = merge(Lo, FieldLo);
2682 Hi = merge(Hi, FieldHi);
2683 if (Lo == Memory || Hi == Memory)
2687 postMerge(Size, Lo, Hi);
2688 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
2692 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2693 uint64_t Size = getContext().getTypeSize(Ty);
2695 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2696 // than eight eightbytes, ..., it has class MEMORY.
2700 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2701 // copy constructor or a non-trivial destructor, it is passed by invisible
2703 if (getRecordArgABI(RT, getCXXABI()))
2706 const RecordDecl *RD = RT->getDecl();
2708 // Assume variable sized types are passed in memory.
2709 if (RD->hasFlexibleArrayMember())
2712 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2714 // Reset Lo class, this will be recomputed.
2717 // If this is a C++ record, classify the bases first.
2718 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
2719 for (const auto &I : CXXRD->bases()) {
2720 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
2721 "Unexpected base class!");
2722 const CXXRecordDecl *Base =
2723 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
2725 // Classify this field.
2727 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2728 // single eightbyte, each is classified separately. Each eightbyte gets
2729 // initialized to class NO_CLASS.
2730 Class FieldLo, FieldHi;
2732 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
2733 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
2734 Lo = merge(Lo, FieldLo);
2735 Hi = merge(Hi, FieldHi);
2736 if (Lo == Memory || Hi == Memory) {
2737 postMerge(Size, Lo, Hi);
2743 // Classify the fields one at a time, merging the results.
2745 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2746 i != e; ++i, ++idx) {
2747 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2748 bool BitField = i->isBitField();
2750 // Ignore padding bit-fields.
2751 if (BitField && i->isUnnamedBitfield())
2754 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2755 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
2757 // The only case a 256-bit wide vector could be used is when the struct
2758 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2759 // to work for sizes wider than 128, early check and fallback to memory.
2761 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2762 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
2764 postMerge(Size, Lo, Hi);
2767 // Note, skip this test for bit-fields, see below.
2768 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
2770 postMerge(Size, Lo, Hi);
2774 // Classify this field.
2776 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2777 // exceeds a single eightbyte, each is classified
2778 // separately. Each eightbyte gets initialized to class
2780 Class FieldLo, FieldHi;
2782 // Bit-fields require special handling, they do not force the
2783 // structure to be passed in memory even if unaligned, and
2784 // therefore they can straddle an eightbyte.
2786 assert(!i->isUnnamedBitfield());
2787 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2788 uint64_t Size = i->getBitWidthValue(getContext());
2790 uint64_t EB_Lo = Offset / 64;
2791 uint64_t EB_Hi = (Offset + Size - 1) / 64;
2794 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2799 FieldHi = EB_Hi ? Integer : NoClass;
2802 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
2803 Lo = merge(Lo, FieldLo);
2804 Hi = merge(Hi, FieldHi);
2805 if (Lo == Memory || Hi == Memory)
2809 postMerge(Size, Lo, Hi);
2813 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
2814 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2816 if (!isAggregateTypeForABI(Ty)) {
2817 // Treat an enum type as its underlying type.
2818 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2819 Ty = EnumTy->getDecl()->getIntegerType();
2821 return (Ty->isPromotableIntegerType() ?
2822 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2825 return getNaturalAlignIndirect(Ty);
2828 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2829 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2830 uint64_t Size = getContext().getTypeSize(VecTy);
2831 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
2832 if (Size <= 64 || Size > LargestVector)
2839 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2840 unsigned freeIntRegs) const {
2841 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2844 // This assumption is optimistic, as there could be free registers available
2845 // when we need to pass this argument in memory, and LLVM could try to pass
2846 // the argument in the free register. This does not seem to happen currently,
2847 // but this code would be much safer if we could mark the argument with
2848 // 'onstack'. See PR12193.
2849 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
2850 // Treat an enum type as its underlying type.
2851 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2852 Ty = EnumTy->getDecl()->getIntegerType();
2854 return (Ty->isPromotableIntegerType() ?
2855 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2858 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
2859 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
2861 // Compute the byval alignment. We specify the alignment of the byval in all
2862 // cases so that the mid-level optimizer knows the alignment of the byval.
2863 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
2865 // Attempt to avoid passing indirect results using byval when possible. This
2866 // is important for good codegen.
2868 // We do this by coercing the value into a scalar type which the backend can
2869 // handle naturally (i.e., without using byval).
2871 // For simplicity, we currently only do this when we have exhausted all of the
2872 // free integer registers. Doing this when there are free integer registers
2873 // would require more care, as we would have to ensure that the coerced value
2874 // did not claim the unused register. That would require either reording the
2875 // arguments to the function (so that any subsequent inreg values came first),
2876 // or only doing this optimization when there were no following arguments that
2879 // We currently expect it to be rare (particularly in well written code) for
2880 // arguments to be passed on the stack when there are still free integer
2881 // registers available (this would typically imply large structs being passed
2882 // by value), so this seems like a fair tradeoff for now.
2884 // We can revisit this if the backend grows support for 'onstack' parameter
2885 // attributes. See PR12193.
2886 if (freeIntRegs == 0) {
2887 uint64_t Size = getContext().getTypeSize(Ty);
2889 // If this type fits in an eightbyte, coerce it into the matching integral
2890 // type, which will end up on the stack (with alignment 8).
2891 if (Align == 8 && Size <= 64)
2892 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2896 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
2899 /// The ABI specifies that a value should be passed in a full vector XMM/YMM
2900 /// register. Pick an LLVM IR type that will be passed as a vector register.
2901 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
2902 // Wrapper structs/arrays that only contain vectors are passed just like
2903 // vectors; strip them off if present.
2904 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2905 Ty = QualType(InnerTy, 0);
2907 llvm::Type *IRType = CGT.ConvertType(Ty);
2908 if (isa<llvm::VectorType>(IRType) ||
2909 IRType->getTypeID() == llvm::Type::FP128TyID)
2912 // We couldn't find the preferred IR vector type for 'Ty'.
2913 uint64_t Size = getContext().getTypeSize(Ty);
2914 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
2916 // Return a LLVM IR vector type based on the size of 'Ty'.
2917 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2921 /// BitsContainNoUserData - Return true if the specified [start,end) bit range
2922 /// is known to either be off the end of the specified type or being in
2923 /// alignment padding. The user type specified is known to be at most 128 bits
2924 /// in size, and have passed through X86_64ABIInfo::classify with a successful
2925 /// classification that put one of the two halves in the INTEGER class.
2927 /// It is conservatively correct to return false.
2928 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2929 unsigned EndBit, ASTContext &Context) {
2930 // If the bytes being queried are off the end of the type, there is no user
2931 // data hiding here. This handles analysis of builtins, vectors and other
2932 // types that don't contain interesting padding.
2933 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2934 if (TySize <= StartBit)
2937 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2938 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2939 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2941 // Check each element to see if the element overlaps with the queried range.
2942 for (unsigned i = 0; i != NumElts; ++i) {
2943 // If the element is after the span we care about, then we're done..
2944 unsigned EltOffset = i*EltSize;
2945 if (EltOffset >= EndBit) break;
2947 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2948 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2949 EndBit-EltOffset, Context))
2952 // If it overlaps no elements, then it is safe to process as padding.
2956 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2957 const RecordDecl *RD = RT->getDecl();
2958 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2960 // If this is a C++ record, check the bases first.
2961 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
2962 for (const auto &I : CXXRD->bases()) {
2963 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
2964 "Unexpected base class!");
2965 const CXXRecordDecl *Base =
2966 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
2968 // If the base is after the span we care about, ignore it.
2969 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
2970 if (BaseOffset >= EndBit) continue;
2972 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
2973 if (!BitsContainNoUserData(I.getType(), BaseStart,
2974 EndBit-BaseOffset, Context))
2979 // Verify that no field has data that overlaps the region of interest. Yes
2980 // this could be sped up a lot by being smarter about queried fields,
2981 // however we're only looking at structs up to 16 bytes, so we don't care
2984 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2985 i != e; ++i, ++idx) {
2986 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
2988 // If we found a field after the region we care about, then we're done.
2989 if (FieldOffset >= EndBit) break;
2991 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2992 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2997 // If nothing in this record overlapped the area of interest, then we're
3005 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3006 /// float member at the specified offset. For example, {int,{float}} has a
3007 /// float at offset 4. It is conservatively correct for this routine to return
3009 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
3010 const llvm::DataLayout &TD) {
3011 // Base case if we find a float.
3012 if (IROffset == 0 && IRType->isFloatTy())
3015 // If this is a struct, recurse into the field at the specified offset.
3016 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3017 const llvm::StructLayout *SL = TD.getStructLayout(STy);
3018 unsigned Elt = SL->getElementContainingOffset(IROffset);
3019 IROffset -= SL->getElementOffset(Elt);
3020 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3023 // If this is an array, recurse into the field at the specified offset.
3024 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3025 llvm::Type *EltTy = ATy->getElementType();
3026 unsigned EltSize = TD.getTypeAllocSize(EltTy);
3027 IROffset -= IROffset/EltSize*EltSize;
3028 return ContainsFloatAtOffset(EltTy, IROffset, TD);
3035 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3036 /// low 8 bytes of an XMM register, corresponding to the SSE class.
3037 llvm::Type *X86_64ABIInfo::
3038 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3039 QualType SourceTy, unsigned SourceOffset) const {
3040 // The only three choices we have are either double, <2 x float>, or float. We
3041 // pass as float if the last 4 bytes is just padding. This happens for
3042 // structs that contain 3 floats.
3043 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3044 SourceOffset*8+64, getContext()))
3045 return llvm::Type::getFloatTy(getVMContext());
3047 // We want to pass as <2 x float> if the LLVM IR type contains a float at
3048 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
3050 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3051 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
3052 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
3054 return llvm::Type::getDoubleTy(getVMContext());
3058 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3059 /// an 8-byte GPR. This means that we either have a scalar or we are talking
3060 /// about the high or low part of an up-to-16-byte struct. This routine picks
3061 /// the best LLVM IR type to represent this, which may be i64 or may be anything
3062 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3065 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3066 /// the source type. IROffset is an offset in bytes into the LLVM IR type that
3067 /// the 8-byte value references. PrefType may be null.
3069 /// SourceTy is the source-level type for the entire argument. SourceOffset is
3070 /// an offset into this that we're processing (which is always either 0 or 8).
3072 llvm::Type *X86_64ABIInfo::
3073 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3074 QualType SourceTy, unsigned SourceOffset) const {
3075 // If we're dealing with an un-offset LLVM IR type, then it means that we're
3076 // returning an 8-byte unit starting with it. See if we can safely use it.
3077 if (IROffset == 0) {
3078 // Pointers and int64's always fill the 8-byte unit.
3079 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3080 IRType->isIntegerTy(64))
3083 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3084 // goodness in the source type is just tail padding. This is allowed to
3085 // kick in for struct {double,int} on the int, but not on
3086 // struct{double,int,int} because we wouldn't return the second int. We
3087 // have to do this analysis on the source type because we can't depend on
3088 // unions being lowered a specific way etc.
3089 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
3090 IRType->isIntegerTy(32) ||
3091 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3092 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3093 cast<llvm::IntegerType>(IRType)->getBitWidth();
3095 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3096 SourceOffset*8+64, getContext()))
3101 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3102 // If this is a struct, recurse into the field at the specified offset.
3103 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
3104 if (IROffset < SL->getSizeInBytes()) {
3105 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3106 IROffset -= SL->getElementOffset(FieldIdx);
3108 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3109 SourceTy, SourceOffset);
3113 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3114 llvm::Type *EltTy = ATy->getElementType();
3115 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
3116 unsigned EltOffset = IROffset/EltSize*EltSize;
3117 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3121 // Okay, we don't have any better idea of what to pass, so we pass this in an
3122 // integer register that isn't too big to fit the rest of the struct.
3123 unsigned TySizeInBytes =
3124 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
3126 assert(TySizeInBytes != SourceOffset && "Empty field?");
3128 // It is always safe to classify this as an integer type up to i64 that
3129 // isn't larger than the structure.
3130 return llvm::IntegerType::get(getVMContext(),
3131 std::min(TySizeInBytes-SourceOffset, 8U)*8);
3135 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3136 /// be used as elements of a two register pair to pass or return, return a
3137 /// first class aggregate to represent them. For example, if the low part of
3138 /// a by-value argument should be passed as i32* and the high part as float,
3139 /// return {i32*, float}.
3141 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
3142 const llvm::DataLayout &TD) {
3143 // In order to correctly satisfy the ABI, we need to the high part to start
3144 // at offset 8. If the high and low parts we inferred are both 4-byte types
3145 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3146 // the second element at offset 8. Check for this:
3147 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3148 unsigned HiAlign = TD.getABITypeAlignment(Hi);
3149 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
3150 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
3152 // To handle this, we have to increase the size of the low part so that the
3153 // second element will start at an 8 byte offset. We can't increase the size
3154 // of the second element because it might make us access off the end of the
3157 // There are usually two sorts of types the ABI generation code can produce
3158 // for the low part of a pair that aren't 8 bytes in size: float or
3159 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
3161 // Promote these to a larger type.
3162 if (Lo->isFloatTy())
3163 Lo = llvm::Type::getDoubleTy(Lo->getContext());
3165 assert((Lo->isIntegerTy() || Lo->isPointerTy())
3166 && "Invalid/unknown lo type");
3167 Lo = llvm::Type::getInt64Ty(Lo->getContext());
3171 llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
3173 // Verify that the second element is at an 8-byte offset.
3174 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3175 "Invalid x86-64 argument pair!");
3179 ABIArgInfo X86_64ABIInfo::
3180 classifyReturnType(QualType RetTy) const {
3181 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3182 // classification algorithm.
3183 X86_64ABIInfo::Class Lo, Hi;
3184 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
3186 // Check some invariants.
3187 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3188 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3190 llvm::Type *ResType = nullptr;
3194 return ABIArgInfo::getIgnore();
3195 // If the low part is just padding, it takes no register, leave ResType
3197 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3198 "Unknown missing lo part");
3203 llvm_unreachable("Invalid classification for lo word.");
3205 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3208 return getIndirectReturnResult(RetTy);
3210 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3211 // available register of the sequence %rax, %rdx is used.
3213 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3215 // If we have a sign or zero extended integer, make sure to return Extend
3216 // so that the parameter gets the right LLVM IR attributes.
3217 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3218 // Treat an enum type as its underlying type.
3219 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3220 RetTy = EnumTy->getDecl()->getIntegerType();
3222 if (RetTy->isIntegralOrEnumerationType() &&
3223 RetTy->isPromotableIntegerType())
3224 return ABIArgInfo::getExtend();
3228 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3229 // available SSE register of the sequence %xmm0, %xmm1 is used.
3231 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3234 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3235 // returned on the X87 stack in %st0 as 80-bit x87 number.
3237 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
3240 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3241 // part of the value is returned in %st0 and the imaginary part in
3244 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
3245 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
3246 llvm::Type::getX86_FP80Ty(getVMContext()));
3250 llvm::Type *HighPart = nullptr;
3252 // Memory was handled previously and X87 should
3253 // never occur as a hi class.
3256 llvm_unreachable("Invalid classification for hi word.");
3258 case ComplexX87: // Previously handled.
3263 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3264 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3265 return ABIArgInfo::getDirect(HighPart, 8);
3268 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3269 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3270 return ABIArgInfo::getDirect(HighPart, 8);
3273 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
3274 // is passed in the next available eightbyte chunk if the last used
3277 // SSEUP should always be preceded by SSE, just widen.
3279 assert(Lo == SSE && "Unexpected SSEUp classification.");
3280 ResType = GetByteVectorType(RetTy);
3283 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3284 // returned together with the previous X87 value in %st0.
3286 // If X87Up is preceded by X87, we don't need to do
3287 // anything. However, in some cases with unions it may not be
3288 // preceded by X87. In such situations we follow gcc and pass the
3289 // extra bits in an SSE reg.
3291 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3292 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3293 return ABIArgInfo::getDirect(HighPart, 8);
3298 // If a high part was specified, merge it together with the low part. It is
3299 // known to pass in the high eightbyte of the result. We do this by forming a
3300 // first class struct aggregate with the high and low part: {low, high}
3302 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3304 return ABIArgInfo::getDirect(ResType);
3307 ABIArgInfo X86_64ABIInfo::classifyArgumentType(
3308 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3312 Ty = useFirstFieldIfTransparentUnion(Ty);
3314 X86_64ABIInfo::Class Lo, Hi;
3315 classify(Ty, 0, Lo, Hi, isNamedArg);
3317 // Check some invariants.
3318 // FIXME: Enforce these by construction.
3319 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3320 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3324 llvm::Type *ResType = nullptr;
3328 return ABIArgInfo::getIgnore();
3329 // If the low part is just padding, it takes no register, leave ResType
3331 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3332 "Unknown missing lo part");
3335 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3339 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3340 // COMPLEX_X87, it is passed in memory.
3343 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
3345 return getIndirectResult(Ty, freeIntRegs);
3349 llvm_unreachable("Invalid classification for lo word.");
3351 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3352 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3357 // Pick an 8-byte type based on the preferred type.
3358 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
3360 // If we have a sign or zero extended integer, make sure to return Extend
3361 // so that the parameter gets the right LLVM IR attributes.
3362 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3363 // Treat an enum type as its underlying type.
3364 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3365 Ty = EnumTy->getDecl()->getIntegerType();
3367 if (Ty->isIntegralOrEnumerationType() &&
3368 Ty->isPromotableIntegerType())
3369 return ABIArgInfo::getExtend();
3374 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3375 // available SSE register is used, the registers are taken in the
3376 // order from %xmm0 to %xmm7.
3378 llvm::Type *IRType = CGT.ConvertType(Ty);
3379 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
3385 llvm::Type *HighPart = nullptr;
3387 // Memory was handled previously, ComplexX87 and X87 should
3388 // never occur as hi classes, and X87Up must be preceded by X87,
3389 // which is passed in memory.
3393 llvm_unreachable("Invalid classification for hi word.");
3395 case NoClass: break;
3399 // Pick an 8-byte type based on the preferred type.
3400 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3402 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3403 return ABIArgInfo::getDirect(HighPart, 8);
3406 // X87Up generally doesn't occur here (long double is passed in
3407 // memory), except in situations involving unions.
3410 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3412 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3413 return ABIArgInfo::getDirect(HighPart, 8);
3418 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3419 // eightbyte is passed in the upper half of the last used SSE
3420 // register. This only happens when 128-bit vectors are passed.
3422 assert(Lo == SSE && "Unexpected SSEUp classification");
3423 ResType = GetByteVectorType(Ty);
3427 // If a high part was specified, merge it together with the low part. It is
3428 // known to pass in the high eightbyte of the result. We do this by forming a
3429 // first class struct aggregate with the high and low part: {low, high}
3431 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3433 return ABIArgInfo::getDirect(ResType);
3437 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3438 unsigned &NeededSSE) const {
3439 auto RT = Ty->getAs<RecordType>();
3440 assert(RT && "classifyRegCallStructType only valid with struct types");
3442 if (RT->getDecl()->hasFlexibleArrayMember())
3443 return getIndirectReturnResult(Ty);
3446 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3447 if (CXXRD->isDynamicClass()) {
3448 NeededInt = NeededSSE = 0;
3449 return getIndirectReturnResult(Ty);
3452 for (const auto &I : CXXRD->bases())
3453 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3455 NeededInt = NeededSSE = 0;
3456 return getIndirectReturnResult(Ty);
3461 for (const auto *FD : RT->getDecl()->fields()) {
3462 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3463 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3465 NeededInt = NeededSSE = 0;
3466 return getIndirectReturnResult(Ty);
3469 unsigned LocalNeededInt, LocalNeededSSE;
3470 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3471 LocalNeededSSE, true)
3473 NeededInt = NeededSSE = 0;
3474 return getIndirectReturnResult(Ty);
3476 NeededInt += LocalNeededInt;
3477 NeededSSE += LocalNeededSSE;
3481 return ABIArgInfo::getDirect();
3484 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3485 unsigned &NeededInt,
3486 unsigned &NeededSSE) const {
3491 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3494 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3496 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
3498 // Keep track of the number of assigned registers.
3499 unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3500 unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3501 unsigned NeededInt, NeededSSE;
3503 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3504 !FI.getReturnType()->getTypePtr()->isUnionType()) {
3505 FI.getReturnInfo() =
3506 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3507 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3508 FreeIntRegs -= NeededInt;
3509 FreeSSERegs -= NeededSSE;
3511 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3513 } else if (!getCXXABI().classifyReturnType(FI))
3514 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3516 // If the return value is indirect, then the hidden argument is consuming one
3517 // integer register.
3518 if (FI.getReturnInfo().isIndirect())
3521 // The chain argument effectively gives us another free register.
3522 if (FI.isChainCall())
3525 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
3526 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3527 // get assigned (in left-to-right order) for passing as follows...
3529 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3530 it != ie; ++it, ++ArgNo) {
3531 bool IsNamedArg = ArgNo < NumRequiredArgs;
3533 if (IsRegCall && it->type->isStructureOrClassType())
3534 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3536 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3537 NeededSSE, IsNamedArg);
3539 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3540 // eightbyte of an argument, the whole argument is passed on the
3541 // stack. If registers have already been assigned for some
3542 // eightbytes of such an argument, the assignments get reverted.
3543 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3544 FreeIntRegs -= NeededInt;
3545 FreeSSERegs -= NeededSSE;
3547 it->info = getIndirectResult(it->type, FreeIntRegs);
3552 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3553 Address VAListAddr, QualType Ty) {
3554 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3555 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
3556 llvm::Value *overflow_arg_area =
3557 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3559 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3560 // byte boundary if alignment needed by type exceeds 8 byte boundary.
3561 // It isn't stated explicitly in the standard, but in practice we use
3562 // alignment greater than 16 where necessary.
3563 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3564 if (Align > CharUnits::fromQuantity(8)) {
3565 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3569 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
3570 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
3572 CGF.Builder.CreateBitCast(overflow_arg_area,
3573 llvm::PointerType::getUnqual(LTy));
3575 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3576 // l->overflow_arg_area + sizeof(type).
3577 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3578 // an 8 byte boundary.
3580 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
3581 llvm::Value *Offset =
3582 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
3583 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3584 "overflow_arg_area.next");
3585 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3587 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
3588 return Address(Res, Align);
3591 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3592 QualType Ty) const {
3593 // Assume that va_list type is correct; should be pointer to LLVM type:
3597 // i8* overflow_arg_area;
3598 // i8* reg_save_area;
3600 unsigned neededInt, neededSSE;
3602 Ty = getContext().getCanonicalType(Ty);
3603 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
3604 /*isNamedArg*/false);
3606 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3607 // in the registers. If not go to step 7.
3608 if (!neededInt && !neededSSE)
3609 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
3611 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3612 // general purpose registers needed to pass type and num_fp to hold
3613 // the number of floating point registers needed.
3615 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3616 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3617 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3619 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3620 // register save space).
3622 llvm::Value *InRegs = nullptr;
3623 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3624 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
3627 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3629 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
3630 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3631 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
3636 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3638 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3639 llvm::Value *FitsInFP =
3640 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3641 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
3642 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3645 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3646 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3647 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3648 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3650 // Emit code to load the value if it was passed in registers.
3652 CGF.EmitBlock(InRegBlock);
3654 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3655 // an offset of l->gp_offset and/or l->fp_offset. This may require
3656 // copying to a temporary location in case the parameter is passed
3657 // in different register classes or requires an alignment greater
3658 // than 8 for general purpose registers and 16 for XMM registers.
3660 // FIXME: This really results in shameful code when we end up needing to
3661 // collect arguments from different places; often what should result in a
3662 // simple assembling of a structure from scattered addresses has many more
3663 // loads than necessary. Can we clean this up?
3664 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
3665 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3666 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3669 Address RegAddr = Address::invalid();
3670 if (neededInt && neededSSE) {
3672 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
3673 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
3674 Address Tmp = CGF.CreateMemTemp(Ty);
3675 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3676 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
3677 llvm::Type *TyLo = ST->getElementType(0);
3678 llvm::Type *TyHi = ST->getElementType(1);
3679 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
3680 "Unexpected ABI info for mixed regs");
3681 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3682 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
3683 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3684 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
3685 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3686 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
3688 // Copy the first element.
3689 // FIXME: Our choice of alignment here and below is probably pessimistic.
3690 llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3691 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
3692 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
3693 CGF.Builder.CreateStore(V,
3694 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3696 // Copy the second element.
3697 V = CGF.Builder.CreateAlignedLoad(
3698 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
3699 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
3700 CharUnits Offset = CharUnits::fromQuantity(
3701 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3702 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3704 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
3705 } else if (neededInt) {
3706 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3707 CharUnits::fromQuantity(8));
3708 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
3710 // Copy to a temporary if necessary to ensure the appropriate alignment.
3711 std::pair<CharUnits, CharUnits> SizeAlign =
3712 getContext().getTypeInfoInChars(Ty);
3713 uint64_t TySize = SizeAlign.first.getQuantity();
3714 CharUnits TyAlign = SizeAlign.second;
3716 // Copy into a temporary if the type is more aligned than the
3717 // register save area.
3718 if (TyAlign.getQuantity() > 8) {
3719 Address Tmp = CGF.CreateMemTemp(Ty);
3720 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
3724 } else if (neededSSE == 1) {
3725 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3726 CharUnits::fromQuantity(16));
3727 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
3729 assert(neededSSE == 2 && "Invalid number of needed registers!");
3730 // SSE registers are spaced 16 bytes apart in the register save
3731 // area, we need to collect the two eightbytes together.
3732 // The ABI isn't explicit about this, but it seems reasonable
3733 // to assume that the slots are 16-byte aligned, since the stack is
3734 // naturally 16-byte aligned and the prologue is expected to store
3735 // all the SSE registers to the RSA.
3736 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3737 CharUnits::fromQuantity(16));
3739 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3740 CharUnits::fromQuantity(16));
3741 llvm::Type *DoubleTy = CGF.DoubleTy;
3742 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy);
3744 Address Tmp = CGF.CreateMemTemp(Ty);
3745 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3746 V = CGF.Builder.CreateLoad(
3747 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3748 CGF.Builder.CreateStore(V,
3749 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3750 V = CGF.Builder.CreateLoad(
3751 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3752 CGF.Builder.CreateStore(V,
3753 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3755 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
3758 // AMD64-ABI 3.5.7p5: Step 5. Set:
3759 // l->gp_offset = l->gp_offset + num_gp * 8
3760 // l->fp_offset = l->fp_offset + num_fp * 16.
3762 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
3763 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3767 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
3768 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3771 CGF.EmitBranch(ContBlock);
3773 // Emit code to load the value if it was passed in memory.
3775 CGF.EmitBlock(InMemBlock);
3776 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
3778 // Return the appropriate result.
3780 CGF.EmitBlock(ContBlock);
3781 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3786 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3787 QualType Ty) const {
3788 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3789 CGF.getContext().getTypeInfoInChars(Ty),
3790 CharUnits::fromQuantity(8),
3791 /*allowHigherAlign*/ false);
3795 WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
3796 const ABIArgInfo ¤t) const {
3797 // Assumes vectorCall calling convention.
3798 const Type *Base = nullptr;
3799 uint64_t NumElts = 0;
3801 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
3802 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
3803 FreeSSERegs -= NumElts;
3804 return getDirectX86Hva();
3809 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3810 bool IsReturnType, bool IsVectorCall,
3811 bool IsRegCall) const {
3813 if (Ty->isVoidType())
3814 return ABIArgInfo::getIgnore();
3816 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3817 Ty = EnumTy->getDecl()->getIntegerType();
3819 TypeInfo Info = getContext().getTypeInfo(Ty);
3820 uint64_t Width = Info.Width;
3821 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
3823 const RecordType *RT = Ty->getAs<RecordType>();
3825 if (!IsReturnType) {
3826 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
3827 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
3830 if (RT->getDecl()->hasFlexibleArrayMember())
3831 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
3835 const Type *Base = nullptr;
3836 uint64_t NumElts = 0;
3837 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3839 if ((IsVectorCall || IsRegCall) &&
3840 isHomogeneousAggregate(Ty, Base, NumElts)) {
3842 if (FreeSSERegs >= NumElts) {
3843 FreeSSERegs -= NumElts;
3844 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3845 return ABIArgInfo::getDirect();
3846 return ABIArgInfo::getExpand();
3848 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3849 } else if (IsVectorCall) {
3850 if (FreeSSERegs >= NumElts &&
3851 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
3852 FreeSSERegs -= NumElts;
3853 return ABIArgInfo::getDirect();
3854 } else if (IsReturnType) {
3855 return ABIArgInfo::getExpand();
3856 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
3857 // HVAs are delayed and reclassified in the 2nd step.
3858 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3863 if (Ty->isMemberPointerType()) {
3864 // If the member pointer is represented by an LLVM int or ptr, pass it
3866 llvm::Type *LLTy = CGT.ConvertType(Ty);
3867 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3868 return ABIArgInfo::getDirect();
3871 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
3872 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3873 // not 1, 2, 4, or 8 bytes, must be passed by reference."
3874 if (Width > 64 || !llvm::isPowerOf2_64(Width))
3875 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
3877 // Otherwise, coerce it to a small integer.
3878 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
3881 // Bool type is always extended to the ABI, other builtin types are not
3883 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3884 if (BT && BT->getKind() == BuiltinType::Bool)
3885 return ABIArgInfo::getExtend();
3887 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3888 // passes them indirectly through memory.
3889 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3890 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3891 if (LDF == &llvm::APFloat::x87DoubleExtended())
3892 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3895 return ABIArgInfo::getDirect();
3898 void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI,
3899 unsigned FreeSSERegs,
3901 bool IsRegCall) const {
3903 for (auto &I : FI.arguments()) {
3904 if (Count < VectorcallMaxParamNumAsReg)
3905 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
3907 // Since these cannot be passed in registers, pretend no registers
3909 unsigned ZeroSSERegsAvail = 0;
3910 I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false,
3911 IsVectorCall, IsRegCall);
3917 for (auto &I : FI.arguments()) {
3918 if (Count < VectorcallMaxParamNumAsReg)
3919 I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info);
3924 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3926 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
3927 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
3929 unsigned FreeSSERegs = 0;
3931 // We can use up to 4 SSE return registers with vectorcall.
3933 } else if (IsRegCall) {
3934 // RegCall gives us 16 SSE registers.
3938 if (!getCXXABI().classifyReturnType(FI))
3939 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
3940 IsVectorCall, IsRegCall);
3943 // We can use up to 6 SSE register parameters with vectorcall.
3945 } else if (IsRegCall) {
3946 // RegCall gives us 16 SSE registers, we can reuse the return registers.
3951 computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall);
3953 for (auto &I : FI.arguments())
3954 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
3959 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3960 QualType Ty) const {
3962 bool IsIndirect = false;
3964 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3965 // not 1, 2, 4, or 8 bytes, must be passed by reference."
3966 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
3967 uint64_t Width = getContext().getTypeSize(Ty);
3968 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
3971 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
3972 CGF.getContext().getTypeInfoInChars(Ty),
3973 CharUnits::fromQuantity(8),
3974 /*allowHigherAlign*/ false);
3979 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3980 class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
3981 bool IsSoftFloatABI;
3983 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
3984 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
3986 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3987 QualType Ty) const override;
3990 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3992 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
3993 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
3995 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
3996 // This is recovered from gcc output.
3997 return 1; // r1 is the dedicated stack pointer
4000 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4001 llvm::Value *Address) const override;
4006 // TODO: this implementation is now likely redundant with
4007 // DefaultABIInfo::EmitVAArg.
4008 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4009 QualType Ty) const {
4010 const unsigned OverflowLimit = 8;
4011 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4012 // TODO: Implement this. For now ignore.
4014 return Address::invalid(); // FIXME?
4017 // struct __va_list_tag {
4018 // unsigned char gpr;
4019 // unsigned char fpr;
4020 // unsigned short reserved;
4021 // void *overflow_arg_area;
4022 // void *reg_save_area;
4025 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
4027 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
4028 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
4030 // All aggregates are passed indirectly? That doesn't seem consistent
4031 // with the argument-lowering code.
4032 bool isIndirect = Ty->isAggregateType();
4034 CGBuilderTy &Builder = CGF.Builder;
4036 // The calling convention either uses 1-2 GPRs or 1 FPR.
4037 Address NumRegsAddr = Address::invalid();
4038 if (isInt || IsSoftFloatABI) {
4039 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
4041 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
4044 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4046 // "Align" the register count when TY is i64.
4047 if (isI64 || (isF64 && IsSoftFloatABI)) {
4048 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4049 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4053 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
4055 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4056 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4057 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4059 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4061 llvm::Type *DirectTy = CGF.ConvertType(Ty);
4062 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
4064 // Case 1: consume registers.
4065 Address RegAddr = Address::invalid();
4067 CGF.EmitBlock(UsingRegs);
4069 Address RegSaveAreaPtr =
4070 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
4071 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4072 CharUnits::fromQuantity(8));
4073 assert(RegAddr.getElementType() == CGF.Int8Ty);
4075 // Floating-point registers start after the general-purpose registers.
4076 if (!(isInt || IsSoftFloatABI)) {
4077 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4078 CharUnits::fromQuantity(32));
4081 // Get the address of the saved value by scaling the number of
4082 // registers we've used by the number of
4083 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
4084 llvm::Value *RegOffset =
4085 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4086 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4087 RegAddr.getPointer(), RegOffset),
4088 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4089 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4091 // Increase the used-register count.
4093 Builder.CreateAdd(NumRegs,
4094 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
4095 Builder.CreateStore(NumRegs, NumRegsAddr);
4097 CGF.EmitBranch(Cont);
4100 // Case 2: consume space in the overflow area.
4101 Address MemAddr = Address::invalid();
4103 CGF.EmitBlock(UsingOverflow);
4105 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4107 // Everything in the overflow area is rounded up to a size of at least 4.
4108 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4112 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
4113 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
4115 Size = CGF.getPointerSize();
4118 Address OverflowAreaAddr =
4119 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
4120 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
4122 // Round up address of argument to alignment
4123 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4124 if (Align > OverflowAreaAlign) {
4125 llvm::Value *Ptr = OverflowArea.getPointer();
4126 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4130 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4132 // Increase the overflow area.
4133 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4134 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4135 CGF.EmitBranch(Cont);
4138 CGF.EmitBlock(Cont);
4140 // Merge the cases with a phi.
4141 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4144 // Load the pointer if the argument was passed indirectly.
4146 Result = Address(Builder.CreateLoad(Result, "aggr"),
4147 getContext().getTypeAlignInChars(Ty));
4154 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4155 llvm::Value *Address) const {
4156 // This is calculated from the LLVM and GCC tables and verified
4157 // against gcc output. AFAIK all ABIs use the same encoding.
4159 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4161 llvm::IntegerType *i8 = CGF.Int8Ty;
4162 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4163 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4164 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4166 // 0-31: r0-31, the 4-byte general-purpose registers
4167 AssignToArrayRange(Builder, Address, Four8, 0, 31);
4169 // 32-63: fp0-31, the 8-byte floating-point registers
4170 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4172 // 64-76 are various 4-byte special-purpose registers:
4179 AssignToArrayRange(Builder, Address, Four8, 64, 76);
4181 // 77-108: v0-31, the 16-byte vector registers
4182 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4189 AssignToArrayRange(Builder, Address, Four8, 109, 113);
4197 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
4198 class PPC64_SVR4_ABIInfo : public ABIInfo {
4206 static const unsigned GPRBits = 64;
4209 bool IsSoftFloatABI;
4211 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4212 // will be passed in a QPX register.
4213 bool IsQPXVectorTy(const Type *Ty) const {
4217 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4218 unsigned NumElements = VT->getNumElements();
4219 if (NumElements == 1)
4222 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4223 if (getContext().getTypeSize(Ty) <= 256)
4225 } else if (VT->getElementType()->
4226 isSpecificBuiltinType(BuiltinType::Float)) {
4227 if (getContext().getTypeSize(Ty) <= 128)
4235 bool IsQPXVectorTy(QualType Ty) const {
4236 return IsQPXVectorTy(Ty.getTypePtr());
4240 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4242 : ABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
4243 IsSoftFloatABI(SoftFloatABI) {}
4245 bool isPromotableTypeForABI(QualType Ty) const;
4246 CharUnits getParamTypeAlignment(QualType Ty) const;
4248 ABIArgInfo classifyReturnType(QualType RetTy) const;
4249 ABIArgInfo classifyArgumentType(QualType Ty) const;
4251 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4252 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4253 uint64_t Members) const override;
4255 // TODO: We can add more logic to computeInfo to improve performance.
4256 // Example: For aggregate arguments that fit in a register, we could
4257 // use getDirectInReg (as is done below for structs containing a single
4258 // floating-point value) to avoid pushing them to memory on function
4259 // entry. This would require changing the logic in PPCISelLowering
4260 // when lowering the parameters in the caller and args in the callee.
4261 void computeInfo(CGFunctionInfo &FI) const override {
4262 if (!getCXXABI().classifyReturnType(FI))
4263 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4264 for (auto &I : FI.arguments()) {
4265 // We rely on the default argument classification for the most part.
4266 // One exception: An aggregate containing a single floating-point
4267 // or vector item must be passed in a register if one is available.
4268 const Type *T = isSingleElementStruct(I.type, getContext());
4270 const BuiltinType *BT = T->getAs<BuiltinType>();
4271 if (IsQPXVectorTy(T) ||
4272 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
4273 (BT && BT->isFloatingPoint())) {
4275 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
4279 I.info = classifyArgumentType(I.type);
4283 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4284 QualType Ty) const override;
4287 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
4290 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
4291 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4293 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX,
4296 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4297 // This is recovered from gcc output.
4298 return 1; // r1 is the dedicated stack pointer
4301 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4302 llvm::Value *Address) const override;
4305 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4307 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4309 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4310 // This is recovered from gcc output.
4311 return 1; // r1 is the dedicated stack pointer
4314 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4315 llvm::Value *Address) const override;
4320 // Return true if the ABI requires Ty to be passed sign- or zero-
4321 // extended to 64 bits.
4323 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4324 // Treat an enum type as its underlying type.
4325 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4326 Ty = EnumTy->getDecl()->getIntegerType();
4328 // Promotable integer types are required to be promoted by the ABI.
4329 if (Ty->isPromotableIntegerType())
4332 // In addition to the usual promotable integer types, we also need to
4333 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4334 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4335 switch (BT->getKind()) {
4336 case BuiltinType::Int:
4337 case BuiltinType::UInt:
4346 /// isAlignedParamType - Determine whether a type requires 16-byte or
4347 /// higher alignment in the parameter area. Always returns at least 8.
4348 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4349 // Complex types are passed just like their elements.
4350 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4351 Ty = CTy->getElementType();
4353 // Only vector types of size 16 bytes need alignment (larger types are
4354 // passed via reference, smaller types are not aligned).
4355 if (IsQPXVectorTy(Ty)) {
4356 if (getContext().getTypeSize(Ty) > 128)
4357 return CharUnits::fromQuantity(32);
4359 return CharUnits::fromQuantity(16);
4360 } else if (Ty->isVectorType()) {
4361 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
4364 // For single-element float/vector structs, we consider the whole type
4365 // to have the same alignment requirements as its single element.
4366 const Type *AlignAsType = nullptr;
4367 const Type *EltType = isSingleElementStruct(Ty, getContext());
4369 const BuiltinType *BT = EltType->getAs<BuiltinType>();
4370 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
4371 getContext().getTypeSize(EltType) == 128) ||
4372 (BT && BT->isFloatingPoint()))
4373 AlignAsType = EltType;
4376 // Likewise for ELFv2 homogeneous aggregates.
4377 const Type *Base = nullptr;
4378 uint64_t Members = 0;
4379 if (!AlignAsType && Kind == ELFv2 &&
4380 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4383 // With special case aggregates, only vector base types need alignment.
4384 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4385 if (getContext().getTypeSize(AlignAsType) > 128)
4386 return CharUnits::fromQuantity(32);
4388 return CharUnits::fromQuantity(16);
4389 } else if (AlignAsType) {
4390 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
4393 // Otherwise, we only need alignment for any aggregate type that
4394 // has an alignment requirement of >= 16 bytes.
4395 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4396 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
4397 return CharUnits::fromQuantity(32);
4398 return CharUnits::fromQuantity(16);
4401 return CharUnits::fromQuantity(8);
4404 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4405 /// aggregate. Base is set to the base element type, and Members is set
4406 /// to the number of base elements.
4407 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4408 uint64_t &Members) const {
4409 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4410 uint64_t NElements = AT->getSize().getZExtValue();
4413 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4415 Members *= NElements;
4416 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4417 const RecordDecl *RD = RT->getDecl();
4418 if (RD->hasFlexibleArrayMember())
4423 // If this is a C++ record, check the bases first.
4424 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4425 for (const auto &I : CXXRD->bases()) {
4426 // Ignore empty records.
4427 if (isEmptyRecord(getContext(), I.getType(), true))
4430 uint64_t FldMembers;
4431 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4434 Members += FldMembers;
4438 for (const auto *FD : RD->fields()) {
4439 // Ignore (non-zero arrays of) empty records.
4440 QualType FT = FD->getType();
4441 while (const ConstantArrayType *AT =
4442 getContext().getAsConstantArrayType(FT)) {
4443 if (AT->getSize().getZExtValue() == 0)
4445 FT = AT->getElementType();
4447 if (isEmptyRecord(getContext(), FT, true))
4450 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4451 if (getContext().getLangOpts().CPlusPlus &&
4452 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4455 uint64_t FldMembers;
4456 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4459 Members = (RD->isUnion() ?
4460 std::max(Members, FldMembers) : Members + FldMembers);
4466 // Ensure there is no padding.
4467 if (getContext().getTypeSize(Base) * Members !=
4468 getContext().getTypeSize(Ty))
4472 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4474 Ty = CT->getElementType();
4477 // Most ABIs only support float, double, and some vector type widths.
4478 if (!isHomogeneousAggregateBaseType(Ty))
4481 // The base type must be the same for all members. Types that
4482 // agree in both total size and mode (float vs. vector) are
4483 // treated as being equivalent here.
4484 const Type *TyPtr = Ty.getTypePtr();
4487 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4488 // so make sure to widen it explicitly.
4489 if (const VectorType *VT = Base->getAs<VectorType>()) {
4490 QualType EltTy = VT->getElementType();
4491 unsigned NumElements =
4492 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4494 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4499 if (Base->isVectorType() != TyPtr->isVectorType() ||
4500 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4503 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4506 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4507 // Homogeneous aggregates for ELFv2 must have base types of float,
4508 // double, long double, or 128-bit vectors.
4509 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4510 if (BT->getKind() == BuiltinType::Float ||
4511 BT->getKind() == BuiltinType::Double ||
4512 BT->getKind() == BuiltinType::LongDouble) {
4518 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4519 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
4525 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4526 const Type *Base, uint64_t Members) const {
4527 // Vector types require one register, floating point types require one
4528 // or two registers depending on their size.
4530 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
4532 // Homogeneous Aggregates may occupy at most 8 registers.
4533 return Members * NumRegs <= 8;
4537 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
4538 Ty = useFirstFieldIfTransparentUnion(Ty);
4540 if (Ty->isAnyComplexType())
4541 return ABIArgInfo::getDirect();
4543 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4544 // or via reference (larger than 16 bytes).
4545 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
4546 uint64_t Size = getContext().getTypeSize(Ty);
4548 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4549 else if (Size < 128) {
4550 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4551 return ABIArgInfo::getDirect(CoerceTy);
4555 if (isAggregateTypeForABI(Ty)) {
4556 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
4557 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4559 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4560 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
4562 // ELFv2 homogeneous aggregates are passed as array types.
4563 const Type *Base = nullptr;
4564 uint64_t Members = 0;
4565 if (Kind == ELFv2 &&
4566 isHomogeneousAggregate(Ty, Base, Members)) {
4567 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4568 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4569 return ABIArgInfo::getDirect(CoerceTy);
4572 // If an aggregate may end up fully in registers, we do not
4573 // use the ByVal method, but pass the aggregate as array.
4574 // This is usually beneficial since we avoid forcing the
4575 // back-end to store the argument to memory.
4576 uint64_t Bits = getContext().getTypeSize(Ty);
4577 if (Bits > 0 && Bits <= 8 * GPRBits) {
4578 llvm::Type *CoerceTy;
4580 // Types up to 8 bytes are passed as integer type (which will be
4581 // properly aligned in the argument save area doubleword).
4582 if (Bits <= GPRBits)
4584 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
4585 // Larger types are passed as arrays, with the base type selected
4586 // according to the required alignment in the save area.
4588 uint64_t RegBits = ABIAlign * 8;
4589 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
4590 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4591 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4594 return ABIArgInfo::getDirect(CoerceTy);
4597 // All other aggregates are passed ByVal.
4598 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4600 /*Realign=*/TyAlign > ABIAlign);
4603 return (isPromotableTypeForABI(Ty) ?
4604 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4608 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4609 if (RetTy->isVoidType())
4610 return ABIArgInfo::getIgnore();
4612 if (RetTy->isAnyComplexType())
4613 return ABIArgInfo::getDirect();
4615 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4616 // or via reference (larger than 16 bytes).
4617 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
4618 uint64_t Size = getContext().getTypeSize(RetTy);
4620 return getNaturalAlignIndirect(RetTy);
4621 else if (Size < 128) {
4622 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4623 return ABIArgInfo::getDirect(CoerceTy);
4627 if (isAggregateTypeForABI(RetTy)) {
4628 // ELFv2 homogeneous aggregates are returned as array types.
4629 const Type *Base = nullptr;
4630 uint64_t Members = 0;
4631 if (Kind == ELFv2 &&
4632 isHomogeneousAggregate(RetTy, Base, Members)) {
4633 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4634 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4635 return ABIArgInfo::getDirect(CoerceTy);
4638 // ELFv2 small aggregates are returned in up to two registers.
4639 uint64_t Bits = getContext().getTypeSize(RetTy);
4640 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4642 return ABIArgInfo::getIgnore();
4644 llvm::Type *CoerceTy;
4645 if (Bits > GPRBits) {
4646 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
4647 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
4650 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
4651 return ABIArgInfo::getDirect(CoerceTy);
4654 // All other aggregates are returned indirectly.
4655 return getNaturalAlignIndirect(RetTy);
4658 return (isPromotableTypeForABI(RetTy) ?
4659 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4662 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
4663 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4664 QualType Ty) const {
4665 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4666 TypeInfo.second = getParamTypeAlignment(Ty);
4668 CharUnits SlotSize = CharUnits::fromQuantity(8);
4670 // If we have a complex type and the base type is smaller than 8 bytes,
4671 // the ABI calls for the real and imaginary parts to be right-adjusted
4672 // in separate doublewords. However, Clang expects us to produce a
4673 // pointer to a structure with the two parts packed tightly. So generate
4674 // loads of the real and imaginary parts relative to the va_list pointer,
4675 // and store them to a temporary structure.
4676 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4677 CharUnits EltSize = TypeInfo.first / 2;
4678 if (EltSize < SlotSize) {
4679 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4680 SlotSize * 2, SlotSize,
4681 SlotSize, /*AllowHigher*/ true);
4683 Address RealAddr = Addr;
4684 Address ImagAddr = RealAddr;
4685 if (CGF.CGM.getDataLayout().isBigEndian()) {
4686 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4687 SlotSize - EltSize);
4688 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4689 2 * SlotSize - EltSize);
4691 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4694 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4695 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4696 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4697 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4698 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4700 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4701 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4707 // Otherwise, just use the general rule.
4708 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4709 TypeInfo, SlotSize, /*AllowHigher*/ true);
4713 PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4714 llvm::Value *Address) {
4715 // This is calculated from the LLVM and GCC tables and verified
4716 // against gcc output. AFAIK all ABIs use the same encoding.
4718 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4720 llvm::IntegerType *i8 = CGF.Int8Ty;
4721 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4722 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4723 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4725 // 0-31: r0-31, the 8-byte general-purpose registers
4726 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4728 // 32-63: fp0-31, the 8-byte floating-point registers
4729 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4731 // 64-67 are various 8-byte special-purpose registers:
4736 AssignToArrayRange(Builder, Address, Eight8, 64, 67);
4738 // 68-76 are various 4-byte special-purpose registers:
4741 AssignToArrayRange(Builder, Address, Four8, 68, 76);
4743 // 77-108: v0-31, the 16-byte vector registers
4744 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4754 AssignToArrayRange(Builder, Address, Eight8, 109, 116);
4760 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4761 CodeGen::CodeGenFunction &CGF,
4762 llvm::Value *Address) const {
4764 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4768 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4769 llvm::Value *Address) const {
4771 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4774 //===----------------------------------------------------------------------===//
4775 // AArch64 ABI Implementation
4776 //===----------------------------------------------------------------------===//
4780 class AArch64ABIInfo : public SwiftABIInfo {
4791 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4792 : SwiftABIInfo(CGT), Kind(Kind) {}
4795 ABIKind getABIKind() const { return Kind; }
4796 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4798 ABIArgInfo classifyReturnType(QualType RetTy) const;
4799 ABIArgInfo classifyArgumentType(QualType RetTy) const;
4800 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4801 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4802 uint64_t Members) const override;
4804 bool isIllegalVectorType(QualType Ty) const;
4806 void computeInfo(CGFunctionInfo &FI) const override {
4807 if (!getCXXABI().classifyReturnType(FI))
4808 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4810 for (auto &it : FI.arguments())
4811 it.info = classifyArgumentType(it.type);
4814 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4815 CodeGenFunction &CGF) const;
4817 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4818 CodeGenFunction &CGF) const;
4820 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4821 QualType Ty) const override {
4822 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4823 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
4826 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
4827 ArrayRef<llvm::Type*> scalars,
4828 bool asReturnValue) const override {
4829 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4831 bool isSwiftErrorInRegister() const override {
4835 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
4836 unsigned elts) const override;
4839 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
4841 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4842 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
4844 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
4845 return "mov\tfp, fp\t\t# marker for objc_retainAutoreleaseReturnValue";
4848 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4852 bool doesReturnSlotInterfereWithArgs() const override { return false; }
4856 ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
4857 Ty = useFirstFieldIfTransparentUnion(Ty);
4859 // Handle illegal vector types here.
4860 if (isIllegalVectorType(Ty)) {
4861 uint64_t Size = getContext().getTypeSize(Ty);
4862 // Android promotes <2 x i8> to i16, not i32
4863 if (isAndroid() && (Size <= 16)) {
4864 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
4865 return ABIArgInfo::getDirect(ResType);
4868 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
4869 return ABIArgInfo::getDirect(ResType);
4872 llvm::Type *ResType =
4873 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
4874 return ABIArgInfo::getDirect(ResType);
4877 llvm::Type *ResType =
4878 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
4879 return ABIArgInfo::getDirect(ResType);
4881 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4884 if (!isAggregateTypeForABI(Ty)) {
4885 // Treat an enum type as its underlying type.
4886 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4887 Ty = EnumTy->getDecl()->getIntegerType();
4889 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4890 ? ABIArgInfo::getExtend()
4891 : ABIArgInfo::getDirect());
4894 // Structures with either a non-trivial destructor or a non-trivial
4895 // copy constructor are always indirect.
4896 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
4897 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4898 CGCXXABI::RAA_DirectInMemory);
4901 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4902 // elsewhere for GNU compatibility.
4903 uint64_t Size = getContext().getTypeSize(Ty);
4904 bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
4905 if (IsEmpty || Size == 0) {
4906 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4907 return ABIArgInfo::getIgnore();
4909 // GNU C mode. The only argument that gets ignored is an empty one with size
4911 if (IsEmpty && Size == 0)
4912 return ABIArgInfo::getIgnore();
4913 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4916 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
4917 const Type *Base = nullptr;
4918 uint64_t Members = 0;
4919 if (isHomogeneousAggregate(Ty, Base, Members)) {
4920 return ABIArgInfo::getDirect(
4921 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
4924 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4926 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
4927 // same size and alignment.
4928 if (getTarget().isRenderScriptTarget()) {
4929 return coerceToIntArray(Ty, getContext(), getVMContext());
4931 unsigned Alignment = getContext().getTypeAlign(Ty);
4932 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
4934 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4935 // For aggregates with 16-byte alignment, we use i128.
4936 if (Alignment < 128 && Size == 128) {
4937 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4938 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4940 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4943 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4946 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
4947 if (RetTy->isVoidType())
4948 return ABIArgInfo::getIgnore();
4950 // Large vector types should be returned via memory.
4951 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
4952 return getNaturalAlignIndirect(RetTy);
4954 if (!isAggregateTypeForABI(RetTy)) {
4955 // Treat an enum type as its underlying type.
4956 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4957 RetTy = EnumTy->getDecl()->getIntegerType();
4959 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4960 ? ABIArgInfo::getExtend()
4961 : ABIArgInfo::getDirect());
4964 uint64_t Size = getContext().getTypeSize(RetTy);
4965 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
4966 return ABIArgInfo::getIgnore();
4968 const Type *Base = nullptr;
4969 uint64_t Members = 0;
4970 if (isHomogeneousAggregate(RetTy, Base, Members))
4971 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4972 return ABIArgInfo::getDirect();
4974 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4976 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
4977 // same size and alignment.
4978 if (getTarget().isRenderScriptTarget()) {
4979 return coerceToIntArray(RetTy, getContext(), getVMContext());
4981 unsigned Alignment = getContext().getTypeAlign(RetTy);
4982 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
4984 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4985 // For aggregates with 16-byte alignment, we use i128.
4986 if (Alignment < 128 && Size == 128) {
4987 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4988 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4990 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4993 return getNaturalAlignIndirect(RetTy);
4996 /// isIllegalVectorType - check whether the vector type is legal for AArch64.
4997 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
4998 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4999 // Check whether VT is legal.
5000 unsigned NumElements = VT->getNumElements();
5001 uint64_t Size = getContext().getTypeSize(VT);
5002 // NumElements should be power of 2.
5003 if (!llvm::isPowerOf2_32(NumElements))
5005 return Size != 64 && (Size != 128 || NumElements == 1);
5010 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5012 unsigned elts) const {
5013 if (!llvm::isPowerOf2_32(elts))
5015 if (totalSize.getQuantity() != 8 &&
5016 (totalSize.getQuantity() != 16 || elts == 1))
5021 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5022 // Homogeneous aggregates for AAPCS64 must have base types of a floating
5023 // point type or a short-vector type. This is the same as the 32-bit ABI,
5024 // but with the difference that any floating-point type is allowed,
5025 // including __fp16.
5026 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5027 if (BT->isFloatingPoint())
5029 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5030 unsigned VecSize = getContext().getTypeSize(VT);
5031 if (VecSize == 64 || VecSize == 128)
5037 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5038 uint64_t Members) const {
5039 return Members <= 4;
5042 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
5044 CodeGenFunction &CGF) const {
5045 ABIArgInfo AI = classifyArgumentType(Ty);
5046 bool IsIndirect = AI.isIndirect();
5048 llvm::Type *BaseTy = CGF.ConvertType(Ty);
5050 BaseTy = llvm::PointerType::getUnqual(BaseTy);
5051 else if (AI.getCoerceToType())
5052 BaseTy = AI.getCoerceToType();
5054 unsigned NumRegs = 1;
5055 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5056 BaseTy = ArrTy->getElementType();
5057 NumRegs = ArrTy->getNumElements();
5059 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5061 // The AArch64 va_list type and handling is specified in the Procedure Call
5062 // Standard, section B.4:
5072 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5073 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5074 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5075 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5077 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5078 CharUnits TyAlign = TyInfo.second;
5080 Address reg_offs_p = Address::invalid();
5081 llvm::Value *reg_offs = nullptr;
5083 CharUnits reg_top_offset;
5084 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
5086 // 3 is the field number of __gr_offs
5088 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5090 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5091 reg_top_index = 1; // field number for __gr_top
5092 reg_top_offset = CharUnits::fromQuantity(8);
5093 RegSize = llvm::alignTo(RegSize, 8);
5095 // 4 is the field number of __vr_offs.
5097 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
5099 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5100 reg_top_index = 2; // field number for __vr_top
5101 reg_top_offset = CharUnits::fromQuantity(16);
5102 RegSize = 16 * NumRegs;
5105 //=======================================
5106 // Find out where argument was passed
5107 //=======================================
5109 // If reg_offs >= 0 we're already using the stack for this type of
5110 // argument. We don't want to keep updating reg_offs (in case it overflows,
5111 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5112 // whatever they get).
5113 llvm::Value *UsingStack = nullptr;
5114 UsingStack = CGF.Builder.CreateICmpSGE(
5115 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5117 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5119 // Otherwise, at least some kind of argument could go in these registers, the
5120 // question is whether this particular type is too big.
5121 CGF.EmitBlock(MaybeRegBlock);
5123 // Integer arguments may need to correct register alignment (for example a
5124 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5125 // align __gr_offs to calculate the potential address.
5126 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5127 int Align = TyAlign.getQuantity();
5129 reg_offs = CGF.Builder.CreateAdd(
5130 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5132 reg_offs = CGF.Builder.CreateAnd(
5133 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5137 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
5138 // The fact that this is done unconditionally reflects the fact that
5139 // allocating an argument to the stack also uses up all the remaining
5140 // registers of the appropriate kind.
5141 llvm::Value *NewOffset = nullptr;
5142 NewOffset = CGF.Builder.CreateAdd(
5143 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5144 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5146 // Now we're in a position to decide whether this argument really was in
5147 // registers or not.
5148 llvm::Value *InRegs = nullptr;
5149 InRegs = CGF.Builder.CreateICmpSLE(
5150 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5152 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5154 //=======================================
5155 // Argument was in registers
5156 //=======================================
5158 // Now we emit the code for if the argument was originally passed in
5159 // registers. First start the appropriate block:
5160 CGF.EmitBlock(InRegBlock);
5162 llvm::Value *reg_top = nullptr;
5163 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
5164 reg_top_offset, "reg_top_p");
5165 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
5166 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5167 CharUnits::fromQuantity(IsFPR ? 16 : 8));
5168 Address RegAddr = Address::invalid();
5169 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
5172 // If it's been passed indirectly (actually a struct), whatever we find from
5173 // stored registers or on the stack will actually be a struct **.
5174 MemTy = llvm::PointerType::getUnqual(MemTy);
5177 const Type *Base = nullptr;
5178 uint64_t NumMembers = 0;
5179 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
5180 if (IsHFA && NumMembers > 1) {
5181 // Homogeneous aggregates passed in registers will have their elements split
5182 // and stored 16-bytes apart regardless of size (they're notionally in qN,
5183 // qN+1, ...). We reload and store into a temporary local variable
5185 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
5186 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
5187 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5188 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
5189 Address Tmp = CGF.CreateTempAlloca(HFATy,
5190 std::max(TyAlign, BaseTyInfo.second));
5192 // On big-endian platforms, the value will be right-aligned in its slot.
5194 if (CGF.CGM.getDataLayout().isBigEndian() &&
5195 BaseTyInfo.first.getQuantity() < 16)
5196 Offset = 16 - BaseTyInfo.first.getQuantity();
5198 for (unsigned i = 0; i < NumMembers; ++i) {
5199 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5201 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5202 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5205 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
5207 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5208 CGF.Builder.CreateStore(Elem, StoreAddr);
5211 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
5213 // Otherwise the object is contiguous in memory.
5215 // It might be right-aligned in its slot.
5216 CharUnits SlotSize = BaseAddr.getAlignment();
5217 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
5218 (IsHFA || !isAggregateTypeForABI(Ty)) &&
5219 TyInfo.first < SlotSize) {
5220 CharUnits Offset = SlotSize - TyInfo.first;
5221 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
5224 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
5227 CGF.EmitBranch(ContBlock);
5229 //=======================================
5230 // Argument was on the stack
5231 //=======================================
5232 CGF.EmitBlock(OnStackBlock);
5234 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
5235 CharUnits::Zero(), "stack_p");
5236 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
5238 // Again, stack arguments may need realignment. In this case both integer and
5239 // floating-point ones might be affected.
5240 if (!IsIndirect && TyAlign.getQuantity() > 8) {
5241 int Align = TyAlign.getQuantity();
5243 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
5245 OnStackPtr = CGF.Builder.CreateAdd(
5246 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
5248 OnStackPtr = CGF.Builder.CreateAnd(
5249 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
5252 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
5254 Address OnStackAddr(OnStackPtr,
5255 std::max(CharUnits::fromQuantity(8), TyAlign));
5257 // All stack slots are multiples of 8 bytes.
5258 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5259 CharUnits StackSize;
5261 StackSize = StackSlotSize;
5263 StackSize = TyInfo.first.alignTo(StackSlotSize);
5265 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
5266 llvm::Value *NewStack =
5267 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
5269 // Write the new value of __stack for the next call to va_arg
5270 CGF.Builder.CreateStore(NewStack, stack_p);
5272 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
5273 TyInfo.first < StackSlotSize) {
5274 CharUnits Offset = StackSlotSize - TyInfo.first;
5275 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
5278 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
5280 CGF.EmitBranch(ContBlock);
5282 //=======================================
5284 //=======================================
5285 CGF.EmitBlock(ContBlock);
5287 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5288 OnStackAddr, OnStackBlock, "vaargs.addr");
5291 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
5297 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5298 CodeGenFunction &CGF) const {
5299 // The backend's lowering doesn't support va_arg for aggregates or
5300 // illegal vector types. Lower VAArg here for these cases and use
5301 // the LLVM va_arg instruction for everything else.
5302 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
5303 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
5305 CharUnits SlotSize = CharUnits::fromQuantity(8);
5307 // Empty records are ignored for parameter passing purposes.
5308 if (isEmptyRecord(getContext(), Ty, true)) {
5309 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5310 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5314 // The size of the actual thing passed, which might end up just
5315 // being a pointer for indirect types.
5316 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5318 // Arguments bigger than 16 bytes which aren't homogeneous
5319 // aggregates should be passed indirectly.
5320 bool IsIndirect = false;
5321 if (TyInfo.first.getQuantity() > 16) {
5322 const Type *Base = nullptr;
5323 uint64_t Members = 0;
5324 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
5327 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5328 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
5331 //===----------------------------------------------------------------------===//
5332 // ARM ABI Implementation
5333 //===----------------------------------------------------------------------===//
5337 class ARMABIInfo : public SwiftABIInfo {
5350 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5351 : SwiftABIInfo(CGT), Kind(_Kind) {
5355 bool isEABI() const {
5356 switch (getTarget().getTriple().getEnvironment()) {
5357 case llvm::Triple::Android:
5358 case llvm::Triple::EABI:
5359 case llvm::Triple::EABIHF:
5360 case llvm::Triple::GNUEABI:
5361 case llvm::Triple::GNUEABIHF:
5362 case llvm::Triple::MuslEABI:
5363 case llvm::Triple::MuslEABIHF:
5370 bool isEABIHF() const {
5371 switch (getTarget().getTriple().getEnvironment()) {
5372 case llvm::Triple::EABIHF:
5373 case llvm::Triple::GNUEABIHF:
5374 case llvm::Triple::MuslEABIHF:
5381 ABIKind getABIKind() const { return Kind; }
5384 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
5385 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
5386 bool isIllegalVectorType(QualType Ty) const;
5388 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5389 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5390 uint64_t Members) const override;
5392 void computeInfo(CGFunctionInfo &FI) const override;
5394 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5395 QualType Ty) const override;
5397 llvm::CallingConv::ID getLLVMDefaultCC() const;
5398 llvm::CallingConv::ID getABIDefaultCC() const;
5401 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5402 ArrayRef<llvm::Type*> scalars,
5403 bool asReturnValue) const override {
5404 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5406 bool isSwiftErrorInRegister() const override {
5409 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5410 unsigned elts) const override;
5413 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5415 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5416 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
5418 const ARMABIInfo &getABIInfo() const {
5419 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5422 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5426 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
5427 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
5430 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5431 llvm::Value *Address) const override {
5432 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
5434 // 0-15 are the 16 integer registers.
5435 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
5439 unsigned getSizeOfUnwindException() const override {
5440 if (getABIInfo().isEABI()) return 88;
5441 return TargetCodeGenInfo::getSizeOfUnwindException();
5444 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5445 CodeGen::CodeGenModule &CGM) const override {
5446 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5450 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5455 switch (Attr->getInterrupt()) {
5456 case ARMInterruptAttr::Generic: Kind = ""; break;
5457 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5458 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5459 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5460 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5461 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5464 llvm::Function *Fn = cast<llvm::Function>(GV);
5466 Fn->addFnAttr("interrupt", Kind);
5468 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5469 if (ABI == ARMABIInfo::APCS)
5472 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5473 // however this is not necessarily true on taking any interrupt. Instruct
5474 // the backend to perform a realignment as part of the function prologue.
5475 llvm::AttrBuilder B;
5476 B.addStackAlignmentAttr(8);
5477 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
5481 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
5483 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5484 : ARMTargetCodeGenInfo(CGT, K) {}
5486 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5487 CodeGen::CodeGenModule &CGM) const override;
5489 void getDependentLibraryOption(llvm::StringRef Lib,
5490 llvm::SmallString<24> &Opt) const override {
5491 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5494 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5495 llvm::SmallString<32> &Opt) const override {
5496 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5500 void WindowsARMTargetCodeGenInfo::setTargetAttributes(
5501 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5502 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5503 addStackProbeSizeTargetAttribute(D, GV, CGM);
5507 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
5508 if (!getCXXABI().classifyReturnType(FI))
5509 FI.getReturnInfo() =
5510 classifyReturnType(FI.getReturnType(), FI.isVariadic());
5512 for (auto &I : FI.arguments())
5513 I.info = classifyArgumentType(I.type, FI.isVariadic());
5515 // Always honor user-specified calling convention.
5516 if (FI.getCallingConvention() != llvm::CallingConv::C)
5519 llvm::CallingConv::ID cc = getRuntimeCC();
5520 if (cc != llvm::CallingConv::C)
5521 FI.setEffectiveCallingConvention(cc);
5524 /// Return the default calling convention that LLVM will use.
5525 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5526 // The default calling convention that LLVM will infer.
5527 if (isEABIHF() || getTarget().getTriple().isWatchABI())
5528 return llvm::CallingConv::ARM_AAPCS_VFP;
5530 return llvm::CallingConv::ARM_AAPCS;
5532 return llvm::CallingConv::ARM_APCS;
5535 /// Return the calling convention that our ABI would like us to use
5536 /// as the C calling convention.
5537 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
5538 switch (getABIKind()) {
5539 case APCS: return llvm::CallingConv::ARM_APCS;
5540 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5541 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
5542 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
5544 llvm_unreachable("bad ABI kind");
5547 void ARMABIInfo::setCCs() {
5548 assert(getRuntimeCC() == llvm::CallingConv::C);
5550 // Don't muddy up the IR with a ton of explicit annotations if
5551 // they'd just match what LLVM will infer from the triple.
5552 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5553 if (abiCC != getLLVMDefaultCC())
5556 // AAPCS apparently requires runtime support functions to be soft-float, but
5557 // that's almost certainly for historic reasons (Thumb1 not supporting VFP
5558 // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
5559 switch (getABIKind()) {
5562 if (abiCC != getLLVMDefaultCC())
5567 BuiltinCC = llvm::CallingConv::ARM_AAPCS;
5572 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5573 bool isVariadic) const {
5574 // 6.1.2.1 The following argument types are VFP CPRCs:
5575 // A single-precision floating-point type (including promoted
5576 // half-precision types); A double-precision floating-point type;
5577 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5578 // with a Base Type of a single- or double-precision floating-point type,
5579 // 64-bit containerized vectors or 128-bit containerized vectors with one
5580 // to four Elements.
5581 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
5583 Ty = useFirstFieldIfTransparentUnion(Ty);
5585 // Handle illegal vector types here.
5586 if (isIllegalVectorType(Ty)) {
5587 uint64_t Size = getContext().getTypeSize(Ty);
5589 llvm::Type *ResType =
5590 llvm::Type::getInt32Ty(getVMContext());
5591 return ABIArgInfo::getDirect(ResType);
5594 llvm::Type *ResType = llvm::VectorType::get(
5595 llvm::Type::getInt32Ty(getVMContext()), 2);
5596 return ABIArgInfo::getDirect(ResType);
5599 llvm::Type *ResType = llvm::VectorType::get(
5600 llvm::Type::getInt32Ty(getVMContext()), 4);
5601 return ABIArgInfo::getDirect(ResType);
5603 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5606 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5607 // unspecified. This is not done for OpenCL as it handles the half type
5608 // natively, and does not need to interwork with AAPCS code.
5609 if (Ty->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
5610 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5611 llvm::Type::getFloatTy(getVMContext()) :
5612 llvm::Type::getInt32Ty(getVMContext());
5613 return ABIArgInfo::getDirect(ResType);
5616 if (!isAggregateTypeForABI(Ty)) {
5617 // Treat an enum type as its underlying type.
5618 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
5619 Ty = EnumTy->getDecl()->getIntegerType();
5622 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5623 : ABIArgInfo::getDirect());
5626 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5627 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
5630 // Ignore empty records.
5631 if (isEmptyRecord(getContext(), Ty, true))
5632 return ABIArgInfo::getIgnore();
5634 if (IsEffectivelyAAPCS_VFP) {
5635 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5636 // into VFP registers.
5637 const Type *Base = nullptr;
5638 uint64_t Members = 0;
5639 if (isHomogeneousAggregate(Ty, Base, Members)) {
5640 assert(Base && "Base class should be set for homogeneous aggregate");
5641 // Base can be a floating-point or a vector.
5642 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
5644 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5645 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5646 // this convention even for a variadic function: the backend will use GPRs
5648 const Type *Base = nullptr;
5649 uint64_t Members = 0;
5650 if (isHomogeneousAggregate(Ty, Base, Members)) {
5651 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5653 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5654 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5658 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5659 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5660 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5661 // bigger than 128-bits, they get placed in space allocated by the caller,
5662 // and a pointer is passed.
5663 return ABIArgInfo::getIndirect(
5664 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
5667 // Support byval for ARM.
5668 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5669 // most 8-byte. We realign the indirect argument if type alignment is bigger
5670 // than ABI alignment.
5671 uint64_t ABIAlign = 4;
5672 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5673 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5674 getABIKind() == ARMABIInfo::AAPCS)
5675 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
5677 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
5678 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
5679 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5681 /*Realign=*/TyAlign > ABIAlign);
5684 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
5685 // same size and alignment.
5686 if (getTarget().isRenderScriptTarget()) {
5687 return coerceToIntArray(Ty, getContext(), getVMContext());
5690 // Otherwise, pass by coercing to a structure of the appropriate size.
5693 // FIXME: Try to match the types of the arguments more accurately where
5695 if (getContext().getTypeAlign(Ty) <= 32) {
5696 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5697 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
5699 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5700 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
5703 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
5706 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
5707 llvm::LLVMContext &VMContext) {
5708 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5709 // is called integer-like if its size is less than or equal to one word, and
5710 // the offset of each of its addressable sub-fields is zero.
5712 uint64_t Size = Context.getTypeSize(Ty);
5714 // Check that the type fits in a word.
5718 // FIXME: Handle vector types!
5719 if (Ty->isVectorType())
5722 // Float types are never treated as "integer like".
5723 if (Ty->isRealFloatingType())
5726 // If this is a builtin or pointer type then it is ok.
5727 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
5730 // Small complex integer types are "integer like".
5731 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5732 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
5734 // Single element and zero sized arrays should be allowed, by the definition
5735 // above, but they are not.
5737 // Otherwise, it must be a record type.
5738 const RecordType *RT = Ty->getAs<RecordType>();
5739 if (!RT) return false;
5741 // Ignore records with flexible arrays.
5742 const RecordDecl *RD = RT->getDecl();
5743 if (RD->hasFlexibleArrayMember())
5746 // Check that all sub-fields are at offset 0, and are themselves "integer
5748 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5750 bool HadField = false;
5752 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5753 i != e; ++i, ++idx) {
5754 const FieldDecl *FD = *i;
5756 // Bit-fields are not addressable, we only need to verify they are "integer
5757 // like". We still have to disallow a subsequent non-bitfield, for example:
5758 // struct { int : 0; int x }
5759 // is non-integer like according to gcc.
5760 if (FD->isBitField()) {
5764 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5770 // Check if this field is at offset 0.
5771 if (Layout.getFieldOffset(idx) != 0)
5774 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5777 // Only allow at most one field in a structure. This doesn't match the
5778 // wording above, but follows gcc in situations with a field following an
5780 if (!RD->isUnion()) {
5791 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5792 bool isVariadic) const {
5793 bool IsEffectivelyAAPCS_VFP =
5794 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
5796 if (RetTy->isVoidType())
5797 return ABIArgInfo::getIgnore();
5799 // Large vector types should be returned via memory.
5800 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
5801 return getNaturalAlignIndirect(RetTy);
5804 // __fp16 gets returned as if it were an int or float, but with the top 16
5805 // bits unspecified. This is not done for OpenCL as it handles the half type
5806 // natively, and does not need to interwork with AAPCS code.
5807 if (RetTy->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
5808 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5809 llvm::Type::getFloatTy(getVMContext()) :
5810 llvm::Type::getInt32Ty(getVMContext());
5811 return ABIArgInfo::getDirect(ResType);
5814 if (!isAggregateTypeForABI(RetTy)) {
5815 // Treat an enum type as its underlying type.
5816 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5817 RetTy = EnumTy->getDecl()->getIntegerType();
5819 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5820 : ABIArgInfo::getDirect();
5823 // Are we following APCS?
5824 if (getABIKind() == APCS) {
5825 if (isEmptyRecord(getContext(), RetTy, false))
5826 return ABIArgInfo::getIgnore();
5828 // Complex types are all returned as packed integers.
5830 // FIXME: Consider using 2 x vector types if the back end handles them
5832 if (RetTy->isAnyComplexType())
5833 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5834 getVMContext(), getContext().getTypeSize(RetTy)));
5836 // Integer like structures are returned in r0.
5837 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
5838 // Return in the smallest viable integer type.
5839 uint64_t Size = getContext().getTypeSize(RetTy);
5841 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5843 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5844 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5847 // Otherwise return in memory.
5848 return getNaturalAlignIndirect(RetTy);
5851 // Otherwise this is an AAPCS variant.
5853 if (isEmptyRecord(getContext(), RetTy, true))
5854 return ABIArgInfo::getIgnore();
5856 // Check for homogeneous aggregates with AAPCS-VFP.
5857 if (IsEffectivelyAAPCS_VFP) {
5858 const Type *Base = nullptr;
5859 uint64_t Members = 0;
5860 if (isHomogeneousAggregate(RetTy, Base, Members)) {
5861 assert(Base && "Base class should be set for homogeneous aggregate");
5862 // Homogeneous Aggregates are returned directly.
5863 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
5867 // Aggregates <= 4 bytes are returned in r0; other aggregates
5868 // are returned indirectly.
5869 uint64_t Size = getContext().getTypeSize(RetTy);
5871 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
5872 // same size and alignment.
5873 if (getTarget().isRenderScriptTarget()) {
5874 return coerceToIntArray(RetTy, getContext(), getVMContext());
5876 if (getDataLayout().isBigEndian())
5877 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
5878 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5880 // Return in the smallest viable integer type.
5882 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5884 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5885 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5886 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
5887 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
5888 llvm::Type *CoerceTy =
5889 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
5890 return ABIArgInfo::getDirect(CoerceTy);
5893 return getNaturalAlignIndirect(RetTy);
5896 /// isIllegalVector - check whether Ty is an illegal vector type.
5897 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
5898 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
5900 // Android shipped using Clang 3.1, which supported a slightly different
5901 // vector ABI. The primary differences were that 3-element vector types
5902 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
5903 // accepts that legacy behavior for Android only.
5904 // Check whether VT is legal.
5905 unsigned NumElements = VT->getNumElements();
5906 // NumElements should be power of 2 or equal to 3.
5907 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
5910 // Check whether VT is legal.
5911 unsigned NumElements = VT->getNumElements();
5912 uint64_t Size = getContext().getTypeSize(VT);
5913 // NumElements should be power of 2.
5914 if (!llvm::isPowerOf2_32(NumElements))
5916 // Size should be greater than 32 bits.
5923 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
5925 unsigned numElts) const {
5926 if (!llvm::isPowerOf2_32(numElts))
5928 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
5931 if (vectorSize.getQuantity() != 8 &&
5932 (vectorSize.getQuantity() != 16 || numElts == 1))
5937 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5938 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5939 // double, or 64-bit or 128-bit vectors.
5940 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5941 if (BT->getKind() == BuiltinType::Float ||
5942 BT->getKind() == BuiltinType::Double ||
5943 BT->getKind() == BuiltinType::LongDouble)
5945 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5946 unsigned VecSize = getContext().getTypeSize(VT);
5947 if (VecSize == 64 || VecSize == 128)
5953 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5954 uint64_t Members) const {
5955 return Members <= 4;
5958 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5959 QualType Ty) const {
5960 CharUnits SlotSize = CharUnits::fromQuantity(4);
5962 // Empty records are ignored for parameter passing purposes.
5963 if (isEmptyRecord(getContext(), Ty, true)) {
5964 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
5965 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5969 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5970 CharUnits TyAlignForABI = TyInfo.second;
5972 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5973 bool IsIndirect = false;
5974 const Type *Base = nullptr;
5975 uint64_t Members = 0;
5976 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
5979 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
5980 // allocated by the caller.
5981 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
5982 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5983 !isHomogeneousAggregate(Ty, Base, Members)) {
5986 // Otherwise, bound the type's ABI alignment.
5987 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5988 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
5989 // Our callers should be prepared to handle an under-aligned address.
5990 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5991 getABIKind() == ARMABIInfo::AAPCS) {
5992 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5993 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
5994 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5995 // ARMv7k allows type alignment up to 16 bytes.
5996 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5997 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
5999 TyAlignForABI = CharUnits::fromQuantity(4);
6001 TyInfo.second = TyAlignForABI;
6003 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
6004 SlotSize, /*AllowHigherAlign*/ true);
6007 //===----------------------------------------------------------------------===//
6008 // NVPTX ABI Implementation
6009 //===----------------------------------------------------------------------===//
6013 class NVPTXABIInfo : public ABIInfo {
6015 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6017 ABIArgInfo classifyReturnType(QualType RetTy) const;
6018 ABIArgInfo classifyArgumentType(QualType Ty) const;
6020 void computeInfo(CGFunctionInfo &FI) const override;
6021 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6022 QualType Ty) const override;
6025 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
6027 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
6028 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
6030 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6031 CodeGen::CodeGenModule &M) const override;
6033 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
6034 // resulting MDNode to the nvvm.annotations MDNode.
6035 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
6038 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
6039 if (RetTy->isVoidType())
6040 return ABIArgInfo::getIgnore();
6042 // note: this is different from default ABI
6043 if (!RetTy->isScalarType())
6044 return ABIArgInfo::getDirect();
6046 // Treat an enum type as its underlying type.
6047 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6048 RetTy = EnumTy->getDecl()->getIntegerType();
6050 return (RetTy->isPromotableIntegerType() ?
6051 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6054 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
6055 // Treat an enum type as its underlying type.
6056 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6057 Ty = EnumTy->getDecl()->getIntegerType();
6059 // Return aggregates type as indirect by value
6060 if (isAggregateTypeForABI(Ty))
6061 return getNaturalAlignIndirect(Ty, /* byval */ true);
6063 return (Ty->isPromotableIntegerType() ?
6064 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6067 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
6068 if (!getCXXABI().classifyReturnType(FI))
6069 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6070 for (auto &I : FI.arguments())
6071 I.info = classifyArgumentType(I.type);
6073 // Always honor user-specified calling convention.
6074 if (FI.getCallingConvention() != llvm::CallingConv::C)
6077 FI.setEffectiveCallingConvention(getRuntimeCC());
6080 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6081 QualType Ty) const {
6082 llvm_unreachable("NVPTX does not support varargs");
6085 void NVPTXTargetCodeGenInfo::
6086 setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6087 CodeGen::CodeGenModule &M) const{
6088 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6091 llvm::Function *F = cast<llvm::Function>(GV);
6093 // Perform special handling in OpenCL mode
6094 if (M.getLangOpts().OpenCL) {
6095 // Use OpenCL function attributes to check for kernel functions
6096 // By default, all functions are device functions
6097 if (FD->hasAttr<OpenCLKernelAttr>()) {
6098 // OpenCL __kernel functions get kernel metadata
6099 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6100 addNVVMMetadata(F, "kernel", 1);
6101 // And kernel functions are not subject to inlining
6102 F->addFnAttr(llvm::Attribute::NoInline);
6106 // Perform special handling in CUDA mode.
6107 if (M.getLangOpts().CUDA) {
6108 // CUDA __global__ functions get a kernel metadata entry. Since
6109 // __global__ functions cannot be called from the device, we do not
6110 // need to set the noinline attribute.
6111 if (FD->hasAttr<CUDAGlobalAttr>()) {
6112 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6113 addNVVMMetadata(F, "kernel", 1);
6115 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
6116 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
6117 llvm::APSInt MaxThreads(32);
6118 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
6120 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
6122 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
6123 // not specified in __launch_bounds__ or if the user specified a 0 value,
6124 // we don't have to add a PTX directive.
6125 if (Attr->getMinBlocks()) {
6126 llvm::APSInt MinBlocks(32);
6127 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
6129 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
6130 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
6136 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
6138 llvm::Module *M = F->getParent();
6139 llvm::LLVMContext &Ctx = M->getContext();
6141 // Get "nvvm.annotations" metadata node
6142 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
6144 llvm::Metadata *MDVals[] = {
6145 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
6146 llvm::ConstantAsMetadata::get(
6147 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
6148 // Append metadata to nvvm.annotations
6149 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6153 //===----------------------------------------------------------------------===//
6154 // SystemZ ABI Implementation
6155 //===----------------------------------------------------------------------===//
6159 class SystemZABIInfo : public SwiftABIInfo {
6163 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
6164 : SwiftABIInfo(CGT), HasVector(HV) {}
6166 bool isPromotableIntegerType(QualType Ty) const;
6167 bool isCompoundType(QualType Ty) const;
6168 bool isVectorArgumentType(QualType Ty) const;
6169 bool isFPArgumentType(QualType Ty) const;
6170 QualType GetSingleElementType(QualType Ty) const;
6172 ABIArgInfo classifyReturnType(QualType RetTy) const;
6173 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
6175 void computeInfo(CGFunctionInfo &FI) const override {
6176 if (!getCXXABI().classifyReturnType(FI))
6177 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6178 for (auto &I : FI.arguments())
6179 I.info = classifyArgumentType(I.type);
6182 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6183 QualType Ty) const override;
6185 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
6186 ArrayRef<llvm::Type*> scalars,
6187 bool asReturnValue) const override {
6188 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6190 bool isSwiftErrorInRegister() const override {
6195 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
6197 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
6198 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
6203 bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
6204 // Treat an enum type as its underlying type.
6205 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6206 Ty = EnumTy->getDecl()->getIntegerType();
6208 // Promotable integer types are required to be promoted by the ABI.
6209 if (Ty->isPromotableIntegerType())
6212 // 32-bit values must also be promoted.
6213 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6214 switch (BT->getKind()) {
6215 case BuiltinType::Int:
6216 case BuiltinType::UInt:
6224 bool SystemZABIInfo::isCompoundType(QualType Ty) const {
6225 return (Ty->isAnyComplexType() ||
6226 Ty->isVectorType() ||
6227 isAggregateTypeForABI(Ty));
6230 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
6231 return (HasVector &&
6232 Ty->isVectorType() &&
6233 getContext().getTypeSize(Ty) <= 128);
6236 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
6237 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6238 switch (BT->getKind()) {
6239 case BuiltinType::Float:
6240 case BuiltinType::Double:
6249 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
6250 if (const RecordType *RT = Ty->getAsStructureType()) {
6251 const RecordDecl *RD = RT->getDecl();
6254 // If this is a C++ record, check the bases first.
6255 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6256 for (const auto &I : CXXRD->bases()) {
6257 QualType Base = I.getType();
6259 // Empty bases don't affect things either way.
6260 if (isEmptyRecord(getContext(), Base, true))
6263 if (!Found.isNull())
6265 Found = GetSingleElementType(Base);
6268 // Check the fields.
6269 for (const auto *FD : RD->fields()) {
6270 // For compatibility with GCC, ignore empty bitfields in C++ mode.
6271 // Unlike isSingleElementStruct(), empty structure and array fields
6272 // do count. So do anonymous bitfields that aren't zero-sized.
6273 if (getContext().getLangOpts().CPlusPlus &&
6274 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
6277 // Unlike isSingleElementStruct(), arrays do not count.
6278 // Nested structures still do though.
6279 if (!Found.isNull())
6281 Found = GetSingleElementType(FD->getType());
6284 // Unlike isSingleElementStruct(), trailing padding is allowed.
6285 // An 8-byte aligned struct s { float f; } is passed as a double.
6286 if (!Found.isNull())
6293 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6294 QualType Ty) const {
6295 // Assume that va_list type is correct; should be pointer to LLVM type:
6299 // i8 *__overflow_arg_area;
6300 // i8 *__reg_save_area;
6303 // Every non-vector argument occupies 8 bytes and is passed by preference
6304 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
6305 // always passed on the stack.
6306 Ty = getContext().getCanonicalType(Ty);
6307 auto TyInfo = getContext().getTypeInfoInChars(Ty);
6308 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
6309 llvm::Type *DirectTy = ArgTy;
6310 ABIArgInfo AI = classifyArgumentType(Ty);
6311 bool IsIndirect = AI.isIndirect();
6312 bool InFPRs = false;
6313 bool IsVector = false;
6314 CharUnits UnpaddedSize;
6315 CharUnits DirectAlign;
6317 DirectTy = llvm::PointerType::getUnqual(DirectTy);
6318 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
6320 if (AI.getCoerceToType())
6321 ArgTy = AI.getCoerceToType();
6322 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
6323 IsVector = ArgTy->isVectorTy();
6324 UnpaddedSize = TyInfo.first;
6325 DirectAlign = TyInfo.second;
6327 CharUnits PaddedSize = CharUnits::fromQuantity(8);
6328 if (IsVector && UnpaddedSize > PaddedSize)
6329 PaddedSize = CharUnits::fromQuantity(16);
6330 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
6332 CharUnits Padding = (PaddedSize - UnpaddedSize);
6334 llvm::Type *IndexTy = CGF.Int64Ty;
6335 llvm::Value *PaddedSizeV =
6336 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
6339 // Work out the address of a vector argument on the stack.
6340 // Vector arguments are always passed in the high bits of a
6341 // single (8 byte) or double (16 byte) stack slot.
6342 Address OverflowArgAreaPtr =
6343 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
6344 "overflow_arg_area_ptr");
6345 Address OverflowArgArea =
6346 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6349 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
6351 // Update overflow_arg_area_ptr pointer
6352 llvm::Value *NewOverflowArgArea =
6353 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6354 "overflow_arg_area");
6355 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6360 assert(PaddedSize.getQuantity() == 8);
6362 unsigned MaxRegs, RegCountField, RegSaveIndex;
6363 CharUnits RegPadding;
6365 MaxRegs = 4; // Maximum of 4 FPR arguments
6366 RegCountField = 1; // __fpr
6367 RegSaveIndex = 16; // save offset for f0
6368 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
6370 MaxRegs = 5; // Maximum of 5 GPR arguments
6371 RegCountField = 0; // __gpr
6372 RegSaveIndex = 2; // save offset for r2
6373 RegPadding = Padding; // values are passed in the low bits of a GPR
6376 Address RegCountPtr = CGF.Builder.CreateStructGEP(
6377 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
6379 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
6380 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
6381 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
6384 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6385 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
6386 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6387 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
6389 // Emit code to load the value if it was passed in registers.
6390 CGF.EmitBlock(InRegBlock);
6392 // Work out the address of an argument register.
6393 llvm::Value *ScaledRegCount =
6394 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
6395 llvm::Value *RegBase =
6396 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
6397 + RegPadding.getQuantity());
6398 llvm::Value *RegOffset =
6399 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
6400 Address RegSaveAreaPtr =
6401 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
6402 "reg_save_area_ptr");
6403 llvm::Value *RegSaveArea =
6404 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
6405 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
6409 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
6411 // Update the register count
6412 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
6413 llvm::Value *NewRegCount =
6414 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
6415 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
6416 CGF.EmitBranch(ContBlock);
6418 // Emit code to load the value if it was passed in memory.
6419 CGF.EmitBlock(InMemBlock);
6421 // Work out the address of a stack argument.
6422 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
6423 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
6424 Address OverflowArgArea =
6425 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6427 Address RawMemAddr =
6428 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6430 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
6432 // Update overflow_arg_area_ptr pointer
6433 llvm::Value *NewOverflowArgArea =
6434 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6435 "overflow_arg_area");
6436 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6437 CGF.EmitBranch(ContBlock);
6439 // Return the appropriate result.
6440 CGF.EmitBlock(ContBlock);
6441 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6442 MemAddr, InMemBlock, "va_arg.addr");
6445 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6451 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6452 if (RetTy->isVoidType())
6453 return ABIArgInfo::getIgnore();
6454 if (isVectorArgumentType(RetTy))
6455 return ABIArgInfo::getDirect();
6456 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
6457 return getNaturalAlignIndirect(RetTy);
6458 return (isPromotableIntegerType(RetTy) ?
6459 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6462 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6463 // Handle the generic C++ ABI.
6464 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6465 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6467 // Integers and enums are extended to full register width.
6468 if (isPromotableIntegerType(Ty))
6469 return ABIArgInfo::getExtend();
6471 // Handle vector types and vector-like structure types. Note that
6472 // as opposed to float-like structure types, we do not allow any
6473 // padding for vector-like structures, so verify the sizes match.
6474 uint64_t Size = getContext().getTypeSize(Ty);
6475 QualType SingleElementTy = GetSingleElementType(Ty);
6476 if (isVectorArgumentType(SingleElementTy) &&
6477 getContext().getTypeSize(SingleElementTy) == Size)
6478 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6480 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
6481 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
6482 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6484 // Handle small structures.
6485 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6486 // Structures with flexible arrays have variable length, so really
6487 // fail the size test above.
6488 const RecordDecl *RD = RT->getDecl();
6489 if (RD->hasFlexibleArrayMember())
6490 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6492 // The structure is passed as an unextended integer, a float, or a double.
6494 if (isFPArgumentType(SingleElementTy)) {
6495 assert(Size == 32 || Size == 64);
6497 PassTy = llvm::Type::getFloatTy(getVMContext());
6499 PassTy = llvm::Type::getDoubleTy(getVMContext());
6501 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6502 return ABIArgInfo::getDirect(PassTy);
6505 // Non-structure compounds are passed indirectly.
6506 if (isCompoundType(Ty))
6507 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6509 return ABIArgInfo::getDirect(nullptr);
6512 //===----------------------------------------------------------------------===//
6513 // MSP430 ABI Implementation
6514 //===----------------------------------------------------------------------===//
6518 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6520 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6521 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
6522 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6523 CodeGen::CodeGenModule &M) const override;
6528 void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
6529 llvm::GlobalValue *GV,
6530 CodeGen::CodeGenModule &M) const {
6531 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
6532 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6533 // Handle 'interrupt' attribute:
6534 llvm::Function *F = cast<llvm::Function>(GV);
6536 // Step 1: Set ISR calling convention.
6537 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6539 // Step 2: Add attributes goodness.
6540 F->addFnAttr(llvm::Attribute::NoInline);
6542 // Step 3: Emit ISR vector alias.
6543 unsigned Num = attr->getNumber() / 2;
6544 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6545 "__isr_" + Twine(Num), F);
6550 //===----------------------------------------------------------------------===//
6551 // MIPS ABI Implementation. This works for both little-endian and
6552 // big-endian variants.
6553 //===----------------------------------------------------------------------===//
6556 class MipsABIInfo : public ABIInfo {
6558 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6559 void CoerceToIntArgs(uint64_t TySize,
6560 SmallVectorImpl<llvm::Type *> &ArgList) const;
6561 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
6562 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
6563 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
6565 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
6566 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
6567 StackAlignInBytes(IsO32 ? 8 : 16) {}
6569 ABIArgInfo classifyReturnType(QualType RetTy) const;
6570 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
6571 void computeInfo(CGFunctionInfo &FI) const override;
6572 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6573 QualType Ty) const override;
6574 bool shouldSignExtUnsignedType(QualType Ty) const override;
6577 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
6578 unsigned SizeOfUnwindException;
6580 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6581 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
6582 SizeOfUnwindException(IsO32 ? 24 : 32) {}
6584 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
6588 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6589 CodeGen::CodeGenModule &CGM) const override {
6590 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6592 llvm::Function *Fn = cast<llvm::Function>(GV);
6593 if (FD->hasAttr<Mips16Attr>()) {
6594 Fn->addFnAttr("mips16");
6596 else if (FD->hasAttr<NoMips16Attr>()) {
6597 Fn->addFnAttr("nomips16");
6600 if (FD->hasAttr<MicroMipsAttr>())
6601 Fn->addFnAttr("micromips");
6602 else if (FD->hasAttr<NoMicroMipsAttr>())
6603 Fn->addFnAttr("nomicromips");
6605 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6610 switch (Attr->getInterrupt()) {
6611 case MipsInterruptAttr::eic: Kind = "eic"; break;
6612 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6613 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6614 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6615 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6616 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6617 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6618 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6619 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6622 Fn->addFnAttr("interrupt", Kind);
6626 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6627 llvm::Value *Address) const override;
6629 unsigned getSizeOfUnwindException() const override {
6630 return SizeOfUnwindException;
6635 void MipsABIInfo::CoerceToIntArgs(
6636 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
6637 llvm::IntegerType *IntTy =
6638 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
6640 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6641 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6642 ArgList.push_back(IntTy);
6644 // If necessary, add one more integer type to ArgList.
6645 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6648 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
6651 // In N32/64, an aligned double precision floating point field is passed in
6653 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
6654 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6657 CoerceToIntArgs(TySize, ArgList);
6658 return llvm::StructType::get(getVMContext(), ArgList);
6661 if (Ty->isComplexType())
6662 return CGT.ConvertType(Ty);
6664 const RecordType *RT = Ty->getAs<RecordType>();
6666 // Unions/vectors are passed in integer registers.
6667 if (!RT || !RT->isStructureOrClassType()) {
6668 CoerceToIntArgs(TySize, ArgList);
6669 return llvm::StructType::get(getVMContext(), ArgList);
6672 const RecordDecl *RD = RT->getDecl();
6673 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6674 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
6676 uint64_t LastOffset = 0;
6678 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6680 // Iterate over fields in the struct/class and check if there are any aligned
6682 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6683 i != e; ++i, ++idx) {
6684 const QualType Ty = i->getType();
6685 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6687 if (!BT || BT->getKind() != BuiltinType::Double)
6690 uint64_t Offset = Layout.getFieldOffset(idx);
6691 if (Offset % 64) // Ignore doubles that are not aligned.
6694 // Add ((Offset - LastOffset) / 64) args of type i64.
6695 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6696 ArgList.push_back(I64);
6699 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6700 LastOffset = Offset + 64;
6703 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6704 ArgList.append(IntArgList.begin(), IntArgList.end());
6706 return llvm::StructType::get(getVMContext(), ArgList);
6709 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6710 uint64_t Offset) const {
6711 if (OrigOffset + MinABIStackAlignInBytes > Offset)
6714 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
6718 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
6719 Ty = useFirstFieldIfTransparentUnion(Ty);
6721 uint64_t OrigOffset = Offset;
6722 uint64_t TySize = getContext().getTypeSize(Ty);
6723 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
6725 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6726 (uint64_t)StackAlignInBytes);
6727 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6728 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
6730 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
6731 // Ignore empty aggregates.
6733 return ABIArgInfo::getIgnore();
6735 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
6736 Offset = OrigOffset + MinABIStackAlignInBytes;
6737 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6740 // Use indirect if the aggregate cannot fit into registers for
6741 // passing arguments according to the ABI
6742 unsigned Threshold = IsO32 ? 16 : 64;
6744 if(getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(Threshold))
6745 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align), true,
6746 getContext().getTypeAlign(Ty) / 8 > Align);
6748 // If we have reached here, aggregates are passed directly by coercing to
6749 // another structure type. Padding is inserted if the offset of the
6750 // aggregate is unaligned.
6751 ABIArgInfo ArgInfo =
6752 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6753 getPaddingType(OrigOffset, CurrOffset));
6754 ArgInfo.setInReg(true);
6758 // Treat an enum type as its underlying type.
6759 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6760 Ty = EnumTy->getDecl()->getIntegerType();
6762 // All integral types are promoted to the GPR width.
6763 if (Ty->isIntegralOrEnumerationType())
6764 return ABIArgInfo::getExtend();
6766 return ABIArgInfo::getDirect(
6767 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
6771 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
6772 const RecordType *RT = RetTy->getAs<RecordType>();
6773 SmallVector<llvm::Type*, 8> RTList;
6775 if (RT && RT->isStructureOrClassType()) {
6776 const RecordDecl *RD = RT->getDecl();
6777 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6778 unsigned FieldCnt = Layout.getFieldCount();
6780 // N32/64 returns struct/classes in floating point registers if the
6781 // following conditions are met:
6782 // 1. The size of the struct/class is no larger than 128-bit.
6783 // 2. The struct/class has one or two fields all of which are floating
6785 // 3. The offset of the first field is zero (this follows what gcc does).
6787 // Any other composite results are returned in integer registers.
6789 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6790 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6791 for (; b != e; ++b) {
6792 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
6794 if (!BT || !BT->isFloatingPoint())
6797 RTList.push_back(CGT.ConvertType(b->getType()));
6801 return llvm::StructType::get(getVMContext(), RTList,
6802 RD->hasAttr<PackedAttr>());
6808 CoerceToIntArgs(Size, RTList);
6809 return llvm::StructType::get(getVMContext(), RTList);
6812 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
6813 uint64_t Size = getContext().getTypeSize(RetTy);
6815 if (RetTy->isVoidType())
6816 return ABIArgInfo::getIgnore();
6818 // O32 doesn't treat zero-sized structs differently from other structs.
6819 // However, N32/N64 ignores zero sized return values.
6820 if (!IsO32 && Size == 0)
6821 return ABIArgInfo::getIgnore();
6823 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
6825 if (RetTy->isAnyComplexType())
6826 return ABIArgInfo::getDirect();
6828 // O32 returns integer vectors in registers and N32/N64 returns all small
6829 // aggregates in registers.
6831 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6832 ABIArgInfo ArgInfo =
6833 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6834 ArgInfo.setInReg(true);
6839 return getNaturalAlignIndirect(RetTy);
6842 // Treat an enum type as its underlying type.
6843 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6844 RetTy = EnumTy->getDecl()->getIntegerType();
6846 return (RetTy->isPromotableIntegerType() ?
6847 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6850 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
6851 ABIArgInfo &RetInfo = FI.getReturnInfo();
6852 if (!getCXXABI().classifyReturnType(FI))
6853 RetInfo = classifyReturnType(FI.getReturnType());
6855 // Check if a pointer to an aggregate is passed as a hidden argument.
6856 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
6858 for (auto &I : FI.arguments())
6859 I.info = classifyArgumentType(I.type, Offset);
6862 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6863 QualType OrigTy) const {
6864 QualType Ty = OrigTy;
6866 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6867 // Pointers are also promoted in the same way but this only matters for N32.
6868 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
6869 unsigned PtrWidth = getTarget().getPointerWidth(0);
6870 bool DidPromote = false;
6871 if ((Ty->isIntegerType() &&
6872 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
6873 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
6875 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6876 Ty->isSignedIntegerType());
6879 auto TyInfo = getContext().getTypeInfoInChars(Ty);
6881 // The alignment of things in the argument area is never larger than
6882 // StackAlignInBytes.
6884 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6886 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6887 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6889 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6890 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6893 // If there was a promotion, "unpromote" into a temporary.
6894 // TODO: can we just use a pointer into a subset of the original slot?
6896 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6897 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6899 // Truncate down to the right width.
6900 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
6902 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
6903 if (OrigTy->isPointerType())
6904 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
6906 CGF.Builder.CreateStore(V, Temp);
6913 bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
6914 int TySize = getContext().getTypeSize(Ty);
6916 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
6917 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
6924 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6925 llvm::Value *Address) const {
6926 // This information comes from gcc's implementation, which seems to
6927 // as canonical as it gets.
6929 // Everything on MIPS is 4 bytes. Double-precision FP registers
6930 // are aliased to pairs of single-precision FP registers.
6931 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
6933 // 0-31 are the general purpose registers, $0 - $31.
6934 // 32-63 are the floating-point registers, $f0 - $f31.
6935 // 64 and 65 are the multiply/divide registers, $hi and $lo.
6936 // 66 is the (notional, I think) register for signal-handler return.
6937 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
6939 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
6940 // They are one bit wide and ignored here.
6942 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
6943 // (coprocessor 1 is the FP unit)
6944 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
6945 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
6946 // 176-181 are the DSP accumulator registers.
6947 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
6951 //===----------------------------------------------------------------------===//
6952 // AVR ABI Implementation.
6953 //===----------------------------------------------------------------------===//
6956 class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
6958 AVRTargetCodeGenInfo(CodeGenTypes &CGT)
6959 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) { }
6961 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6962 CodeGen::CodeGenModule &CGM) const override {
6963 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
6965 auto *Fn = cast<llvm::Function>(GV);
6967 if (FD->getAttr<AVRInterruptAttr>())
6968 Fn->addFnAttr("interrupt");
6970 if (FD->getAttr<AVRSignalAttr>())
6971 Fn->addFnAttr("signal");
6976 //===----------------------------------------------------------------------===//
6977 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
6978 // Currently subclassed only to implement custom OpenCL C function attribute
6980 //===----------------------------------------------------------------------===//
6984 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
6986 TCETargetCodeGenInfo(CodeGenTypes &CGT)
6987 : DefaultTargetCodeGenInfo(CGT) {}
6989 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6990 CodeGen::CodeGenModule &M) const override;
6993 void TCETargetCodeGenInfo::setTargetAttributes(
6994 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
6995 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6998 llvm::Function *F = cast<llvm::Function>(GV);
7000 if (M.getLangOpts().OpenCL) {
7001 if (FD->hasAttr<OpenCLKernelAttr>()) {
7002 // OpenCL C Kernel functions are not subject to inlining
7003 F->addFnAttr(llvm::Attribute::NoInline);
7004 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
7006 // Convert the reqd_work_group_size() attributes to metadata.
7007 llvm::LLVMContext &Context = F->getContext();
7008 llvm::NamedMDNode *OpenCLMetadata =
7009 M.getModule().getOrInsertNamedMetadata(
7010 "opencl.kernel_wg_size_info");
7012 SmallVector<llvm::Metadata *, 5> Operands;
7013 Operands.push_back(llvm::ConstantAsMetadata::get(F));
7016 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7017 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
7019 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7020 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
7022 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7023 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
7025 // Add a boolean constant operand for "required" (true) or "hint"
7026 // (false) for implementing the work_group_size_hint attr later.
7027 // Currently always true as the hint is not yet implemented.
7029 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
7030 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
7038 //===----------------------------------------------------------------------===//
7039 // Hexagon ABI Implementation
7040 //===----------------------------------------------------------------------===//
7044 class HexagonABIInfo : public ABIInfo {
7048 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7052 ABIArgInfo classifyReturnType(QualType RetTy) const;
7053 ABIArgInfo classifyArgumentType(QualType RetTy) const;
7055 void computeInfo(CGFunctionInfo &FI) const override;
7057 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7058 QualType Ty) const override;
7061 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
7063 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
7064 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
7066 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
7073 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
7074 if (!getCXXABI().classifyReturnType(FI))
7075 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7076 for (auto &I : FI.arguments())
7077 I.info = classifyArgumentType(I.type);
7080 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
7081 if (!isAggregateTypeForABI(Ty)) {
7082 // Treat an enum type as its underlying type.
7083 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7084 Ty = EnumTy->getDecl()->getIntegerType();
7086 return (Ty->isPromotableIntegerType() ?
7087 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
7090 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7091 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7093 // Ignore empty records.
7094 if (isEmptyRecord(getContext(), Ty, true))
7095 return ABIArgInfo::getIgnore();
7097 uint64_t Size = getContext().getTypeSize(Ty);
7099 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
7100 // Pass in the smallest viable integer type.
7102 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7104 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7106 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7108 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7111 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
7112 if (RetTy->isVoidType())
7113 return ABIArgInfo::getIgnore();
7115 // Large vector types should be returned via memory.
7116 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
7117 return getNaturalAlignIndirect(RetTy);
7119 if (!isAggregateTypeForABI(RetTy)) {
7120 // Treat an enum type as its underlying type.
7121 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7122 RetTy = EnumTy->getDecl()->getIntegerType();
7124 return (RetTy->isPromotableIntegerType() ?
7125 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
7128 if (isEmptyRecord(getContext(), RetTy, true))
7129 return ABIArgInfo::getIgnore();
7131 // Aggregates <= 8 bytes are returned in r0; other aggregates
7132 // are returned indirectly.
7133 uint64_t Size = getContext().getTypeSize(RetTy);
7135 // Return in the smallest viable integer type.
7137 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7139 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7141 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7142 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7145 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
7148 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7149 QualType Ty) const {
7150 // FIXME: Someone needs to audit that this handle alignment correctly.
7151 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7152 getContext().getTypeInfoInChars(Ty),
7153 CharUnits::fromQuantity(4),
7154 /*AllowHigherAlign*/ true);
7157 //===----------------------------------------------------------------------===//
7158 // Lanai ABI Implementation
7159 //===----------------------------------------------------------------------===//
7162 class LanaiABIInfo : public DefaultABIInfo {
7164 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7166 bool shouldUseInReg(QualType Ty, CCState &State) const;
7168 void computeInfo(CGFunctionInfo &FI) const override {
7169 CCState State(FI.getCallingConvention());
7170 // Lanai uses 4 registers to pass arguments unless the function has the
7171 // regparm attribute set.
7172 if (FI.getHasRegParm()) {
7173 State.FreeRegs = FI.getRegParm();
7178 if (!getCXXABI().classifyReturnType(FI))
7179 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7180 for (auto &I : FI.arguments())
7181 I.info = classifyArgumentType(I.type, State);
7184 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
7185 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
7187 } // end anonymous namespace
7189 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
7190 unsigned Size = getContext().getTypeSize(Ty);
7191 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
7193 if (SizeInRegs == 0)
7196 if (SizeInRegs > State.FreeRegs) {
7201 State.FreeRegs -= SizeInRegs;
7206 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
7207 CCState &State) const {
7209 if (State.FreeRegs) {
7210 --State.FreeRegs; // Non-byval indirects just use one pointer.
7211 return getNaturalAlignIndirectInReg(Ty);
7213 return getNaturalAlignIndirect(Ty, false);
7216 // Compute the byval alignment.
7217 const unsigned MinABIStackAlignInBytes = 4;
7218 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
7219 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
7220 /*Realign=*/TypeAlign >
7221 MinABIStackAlignInBytes);
7224 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
7225 CCState &State) const {
7226 // Check with the C++ ABI first.
7227 const RecordType *RT = Ty->getAs<RecordType>();
7229 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
7230 if (RAA == CGCXXABI::RAA_Indirect) {
7231 return getIndirectResult(Ty, /*ByVal=*/false, State);
7232 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
7233 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
7237 if (isAggregateTypeForABI(Ty)) {
7238 // Structures with flexible arrays are always indirect.
7239 if (RT && RT->getDecl()->hasFlexibleArrayMember())
7240 return getIndirectResult(Ty, /*ByVal=*/true, State);
7242 // Ignore empty structs/unions.
7243 if (isEmptyRecord(getContext(), Ty, true))
7244 return ABIArgInfo::getIgnore();
7246 llvm::LLVMContext &LLVMContext = getVMContext();
7247 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
7248 if (SizeInRegs <= State.FreeRegs) {
7249 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
7250 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
7251 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
7252 State.FreeRegs -= SizeInRegs;
7253 return ABIArgInfo::getDirectInReg(Result);
7257 return getIndirectResult(Ty, true, State);
7260 // Treat an enum type as its underlying type.
7261 if (const auto *EnumTy = Ty->getAs<EnumType>())
7262 Ty = EnumTy->getDecl()->getIntegerType();
7264 bool InReg = shouldUseInReg(Ty, State);
7265 if (Ty->isPromotableIntegerType()) {
7267 return ABIArgInfo::getDirectInReg();
7268 return ABIArgInfo::getExtend();
7271 return ABIArgInfo::getDirectInReg();
7272 return ABIArgInfo::getDirect();
7276 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
7278 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7279 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
7283 //===----------------------------------------------------------------------===//
7284 // AMDGPU ABI Implementation
7285 //===----------------------------------------------------------------------===//
7289 class AMDGPUABIInfo final : public DefaultABIInfo {
7291 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7294 ABIArgInfo classifyArgumentType(QualType Ty) const;
7296 void computeInfo(CGFunctionInfo &FI) const override;
7299 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
7300 if (!getCXXABI().classifyReturnType(FI))
7301 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7303 unsigned CC = FI.getCallingConvention();
7304 for (auto &Arg : FI.arguments())
7305 if (CC == llvm::CallingConv::AMDGPU_KERNEL)
7306 Arg.info = classifyArgumentType(Arg.type);
7308 Arg.info = DefaultABIInfo::classifyArgumentType(Arg.type);
7311 /// \brief Classify argument of given type \p Ty.
7312 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty) const {
7313 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7315 return DefaultABIInfo::classifyArgumentType(Ty);
7318 // Coerce single element structs to its element.
7319 if (StrTy->getNumElements() == 1) {
7320 return ABIArgInfo::getDirect();
7323 // If we set CanBeFlattened to true, CodeGen will expand the struct to its
7324 // individual elements, which confuses the Clover OpenCL backend; therefore we
7325 // have to set it to false here. Other args of getDirect() are just defaults.
7326 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
7329 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
7331 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
7332 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {}
7333 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7334 CodeGen::CodeGenModule &M) const override;
7335 unsigned getOpenCLKernelCallingConv() const override;
7337 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
7338 llvm::PointerType *T, QualType QT) const override;
7340 unsigned getASTAllocaAddressSpace() const override {
7341 return LangAS::FirstTargetAddressSpace +
7342 getABIInfo().getDataLayout().getAllocaAddrSpace();
7347 static void appendOpenCLVersionMD (CodeGen::CodeGenModule &CGM);
7349 void AMDGPUTargetCodeGenInfo::setTargetAttributes(
7351 llvm::GlobalValue *GV,
7352 CodeGen::CodeGenModule &M) const {
7353 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7357 llvm::Function *F = cast<llvm::Function>(GV);
7359 const auto *ReqdWGS = M.getLangOpts().OpenCL ?
7360 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
7361 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
7362 if (ReqdWGS || FlatWGS) {
7363 unsigned Min = FlatWGS ? FlatWGS->getMin() : 0;
7364 unsigned Max = FlatWGS ? FlatWGS->getMax() : 0;
7365 if (ReqdWGS && Min == 0 && Max == 0)
7366 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
7369 assert(Min <= Max && "Min must be less than or equal Max");
7371 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
7372 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
7374 assert(Max == 0 && "Max must be zero");
7377 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
7378 unsigned Min = Attr->getMin();
7379 unsigned Max = Attr->getMax();
7382 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
7384 std::string AttrVal = llvm::utostr(Min);
7386 AttrVal = AttrVal + "," + llvm::utostr(Max);
7387 F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
7389 assert(Max == 0 && "Max must be zero");
7392 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
7393 unsigned NumSGPR = Attr->getNumSGPR();
7396 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
7399 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
7400 uint32_t NumVGPR = Attr->getNumVGPR();
7403 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
7406 appendOpenCLVersionMD(M);
7409 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7410 return llvm::CallingConv::AMDGPU_KERNEL;
7413 // Currently LLVM assumes null pointers always have value 0,
7414 // which results in incorrectly transformed IR. Therefore, instead of
7415 // emitting null pointers in private and local address spaces, a null
7416 // pointer in generic address space is emitted which is casted to a
7417 // pointer in local or private address space.
7418 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
7419 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
7420 QualType QT) const {
7421 if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
7422 return llvm::ConstantPointerNull::get(PT);
7424 auto &Ctx = CGM.getContext();
7425 auto NPT = llvm::PointerType::get(PT->getElementType(),
7426 Ctx.getTargetAddressSpace(LangAS::opencl_generic));
7427 return llvm::ConstantExpr::getAddrSpaceCast(
7428 llvm::ConstantPointerNull::get(NPT), PT);
7431 //===----------------------------------------------------------------------===//
7432 // SPARC v8 ABI Implementation.
7433 // Based on the SPARC Compliance Definition version 2.4.1.
7435 // Ensures that complex values are passed in registers.
7438 class SparcV8ABIInfo : public DefaultABIInfo {
7440 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7443 ABIArgInfo classifyReturnType(QualType RetTy) const;
7444 void computeInfo(CGFunctionInfo &FI) const override;
7446 } // end anonymous namespace
7450 SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
7451 if (Ty->isAnyComplexType()) {
7452 return ABIArgInfo::getDirect();
7455 return DefaultABIInfo::classifyReturnType(Ty);
7459 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7461 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7462 for (auto &Arg : FI.arguments())
7463 Arg.info = classifyArgumentType(Arg.type);
7467 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
7469 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
7470 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
7472 } // end anonymous namespace
7474 //===----------------------------------------------------------------------===//
7475 // SPARC v9 ABI Implementation.
7476 // Based on the SPARC Compliance Definition version 2.4.1.
7478 // Function arguments a mapped to a nominal "parameter array" and promoted to
7479 // registers depending on their type. Each argument occupies 8 or 16 bytes in
7480 // the array, structs larger than 16 bytes are passed indirectly.
7482 // One case requires special care:
7489 // When a struct mixed is passed by value, it only occupies 8 bytes in the
7490 // parameter array, but the int is passed in an integer register, and the float
7491 // is passed in a floating point register. This is represented as two arguments
7492 // with the LLVM IR inreg attribute:
7494 // declare void f(i32 inreg %i, float inreg %f)
7496 // The code generator will only allocate 4 bytes from the parameter array for
7497 // the inreg arguments. All other arguments are allocated a multiple of 8
7501 class SparcV9ABIInfo : public ABIInfo {
7503 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7506 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
7507 void computeInfo(CGFunctionInfo &FI) const override;
7508 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7509 QualType Ty) const override;
7511 // Coercion type builder for structs passed in registers. The coercion type
7512 // serves two purposes:
7514 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
7516 // 2. Expose aligned floating point elements as first-level elements, so the
7517 // code generator knows to pass them in floating point registers.
7519 // We also compute the InReg flag which indicates that the struct contains
7520 // aligned 32-bit floats.
7522 struct CoerceBuilder {
7523 llvm::LLVMContext &Context;
7524 const llvm::DataLayout &DL;
7525 SmallVector<llvm::Type*, 8> Elems;
7529 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
7530 : Context(c), DL(dl), Size(0), InReg(false) {}
7532 // Pad Elems with integers until Size is ToSize.
7533 void pad(uint64_t ToSize) {
7534 assert(ToSize >= Size && "Cannot remove elements");
7538 // Finish the current 64-bit word.
7539 uint64_t Aligned = llvm::alignTo(Size, 64);
7540 if (Aligned > Size && Aligned <= ToSize) {
7541 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
7545 // Add whole 64-bit words.
7546 while (Size + 64 <= ToSize) {
7547 Elems.push_back(llvm::Type::getInt64Ty(Context));
7551 // Final in-word padding.
7552 if (Size < ToSize) {
7553 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
7558 // Add a floating point element at Offset.
7559 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
7560 // Unaligned floats are treated as integers.
7563 // The InReg flag is only required if there are any floats < 64 bits.
7567 Elems.push_back(Ty);
7568 Size = Offset + Bits;
7571 // Add a struct type to the coercion type, starting at Offset (in bits).
7572 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
7573 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
7574 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
7575 llvm::Type *ElemTy = StrTy->getElementType(i);
7576 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
7577 switch (ElemTy->getTypeID()) {
7578 case llvm::Type::StructTyID:
7579 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
7581 case llvm::Type::FloatTyID:
7582 addFloat(ElemOffset, ElemTy, 32);
7584 case llvm::Type::DoubleTyID:
7585 addFloat(ElemOffset, ElemTy, 64);
7587 case llvm::Type::FP128TyID:
7588 addFloat(ElemOffset, ElemTy, 128);
7590 case llvm::Type::PointerTyID:
7591 if (ElemOffset % 64 == 0) {
7593 Elems.push_back(ElemTy);
7603 // Check if Ty is a usable substitute for the coercion type.
7604 bool isUsableType(llvm::StructType *Ty) const {
7605 return llvm::makeArrayRef(Elems) == Ty->elements();
7608 // Get the coercion type as a literal struct type.
7609 llvm::Type *getType() const {
7610 if (Elems.size() == 1)
7611 return Elems.front();
7613 return llvm::StructType::get(Context, Elems);
7617 } // end anonymous namespace
7620 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
7621 if (Ty->isVoidType())
7622 return ABIArgInfo::getIgnore();
7624 uint64_t Size = getContext().getTypeSize(Ty);
7626 // Anything too big to fit in registers is passed with an explicit indirect
7627 // pointer / sret pointer.
7628 if (Size > SizeLimit)
7629 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7631 // Treat an enum type as its underlying type.
7632 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7633 Ty = EnumTy->getDecl()->getIntegerType();
7635 // Integer types smaller than a register are extended.
7636 if (Size < 64 && Ty->isIntegerType())
7637 return ABIArgInfo::getExtend();
7639 // Other non-aggregates go in registers.
7640 if (!isAggregateTypeForABI(Ty))
7641 return ABIArgInfo::getDirect();
7643 // If a C++ object has either a non-trivial copy constructor or a non-trivial
7644 // destructor, it is passed with an explicit indirect pointer / sret pointer.
7645 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7646 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7648 // This is a small aggregate type that should be passed in registers.
7649 // Build a coercion type from the LLVM struct type.
7650 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7652 return ABIArgInfo::getDirect();
7654 CoerceBuilder CB(getVMContext(), getDataLayout());
7655 CB.addStruct(0, StrTy);
7656 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
7658 // Try to use the original type for coercion.
7659 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
7662 return ABIArgInfo::getDirectInReg(CoerceTy);
7664 return ABIArgInfo::getDirect(CoerceTy);
7667 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7668 QualType Ty) const {
7669 ABIArgInfo AI = classifyType(Ty, 16 * 8);
7670 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7671 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7672 AI.setCoerceToType(ArgTy);
7674 CharUnits SlotSize = CharUnits::fromQuantity(8);
7676 CGBuilderTy &Builder = CGF.Builder;
7677 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
7678 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
7680 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
7682 Address ArgAddr = Address::invalid();
7684 switch (AI.getKind()) {
7685 case ABIArgInfo::Expand:
7686 case ABIArgInfo::CoerceAndExpand:
7687 case ABIArgInfo::InAlloca:
7688 llvm_unreachable("Unsupported ABI kind for va_arg");
7690 case ABIArgInfo::Extend: {
7692 CharUnits Offset = SlotSize - TypeInfo.first;
7693 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
7697 case ABIArgInfo::Direct: {
7698 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
7699 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
7704 case ABIArgInfo::Indirect:
7706 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
7707 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
7711 case ABIArgInfo::Ignore:
7712 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
7716 llvm::Value *NextPtr =
7717 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
7718 Builder.CreateStore(NextPtr, VAListAddr);
7720 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
7723 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7724 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
7725 for (auto &I : FI.arguments())
7726 I.info = classifyType(I.type, 16 * 8);
7730 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
7732 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
7733 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
7735 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
7739 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7740 llvm::Value *Address) const override;
7742 } // end anonymous namespace
7745 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7746 llvm::Value *Address) const {
7747 // This is calculated from the LLVM and GCC tables and verified
7748 // against gcc output. AFAIK all ABIs use the same encoding.
7750 CodeGen::CGBuilderTy &Builder = CGF.Builder;
7752 llvm::IntegerType *i8 = CGF.Int8Ty;
7753 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
7754 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
7756 // 0-31: the 8-byte general-purpose registers
7757 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
7759 // 32-63: f0-31, the 4-byte floating-point registers
7760 AssignToArrayRange(Builder, Address, Four8, 32, 63);
7770 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
7772 // 72-87: d0-15, the 8-byte floating-point registers
7773 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
7779 //===----------------------------------------------------------------------===//
7780 // XCore ABI Implementation
7781 //===----------------------------------------------------------------------===//
7785 /// A SmallStringEnc instance is used to build up the TypeString by passing
7786 /// it by reference between functions that append to it.
7787 typedef llvm::SmallString<128> SmallStringEnc;
7789 /// TypeStringCache caches the meta encodings of Types.
7791 /// The reason for caching TypeStrings is two fold:
7792 /// 1. To cache a type's encoding for later uses;
7793 /// 2. As a means to break recursive member type inclusion.
7795 /// A cache Entry can have a Status of:
7796 /// NonRecursive: The type encoding is not recursive;
7797 /// Recursive: The type encoding is recursive;
7798 /// Incomplete: An incomplete TypeString;
7799 /// IncompleteUsed: An incomplete TypeString that has been used in a
7800 /// Recursive type encoding.
7802 /// A NonRecursive entry will have all of its sub-members expanded as fully
7803 /// as possible. Whilst it may contain types which are recursive, the type
7804 /// itself is not recursive and thus its encoding may be safely used whenever
7805 /// the type is encountered.
7807 /// A Recursive entry will have all of its sub-members expanded as fully as
7808 /// possible. The type itself is recursive and it may contain other types which
7809 /// are recursive. The Recursive encoding must not be used during the expansion
7810 /// of a recursive type's recursive branch. For simplicity the code uses
7811 /// IncompleteCount to reject all usage of Recursive encodings for member types.
7813 /// An Incomplete entry is always a RecordType and only encodes its
7814 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
7815 /// are placed into the cache during type expansion as a means to identify and
7816 /// handle recursive inclusion of types as sub-members. If there is recursion
7817 /// the entry becomes IncompleteUsed.
7819 /// During the expansion of a RecordType's members:
7821 /// If the cache contains a NonRecursive encoding for the member type, the
7822 /// cached encoding is used;
7824 /// If the cache contains a Recursive encoding for the member type, the
7825 /// cached encoding is 'Swapped' out, as it may be incorrect, and...
7827 /// If the member is a RecordType, an Incomplete encoding is placed into the
7828 /// cache to break potential recursive inclusion of itself as a sub-member;
7830 /// Once a member RecordType has been expanded, its temporary incomplete
7831 /// entry is removed from the cache. If a Recursive encoding was swapped out
7832 /// it is swapped back in;
7834 /// If an incomplete entry is used to expand a sub-member, the incomplete
7835 /// entry is marked as IncompleteUsed. The cache keeps count of how many
7836 /// IncompleteUsed entries it currently contains in IncompleteUsedCount;
7838 /// If a member's encoding is found to be a NonRecursive or Recursive viz:
7839 /// IncompleteUsedCount==0, the member's encoding is added to the cache.
7840 /// Else the member is part of a recursive type and thus the recursion has
7841 /// been exited too soon for the encoding to be correct for the member.
7843 class TypeStringCache {
7844 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
7846 std::string Str; // The encoded TypeString for the type.
7847 enum Status State; // Information about the encoding in 'Str'.
7848 std::string Swapped; // A temporary place holder for a Recursive encoding
7849 // during the expansion of RecordType's members.
7851 std::map<const IdentifierInfo *, struct Entry> Map;
7852 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
7853 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
7855 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
7856 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
7857 bool removeIncomplete(const IdentifierInfo *ID);
7858 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
7860 StringRef lookupStr(const IdentifierInfo *ID);
7863 /// TypeString encodings for enum & union fields must be order.
7864 /// FieldEncoding is a helper for this ordering process.
7865 class FieldEncoding {
7869 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
7870 StringRef str() { return Enc; }
7871 bool operator<(const FieldEncoding &rhs) const {
7872 if (HasName != rhs.HasName) return HasName;
7873 return Enc < rhs.Enc;
7877 class XCoreABIInfo : public DefaultABIInfo {
7879 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7880 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7881 QualType Ty) const override;
7884 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
7885 mutable TypeStringCache TSC;
7887 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
7888 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
7889 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7890 CodeGen::CodeGenModule &M) const override;
7893 } // End anonymous namespace.
7895 // TODO: this implementation is likely now redundant with the default
7897 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7898 QualType Ty) const {
7899 CGBuilderTy &Builder = CGF.Builder;
7902 CharUnits SlotSize = CharUnits::fromQuantity(4);
7903 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
7905 // Handle the argument.
7906 ABIArgInfo AI = classifyArgumentType(Ty);
7907 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
7908 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7909 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7910 AI.setCoerceToType(ArgTy);
7911 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
7913 Address Val = Address::invalid();
7914 CharUnits ArgSize = CharUnits::Zero();
7915 switch (AI.getKind()) {
7916 case ABIArgInfo::Expand:
7917 case ABIArgInfo::CoerceAndExpand:
7918 case ABIArgInfo::InAlloca:
7919 llvm_unreachable("Unsupported ABI kind for va_arg");
7920 case ABIArgInfo::Ignore:
7921 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
7922 ArgSize = CharUnits::Zero();
7924 case ABIArgInfo::Extend:
7925 case ABIArgInfo::Direct:
7926 Val = Builder.CreateBitCast(AP, ArgPtrTy);
7927 ArgSize = CharUnits::fromQuantity(
7928 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
7929 ArgSize = ArgSize.alignTo(SlotSize);
7931 case ABIArgInfo::Indirect:
7932 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
7933 Val = Address(Builder.CreateLoad(Val), TypeAlign);
7938 // Increment the VAList.
7939 if (!ArgSize.isZero()) {
7941 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
7942 Builder.CreateStore(APN, VAListAddr);
7948 /// During the expansion of a RecordType, an incomplete TypeString is placed
7949 /// into the cache as a means to identify and break recursion.
7950 /// If there is a Recursive encoding in the cache, it is swapped out and will
7951 /// be reinserted by removeIncomplete().
7952 /// All other types of encoding should have been used rather than arriving here.
7953 void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
7954 std::string StubEnc) {
7958 assert( (E.Str.empty() || E.State == Recursive) &&
7959 "Incorrectly use of addIncomplete");
7960 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
7961 E.Swapped.swap(E.Str); // swap out the Recursive
7962 E.Str.swap(StubEnc);
7963 E.State = Incomplete;
7967 /// Once the RecordType has been expanded, the temporary incomplete TypeString
7968 /// must be removed from the cache.
7969 /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
7970 /// Returns true if the RecordType was defined recursively.
7971 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
7974 auto I = Map.find(ID);
7975 assert(I != Map.end() && "Entry not present");
7976 Entry &E = I->second;
7977 assert( (E.State == Incomplete ||
7978 E.State == IncompleteUsed) &&
7979 "Entry must be an incomplete type");
7980 bool IsRecursive = false;
7981 if (E.State == IncompleteUsed) {
7982 // We made use of our Incomplete encoding, thus we are recursive.
7984 --IncompleteUsedCount;
7986 if (E.Swapped.empty())
7989 // Swap the Recursive back.
7990 E.Swapped.swap(E.Str);
7992 E.State = Recursive;
7998 /// Add the encoded TypeString to the cache only if it is NonRecursive or
7999 /// Recursive (viz: all sub-members were expanded as fully as possible).
8000 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
8002 if (!ID || IncompleteUsedCount)
8003 return; // No key or it is is an incomplete sub-type so don't add.
8005 if (IsRecursive && !E.Str.empty()) {
8006 assert(E.State==Recursive && E.Str.size() == Str.size() &&
8007 "This is not the same Recursive entry");
8008 // The parent container was not recursive after all, so we could have used
8009 // this Recursive sub-member entry after all, but we assumed the worse when
8010 // we started viz: IncompleteCount!=0.
8013 assert(E.Str.empty() && "Entry already present");
8015 E.State = IsRecursive? Recursive : NonRecursive;
8018 /// Return a cached TypeString encoding for the ID. If there isn't one, or we
8019 /// are recursively expanding a type (IncompleteCount != 0) and the cached
8020 /// encoding is Recursive, return an empty StringRef.
8021 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
8023 return StringRef(); // We have no key.
8024 auto I = Map.find(ID);
8026 return StringRef(); // We have no encoding.
8027 Entry &E = I->second;
8028 if (E.State == Recursive && IncompleteCount)
8029 return StringRef(); // We don't use Recursive encodings for member types.
8031 if (E.State == Incomplete) {
8032 // The incomplete type is being used to break out of recursion.
8033 E.State = IncompleteUsed;
8034 ++IncompleteUsedCount;
8039 /// The XCore ABI includes a type information section that communicates symbol
8040 /// type information to the linker. The linker uses this information to verify
8041 /// safety/correctness of things such as array bound and pointers et al.
8042 /// The ABI only requires C (and XC) language modules to emit TypeStrings.
8043 /// This type information (TypeString) is emitted into meta data for all global
8044 /// symbols: definitions, declarations, functions & variables.
8046 /// The TypeString carries type, qualifier, name, size & value details.
8047 /// Please see 'Tools Development Guide' section 2.16.2 for format details:
8048 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
8049 /// The output is tested by test/CodeGen/xcore-stringtype.c.
8051 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8052 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
8054 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
8055 void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8056 CodeGen::CodeGenModule &CGM) const {
8058 if (getTypeString(Enc, D, CGM, TSC)) {
8059 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
8060 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
8061 llvm::MDString::get(Ctx, Enc.str())};
8062 llvm::NamedMDNode *MD =
8063 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
8064 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
8068 //===----------------------------------------------------------------------===//
8069 // SPIR ABI Implementation
8070 //===----------------------------------------------------------------------===//
8073 class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
8075 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8076 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
8077 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8078 CodeGen::CodeGenModule &M) const override;
8079 unsigned getOpenCLKernelCallingConv() const override;
8082 } // End anonymous namespace.
8086 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
8087 DefaultABIInfo SPIRABI(CGM.getTypes());
8088 SPIRABI.computeInfo(FI);
8093 /// Emit SPIR specific metadata: OpenCL and SPIR version.
8094 void SPIRTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8095 CodeGen::CodeGenModule &CGM) const {
8096 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
8097 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(Ctx);
8098 llvm::Module &M = CGM.getModule();
8099 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
8100 // opencl.spir.version named metadata.
8101 llvm::Metadata *SPIRVerElts[] = {
8102 llvm::ConstantAsMetadata::get(
8103 llvm::ConstantInt::get(Int32Ty, CGM.getLangOpts().OpenCLVersion / 100)),
8104 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
8105 Int32Ty, (CGM.getLangOpts().OpenCLVersion / 100 > 1) ? 0 : 2))};
8106 llvm::NamedMDNode *SPIRVerMD =
8107 M.getOrInsertNamedMetadata("opencl.spir.version");
8108 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
8109 appendOpenCLVersionMD(CGM);
8112 static void appendOpenCLVersionMD(CodeGen::CodeGenModule &CGM) {
8113 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
8114 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(Ctx);
8115 llvm::Module &M = CGM.getModule();
8116 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
8117 // opencl.ocl.version named metadata node.
8118 llvm::Metadata *OCLVerElts[] = {
8119 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
8120 Int32Ty, CGM.getLangOpts().OpenCLVersion / 100)),
8121 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
8122 Int32Ty, (CGM.getLangOpts().OpenCLVersion % 100) / 10))};
8123 llvm::NamedMDNode *OCLVerMD =
8124 M.getOrInsertNamedMetadata("opencl.ocl.version");
8125 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
8128 unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
8129 return llvm::CallingConv::SPIR_KERNEL;
8132 static bool appendType(SmallStringEnc &Enc, QualType QType,
8133 const CodeGen::CodeGenModule &CGM,
8134 TypeStringCache &TSC);
8136 /// Helper function for appendRecordType().
8137 /// Builds a SmallVector containing the encoded field types in declaration
8139 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
8140 const RecordDecl *RD,
8141 const CodeGen::CodeGenModule &CGM,
8142 TypeStringCache &TSC) {
8143 for (const auto *Field : RD->fields()) {
8146 Enc += Field->getName();
8148 if (Field->isBitField()) {
8150 llvm::raw_svector_ostream OS(Enc);
8151 OS << Field->getBitWidthValue(CGM.getContext());
8154 if (!appendType(Enc, Field->getType(), CGM, TSC))
8156 if (Field->isBitField())
8159 FE.emplace_back(!Field->getName().empty(), Enc);
8164 /// Appends structure and union types to Enc and adds encoding to cache.
8165 /// Recursively calls appendType (via extractFieldType) for each field.
8166 /// Union types have their fields ordered according to the ABI.
8167 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
8168 const CodeGen::CodeGenModule &CGM,
8169 TypeStringCache &TSC, const IdentifierInfo *ID) {
8170 // Append the cached TypeString if we have one.
8171 StringRef TypeString = TSC.lookupStr(ID);
8172 if (!TypeString.empty()) {
8177 // Start to emit an incomplete TypeString.
8178 size_t Start = Enc.size();
8179 Enc += (RT->isUnionType()? 'u' : 's');
8182 Enc += ID->getName();
8185 // We collect all encoded fields and order as necessary.
8186 bool IsRecursive = false;
8187 const RecordDecl *RD = RT->getDecl()->getDefinition();
8188 if (RD && !RD->field_empty()) {
8189 // An incomplete TypeString stub is placed in the cache for this RecordType
8190 // so that recursive calls to this RecordType will use it whilst building a
8191 // complete TypeString for this RecordType.
8192 SmallVector<FieldEncoding, 16> FE;
8193 std::string StubEnc(Enc.substr(Start).str());
8194 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
8195 TSC.addIncomplete(ID, std::move(StubEnc));
8196 if (!extractFieldType(FE, RD, CGM, TSC)) {
8197 (void) TSC.removeIncomplete(ID);
8200 IsRecursive = TSC.removeIncomplete(ID);
8201 // The ABI requires unions to be sorted but not structures.
8202 // See FieldEncoding::operator< for sort algorithm.
8203 if (RT->isUnionType())
8204 std::sort(FE.begin(), FE.end());
8205 // We can now complete the TypeString.
8206 unsigned E = FE.size();
8207 for (unsigned I = 0; I != E; ++I) {
8214 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
8218 /// Appends enum types to Enc and adds the encoding to the cache.
8219 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
8220 TypeStringCache &TSC,
8221 const IdentifierInfo *ID) {
8222 // Append the cached TypeString if we have one.
8223 StringRef TypeString = TSC.lookupStr(ID);
8224 if (!TypeString.empty()) {
8229 size_t Start = Enc.size();
8232 Enc += ID->getName();
8235 // We collect all encoded enumerations and order them alphanumerically.
8236 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
8237 SmallVector<FieldEncoding, 16> FE;
8238 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
8240 SmallStringEnc EnumEnc;
8242 EnumEnc += I->getName();
8244 I->getInitVal().toString(EnumEnc);
8246 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
8248 std::sort(FE.begin(), FE.end());
8249 unsigned E = FE.size();
8250 for (unsigned I = 0; I != E; ++I) {
8257 TSC.addIfComplete(ID, Enc.substr(Start), false);
8261 /// Appends type's qualifier to Enc.
8262 /// This is done prior to appending the type's encoding.
8263 static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
8264 // Qualifiers are emitted in alphabetical order.
8265 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
8267 if (QT.isConstQualified())
8269 if (QT.isRestrictQualified())
8271 if (QT.isVolatileQualified())
8273 Enc += Table[Lookup];
8276 /// Appends built-in types to Enc.
8277 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
8278 const char *EncType;
8279 switch (BT->getKind()) {
8280 case BuiltinType::Void:
8283 case BuiltinType::Bool:
8286 case BuiltinType::Char_U:
8289 case BuiltinType::UChar:
8292 case BuiltinType::SChar:
8295 case BuiltinType::UShort:
8298 case BuiltinType::Short:
8301 case BuiltinType::UInt:
8304 case BuiltinType::Int:
8307 case BuiltinType::ULong:
8310 case BuiltinType::Long:
8313 case BuiltinType::ULongLong:
8316 case BuiltinType::LongLong:
8319 case BuiltinType::Float:
8322 case BuiltinType::Double:
8325 case BuiltinType::LongDouble:
8335 /// Appends a pointer encoding to Enc before calling appendType for the pointee.
8336 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
8337 const CodeGen::CodeGenModule &CGM,
8338 TypeStringCache &TSC) {
8340 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
8346 /// Appends array encoding to Enc before calling appendType for the element.
8347 static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
8348 const ArrayType *AT,
8349 const CodeGen::CodeGenModule &CGM,
8350 TypeStringCache &TSC, StringRef NoSizeEnc) {
8351 if (AT->getSizeModifier() != ArrayType::Normal)
8354 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
8355 CAT->getSize().toStringUnsigned(Enc);
8357 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
8359 // The Qualifiers should be attached to the type rather than the array.
8360 appendQualifier(Enc, QT);
8361 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
8367 /// Appends a function encoding to Enc, calling appendType for the return type
8368 /// and the arguments.
8369 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
8370 const CodeGen::CodeGenModule &CGM,
8371 TypeStringCache &TSC) {
8373 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
8376 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
8377 // N.B. we are only interested in the adjusted param types.
8378 auto I = FPT->param_type_begin();
8379 auto E = FPT->param_type_end();
8382 if (!appendType(Enc, *I, CGM, TSC))
8388 if (FPT->isVariadic())
8391 if (FPT->isVariadic())
8401 /// Handles the type's qualifier before dispatching a call to handle specific
8403 static bool appendType(SmallStringEnc &Enc, QualType QType,
8404 const CodeGen::CodeGenModule &CGM,
8405 TypeStringCache &TSC) {
8407 QualType QT = QType.getCanonicalType();
8409 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
8410 // The Qualifiers should be attached to the type rather than the array.
8411 // Thus we don't call appendQualifier() here.
8412 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
8414 appendQualifier(Enc, QT);
8416 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
8417 return appendBuiltinType(Enc, BT);
8419 if (const PointerType *PT = QT->getAs<PointerType>())
8420 return appendPointerType(Enc, PT, CGM, TSC);
8422 if (const EnumType *ET = QT->getAs<EnumType>())
8423 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
8425 if (const RecordType *RT = QT->getAsStructureType())
8426 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8428 if (const RecordType *RT = QT->getAsUnionType())
8429 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8431 if (const FunctionType *FT = QT->getAs<FunctionType>())
8432 return appendFunctionType(Enc, FT, CGM, TSC);
8437 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8438 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
8442 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8443 if (FD->getLanguageLinkage() != CLanguageLinkage)
8445 return appendType(Enc, FD->getType(), CGM, TSC);
8448 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8449 if (VD->getLanguageLinkage() != CLanguageLinkage)
8451 QualType QT = VD->getType().getCanonicalType();
8452 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
8453 // Global ArrayTypes are given a size of '*' if the size is unknown.
8454 // The Qualifiers should be attached to the type rather than the array.
8455 // Thus we don't call appendQualifier() here.
8456 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
8458 return appendType(Enc, QT, CGM, TSC);
8464 //===----------------------------------------------------------------------===//
8466 //===----------------------------------------------------------------------===//
8468 bool CodeGenModule::supportsCOMDAT() const {
8469 return getTriple().supportsCOMDAT();
8472 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
8473 if (TheTargetCodeGenInfo)
8474 return *TheTargetCodeGenInfo;
8476 // Helper to set the unique_ptr while still keeping the return value.
8477 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
8478 this->TheTargetCodeGenInfo.reset(P);
8482 const llvm::Triple &Triple = getTarget().getTriple();
8483 switch (Triple.getArch()) {
8485 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
8487 case llvm::Triple::le32:
8488 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
8489 case llvm::Triple::mips:
8490 case llvm::Triple::mipsel:
8491 if (Triple.getOS() == llvm::Triple::NaCl)
8492 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
8493 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
8495 case llvm::Triple::mips64:
8496 case llvm::Triple::mips64el:
8497 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
8499 case llvm::Triple::avr:
8500 return SetCGInfo(new AVRTargetCodeGenInfo(Types));
8502 case llvm::Triple::aarch64:
8503 case llvm::Triple::aarch64_be: {
8504 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
8505 if (getTarget().getABI() == "darwinpcs")
8506 Kind = AArch64ABIInfo::DarwinPCS;
8508 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
8511 case llvm::Triple::wasm32:
8512 case llvm::Triple::wasm64:
8513 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
8515 case llvm::Triple::arm:
8516 case llvm::Triple::armeb:
8517 case llvm::Triple::thumb:
8518 case llvm::Triple::thumbeb: {
8519 if (Triple.getOS() == llvm::Triple::Win32) {
8521 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
8524 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
8525 StringRef ABIStr = getTarget().getABI();
8526 if (ABIStr == "apcs-gnu")
8527 Kind = ARMABIInfo::APCS;
8528 else if (ABIStr == "aapcs16")
8529 Kind = ARMABIInfo::AAPCS16_VFP;
8530 else if (CodeGenOpts.FloatABI == "hard" ||
8531 (CodeGenOpts.FloatABI != "soft" &&
8532 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
8533 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
8534 Triple.getEnvironment() == llvm::Triple::EABIHF)))
8535 Kind = ARMABIInfo::AAPCS_VFP;
8537 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
8540 case llvm::Triple::ppc:
8542 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
8543 case llvm::Triple::ppc64:
8544 if (Triple.isOSBinFormatELF()) {
8545 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
8546 if (getTarget().getABI() == "elfv2")
8547 Kind = PPC64_SVR4_ABIInfo::ELFv2;
8548 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
8549 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
8551 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8554 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
8555 case llvm::Triple::ppc64le: {
8556 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
8557 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
8558 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
8559 Kind = PPC64_SVR4_ABIInfo::ELFv1;
8560 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
8561 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
8563 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8567 case llvm::Triple::nvptx:
8568 case llvm::Triple::nvptx64:
8569 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
8571 case llvm::Triple::msp430:
8572 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
8574 case llvm::Triple::systemz: {
8575 bool HasVector = getTarget().getABI() == "vector";
8576 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
8579 case llvm::Triple::tce:
8580 case llvm::Triple::tcele:
8581 return SetCGInfo(new TCETargetCodeGenInfo(Types));
8583 case llvm::Triple::x86: {
8584 bool IsDarwinVectorABI = Triple.isOSDarwin();
8585 bool RetSmallStructInRegABI =
8586 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
8587 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
8589 if (Triple.getOS() == llvm::Triple::Win32) {
8590 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
8591 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8592 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
8594 return SetCGInfo(new X86_32TargetCodeGenInfo(
8595 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8596 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
8597 CodeGenOpts.FloatABI == "soft"));
8601 case llvm::Triple::x86_64: {
8602 StringRef ABI = getTarget().getABI();
8603 X86AVXABILevel AVXLevel =
8605 ? X86AVXABILevel::AVX512
8606 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
8608 switch (Triple.getOS()) {
8609 case llvm::Triple::Win32:
8610 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
8611 case llvm::Triple::PS4:
8612 return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
8614 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
8617 case llvm::Triple::hexagon:
8618 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
8619 case llvm::Triple::lanai:
8620 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
8621 case llvm::Triple::r600:
8622 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
8623 case llvm::Triple::amdgcn:
8624 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
8625 case llvm::Triple::sparc:
8626 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
8627 case llvm::Triple::sparcv9:
8628 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
8629 case llvm::Triple::xcore:
8630 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
8631 case llvm::Triple::spir:
8632 case llvm::Triple::spir64:
8633 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));