1 //===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // These classes wrap the information about a call or function 10 // definition used to handle ABI compliancy. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "TargetInfo.h" 15 #include "ABIInfo.h" 16 #include "CGBlocks.h" 17 #include "CGCXXABI.h" 18 #include "CGValue.h" 19 #include "CodeGenFunction.h" 20 #include "clang/AST/Attr.h" 21 #include "clang/AST/RecordLayout.h" 22 #include "clang/Basic/CodeGenOptions.h" 23 #include "clang/CodeGen/CGFunctionInfo.h" 24 #include "clang/CodeGen/SwiftCallingConv.h" 25 #include "llvm/ADT/SmallBitVector.h" 26 #include "llvm/ADT/StringExtras.h" 27 #include "llvm/ADT/StringSwitch.h" 28 #include "llvm/ADT/Triple.h" 29 #include "llvm/ADT/Twine.h" 30 #include "llvm/IR/DataLayout.h" 31 #include "llvm/IR/IntrinsicsNVPTX.h" 32 #include "llvm/IR/Type.h" 33 #include "llvm/Support/raw_ostream.h" 34 #include <algorithm> // std::sort 35 36 using namespace clang; 37 using namespace CodeGen; 38 39 // Helper for coercing an aggregate argument or return value into an integer 40 // array of the same size (including padding) and alignment. This alternate 41 // coercion happens only for the RenderScript ABI and can be removed after 42 // runtimes that rely on it are no longer supported. 43 // 44 // RenderScript assumes that the size of the argument / return value in the IR 45 // is the same as the size of the corresponding qualified type. This helper 46 // coerces the aggregate type into an array of the same size (including 47 // padding). This coercion is used in lieu of expansion of struct members or 48 // other canonical coercions that return a coerced-type of larger size. 49 // 50 // Ty - The argument / return value type 51 // Context - The associated ASTContext 52 // LLVMContext - The associated LLVMContext 53 static ABIArgInfo coerceToIntArray(QualType Ty, 54 ASTContext &Context, 55 llvm::LLVMContext &LLVMContext) { 56 // Alignment and Size are measured in bits. 57 const uint64_t Size = Context.getTypeSize(Ty); 58 const uint64_t Alignment = Context.getTypeAlign(Ty); 59 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment); 60 const uint64_t NumElements = (Size + Alignment - 1) / Alignment; 61 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements)); 62 } 63 64 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder, 65 llvm::Value *Array, 66 llvm::Value *Value, 67 unsigned FirstIndex, 68 unsigned LastIndex) { 69 // Alternatively, we could emit this as a loop in the source. 70 for (unsigned I = FirstIndex; I <= LastIndex; ++I) { 71 llvm::Value *Cell = 72 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I); 73 Builder.CreateAlignedStore(Value, Cell, CharUnits::One()); 74 } 75 } 76 77 static bool isAggregateTypeForABI(QualType T) { 78 return !CodeGenFunction::hasScalarEvaluationKind(T) || 79 T->isMemberFunctionPointerType(); 80 } 81 82 ABIArgInfo 83 ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByRef, bool Realign, 84 llvm::Type *Padding) const { 85 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty), 86 ByRef, Realign, Padding); 87 } 88 89 ABIArgInfo 90 ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const { 91 return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty), 92 /*ByRef*/ false, Realign); 93 } 94 95 Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 96 QualType Ty) const { 97 return Address::invalid(); 98 } 99 100 ABIInfo::~ABIInfo() {} 101 102 /// Does the given lowering require more than the given number of 103 /// registers when expanded? 104 /// 105 /// This is intended to be the basis of a reasonable basic implementation 106 /// of should{Pass,Return}IndirectlyForSwift. 107 /// 108 /// For most targets, a limit of four total registers is reasonable; this 109 /// limits the amount of code required in order to move around the value 110 /// in case it wasn't produced immediately prior to the call by the caller 111 /// (or wasn't produced in exactly the right registers) or isn't used 112 /// immediately within the callee. But some targets may need to further 113 /// limit the register count due to an inability to support that many 114 /// return registers. 115 static bool occupiesMoreThan(CodeGenTypes &cgt, 116 ArrayRef<llvm::Type*> scalarTypes, 117 unsigned maxAllRegisters) { 118 unsigned intCount = 0, fpCount = 0; 119 for (llvm::Type *type : scalarTypes) { 120 if (type->isPointerTy()) { 121 intCount++; 122 } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) { 123 auto ptrWidth = cgt.getTarget().getPointerWidth(0); 124 intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth; 125 } else { 126 assert(type->isVectorTy() || type->isFloatingPointTy()); 127 fpCount++; 128 } 129 } 130 131 return (intCount + fpCount > maxAllRegisters); 132 } 133 134 bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize, 135 llvm::Type *eltTy, 136 unsigned numElts) const { 137 // The default implementation of this assumes that the target guarantees 138 // 128-bit SIMD support but nothing more. 139 return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16); 140 } 141 142 static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT, 143 CGCXXABI &CXXABI) { 144 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 145 if (!RD) { 146 if (!RT->getDecl()->canPassInRegisters()) 147 return CGCXXABI::RAA_Indirect; 148 return CGCXXABI::RAA_Default; 149 } 150 return CXXABI.getRecordArgABI(RD); 151 } 152 153 static CGCXXABI::RecordArgABI getRecordArgABI(QualType T, 154 CGCXXABI &CXXABI) { 155 const RecordType *RT = T->getAs<RecordType>(); 156 if (!RT) 157 return CGCXXABI::RAA_Default; 158 return getRecordArgABI(RT, CXXABI); 159 } 160 161 static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI, 162 const ABIInfo &Info) { 163 QualType Ty = FI.getReturnType(); 164 165 if (const auto *RT = Ty->getAs<RecordType>()) 166 if (!isa<CXXRecordDecl>(RT->getDecl()) && 167 !RT->getDecl()->canPassInRegisters()) { 168 FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty); 169 return true; 170 } 171 172 return CXXABI.classifyReturnType(FI); 173 } 174 175 /// Pass transparent unions as if they were the type of the first element. Sema 176 /// should ensure that all elements of the union have the same "machine type". 177 static QualType useFirstFieldIfTransparentUnion(QualType Ty) { 178 if (const RecordType *UT = Ty->getAsUnionType()) { 179 const RecordDecl *UD = UT->getDecl(); 180 if (UD->hasAttr<TransparentUnionAttr>()) { 181 assert(!UD->field_empty() && "sema created an empty transparent union"); 182 return UD->field_begin()->getType(); 183 } 184 } 185 return Ty; 186 } 187 188 CGCXXABI &ABIInfo::getCXXABI() const { 189 return CGT.getCXXABI(); 190 } 191 192 ASTContext &ABIInfo::getContext() const { 193 return CGT.getContext(); 194 } 195 196 llvm::LLVMContext &ABIInfo::getVMContext() const { 197 return CGT.getLLVMContext(); 198 } 199 200 const llvm::DataLayout &ABIInfo::getDataLayout() const { 201 return CGT.getDataLayout(); 202 } 203 204 const TargetInfo &ABIInfo::getTarget() const { 205 return CGT.getTarget(); 206 } 207 208 const CodeGenOptions &ABIInfo::getCodeGenOpts() const { 209 return CGT.getCodeGenOpts(); 210 } 211 212 bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); } 213 214 bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 215 return false; 216 } 217 218 bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 219 uint64_t Members) const { 220 return false; 221 } 222 223 LLVM_DUMP_METHOD void ABIArgInfo::dump() const { 224 raw_ostream &OS = llvm::errs(); 225 OS << "(ABIArgInfo Kind="; 226 switch (TheKind) { 227 case Direct: 228 OS << "Direct Type="; 229 if (llvm::Type *Ty = getCoerceToType()) 230 Ty->print(OS); 231 else 232 OS << "null"; 233 break; 234 case Extend: 235 OS << "Extend"; 236 break; 237 case Ignore: 238 OS << "Ignore"; 239 break; 240 case InAlloca: 241 OS << "InAlloca Offset=" << getInAllocaFieldIndex(); 242 break; 243 case Indirect: 244 OS << "Indirect Align=" << getIndirectAlign().getQuantity() 245 << " ByVal=" << getIndirectByVal() 246 << " Realign=" << getIndirectRealign(); 247 break; 248 case Expand: 249 OS << "Expand"; 250 break; 251 case CoerceAndExpand: 252 OS << "CoerceAndExpand Type="; 253 getCoerceAndExpandType()->print(OS); 254 break; 255 } 256 OS << ")\n"; 257 } 258 259 // Dynamically round a pointer up to a multiple of the given alignment. 260 static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF, 261 llvm::Value *Ptr, 262 CharUnits Align) { 263 llvm::Value *PtrAsInt = Ptr; 264 // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align; 265 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy); 266 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt, 267 llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1)); 268 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt, 269 llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity())); 270 PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt, 271 Ptr->getType(), 272 Ptr->getName() + ".aligned"); 273 return PtrAsInt; 274 } 275 276 /// Emit va_arg for a platform using the common void* representation, 277 /// where arguments are simply emitted in an array of slots on the stack. 278 /// 279 /// This version implements the core direct-value passing rules. 280 /// 281 /// \param SlotSize - The size and alignment of a stack slot. 282 /// Each argument will be allocated to a multiple of this number of 283 /// slots, and all the slots will be aligned to this value. 284 /// \param AllowHigherAlign - The slot alignment is not a cap; 285 /// an argument type with an alignment greater than the slot size 286 /// will be emitted on a higher-alignment address, potentially 287 /// leaving one or more empty slots behind as padding. If this 288 /// is false, the returned address might be less-aligned than 289 /// DirectAlign. 290 static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF, 291 Address VAListAddr, 292 llvm::Type *DirectTy, 293 CharUnits DirectSize, 294 CharUnits DirectAlign, 295 CharUnits SlotSize, 296 bool AllowHigherAlign) { 297 // Cast the element type to i8* if necessary. Some platforms define 298 // va_list as a struct containing an i8* instead of just an i8*. 299 if (VAListAddr.getElementType() != CGF.Int8PtrTy) 300 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy); 301 302 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur"); 303 304 // If the CC aligns values higher than the slot size, do so if needed. 305 Address Addr = Address::invalid(); 306 if (AllowHigherAlign && DirectAlign > SlotSize) { 307 Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign), 308 DirectAlign); 309 } else { 310 Addr = Address(Ptr, SlotSize); 311 } 312 313 // Advance the pointer past the argument, then store that back. 314 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize); 315 Address NextPtr = 316 CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next"); 317 CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr); 318 319 // If the argument is smaller than a slot, and this is a big-endian 320 // target, the argument will be right-adjusted in its slot. 321 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() && 322 !DirectTy->isStructTy()) { 323 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize); 324 } 325 326 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy); 327 return Addr; 328 } 329 330 /// Emit va_arg for a platform using the common void* representation, 331 /// where arguments are simply emitted in an array of slots on the stack. 332 /// 333 /// \param IsIndirect - Values of this type are passed indirectly. 334 /// \param ValueInfo - The size and alignment of this type, generally 335 /// computed with getContext().getTypeInfoInChars(ValueTy). 336 /// \param SlotSizeAndAlign - The size and alignment of a stack slot. 337 /// Each argument will be allocated to a multiple of this number of 338 /// slots, and all the slots will be aligned to this value. 339 /// \param AllowHigherAlign - The slot alignment is not a cap; 340 /// an argument type with an alignment greater than the slot size 341 /// will be emitted on a higher-alignment address, potentially 342 /// leaving one or more empty slots behind as padding. 343 static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr, 344 QualType ValueTy, bool IsIndirect, 345 std::pair<CharUnits, CharUnits> ValueInfo, 346 CharUnits SlotSizeAndAlign, 347 bool AllowHigherAlign) { 348 // The size and alignment of the value that was passed directly. 349 CharUnits DirectSize, DirectAlign; 350 if (IsIndirect) { 351 DirectSize = CGF.getPointerSize(); 352 DirectAlign = CGF.getPointerAlign(); 353 } else { 354 DirectSize = ValueInfo.first; 355 DirectAlign = ValueInfo.second; 356 } 357 358 // Cast the address we've calculated to the right type. 359 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy); 360 if (IsIndirect) 361 DirectTy = DirectTy->getPointerTo(0); 362 363 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy, 364 DirectSize, DirectAlign, 365 SlotSizeAndAlign, 366 AllowHigherAlign); 367 368 if (IsIndirect) { 369 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second); 370 } 371 372 return Addr; 373 374 } 375 376 static Address emitMergePHI(CodeGenFunction &CGF, 377 Address Addr1, llvm::BasicBlock *Block1, 378 Address Addr2, llvm::BasicBlock *Block2, 379 const llvm::Twine &Name = "") { 380 assert(Addr1.getType() == Addr2.getType()); 381 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name); 382 PHI->addIncoming(Addr1.getPointer(), Block1); 383 PHI->addIncoming(Addr2.getPointer(), Block2); 384 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment()); 385 return Address(PHI, Align); 386 } 387 388 TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; } 389 390 // If someone can figure out a general rule for this, that would be great. 391 // It's probably just doomed to be platform-dependent, though. 392 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const { 393 // Verified for: 394 // x86-64 FreeBSD, Linux, Darwin 395 // x86-32 FreeBSD, Linux, Darwin 396 // PowerPC Linux, Darwin 397 // ARM Darwin (*not* EABI) 398 // AArch64 Linux 399 return 32; 400 } 401 402 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args, 403 const FunctionNoProtoType *fnType) const { 404 // The following conventions are known to require this to be false: 405 // x86_stdcall 406 // MIPS 407 // For everything else, we just prefer false unless we opt out. 408 return false; 409 } 410 411 void 412 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib, 413 llvm::SmallString<24> &Opt) const { 414 // This assumes the user is passing a library name like "rt" instead of a 415 // filename like "librt.a/so", and that they don't care whether it's static or 416 // dynamic. 417 Opt = "-l"; 418 Opt += Lib; 419 } 420 421 unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const { 422 // OpenCL kernels are called via an explicit runtime API with arguments 423 // set with clSetKernelArg(), not as normal sub-functions. 424 // Return SPIR_KERNEL by default as the kernel calling convention to 425 // ensure the fingerprint is fixed such way that each OpenCL argument 426 // gets one matching argument in the produced kernel function argument 427 // list to enable feasible implementation of clSetKernelArg() with 428 // aggregates etc. In case we would use the default C calling conv here, 429 // clSetKernelArg() might break depending on the target-specific 430 // conventions; different targets might split structs passed as values 431 // to multiple function arguments etc. 432 return llvm::CallingConv::SPIR_KERNEL; 433 } 434 435 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM, 436 llvm::PointerType *T, QualType QT) const { 437 return llvm::ConstantPointerNull::get(T); 438 } 439 440 LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM, 441 const VarDecl *D) const { 442 assert(!CGM.getLangOpts().OpenCL && 443 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && 444 "Address space agnostic languages only"); 445 return D ? D->getType().getAddressSpace() : LangAS::Default; 446 } 447 448 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast( 449 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr, 450 LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const { 451 // Since target may map different address spaces in AST to the same address 452 // space, an address space conversion may end up as a bitcast. 453 if (auto *C = dyn_cast<llvm::Constant>(Src)) 454 return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy); 455 // Try to preserve the source's name to make IR more readable. 456 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 457 Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : ""); 458 } 459 460 llvm::Constant * 461 TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src, 462 LangAS SrcAddr, LangAS DestAddr, 463 llvm::Type *DestTy) const { 464 // Since target may map different address spaces in AST to the same address 465 // space, an address space conversion may end up as a bitcast. 466 return llvm::ConstantExpr::getPointerCast(Src, DestTy); 467 } 468 469 llvm::SyncScope::ID 470 TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts, 471 SyncScope Scope, 472 llvm::AtomicOrdering Ordering, 473 llvm::LLVMContext &Ctx) const { 474 return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */ 475 } 476 477 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays); 478 479 /// isEmptyField - Return true iff a the field is "empty", that is it 480 /// is an unnamed bit-field or an (array of) empty record(s). 481 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD, 482 bool AllowArrays) { 483 if (FD->isUnnamedBitfield()) 484 return true; 485 486 QualType FT = FD->getType(); 487 488 // Constant arrays of empty records count as empty, strip them off. 489 // Constant arrays of zero length always count as empty. 490 if (AllowArrays) 491 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 492 if (AT->getSize() == 0) 493 return true; 494 FT = AT->getElementType(); 495 } 496 497 const RecordType *RT = FT->getAs<RecordType>(); 498 if (!RT) 499 return false; 500 501 // C++ record fields are never empty, at least in the Itanium ABI. 502 // 503 // FIXME: We should use a predicate for whether this behavior is true in the 504 // current ABI. 505 if (isa<CXXRecordDecl>(RT->getDecl())) 506 return false; 507 508 return isEmptyRecord(Context, FT, AllowArrays); 509 } 510 511 /// isEmptyRecord - Return true iff a structure contains only empty 512 /// fields. Note that a structure with a flexible array member is not 513 /// considered empty. 514 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) { 515 const RecordType *RT = T->getAs<RecordType>(); 516 if (!RT) 517 return false; 518 const RecordDecl *RD = RT->getDecl(); 519 if (RD->hasFlexibleArrayMember()) 520 return false; 521 522 // If this is a C++ record, check the bases first. 523 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 524 for (const auto &I : CXXRD->bases()) 525 if (!isEmptyRecord(Context, I.getType(), true)) 526 return false; 527 528 for (const auto *I : RD->fields()) 529 if (!isEmptyField(Context, I, AllowArrays)) 530 return false; 531 return true; 532 } 533 534 /// isSingleElementStruct - Determine if a structure is a "single 535 /// element struct", i.e. it has exactly one non-empty field or 536 /// exactly one field which is itself a single element 537 /// struct. Structures with flexible array members are never 538 /// considered single element structs. 539 /// 540 /// \return The field declaration for the single non-empty field, if 541 /// it exists. 542 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) { 543 const RecordType *RT = T->getAs<RecordType>(); 544 if (!RT) 545 return nullptr; 546 547 const RecordDecl *RD = RT->getDecl(); 548 if (RD->hasFlexibleArrayMember()) 549 return nullptr; 550 551 const Type *Found = nullptr; 552 553 // If this is a C++ record, check the bases first. 554 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 555 for (const auto &I : CXXRD->bases()) { 556 // Ignore empty records. 557 if (isEmptyRecord(Context, I.getType(), true)) 558 continue; 559 560 // If we already found an element then this isn't a single-element struct. 561 if (Found) 562 return nullptr; 563 564 // If this is non-empty and not a single element struct, the composite 565 // cannot be a single element struct. 566 Found = isSingleElementStruct(I.getType(), Context); 567 if (!Found) 568 return nullptr; 569 } 570 } 571 572 // Check for single element. 573 for (const auto *FD : RD->fields()) { 574 QualType FT = FD->getType(); 575 576 // Ignore empty fields. 577 if (isEmptyField(Context, FD, true)) 578 continue; 579 580 // If we already found an element then this isn't a single-element 581 // struct. 582 if (Found) 583 return nullptr; 584 585 // Treat single element arrays as the element. 586 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 587 if (AT->getSize().getZExtValue() != 1) 588 break; 589 FT = AT->getElementType(); 590 } 591 592 if (!isAggregateTypeForABI(FT)) { 593 Found = FT.getTypePtr(); 594 } else { 595 Found = isSingleElementStruct(FT, Context); 596 if (!Found) 597 return nullptr; 598 } 599 } 600 601 // We don't consider a struct a single-element struct if it has 602 // padding beyond the element type. 603 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T)) 604 return nullptr; 605 606 return Found; 607 } 608 609 namespace { 610 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty, 611 const ABIArgInfo &AI) { 612 // This default implementation defers to the llvm backend's va_arg 613 // instruction. It can handle only passing arguments directly 614 // (typically only handled in the backend for primitive types), or 615 // aggregates passed indirectly by pointer (NOTE: if the "byval" 616 // flag has ABI impact in the callee, this implementation cannot 617 // work.) 618 619 // Only a few cases are covered here at the moment -- those needed 620 // by the default abi. 621 llvm::Value *Val; 622 623 if (AI.isIndirect()) { 624 assert(!AI.getPaddingType() && 625 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!"); 626 assert( 627 !AI.getIndirectRealign() && 628 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!"); 629 630 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty); 631 CharUnits TyAlignForABI = TyInfo.second; 632 633 llvm::Type *BaseTy = 634 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); 635 llvm::Value *Addr = 636 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy); 637 return Address(Addr, TyAlignForABI); 638 } else { 639 assert((AI.isDirect() || AI.isExtend()) && 640 "Unexpected ArgInfo Kind in generic VAArg emitter!"); 641 642 assert(!AI.getInReg() && 643 "Unexpected InReg seen in arginfo in generic VAArg emitter!"); 644 assert(!AI.getPaddingType() && 645 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!"); 646 assert(!AI.getDirectOffset() && 647 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!"); 648 assert(!AI.getCoerceToType() && 649 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!"); 650 651 Address Temp = CGF.CreateMemTemp(Ty, "varet"); 652 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty)); 653 CGF.Builder.CreateStore(Val, Temp); 654 return Temp; 655 } 656 } 657 658 /// DefaultABIInfo - The default implementation for ABI specific 659 /// details. This implementation provides information which results in 660 /// self-consistent and sensible LLVM IR generation, but does not 661 /// conform to any particular ABI. 662 class DefaultABIInfo : public ABIInfo { 663 public: 664 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 665 666 ABIArgInfo classifyReturnType(QualType RetTy) const; 667 ABIArgInfo classifyArgumentType(QualType RetTy) const; 668 669 void computeInfo(CGFunctionInfo &FI) const override { 670 if (!getCXXABI().classifyReturnType(FI)) 671 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 672 for (auto &I : FI.arguments()) 673 I.info = classifyArgumentType(I.type); 674 } 675 676 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 677 QualType Ty) const override { 678 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty)); 679 } 680 }; 681 682 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo { 683 public: 684 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 685 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {} 686 }; 687 688 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const { 689 Ty = useFirstFieldIfTransparentUnion(Ty); 690 691 if (isAggregateTypeForABI(Ty)) { 692 // Records with non-trivial destructors/copy-constructors should not be 693 // passed by value. 694 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 695 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 696 697 return getNaturalAlignIndirect(Ty); 698 } 699 700 // Treat an enum type as its underlying type. 701 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 702 Ty = EnumTy->getDecl()->getIntegerType(); 703 704 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 705 : ABIArgInfo::getDirect()); 706 } 707 708 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const { 709 if (RetTy->isVoidType()) 710 return ABIArgInfo::getIgnore(); 711 712 if (isAggregateTypeForABI(RetTy)) 713 return getNaturalAlignIndirect(RetTy); 714 715 // Treat an enum type as its underlying type. 716 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 717 RetTy = EnumTy->getDecl()->getIntegerType(); 718 719 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) 720 : ABIArgInfo::getDirect()); 721 } 722 723 //===----------------------------------------------------------------------===// 724 // WebAssembly ABI Implementation 725 // 726 // This is a very simple ABI that relies a lot on DefaultABIInfo. 727 //===----------------------------------------------------------------------===// 728 729 class WebAssemblyABIInfo final : public SwiftABIInfo { 730 public: 731 enum ABIKind { 732 MVP = 0, 733 ExperimentalMV = 1, 734 }; 735 736 private: 737 DefaultABIInfo defaultInfo; 738 ABIKind Kind; 739 740 public: 741 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind) 742 : SwiftABIInfo(CGT), defaultInfo(CGT), Kind(Kind) {} 743 744 private: 745 ABIArgInfo classifyReturnType(QualType RetTy) const; 746 ABIArgInfo classifyArgumentType(QualType Ty) const; 747 748 // DefaultABIInfo's classifyReturnType and classifyArgumentType are 749 // non-virtual, but computeInfo and EmitVAArg are virtual, so we 750 // overload them. 751 void computeInfo(CGFunctionInfo &FI) const override { 752 if (!getCXXABI().classifyReturnType(FI)) 753 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 754 for (auto &Arg : FI.arguments()) 755 Arg.info = classifyArgumentType(Arg.type); 756 } 757 758 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 759 QualType Ty) const override; 760 761 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 762 bool asReturnValue) const override { 763 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 764 } 765 766 bool isSwiftErrorInRegister() const override { 767 return false; 768 } 769 }; 770 771 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo { 772 public: 773 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 774 WebAssemblyABIInfo::ABIKind K) 775 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT, K)) {} 776 777 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 778 CodeGen::CodeGenModule &CGM) const override { 779 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 780 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 781 if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) { 782 llvm::Function *Fn = cast<llvm::Function>(GV); 783 llvm::AttrBuilder B; 784 B.addAttribute("wasm-import-module", Attr->getImportModule()); 785 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); 786 } 787 if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) { 788 llvm::Function *Fn = cast<llvm::Function>(GV); 789 llvm::AttrBuilder B; 790 B.addAttribute("wasm-import-name", Attr->getImportName()); 791 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); 792 } 793 if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) { 794 llvm::Function *Fn = cast<llvm::Function>(GV); 795 llvm::AttrBuilder B; 796 B.addAttribute("wasm-export-name", Attr->getExportName()); 797 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); 798 } 799 } 800 801 if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 802 llvm::Function *Fn = cast<llvm::Function>(GV); 803 if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype()) 804 Fn->addFnAttr("no-prototype"); 805 } 806 } 807 }; 808 809 /// Classify argument of given type \p Ty. 810 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const { 811 Ty = useFirstFieldIfTransparentUnion(Ty); 812 813 if (isAggregateTypeForABI(Ty)) { 814 // Records with non-trivial destructors/copy-constructors should not be 815 // passed by value. 816 if (auto RAA = getRecordArgABI(Ty, getCXXABI())) 817 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 818 // Ignore empty structs/unions. 819 if (isEmptyRecord(getContext(), Ty, true)) 820 return ABIArgInfo::getIgnore(); 821 // Lower single-element structs to just pass a regular value. TODO: We 822 // could do reasonable-size multiple-element structs too, using getExpand(), 823 // though watch out for things like bitfields. 824 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 825 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 826 // For the experimental multivalue ABI, fully expand all other aggregates 827 if (Kind == ABIKind::ExperimentalMV) { 828 const RecordType *RT = Ty->getAs<RecordType>(); 829 assert(RT); 830 bool HasBitField = false; 831 for (auto *Field : RT->getDecl()->fields()) { 832 if (Field->isBitField()) { 833 HasBitField = true; 834 break; 835 } 836 } 837 if (!HasBitField) 838 return ABIArgInfo::getExpand(); 839 } 840 } 841 842 // Otherwise just do the default thing. 843 return defaultInfo.classifyArgumentType(Ty); 844 } 845 846 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const { 847 if (isAggregateTypeForABI(RetTy)) { 848 // Records with non-trivial destructors/copy-constructors should not be 849 // returned by value. 850 if (!getRecordArgABI(RetTy, getCXXABI())) { 851 // Ignore empty structs/unions. 852 if (isEmptyRecord(getContext(), RetTy, true)) 853 return ABIArgInfo::getIgnore(); 854 // Lower single-element structs to just return a regular value. TODO: We 855 // could do reasonable-size multiple-element structs too, using 856 // ABIArgInfo::getDirect(). 857 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 858 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 859 // For the experimental multivalue ABI, return all other aggregates 860 if (Kind == ABIKind::ExperimentalMV) 861 return ABIArgInfo::getDirect(); 862 } 863 } 864 865 // Otherwise just do the default thing. 866 return defaultInfo.classifyReturnType(RetTy); 867 } 868 869 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 870 QualType Ty) const { 871 bool IsIndirect = isAggregateTypeForABI(Ty) && 872 !isEmptyRecord(getContext(), Ty, true) && 873 !isSingleElementStruct(Ty, getContext()); 874 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 875 getContext().getTypeInfoInChars(Ty), 876 CharUnits::fromQuantity(4), 877 /*AllowHigherAlign=*/true); 878 } 879 880 //===----------------------------------------------------------------------===// 881 // le32/PNaCl bitcode ABI Implementation 882 // 883 // This is a simplified version of the x86_32 ABI. Arguments and return values 884 // are always passed on the stack. 885 //===----------------------------------------------------------------------===// 886 887 class PNaClABIInfo : public ABIInfo { 888 public: 889 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 890 891 ABIArgInfo classifyReturnType(QualType RetTy) const; 892 ABIArgInfo classifyArgumentType(QualType RetTy) const; 893 894 void computeInfo(CGFunctionInfo &FI) const override; 895 Address EmitVAArg(CodeGenFunction &CGF, 896 Address VAListAddr, QualType Ty) const override; 897 }; 898 899 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo { 900 public: 901 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 902 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {} 903 }; 904 905 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const { 906 if (!getCXXABI().classifyReturnType(FI)) 907 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 908 909 for (auto &I : FI.arguments()) 910 I.info = classifyArgumentType(I.type); 911 } 912 913 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 914 QualType Ty) const { 915 // The PNaCL ABI is a bit odd, in that varargs don't use normal 916 // function classification. Structs get passed directly for varargs 917 // functions, through a rewriting transform in 918 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows 919 // this target to actually support a va_arg instructions with an 920 // aggregate type, unlike other targets. 921 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect()); 922 } 923 924 /// Classify argument of given type \p Ty. 925 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const { 926 if (isAggregateTypeForABI(Ty)) { 927 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 928 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 929 return getNaturalAlignIndirect(Ty); 930 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) { 931 // Treat an enum type as its underlying type. 932 Ty = EnumTy->getDecl()->getIntegerType(); 933 } else if (Ty->isFloatingType()) { 934 // Floating-point types don't go inreg. 935 return ABIArgInfo::getDirect(); 936 } 937 938 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 939 : ABIArgInfo::getDirect()); 940 } 941 942 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const { 943 if (RetTy->isVoidType()) 944 return ABIArgInfo::getIgnore(); 945 946 // In the PNaCl ABI we always return records/structures on the stack. 947 if (isAggregateTypeForABI(RetTy)) 948 return getNaturalAlignIndirect(RetTy); 949 950 // Treat an enum type as its underlying type. 951 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 952 RetTy = EnumTy->getDecl()->getIntegerType(); 953 954 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) 955 : ABIArgInfo::getDirect()); 956 } 957 958 /// IsX86_MMXType - Return true if this is an MMX type. 959 bool IsX86_MMXType(llvm::Type *IRType) { 960 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>. 961 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 && 962 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() && 963 IRType->getScalarSizeInBits() != 64; 964 } 965 966 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 967 StringRef Constraint, 968 llvm::Type* Ty) { 969 bool IsMMXCons = llvm::StringSwitch<bool>(Constraint) 970 .Cases("y", "&y", "^Ym", true) 971 .Default(false); 972 if (IsMMXCons && Ty->isVectorTy()) { 973 if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedSize() != 974 64) { 975 // Invalid MMX constraint 976 return nullptr; 977 } 978 979 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext()); 980 } 981 982 // No operation needed 983 return Ty; 984 } 985 986 /// Returns true if this type can be passed in SSE registers with the 987 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64. 988 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) { 989 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 990 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) { 991 if (BT->getKind() == BuiltinType::LongDouble) { 992 if (&Context.getTargetInfo().getLongDoubleFormat() == 993 &llvm::APFloat::x87DoubleExtended()) 994 return false; 995 } 996 return true; 997 } 998 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 999 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX 1000 // registers specially. 1001 unsigned VecSize = Context.getTypeSize(VT); 1002 if (VecSize == 128 || VecSize == 256 || VecSize == 512) 1003 return true; 1004 } 1005 return false; 1006 } 1007 1008 /// Returns true if this aggregate is small enough to be passed in SSE registers 1009 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64. 1010 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) { 1011 return NumMembers <= 4; 1012 } 1013 1014 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86. 1015 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) { 1016 auto AI = ABIArgInfo::getDirect(T); 1017 AI.setInReg(true); 1018 AI.setCanBeFlattened(false); 1019 return AI; 1020 } 1021 1022 //===----------------------------------------------------------------------===// 1023 // X86-32 ABI Implementation 1024 //===----------------------------------------------------------------------===// 1025 1026 /// Similar to llvm::CCState, but for Clang. 1027 struct CCState { 1028 CCState(CGFunctionInfo &FI) 1029 : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {} 1030 1031 llvm::SmallBitVector IsPreassigned; 1032 unsigned CC = CallingConv::CC_C; 1033 unsigned FreeRegs = 0; 1034 unsigned FreeSSERegs = 0; 1035 }; 1036 1037 enum { 1038 // Vectorcall only allows the first 6 parameters to be passed in registers. 1039 VectorcallMaxParamNumAsReg = 6 1040 }; 1041 1042 /// X86_32ABIInfo - The X86-32 ABI information. 1043 class X86_32ABIInfo : public SwiftABIInfo { 1044 enum Class { 1045 Integer, 1046 Float 1047 }; 1048 1049 static const unsigned MinABIStackAlignInBytes = 4; 1050 1051 bool IsDarwinVectorABI; 1052 bool IsRetSmallStructInRegABI; 1053 bool IsWin32StructABI; 1054 bool IsSoftFloatABI; 1055 bool IsMCUABI; 1056 unsigned DefaultNumRegisterParameters; 1057 1058 static bool isRegisterSize(unsigned Size) { 1059 return (Size == 8 || Size == 16 || Size == 32 || Size == 64); 1060 } 1061 1062 bool isHomogeneousAggregateBaseType(QualType Ty) const override { 1063 // FIXME: Assumes vectorcall is in use. 1064 return isX86VectorTypeForVectorCall(getContext(), Ty); 1065 } 1066 1067 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 1068 uint64_t NumMembers) const override { 1069 // FIXME: Assumes vectorcall is in use. 1070 return isX86VectorCallAggregateSmallEnough(NumMembers); 1071 } 1072 1073 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const; 1074 1075 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 1076 /// such that the argument will be passed in memory. 1077 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; 1078 1079 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const; 1080 1081 /// Return the alignment to use for the given type on the stack. 1082 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const; 1083 1084 Class classify(QualType Ty) const; 1085 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const; 1086 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; 1087 1088 /// Updates the number of available free registers, returns 1089 /// true if any registers were allocated. 1090 bool updateFreeRegs(QualType Ty, CCState &State) const; 1091 1092 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg, 1093 bool &NeedsPadding) const; 1094 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const; 1095 1096 bool canExpandIndirectArgument(QualType Ty) const; 1097 1098 /// Rewrite the function info so that all memory arguments use 1099 /// inalloca. 1100 void rewriteWithInAlloca(CGFunctionInfo &FI) const; 1101 1102 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields, 1103 CharUnits &StackOffset, ABIArgInfo &Info, 1104 QualType Type) const; 1105 void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const; 1106 1107 public: 1108 1109 void computeInfo(CGFunctionInfo &FI) const override; 1110 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 1111 QualType Ty) const override; 1112 1113 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, 1114 bool RetSmallStructInRegABI, bool Win32StructABI, 1115 unsigned NumRegisterParameters, bool SoftFloatABI) 1116 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI), 1117 IsRetSmallStructInRegABI(RetSmallStructInRegABI), 1118 IsWin32StructABI(Win32StructABI), 1119 IsSoftFloatABI(SoftFloatABI), 1120 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()), 1121 DefaultNumRegisterParameters(NumRegisterParameters) {} 1122 1123 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 1124 bool asReturnValue) const override { 1125 // LLVM's x86-32 lowering currently only assigns up to three 1126 // integer registers and three fp registers. Oddly, it'll use up to 1127 // four vector registers for vectors, but those can overlap with the 1128 // scalar registers. 1129 return occupiesMoreThan(CGT, scalars, /*total*/ 3); 1130 } 1131 1132 bool isSwiftErrorInRegister() const override { 1133 // x86-32 lowering does not support passing swifterror in a register. 1134 return false; 1135 } 1136 }; 1137 1138 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo { 1139 public: 1140 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, 1141 bool RetSmallStructInRegABI, bool Win32StructABI, 1142 unsigned NumRegisterParameters, bool SoftFloatABI) 1143 : TargetCodeGenInfo(new X86_32ABIInfo( 1144 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI, 1145 NumRegisterParameters, SoftFloatABI)) {} 1146 1147 static bool isStructReturnInRegABI( 1148 const llvm::Triple &Triple, const CodeGenOptions &Opts); 1149 1150 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 1151 CodeGen::CodeGenModule &CGM) const override; 1152 1153 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 1154 // Darwin uses different dwarf register numbers for EH. 1155 if (CGM.getTarget().getTriple().isOSDarwin()) return 5; 1156 return 4; 1157 } 1158 1159 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 1160 llvm::Value *Address) const override; 1161 1162 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 1163 StringRef Constraint, 1164 llvm::Type* Ty) const override { 1165 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 1166 } 1167 1168 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue, 1169 std::string &Constraints, 1170 std::vector<llvm::Type *> &ResultRegTypes, 1171 std::vector<llvm::Type *> &ResultTruncRegTypes, 1172 std::vector<LValue> &ResultRegDests, 1173 std::string &AsmString, 1174 unsigned NumOutputs) const override; 1175 1176 llvm::Constant * 1177 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { 1178 unsigned Sig = (0xeb << 0) | // jmp rel8 1179 (0x06 << 8) | // .+0x08 1180 ('v' << 16) | 1181 ('2' << 24); 1182 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 1183 } 1184 1185 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 1186 return "movl\t%ebp, %ebp" 1187 "\t\t// marker for objc_retainAutoreleaseReturnValue"; 1188 } 1189 }; 1190 1191 } 1192 1193 /// Rewrite input constraint references after adding some output constraints. 1194 /// In the case where there is one output and one input and we add one output, 1195 /// we need to replace all operand references greater than or equal to 1: 1196 /// mov $0, $1 1197 /// mov eax, $1 1198 /// The result will be: 1199 /// mov $0, $2 1200 /// mov eax, $2 1201 static void rewriteInputConstraintReferences(unsigned FirstIn, 1202 unsigned NumNewOuts, 1203 std::string &AsmString) { 1204 std::string Buf; 1205 llvm::raw_string_ostream OS(Buf); 1206 size_t Pos = 0; 1207 while (Pos < AsmString.size()) { 1208 size_t DollarStart = AsmString.find('$', Pos); 1209 if (DollarStart == std::string::npos) 1210 DollarStart = AsmString.size(); 1211 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart); 1212 if (DollarEnd == std::string::npos) 1213 DollarEnd = AsmString.size(); 1214 OS << StringRef(&AsmString[Pos], DollarEnd - Pos); 1215 Pos = DollarEnd; 1216 size_t NumDollars = DollarEnd - DollarStart; 1217 if (NumDollars % 2 != 0 && Pos < AsmString.size()) { 1218 // We have an operand reference. 1219 size_t DigitStart = Pos; 1220 if (AsmString[DigitStart] == '{') { 1221 OS << '{'; 1222 ++DigitStart; 1223 } 1224 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart); 1225 if (DigitEnd == std::string::npos) 1226 DigitEnd = AsmString.size(); 1227 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart); 1228 unsigned OperandIndex; 1229 if (!OperandStr.getAsInteger(10, OperandIndex)) { 1230 if (OperandIndex >= FirstIn) 1231 OperandIndex += NumNewOuts; 1232 OS << OperandIndex; 1233 } else { 1234 OS << OperandStr; 1235 } 1236 Pos = DigitEnd; 1237 } 1238 } 1239 AsmString = std::move(OS.str()); 1240 } 1241 1242 /// Add output constraints for EAX:EDX because they are return registers. 1243 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs( 1244 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints, 1245 std::vector<llvm::Type *> &ResultRegTypes, 1246 std::vector<llvm::Type *> &ResultTruncRegTypes, 1247 std::vector<LValue> &ResultRegDests, std::string &AsmString, 1248 unsigned NumOutputs) const { 1249 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType()); 1250 1251 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is 1252 // larger. 1253 if (!Constraints.empty()) 1254 Constraints += ','; 1255 if (RetWidth <= 32) { 1256 Constraints += "={eax}"; 1257 ResultRegTypes.push_back(CGF.Int32Ty); 1258 } else { 1259 // Use the 'A' constraint for EAX:EDX. 1260 Constraints += "=A"; 1261 ResultRegTypes.push_back(CGF.Int64Ty); 1262 } 1263 1264 // Truncate EAX or EAX:EDX to an integer of the appropriate size. 1265 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth); 1266 ResultTruncRegTypes.push_back(CoerceTy); 1267 1268 // Coerce the integer by bitcasting the return slot pointer. 1269 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(CGF), 1270 CoerceTy->getPointerTo())); 1271 ResultRegDests.push_back(ReturnSlot); 1272 1273 rewriteInputConstraintReferences(NumOutputs, 1, AsmString); 1274 } 1275 1276 /// shouldReturnTypeInRegister - Determine if the given type should be 1277 /// returned in a register (for the Darwin and MCU ABI). 1278 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty, 1279 ASTContext &Context) const { 1280 uint64_t Size = Context.getTypeSize(Ty); 1281 1282 // For i386, type must be register sized. 1283 // For the MCU ABI, it only needs to be <= 8-byte 1284 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size))) 1285 return false; 1286 1287 if (Ty->isVectorType()) { 1288 // 64- and 128- bit vectors inside structures are not returned in 1289 // registers. 1290 if (Size == 64 || Size == 128) 1291 return false; 1292 1293 return true; 1294 } 1295 1296 // If this is a builtin, pointer, enum, complex type, member pointer, or 1297 // member function pointer it is ok. 1298 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() || 1299 Ty->isAnyComplexType() || Ty->isEnumeralType() || 1300 Ty->isBlockPointerType() || Ty->isMemberPointerType()) 1301 return true; 1302 1303 // Arrays are treated like records. 1304 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) 1305 return shouldReturnTypeInRegister(AT->getElementType(), Context); 1306 1307 // Otherwise, it must be a record type. 1308 const RecordType *RT = Ty->getAs<RecordType>(); 1309 if (!RT) return false; 1310 1311 // FIXME: Traverse bases here too. 1312 1313 // Structure types are passed in register if all fields would be 1314 // passed in a register. 1315 for (const auto *FD : RT->getDecl()->fields()) { 1316 // Empty fields are ignored. 1317 if (isEmptyField(Context, FD, true)) 1318 continue; 1319 1320 // Check fields recursively. 1321 if (!shouldReturnTypeInRegister(FD->getType(), Context)) 1322 return false; 1323 } 1324 return true; 1325 } 1326 1327 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) { 1328 // Treat complex types as the element type. 1329 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 1330 Ty = CTy->getElementType(); 1331 1332 // Check for a type which we know has a simple scalar argument-passing 1333 // convention without any padding. (We're specifically looking for 32 1334 // and 64-bit integer and integer-equivalents, float, and double.) 1335 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() && 1336 !Ty->isEnumeralType() && !Ty->isBlockPointerType()) 1337 return false; 1338 1339 uint64_t Size = Context.getTypeSize(Ty); 1340 return Size == 32 || Size == 64; 1341 } 1342 1343 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD, 1344 uint64_t &Size) { 1345 for (const auto *FD : RD->fields()) { 1346 // Scalar arguments on the stack get 4 byte alignment on x86. If the 1347 // argument is smaller than 32-bits, expanding the struct will create 1348 // alignment padding. 1349 if (!is32Or64BitBasicType(FD->getType(), Context)) 1350 return false; 1351 1352 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know 1353 // how to expand them yet, and the predicate for telling if a bitfield still 1354 // counts as "basic" is more complicated than what we were doing previously. 1355 if (FD->isBitField()) 1356 return false; 1357 1358 Size += Context.getTypeSize(FD->getType()); 1359 } 1360 return true; 1361 } 1362 1363 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD, 1364 uint64_t &Size) { 1365 // Don't do this if there are any non-empty bases. 1366 for (const CXXBaseSpecifier &Base : RD->bases()) { 1367 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(), 1368 Size)) 1369 return false; 1370 } 1371 if (!addFieldSizes(Context, RD, Size)) 1372 return false; 1373 return true; 1374 } 1375 1376 /// Test whether an argument type which is to be passed indirectly (on the 1377 /// stack) would have the equivalent layout if it was expanded into separate 1378 /// arguments. If so, we prefer to do the latter to avoid inhibiting 1379 /// optimizations. 1380 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const { 1381 // We can only expand structure types. 1382 const RecordType *RT = Ty->getAs<RecordType>(); 1383 if (!RT) 1384 return false; 1385 const RecordDecl *RD = RT->getDecl(); 1386 uint64_t Size = 0; 1387 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 1388 if (!IsWin32StructABI) { 1389 // On non-Windows, we have to conservatively match our old bitcode 1390 // prototypes in order to be ABI-compatible at the bitcode level. 1391 if (!CXXRD->isCLike()) 1392 return false; 1393 } else { 1394 // Don't do this for dynamic classes. 1395 if (CXXRD->isDynamicClass()) 1396 return false; 1397 } 1398 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size)) 1399 return false; 1400 } else { 1401 if (!addFieldSizes(getContext(), RD, Size)) 1402 return false; 1403 } 1404 1405 // We can do this if there was no alignment padding. 1406 return Size == getContext().getTypeSize(Ty); 1407 } 1408 1409 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const { 1410 // If the return value is indirect, then the hidden argument is consuming one 1411 // integer register. 1412 if (State.FreeRegs) { 1413 --State.FreeRegs; 1414 if (!IsMCUABI) 1415 return getNaturalAlignIndirectInReg(RetTy); 1416 } 1417 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 1418 } 1419 1420 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, 1421 CCState &State) const { 1422 if (RetTy->isVoidType()) 1423 return ABIArgInfo::getIgnore(); 1424 1425 const Type *Base = nullptr; 1426 uint64_t NumElts = 0; 1427 if ((State.CC == llvm::CallingConv::X86_VectorCall || 1428 State.CC == llvm::CallingConv::X86_RegCall) && 1429 isHomogeneousAggregate(RetTy, Base, NumElts)) { 1430 // The LLVM struct type for such an aggregate should lower properly. 1431 return ABIArgInfo::getDirect(); 1432 } 1433 1434 if (const VectorType *VT = RetTy->getAs<VectorType>()) { 1435 // On Darwin, some vectors are returned in registers. 1436 if (IsDarwinVectorABI) { 1437 uint64_t Size = getContext().getTypeSize(RetTy); 1438 1439 // 128-bit vectors are a special case; they are returned in 1440 // registers and we need to make sure to pick a type the LLVM 1441 // backend will like. 1442 if (Size == 128) 1443 return ABIArgInfo::getDirect(llvm::VectorType::get( 1444 llvm::Type::getInt64Ty(getVMContext()), 2)); 1445 1446 // Always return in register if it fits in a general purpose 1447 // register, or if it is 64 bits and has a single element. 1448 if ((Size == 8 || Size == 16 || Size == 32) || 1449 (Size == 64 && VT->getNumElements() == 1)) 1450 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 1451 Size)); 1452 1453 return getIndirectReturnResult(RetTy, State); 1454 } 1455 1456 return ABIArgInfo::getDirect(); 1457 } 1458 1459 if (isAggregateTypeForABI(RetTy)) { 1460 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 1461 // Structures with flexible arrays are always indirect. 1462 if (RT->getDecl()->hasFlexibleArrayMember()) 1463 return getIndirectReturnResult(RetTy, State); 1464 } 1465 1466 // If specified, structs and unions are always indirect. 1467 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType()) 1468 return getIndirectReturnResult(RetTy, State); 1469 1470 // Ignore empty structs/unions. 1471 if (isEmptyRecord(getContext(), RetTy, true)) 1472 return ABIArgInfo::getIgnore(); 1473 1474 // Small structures which are register sized are generally returned 1475 // in a register. 1476 if (shouldReturnTypeInRegister(RetTy, getContext())) { 1477 uint64_t Size = getContext().getTypeSize(RetTy); 1478 1479 // As a special-case, if the struct is a "single-element" struct, and 1480 // the field is of type "float" or "double", return it in a 1481 // floating-point register. (MSVC does not apply this special case.) 1482 // We apply a similar transformation for pointer types to improve the 1483 // quality of the generated IR. 1484 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 1485 if ((!IsWin32StructABI && SeltTy->isRealFloatingType()) 1486 || SeltTy->hasPointerRepresentation()) 1487 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 1488 1489 // FIXME: We should be able to narrow this integer in cases with dead 1490 // padding. 1491 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size)); 1492 } 1493 1494 return getIndirectReturnResult(RetTy, State); 1495 } 1496 1497 // Treat an enum type as its underlying type. 1498 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 1499 RetTy = EnumTy->getDecl()->getIntegerType(); 1500 1501 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) 1502 : ABIArgInfo::getDirect()); 1503 } 1504 1505 static bool isSSEVectorType(ASTContext &Context, QualType Ty) { 1506 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128; 1507 } 1508 1509 static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) { 1510 const RecordType *RT = Ty->getAs<RecordType>(); 1511 if (!RT) 1512 return 0; 1513 const RecordDecl *RD = RT->getDecl(); 1514 1515 // If this is a C++ record, check the bases first. 1516 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 1517 for (const auto &I : CXXRD->bases()) 1518 if (!isRecordWithSSEVectorType(Context, I.getType())) 1519 return false; 1520 1521 for (const auto *i : RD->fields()) { 1522 QualType FT = i->getType(); 1523 1524 if (isSSEVectorType(Context, FT)) 1525 return true; 1526 1527 if (isRecordWithSSEVectorType(Context, FT)) 1528 return true; 1529 } 1530 1531 return false; 1532 } 1533 1534 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty, 1535 unsigned Align) const { 1536 // Otherwise, if the alignment is less than or equal to the minimum ABI 1537 // alignment, just use the default; the backend will handle this. 1538 if (Align <= MinABIStackAlignInBytes) 1539 return 0; // Use default alignment. 1540 1541 // On non-Darwin, the stack type alignment is always 4. 1542 if (!IsDarwinVectorABI) { 1543 // Set explicit alignment, since we may need to realign the top. 1544 return MinABIStackAlignInBytes; 1545 } 1546 1547 // Otherwise, if the type contains an SSE vector type, the alignment is 16. 1548 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) || 1549 isRecordWithSSEVectorType(getContext(), Ty))) 1550 return 16; 1551 1552 return MinABIStackAlignInBytes; 1553 } 1554 1555 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal, 1556 CCState &State) const { 1557 if (!ByVal) { 1558 if (State.FreeRegs) { 1559 --State.FreeRegs; // Non-byval indirects just use one pointer. 1560 if (!IsMCUABI) 1561 return getNaturalAlignIndirectInReg(Ty); 1562 } 1563 return getNaturalAlignIndirect(Ty, false); 1564 } 1565 1566 // Compute the byval alignment. 1567 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 1568 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign); 1569 if (StackAlign == 0) 1570 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true); 1571 1572 // If the stack alignment is less than the type alignment, realign the 1573 // argument. 1574 bool Realign = TypeAlign > StackAlign; 1575 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign), 1576 /*ByVal=*/true, Realign); 1577 } 1578 1579 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const { 1580 const Type *T = isSingleElementStruct(Ty, getContext()); 1581 if (!T) 1582 T = Ty.getTypePtr(); 1583 1584 if (const BuiltinType *BT = T->getAs<BuiltinType>()) { 1585 BuiltinType::Kind K = BT->getKind(); 1586 if (K == BuiltinType::Float || K == BuiltinType::Double) 1587 return Float; 1588 } 1589 return Integer; 1590 } 1591 1592 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const { 1593 if (!IsSoftFloatABI) { 1594 Class C = classify(Ty); 1595 if (C == Float) 1596 return false; 1597 } 1598 1599 unsigned Size = getContext().getTypeSize(Ty); 1600 unsigned SizeInRegs = (Size + 31) / 32; 1601 1602 if (SizeInRegs == 0) 1603 return false; 1604 1605 if (!IsMCUABI) { 1606 if (SizeInRegs > State.FreeRegs) { 1607 State.FreeRegs = 0; 1608 return false; 1609 } 1610 } else { 1611 // The MCU psABI allows passing parameters in-reg even if there are 1612 // earlier parameters that are passed on the stack. Also, 1613 // it does not allow passing >8-byte structs in-register, 1614 // even if there are 3 free registers available. 1615 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2) 1616 return false; 1617 } 1618 1619 State.FreeRegs -= SizeInRegs; 1620 return true; 1621 } 1622 1623 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State, 1624 bool &InReg, 1625 bool &NeedsPadding) const { 1626 // On Windows, aggregates other than HFAs are never passed in registers, and 1627 // they do not consume register slots. Homogenous floating-point aggregates 1628 // (HFAs) have already been dealt with at this point. 1629 if (IsWin32StructABI && isAggregateTypeForABI(Ty)) 1630 return false; 1631 1632 NeedsPadding = false; 1633 InReg = !IsMCUABI; 1634 1635 if (!updateFreeRegs(Ty, State)) 1636 return false; 1637 1638 if (IsMCUABI) 1639 return true; 1640 1641 if (State.CC == llvm::CallingConv::X86_FastCall || 1642 State.CC == llvm::CallingConv::X86_VectorCall || 1643 State.CC == llvm::CallingConv::X86_RegCall) { 1644 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs) 1645 NeedsPadding = true; 1646 1647 return false; 1648 } 1649 1650 return true; 1651 } 1652 1653 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const { 1654 if (!updateFreeRegs(Ty, State)) 1655 return false; 1656 1657 if (IsMCUABI) 1658 return false; 1659 1660 if (State.CC == llvm::CallingConv::X86_FastCall || 1661 State.CC == llvm::CallingConv::X86_VectorCall || 1662 State.CC == llvm::CallingConv::X86_RegCall) { 1663 if (getContext().getTypeSize(Ty) > 32) 1664 return false; 1665 1666 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() || 1667 Ty->isReferenceType()); 1668 } 1669 1670 return true; 1671 } 1672 1673 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const { 1674 // Vectorcall x86 works subtly different than in x64, so the format is 1675 // a bit different than the x64 version. First, all vector types (not HVAs) 1676 // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers. 1677 // This differs from the x64 implementation, where the first 6 by INDEX get 1678 // registers. 1679 // In the second pass over the arguments, HVAs are passed in the remaining 1680 // vector registers if possible, or indirectly by address. The address will be 1681 // passed in ECX/EDX if available. Any other arguments are passed according to 1682 // the usual fastcall rules. 1683 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments(); 1684 for (int I = 0, E = Args.size(); I < E; ++I) { 1685 const Type *Base = nullptr; 1686 uint64_t NumElts = 0; 1687 const QualType &Ty = Args[I].type; 1688 if ((Ty->isVectorType() || Ty->isBuiltinType()) && 1689 isHomogeneousAggregate(Ty, Base, NumElts)) { 1690 if (State.FreeSSERegs >= NumElts) { 1691 State.FreeSSERegs -= NumElts; 1692 Args[I].info = ABIArgInfo::getDirectInReg(); 1693 State.IsPreassigned.set(I); 1694 } 1695 } 1696 } 1697 } 1698 1699 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, 1700 CCState &State) const { 1701 // FIXME: Set alignment on indirect arguments. 1702 bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall; 1703 bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall; 1704 bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall; 1705 1706 Ty = useFirstFieldIfTransparentUnion(Ty); 1707 TypeInfo TI = getContext().getTypeInfo(Ty); 1708 1709 // Check with the C++ ABI first. 1710 const RecordType *RT = Ty->getAs<RecordType>(); 1711 if (RT) { 1712 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 1713 if (RAA == CGCXXABI::RAA_Indirect) { 1714 return getIndirectResult(Ty, false, State); 1715 } else if (RAA == CGCXXABI::RAA_DirectInMemory) { 1716 // The field index doesn't matter, we'll fix it up later. 1717 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0); 1718 } 1719 } 1720 1721 // Regcall uses the concept of a homogenous vector aggregate, similar 1722 // to other targets. 1723 const Type *Base = nullptr; 1724 uint64_t NumElts = 0; 1725 if ((IsRegCall || IsVectorCall) && 1726 isHomogeneousAggregate(Ty, Base, NumElts)) { 1727 if (State.FreeSSERegs >= NumElts) { 1728 State.FreeSSERegs -= NumElts; 1729 1730 // Vectorcall passes HVAs directly and does not flatten them, but regcall 1731 // does. 1732 if (IsVectorCall) 1733 return getDirectX86Hva(); 1734 1735 if (Ty->isBuiltinType() || Ty->isVectorType()) 1736 return ABIArgInfo::getDirect(); 1737 return ABIArgInfo::getExpand(); 1738 } 1739 return getIndirectResult(Ty, /*ByVal=*/false, State); 1740 } 1741 1742 if (isAggregateTypeForABI(Ty)) { 1743 // Structures with flexible arrays are always indirect. 1744 // FIXME: This should not be byval! 1745 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 1746 return getIndirectResult(Ty, true, State); 1747 1748 // Ignore empty structs/unions on non-Windows. 1749 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true)) 1750 return ABIArgInfo::getIgnore(); 1751 1752 llvm::LLVMContext &LLVMContext = getVMContext(); 1753 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 1754 bool NeedsPadding = false; 1755 bool InReg; 1756 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) { 1757 unsigned SizeInRegs = (TI.Width + 31) / 32; 1758 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32); 1759 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 1760 if (InReg) 1761 return ABIArgInfo::getDirectInReg(Result); 1762 else 1763 return ABIArgInfo::getDirect(Result); 1764 } 1765 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr; 1766 1767 // Pass over-aligned aggregates on Windows indirectly. This behavior was 1768 // added in MSVC 2015. 1769 if (IsWin32StructABI && TI.AlignIsRequired && TI.Align > 32) 1770 return getIndirectResult(Ty, /*ByVal=*/false, State); 1771 1772 // Expand small (<= 128-bit) record types when we know that the stack layout 1773 // of those arguments will match the struct. This is important because the 1774 // LLVM backend isn't smart enough to remove byval, which inhibits many 1775 // optimizations. 1776 // Don't do this for the MCU if there are still free integer registers 1777 // (see X86_64 ABI for full explanation). 1778 if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) && 1779 canExpandIndirectArgument(Ty)) 1780 return ABIArgInfo::getExpandWithPadding( 1781 IsFastCall || IsVectorCall || IsRegCall, PaddingType); 1782 1783 return getIndirectResult(Ty, true, State); 1784 } 1785 1786 if (const VectorType *VT = Ty->getAs<VectorType>()) { 1787 // On Windows, vectors are passed directly if registers are available, or 1788 // indirectly if not. This avoids the need to align argument memory. Pass 1789 // user-defined vector types larger than 512 bits indirectly for simplicity. 1790 if (IsWin32StructABI) { 1791 if (TI.Width <= 512 && State.FreeSSERegs > 0) { 1792 --State.FreeSSERegs; 1793 return ABIArgInfo::getDirectInReg(); 1794 } 1795 return getIndirectResult(Ty, /*ByVal=*/false, State); 1796 } 1797 1798 // On Darwin, some vectors are passed in memory, we handle this by passing 1799 // it as an i8/i16/i32/i64. 1800 if (IsDarwinVectorABI) { 1801 if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) || 1802 (TI.Width == 64 && VT->getNumElements() == 1)) 1803 return ABIArgInfo::getDirect( 1804 llvm::IntegerType::get(getVMContext(), TI.Width)); 1805 } 1806 1807 if (IsX86_MMXType(CGT.ConvertType(Ty))) 1808 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64)); 1809 1810 return ABIArgInfo::getDirect(); 1811 } 1812 1813 1814 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 1815 Ty = EnumTy->getDecl()->getIntegerType(); 1816 1817 bool InReg = shouldPrimitiveUseInReg(Ty, State); 1818 1819 if (Ty->isPromotableIntegerType()) { 1820 if (InReg) 1821 return ABIArgInfo::getExtendInReg(Ty); 1822 return ABIArgInfo::getExtend(Ty); 1823 } 1824 1825 if (InReg) 1826 return ABIArgInfo::getDirectInReg(); 1827 return ABIArgInfo::getDirect(); 1828 } 1829 1830 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const { 1831 CCState State(FI); 1832 if (IsMCUABI) 1833 State.FreeRegs = 3; 1834 else if (State.CC == llvm::CallingConv::X86_FastCall) { 1835 State.FreeRegs = 2; 1836 State.FreeSSERegs = 3; 1837 } else if (State.CC == llvm::CallingConv::X86_VectorCall) { 1838 State.FreeRegs = 2; 1839 State.FreeSSERegs = 6; 1840 } else if (FI.getHasRegParm()) 1841 State.FreeRegs = FI.getRegParm(); 1842 else if (State.CC == llvm::CallingConv::X86_RegCall) { 1843 State.FreeRegs = 5; 1844 State.FreeSSERegs = 8; 1845 } else if (IsWin32StructABI) { 1846 // Since MSVC 2015, the first three SSE vectors have been passed in 1847 // registers. The rest are passed indirectly. 1848 State.FreeRegs = DefaultNumRegisterParameters; 1849 State.FreeSSERegs = 3; 1850 } else 1851 State.FreeRegs = DefaultNumRegisterParameters; 1852 1853 if (!::classifyReturnType(getCXXABI(), FI, *this)) { 1854 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State); 1855 } else if (FI.getReturnInfo().isIndirect()) { 1856 // The C++ ABI is not aware of register usage, so we have to check if the 1857 // return value was sret and put it in a register ourselves if appropriate. 1858 if (State.FreeRegs) { 1859 --State.FreeRegs; // The sret parameter consumes a register. 1860 if (!IsMCUABI) 1861 FI.getReturnInfo().setInReg(true); 1862 } 1863 } 1864 1865 // The chain argument effectively gives us another free register. 1866 if (FI.isChainCall()) 1867 ++State.FreeRegs; 1868 1869 // For vectorcall, do a first pass over the arguments, assigning FP and vector 1870 // arguments to XMM registers as available. 1871 if (State.CC == llvm::CallingConv::X86_VectorCall) 1872 runVectorCallFirstPass(FI, State); 1873 1874 bool UsedInAlloca = false; 1875 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments(); 1876 for (int I = 0, E = Args.size(); I < E; ++I) { 1877 // Skip arguments that have already been assigned. 1878 if (State.IsPreassigned.test(I)) 1879 continue; 1880 1881 Args[I].info = classifyArgumentType(Args[I].type, State); 1882 UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca); 1883 } 1884 1885 // If we needed to use inalloca for any argument, do a second pass and rewrite 1886 // all the memory arguments to use inalloca. 1887 if (UsedInAlloca) 1888 rewriteWithInAlloca(FI); 1889 } 1890 1891 void 1892 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields, 1893 CharUnits &StackOffset, ABIArgInfo &Info, 1894 QualType Type) const { 1895 // Arguments are always 4-byte-aligned. 1896 CharUnits WordSize = CharUnits::fromQuantity(4); 1897 assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct"); 1898 1899 // sret pointers and indirect things will require an extra pointer 1900 // indirection, unless they are byval. Most things are byval, and will not 1901 // require this indirection. 1902 bool IsIndirect = false; 1903 if (Info.isIndirect() && !Info.getIndirectByVal()) 1904 IsIndirect = true; 1905 Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect); 1906 llvm::Type *LLTy = CGT.ConvertTypeForMem(Type); 1907 if (IsIndirect) 1908 LLTy = LLTy->getPointerTo(0); 1909 FrameFields.push_back(LLTy); 1910 StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type); 1911 1912 // Insert padding bytes to respect alignment. 1913 CharUnits FieldEnd = StackOffset; 1914 StackOffset = FieldEnd.alignTo(WordSize); 1915 if (StackOffset != FieldEnd) { 1916 CharUnits NumBytes = StackOffset - FieldEnd; 1917 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext()); 1918 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity()); 1919 FrameFields.push_back(Ty); 1920 } 1921 } 1922 1923 static bool isArgInAlloca(const ABIArgInfo &Info) { 1924 // Leave ignored and inreg arguments alone. 1925 switch (Info.getKind()) { 1926 case ABIArgInfo::InAlloca: 1927 return true; 1928 case ABIArgInfo::Ignore: 1929 return false; 1930 case ABIArgInfo::Indirect: 1931 case ABIArgInfo::Direct: 1932 case ABIArgInfo::Extend: 1933 return !Info.getInReg(); 1934 case ABIArgInfo::Expand: 1935 case ABIArgInfo::CoerceAndExpand: 1936 // These are aggregate types which are never passed in registers when 1937 // inalloca is involved. 1938 return true; 1939 } 1940 llvm_unreachable("invalid enum"); 1941 } 1942 1943 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const { 1944 assert(IsWin32StructABI && "inalloca only supported on win32"); 1945 1946 // Build a packed struct type for all of the arguments in memory. 1947 SmallVector<llvm::Type *, 6> FrameFields; 1948 1949 // The stack alignment is always 4. 1950 CharUnits StackAlign = CharUnits::fromQuantity(4); 1951 1952 CharUnits StackOffset; 1953 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end(); 1954 1955 // Put 'this' into the struct before 'sret', if necessary. 1956 bool IsThisCall = 1957 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall; 1958 ABIArgInfo &Ret = FI.getReturnInfo(); 1959 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall && 1960 isArgInAlloca(I->info)) { 1961 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); 1962 ++I; 1963 } 1964 1965 // Put the sret parameter into the inalloca struct if it's in memory. 1966 if (Ret.isIndirect() && !Ret.getInReg()) { 1967 addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType()); 1968 // On Windows, the hidden sret parameter is always returned in eax. 1969 Ret.setInAllocaSRet(IsWin32StructABI); 1970 } 1971 1972 // Skip the 'this' parameter in ecx. 1973 if (IsThisCall) 1974 ++I; 1975 1976 // Put arguments passed in memory into the struct. 1977 for (; I != E; ++I) { 1978 if (isArgInAlloca(I->info)) 1979 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); 1980 } 1981 1982 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields, 1983 /*isPacked=*/true), 1984 StackAlign); 1985 } 1986 1987 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF, 1988 Address VAListAddr, QualType Ty) const { 1989 1990 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 1991 1992 // x86-32 changes the alignment of certain arguments on the stack. 1993 // 1994 // Just messing with TypeInfo like this works because we never pass 1995 // anything indirectly. 1996 TypeInfo.second = CharUnits::fromQuantity( 1997 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity())); 1998 1999 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, 2000 TypeInfo, CharUnits::fromQuantity(4), 2001 /*AllowHigherAlign*/ true); 2002 } 2003 2004 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI( 2005 const llvm::Triple &Triple, const CodeGenOptions &Opts) { 2006 assert(Triple.getArch() == llvm::Triple::x86); 2007 2008 switch (Opts.getStructReturnConvention()) { 2009 case CodeGenOptions::SRCK_Default: 2010 break; 2011 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return 2012 return false; 2013 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return 2014 return true; 2015 } 2016 2017 if (Triple.isOSDarwin() || Triple.isOSIAMCU()) 2018 return true; 2019 2020 switch (Triple.getOS()) { 2021 case llvm::Triple::DragonFly: 2022 case llvm::Triple::FreeBSD: 2023 case llvm::Triple::OpenBSD: 2024 case llvm::Triple::Win32: 2025 return true; 2026 default: 2027 return false; 2028 } 2029 } 2030 2031 void X86_32TargetCodeGenInfo::setTargetAttributes( 2032 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2033 if (GV->isDeclaration()) 2034 return; 2035 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2036 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2037 llvm::Function *Fn = cast<llvm::Function>(GV); 2038 Fn->addFnAttr("stackrealign"); 2039 } 2040 if (FD->hasAttr<AnyX86InterruptAttr>()) { 2041 llvm::Function *Fn = cast<llvm::Function>(GV); 2042 Fn->setCallingConv(llvm::CallingConv::X86_INTR); 2043 } 2044 } 2045 } 2046 2047 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable( 2048 CodeGen::CodeGenFunction &CGF, 2049 llvm::Value *Address) const { 2050 CodeGen::CGBuilderTy &Builder = CGF.Builder; 2051 2052 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 2053 2054 // 0-7 are the eight integer registers; the order is different 2055 // on Darwin (for EH), but the range is the same. 2056 // 8 is %eip. 2057 AssignToArrayRange(Builder, Address, Four8, 0, 8); 2058 2059 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) { 2060 // 12-16 are st(0..4). Not sure why we stop at 4. 2061 // These have size 16, which is sizeof(long double) on 2062 // platforms with 8-byte alignment for that type. 2063 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16); 2064 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16); 2065 2066 } else { 2067 // 9 is %eflags, which doesn't get a size on Darwin for some 2068 // reason. 2069 Builder.CreateAlignedStore( 2070 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9), 2071 CharUnits::One()); 2072 2073 // 11-16 are st(0..5). Not sure why we stop at 5. 2074 // These have size 12, which is sizeof(long double) on 2075 // platforms with 4-byte alignment for that type. 2076 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12); 2077 AssignToArrayRange(Builder, Address, Twelve8, 11, 16); 2078 } 2079 2080 return false; 2081 } 2082 2083 //===----------------------------------------------------------------------===// 2084 // X86-64 ABI Implementation 2085 //===----------------------------------------------------------------------===// 2086 2087 2088 namespace { 2089 /// The AVX ABI level for X86 targets. 2090 enum class X86AVXABILevel { 2091 None, 2092 AVX, 2093 AVX512 2094 }; 2095 2096 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel. 2097 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) { 2098 switch (AVXLevel) { 2099 case X86AVXABILevel::AVX512: 2100 return 512; 2101 case X86AVXABILevel::AVX: 2102 return 256; 2103 case X86AVXABILevel::None: 2104 return 128; 2105 } 2106 llvm_unreachable("Unknown AVXLevel"); 2107 } 2108 2109 /// X86_64ABIInfo - The X86_64 ABI information. 2110 class X86_64ABIInfo : public SwiftABIInfo { 2111 enum Class { 2112 Integer = 0, 2113 SSE, 2114 SSEUp, 2115 X87, 2116 X87Up, 2117 ComplexX87, 2118 NoClass, 2119 Memory 2120 }; 2121 2122 /// merge - Implement the X86_64 ABI merging algorithm. 2123 /// 2124 /// Merge an accumulating classification \arg Accum with a field 2125 /// classification \arg Field. 2126 /// 2127 /// \param Accum - The accumulating classification. This should 2128 /// always be either NoClass or the result of a previous merge 2129 /// call. In addition, this should never be Memory (the caller 2130 /// should just return Memory for the aggregate). 2131 static Class merge(Class Accum, Class Field); 2132 2133 /// postMerge - Implement the X86_64 ABI post merging algorithm. 2134 /// 2135 /// Post merger cleanup, reduces a malformed Hi and Lo pair to 2136 /// final MEMORY or SSE classes when necessary. 2137 /// 2138 /// \param AggregateSize - The size of the current aggregate in 2139 /// the classification process. 2140 /// 2141 /// \param Lo - The classification for the parts of the type 2142 /// residing in the low word of the containing object. 2143 /// 2144 /// \param Hi - The classification for the parts of the type 2145 /// residing in the higher words of the containing object. 2146 /// 2147 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const; 2148 2149 /// classify - Determine the x86_64 register classes in which the 2150 /// given type T should be passed. 2151 /// 2152 /// \param Lo - The classification for the parts of the type 2153 /// residing in the low word of the containing object. 2154 /// 2155 /// \param Hi - The classification for the parts of the type 2156 /// residing in the high word of the containing object. 2157 /// 2158 /// \param OffsetBase - The bit offset of this type in the 2159 /// containing object. Some parameters are classified different 2160 /// depending on whether they straddle an eightbyte boundary. 2161 /// 2162 /// \param isNamedArg - Whether the argument in question is a "named" 2163 /// argument, as used in AMD64-ABI 3.5.7. 2164 /// 2165 /// If a word is unused its result will be NoClass; if a type should 2166 /// be passed in Memory then at least the classification of \arg Lo 2167 /// will be Memory. 2168 /// 2169 /// The \arg Lo class will be NoClass iff the argument is ignored. 2170 /// 2171 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will 2172 /// also be ComplexX87. 2173 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi, 2174 bool isNamedArg) const; 2175 2176 llvm::Type *GetByteVectorType(QualType Ty) const; 2177 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType, 2178 unsigned IROffset, QualType SourceTy, 2179 unsigned SourceOffset) const; 2180 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType, 2181 unsigned IROffset, QualType SourceTy, 2182 unsigned SourceOffset) const; 2183 2184 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 2185 /// such that the argument will be returned in memory. 2186 ABIArgInfo getIndirectReturnResult(QualType Ty) const; 2187 2188 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 2189 /// such that the argument will be passed in memory. 2190 /// 2191 /// \param freeIntRegs - The number of free integer registers remaining 2192 /// available. 2193 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const; 2194 2195 ABIArgInfo classifyReturnType(QualType RetTy) const; 2196 2197 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs, 2198 unsigned &neededInt, unsigned &neededSSE, 2199 bool isNamedArg) const; 2200 2201 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt, 2202 unsigned &NeededSSE) const; 2203 2204 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt, 2205 unsigned &NeededSSE) const; 2206 2207 bool IsIllegalVectorType(QualType Ty) const; 2208 2209 /// The 0.98 ABI revision clarified a lot of ambiguities, 2210 /// unfortunately in ways that were not always consistent with 2211 /// certain previous compilers. In particular, platforms which 2212 /// required strict binary compatibility with older versions of GCC 2213 /// may need to exempt themselves. 2214 bool honorsRevision0_98() const { 2215 return !getTarget().getTriple().isOSDarwin(); 2216 } 2217 2218 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to 2219 /// classify it as INTEGER (for compatibility with older clang compilers). 2220 bool classifyIntegerMMXAsSSE() const { 2221 // Clang <= 3.8 did not do this. 2222 if (getContext().getLangOpts().getClangABICompat() <= 2223 LangOptions::ClangABI::Ver3_8) 2224 return false; 2225 2226 const llvm::Triple &Triple = getTarget().getTriple(); 2227 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4) 2228 return false; 2229 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10) 2230 return false; 2231 return true; 2232 } 2233 2234 // GCC classifies vectors of __int128 as memory. 2235 bool passInt128VectorsInMem() const { 2236 // Clang <= 9.0 did not do this. 2237 if (getContext().getLangOpts().getClangABICompat() <= 2238 LangOptions::ClangABI::Ver9) 2239 return false; 2240 2241 const llvm::Triple &T = getTarget().getTriple(); 2242 return T.isOSLinux() || T.isOSNetBSD(); 2243 } 2244 2245 X86AVXABILevel AVXLevel; 2246 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on 2247 // 64-bit hardware. 2248 bool Has64BitPointers; 2249 2250 public: 2251 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) : 2252 SwiftABIInfo(CGT), AVXLevel(AVXLevel), 2253 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) { 2254 } 2255 2256 bool isPassedUsingAVXType(QualType type) const { 2257 unsigned neededInt, neededSSE; 2258 // The freeIntRegs argument doesn't matter here. 2259 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE, 2260 /*isNamedArg*/true); 2261 if (info.isDirect()) { 2262 llvm::Type *ty = info.getCoerceToType(); 2263 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty)) 2264 return vectorTy->getPrimitiveSizeInBits().getFixedSize() > 128; 2265 } 2266 return false; 2267 } 2268 2269 void computeInfo(CGFunctionInfo &FI) const override; 2270 2271 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 2272 QualType Ty) const override; 2273 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 2274 QualType Ty) const override; 2275 2276 bool has64BitPointers() const { 2277 return Has64BitPointers; 2278 } 2279 2280 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 2281 bool asReturnValue) const override { 2282 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 2283 } 2284 bool isSwiftErrorInRegister() const override { 2285 return true; 2286 } 2287 }; 2288 2289 /// WinX86_64ABIInfo - The Windows X86_64 ABI information. 2290 class WinX86_64ABIInfo : public SwiftABIInfo { 2291 public: 2292 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) 2293 : SwiftABIInfo(CGT), AVXLevel(AVXLevel), 2294 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {} 2295 2296 void computeInfo(CGFunctionInfo &FI) const override; 2297 2298 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 2299 QualType Ty) const override; 2300 2301 bool isHomogeneousAggregateBaseType(QualType Ty) const override { 2302 // FIXME: Assumes vectorcall is in use. 2303 return isX86VectorTypeForVectorCall(getContext(), Ty); 2304 } 2305 2306 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 2307 uint64_t NumMembers) const override { 2308 // FIXME: Assumes vectorcall is in use. 2309 return isX86VectorCallAggregateSmallEnough(NumMembers); 2310 } 2311 2312 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars, 2313 bool asReturnValue) const override { 2314 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 2315 } 2316 2317 bool isSwiftErrorInRegister() const override { 2318 return true; 2319 } 2320 2321 private: 2322 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType, 2323 bool IsVectorCall, bool IsRegCall) const; 2324 ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs, 2325 const ABIArgInfo ¤t) const; 2326 void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs, 2327 bool IsVectorCall, bool IsRegCall) const; 2328 2329 X86AVXABILevel AVXLevel; 2330 2331 bool IsMingw64; 2332 }; 2333 2334 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo { 2335 public: 2336 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) 2337 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {} 2338 2339 const X86_64ABIInfo &getABIInfo() const { 2340 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo()); 2341 } 2342 2343 /// Disable tail call on x86-64. The epilogue code before the tail jump blocks 2344 /// the autoreleaseRV/retainRV optimization. 2345 bool shouldSuppressTailCallsOfRetainAutoreleasedReturnValue() const override { 2346 return true; 2347 } 2348 2349 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 2350 return 7; 2351 } 2352 2353 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2354 llvm::Value *Address) const override { 2355 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 2356 2357 // 0-15 are the 16 integer registers. 2358 // 16 is %rip. 2359 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 2360 return false; 2361 } 2362 2363 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 2364 StringRef Constraint, 2365 llvm::Type* Ty) const override { 2366 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 2367 } 2368 2369 bool isNoProtoCallVariadic(const CallArgList &args, 2370 const FunctionNoProtoType *fnType) const override { 2371 // The default CC on x86-64 sets %al to the number of SSA 2372 // registers used, and GCC sets this when calling an unprototyped 2373 // function, so we override the default behavior. However, don't do 2374 // that when AVX types are involved: the ABI explicitly states it is 2375 // undefined, and it doesn't work in practice because of how the ABI 2376 // defines varargs anyway. 2377 if (fnType->getCallConv() == CC_C) { 2378 bool HasAVXType = false; 2379 for (CallArgList::const_iterator 2380 it = args.begin(), ie = args.end(); it != ie; ++it) { 2381 if (getABIInfo().isPassedUsingAVXType(it->Ty)) { 2382 HasAVXType = true; 2383 break; 2384 } 2385 } 2386 2387 if (!HasAVXType) 2388 return true; 2389 } 2390 2391 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType); 2392 } 2393 2394 llvm::Constant * 2395 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { 2396 unsigned Sig = (0xeb << 0) | // jmp rel8 2397 (0x06 << 8) | // .+0x08 2398 ('v' << 16) | 2399 ('2' << 24); 2400 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 2401 } 2402 2403 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2404 CodeGen::CodeGenModule &CGM) const override { 2405 if (GV->isDeclaration()) 2406 return; 2407 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2408 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2409 llvm::Function *Fn = cast<llvm::Function>(GV); 2410 Fn->addFnAttr("stackrealign"); 2411 } 2412 if (FD->hasAttr<AnyX86InterruptAttr>()) { 2413 llvm::Function *Fn = cast<llvm::Function>(GV); 2414 Fn->setCallingConv(llvm::CallingConv::X86_INTR); 2415 } 2416 } 2417 } 2418 }; 2419 2420 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) { 2421 // If the argument does not end in .lib, automatically add the suffix. 2422 // If the argument contains a space, enclose it in quotes. 2423 // This matches the behavior of MSVC. 2424 bool Quote = (Lib.find(" ") != StringRef::npos); 2425 std::string ArgStr = Quote ? "\"" : ""; 2426 ArgStr += Lib; 2427 if (!Lib.endswith_lower(".lib") && !Lib.endswith_lower(".a")) 2428 ArgStr += ".lib"; 2429 ArgStr += Quote ? "\"" : ""; 2430 return ArgStr; 2431 } 2432 2433 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo { 2434 public: 2435 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 2436 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI, 2437 unsigned NumRegisterParameters) 2438 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI, 2439 Win32StructABI, NumRegisterParameters, false) {} 2440 2441 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2442 CodeGen::CodeGenModule &CGM) const override; 2443 2444 void getDependentLibraryOption(llvm::StringRef Lib, 2445 llvm::SmallString<24> &Opt) const override { 2446 Opt = "/DEFAULTLIB:"; 2447 Opt += qualifyWindowsLibrary(Lib); 2448 } 2449 2450 void getDetectMismatchOption(llvm::StringRef Name, 2451 llvm::StringRef Value, 2452 llvm::SmallString<32> &Opt) const override { 2453 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 2454 } 2455 }; 2456 2457 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2458 CodeGen::CodeGenModule &CGM) { 2459 if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) { 2460 2461 if (CGM.getCodeGenOpts().StackProbeSize != 4096) 2462 Fn->addFnAttr("stack-probe-size", 2463 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize)); 2464 if (CGM.getCodeGenOpts().NoStackArgProbe) 2465 Fn->addFnAttr("no-stack-arg-probe"); 2466 } 2467 } 2468 2469 void WinX86_32TargetCodeGenInfo::setTargetAttributes( 2470 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2471 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 2472 if (GV->isDeclaration()) 2473 return; 2474 addStackProbeTargetAttributes(D, GV, CGM); 2475 } 2476 2477 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo { 2478 public: 2479 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 2480 X86AVXABILevel AVXLevel) 2481 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT, AVXLevel)) {} 2482 2483 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2484 CodeGen::CodeGenModule &CGM) const override; 2485 2486 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 2487 return 7; 2488 } 2489 2490 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2491 llvm::Value *Address) const override { 2492 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 2493 2494 // 0-15 are the 16 integer registers. 2495 // 16 is %rip. 2496 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 2497 return false; 2498 } 2499 2500 void getDependentLibraryOption(llvm::StringRef Lib, 2501 llvm::SmallString<24> &Opt) const override { 2502 Opt = "/DEFAULTLIB:"; 2503 Opt += qualifyWindowsLibrary(Lib); 2504 } 2505 2506 void getDetectMismatchOption(llvm::StringRef Name, 2507 llvm::StringRef Value, 2508 llvm::SmallString<32> &Opt) const override { 2509 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 2510 } 2511 }; 2512 2513 void WinX86_64TargetCodeGenInfo::setTargetAttributes( 2514 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2515 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 2516 if (GV->isDeclaration()) 2517 return; 2518 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2519 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2520 llvm::Function *Fn = cast<llvm::Function>(GV); 2521 Fn->addFnAttr("stackrealign"); 2522 } 2523 if (FD->hasAttr<AnyX86InterruptAttr>()) { 2524 llvm::Function *Fn = cast<llvm::Function>(GV); 2525 Fn->setCallingConv(llvm::CallingConv::X86_INTR); 2526 } 2527 } 2528 2529 addStackProbeTargetAttributes(D, GV, CGM); 2530 } 2531 } 2532 2533 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo, 2534 Class &Hi) const { 2535 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done: 2536 // 2537 // (a) If one of the classes is Memory, the whole argument is passed in 2538 // memory. 2539 // 2540 // (b) If X87UP is not preceded by X87, the whole argument is passed in 2541 // memory. 2542 // 2543 // (c) If the size of the aggregate exceeds two eightbytes and the first 2544 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole 2545 // argument is passed in memory. NOTE: This is necessary to keep the 2546 // ABI working for processors that don't support the __m256 type. 2547 // 2548 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE. 2549 // 2550 // Some of these are enforced by the merging logic. Others can arise 2551 // only with unions; for example: 2552 // union { _Complex double; unsigned; } 2553 // 2554 // Note that clauses (b) and (c) were added in 0.98. 2555 // 2556 if (Hi == Memory) 2557 Lo = Memory; 2558 if (Hi == X87Up && Lo != X87 && honorsRevision0_98()) 2559 Lo = Memory; 2560 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp)) 2561 Lo = Memory; 2562 if (Hi == SSEUp && Lo != SSE) 2563 Hi = SSE; 2564 } 2565 2566 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) { 2567 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is 2568 // classified recursively so that always two fields are 2569 // considered. The resulting class is calculated according to 2570 // the classes of the fields in the eightbyte: 2571 // 2572 // (a) If both classes are equal, this is the resulting class. 2573 // 2574 // (b) If one of the classes is NO_CLASS, the resulting class is 2575 // the other class. 2576 // 2577 // (c) If one of the classes is MEMORY, the result is the MEMORY 2578 // class. 2579 // 2580 // (d) If one of the classes is INTEGER, the result is the 2581 // INTEGER. 2582 // 2583 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class, 2584 // MEMORY is used as class. 2585 // 2586 // (f) Otherwise class SSE is used. 2587 2588 // Accum should never be memory (we should have returned) or 2589 // ComplexX87 (because this cannot be passed in a structure). 2590 assert((Accum != Memory && Accum != ComplexX87) && 2591 "Invalid accumulated classification during merge."); 2592 if (Accum == Field || Field == NoClass) 2593 return Accum; 2594 if (Field == Memory) 2595 return Memory; 2596 if (Accum == NoClass) 2597 return Field; 2598 if (Accum == Integer || Field == Integer) 2599 return Integer; 2600 if (Field == X87 || Field == X87Up || Field == ComplexX87 || 2601 Accum == X87 || Accum == X87Up) 2602 return Memory; 2603 return SSE; 2604 } 2605 2606 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase, 2607 Class &Lo, Class &Hi, bool isNamedArg) const { 2608 // FIXME: This code can be simplified by introducing a simple value class for 2609 // Class pairs with appropriate constructor methods for the various 2610 // situations. 2611 2612 // FIXME: Some of the split computations are wrong; unaligned vectors 2613 // shouldn't be passed in registers for example, so there is no chance they 2614 // can straddle an eightbyte. Verify & simplify. 2615 2616 Lo = Hi = NoClass; 2617 2618 Class &Current = OffsetBase < 64 ? Lo : Hi; 2619 Current = Memory; 2620 2621 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 2622 BuiltinType::Kind k = BT->getKind(); 2623 2624 if (k == BuiltinType::Void) { 2625 Current = NoClass; 2626 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) { 2627 Lo = Integer; 2628 Hi = Integer; 2629 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) { 2630 Current = Integer; 2631 } else if (k == BuiltinType::Float || k == BuiltinType::Double) { 2632 Current = SSE; 2633 } else if (k == BuiltinType::LongDouble) { 2634 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 2635 if (LDF == &llvm::APFloat::IEEEquad()) { 2636 Lo = SSE; 2637 Hi = SSEUp; 2638 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) { 2639 Lo = X87; 2640 Hi = X87Up; 2641 } else if (LDF == &llvm::APFloat::IEEEdouble()) { 2642 Current = SSE; 2643 } else 2644 llvm_unreachable("unexpected long double representation!"); 2645 } 2646 // FIXME: _Decimal32 and _Decimal64 are SSE. 2647 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp). 2648 return; 2649 } 2650 2651 if (const EnumType *ET = Ty->getAs<EnumType>()) { 2652 // Classify the underlying integer type. 2653 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg); 2654 return; 2655 } 2656 2657 if (Ty->hasPointerRepresentation()) { 2658 Current = Integer; 2659 return; 2660 } 2661 2662 if (Ty->isMemberPointerType()) { 2663 if (Ty->isMemberFunctionPointerType()) { 2664 if (Has64BitPointers) { 2665 // If Has64BitPointers, this is an {i64, i64}, so classify both 2666 // Lo and Hi now. 2667 Lo = Hi = Integer; 2668 } else { 2669 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that 2670 // straddles an eightbyte boundary, Hi should be classified as well. 2671 uint64_t EB_FuncPtr = (OffsetBase) / 64; 2672 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64; 2673 if (EB_FuncPtr != EB_ThisAdj) { 2674 Lo = Hi = Integer; 2675 } else { 2676 Current = Integer; 2677 } 2678 } 2679 } else { 2680 Current = Integer; 2681 } 2682 return; 2683 } 2684 2685 if (const VectorType *VT = Ty->getAs<VectorType>()) { 2686 uint64_t Size = getContext().getTypeSize(VT); 2687 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) { 2688 // gcc passes the following as integer: 2689 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float> 2690 // 2 bytes - <2 x char>, <1 x short> 2691 // 1 byte - <1 x char> 2692 Current = Integer; 2693 2694 // If this type crosses an eightbyte boundary, it should be 2695 // split. 2696 uint64_t EB_Lo = (OffsetBase) / 64; 2697 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64; 2698 if (EB_Lo != EB_Hi) 2699 Hi = Lo; 2700 } else if (Size == 64) { 2701 QualType ElementType = VT->getElementType(); 2702 2703 // gcc passes <1 x double> in memory. :( 2704 if (ElementType->isSpecificBuiltinType(BuiltinType::Double)) 2705 return; 2706 2707 // gcc passes <1 x long long> as SSE but clang used to unconditionally 2708 // pass them as integer. For platforms where clang is the de facto 2709 // platform compiler, we must continue to use integer. 2710 if (!classifyIntegerMMXAsSSE() && 2711 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) || 2712 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) || 2713 ElementType->isSpecificBuiltinType(BuiltinType::Long) || 2714 ElementType->isSpecificBuiltinType(BuiltinType::ULong))) 2715 Current = Integer; 2716 else 2717 Current = SSE; 2718 2719 // If this type crosses an eightbyte boundary, it should be 2720 // split. 2721 if (OffsetBase && OffsetBase != 64) 2722 Hi = Lo; 2723 } else if (Size == 128 || 2724 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) { 2725 QualType ElementType = VT->getElementType(); 2726 2727 // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :( 2728 if (passInt128VectorsInMem() && Size != 128 && 2729 (ElementType->isSpecificBuiltinType(BuiltinType::Int128) || 2730 ElementType->isSpecificBuiltinType(BuiltinType::UInt128))) 2731 return; 2732 2733 // Arguments of 256-bits are split into four eightbyte chunks. The 2734 // least significant one belongs to class SSE and all the others to class 2735 // SSEUP. The original Lo and Hi design considers that types can't be 2736 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense. 2737 // This design isn't correct for 256-bits, but since there're no cases 2738 // where the upper parts would need to be inspected, avoid adding 2739 // complexity and just consider Hi to match the 64-256 part. 2740 // 2741 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in 2742 // registers if they are "named", i.e. not part of the "..." of a 2743 // variadic function. 2744 // 2745 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are 2746 // split into eight eightbyte chunks, one SSE and seven SSEUP. 2747 Lo = SSE; 2748 Hi = SSEUp; 2749 } 2750 return; 2751 } 2752 2753 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 2754 QualType ET = getContext().getCanonicalType(CT->getElementType()); 2755 2756 uint64_t Size = getContext().getTypeSize(Ty); 2757 if (ET->isIntegralOrEnumerationType()) { 2758 if (Size <= 64) 2759 Current = Integer; 2760 else if (Size <= 128) 2761 Lo = Hi = Integer; 2762 } else if (ET == getContext().FloatTy) { 2763 Current = SSE; 2764 } else if (ET == getContext().DoubleTy) { 2765 Lo = Hi = SSE; 2766 } else if (ET == getContext().LongDoubleTy) { 2767 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 2768 if (LDF == &llvm::APFloat::IEEEquad()) 2769 Current = Memory; 2770 else if (LDF == &llvm::APFloat::x87DoubleExtended()) 2771 Current = ComplexX87; 2772 else if (LDF == &llvm::APFloat::IEEEdouble()) 2773 Lo = Hi = SSE; 2774 else 2775 llvm_unreachable("unexpected long double representation!"); 2776 } 2777 2778 // If this complex type crosses an eightbyte boundary then it 2779 // should be split. 2780 uint64_t EB_Real = (OffsetBase) / 64; 2781 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64; 2782 if (Hi == NoClass && EB_Real != EB_Imag) 2783 Hi = Lo; 2784 2785 return; 2786 } 2787 2788 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 2789 // Arrays are treated like structures. 2790 2791 uint64_t Size = getContext().getTypeSize(Ty); 2792 2793 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 2794 // than eight eightbytes, ..., it has class MEMORY. 2795 if (Size > 512) 2796 return; 2797 2798 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned 2799 // fields, it has class MEMORY. 2800 // 2801 // Only need to check alignment of array base. 2802 if (OffsetBase % getContext().getTypeAlign(AT->getElementType())) 2803 return; 2804 2805 // Otherwise implement simplified merge. We could be smarter about 2806 // this, but it isn't worth it and would be harder to verify. 2807 Current = NoClass; 2808 uint64_t EltSize = getContext().getTypeSize(AT->getElementType()); 2809 uint64_t ArraySize = AT->getSize().getZExtValue(); 2810 2811 // The only case a 256-bit wide vector could be used is when the array 2812 // contains a single 256-bit element. Since Lo and Hi logic isn't extended 2813 // to work for sizes wider than 128, early check and fallback to memory. 2814 // 2815 if (Size > 128 && 2816 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel))) 2817 return; 2818 2819 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) { 2820 Class FieldLo, FieldHi; 2821 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg); 2822 Lo = merge(Lo, FieldLo); 2823 Hi = merge(Hi, FieldHi); 2824 if (Lo == Memory || Hi == Memory) 2825 break; 2826 } 2827 2828 postMerge(Size, Lo, Hi); 2829 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification."); 2830 return; 2831 } 2832 2833 if (const RecordType *RT = Ty->getAs<RecordType>()) { 2834 uint64_t Size = getContext().getTypeSize(Ty); 2835 2836 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 2837 // than eight eightbytes, ..., it has class MEMORY. 2838 if (Size > 512) 2839 return; 2840 2841 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial 2842 // copy constructor or a non-trivial destructor, it is passed by invisible 2843 // reference. 2844 if (getRecordArgABI(RT, getCXXABI())) 2845 return; 2846 2847 const RecordDecl *RD = RT->getDecl(); 2848 2849 // Assume variable sized types are passed in memory. 2850 if (RD->hasFlexibleArrayMember()) 2851 return; 2852 2853 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 2854 2855 // Reset Lo class, this will be recomputed. 2856 Current = NoClass; 2857 2858 // If this is a C++ record, classify the bases first. 2859 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 2860 for (const auto &I : CXXRD->bases()) { 2861 assert(!I.isVirtual() && !I.getType()->isDependentType() && 2862 "Unexpected base class!"); 2863 const auto *Base = 2864 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 2865 2866 // Classify this field. 2867 // 2868 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a 2869 // single eightbyte, each is classified separately. Each eightbyte gets 2870 // initialized to class NO_CLASS. 2871 Class FieldLo, FieldHi; 2872 uint64_t Offset = 2873 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base)); 2874 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg); 2875 Lo = merge(Lo, FieldLo); 2876 Hi = merge(Hi, FieldHi); 2877 if (Lo == Memory || Hi == Memory) { 2878 postMerge(Size, Lo, Hi); 2879 return; 2880 } 2881 } 2882 } 2883 2884 // Classify the fields one at a time, merging the results. 2885 unsigned idx = 0; 2886 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 2887 i != e; ++i, ++idx) { 2888 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 2889 bool BitField = i->isBitField(); 2890 2891 // Ignore padding bit-fields. 2892 if (BitField && i->isUnnamedBitfield()) 2893 continue; 2894 2895 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than 2896 // four eightbytes, or it contains unaligned fields, it has class MEMORY. 2897 // 2898 // The only case a 256-bit wide vector could be used is when the struct 2899 // contains a single 256-bit element. Since Lo and Hi logic isn't extended 2900 // to work for sizes wider than 128, early check and fallback to memory. 2901 // 2902 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) || 2903 Size > getNativeVectorSizeForAVXABI(AVXLevel))) { 2904 Lo = Memory; 2905 postMerge(Size, Lo, Hi); 2906 return; 2907 } 2908 // Note, skip this test for bit-fields, see below. 2909 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) { 2910 Lo = Memory; 2911 postMerge(Size, Lo, Hi); 2912 return; 2913 } 2914 2915 // Classify this field. 2916 // 2917 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate 2918 // exceeds a single eightbyte, each is classified 2919 // separately. Each eightbyte gets initialized to class 2920 // NO_CLASS. 2921 Class FieldLo, FieldHi; 2922 2923 // Bit-fields require special handling, they do not force the 2924 // structure to be passed in memory even if unaligned, and 2925 // therefore they can straddle an eightbyte. 2926 if (BitField) { 2927 assert(!i->isUnnamedBitfield()); 2928 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 2929 uint64_t Size = i->getBitWidthValue(getContext()); 2930 2931 uint64_t EB_Lo = Offset / 64; 2932 uint64_t EB_Hi = (Offset + Size - 1) / 64; 2933 2934 if (EB_Lo) { 2935 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes."); 2936 FieldLo = NoClass; 2937 FieldHi = Integer; 2938 } else { 2939 FieldLo = Integer; 2940 FieldHi = EB_Hi ? Integer : NoClass; 2941 } 2942 } else 2943 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg); 2944 Lo = merge(Lo, FieldLo); 2945 Hi = merge(Hi, FieldHi); 2946 if (Lo == Memory || Hi == Memory) 2947 break; 2948 } 2949 2950 postMerge(Size, Lo, Hi); 2951 } 2952 } 2953 2954 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const { 2955 // If this is a scalar LLVM value then assume LLVM will pass it in the right 2956 // place naturally. 2957 if (!isAggregateTypeForABI(Ty)) { 2958 // Treat an enum type as its underlying type. 2959 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 2960 Ty = EnumTy->getDecl()->getIntegerType(); 2961 2962 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 2963 : ABIArgInfo::getDirect()); 2964 } 2965 2966 return getNaturalAlignIndirect(Ty); 2967 } 2968 2969 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const { 2970 if (const VectorType *VecTy = Ty->getAs<VectorType>()) { 2971 uint64_t Size = getContext().getTypeSize(VecTy); 2972 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel); 2973 if (Size <= 64 || Size > LargestVector) 2974 return true; 2975 QualType EltTy = VecTy->getElementType(); 2976 if (passInt128VectorsInMem() && 2977 (EltTy->isSpecificBuiltinType(BuiltinType::Int128) || 2978 EltTy->isSpecificBuiltinType(BuiltinType::UInt128))) 2979 return true; 2980 } 2981 2982 return false; 2983 } 2984 2985 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty, 2986 unsigned freeIntRegs) const { 2987 // If this is a scalar LLVM value then assume LLVM will pass it in the right 2988 // place naturally. 2989 // 2990 // This assumption is optimistic, as there could be free registers available 2991 // when we need to pass this argument in memory, and LLVM could try to pass 2992 // the argument in the free register. This does not seem to happen currently, 2993 // but this code would be much safer if we could mark the argument with 2994 // 'onstack'. See PR12193. 2995 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) { 2996 // Treat an enum type as its underlying type. 2997 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 2998 Ty = EnumTy->getDecl()->getIntegerType(); 2999 3000 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 3001 : ABIArgInfo::getDirect()); 3002 } 3003 3004 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 3005 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 3006 3007 // Compute the byval alignment. We specify the alignment of the byval in all 3008 // cases so that the mid-level optimizer knows the alignment of the byval. 3009 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U); 3010 3011 // Attempt to avoid passing indirect results using byval when possible. This 3012 // is important for good codegen. 3013 // 3014 // We do this by coercing the value into a scalar type which the backend can 3015 // handle naturally (i.e., without using byval). 3016 // 3017 // For simplicity, we currently only do this when we have exhausted all of the 3018 // free integer registers. Doing this when there are free integer registers 3019 // would require more care, as we would have to ensure that the coerced value 3020 // did not claim the unused register. That would require either reording the 3021 // arguments to the function (so that any subsequent inreg values came first), 3022 // or only doing this optimization when there were no following arguments that 3023 // might be inreg. 3024 // 3025 // We currently expect it to be rare (particularly in well written code) for 3026 // arguments to be passed on the stack when there are still free integer 3027 // registers available (this would typically imply large structs being passed 3028 // by value), so this seems like a fair tradeoff for now. 3029 // 3030 // We can revisit this if the backend grows support for 'onstack' parameter 3031 // attributes. See PR12193. 3032 if (freeIntRegs == 0) { 3033 uint64_t Size = getContext().getTypeSize(Ty); 3034 3035 // If this type fits in an eightbyte, coerce it into the matching integral 3036 // type, which will end up on the stack (with alignment 8). 3037 if (Align == 8 && Size <= 64) 3038 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 3039 Size)); 3040 } 3041 3042 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align)); 3043 } 3044 3045 /// The ABI specifies that a value should be passed in a full vector XMM/YMM 3046 /// register. Pick an LLVM IR type that will be passed as a vector register. 3047 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const { 3048 // Wrapper structs/arrays that only contain vectors are passed just like 3049 // vectors; strip them off if present. 3050 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext())) 3051 Ty = QualType(InnerTy, 0); 3052 3053 llvm::Type *IRType = CGT.ConvertType(Ty); 3054 if (isa<llvm::VectorType>(IRType)) { 3055 // Don't pass vXi128 vectors in their native type, the backend can't 3056 // legalize them. 3057 if (passInt128VectorsInMem() && 3058 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) { 3059 // Use a vXi64 vector. 3060 uint64_t Size = getContext().getTypeSize(Ty); 3061 return llvm::VectorType::get(llvm::Type::getInt64Ty(getVMContext()), 3062 Size / 64); 3063 } 3064 3065 return IRType; 3066 } 3067 3068 if (IRType->getTypeID() == llvm::Type::FP128TyID) 3069 return IRType; 3070 3071 // We couldn't find the preferred IR vector type for 'Ty'. 3072 uint64_t Size = getContext().getTypeSize(Ty); 3073 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!"); 3074 3075 3076 // Return a LLVM IR vector type based on the size of 'Ty'. 3077 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 3078 Size / 64); 3079 } 3080 3081 /// BitsContainNoUserData - Return true if the specified [start,end) bit range 3082 /// is known to either be off the end of the specified type or being in 3083 /// alignment padding. The user type specified is known to be at most 128 bits 3084 /// in size, and have passed through X86_64ABIInfo::classify with a successful 3085 /// classification that put one of the two halves in the INTEGER class. 3086 /// 3087 /// It is conservatively correct to return false. 3088 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit, 3089 unsigned EndBit, ASTContext &Context) { 3090 // If the bytes being queried are off the end of the type, there is no user 3091 // data hiding here. This handles analysis of builtins, vectors and other 3092 // types that don't contain interesting padding. 3093 unsigned TySize = (unsigned)Context.getTypeSize(Ty); 3094 if (TySize <= StartBit) 3095 return true; 3096 3097 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { 3098 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType()); 3099 unsigned NumElts = (unsigned)AT->getSize().getZExtValue(); 3100 3101 // Check each element to see if the element overlaps with the queried range. 3102 for (unsigned i = 0; i != NumElts; ++i) { 3103 // If the element is after the span we care about, then we're done.. 3104 unsigned EltOffset = i*EltSize; 3105 if (EltOffset >= EndBit) break; 3106 3107 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0; 3108 if (!BitsContainNoUserData(AT->getElementType(), EltStart, 3109 EndBit-EltOffset, Context)) 3110 return false; 3111 } 3112 // If it overlaps no elements, then it is safe to process as padding. 3113 return true; 3114 } 3115 3116 if (const RecordType *RT = Ty->getAs<RecordType>()) { 3117 const RecordDecl *RD = RT->getDecl(); 3118 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 3119 3120 // If this is a C++ record, check the bases first. 3121 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 3122 for (const auto &I : CXXRD->bases()) { 3123 assert(!I.isVirtual() && !I.getType()->isDependentType() && 3124 "Unexpected base class!"); 3125 const auto *Base = 3126 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 3127 3128 // If the base is after the span we care about, ignore it. 3129 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base)); 3130 if (BaseOffset >= EndBit) continue; 3131 3132 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0; 3133 if (!BitsContainNoUserData(I.getType(), BaseStart, 3134 EndBit-BaseOffset, Context)) 3135 return false; 3136 } 3137 } 3138 3139 // Verify that no field has data that overlaps the region of interest. Yes 3140 // this could be sped up a lot by being smarter about queried fields, 3141 // however we're only looking at structs up to 16 bytes, so we don't care 3142 // much. 3143 unsigned idx = 0; 3144 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3145 i != e; ++i, ++idx) { 3146 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx); 3147 3148 // If we found a field after the region we care about, then we're done. 3149 if (FieldOffset >= EndBit) break; 3150 3151 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0; 3152 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset, 3153 Context)) 3154 return false; 3155 } 3156 3157 // If nothing in this record overlapped the area of interest, then we're 3158 // clean. 3159 return true; 3160 } 3161 3162 return false; 3163 } 3164 3165 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a 3166 /// float member at the specified offset. For example, {int,{float}} has a 3167 /// float at offset 4. It is conservatively correct for this routine to return 3168 /// false. 3169 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset, 3170 const llvm::DataLayout &TD) { 3171 // Base case if we find a float. 3172 if (IROffset == 0 && IRType->isFloatTy()) 3173 return true; 3174 3175 // If this is a struct, recurse into the field at the specified offset. 3176 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 3177 const llvm::StructLayout *SL = TD.getStructLayout(STy); 3178 unsigned Elt = SL->getElementContainingOffset(IROffset); 3179 IROffset -= SL->getElementOffset(Elt); 3180 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD); 3181 } 3182 3183 // If this is an array, recurse into the field at the specified offset. 3184 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 3185 llvm::Type *EltTy = ATy->getElementType(); 3186 unsigned EltSize = TD.getTypeAllocSize(EltTy); 3187 IROffset -= IROffset/EltSize*EltSize; 3188 return ContainsFloatAtOffset(EltTy, IROffset, TD); 3189 } 3190 3191 return false; 3192 } 3193 3194 3195 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the 3196 /// low 8 bytes of an XMM register, corresponding to the SSE class. 3197 llvm::Type *X86_64ABIInfo:: 3198 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset, 3199 QualType SourceTy, unsigned SourceOffset) const { 3200 // The only three choices we have are either double, <2 x float>, or float. We 3201 // pass as float if the last 4 bytes is just padding. This happens for 3202 // structs that contain 3 floats. 3203 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32, 3204 SourceOffset*8+64, getContext())) 3205 return llvm::Type::getFloatTy(getVMContext()); 3206 3207 // We want to pass as <2 x float> if the LLVM IR type contains a float at 3208 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the 3209 // case. 3210 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) && 3211 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout())) 3212 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2); 3213 3214 return llvm::Type::getDoubleTy(getVMContext()); 3215 } 3216 3217 3218 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in 3219 /// an 8-byte GPR. This means that we either have a scalar or we are talking 3220 /// about the high or low part of an up-to-16-byte struct. This routine picks 3221 /// the best LLVM IR type to represent this, which may be i64 or may be anything 3222 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*, 3223 /// etc). 3224 /// 3225 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for 3226 /// the source type. IROffset is an offset in bytes into the LLVM IR type that 3227 /// the 8-byte value references. PrefType may be null. 3228 /// 3229 /// SourceTy is the source-level type for the entire argument. SourceOffset is 3230 /// an offset into this that we're processing (which is always either 0 or 8). 3231 /// 3232 llvm::Type *X86_64ABIInfo:: 3233 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset, 3234 QualType SourceTy, unsigned SourceOffset) const { 3235 // If we're dealing with an un-offset LLVM IR type, then it means that we're 3236 // returning an 8-byte unit starting with it. See if we can safely use it. 3237 if (IROffset == 0) { 3238 // Pointers and int64's always fill the 8-byte unit. 3239 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) || 3240 IRType->isIntegerTy(64)) 3241 return IRType; 3242 3243 // If we have a 1/2/4-byte integer, we can use it only if the rest of the 3244 // goodness in the source type is just tail padding. This is allowed to 3245 // kick in for struct {double,int} on the int, but not on 3246 // struct{double,int,int} because we wouldn't return the second int. We 3247 // have to do this analysis on the source type because we can't depend on 3248 // unions being lowered a specific way etc. 3249 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) || 3250 IRType->isIntegerTy(32) || 3251 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) { 3252 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 : 3253 cast<llvm::IntegerType>(IRType)->getBitWidth(); 3254 3255 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth, 3256 SourceOffset*8+64, getContext())) 3257 return IRType; 3258 } 3259 } 3260 3261 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 3262 // If this is a struct, recurse into the field at the specified offset. 3263 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy); 3264 if (IROffset < SL->getSizeInBytes()) { 3265 unsigned FieldIdx = SL->getElementContainingOffset(IROffset); 3266 IROffset -= SL->getElementOffset(FieldIdx); 3267 3268 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset, 3269 SourceTy, SourceOffset); 3270 } 3271 } 3272 3273 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 3274 llvm::Type *EltTy = ATy->getElementType(); 3275 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy); 3276 unsigned EltOffset = IROffset/EltSize*EltSize; 3277 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy, 3278 SourceOffset); 3279 } 3280 3281 // Okay, we don't have any better idea of what to pass, so we pass this in an 3282 // integer register that isn't too big to fit the rest of the struct. 3283 unsigned TySizeInBytes = 3284 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity(); 3285 3286 assert(TySizeInBytes != SourceOffset && "Empty field?"); 3287 3288 // It is always safe to classify this as an integer type up to i64 that 3289 // isn't larger than the structure. 3290 return llvm::IntegerType::get(getVMContext(), 3291 std::min(TySizeInBytes-SourceOffset, 8U)*8); 3292 } 3293 3294 3295 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally 3296 /// be used as elements of a two register pair to pass or return, return a 3297 /// first class aggregate to represent them. For example, if the low part of 3298 /// a by-value argument should be passed as i32* and the high part as float, 3299 /// return {i32*, float}. 3300 static llvm::Type * 3301 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi, 3302 const llvm::DataLayout &TD) { 3303 // In order to correctly satisfy the ABI, we need to the high part to start 3304 // at offset 8. If the high and low parts we inferred are both 4-byte types 3305 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have 3306 // the second element at offset 8. Check for this: 3307 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo); 3308 unsigned HiAlign = TD.getABITypeAlignment(Hi); 3309 unsigned HiStart = llvm::alignTo(LoSize, HiAlign); 3310 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!"); 3311 3312 // To handle this, we have to increase the size of the low part so that the 3313 // second element will start at an 8 byte offset. We can't increase the size 3314 // of the second element because it might make us access off the end of the 3315 // struct. 3316 if (HiStart != 8) { 3317 // There are usually two sorts of types the ABI generation code can produce 3318 // for the low part of a pair that aren't 8 bytes in size: float or 3319 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and 3320 // NaCl). 3321 // Promote these to a larger type. 3322 if (Lo->isFloatTy()) 3323 Lo = llvm::Type::getDoubleTy(Lo->getContext()); 3324 else { 3325 assert((Lo->isIntegerTy() || Lo->isPointerTy()) 3326 && "Invalid/unknown lo type"); 3327 Lo = llvm::Type::getInt64Ty(Lo->getContext()); 3328 } 3329 } 3330 3331 llvm::StructType *Result = llvm::StructType::get(Lo, Hi); 3332 3333 // Verify that the second element is at an 8-byte offset. 3334 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 && 3335 "Invalid x86-64 argument pair!"); 3336 return Result; 3337 } 3338 3339 ABIArgInfo X86_64ABIInfo:: 3340 classifyReturnType(QualType RetTy) const { 3341 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the 3342 // classification algorithm. 3343 X86_64ABIInfo::Class Lo, Hi; 3344 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true); 3345 3346 // Check some invariants. 3347 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 3348 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 3349 3350 llvm::Type *ResType = nullptr; 3351 switch (Lo) { 3352 case NoClass: 3353 if (Hi == NoClass) 3354 return ABIArgInfo::getIgnore(); 3355 // If the low part is just padding, it takes no register, leave ResType 3356 // null. 3357 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 3358 "Unknown missing lo part"); 3359 break; 3360 3361 case SSEUp: 3362 case X87Up: 3363 llvm_unreachable("Invalid classification for lo word."); 3364 3365 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via 3366 // hidden argument. 3367 case Memory: 3368 return getIndirectReturnResult(RetTy); 3369 3370 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next 3371 // available register of the sequence %rax, %rdx is used. 3372 case Integer: 3373 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 3374 3375 // If we have a sign or zero extended integer, make sure to return Extend 3376 // so that the parameter gets the right LLVM IR attributes. 3377 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 3378 // Treat an enum type as its underlying type. 3379 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 3380 RetTy = EnumTy->getDecl()->getIntegerType(); 3381 3382 if (RetTy->isIntegralOrEnumerationType() && 3383 RetTy->isPromotableIntegerType()) 3384 return ABIArgInfo::getExtend(RetTy); 3385 } 3386 break; 3387 3388 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next 3389 // available SSE register of the sequence %xmm0, %xmm1 is used. 3390 case SSE: 3391 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 3392 break; 3393 3394 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is 3395 // returned on the X87 stack in %st0 as 80-bit x87 number. 3396 case X87: 3397 ResType = llvm::Type::getX86_FP80Ty(getVMContext()); 3398 break; 3399 3400 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real 3401 // part of the value is returned in %st0 and the imaginary part in 3402 // %st1. 3403 case ComplexX87: 3404 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification."); 3405 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()), 3406 llvm::Type::getX86_FP80Ty(getVMContext())); 3407 break; 3408 } 3409 3410 llvm::Type *HighPart = nullptr; 3411 switch (Hi) { 3412 // Memory was handled previously and X87 should 3413 // never occur as a hi class. 3414 case Memory: 3415 case X87: 3416 llvm_unreachable("Invalid classification for hi word."); 3417 3418 case ComplexX87: // Previously handled. 3419 case NoClass: 3420 break; 3421 3422 case Integer: 3423 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3424 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3425 return ABIArgInfo::getDirect(HighPart, 8); 3426 break; 3427 case SSE: 3428 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3429 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3430 return ABIArgInfo::getDirect(HighPart, 8); 3431 break; 3432 3433 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte 3434 // is passed in the next available eightbyte chunk if the last used 3435 // vector register. 3436 // 3437 // SSEUP should always be preceded by SSE, just widen. 3438 case SSEUp: 3439 assert(Lo == SSE && "Unexpected SSEUp classification."); 3440 ResType = GetByteVectorType(RetTy); 3441 break; 3442 3443 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is 3444 // returned together with the previous X87 value in %st0. 3445 case X87Up: 3446 // If X87Up is preceded by X87, we don't need to do 3447 // anything. However, in some cases with unions it may not be 3448 // preceded by X87. In such situations we follow gcc and pass the 3449 // extra bits in an SSE reg. 3450 if (Lo != X87) { 3451 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3452 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3453 return ABIArgInfo::getDirect(HighPart, 8); 3454 } 3455 break; 3456 } 3457 3458 // If a high part was specified, merge it together with the low part. It is 3459 // known to pass in the high eightbyte of the result. We do this by forming a 3460 // first class struct aggregate with the high and low part: {low, high} 3461 if (HighPart) 3462 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 3463 3464 return ABIArgInfo::getDirect(ResType); 3465 } 3466 3467 ABIArgInfo X86_64ABIInfo::classifyArgumentType( 3468 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE, 3469 bool isNamedArg) 3470 const 3471 { 3472 Ty = useFirstFieldIfTransparentUnion(Ty); 3473 3474 X86_64ABIInfo::Class Lo, Hi; 3475 classify(Ty, 0, Lo, Hi, isNamedArg); 3476 3477 // Check some invariants. 3478 // FIXME: Enforce these by construction. 3479 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 3480 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 3481 3482 neededInt = 0; 3483 neededSSE = 0; 3484 llvm::Type *ResType = nullptr; 3485 switch (Lo) { 3486 case NoClass: 3487 if (Hi == NoClass) 3488 return ABIArgInfo::getIgnore(); 3489 // If the low part is just padding, it takes no register, leave ResType 3490 // null. 3491 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 3492 "Unknown missing lo part"); 3493 break; 3494 3495 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument 3496 // on the stack. 3497 case Memory: 3498 3499 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or 3500 // COMPLEX_X87, it is passed in memory. 3501 case X87: 3502 case ComplexX87: 3503 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect) 3504 ++neededInt; 3505 return getIndirectResult(Ty, freeIntRegs); 3506 3507 case SSEUp: 3508 case X87Up: 3509 llvm_unreachable("Invalid classification for lo word."); 3510 3511 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next 3512 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 3513 // and %r9 is used. 3514 case Integer: 3515 ++neededInt; 3516 3517 // Pick an 8-byte type based on the preferred type. 3518 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0); 3519 3520 // If we have a sign or zero extended integer, make sure to return Extend 3521 // so that the parameter gets the right LLVM IR attributes. 3522 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 3523 // Treat an enum type as its underlying type. 3524 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3525 Ty = EnumTy->getDecl()->getIntegerType(); 3526 3527 if (Ty->isIntegralOrEnumerationType() && 3528 Ty->isPromotableIntegerType()) 3529 return ABIArgInfo::getExtend(Ty); 3530 } 3531 3532 break; 3533 3534 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next 3535 // available SSE register is used, the registers are taken in the 3536 // order from %xmm0 to %xmm7. 3537 case SSE: { 3538 llvm::Type *IRType = CGT.ConvertType(Ty); 3539 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0); 3540 ++neededSSE; 3541 break; 3542 } 3543 } 3544 3545 llvm::Type *HighPart = nullptr; 3546 switch (Hi) { 3547 // Memory was handled previously, ComplexX87 and X87 should 3548 // never occur as hi classes, and X87Up must be preceded by X87, 3549 // which is passed in memory. 3550 case Memory: 3551 case X87: 3552 case ComplexX87: 3553 llvm_unreachable("Invalid classification for hi word."); 3554 3555 case NoClass: break; 3556 3557 case Integer: 3558 ++neededInt; 3559 // Pick an 8-byte type based on the preferred type. 3560 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 3561 3562 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 3563 return ABIArgInfo::getDirect(HighPart, 8); 3564 break; 3565 3566 // X87Up generally doesn't occur here (long double is passed in 3567 // memory), except in situations involving unions. 3568 case X87Up: 3569 case SSE: 3570 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 3571 3572 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 3573 return ABIArgInfo::getDirect(HighPart, 8); 3574 3575 ++neededSSE; 3576 break; 3577 3578 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the 3579 // eightbyte is passed in the upper half of the last used SSE 3580 // register. This only happens when 128-bit vectors are passed. 3581 case SSEUp: 3582 assert(Lo == SSE && "Unexpected SSEUp classification"); 3583 ResType = GetByteVectorType(Ty); 3584 break; 3585 } 3586 3587 // If a high part was specified, merge it together with the low part. It is 3588 // known to pass in the high eightbyte of the result. We do this by forming a 3589 // first class struct aggregate with the high and low part: {low, high} 3590 if (HighPart) 3591 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 3592 3593 return ABIArgInfo::getDirect(ResType); 3594 } 3595 3596 ABIArgInfo 3597 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt, 3598 unsigned &NeededSSE) const { 3599 auto RT = Ty->getAs<RecordType>(); 3600 assert(RT && "classifyRegCallStructType only valid with struct types"); 3601 3602 if (RT->getDecl()->hasFlexibleArrayMember()) 3603 return getIndirectReturnResult(Ty); 3604 3605 // Sum up bases 3606 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 3607 if (CXXRD->isDynamicClass()) { 3608 NeededInt = NeededSSE = 0; 3609 return getIndirectReturnResult(Ty); 3610 } 3611 3612 for (const auto &I : CXXRD->bases()) 3613 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE) 3614 .isIndirect()) { 3615 NeededInt = NeededSSE = 0; 3616 return getIndirectReturnResult(Ty); 3617 } 3618 } 3619 3620 // Sum up members 3621 for (const auto *FD : RT->getDecl()->fields()) { 3622 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) { 3623 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE) 3624 .isIndirect()) { 3625 NeededInt = NeededSSE = 0; 3626 return getIndirectReturnResult(Ty); 3627 } 3628 } else { 3629 unsigned LocalNeededInt, LocalNeededSSE; 3630 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt, 3631 LocalNeededSSE, true) 3632 .isIndirect()) { 3633 NeededInt = NeededSSE = 0; 3634 return getIndirectReturnResult(Ty); 3635 } 3636 NeededInt += LocalNeededInt; 3637 NeededSSE += LocalNeededSSE; 3638 } 3639 } 3640 3641 return ABIArgInfo::getDirect(); 3642 } 3643 3644 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty, 3645 unsigned &NeededInt, 3646 unsigned &NeededSSE) const { 3647 3648 NeededInt = 0; 3649 NeededSSE = 0; 3650 3651 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE); 3652 } 3653 3654 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 3655 3656 const unsigned CallingConv = FI.getCallingConvention(); 3657 // It is possible to force Win64 calling convention on any x86_64 target by 3658 // using __attribute__((ms_abi)). In such case to correctly emit Win64 3659 // compatible code delegate this call to WinX86_64ABIInfo::computeInfo. 3660 if (CallingConv == llvm::CallingConv::Win64) { 3661 WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel); 3662 Win64ABIInfo.computeInfo(FI); 3663 return; 3664 } 3665 3666 bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall; 3667 3668 // Keep track of the number of assigned registers. 3669 unsigned FreeIntRegs = IsRegCall ? 11 : 6; 3670 unsigned FreeSSERegs = IsRegCall ? 16 : 8; 3671 unsigned NeededInt, NeededSSE; 3672 3673 if (!::classifyReturnType(getCXXABI(), FI, *this)) { 3674 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() && 3675 !FI.getReturnType()->getTypePtr()->isUnionType()) { 3676 FI.getReturnInfo() = 3677 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE); 3678 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) { 3679 FreeIntRegs -= NeededInt; 3680 FreeSSERegs -= NeededSSE; 3681 } else { 3682 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType()); 3683 } 3684 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>()) { 3685 // Complex Long Double Type is passed in Memory when Regcall 3686 // calling convention is used. 3687 const ComplexType *CT = FI.getReturnType()->getAs<ComplexType>(); 3688 if (getContext().getCanonicalType(CT->getElementType()) == 3689 getContext().LongDoubleTy) 3690 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType()); 3691 } else 3692 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 3693 } 3694 3695 // If the return value is indirect, then the hidden argument is consuming one 3696 // integer register. 3697 if (FI.getReturnInfo().isIndirect()) 3698 --FreeIntRegs; 3699 3700 // The chain argument effectively gives us another free register. 3701 if (FI.isChainCall()) 3702 ++FreeIntRegs; 3703 3704 unsigned NumRequiredArgs = FI.getNumRequiredArgs(); 3705 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers 3706 // get assigned (in left-to-right order) for passing as follows... 3707 unsigned ArgNo = 0; 3708 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 3709 it != ie; ++it, ++ArgNo) { 3710 bool IsNamedArg = ArgNo < NumRequiredArgs; 3711 3712 if (IsRegCall && it->type->isStructureOrClassType()) 3713 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE); 3714 else 3715 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt, 3716 NeededSSE, IsNamedArg); 3717 3718 // AMD64-ABI 3.2.3p3: If there are no registers available for any 3719 // eightbyte of an argument, the whole argument is passed on the 3720 // stack. If registers have already been assigned for some 3721 // eightbytes of such an argument, the assignments get reverted. 3722 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) { 3723 FreeIntRegs -= NeededInt; 3724 FreeSSERegs -= NeededSSE; 3725 } else { 3726 it->info = getIndirectResult(it->type, FreeIntRegs); 3727 } 3728 } 3729 } 3730 3731 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF, 3732 Address VAListAddr, QualType Ty) { 3733 Address overflow_arg_area_p = 3734 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p"); 3735 llvm::Value *overflow_arg_area = 3736 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area"); 3737 3738 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16 3739 // byte boundary if alignment needed by type exceeds 8 byte boundary. 3740 // It isn't stated explicitly in the standard, but in practice we use 3741 // alignment greater than 16 where necessary. 3742 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty); 3743 if (Align > CharUnits::fromQuantity(8)) { 3744 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area, 3745 Align); 3746 } 3747 3748 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area. 3749 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 3750 llvm::Value *Res = 3751 CGF.Builder.CreateBitCast(overflow_arg_area, 3752 llvm::PointerType::getUnqual(LTy)); 3753 3754 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to: 3755 // l->overflow_arg_area + sizeof(type). 3756 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to 3757 // an 8 byte boundary. 3758 3759 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8; 3760 llvm::Value *Offset = 3761 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7); 3762 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset, 3763 "overflow_arg_area.next"); 3764 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p); 3765 3766 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type. 3767 return Address(Res, Align); 3768 } 3769 3770 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 3771 QualType Ty) const { 3772 // Assume that va_list type is correct; should be pointer to LLVM type: 3773 // struct { 3774 // i32 gp_offset; 3775 // i32 fp_offset; 3776 // i8* overflow_arg_area; 3777 // i8* reg_save_area; 3778 // }; 3779 unsigned neededInt, neededSSE; 3780 3781 Ty = getContext().getCanonicalType(Ty); 3782 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE, 3783 /*isNamedArg*/false); 3784 3785 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed 3786 // in the registers. If not go to step 7. 3787 if (!neededInt && !neededSSE) 3788 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty); 3789 3790 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of 3791 // general purpose registers needed to pass type and num_fp to hold 3792 // the number of floating point registers needed. 3793 3794 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into 3795 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or 3796 // l->fp_offset > 304 - num_fp * 16 go to step 7. 3797 // 3798 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of 3799 // register save space). 3800 3801 llvm::Value *InRegs = nullptr; 3802 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid(); 3803 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr; 3804 if (neededInt) { 3805 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p"); 3806 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset"); 3807 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8); 3808 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp"); 3809 } 3810 3811 if (neededSSE) { 3812 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p"); 3813 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset"); 3814 llvm::Value *FitsInFP = 3815 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16); 3816 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp"); 3817 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP; 3818 } 3819 3820 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 3821 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 3822 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 3823 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 3824 3825 // Emit code to load the value if it was passed in registers. 3826 3827 CGF.EmitBlock(InRegBlock); 3828 3829 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with 3830 // an offset of l->gp_offset and/or l->fp_offset. This may require 3831 // copying to a temporary location in case the parameter is passed 3832 // in different register classes or requires an alignment greater 3833 // than 8 for general purpose registers and 16 for XMM registers. 3834 // 3835 // FIXME: This really results in shameful code when we end up needing to 3836 // collect arguments from different places; often what should result in a 3837 // simple assembling of a structure from scattered addresses has many more 3838 // loads than necessary. Can we clean this up? 3839 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 3840 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad( 3841 CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area"); 3842 3843 Address RegAddr = Address::invalid(); 3844 if (neededInt && neededSSE) { 3845 // FIXME: Cleanup. 3846 assert(AI.isDirect() && "Unexpected ABI info for mixed regs"); 3847 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType()); 3848 Address Tmp = CGF.CreateMemTemp(Ty); 3849 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); 3850 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs"); 3851 llvm::Type *TyLo = ST->getElementType(0); 3852 llvm::Type *TyHi = ST->getElementType(1); 3853 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) && 3854 "Unexpected ABI info for mixed regs"); 3855 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo); 3856 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi); 3857 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset); 3858 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset); 3859 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr; 3860 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr; 3861 3862 // Copy the first element. 3863 // FIXME: Our choice of alignment here and below is probably pessimistic. 3864 llvm::Value *V = CGF.Builder.CreateAlignedLoad( 3865 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo), 3866 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo))); 3867 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 3868 3869 // Copy the second element. 3870 V = CGF.Builder.CreateAlignedLoad( 3871 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi), 3872 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi))); 3873 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 3874 3875 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy); 3876 } else if (neededInt) { 3877 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset), 3878 CharUnits::fromQuantity(8)); 3879 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy); 3880 3881 // Copy to a temporary if necessary to ensure the appropriate alignment. 3882 std::pair<CharUnits, CharUnits> SizeAlign = 3883 getContext().getTypeInfoInChars(Ty); 3884 uint64_t TySize = SizeAlign.first.getQuantity(); 3885 CharUnits TyAlign = SizeAlign.second; 3886 3887 // Copy into a temporary if the type is more aligned than the 3888 // register save area. 3889 if (TyAlign.getQuantity() > 8) { 3890 Address Tmp = CGF.CreateMemTemp(Ty); 3891 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false); 3892 RegAddr = Tmp; 3893 } 3894 3895 } else if (neededSSE == 1) { 3896 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset), 3897 CharUnits::fromQuantity(16)); 3898 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy); 3899 } else { 3900 assert(neededSSE == 2 && "Invalid number of needed registers!"); 3901 // SSE registers are spaced 16 bytes apart in the register save 3902 // area, we need to collect the two eightbytes together. 3903 // The ABI isn't explicit about this, but it seems reasonable 3904 // to assume that the slots are 16-byte aligned, since the stack is 3905 // naturally 16-byte aligned and the prologue is expected to store 3906 // all the SSE registers to the RSA. 3907 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset), 3908 CharUnits::fromQuantity(16)); 3909 Address RegAddrHi = 3910 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo, 3911 CharUnits::fromQuantity(16)); 3912 llvm::Type *ST = AI.canHaveCoerceToType() 3913 ? AI.getCoerceToType() 3914 : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy); 3915 llvm::Value *V; 3916 Address Tmp = CGF.CreateMemTemp(Ty); 3917 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); 3918 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast( 3919 RegAddrLo, ST->getStructElementType(0))); 3920 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 3921 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast( 3922 RegAddrHi, ST->getStructElementType(1))); 3923 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 3924 3925 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy); 3926 } 3927 3928 // AMD64-ABI 3.5.7p5: Step 5. Set: 3929 // l->gp_offset = l->gp_offset + num_gp * 8 3930 // l->fp_offset = l->fp_offset + num_fp * 16. 3931 if (neededInt) { 3932 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8); 3933 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset), 3934 gp_offset_p); 3935 } 3936 if (neededSSE) { 3937 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16); 3938 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset), 3939 fp_offset_p); 3940 } 3941 CGF.EmitBranch(ContBlock); 3942 3943 // Emit code to load the value if it was passed in memory. 3944 3945 CGF.EmitBlock(InMemBlock); 3946 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty); 3947 3948 // Return the appropriate result. 3949 3950 CGF.EmitBlock(ContBlock); 3951 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock, 3952 "vaarg.addr"); 3953 return ResAddr; 3954 } 3955 3956 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 3957 QualType Ty) const { 3958 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 3959 CGF.getContext().getTypeInfoInChars(Ty), 3960 CharUnits::fromQuantity(8), 3961 /*allowHigherAlign*/ false); 3962 } 3963 3964 ABIArgInfo 3965 WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs, 3966 const ABIArgInfo ¤t) const { 3967 // Assumes vectorCall calling convention. 3968 const Type *Base = nullptr; 3969 uint64_t NumElts = 0; 3970 3971 if (!Ty->isBuiltinType() && !Ty->isVectorType() && 3972 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) { 3973 FreeSSERegs -= NumElts; 3974 return getDirectX86Hva(); 3975 } 3976 return current; 3977 } 3978 3979 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs, 3980 bool IsReturnType, bool IsVectorCall, 3981 bool IsRegCall) const { 3982 3983 if (Ty->isVoidType()) 3984 return ABIArgInfo::getIgnore(); 3985 3986 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3987 Ty = EnumTy->getDecl()->getIntegerType(); 3988 3989 TypeInfo Info = getContext().getTypeInfo(Ty); 3990 uint64_t Width = Info.Width; 3991 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align); 3992 3993 const RecordType *RT = Ty->getAs<RecordType>(); 3994 if (RT) { 3995 if (!IsReturnType) { 3996 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI())) 3997 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 3998 } 3999 4000 if (RT->getDecl()->hasFlexibleArrayMember()) 4001 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 4002 4003 } 4004 4005 const Type *Base = nullptr; 4006 uint64_t NumElts = 0; 4007 // vectorcall adds the concept of a homogenous vector aggregate, similar to 4008 // other targets. 4009 if ((IsVectorCall || IsRegCall) && 4010 isHomogeneousAggregate(Ty, Base, NumElts)) { 4011 if (IsRegCall) { 4012 if (FreeSSERegs >= NumElts) { 4013 FreeSSERegs -= NumElts; 4014 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType()) 4015 return ABIArgInfo::getDirect(); 4016 return ABIArgInfo::getExpand(); 4017 } 4018 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4019 } else if (IsVectorCall) { 4020 if (FreeSSERegs >= NumElts && 4021 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) { 4022 FreeSSERegs -= NumElts; 4023 return ABIArgInfo::getDirect(); 4024 } else if (IsReturnType) { 4025 return ABIArgInfo::getExpand(); 4026 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) { 4027 // HVAs are delayed and reclassified in the 2nd step. 4028 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4029 } 4030 } 4031 } 4032 4033 if (Ty->isMemberPointerType()) { 4034 // If the member pointer is represented by an LLVM int or ptr, pass it 4035 // directly. 4036 llvm::Type *LLTy = CGT.ConvertType(Ty); 4037 if (LLTy->isPointerTy() || LLTy->isIntegerTy()) 4038 return ABIArgInfo::getDirect(); 4039 } 4040 4041 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) { 4042 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4043 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4044 if (Width > 64 || !llvm::isPowerOf2_64(Width)) 4045 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 4046 4047 // Otherwise, coerce it to a small integer. 4048 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width)); 4049 } 4050 4051 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 4052 switch (BT->getKind()) { 4053 case BuiltinType::Bool: 4054 // Bool type is always extended to the ABI, other builtin types are not 4055 // extended. 4056 return ABIArgInfo::getExtend(Ty); 4057 4058 case BuiltinType::LongDouble: 4059 // Mingw64 GCC uses the old 80 bit extended precision floating point 4060 // unit. It passes them indirectly through memory. 4061 if (IsMingw64) { 4062 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 4063 if (LDF == &llvm::APFloat::x87DoubleExtended()) 4064 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4065 } 4066 break; 4067 4068 case BuiltinType::Int128: 4069 case BuiltinType::UInt128: 4070 // If it's a parameter type, the normal ABI rule is that arguments larger 4071 // than 8 bytes are passed indirectly. GCC follows it. We follow it too, 4072 // even though it isn't particularly efficient. 4073 if (!IsReturnType) 4074 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4075 4076 // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that. 4077 // Clang matches them for compatibility. 4078 return ABIArgInfo::getDirect( 4079 llvm::VectorType::get(llvm::Type::getInt64Ty(getVMContext()), 2)); 4080 4081 default: 4082 break; 4083 } 4084 } 4085 4086 return ABIArgInfo::getDirect(); 4087 } 4088 4089 void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, 4090 unsigned FreeSSERegs, 4091 bool IsVectorCall, 4092 bool IsRegCall) const { 4093 unsigned Count = 0; 4094 for (auto &I : FI.arguments()) { 4095 // Vectorcall in x64 only permits the first 6 arguments to be passed 4096 // as XMM/YMM registers. 4097 if (Count < VectorcallMaxParamNumAsReg) 4098 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall); 4099 else { 4100 // Since these cannot be passed in registers, pretend no registers 4101 // are left. 4102 unsigned ZeroSSERegsAvail = 0; 4103 I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false, 4104 IsVectorCall, IsRegCall); 4105 } 4106 ++Count; 4107 } 4108 4109 for (auto &I : FI.arguments()) { 4110 I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info); 4111 } 4112 } 4113 4114 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 4115 const unsigned CC = FI.getCallingConvention(); 4116 bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall; 4117 bool IsRegCall = CC == llvm::CallingConv::X86_RegCall; 4118 4119 // If __attribute__((sysv_abi)) is in use, use the SysV argument 4120 // classification rules. 4121 if (CC == llvm::CallingConv::X86_64_SysV) { 4122 X86_64ABIInfo SysVABIInfo(CGT, AVXLevel); 4123 SysVABIInfo.computeInfo(FI); 4124 return; 4125 } 4126 4127 unsigned FreeSSERegs = 0; 4128 if (IsVectorCall) { 4129 // We can use up to 4 SSE return registers with vectorcall. 4130 FreeSSERegs = 4; 4131 } else if (IsRegCall) { 4132 // RegCall gives us 16 SSE registers. 4133 FreeSSERegs = 16; 4134 } 4135 4136 if (!getCXXABI().classifyReturnType(FI)) 4137 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true, 4138 IsVectorCall, IsRegCall); 4139 4140 if (IsVectorCall) { 4141 // We can use up to 6 SSE register parameters with vectorcall. 4142 FreeSSERegs = 6; 4143 } else if (IsRegCall) { 4144 // RegCall gives us 16 SSE registers, we can reuse the return registers. 4145 FreeSSERegs = 16; 4146 } 4147 4148 if (IsVectorCall) { 4149 computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall); 4150 } else { 4151 for (auto &I : FI.arguments()) 4152 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall); 4153 } 4154 4155 } 4156 4157 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4158 QualType Ty) const { 4159 4160 bool IsIndirect = false; 4161 4162 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4163 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4164 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) { 4165 uint64_t Width = getContext().getTypeSize(Ty); 4166 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width); 4167 } 4168 4169 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 4170 CGF.getContext().getTypeInfoInChars(Ty), 4171 CharUnits::fromQuantity(8), 4172 /*allowHigherAlign*/ false); 4173 } 4174 4175 // PowerPC-32 4176 namespace { 4177 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information. 4178 class PPC32_SVR4_ABIInfo : public DefaultABIInfo { 4179 bool IsSoftFloatABI; 4180 4181 CharUnits getParamTypeAlignment(QualType Ty) const; 4182 4183 public: 4184 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI) 4185 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {} 4186 4187 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4188 QualType Ty) const override; 4189 }; 4190 4191 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo { 4192 public: 4193 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI) 4194 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {} 4195 4196 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4197 // This is recovered from gcc output. 4198 return 1; // r1 is the dedicated stack pointer 4199 } 4200 4201 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4202 llvm::Value *Address) const override; 4203 }; 4204 } 4205 4206 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const { 4207 // Complex types are passed just like their elements 4208 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 4209 Ty = CTy->getElementType(); 4210 4211 if (Ty->isVectorType()) 4212 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 4213 : 4); 4214 4215 // For single-element float/vector structs, we consider the whole type 4216 // to have the same alignment requirements as its single element. 4217 const Type *AlignTy = nullptr; 4218 if (const Type *EltType = isSingleElementStruct(Ty, getContext())) { 4219 const BuiltinType *BT = EltType->getAs<BuiltinType>(); 4220 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) || 4221 (BT && BT->isFloatingPoint())) 4222 AlignTy = EltType; 4223 } 4224 4225 if (AlignTy) 4226 return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4); 4227 return CharUnits::fromQuantity(4); 4228 } 4229 4230 // TODO: this implementation is now likely redundant with 4231 // DefaultABIInfo::EmitVAArg. 4232 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList, 4233 QualType Ty) const { 4234 if (getTarget().getTriple().isOSDarwin()) { 4235 auto TI = getContext().getTypeInfoInChars(Ty); 4236 TI.second = getParamTypeAlignment(Ty); 4237 4238 CharUnits SlotSize = CharUnits::fromQuantity(4); 4239 return emitVoidPtrVAArg(CGF, VAList, Ty, 4240 classifyArgumentType(Ty).isIndirect(), TI, SlotSize, 4241 /*AllowHigherAlign=*/true); 4242 } 4243 4244 const unsigned OverflowLimit = 8; 4245 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 4246 // TODO: Implement this. For now ignore. 4247 (void)CTy; 4248 return Address::invalid(); // FIXME? 4249 } 4250 4251 // struct __va_list_tag { 4252 // unsigned char gpr; 4253 // unsigned char fpr; 4254 // unsigned short reserved; 4255 // void *overflow_arg_area; 4256 // void *reg_save_area; 4257 // }; 4258 4259 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64; 4260 bool isInt = 4261 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType(); 4262 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64; 4263 4264 // All aggregates are passed indirectly? That doesn't seem consistent 4265 // with the argument-lowering code. 4266 bool isIndirect = Ty->isAggregateType(); 4267 4268 CGBuilderTy &Builder = CGF.Builder; 4269 4270 // The calling convention either uses 1-2 GPRs or 1 FPR. 4271 Address NumRegsAddr = Address::invalid(); 4272 if (isInt || IsSoftFloatABI) { 4273 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr"); 4274 } else { 4275 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr"); 4276 } 4277 4278 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs"); 4279 4280 // "Align" the register count when TY is i64. 4281 if (isI64 || (isF64 && IsSoftFloatABI)) { 4282 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1)); 4283 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U)); 4284 } 4285 4286 llvm::Value *CC = 4287 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond"); 4288 4289 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs"); 4290 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow"); 4291 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 4292 4293 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow); 4294 4295 llvm::Type *DirectTy = CGF.ConvertType(Ty); 4296 if (isIndirect) DirectTy = DirectTy->getPointerTo(0); 4297 4298 // Case 1: consume registers. 4299 Address RegAddr = Address::invalid(); 4300 { 4301 CGF.EmitBlock(UsingRegs); 4302 4303 Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4); 4304 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr), 4305 CharUnits::fromQuantity(8)); 4306 assert(RegAddr.getElementType() == CGF.Int8Ty); 4307 4308 // Floating-point registers start after the general-purpose registers. 4309 if (!(isInt || IsSoftFloatABI)) { 4310 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr, 4311 CharUnits::fromQuantity(32)); 4312 } 4313 4314 // Get the address of the saved value by scaling the number of 4315 // registers we've used by the number of 4316 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8); 4317 llvm::Value *RegOffset = 4318 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity())); 4319 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty, 4320 RegAddr.getPointer(), RegOffset), 4321 RegAddr.getAlignment().alignmentOfArrayElement(RegSize)); 4322 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy); 4323 4324 // Increase the used-register count. 4325 NumRegs = 4326 Builder.CreateAdd(NumRegs, 4327 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1)); 4328 Builder.CreateStore(NumRegs, NumRegsAddr); 4329 4330 CGF.EmitBranch(Cont); 4331 } 4332 4333 // Case 2: consume space in the overflow area. 4334 Address MemAddr = Address::invalid(); 4335 { 4336 CGF.EmitBlock(UsingOverflow); 4337 4338 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr); 4339 4340 // Everything in the overflow area is rounded up to a size of at least 4. 4341 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4); 4342 4343 CharUnits Size; 4344 if (!isIndirect) { 4345 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty); 4346 Size = TypeInfo.first.alignTo(OverflowAreaAlign); 4347 } else { 4348 Size = CGF.getPointerSize(); 4349 } 4350 4351 Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3); 4352 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"), 4353 OverflowAreaAlign); 4354 // Round up address of argument to alignment 4355 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty); 4356 if (Align > OverflowAreaAlign) { 4357 llvm::Value *Ptr = OverflowArea.getPointer(); 4358 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align), 4359 Align); 4360 } 4361 4362 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy); 4363 4364 // Increase the overflow area. 4365 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size); 4366 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr); 4367 CGF.EmitBranch(Cont); 4368 } 4369 4370 CGF.EmitBlock(Cont); 4371 4372 // Merge the cases with a phi. 4373 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow, 4374 "vaarg.addr"); 4375 4376 // Load the pointer if the argument was passed indirectly. 4377 if (isIndirect) { 4378 Result = Address(Builder.CreateLoad(Result, "aggr"), 4379 getContext().getTypeAlignInChars(Ty)); 4380 } 4381 4382 return Result; 4383 } 4384 4385 bool 4386 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4387 llvm::Value *Address) const { 4388 // This is calculated from the LLVM and GCC tables and verified 4389 // against gcc output. AFAIK all ABIs use the same encoding. 4390 4391 CodeGen::CGBuilderTy &Builder = CGF.Builder; 4392 4393 llvm::IntegerType *i8 = CGF.Int8Ty; 4394 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 4395 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 4396 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16); 4397 4398 // 0-31: r0-31, the 4-byte general-purpose registers 4399 AssignToArrayRange(Builder, Address, Four8, 0, 31); 4400 4401 // 32-63: fp0-31, the 8-byte floating-point registers 4402 AssignToArrayRange(Builder, Address, Eight8, 32, 63); 4403 4404 // 64-76 are various 4-byte special-purpose registers: 4405 // 64: mq 4406 // 65: lr 4407 // 66: ctr 4408 // 67: ap 4409 // 68-75 cr0-7 4410 // 76: xer 4411 AssignToArrayRange(Builder, Address, Four8, 64, 76); 4412 4413 // 77-108: v0-31, the 16-byte vector registers 4414 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108); 4415 4416 // 109: vrsave 4417 // 110: vscr 4418 // 111: spe_acc 4419 // 112: spefscr 4420 // 113: sfp 4421 AssignToArrayRange(Builder, Address, Four8, 109, 113); 4422 4423 return false; 4424 } 4425 4426 // PowerPC-64 4427 4428 namespace { 4429 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information. 4430 class PPC64_SVR4_ABIInfo : public SwiftABIInfo { 4431 public: 4432 enum ABIKind { 4433 ELFv1 = 0, 4434 ELFv2 4435 }; 4436 4437 private: 4438 static const unsigned GPRBits = 64; 4439 ABIKind Kind; 4440 bool HasQPX; 4441 bool IsSoftFloatABI; 4442 4443 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and 4444 // will be passed in a QPX register. 4445 bool IsQPXVectorTy(const Type *Ty) const { 4446 if (!HasQPX) 4447 return false; 4448 4449 if (const VectorType *VT = Ty->getAs<VectorType>()) { 4450 unsigned NumElements = VT->getNumElements(); 4451 if (NumElements == 1) 4452 return false; 4453 4454 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) { 4455 if (getContext().getTypeSize(Ty) <= 256) 4456 return true; 4457 } else if (VT->getElementType()-> 4458 isSpecificBuiltinType(BuiltinType::Float)) { 4459 if (getContext().getTypeSize(Ty) <= 128) 4460 return true; 4461 } 4462 } 4463 4464 return false; 4465 } 4466 4467 bool IsQPXVectorTy(QualType Ty) const { 4468 return IsQPXVectorTy(Ty.getTypePtr()); 4469 } 4470 4471 public: 4472 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX, 4473 bool SoftFloatABI) 4474 : SwiftABIInfo(CGT), Kind(Kind), HasQPX(HasQPX), 4475 IsSoftFloatABI(SoftFloatABI) {} 4476 4477 bool isPromotableTypeForABI(QualType Ty) const; 4478 CharUnits getParamTypeAlignment(QualType Ty) const; 4479 4480 ABIArgInfo classifyReturnType(QualType RetTy) const; 4481 ABIArgInfo classifyArgumentType(QualType Ty) const; 4482 4483 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 4484 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 4485 uint64_t Members) const override; 4486 4487 // TODO: We can add more logic to computeInfo to improve performance. 4488 // Example: For aggregate arguments that fit in a register, we could 4489 // use getDirectInReg (as is done below for structs containing a single 4490 // floating-point value) to avoid pushing them to memory on function 4491 // entry. This would require changing the logic in PPCISelLowering 4492 // when lowering the parameters in the caller and args in the callee. 4493 void computeInfo(CGFunctionInfo &FI) const override { 4494 if (!getCXXABI().classifyReturnType(FI)) 4495 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4496 for (auto &I : FI.arguments()) { 4497 // We rely on the default argument classification for the most part. 4498 // One exception: An aggregate containing a single floating-point 4499 // or vector item must be passed in a register if one is available. 4500 const Type *T = isSingleElementStruct(I.type, getContext()); 4501 if (T) { 4502 const BuiltinType *BT = T->getAs<BuiltinType>(); 4503 if (IsQPXVectorTy(T) || 4504 (T->isVectorType() && getContext().getTypeSize(T) == 128) || 4505 (BT && BT->isFloatingPoint())) { 4506 QualType QT(T, 0); 4507 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT)); 4508 continue; 4509 } 4510 } 4511 I.info = classifyArgumentType(I.type); 4512 } 4513 } 4514 4515 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4516 QualType Ty) const override; 4517 4518 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 4519 bool asReturnValue) const override { 4520 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 4521 } 4522 4523 bool isSwiftErrorInRegister() const override { 4524 return false; 4525 } 4526 }; 4527 4528 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo { 4529 4530 public: 4531 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT, 4532 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX, 4533 bool SoftFloatABI) 4534 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX, 4535 SoftFloatABI)) {} 4536 4537 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4538 // This is recovered from gcc output. 4539 return 1; // r1 is the dedicated stack pointer 4540 } 4541 4542 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4543 llvm::Value *Address) const override; 4544 }; 4545 4546 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo { 4547 public: 4548 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {} 4549 4550 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4551 // This is recovered from gcc output. 4552 return 1; // r1 is the dedicated stack pointer 4553 } 4554 4555 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4556 llvm::Value *Address) const override; 4557 }; 4558 4559 } 4560 4561 // Return true if the ABI requires Ty to be passed sign- or zero- 4562 // extended to 64 bits. 4563 bool 4564 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const { 4565 // Treat an enum type as its underlying type. 4566 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4567 Ty = EnumTy->getDecl()->getIntegerType(); 4568 4569 // Promotable integer types are required to be promoted by the ABI. 4570 if (Ty->isPromotableIntegerType()) 4571 return true; 4572 4573 // In addition to the usual promotable integer types, we also need to 4574 // extend all 32-bit types, since the ABI requires promotion to 64 bits. 4575 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 4576 switch (BT->getKind()) { 4577 case BuiltinType::Int: 4578 case BuiltinType::UInt: 4579 return true; 4580 default: 4581 break; 4582 } 4583 4584 return false; 4585 } 4586 4587 /// isAlignedParamType - Determine whether a type requires 16-byte or 4588 /// higher alignment in the parameter area. Always returns at least 8. 4589 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const { 4590 // Complex types are passed just like their elements. 4591 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 4592 Ty = CTy->getElementType(); 4593 4594 // Only vector types of size 16 bytes need alignment (larger types are 4595 // passed via reference, smaller types are not aligned). 4596 if (IsQPXVectorTy(Ty)) { 4597 if (getContext().getTypeSize(Ty) > 128) 4598 return CharUnits::fromQuantity(32); 4599 4600 return CharUnits::fromQuantity(16); 4601 } else if (Ty->isVectorType()) { 4602 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8); 4603 } 4604 4605 // For single-element float/vector structs, we consider the whole type 4606 // to have the same alignment requirements as its single element. 4607 const Type *AlignAsType = nullptr; 4608 const Type *EltType = isSingleElementStruct(Ty, getContext()); 4609 if (EltType) { 4610 const BuiltinType *BT = EltType->getAs<BuiltinType>(); 4611 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() && 4612 getContext().getTypeSize(EltType) == 128) || 4613 (BT && BT->isFloatingPoint())) 4614 AlignAsType = EltType; 4615 } 4616 4617 // Likewise for ELFv2 homogeneous aggregates. 4618 const Type *Base = nullptr; 4619 uint64_t Members = 0; 4620 if (!AlignAsType && Kind == ELFv2 && 4621 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members)) 4622 AlignAsType = Base; 4623 4624 // With special case aggregates, only vector base types need alignment. 4625 if (AlignAsType && IsQPXVectorTy(AlignAsType)) { 4626 if (getContext().getTypeSize(AlignAsType) > 128) 4627 return CharUnits::fromQuantity(32); 4628 4629 return CharUnits::fromQuantity(16); 4630 } else if (AlignAsType) { 4631 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8); 4632 } 4633 4634 // Otherwise, we only need alignment for any aggregate type that 4635 // has an alignment requirement of >= 16 bytes. 4636 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) { 4637 if (HasQPX && getContext().getTypeAlign(Ty) >= 256) 4638 return CharUnits::fromQuantity(32); 4639 return CharUnits::fromQuantity(16); 4640 } 4641 4642 return CharUnits::fromQuantity(8); 4643 } 4644 4645 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous 4646 /// aggregate. Base is set to the base element type, and Members is set 4647 /// to the number of base elements. 4648 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base, 4649 uint64_t &Members) const { 4650 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 4651 uint64_t NElements = AT->getSize().getZExtValue(); 4652 if (NElements == 0) 4653 return false; 4654 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members)) 4655 return false; 4656 Members *= NElements; 4657 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 4658 const RecordDecl *RD = RT->getDecl(); 4659 if (RD->hasFlexibleArrayMember()) 4660 return false; 4661 4662 Members = 0; 4663 4664 // If this is a C++ record, check the bases first. 4665 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 4666 for (const auto &I : CXXRD->bases()) { 4667 // Ignore empty records. 4668 if (isEmptyRecord(getContext(), I.getType(), true)) 4669 continue; 4670 4671 uint64_t FldMembers; 4672 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers)) 4673 return false; 4674 4675 Members += FldMembers; 4676 } 4677 } 4678 4679 for (const auto *FD : RD->fields()) { 4680 // Ignore (non-zero arrays of) empty records. 4681 QualType FT = FD->getType(); 4682 while (const ConstantArrayType *AT = 4683 getContext().getAsConstantArrayType(FT)) { 4684 if (AT->getSize().getZExtValue() == 0) 4685 return false; 4686 FT = AT->getElementType(); 4687 } 4688 if (isEmptyRecord(getContext(), FT, true)) 4689 continue; 4690 4691 // For compatibility with GCC, ignore empty bitfields in C++ mode. 4692 if (getContext().getLangOpts().CPlusPlus && 4693 FD->isZeroLengthBitField(getContext())) 4694 continue; 4695 4696 uint64_t FldMembers; 4697 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers)) 4698 return false; 4699 4700 Members = (RD->isUnion() ? 4701 std::max(Members, FldMembers) : Members + FldMembers); 4702 } 4703 4704 if (!Base) 4705 return false; 4706 4707 // Ensure there is no padding. 4708 if (getContext().getTypeSize(Base) * Members != 4709 getContext().getTypeSize(Ty)) 4710 return false; 4711 } else { 4712 Members = 1; 4713 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 4714 Members = 2; 4715 Ty = CT->getElementType(); 4716 } 4717 4718 // Most ABIs only support float, double, and some vector type widths. 4719 if (!isHomogeneousAggregateBaseType(Ty)) 4720 return false; 4721 4722 // The base type must be the same for all members. Types that 4723 // agree in both total size and mode (float vs. vector) are 4724 // treated as being equivalent here. 4725 const Type *TyPtr = Ty.getTypePtr(); 4726 if (!Base) { 4727 Base = TyPtr; 4728 // If it's a non-power-of-2 vector, its size is already a power-of-2, 4729 // so make sure to widen it explicitly. 4730 if (const VectorType *VT = Base->getAs<VectorType>()) { 4731 QualType EltTy = VT->getElementType(); 4732 unsigned NumElements = 4733 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy); 4734 Base = getContext() 4735 .getVectorType(EltTy, NumElements, VT->getVectorKind()) 4736 .getTypePtr(); 4737 } 4738 } 4739 4740 if (Base->isVectorType() != TyPtr->isVectorType() || 4741 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr)) 4742 return false; 4743 } 4744 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members); 4745 } 4746 4747 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 4748 // Homogeneous aggregates for ELFv2 must have base types of float, 4749 // double, long double, or 128-bit vectors. 4750 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 4751 if (BT->getKind() == BuiltinType::Float || 4752 BT->getKind() == BuiltinType::Double || 4753 BT->getKind() == BuiltinType::LongDouble || 4754 (getContext().getTargetInfo().hasFloat128Type() && 4755 (BT->getKind() == BuiltinType::Float128))) { 4756 if (IsSoftFloatABI) 4757 return false; 4758 return true; 4759 } 4760 } 4761 if (const VectorType *VT = Ty->getAs<VectorType>()) { 4762 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty)) 4763 return true; 4764 } 4765 return false; 4766 } 4767 4768 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough( 4769 const Type *Base, uint64_t Members) const { 4770 // Vector and fp128 types require one register, other floating point types 4771 // require one or two registers depending on their size. 4772 uint32_t NumRegs = 4773 ((getContext().getTargetInfo().hasFloat128Type() && 4774 Base->isFloat128Type()) || 4775 Base->isVectorType()) ? 1 4776 : (getContext().getTypeSize(Base) + 63) / 64; 4777 4778 // Homogeneous Aggregates may occupy at most 8 registers. 4779 return Members * NumRegs <= 8; 4780 } 4781 4782 ABIArgInfo 4783 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const { 4784 Ty = useFirstFieldIfTransparentUnion(Ty); 4785 4786 if (Ty->isAnyComplexType()) 4787 return ABIArgInfo::getDirect(); 4788 4789 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes) 4790 // or via reference (larger than 16 bytes). 4791 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) { 4792 uint64_t Size = getContext().getTypeSize(Ty); 4793 if (Size > 128) 4794 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 4795 else if (Size < 128) { 4796 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size); 4797 return ABIArgInfo::getDirect(CoerceTy); 4798 } 4799 } 4800 4801 if (isAggregateTypeForABI(Ty)) { 4802 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 4803 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 4804 4805 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity(); 4806 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity(); 4807 4808 // ELFv2 homogeneous aggregates are passed as array types. 4809 const Type *Base = nullptr; 4810 uint64_t Members = 0; 4811 if (Kind == ELFv2 && 4812 isHomogeneousAggregate(Ty, Base, Members)) { 4813 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0)); 4814 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members); 4815 return ABIArgInfo::getDirect(CoerceTy); 4816 } 4817 4818 // If an aggregate may end up fully in registers, we do not 4819 // use the ByVal method, but pass the aggregate as array. 4820 // This is usually beneficial since we avoid forcing the 4821 // back-end to store the argument to memory. 4822 uint64_t Bits = getContext().getTypeSize(Ty); 4823 if (Bits > 0 && Bits <= 8 * GPRBits) { 4824 llvm::Type *CoerceTy; 4825 4826 // Types up to 8 bytes are passed as integer type (which will be 4827 // properly aligned in the argument save area doubleword). 4828 if (Bits <= GPRBits) 4829 CoerceTy = 4830 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8)); 4831 // Larger types are passed as arrays, with the base type selected 4832 // according to the required alignment in the save area. 4833 else { 4834 uint64_t RegBits = ABIAlign * 8; 4835 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits; 4836 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits); 4837 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs); 4838 } 4839 4840 return ABIArgInfo::getDirect(CoerceTy); 4841 } 4842 4843 // All other aggregates are passed ByVal. 4844 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign), 4845 /*ByVal=*/true, 4846 /*Realign=*/TyAlign > ABIAlign); 4847 } 4848 4849 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 4850 : ABIArgInfo::getDirect()); 4851 } 4852 4853 ABIArgInfo 4854 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const { 4855 if (RetTy->isVoidType()) 4856 return ABIArgInfo::getIgnore(); 4857 4858 if (RetTy->isAnyComplexType()) 4859 return ABIArgInfo::getDirect(); 4860 4861 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes) 4862 // or via reference (larger than 16 bytes). 4863 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) { 4864 uint64_t Size = getContext().getTypeSize(RetTy); 4865 if (Size > 128) 4866 return getNaturalAlignIndirect(RetTy); 4867 else if (Size < 128) { 4868 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size); 4869 return ABIArgInfo::getDirect(CoerceTy); 4870 } 4871 } 4872 4873 if (isAggregateTypeForABI(RetTy)) { 4874 // ELFv2 homogeneous aggregates are returned as array types. 4875 const Type *Base = nullptr; 4876 uint64_t Members = 0; 4877 if (Kind == ELFv2 && 4878 isHomogeneousAggregate(RetTy, Base, Members)) { 4879 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0)); 4880 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members); 4881 return ABIArgInfo::getDirect(CoerceTy); 4882 } 4883 4884 // ELFv2 small aggregates are returned in up to two registers. 4885 uint64_t Bits = getContext().getTypeSize(RetTy); 4886 if (Kind == ELFv2 && Bits <= 2 * GPRBits) { 4887 if (Bits == 0) 4888 return ABIArgInfo::getIgnore(); 4889 4890 llvm::Type *CoerceTy; 4891 if (Bits > GPRBits) { 4892 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits); 4893 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy); 4894 } else 4895 CoerceTy = 4896 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8)); 4897 return ABIArgInfo::getDirect(CoerceTy); 4898 } 4899 4900 // All other aggregates are returned indirectly. 4901 return getNaturalAlignIndirect(RetTy); 4902 } 4903 4904 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 4905 : ABIArgInfo::getDirect()); 4906 } 4907 4908 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine. 4909 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4910 QualType Ty) const { 4911 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 4912 TypeInfo.second = getParamTypeAlignment(Ty); 4913 4914 CharUnits SlotSize = CharUnits::fromQuantity(8); 4915 4916 // If we have a complex type and the base type is smaller than 8 bytes, 4917 // the ABI calls for the real and imaginary parts to be right-adjusted 4918 // in separate doublewords. However, Clang expects us to produce a 4919 // pointer to a structure with the two parts packed tightly. So generate 4920 // loads of the real and imaginary parts relative to the va_list pointer, 4921 // and store them to a temporary structure. 4922 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 4923 CharUnits EltSize = TypeInfo.first / 2; 4924 if (EltSize < SlotSize) { 4925 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty, 4926 SlotSize * 2, SlotSize, 4927 SlotSize, /*AllowHigher*/ true); 4928 4929 Address RealAddr = Addr; 4930 Address ImagAddr = RealAddr; 4931 if (CGF.CGM.getDataLayout().isBigEndian()) { 4932 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, 4933 SlotSize - EltSize); 4934 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr, 4935 2 * SlotSize - EltSize); 4936 } else { 4937 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize); 4938 } 4939 4940 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType()); 4941 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy); 4942 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy); 4943 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal"); 4944 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag"); 4945 4946 Address Temp = CGF.CreateMemTemp(Ty, "vacplx"); 4947 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty), 4948 /*init*/ true); 4949 return Temp; 4950 } 4951 } 4952 4953 // Otherwise, just use the general rule. 4954 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, 4955 TypeInfo, SlotSize, /*AllowHigher*/ true); 4956 } 4957 4958 static bool 4959 PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4960 llvm::Value *Address) { 4961 // This is calculated from the LLVM and GCC tables and verified 4962 // against gcc output. AFAIK all ABIs use the same encoding. 4963 4964 CodeGen::CGBuilderTy &Builder = CGF.Builder; 4965 4966 llvm::IntegerType *i8 = CGF.Int8Ty; 4967 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 4968 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 4969 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16); 4970 4971 // 0-31: r0-31, the 8-byte general-purpose registers 4972 AssignToArrayRange(Builder, Address, Eight8, 0, 31); 4973 4974 // 32-63: fp0-31, the 8-byte floating-point registers 4975 AssignToArrayRange(Builder, Address, Eight8, 32, 63); 4976 4977 // 64-67 are various 8-byte special-purpose registers: 4978 // 64: mq 4979 // 65: lr 4980 // 66: ctr 4981 // 67: ap 4982 AssignToArrayRange(Builder, Address, Eight8, 64, 67); 4983 4984 // 68-76 are various 4-byte special-purpose registers: 4985 // 68-75 cr0-7 4986 // 76: xer 4987 AssignToArrayRange(Builder, Address, Four8, 68, 76); 4988 4989 // 77-108: v0-31, the 16-byte vector registers 4990 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108); 4991 4992 // 109: vrsave 4993 // 110: vscr 4994 // 111: spe_acc 4995 // 112: spefscr 4996 // 113: sfp 4997 // 114: tfhar 4998 // 115: tfiar 4999 // 116: texasr 5000 AssignToArrayRange(Builder, Address, Eight8, 109, 116); 5001 5002 return false; 5003 } 5004 5005 bool 5006 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable( 5007 CodeGen::CodeGenFunction &CGF, 5008 llvm::Value *Address) const { 5009 5010 return PPC64_initDwarfEHRegSizeTable(CGF, Address); 5011 } 5012 5013 bool 5014 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5015 llvm::Value *Address) const { 5016 5017 return PPC64_initDwarfEHRegSizeTable(CGF, Address); 5018 } 5019 5020 //===----------------------------------------------------------------------===// 5021 // AArch64 ABI Implementation 5022 //===----------------------------------------------------------------------===// 5023 5024 namespace { 5025 5026 class AArch64ABIInfo : public SwiftABIInfo { 5027 public: 5028 enum ABIKind { 5029 AAPCS = 0, 5030 DarwinPCS, 5031 Win64 5032 }; 5033 5034 private: 5035 ABIKind Kind; 5036 5037 public: 5038 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) 5039 : SwiftABIInfo(CGT), Kind(Kind) {} 5040 5041 private: 5042 ABIKind getABIKind() const { return Kind; } 5043 bool isDarwinPCS() const { return Kind == DarwinPCS; } 5044 5045 ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const; 5046 ABIArgInfo classifyArgumentType(QualType RetTy) const; 5047 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 5048 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 5049 uint64_t Members) const override; 5050 5051 bool isIllegalVectorType(QualType Ty) const; 5052 5053 void computeInfo(CGFunctionInfo &FI) const override { 5054 if (!::classifyReturnType(getCXXABI(), FI, *this)) 5055 FI.getReturnInfo() = 5056 classifyReturnType(FI.getReturnType(), FI.isVariadic()); 5057 5058 for (auto &it : FI.arguments()) 5059 it.info = classifyArgumentType(it.type); 5060 } 5061 5062 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty, 5063 CodeGenFunction &CGF) const; 5064 5065 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty, 5066 CodeGenFunction &CGF) const; 5067 5068 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 5069 QualType Ty) const override { 5070 return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty) 5071 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF) 5072 : EmitAAPCSVAArg(VAListAddr, Ty, CGF); 5073 } 5074 5075 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 5076 QualType Ty) const override; 5077 5078 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 5079 bool asReturnValue) const override { 5080 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 5081 } 5082 bool isSwiftErrorInRegister() const override { 5083 return true; 5084 } 5085 5086 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy, 5087 unsigned elts) const override; 5088 }; 5089 5090 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo { 5091 public: 5092 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind) 5093 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {} 5094 5095 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 5096 return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue"; 5097 } 5098 5099 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 5100 return 31; 5101 } 5102 5103 bool doesReturnSlotInterfereWithArgs() const override { return false; } 5104 5105 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5106 CodeGen::CodeGenModule &CGM) const override { 5107 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 5108 if (!FD) 5109 return; 5110 5111 LangOptions::SignReturnAddressScopeKind Scope = 5112 CGM.getLangOpts().getSignReturnAddressScope(); 5113 LangOptions::SignReturnAddressKeyKind Key = 5114 CGM.getLangOpts().getSignReturnAddressKey(); 5115 bool BranchTargetEnforcement = CGM.getLangOpts().BranchTargetEnforcement; 5116 if (const auto *TA = FD->getAttr<TargetAttr>()) { 5117 ParsedTargetAttr Attr = TA->parse(); 5118 if (!Attr.BranchProtection.empty()) { 5119 TargetInfo::BranchProtectionInfo BPI; 5120 StringRef Error; 5121 (void)CGM.getTarget().validateBranchProtection(Attr.BranchProtection, 5122 BPI, Error); 5123 assert(Error.empty()); 5124 Scope = BPI.SignReturnAddr; 5125 Key = BPI.SignKey; 5126 BranchTargetEnforcement = BPI.BranchTargetEnforcement; 5127 } 5128 } 5129 5130 auto *Fn = cast<llvm::Function>(GV); 5131 if (Scope != LangOptions::SignReturnAddressScopeKind::None) { 5132 Fn->addFnAttr("sign-return-address", 5133 Scope == LangOptions::SignReturnAddressScopeKind::All 5134 ? "all" 5135 : "non-leaf"); 5136 5137 Fn->addFnAttr("sign-return-address-key", 5138 Key == LangOptions::SignReturnAddressKeyKind::AKey 5139 ? "a_key" 5140 : "b_key"); 5141 } 5142 5143 if (BranchTargetEnforcement) 5144 Fn->addFnAttr("branch-target-enforcement"); 5145 } 5146 }; 5147 5148 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo { 5149 public: 5150 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K) 5151 : AArch64TargetCodeGenInfo(CGT, K) {} 5152 5153 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5154 CodeGen::CodeGenModule &CGM) const override; 5155 5156 void getDependentLibraryOption(llvm::StringRef Lib, 5157 llvm::SmallString<24> &Opt) const override { 5158 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib); 5159 } 5160 5161 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, 5162 llvm::SmallString<32> &Opt) const override { 5163 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 5164 } 5165 }; 5166 5167 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes( 5168 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 5169 AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 5170 if (GV->isDeclaration()) 5171 return; 5172 addStackProbeTargetAttributes(D, GV, CGM); 5173 } 5174 } 5175 5176 ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const { 5177 Ty = useFirstFieldIfTransparentUnion(Ty); 5178 5179 // Handle illegal vector types here. 5180 if (isIllegalVectorType(Ty)) { 5181 uint64_t Size = getContext().getTypeSize(Ty); 5182 // Android promotes <2 x i8> to i16, not i32 5183 if (isAndroid() && (Size <= 16)) { 5184 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext()); 5185 return ABIArgInfo::getDirect(ResType); 5186 } 5187 if (Size <= 32) { 5188 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext()); 5189 return ABIArgInfo::getDirect(ResType); 5190 } 5191 if (Size == 64) { 5192 llvm::Type *ResType = 5193 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2); 5194 return ABIArgInfo::getDirect(ResType); 5195 } 5196 if (Size == 128) { 5197 llvm::Type *ResType = 5198 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4); 5199 return ABIArgInfo::getDirect(ResType); 5200 } 5201 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5202 } 5203 5204 if (!isAggregateTypeForABI(Ty)) { 5205 // Treat an enum type as its underlying type. 5206 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 5207 Ty = EnumTy->getDecl()->getIntegerType(); 5208 5209 return (Ty->isPromotableIntegerType() && isDarwinPCS() 5210 ? ABIArgInfo::getExtend(Ty) 5211 : ABIArgInfo::getDirect()); 5212 } 5213 5214 // Structures with either a non-trivial destructor or a non-trivial 5215 // copy constructor are always indirect. 5216 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 5217 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA == 5218 CGCXXABI::RAA_DirectInMemory); 5219 } 5220 5221 // Empty records are always ignored on Darwin, but actually passed in C++ mode 5222 // elsewhere for GNU compatibility. 5223 uint64_t Size = getContext().getTypeSize(Ty); 5224 bool IsEmpty = isEmptyRecord(getContext(), Ty, true); 5225 if (IsEmpty || Size == 0) { 5226 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS()) 5227 return ABIArgInfo::getIgnore(); 5228 5229 // GNU C mode. The only argument that gets ignored is an empty one with size 5230 // 0. 5231 if (IsEmpty && Size == 0) 5232 return ABIArgInfo::getIgnore(); 5233 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 5234 } 5235 5236 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded. 5237 const Type *Base = nullptr; 5238 uint64_t Members = 0; 5239 if (isHomogeneousAggregate(Ty, Base, Members)) { 5240 return ABIArgInfo::getDirect( 5241 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members)); 5242 } 5243 5244 // Aggregates <= 16 bytes are passed directly in registers or on the stack. 5245 if (Size <= 128) { 5246 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of 5247 // same size and alignment. 5248 if (getTarget().isRenderScriptTarget()) { 5249 return coerceToIntArray(Ty, getContext(), getVMContext()); 5250 } 5251 unsigned Alignment; 5252 if (Kind == AArch64ABIInfo::AAPCS) { 5253 Alignment = getContext().getTypeUnadjustedAlign(Ty); 5254 Alignment = Alignment < 128 ? 64 : 128; 5255 } else { 5256 Alignment = std::max(getContext().getTypeAlign(Ty), 5257 (unsigned)getTarget().getPointerWidth(0)); 5258 } 5259 Size = llvm::alignTo(Size, Alignment); 5260 5261 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment. 5262 // For aggregates with 16-byte alignment, we use i128. 5263 llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment); 5264 return ABIArgInfo::getDirect( 5265 Size == Alignment ? BaseTy 5266 : llvm::ArrayType::get(BaseTy, Size / Alignment)); 5267 } 5268 5269 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5270 } 5271 5272 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy, 5273 bool IsVariadic) const { 5274 if (RetTy->isVoidType()) 5275 return ABIArgInfo::getIgnore(); 5276 5277 // Large vector types should be returned via memory. 5278 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) 5279 return getNaturalAlignIndirect(RetTy); 5280 5281 if (!isAggregateTypeForABI(RetTy)) { 5282 // Treat an enum type as its underlying type. 5283 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 5284 RetTy = EnumTy->getDecl()->getIntegerType(); 5285 5286 return (RetTy->isPromotableIntegerType() && isDarwinPCS() 5287 ? ABIArgInfo::getExtend(RetTy) 5288 : ABIArgInfo::getDirect()); 5289 } 5290 5291 uint64_t Size = getContext().getTypeSize(RetTy); 5292 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0) 5293 return ABIArgInfo::getIgnore(); 5294 5295 const Type *Base = nullptr; 5296 uint64_t Members = 0; 5297 if (isHomogeneousAggregate(RetTy, Base, Members) && 5298 !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 && 5299 IsVariadic)) 5300 // Homogeneous Floating-point Aggregates (HFAs) are returned directly. 5301 return ABIArgInfo::getDirect(); 5302 5303 // Aggregates <= 16 bytes are returned directly in registers or on the stack. 5304 if (Size <= 128) { 5305 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of 5306 // same size and alignment. 5307 if (getTarget().isRenderScriptTarget()) { 5308 return coerceToIntArray(RetTy, getContext(), getVMContext()); 5309 } 5310 unsigned Alignment = getContext().getTypeAlign(RetTy); 5311 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes 5312 5313 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment. 5314 // For aggregates with 16-byte alignment, we use i128. 5315 if (Alignment < 128 && Size == 128) { 5316 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext()); 5317 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64)); 5318 } 5319 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size)); 5320 } 5321 5322 return getNaturalAlignIndirect(RetTy); 5323 } 5324 5325 /// isIllegalVectorType - check whether the vector type is legal for AArch64. 5326 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const { 5327 if (const VectorType *VT = Ty->getAs<VectorType>()) { 5328 // Check whether VT is legal. 5329 unsigned NumElements = VT->getNumElements(); 5330 uint64_t Size = getContext().getTypeSize(VT); 5331 // NumElements should be power of 2. 5332 if (!llvm::isPowerOf2_32(NumElements)) 5333 return true; 5334 5335 // arm64_32 has to be compatible with the ARM logic here, which allows huge 5336 // vectors for some reason. 5337 llvm::Triple Triple = getTarget().getTriple(); 5338 if (Triple.getArch() == llvm::Triple::aarch64_32 && 5339 Triple.isOSBinFormatMachO()) 5340 return Size <= 32; 5341 5342 return Size != 64 && (Size != 128 || NumElements == 1); 5343 } 5344 return false; 5345 } 5346 5347 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize, 5348 llvm::Type *eltTy, 5349 unsigned elts) const { 5350 if (!llvm::isPowerOf2_32(elts)) 5351 return false; 5352 if (totalSize.getQuantity() != 8 && 5353 (totalSize.getQuantity() != 16 || elts == 1)) 5354 return false; 5355 return true; 5356 } 5357 5358 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 5359 // Homogeneous aggregates for AAPCS64 must have base types of a floating 5360 // point type or a short-vector type. This is the same as the 32-bit ABI, 5361 // but with the difference that any floating-point type is allowed, 5362 // including __fp16. 5363 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 5364 if (BT->isFloatingPoint()) 5365 return true; 5366 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 5367 unsigned VecSize = getContext().getTypeSize(VT); 5368 if (VecSize == 64 || VecSize == 128) 5369 return true; 5370 } 5371 return false; 5372 } 5373 5374 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 5375 uint64_t Members) const { 5376 return Members <= 4; 5377 } 5378 5379 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr, 5380 QualType Ty, 5381 CodeGenFunction &CGF) const { 5382 ABIArgInfo AI = classifyArgumentType(Ty); 5383 bool IsIndirect = AI.isIndirect(); 5384 5385 llvm::Type *BaseTy = CGF.ConvertType(Ty); 5386 if (IsIndirect) 5387 BaseTy = llvm::PointerType::getUnqual(BaseTy); 5388 else if (AI.getCoerceToType()) 5389 BaseTy = AI.getCoerceToType(); 5390 5391 unsigned NumRegs = 1; 5392 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) { 5393 BaseTy = ArrTy->getElementType(); 5394 NumRegs = ArrTy->getNumElements(); 5395 } 5396 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy(); 5397 5398 // The AArch64 va_list type and handling is specified in the Procedure Call 5399 // Standard, section B.4: 5400 // 5401 // struct { 5402 // void *__stack; 5403 // void *__gr_top; 5404 // void *__vr_top; 5405 // int __gr_offs; 5406 // int __vr_offs; 5407 // }; 5408 5409 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg"); 5410 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 5411 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack"); 5412 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 5413 5414 CharUnits TySize = getContext().getTypeSizeInChars(Ty); 5415 CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty); 5416 5417 Address reg_offs_p = Address::invalid(); 5418 llvm::Value *reg_offs = nullptr; 5419 int reg_top_index; 5420 int RegSize = IsIndirect ? 8 : TySize.getQuantity(); 5421 if (!IsFPR) { 5422 // 3 is the field number of __gr_offs 5423 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p"); 5424 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs"); 5425 reg_top_index = 1; // field number for __gr_top 5426 RegSize = llvm::alignTo(RegSize, 8); 5427 } else { 5428 // 4 is the field number of __vr_offs. 5429 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p"); 5430 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs"); 5431 reg_top_index = 2; // field number for __vr_top 5432 RegSize = 16 * NumRegs; 5433 } 5434 5435 //======================================= 5436 // Find out where argument was passed 5437 //======================================= 5438 5439 // If reg_offs >= 0 we're already using the stack for this type of 5440 // argument. We don't want to keep updating reg_offs (in case it overflows, 5441 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves 5442 // whatever they get). 5443 llvm::Value *UsingStack = nullptr; 5444 UsingStack = CGF.Builder.CreateICmpSGE( 5445 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0)); 5446 5447 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock); 5448 5449 // Otherwise, at least some kind of argument could go in these registers, the 5450 // question is whether this particular type is too big. 5451 CGF.EmitBlock(MaybeRegBlock); 5452 5453 // Integer arguments may need to correct register alignment (for example a 5454 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we 5455 // align __gr_offs to calculate the potential address. 5456 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) { 5457 int Align = TyAlign.getQuantity(); 5458 5459 reg_offs = CGF.Builder.CreateAdd( 5460 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1), 5461 "align_regoffs"); 5462 reg_offs = CGF.Builder.CreateAnd( 5463 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align), 5464 "aligned_regoffs"); 5465 } 5466 5467 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list. 5468 // The fact that this is done unconditionally reflects the fact that 5469 // allocating an argument to the stack also uses up all the remaining 5470 // registers of the appropriate kind. 5471 llvm::Value *NewOffset = nullptr; 5472 NewOffset = CGF.Builder.CreateAdd( 5473 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs"); 5474 CGF.Builder.CreateStore(NewOffset, reg_offs_p); 5475 5476 // Now we're in a position to decide whether this argument really was in 5477 // registers or not. 5478 llvm::Value *InRegs = nullptr; 5479 InRegs = CGF.Builder.CreateICmpSLE( 5480 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg"); 5481 5482 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock); 5483 5484 //======================================= 5485 // Argument was in registers 5486 //======================================= 5487 5488 // Now we emit the code for if the argument was originally passed in 5489 // registers. First start the appropriate block: 5490 CGF.EmitBlock(InRegBlock); 5491 5492 llvm::Value *reg_top = nullptr; 5493 Address reg_top_p = 5494 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p"); 5495 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top"); 5496 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs), 5497 CharUnits::fromQuantity(IsFPR ? 16 : 8)); 5498 Address RegAddr = Address::invalid(); 5499 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty); 5500 5501 if (IsIndirect) { 5502 // If it's been passed indirectly (actually a struct), whatever we find from 5503 // stored registers or on the stack will actually be a struct **. 5504 MemTy = llvm::PointerType::getUnqual(MemTy); 5505 } 5506 5507 const Type *Base = nullptr; 5508 uint64_t NumMembers = 0; 5509 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers); 5510 if (IsHFA && NumMembers > 1) { 5511 // Homogeneous aggregates passed in registers will have their elements split 5512 // and stored 16-bytes apart regardless of size (they're notionally in qN, 5513 // qN+1, ...). We reload and store into a temporary local variable 5514 // contiguously. 5515 assert(!IsIndirect && "Homogeneous aggregates should be passed directly"); 5516 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0)); 5517 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0)); 5518 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers); 5519 Address Tmp = CGF.CreateTempAlloca(HFATy, 5520 std::max(TyAlign, BaseTyInfo.second)); 5521 5522 // On big-endian platforms, the value will be right-aligned in its slot. 5523 int Offset = 0; 5524 if (CGF.CGM.getDataLayout().isBigEndian() && 5525 BaseTyInfo.first.getQuantity() < 16) 5526 Offset = 16 - BaseTyInfo.first.getQuantity(); 5527 5528 for (unsigned i = 0; i < NumMembers; ++i) { 5529 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset); 5530 Address LoadAddr = 5531 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset); 5532 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy); 5533 5534 Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i); 5535 5536 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr); 5537 CGF.Builder.CreateStore(Elem, StoreAddr); 5538 } 5539 5540 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy); 5541 } else { 5542 // Otherwise the object is contiguous in memory. 5543 5544 // It might be right-aligned in its slot. 5545 CharUnits SlotSize = BaseAddr.getAlignment(); 5546 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect && 5547 (IsHFA || !isAggregateTypeForABI(Ty)) && 5548 TySize < SlotSize) { 5549 CharUnits Offset = SlotSize - TySize; 5550 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset); 5551 } 5552 5553 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy); 5554 } 5555 5556 CGF.EmitBranch(ContBlock); 5557 5558 //======================================= 5559 // Argument was on the stack 5560 //======================================= 5561 CGF.EmitBlock(OnStackBlock); 5562 5563 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p"); 5564 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack"); 5565 5566 // Again, stack arguments may need realignment. In this case both integer and 5567 // floating-point ones might be affected. 5568 if (!IsIndirect && TyAlign.getQuantity() > 8) { 5569 int Align = TyAlign.getQuantity(); 5570 5571 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty); 5572 5573 OnStackPtr = CGF.Builder.CreateAdd( 5574 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1), 5575 "align_stack"); 5576 OnStackPtr = CGF.Builder.CreateAnd( 5577 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align), 5578 "align_stack"); 5579 5580 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy); 5581 } 5582 Address OnStackAddr(OnStackPtr, 5583 std::max(CharUnits::fromQuantity(8), TyAlign)); 5584 5585 // All stack slots are multiples of 8 bytes. 5586 CharUnits StackSlotSize = CharUnits::fromQuantity(8); 5587 CharUnits StackSize; 5588 if (IsIndirect) 5589 StackSize = StackSlotSize; 5590 else 5591 StackSize = TySize.alignTo(StackSlotSize); 5592 5593 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize); 5594 llvm::Value *NewStack = 5595 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack"); 5596 5597 // Write the new value of __stack for the next call to va_arg 5598 CGF.Builder.CreateStore(NewStack, stack_p); 5599 5600 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) && 5601 TySize < StackSlotSize) { 5602 CharUnits Offset = StackSlotSize - TySize; 5603 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset); 5604 } 5605 5606 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy); 5607 5608 CGF.EmitBranch(ContBlock); 5609 5610 //======================================= 5611 // Tidy up 5612 //======================================= 5613 CGF.EmitBlock(ContBlock); 5614 5615 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, 5616 OnStackAddr, OnStackBlock, "vaargs.addr"); 5617 5618 if (IsIndirect) 5619 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"), 5620 TyAlign); 5621 5622 return ResAddr; 5623 } 5624 5625 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty, 5626 CodeGenFunction &CGF) const { 5627 // The backend's lowering doesn't support va_arg for aggregates or 5628 // illegal vector types. Lower VAArg here for these cases and use 5629 // the LLVM va_arg instruction for everything else. 5630 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty)) 5631 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect()); 5632 5633 uint64_t PointerSize = getTarget().getPointerWidth(0) / 8; 5634 CharUnits SlotSize = CharUnits::fromQuantity(PointerSize); 5635 5636 // Empty records are ignored for parameter passing purposes. 5637 if (isEmptyRecord(getContext(), Ty, true)) { 5638 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize); 5639 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 5640 return Addr; 5641 } 5642 5643 // The size of the actual thing passed, which might end up just 5644 // being a pointer for indirect types. 5645 auto TyInfo = getContext().getTypeInfoInChars(Ty); 5646 5647 // Arguments bigger than 16 bytes which aren't homogeneous 5648 // aggregates should be passed indirectly. 5649 bool IsIndirect = false; 5650 if (TyInfo.first.getQuantity() > 16) { 5651 const Type *Base = nullptr; 5652 uint64_t Members = 0; 5653 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members); 5654 } 5655 5656 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 5657 TyInfo, SlotSize, /*AllowHigherAlign*/ true); 5658 } 5659 5660 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 5661 QualType Ty) const { 5662 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 5663 CGF.getContext().getTypeInfoInChars(Ty), 5664 CharUnits::fromQuantity(8), 5665 /*allowHigherAlign*/ false); 5666 } 5667 5668 //===----------------------------------------------------------------------===// 5669 // ARM ABI Implementation 5670 //===----------------------------------------------------------------------===// 5671 5672 namespace { 5673 5674 class ARMABIInfo : public SwiftABIInfo { 5675 public: 5676 enum ABIKind { 5677 APCS = 0, 5678 AAPCS = 1, 5679 AAPCS_VFP = 2, 5680 AAPCS16_VFP = 3, 5681 }; 5682 5683 private: 5684 ABIKind Kind; 5685 5686 public: 5687 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) 5688 : SwiftABIInfo(CGT), Kind(_Kind) { 5689 setCCs(); 5690 } 5691 5692 bool isEABI() const { 5693 switch (getTarget().getTriple().getEnvironment()) { 5694 case llvm::Triple::Android: 5695 case llvm::Triple::EABI: 5696 case llvm::Triple::EABIHF: 5697 case llvm::Triple::GNUEABI: 5698 case llvm::Triple::GNUEABIHF: 5699 case llvm::Triple::MuslEABI: 5700 case llvm::Triple::MuslEABIHF: 5701 return true; 5702 default: 5703 return false; 5704 } 5705 } 5706 5707 bool isEABIHF() const { 5708 switch (getTarget().getTriple().getEnvironment()) { 5709 case llvm::Triple::EABIHF: 5710 case llvm::Triple::GNUEABIHF: 5711 case llvm::Triple::MuslEABIHF: 5712 return true; 5713 default: 5714 return false; 5715 } 5716 } 5717 5718 ABIKind getABIKind() const { return Kind; } 5719 5720 private: 5721 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic, 5722 unsigned functionCallConv) const; 5723 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic, 5724 unsigned functionCallConv) const; 5725 ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base, 5726 uint64_t Members) const; 5727 ABIArgInfo coerceIllegalVector(QualType Ty) const; 5728 bool isIllegalVectorType(QualType Ty) const; 5729 bool containsAnyFP16Vectors(QualType Ty) const; 5730 5731 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 5732 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 5733 uint64_t Members) const override; 5734 5735 bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const; 5736 5737 void computeInfo(CGFunctionInfo &FI) const override; 5738 5739 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 5740 QualType Ty) const override; 5741 5742 llvm::CallingConv::ID getLLVMDefaultCC() const; 5743 llvm::CallingConv::ID getABIDefaultCC() const; 5744 void setCCs(); 5745 5746 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 5747 bool asReturnValue) const override { 5748 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 5749 } 5750 bool isSwiftErrorInRegister() const override { 5751 return true; 5752 } 5753 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy, 5754 unsigned elts) const override; 5755 }; 5756 5757 class ARMTargetCodeGenInfo : public TargetCodeGenInfo { 5758 public: 5759 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) 5760 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {} 5761 5762 const ARMABIInfo &getABIInfo() const { 5763 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo()); 5764 } 5765 5766 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 5767 return 13; 5768 } 5769 5770 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 5771 return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue"; 5772 } 5773 5774 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5775 llvm::Value *Address) const override { 5776 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 5777 5778 // 0-15 are the 16 integer registers. 5779 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15); 5780 return false; 5781 } 5782 5783 unsigned getSizeOfUnwindException() const override { 5784 if (getABIInfo().isEABI()) return 88; 5785 return TargetCodeGenInfo::getSizeOfUnwindException(); 5786 } 5787 5788 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5789 CodeGen::CodeGenModule &CGM) const override { 5790 if (GV->isDeclaration()) 5791 return; 5792 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 5793 if (!FD) 5794 return; 5795 5796 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>(); 5797 if (!Attr) 5798 return; 5799 5800 const char *Kind; 5801 switch (Attr->getInterrupt()) { 5802 case ARMInterruptAttr::Generic: Kind = ""; break; 5803 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break; 5804 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break; 5805 case ARMInterruptAttr::SWI: Kind = "SWI"; break; 5806 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break; 5807 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break; 5808 } 5809 5810 llvm::Function *Fn = cast<llvm::Function>(GV); 5811 5812 Fn->addFnAttr("interrupt", Kind); 5813 5814 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind(); 5815 if (ABI == ARMABIInfo::APCS) 5816 return; 5817 5818 // AAPCS guarantees that sp will be 8-byte aligned on any public interface, 5819 // however this is not necessarily true on taking any interrupt. Instruct 5820 // the backend to perform a realignment as part of the function prologue. 5821 llvm::AttrBuilder B; 5822 B.addStackAlignmentAttr(8); 5823 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); 5824 } 5825 }; 5826 5827 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo { 5828 public: 5829 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) 5830 : ARMTargetCodeGenInfo(CGT, K) {} 5831 5832 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5833 CodeGen::CodeGenModule &CGM) const override; 5834 5835 void getDependentLibraryOption(llvm::StringRef Lib, 5836 llvm::SmallString<24> &Opt) const override { 5837 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib); 5838 } 5839 5840 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, 5841 llvm::SmallString<32> &Opt) const override { 5842 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 5843 } 5844 }; 5845 5846 void WindowsARMTargetCodeGenInfo::setTargetAttributes( 5847 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 5848 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 5849 if (GV->isDeclaration()) 5850 return; 5851 addStackProbeTargetAttributes(D, GV, CGM); 5852 } 5853 } 5854 5855 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const { 5856 if (!::classifyReturnType(getCXXABI(), FI, *this)) 5857 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(), 5858 FI.getCallingConvention()); 5859 5860 for (auto &I : FI.arguments()) 5861 I.info = classifyArgumentType(I.type, FI.isVariadic(), 5862 FI.getCallingConvention()); 5863 5864 5865 // Always honor user-specified calling convention. 5866 if (FI.getCallingConvention() != llvm::CallingConv::C) 5867 return; 5868 5869 llvm::CallingConv::ID cc = getRuntimeCC(); 5870 if (cc != llvm::CallingConv::C) 5871 FI.setEffectiveCallingConvention(cc); 5872 } 5873 5874 /// Return the default calling convention that LLVM will use. 5875 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const { 5876 // The default calling convention that LLVM will infer. 5877 if (isEABIHF() || getTarget().getTriple().isWatchABI()) 5878 return llvm::CallingConv::ARM_AAPCS_VFP; 5879 else if (isEABI()) 5880 return llvm::CallingConv::ARM_AAPCS; 5881 else 5882 return llvm::CallingConv::ARM_APCS; 5883 } 5884 5885 /// Return the calling convention that our ABI would like us to use 5886 /// as the C calling convention. 5887 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const { 5888 switch (getABIKind()) { 5889 case APCS: return llvm::CallingConv::ARM_APCS; 5890 case AAPCS: return llvm::CallingConv::ARM_AAPCS; 5891 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 5892 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 5893 } 5894 llvm_unreachable("bad ABI kind"); 5895 } 5896 5897 void ARMABIInfo::setCCs() { 5898 assert(getRuntimeCC() == llvm::CallingConv::C); 5899 5900 // Don't muddy up the IR with a ton of explicit annotations if 5901 // they'd just match what LLVM will infer from the triple. 5902 llvm::CallingConv::ID abiCC = getABIDefaultCC(); 5903 if (abiCC != getLLVMDefaultCC()) 5904 RuntimeCC = abiCC; 5905 } 5906 5907 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const { 5908 uint64_t Size = getContext().getTypeSize(Ty); 5909 if (Size <= 32) { 5910 llvm::Type *ResType = 5911 llvm::Type::getInt32Ty(getVMContext()); 5912 return ABIArgInfo::getDirect(ResType); 5913 } 5914 if (Size == 64 || Size == 128) { 5915 llvm::Type *ResType = llvm::VectorType::get( 5916 llvm::Type::getInt32Ty(getVMContext()), Size / 32); 5917 return ABIArgInfo::getDirect(ResType); 5918 } 5919 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5920 } 5921 5922 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty, 5923 const Type *Base, 5924 uint64_t Members) const { 5925 assert(Base && "Base class should be set for homogeneous aggregate"); 5926 // Base can be a floating-point or a vector. 5927 if (const VectorType *VT = Base->getAs<VectorType>()) { 5928 // FP16 vectors should be converted to integer vectors 5929 if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) { 5930 uint64_t Size = getContext().getTypeSize(VT); 5931 llvm::Type *NewVecTy = llvm::VectorType::get( 5932 llvm::Type::getInt32Ty(getVMContext()), Size / 32); 5933 llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members); 5934 return ABIArgInfo::getDirect(Ty, 0, nullptr, false); 5935 } 5936 } 5937 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false); 5938 } 5939 5940 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic, 5941 unsigned functionCallConv) const { 5942 // 6.1.2.1 The following argument types are VFP CPRCs: 5943 // A single-precision floating-point type (including promoted 5944 // half-precision types); A double-precision floating-point type; 5945 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate 5946 // with a Base Type of a single- or double-precision floating-point type, 5947 // 64-bit containerized vectors or 128-bit containerized vectors with one 5948 // to four Elements. 5949 // Variadic functions should always marshal to the base standard. 5950 bool IsAAPCS_VFP = 5951 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false); 5952 5953 Ty = useFirstFieldIfTransparentUnion(Ty); 5954 5955 // Handle illegal vector types here. 5956 if (isIllegalVectorType(Ty)) 5957 return coerceIllegalVector(Ty); 5958 5959 // _Float16 and __fp16 get passed as if it were an int or float, but with 5960 // the top 16 bits unspecified. This is not done for OpenCL as it handles the 5961 // half type natively, and does not need to interwork with AAPCS code. 5962 if ((Ty->isFloat16Type() || Ty->isHalfType()) && 5963 !getContext().getLangOpts().NativeHalfArgsAndReturns) { 5964 llvm::Type *ResType = IsAAPCS_VFP ? 5965 llvm::Type::getFloatTy(getVMContext()) : 5966 llvm::Type::getInt32Ty(getVMContext()); 5967 return ABIArgInfo::getDirect(ResType); 5968 } 5969 5970 if (!isAggregateTypeForABI(Ty)) { 5971 // Treat an enum type as its underlying type. 5972 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) { 5973 Ty = EnumTy->getDecl()->getIntegerType(); 5974 } 5975 5976 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 5977 : ABIArgInfo::getDirect()); 5978 } 5979 5980 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 5981 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 5982 } 5983 5984 // Ignore empty records. 5985 if (isEmptyRecord(getContext(), Ty, true)) 5986 return ABIArgInfo::getIgnore(); 5987 5988 if (IsAAPCS_VFP) { 5989 // Homogeneous Aggregates need to be expanded when we can fit the aggregate 5990 // into VFP registers. 5991 const Type *Base = nullptr; 5992 uint64_t Members = 0; 5993 if (isHomogeneousAggregate(Ty, Base, Members)) 5994 return classifyHomogeneousAggregate(Ty, Base, Members); 5995 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) { 5996 // WatchOS does have homogeneous aggregates. Note that we intentionally use 5997 // this convention even for a variadic function: the backend will use GPRs 5998 // if needed. 5999 const Type *Base = nullptr; 6000 uint64_t Members = 0; 6001 if (isHomogeneousAggregate(Ty, Base, Members)) { 6002 assert(Base && Members <= 4 && "unexpected homogeneous aggregate"); 6003 llvm::Type *Ty = 6004 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members); 6005 return ABIArgInfo::getDirect(Ty, 0, nullptr, false); 6006 } 6007 } 6008 6009 if (getABIKind() == ARMABIInfo::AAPCS16_VFP && 6010 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) { 6011 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're 6012 // bigger than 128-bits, they get placed in space allocated by the caller, 6013 // and a pointer is passed. 6014 return ABIArgInfo::getIndirect( 6015 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false); 6016 } 6017 6018 // Support byval for ARM. 6019 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at 6020 // most 8-byte. We realign the indirect argument if type alignment is bigger 6021 // than ABI alignment. 6022 uint64_t ABIAlign = 4; 6023 uint64_t TyAlign; 6024 if (getABIKind() == ARMABIInfo::AAPCS_VFP || 6025 getABIKind() == ARMABIInfo::AAPCS) { 6026 TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity(); 6027 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8); 6028 } else { 6029 TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity(); 6030 } 6031 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) { 6032 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval"); 6033 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign), 6034 /*ByVal=*/true, 6035 /*Realign=*/TyAlign > ABIAlign); 6036 } 6037 6038 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of 6039 // same size and alignment. 6040 if (getTarget().isRenderScriptTarget()) { 6041 return coerceToIntArray(Ty, getContext(), getVMContext()); 6042 } 6043 6044 // Otherwise, pass by coercing to a structure of the appropriate size. 6045 llvm::Type* ElemTy; 6046 unsigned SizeRegs; 6047 // FIXME: Try to match the types of the arguments more accurately where 6048 // we can. 6049 if (TyAlign <= 4) { 6050 ElemTy = llvm::Type::getInt32Ty(getVMContext()); 6051 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32; 6052 } else { 6053 ElemTy = llvm::Type::getInt64Ty(getVMContext()); 6054 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64; 6055 } 6056 6057 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs)); 6058 } 6059 6060 static bool isIntegerLikeType(QualType Ty, ASTContext &Context, 6061 llvm::LLVMContext &VMContext) { 6062 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure 6063 // is called integer-like if its size is less than or equal to one word, and 6064 // the offset of each of its addressable sub-fields is zero. 6065 6066 uint64_t Size = Context.getTypeSize(Ty); 6067 6068 // Check that the type fits in a word. 6069 if (Size > 32) 6070 return false; 6071 6072 // FIXME: Handle vector types! 6073 if (Ty->isVectorType()) 6074 return false; 6075 6076 // Float types are never treated as "integer like". 6077 if (Ty->isRealFloatingType()) 6078 return false; 6079 6080 // If this is a builtin or pointer type then it is ok. 6081 if (Ty->getAs<BuiltinType>() || Ty->isPointerType()) 6082 return true; 6083 6084 // Small complex integer types are "integer like". 6085 if (const ComplexType *CT = Ty->getAs<ComplexType>()) 6086 return isIntegerLikeType(CT->getElementType(), Context, VMContext); 6087 6088 // Single element and zero sized arrays should be allowed, by the definition 6089 // above, but they are not. 6090 6091 // Otherwise, it must be a record type. 6092 const RecordType *RT = Ty->getAs<RecordType>(); 6093 if (!RT) return false; 6094 6095 // Ignore records with flexible arrays. 6096 const RecordDecl *RD = RT->getDecl(); 6097 if (RD->hasFlexibleArrayMember()) 6098 return false; 6099 6100 // Check that all sub-fields are at offset 0, and are themselves "integer 6101 // like". 6102 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 6103 6104 bool HadField = false; 6105 unsigned idx = 0; 6106 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 6107 i != e; ++i, ++idx) { 6108 const FieldDecl *FD = *i; 6109 6110 // Bit-fields are not addressable, we only need to verify they are "integer 6111 // like". We still have to disallow a subsequent non-bitfield, for example: 6112 // struct { int : 0; int x } 6113 // is non-integer like according to gcc. 6114 if (FD->isBitField()) { 6115 if (!RD->isUnion()) 6116 HadField = true; 6117 6118 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 6119 return false; 6120 6121 continue; 6122 } 6123 6124 // Check if this field is at offset 0. 6125 if (Layout.getFieldOffset(idx) != 0) 6126 return false; 6127 6128 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 6129 return false; 6130 6131 // Only allow at most one field in a structure. This doesn't match the 6132 // wording above, but follows gcc in situations with a field following an 6133 // empty structure. 6134 if (!RD->isUnion()) { 6135 if (HadField) 6136 return false; 6137 6138 HadField = true; 6139 } 6140 } 6141 6142 return true; 6143 } 6144 6145 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic, 6146 unsigned functionCallConv) const { 6147 6148 // Variadic functions should always marshal to the base standard. 6149 bool IsAAPCS_VFP = 6150 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true); 6151 6152 if (RetTy->isVoidType()) 6153 return ABIArgInfo::getIgnore(); 6154 6155 if (const VectorType *VT = RetTy->getAs<VectorType>()) { 6156 // Large vector types should be returned via memory. 6157 if (getContext().getTypeSize(RetTy) > 128) 6158 return getNaturalAlignIndirect(RetTy); 6159 // FP16 vectors should be converted to integer vectors 6160 if (!getTarget().hasLegalHalfType() && 6161 (VT->getElementType()->isFloat16Type() || 6162 VT->getElementType()->isHalfType())) 6163 return coerceIllegalVector(RetTy); 6164 } 6165 6166 // _Float16 and __fp16 get returned as if it were an int or float, but with 6167 // the top 16 bits unspecified. This is not done for OpenCL as it handles the 6168 // half type natively, and does not need to interwork with AAPCS code. 6169 if ((RetTy->isFloat16Type() || RetTy->isHalfType()) && 6170 !getContext().getLangOpts().NativeHalfArgsAndReturns) { 6171 llvm::Type *ResType = IsAAPCS_VFP ? 6172 llvm::Type::getFloatTy(getVMContext()) : 6173 llvm::Type::getInt32Ty(getVMContext()); 6174 return ABIArgInfo::getDirect(ResType); 6175 } 6176 6177 if (!isAggregateTypeForABI(RetTy)) { 6178 // Treat an enum type as its underlying type. 6179 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 6180 RetTy = EnumTy->getDecl()->getIntegerType(); 6181 6182 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) 6183 : ABIArgInfo::getDirect(); 6184 } 6185 6186 // Are we following APCS? 6187 if (getABIKind() == APCS) { 6188 if (isEmptyRecord(getContext(), RetTy, false)) 6189 return ABIArgInfo::getIgnore(); 6190 6191 // Complex types are all returned as packed integers. 6192 // 6193 // FIXME: Consider using 2 x vector types if the back end handles them 6194 // correctly. 6195 if (RetTy->isAnyComplexType()) 6196 return ABIArgInfo::getDirect(llvm::IntegerType::get( 6197 getVMContext(), getContext().getTypeSize(RetTy))); 6198 6199 // Integer like structures are returned in r0. 6200 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) { 6201 // Return in the smallest viable integer type. 6202 uint64_t Size = getContext().getTypeSize(RetTy); 6203 if (Size <= 8) 6204 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 6205 if (Size <= 16) 6206 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 6207 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6208 } 6209 6210 // Otherwise return in memory. 6211 return getNaturalAlignIndirect(RetTy); 6212 } 6213 6214 // Otherwise this is an AAPCS variant. 6215 6216 if (isEmptyRecord(getContext(), RetTy, true)) 6217 return ABIArgInfo::getIgnore(); 6218 6219 // Check for homogeneous aggregates with AAPCS-VFP. 6220 if (IsAAPCS_VFP) { 6221 const Type *Base = nullptr; 6222 uint64_t Members = 0; 6223 if (isHomogeneousAggregate(RetTy, Base, Members)) 6224 return classifyHomogeneousAggregate(RetTy, Base, Members); 6225 } 6226 6227 // Aggregates <= 4 bytes are returned in r0; other aggregates 6228 // are returned indirectly. 6229 uint64_t Size = getContext().getTypeSize(RetTy); 6230 if (Size <= 32) { 6231 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of 6232 // same size and alignment. 6233 if (getTarget().isRenderScriptTarget()) { 6234 return coerceToIntArray(RetTy, getContext(), getVMContext()); 6235 } 6236 if (getDataLayout().isBigEndian()) 6237 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4) 6238 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6239 6240 // Return in the smallest viable integer type. 6241 if (Size <= 8) 6242 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 6243 if (Size <= 16) 6244 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 6245 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6246 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) { 6247 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext()); 6248 llvm::Type *CoerceTy = 6249 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32); 6250 return ABIArgInfo::getDirect(CoerceTy); 6251 } 6252 6253 return getNaturalAlignIndirect(RetTy); 6254 } 6255 6256 /// isIllegalVector - check whether Ty is an illegal vector type. 6257 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const { 6258 if (const VectorType *VT = Ty->getAs<VectorType> ()) { 6259 // On targets that don't support FP16, FP16 is expanded into float, and we 6260 // don't want the ABI to depend on whether or not FP16 is supported in 6261 // hardware. Thus return false to coerce FP16 vectors into integer vectors. 6262 if (!getTarget().hasLegalHalfType() && 6263 (VT->getElementType()->isFloat16Type() || 6264 VT->getElementType()->isHalfType())) 6265 return true; 6266 if (isAndroid()) { 6267 // Android shipped using Clang 3.1, which supported a slightly different 6268 // vector ABI. The primary differences were that 3-element vector types 6269 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path 6270 // accepts that legacy behavior for Android only. 6271 // Check whether VT is legal. 6272 unsigned NumElements = VT->getNumElements(); 6273 // NumElements should be power of 2 or equal to 3. 6274 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3) 6275 return true; 6276 } else { 6277 // Check whether VT is legal. 6278 unsigned NumElements = VT->getNumElements(); 6279 uint64_t Size = getContext().getTypeSize(VT); 6280 // NumElements should be power of 2. 6281 if (!llvm::isPowerOf2_32(NumElements)) 6282 return true; 6283 // Size should be greater than 32 bits. 6284 return Size <= 32; 6285 } 6286 } 6287 return false; 6288 } 6289 6290 /// Return true if a type contains any 16-bit floating point vectors 6291 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const { 6292 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 6293 uint64_t NElements = AT->getSize().getZExtValue(); 6294 if (NElements == 0) 6295 return false; 6296 return containsAnyFP16Vectors(AT->getElementType()); 6297 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 6298 const RecordDecl *RD = RT->getDecl(); 6299 6300 // If this is a C++ record, check the bases first. 6301 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6302 if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) { 6303 return containsAnyFP16Vectors(B.getType()); 6304 })) 6305 return true; 6306 6307 if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) { 6308 return FD && containsAnyFP16Vectors(FD->getType()); 6309 })) 6310 return true; 6311 6312 return false; 6313 } else { 6314 if (const VectorType *VT = Ty->getAs<VectorType>()) 6315 return (VT->getElementType()->isFloat16Type() || 6316 VT->getElementType()->isHalfType()); 6317 return false; 6318 } 6319 } 6320 6321 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize, 6322 llvm::Type *eltTy, 6323 unsigned numElts) const { 6324 if (!llvm::isPowerOf2_32(numElts)) 6325 return false; 6326 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy); 6327 if (size > 64) 6328 return false; 6329 if (vectorSize.getQuantity() != 8 && 6330 (vectorSize.getQuantity() != 16 || numElts == 1)) 6331 return false; 6332 return true; 6333 } 6334 6335 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 6336 // Homogeneous aggregates for AAPCS-VFP must have base types of float, 6337 // double, or 64-bit or 128-bit vectors. 6338 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 6339 if (BT->getKind() == BuiltinType::Float || 6340 BT->getKind() == BuiltinType::Double || 6341 BT->getKind() == BuiltinType::LongDouble) 6342 return true; 6343 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 6344 unsigned VecSize = getContext().getTypeSize(VT); 6345 if (VecSize == 64 || VecSize == 128) 6346 return true; 6347 } 6348 return false; 6349 } 6350 6351 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 6352 uint64_t Members) const { 6353 return Members <= 4; 6354 } 6355 6356 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention, 6357 bool acceptHalf) const { 6358 // Give precedence to user-specified calling conventions. 6359 if (callConvention != llvm::CallingConv::C) 6360 return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP); 6361 else 6362 return (getABIKind() == AAPCS_VFP) || 6363 (acceptHalf && (getABIKind() == AAPCS16_VFP)); 6364 } 6365 6366 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6367 QualType Ty) const { 6368 CharUnits SlotSize = CharUnits::fromQuantity(4); 6369 6370 // Empty records are ignored for parameter passing purposes. 6371 if (isEmptyRecord(getContext(), Ty, true)) { 6372 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize); 6373 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 6374 return Addr; 6375 } 6376 6377 CharUnits TySize = getContext().getTypeSizeInChars(Ty); 6378 CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty); 6379 6380 // Use indirect if size of the illegal vector is bigger than 16 bytes. 6381 bool IsIndirect = false; 6382 const Type *Base = nullptr; 6383 uint64_t Members = 0; 6384 if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) { 6385 IsIndirect = true; 6386 6387 // ARMv7k passes structs bigger than 16 bytes indirectly, in space 6388 // allocated by the caller. 6389 } else if (TySize > CharUnits::fromQuantity(16) && 6390 getABIKind() == ARMABIInfo::AAPCS16_VFP && 6391 !isHomogeneousAggregate(Ty, Base, Members)) { 6392 IsIndirect = true; 6393 6394 // Otherwise, bound the type's ABI alignment. 6395 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for 6396 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte. 6397 // Our callers should be prepared to handle an under-aligned address. 6398 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP || 6399 getABIKind() == ARMABIInfo::AAPCS) { 6400 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4)); 6401 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8)); 6402 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) { 6403 // ARMv7k allows type alignment up to 16 bytes. 6404 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4)); 6405 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16)); 6406 } else { 6407 TyAlignForABI = CharUnits::fromQuantity(4); 6408 } 6409 6410 std::pair<CharUnits, CharUnits> TyInfo = { TySize, TyAlignForABI }; 6411 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo, 6412 SlotSize, /*AllowHigherAlign*/ true); 6413 } 6414 6415 //===----------------------------------------------------------------------===// 6416 // NVPTX ABI Implementation 6417 //===----------------------------------------------------------------------===// 6418 6419 namespace { 6420 6421 class NVPTXTargetCodeGenInfo; 6422 6423 class NVPTXABIInfo : public ABIInfo { 6424 NVPTXTargetCodeGenInfo &CGInfo; 6425 6426 public: 6427 NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info) 6428 : ABIInfo(CGT), CGInfo(Info) {} 6429 6430 ABIArgInfo classifyReturnType(QualType RetTy) const; 6431 ABIArgInfo classifyArgumentType(QualType Ty) const; 6432 6433 void computeInfo(CGFunctionInfo &FI) const override; 6434 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6435 QualType Ty) const override; 6436 }; 6437 6438 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo { 6439 public: 6440 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT) 6441 : TargetCodeGenInfo(new NVPTXABIInfo(CGT, *this)) {} 6442 6443 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 6444 CodeGen::CodeGenModule &M) const override; 6445 bool shouldEmitStaticExternCAliases() const override; 6446 6447 llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override { 6448 // On the device side, surface reference is represented as an object handle 6449 // in 64-bit integer. 6450 return llvm::Type::getInt64Ty(getABIInfo().getVMContext()); 6451 } 6452 6453 llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override { 6454 // On the device side, texture reference is represented as an object handle 6455 // in 64-bit integer. 6456 return llvm::Type::getInt64Ty(getABIInfo().getVMContext()); 6457 } 6458 6459 bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst, 6460 LValue Src) const override { 6461 emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src); 6462 return true; 6463 } 6464 6465 bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst, 6466 LValue Src) const override { 6467 emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src); 6468 return true; 6469 } 6470 6471 private: 6472 // Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the 6473 // resulting MDNode to the nvvm.annotations MDNode. 6474 static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name, 6475 int Operand); 6476 6477 static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst, 6478 LValue Src) { 6479 llvm::Value *Handle = nullptr; 6480 llvm::Constant *C = 6481 llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer()); 6482 // Lookup `addrspacecast` through the constant pointer if any. 6483 if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C)) 6484 C = llvm::cast<llvm::Constant>(ASC->getPointerOperand()); 6485 if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) { 6486 // Load the handle from the specific global variable using 6487 // `nvvm.texsurf.handle.internal` intrinsic. 6488 Handle = CGF.EmitRuntimeCall( 6489 CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal, 6490 {GV->getType()}), 6491 {GV}, "texsurf_handle"); 6492 } else 6493 Handle = CGF.EmitLoadOfScalar(Src, SourceLocation()); 6494 CGF.EmitStoreOfScalar(Handle, Dst); 6495 } 6496 }; 6497 6498 /// Checks if the type is unsupported directly by the current target. 6499 static bool isUnsupportedType(ASTContext &Context, QualType T) { 6500 if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type()) 6501 return true; 6502 if (!Context.getTargetInfo().hasFloat128Type() && 6503 (T->isFloat128Type() || 6504 (T->isRealFloatingType() && Context.getTypeSize(T) == 128))) 6505 return true; 6506 if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() && 6507 Context.getTypeSize(T) > 64) 6508 return true; 6509 if (const auto *AT = T->getAsArrayTypeUnsafe()) 6510 return isUnsupportedType(Context, AT->getElementType()); 6511 const auto *RT = T->getAs<RecordType>(); 6512 if (!RT) 6513 return false; 6514 const RecordDecl *RD = RT->getDecl(); 6515 6516 // If this is a C++ record, check the bases first. 6517 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6518 for (const CXXBaseSpecifier &I : CXXRD->bases()) 6519 if (isUnsupportedType(Context, I.getType())) 6520 return true; 6521 6522 for (const FieldDecl *I : RD->fields()) 6523 if (isUnsupportedType(Context, I->getType())) 6524 return true; 6525 return false; 6526 } 6527 6528 /// Coerce the given type into an array with maximum allowed size of elements. 6529 static ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, ASTContext &Context, 6530 llvm::LLVMContext &LLVMContext, 6531 unsigned MaxSize) { 6532 // Alignment and Size are measured in bits. 6533 const uint64_t Size = Context.getTypeSize(Ty); 6534 const uint64_t Alignment = Context.getTypeAlign(Ty); 6535 const unsigned Div = std::min<unsigned>(MaxSize, Alignment); 6536 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Div); 6537 const uint64_t NumElements = (Size + Div - 1) / Div; 6538 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements)); 6539 } 6540 6541 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const { 6542 if (RetTy->isVoidType()) 6543 return ABIArgInfo::getIgnore(); 6544 6545 if (getContext().getLangOpts().OpenMP && 6546 getContext().getLangOpts().OpenMPIsDevice && 6547 isUnsupportedType(getContext(), RetTy)) 6548 return coerceToIntArrayWithLimit(RetTy, getContext(), getVMContext(), 64); 6549 6550 // note: this is different from default ABI 6551 if (!RetTy->isScalarType()) 6552 return ABIArgInfo::getDirect(); 6553 6554 // Treat an enum type as its underlying type. 6555 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 6556 RetTy = EnumTy->getDecl()->getIntegerType(); 6557 6558 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) 6559 : ABIArgInfo::getDirect()); 6560 } 6561 6562 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const { 6563 // Treat an enum type as its underlying type. 6564 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 6565 Ty = EnumTy->getDecl()->getIntegerType(); 6566 6567 // Return aggregates type as indirect by value 6568 if (isAggregateTypeForABI(Ty)) { 6569 // Under CUDA device compilation, tex/surf builtin types are replaced with 6570 // object types and passed directly. 6571 if (getContext().getLangOpts().CUDAIsDevice) { 6572 if (Ty->isCUDADeviceBuiltinSurfaceType()) 6573 return ABIArgInfo::getDirect( 6574 CGInfo.getCUDADeviceBuiltinSurfaceDeviceType()); 6575 if (Ty->isCUDADeviceBuiltinTextureType()) 6576 return ABIArgInfo::getDirect( 6577 CGInfo.getCUDADeviceBuiltinTextureDeviceType()); 6578 } 6579 return getNaturalAlignIndirect(Ty, /* byval */ true); 6580 } 6581 6582 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 6583 : ABIArgInfo::getDirect()); 6584 } 6585 6586 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const { 6587 if (!getCXXABI().classifyReturnType(FI)) 6588 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 6589 for (auto &I : FI.arguments()) 6590 I.info = classifyArgumentType(I.type); 6591 6592 // Always honor user-specified calling convention. 6593 if (FI.getCallingConvention() != llvm::CallingConv::C) 6594 return; 6595 6596 FI.setEffectiveCallingConvention(getRuntimeCC()); 6597 } 6598 6599 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6600 QualType Ty) const { 6601 llvm_unreachable("NVPTX does not support varargs"); 6602 } 6603 6604 void NVPTXTargetCodeGenInfo::setTargetAttributes( 6605 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 6606 if (GV->isDeclaration()) 6607 return; 6608 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D); 6609 if (VD) { 6610 if (M.getLangOpts().CUDA) { 6611 if (VD->getType()->isCUDADeviceBuiltinSurfaceType()) 6612 addNVVMMetadata(GV, "surface", 1); 6613 else if (VD->getType()->isCUDADeviceBuiltinTextureType()) 6614 addNVVMMetadata(GV, "texture", 1); 6615 return; 6616 } 6617 } 6618 6619 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 6620 if (!FD) return; 6621 6622 llvm::Function *F = cast<llvm::Function>(GV); 6623 6624 // Perform special handling in OpenCL mode 6625 if (M.getLangOpts().OpenCL) { 6626 // Use OpenCL function attributes to check for kernel functions 6627 // By default, all functions are device functions 6628 if (FD->hasAttr<OpenCLKernelAttr>()) { 6629 // OpenCL __kernel functions get kernel metadata 6630 // Create !{<func-ref>, metadata !"kernel", i32 1} node 6631 addNVVMMetadata(F, "kernel", 1); 6632 // And kernel functions are not subject to inlining 6633 F->addFnAttr(llvm::Attribute::NoInline); 6634 } 6635 } 6636 6637 // Perform special handling in CUDA mode. 6638 if (M.getLangOpts().CUDA) { 6639 // CUDA __global__ functions get a kernel metadata entry. Since 6640 // __global__ functions cannot be called from the device, we do not 6641 // need to set the noinline attribute. 6642 if (FD->hasAttr<CUDAGlobalAttr>()) { 6643 // Create !{<func-ref>, metadata !"kernel", i32 1} node 6644 addNVVMMetadata(F, "kernel", 1); 6645 } 6646 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) { 6647 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node 6648 llvm::APSInt MaxThreads(32); 6649 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext()); 6650 if (MaxThreads > 0) 6651 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue()); 6652 6653 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was 6654 // not specified in __launch_bounds__ or if the user specified a 0 value, 6655 // we don't have to add a PTX directive. 6656 if (Attr->getMinBlocks()) { 6657 llvm::APSInt MinBlocks(32); 6658 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext()); 6659 if (MinBlocks > 0) 6660 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node 6661 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue()); 6662 } 6663 } 6664 } 6665 } 6666 6667 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV, 6668 StringRef Name, int Operand) { 6669 llvm::Module *M = GV->getParent(); 6670 llvm::LLVMContext &Ctx = M->getContext(); 6671 6672 // Get "nvvm.annotations" metadata node 6673 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations"); 6674 6675 llvm::Metadata *MDVals[] = { 6676 llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name), 6677 llvm::ConstantAsMetadata::get( 6678 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))}; 6679 // Append metadata to nvvm.annotations 6680 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 6681 } 6682 6683 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const { 6684 return false; 6685 } 6686 } 6687 6688 //===----------------------------------------------------------------------===// 6689 // SystemZ ABI Implementation 6690 //===----------------------------------------------------------------------===// 6691 6692 namespace { 6693 6694 class SystemZABIInfo : public SwiftABIInfo { 6695 bool HasVector; 6696 bool IsSoftFloatABI; 6697 6698 public: 6699 SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF) 6700 : SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {} 6701 6702 bool isPromotableIntegerType(QualType Ty) const; 6703 bool isCompoundType(QualType Ty) const; 6704 bool isVectorArgumentType(QualType Ty) const; 6705 bool isFPArgumentType(QualType Ty) const; 6706 QualType GetSingleElementType(QualType Ty) const; 6707 6708 ABIArgInfo classifyReturnType(QualType RetTy) const; 6709 ABIArgInfo classifyArgumentType(QualType ArgTy) const; 6710 6711 void computeInfo(CGFunctionInfo &FI) const override { 6712 if (!getCXXABI().classifyReturnType(FI)) 6713 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 6714 for (auto &I : FI.arguments()) 6715 I.info = classifyArgumentType(I.type); 6716 } 6717 6718 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6719 QualType Ty) const override; 6720 6721 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 6722 bool asReturnValue) const override { 6723 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 6724 } 6725 bool isSwiftErrorInRegister() const override { 6726 return false; 6727 } 6728 }; 6729 6730 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo { 6731 public: 6732 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI) 6733 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector, SoftFloatABI)) {} 6734 }; 6735 6736 } 6737 6738 bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const { 6739 // Treat an enum type as its underlying type. 6740 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 6741 Ty = EnumTy->getDecl()->getIntegerType(); 6742 6743 // Promotable integer types are required to be promoted by the ABI. 6744 if (Ty->isPromotableIntegerType()) 6745 return true; 6746 6747 // 32-bit values must also be promoted. 6748 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 6749 switch (BT->getKind()) { 6750 case BuiltinType::Int: 6751 case BuiltinType::UInt: 6752 return true; 6753 default: 6754 return false; 6755 } 6756 return false; 6757 } 6758 6759 bool SystemZABIInfo::isCompoundType(QualType Ty) const { 6760 return (Ty->isAnyComplexType() || 6761 Ty->isVectorType() || 6762 isAggregateTypeForABI(Ty)); 6763 } 6764 6765 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const { 6766 return (HasVector && 6767 Ty->isVectorType() && 6768 getContext().getTypeSize(Ty) <= 128); 6769 } 6770 6771 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const { 6772 if (IsSoftFloatABI) 6773 return false; 6774 6775 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 6776 switch (BT->getKind()) { 6777 case BuiltinType::Float: 6778 case BuiltinType::Double: 6779 return true; 6780 default: 6781 return false; 6782 } 6783 6784 return false; 6785 } 6786 6787 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const { 6788 if (const RecordType *RT = Ty->getAsStructureType()) { 6789 const RecordDecl *RD = RT->getDecl(); 6790 QualType Found; 6791 6792 // If this is a C++ record, check the bases first. 6793 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6794 for (const auto &I : CXXRD->bases()) { 6795 QualType Base = I.getType(); 6796 6797 // Empty bases don't affect things either way. 6798 if (isEmptyRecord(getContext(), Base, true)) 6799 continue; 6800 6801 if (!Found.isNull()) 6802 return Ty; 6803 Found = GetSingleElementType(Base); 6804 } 6805 6806 // Check the fields. 6807 for (const auto *FD : RD->fields()) { 6808 // For compatibility with GCC, ignore empty bitfields in C++ mode. 6809 // Unlike isSingleElementStruct(), empty structure and array fields 6810 // do count. So do anonymous bitfields that aren't zero-sized. 6811 if (getContext().getLangOpts().CPlusPlus && 6812 FD->isZeroLengthBitField(getContext())) 6813 continue; 6814 6815 // Unlike isSingleElementStruct(), arrays do not count. 6816 // Nested structures still do though. 6817 if (!Found.isNull()) 6818 return Ty; 6819 Found = GetSingleElementType(FD->getType()); 6820 } 6821 6822 // Unlike isSingleElementStruct(), trailing padding is allowed. 6823 // An 8-byte aligned struct s { float f; } is passed as a double. 6824 if (!Found.isNull()) 6825 return Found; 6826 } 6827 6828 return Ty; 6829 } 6830 6831 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6832 QualType Ty) const { 6833 // Assume that va_list type is correct; should be pointer to LLVM type: 6834 // struct { 6835 // i64 __gpr; 6836 // i64 __fpr; 6837 // i8 *__overflow_arg_area; 6838 // i8 *__reg_save_area; 6839 // }; 6840 6841 // Every non-vector argument occupies 8 bytes and is passed by preference 6842 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are 6843 // always passed on the stack. 6844 Ty = getContext().getCanonicalType(Ty); 6845 auto TyInfo = getContext().getTypeInfoInChars(Ty); 6846 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty); 6847 llvm::Type *DirectTy = ArgTy; 6848 ABIArgInfo AI = classifyArgumentType(Ty); 6849 bool IsIndirect = AI.isIndirect(); 6850 bool InFPRs = false; 6851 bool IsVector = false; 6852 CharUnits UnpaddedSize; 6853 CharUnits DirectAlign; 6854 if (IsIndirect) { 6855 DirectTy = llvm::PointerType::getUnqual(DirectTy); 6856 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8); 6857 } else { 6858 if (AI.getCoerceToType()) 6859 ArgTy = AI.getCoerceToType(); 6860 InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy())); 6861 IsVector = ArgTy->isVectorTy(); 6862 UnpaddedSize = TyInfo.first; 6863 DirectAlign = TyInfo.second; 6864 } 6865 CharUnits PaddedSize = CharUnits::fromQuantity(8); 6866 if (IsVector && UnpaddedSize > PaddedSize) 6867 PaddedSize = CharUnits::fromQuantity(16); 6868 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size."); 6869 6870 CharUnits Padding = (PaddedSize - UnpaddedSize); 6871 6872 llvm::Type *IndexTy = CGF.Int64Ty; 6873 llvm::Value *PaddedSizeV = 6874 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity()); 6875 6876 if (IsVector) { 6877 // Work out the address of a vector argument on the stack. 6878 // Vector arguments are always passed in the high bits of a 6879 // single (8 byte) or double (16 byte) stack slot. 6880 Address OverflowArgAreaPtr = 6881 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr"); 6882 Address OverflowArgArea = 6883 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"), 6884 TyInfo.second); 6885 Address MemAddr = 6886 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr"); 6887 6888 // Update overflow_arg_area_ptr pointer 6889 llvm::Value *NewOverflowArgArea = 6890 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV, 6891 "overflow_arg_area"); 6892 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); 6893 6894 return MemAddr; 6895 } 6896 6897 assert(PaddedSize.getQuantity() == 8); 6898 6899 unsigned MaxRegs, RegCountField, RegSaveIndex; 6900 CharUnits RegPadding; 6901 if (InFPRs) { 6902 MaxRegs = 4; // Maximum of 4 FPR arguments 6903 RegCountField = 1; // __fpr 6904 RegSaveIndex = 16; // save offset for f0 6905 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR 6906 } else { 6907 MaxRegs = 5; // Maximum of 5 GPR arguments 6908 RegCountField = 0; // __gpr 6909 RegSaveIndex = 2; // save offset for r2 6910 RegPadding = Padding; // values are passed in the low bits of a GPR 6911 } 6912 6913 Address RegCountPtr = 6914 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr"); 6915 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count"); 6916 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs); 6917 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV, 6918 "fits_in_regs"); 6919 6920 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 6921 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 6922 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 6923 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 6924 6925 // Emit code to load the value if it was passed in registers. 6926 CGF.EmitBlock(InRegBlock); 6927 6928 // Work out the address of an argument register. 6929 llvm::Value *ScaledRegCount = 6930 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count"); 6931 llvm::Value *RegBase = 6932 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity() 6933 + RegPadding.getQuantity()); 6934 llvm::Value *RegOffset = 6935 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset"); 6936 Address RegSaveAreaPtr = 6937 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr"); 6938 llvm::Value *RegSaveArea = 6939 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area"); 6940 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset, 6941 "raw_reg_addr"), 6942 PaddedSize); 6943 Address RegAddr = 6944 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr"); 6945 6946 // Update the register count 6947 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1); 6948 llvm::Value *NewRegCount = 6949 CGF.Builder.CreateAdd(RegCount, One, "reg_count"); 6950 CGF.Builder.CreateStore(NewRegCount, RegCountPtr); 6951 CGF.EmitBranch(ContBlock); 6952 6953 // Emit code to load the value if it was passed in memory. 6954 CGF.EmitBlock(InMemBlock); 6955 6956 // Work out the address of a stack argument. 6957 Address OverflowArgAreaPtr = 6958 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr"); 6959 Address OverflowArgArea = 6960 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"), 6961 PaddedSize); 6962 Address RawMemAddr = 6963 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr"); 6964 Address MemAddr = 6965 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr"); 6966 6967 // Update overflow_arg_area_ptr pointer 6968 llvm::Value *NewOverflowArgArea = 6969 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV, 6970 "overflow_arg_area"); 6971 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); 6972 CGF.EmitBranch(ContBlock); 6973 6974 // Return the appropriate result. 6975 CGF.EmitBlock(ContBlock); 6976 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, 6977 MemAddr, InMemBlock, "va_arg.addr"); 6978 6979 if (IsIndirect) 6980 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"), 6981 TyInfo.second); 6982 6983 return ResAddr; 6984 } 6985 6986 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const { 6987 if (RetTy->isVoidType()) 6988 return ABIArgInfo::getIgnore(); 6989 if (isVectorArgumentType(RetTy)) 6990 return ABIArgInfo::getDirect(); 6991 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64) 6992 return getNaturalAlignIndirect(RetTy); 6993 return (isPromotableIntegerType(RetTy) ? ABIArgInfo::getExtend(RetTy) 6994 : ABIArgInfo::getDirect()); 6995 } 6996 6997 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const { 6998 // Handle the generic C++ ABI. 6999 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 7000 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 7001 7002 // Integers and enums are extended to full register width. 7003 if (isPromotableIntegerType(Ty)) 7004 return ABIArgInfo::getExtend(Ty); 7005 7006 // Handle vector types and vector-like structure types. Note that 7007 // as opposed to float-like structure types, we do not allow any 7008 // padding for vector-like structures, so verify the sizes match. 7009 uint64_t Size = getContext().getTypeSize(Ty); 7010 QualType SingleElementTy = GetSingleElementType(Ty); 7011 if (isVectorArgumentType(SingleElementTy) && 7012 getContext().getTypeSize(SingleElementTy) == Size) 7013 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy)); 7014 7015 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly. 7016 if (Size != 8 && Size != 16 && Size != 32 && Size != 64) 7017 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7018 7019 // Handle small structures. 7020 if (const RecordType *RT = Ty->getAs<RecordType>()) { 7021 // Structures with flexible arrays have variable length, so really 7022 // fail the size test above. 7023 const RecordDecl *RD = RT->getDecl(); 7024 if (RD->hasFlexibleArrayMember()) 7025 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7026 7027 // The structure is passed as an unextended integer, a float, or a double. 7028 llvm::Type *PassTy; 7029 if (isFPArgumentType(SingleElementTy)) { 7030 assert(Size == 32 || Size == 64); 7031 if (Size == 32) 7032 PassTy = llvm::Type::getFloatTy(getVMContext()); 7033 else 7034 PassTy = llvm::Type::getDoubleTy(getVMContext()); 7035 } else 7036 PassTy = llvm::IntegerType::get(getVMContext(), Size); 7037 return ABIArgInfo::getDirect(PassTy); 7038 } 7039 7040 // Non-structure compounds are passed indirectly. 7041 if (isCompoundType(Ty)) 7042 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7043 7044 return ABIArgInfo::getDirect(nullptr); 7045 } 7046 7047 //===----------------------------------------------------------------------===// 7048 // MSP430 ABI Implementation 7049 //===----------------------------------------------------------------------===// 7050 7051 namespace { 7052 7053 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo { 7054 public: 7055 MSP430TargetCodeGenInfo(CodeGenTypes &CGT) 7056 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {} 7057 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7058 CodeGen::CodeGenModule &M) const override; 7059 }; 7060 7061 } 7062 7063 void MSP430TargetCodeGenInfo::setTargetAttributes( 7064 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 7065 if (GV->isDeclaration()) 7066 return; 7067 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 7068 const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>(); 7069 if (!InterruptAttr) 7070 return; 7071 7072 // Handle 'interrupt' attribute: 7073 llvm::Function *F = cast<llvm::Function>(GV); 7074 7075 // Step 1: Set ISR calling convention. 7076 F->setCallingConv(llvm::CallingConv::MSP430_INTR); 7077 7078 // Step 2: Add attributes goodness. 7079 F->addFnAttr(llvm::Attribute::NoInline); 7080 F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber())); 7081 } 7082 } 7083 7084 //===----------------------------------------------------------------------===// 7085 // MIPS ABI Implementation. This works for both little-endian and 7086 // big-endian variants. 7087 //===----------------------------------------------------------------------===// 7088 7089 namespace { 7090 class MipsABIInfo : public ABIInfo { 7091 bool IsO32; 7092 unsigned MinABIStackAlignInBytes, StackAlignInBytes; 7093 void CoerceToIntArgs(uint64_t TySize, 7094 SmallVectorImpl<llvm::Type *> &ArgList) const; 7095 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const; 7096 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const; 7097 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const; 7098 public: 7099 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) : 7100 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8), 7101 StackAlignInBytes(IsO32 ? 8 : 16) {} 7102 7103 ABIArgInfo classifyReturnType(QualType RetTy) const; 7104 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const; 7105 void computeInfo(CGFunctionInfo &FI) const override; 7106 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7107 QualType Ty) const override; 7108 ABIArgInfo extendType(QualType Ty) const; 7109 }; 7110 7111 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo { 7112 unsigned SizeOfUnwindException; 7113 public: 7114 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32) 7115 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)), 7116 SizeOfUnwindException(IsO32 ? 24 : 32) {} 7117 7118 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 7119 return 29; 7120 } 7121 7122 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7123 CodeGen::CodeGenModule &CGM) const override { 7124 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 7125 if (!FD) return; 7126 llvm::Function *Fn = cast<llvm::Function>(GV); 7127 7128 if (FD->hasAttr<MipsLongCallAttr>()) 7129 Fn->addFnAttr("long-call"); 7130 else if (FD->hasAttr<MipsShortCallAttr>()) 7131 Fn->addFnAttr("short-call"); 7132 7133 // Other attributes do not have a meaning for declarations. 7134 if (GV->isDeclaration()) 7135 return; 7136 7137 if (FD->hasAttr<Mips16Attr>()) { 7138 Fn->addFnAttr("mips16"); 7139 } 7140 else if (FD->hasAttr<NoMips16Attr>()) { 7141 Fn->addFnAttr("nomips16"); 7142 } 7143 7144 if (FD->hasAttr<MicroMipsAttr>()) 7145 Fn->addFnAttr("micromips"); 7146 else if (FD->hasAttr<NoMicroMipsAttr>()) 7147 Fn->addFnAttr("nomicromips"); 7148 7149 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>(); 7150 if (!Attr) 7151 return; 7152 7153 const char *Kind; 7154 switch (Attr->getInterrupt()) { 7155 case MipsInterruptAttr::eic: Kind = "eic"; break; 7156 case MipsInterruptAttr::sw0: Kind = "sw0"; break; 7157 case MipsInterruptAttr::sw1: Kind = "sw1"; break; 7158 case MipsInterruptAttr::hw0: Kind = "hw0"; break; 7159 case MipsInterruptAttr::hw1: Kind = "hw1"; break; 7160 case MipsInterruptAttr::hw2: Kind = "hw2"; break; 7161 case MipsInterruptAttr::hw3: Kind = "hw3"; break; 7162 case MipsInterruptAttr::hw4: Kind = "hw4"; break; 7163 case MipsInterruptAttr::hw5: Kind = "hw5"; break; 7164 } 7165 7166 Fn->addFnAttr("interrupt", Kind); 7167 7168 } 7169 7170 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 7171 llvm::Value *Address) const override; 7172 7173 unsigned getSizeOfUnwindException() const override { 7174 return SizeOfUnwindException; 7175 } 7176 }; 7177 } 7178 7179 void MipsABIInfo::CoerceToIntArgs( 7180 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const { 7181 llvm::IntegerType *IntTy = 7182 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8); 7183 7184 // Add (TySize / MinABIStackAlignInBytes) args of IntTy. 7185 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N) 7186 ArgList.push_back(IntTy); 7187 7188 // If necessary, add one more integer type to ArgList. 7189 unsigned R = TySize % (MinABIStackAlignInBytes * 8); 7190 7191 if (R) 7192 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R)); 7193 } 7194 7195 // In N32/64, an aligned double precision floating point field is passed in 7196 // a register. 7197 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const { 7198 SmallVector<llvm::Type*, 8> ArgList, IntArgList; 7199 7200 if (IsO32) { 7201 CoerceToIntArgs(TySize, ArgList); 7202 return llvm::StructType::get(getVMContext(), ArgList); 7203 } 7204 7205 if (Ty->isComplexType()) 7206 return CGT.ConvertType(Ty); 7207 7208 const RecordType *RT = Ty->getAs<RecordType>(); 7209 7210 // Unions/vectors are passed in integer registers. 7211 if (!RT || !RT->isStructureOrClassType()) { 7212 CoerceToIntArgs(TySize, ArgList); 7213 return llvm::StructType::get(getVMContext(), ArgList); 7214 } 7215 7216 const RecordDecl *RD = RT->getDecl(); 7217 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 7218 assert(!(TySize % 8) && "Size of structure must be multiple of 8."); 7219 7220 uint64_t LastOffset = 0; 7221 unsigned idx = 0; 7222 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64); 7223 7224 // Iterate over fields in the struct/class and check if there are any aligned 7225 // double fields. 7226 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 7227 i != e; ++i, ++idx) { 7228 const QualType Ty = i->getType(); 7229 const BuiltinType *BT = Ty->getAs<BuiltinType>(); 7230 7231 if (!BT || BT->getKind() != BuiltinType::Double) 7232 continue; 7233 7234 uint64_t Offset = Layout.getFieldOffset(idx); 7235 if (Offset % 64) // Ignore doubles that are not aligned. 7236 continue; 7237 7238 // Add ((Offset - LastOffset) / 64) args of type i64. 7239 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j) 7240 ArgList.push_back(I64); 7241 7242 // Add double type. 7243 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext())); 7244 LastOffset = Offset + 64; 7245 } 7246 7247 CoerceToIntArgs(TySize - LastOffset, IntArgList); 7248 ArgList.append(IntArgList.begin(), IntArgList.end()); 7249 7250 return llvm::StructType::get(getVMContext(), ArgList); 7251 } 7252 7253 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset, 7254 uint64_t Offset) const { 7255 if (OrigOffset + MinABIStackAlignInBytes > Offset) 7256 return nullptr; 7257 7258 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8); 7259 } 7260 7261 ABIArgInfo 7262 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const { 7263 Ty = useFirstFieldIfTransparentUnion(Ty); 7264 7265 uint64_t OrigOffset = Offset; 7266 uint64_t TySize = getContext().getTypeSize(Ty); 7267 uint64_t Align = getContext().getTypeAlign(Ty) / 8; 7268 7269 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes), 7270 (uint64_t)StackAlignInBytes); 7271 unsigned CurrOffset = llvm::alignTo(Offset, Align); 7272 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8; 7273 7274 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) { 7275 // Ignore empty aggregates. 7276 if (TySize == 0) 7277 return ABIArgInfo::getIgnore(); 7278 7279 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 7280 Offset = OrigOffset + MinABIStackAlignInBytes; 7281 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 7282 } 7283 7284 // If we have reached here, aggregates are passed directly by coercing to 7285 // another structure type. Padding is inserted if the offset of the 7286 // aggregate is unaligned. 7287 ABIArgInfo ArgInfo = 7288 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0, 7289 getPaddingType(OrigOffset, CurrOffset)); 7290 ArgInfo.setInReg(true); 7291 return ArgInfo; 7292 } 7293 7294 // Treat an enum type as its underlying type. 7295 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 7296 Ty = EnumTy->getDecl()->getIntegerType(); 7297 7298 // All integral types are promoted to the GPR width. 7299 if (Ty->isIntegralOrEnumerationType()) 7300 return extendType(Ty); 7301 7302 return ABIArgInfo::getDirect( 7303 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset)); 7304 } 7305 7306 llvm::Type* 7307 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const { 7308 const RecordType *RT = RetTy->getAs<RecordType>(); 7309 SmallVector<llvm::Type*, 8> RTList; 7310 7311 if (RT && RT->isStructureOrClassType()) { 7312 const RecordDecl *RD = RT->getDecl(); 7313 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 7314 unsigned FieldCnt = Layout.getFieldCount(); 7315 7316 // N32/64 returns struct/classes in floating point registers if the 7317 // following conditions are met: 7318 // 1. The size of the struct/class is no larger than 128-bit. 7319 // 2. The struct/class has one or two fields all of which are floating 7320 // point types. 7321 // 3. The offset of the first field is zero (this follows what gcc does). 7322 // 7323 // Any other composite results are returned in integer registers. 7324 // 7325 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) { 7326 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end(); 7327 for (; b != e; ++b) { 7328 const BuiltinType *BT = b->getType()->getAs<BuiltinType>(); 7329 7330 if (!BT || !BT->isFloatingPoint()) 7331 break; 7332 7333 RTList.push_back(CGT.ConvertType(b->getType())); 7334 } 7335 7336 if (b == e) 7337 return llvm::StructType::get(getVMContext(), RTList, 7338 RD->hasAttr<PackedAttr>()); 7339 7340 RTList.clear(); 7341 } 7342 } 7343 7344 CoerceToIntArgs(Size, RTList); 7345 return llvm::StructType::get(getVMContext(), RTList); 7346 } 7347 7348 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const { 7349 uint64_t Size = getContext().getTypeSize(RetTy); 7350 7351 if (RetTy->isVoidType()) 7352 return ABIArgInfo::getIgnore(); 7353 7354 // O32 doesn't treat zero-sized structs differently from other structs. 7355 // However, N32/N64 ignores zero sized return values. 7356 if (!IsO32 && Size == 0) 7357 return ABIArgInfo::getIgnore(); 7358 7359 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) { 7360 if (Size <= 128) { 7361 if (RetTy->isAnyComplexType()) 7362 return ABIArgInfo::getDirect(); 7363 7364 // O32 returns integer vectors in registers and N32/N64 returns all small 7365 // aggregates in registers. 7366 if (!IsO32 || 7367 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) { 7368 ABIArgInfo ArgInfo = 7369 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size)); 7370 ArgInfo.setInReg(true); 7371 return ArgInfo; 7372 } 7373 } 7374 7375 return getNaturalAlignIndirect(RetTy); 7376 } 7377 7378 // Treat an enum type as its underlying type. 7379 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 7380 RetTy = EnumTy->getDecl()->getIntegerType(); 7381 7382 if (RetTy->isPromotableIntegerType()) 7383 return ABIArgInfo::getExtend(RetTy); 7384 7385 if ((RetTy->isUnsignedIntegerOrEnumerationType() || 7386 RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32) 7387 return ABIArgInfo::getSignExtend(RetTy); 7388 7389 return ABIArgInfo::getDirect(); 7390 } 7391 7392 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const { 7393 ABIArgInfo &RetInfo = FI.getReturnInfo(); 7394 if (!getCXXABI().classifyReturnType(FI)) 7395 RetInfo = classifyReturnType(FI.getReturnType()); 7396 7397 // Check if a pointer to an aggregate is passed as a hidden argument. 7398 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0; 7399 7400 for (auto &I : FI.arguments()) 7401 I.info = classifyArgumentType(I.type, Offset); 7402 } 7403 7404 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7405 QualType OrigTy) const { 7406 QualType Ty = OrigTy; 7407 7408 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64. 7409 // Pointers are also promoted in the same way but this only matters for N32. 7410 unsigned SlotSizeInBits = IsO32 ? 32 : 64; 7411 unsigned PtrWidth = getTarget().getPointerWidth(0); 7412 bool DidPromote = false; 7413 if ((Ty->isIntegerType() && 7414 getContext().getIntWidth(Ty) < SlotSizeInBits) || 7415 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) { 7416 DidPromote = true; 7417 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits, 7418 Ty->isSignedIntegerType()); 7419 } 7420 7421 auto TyInfo = getContext().getTypeInfoInChars(Ty); 7422 7423 // The alignment of things in the argument area is never larger than 7424 // StackAlignInBytes. 7425 TyInfo.second = 7426 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes)); 7427 7428 // MinABIStackAlignInBytes is the size of argument slots on the stack. 7429 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes); 7430 7431 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 7432 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true); 7433 7434 7435 // If there was a promotion, "unpromote" into a temporary. 7436 // TODO: can we just use a pointer into a subset of the original slot? 7437 if (DidPromote) { 7438 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp"); 7439 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr); 7440 7441 // Truncate down to the right width. 7442 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType() 7443 : CGF.IntPtrTy); 7444 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy); 7445 if (OrigTy->isPointerType()) 7446 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType()); 7447 7448 CGF.Builder.CreateStore(V, Temp); 7449 Addr = Temp; 7450 } 7451 7452 return Addr; 7453 } 7454 7455 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const { 7456 int TySize = getContext().getTypeSize(Ty); 7457 7458 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended. 7459 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32) 7460 return ABIArgInfo::getSignExtend(Ty); 7461 7462 return ABIArgInfo::getExtend(Ty); 7463 } 7464 7465 bool 7466 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 7467 llvm::Value *Address) const { 7468 // This information comes from gcc's implementation, which seems to 7469 // as canonical as it gets. 7470 7471 // Everything on MIPS is 4 bytes. Double-precision FP registers 7472 // are aliased to pairs of single-precision FP registers. 7473 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 7474 7475 // 0-31 are the general purpose registers, $0 - $31. 7476 // 32-63 are the floating-point registers, $f0 - $f31. 7477 // 64 and 65 are the multiply/divide registers, $hi and $lo. 7478 // 66 is the (notional, I think) register for signal-handler return. 7479 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65); 7480 7481 // 67-74 are the floating-point status registers, $fcc0 - $fcc7. 7482 // They are one bit wide and ignored here. 7483 7484 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31. 7485 // (coprocessor 1 is the FP unit) 7486 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31. 7487 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31. 7488 // 176-181 are the DSP accumulator registers. 7489 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181); 7490 return false; 7491 } 7492 7493 //===----------------------------------------------------------------------===// 7494 // AVR ABI Implementation. 7495 //===----------------------------------------------------------------------===// 7496 7497 namespace { 7498 class AVRTargetCodeGenInfo : public TargetCodeGenInfo { 7499 public: 7500 AVRTargetCodeGenInfo(CodeGenTypes &CGT) 7501 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) { } 7502 7503 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7504 CodeGen::CodeGenModule &CGM) const override { 7505 if (GV->isDeclaration()) 7506 return; 7507 const auto *FD = dyn_cast_or_null<FunctionDecl>(D); 7508 if (!FD) return; 7509 auto *Fn = cast<llvm::Function>(GV); 7510 7511 if (FD->getAttr<AVRInterruptAttr>()) 7512 Fn->addFnAttr("interrupt"); 7513 7514 if (FD->getAttr<AVRSignalAttr>()) 7515 Fn->addFnAttr("signal"); 7516 } 7517 }; 7518 } 7519 7520 //===----------------------------------------------------------------------===// 7521 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults. 7522 // Currently subclassed only to implement custom OpenCL C function attribute 7523 // handling. 7524 //===----------------------------------------------------------------------===// 7525 7526 namespace { 7527 7528 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo { 7529 public: 7530 TCETargetCodeGenInfo(CodeGenTypes &CGT) 7531 : DefaultTargetCodeGenInfo(CGT) {} 7532 7533 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7534 CodeGen::CodeGenModule &M) const override; 7535 }; 7536 7537 void TCETargetCodeGenInfo::setTargetAttributes( 7538 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 7539 if (GV->isDeclaration()) 7540 return; 7541 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 7542 if (!FD) return; 7543 7544 llvm::Function *F = cast<llvm::Function>(GV); 7545 7546 if (M.getLangOpts().OpenCL) { 7547 if (FD->hasAttr<OpenCLKernelAttr>()) { 7548 // OpenCL C Kernel functions are not subject to inlining 7549 F->addFnAttr(llvm::Attribute::NoInline); 7550 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>(); 7551 if (Attr) { 7552 // Convert the reqd_work_group_size() attributes to metadata. 7553 llvm::LLVMContext &Context = F->getContext(); 7554 llvm::NamedMDNode *OpenCLMetadata = 7555 M.getModule().getOrInsertNamedMetadata( 7556 "opencl.kernel_wg_size_info"); 7557 7558 SmallVector<llvm::Metadata *, 5> Operands; 7559 Operands.push_back(llvm::ConstantAsMetadata::get(F)); 7560 7561 Operands.push_back( 7562 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 7563 M.Int32Ty, llvm::APInt(32, Attr->getXDim())))); 7564 Operands.push_back( 7565 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 7566 M.Int32Ty, llvm::APInt(32, Attr->getYDim())))); 7567 Operands.push_back( 7568 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 7569 M.Int32Ty, llvm::APInt(32, Attr->getZDim())))); 7570 7571 // Add a boolean constant operand for "required" (true) or "hint" 7572 // (false) for implementing the work_group_size_hint attr later. 7573 // Currently always true as the hint is not yet implemented. 7574 Operands.push_back( 7575 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context))); 7576 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands)); 7577 } 7578 } 7579 } 7580 } 7581 7582 } 7583 7584 //===----------------------------------------------------------------------===// 7585 // Hexagon ABI Implementation 7586 //===----------------------------------------------------------------------===// 7587 7588 namespace { 7589 7590 class HexagonABIInfo : public DefaultABIInfo { 7591 public: 7592 HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 7593 7594 private: 7595 ABIArgInfo classifyReturnType(QualType RetTy) const; 7596 ABIArgInfo classifyArgumentType(QualType RetTy) const; 7597 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const; 7598 7599 void computeInfo(CGFunctionInfo &FI) const override; 7600 7601 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7602 QualType Ty) const override; 7603 Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr, 7604 QualType Ty) const; 7605 Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr, 7606 QualType Ty) const; 7607 Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr, 7608 QualType Ty) const; 7609 }; 7610 7611 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo { 7612 public: 7613 HexagonTargetCodeGenInfo(CodeGenTypes &CGT) 7614 : TargetCodeGenInfo(new HexagonABIInfo(CGT)) {} 7615 7616 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 7617 return 29; 7618 } 7619 7620 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7621 CodeGen::CodeGenModule &GCM) const override { 7622 if (GV->isDeclaration()) 7623 return; 7624 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 7625 if (!FD) 7626 return; 7627 } 7628 }; 7629 7630 } // namespace 7631 7632 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const { 7633 unsigned RegsLeft = 6; 7634 if (!getCXXABI().classifyReturnType(FI)) 7635 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7636 for (auto &I : FI.arguments()) 7637 I.info = classifyArgumentType(I.type, &RegsLeft); 7638 } 7639 7640 static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) { 7641 assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits" 7642 " through registers"); 7643 7644 if (*RegsLeft == 0) 7645 return false; 7646 7647 if (Size <= 32) { 7648 (*RegsLeft)--; 7649 return true; 7650 } 7651 7652 if (2 <= (*RegsLeft & (~1U))) { 7653 *RegsLeft = (*RegsLeft & (~1U)) - 2; 7654 return true; 7655 } 7656 7657 // Next available register was r5 but candidate was greater than 32-bits so it 7658 // has to go on the stack. However we still consume r5 7659 if (*RegsLeft == 1) 7660 *RegsLeft = 0; 7661 7662 return false; 7663 } 7664 7665 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty, 7666 unsigned *RegsLeft) const { 7667 if (!isAggregateTypeForABI(Ty)) { 7668 // Treat an enum type as its underlying type. 7669 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 7670 Ty = EnumTy->getDecl()->getIntegerType(); 7671 7672 uint64_t Size = getContext().getTypeSize(Ty); 7673 if (Size <= 64) 7674 HexagonAdjustRegsLeft(Size, RegsLeft); 7675 7676 return Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 7677 : ABIArgInfo::getDirect(); 7678 } 7679 7680 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 7681 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 7682 7683 // Ignore empty records. 7684 if (isEmptyRecord(getContext(), Ty, true)) 7685 return ABIArgInfo::getIgnore(); 7686 7687 uint64_t Size = getContext().getTypeSize(Ty); 7688 unsigned Align = getContext().getTypeAlign(Ty); 7689 7690 if (Size > 64) 7691 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 7692 7693 if (HexagonAdjustRegsLeft(Size, RegsLeft)) 7694 Align = Size <= 32 ? 32 : 64; 7695 if (Size <= Align) { 7696 // Pass in the smallest viable integer type. 7697 if (!llvm::isPowerOf2_64(Size)) 7698 Size = llvm::NextPowerOf2(Size); 7699 return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size)); 7700 } 7701 return DefaultABIInfo::classifyArgumentType(Ty); 7702 } 7703 7704 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const { 7705 if (RetTy->isVoidType()) 7706 return ABIArgInfo::getIgnore(); 7707 7708 const TargetInfo &T = CGT.getTarget(); 7709 uint64_t Size = getContext().getTypeSize(RetTy); 7710 7711 if (RetTy->getAs<VectorType>()) { 7712 // HVX vectors are returned in vector registers or register pairs. 7713 if (T.hasFeature("hvx")) { 7714 assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b")); 7715 uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8; 7716 if (Size == VecSize || Size == 2*VecSize) 7717 return ABIArgInfo::getDirectInReg(); 7718 } 7719 // Large vector types should be returned via memory. 7720 if (Size > 64) 7721 return getNaturalAlignIndirect(RetTy); 7722 } 7723 7724 if (!isAggregateTypeForABI(RetTy)) { 7725 // Treat an enum type as its underlying type. 7726 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 7727 RetTy = EnumTy->getDecl()->getIntegerType(); 7728 7729 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) 7730 : ABIArgInfo::getDirect(); 7731 } 7732 7733 if (isEmptyRecord(getContext(), RetTy, true)) 7734 return ABIArgInfo::getIgnore(); 7735 7736 // Aggregates <= 8 bytes are returned in registers, other aggregates 7737 // are returned indirectly. 7738 if (Size <= 64) { 7739 // Return in the smallest viable integer type. 7740 if (!llvm::isPowerOf2_64(Size)) 7741 Size = llvm::NextPowerOf2(Size); 7742 return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size)); 7743 } 7744 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true); 7745 } 7746 7747 Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF, 7748 Address VAListAddr, 7749 QualType Ty) const { 7750 // Load the overflow area pointer. 7751 Address __overflow_area_pointer_p = 7752 CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p"); 7753 llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad( 7754 __overflow_area_pointer_p, "__overflow_area_pointer"); 7755 7756 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8; 7757 if (Align > 4) { 7758 // Alignment should be a power of 2. 7759 assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!"); 7760 7761 // overflow_arg_area = (overflow_arg_area + align - 1) & -align; 7762 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1); 7763 7764 // Add offset to the current pointer to access the argument. 7765 __overflow_area_pointer = 7766 CGF.Builder.CreateGEP(__overflow_area_pointer, Offset); 7767 llvm::Value *AsInt = 7768 CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty); 7769 7770 // Create a mask which should be "AND"ed 7771 // with (overflow_arg_area + align - 1) 7772 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align); 7773 __overflow_area_pointer = CGF.Builder.CreateIntToPtr( 7774 CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(), 7775 "__overflow_area_pointer.align"); 7776 } 7777 7778 // Get the type of the argument from memory and bitcast 7779 // overflow area pointer to the argument type. 7780 llvm::Type *PTy = CGF.ConvertTypeForMem(Ty); 7781 Address AddrTyped = CGF.Builder.CreateBitCast( 7782 Address(__overflow_area_pointer, CharUnits::fromQuantity(Align)), 7783 llvm::PointerType::getUnqual(PTy)); 7784 7785 // Round up to the minimum stack alignment for varargs which is 4 bytes. 7786 uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4); 7787 7788 __overflow_area_pointer = CGF.Builder.CreateGEP( 7789 __overflow_area_pointer, llvm::ConstantInt::get(CGF.Int32Ty, Offset), 7790 "__overflow_area_pointer.next"); 7791 CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p); 7792 7793 return AddrTyped; 7794 } 7795 7796 Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF, 7797 Address VAListAddr, 7798 QualType Ty) const { 7799 // FIXME: Need to handle alignment 7800 llvm::Type *BP = CGF.Int8PtrTy; 7801 llvm::Type *BPP = CGF.Int8PtrPtrTy; 7802 CGBuilderTy &Builder = CGF.Builder; 7803 Address VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); 7804 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 7805 // Handle address alignment for type alignment > 32 bits 7806 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8; 7807 if (TyAlign > 4) { 7808 assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!"); 7809 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty); 7810 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1)); 7811 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1))); 7812 Addr = Builder.CreateIntToPtr(AddrAsInt, BP); 7813 } 7814 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 7815 Address AddrTyped = Builder.CreateBitCast( 7816 Address(Addr, CharUnits::fromQuantity(TyAlign)), PTy); 7817 7818 uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4); 7819 llvm::Value *NextAddr = Builder.CreateGEP( 7820 Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next"); 7821 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 7822 7823 return AddrTyped; 7824 } 7825 7826 Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF, 7827 Address VAListAddr, 7828 QualType Ty) const { 7829 int ArgSize = CGF.getContext().getTypeSize(Ty) / 8; 7830 7831 if (ArgSize > 8) 7832 return EmitVAArgFromMemory(CGF, VAListAddr, Ty); 7833 7834 // Here we have check if the argument is in register area or 7835 // in overflow area. 7836 // If the saved register area pointer + argsize rounded up to alignment > 7837 // saved register area end pointer, argument is in overflow area. 7838 unsigned RegsLeft = 6; 7839 Ty = CGF.getContext().getCanonicalType(Ty); 7840 (void)classifyArgumentType(Ty, &RegsLeft); 7841 7842 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg"); 7843 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 7844 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack"); 7845 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 7846 7847 // Get rounded size of the argument.GCC does not allow vararg of 7848 // size < 4 bytes. We follow the same logic here. 7849 ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8; 7850 int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8; 7851 7852 // Argument may be in saved register area 7853 CGF.EmitBlock(MaybeRegBlock); 7854 7855 // Load the current saved register area pointer. 7856 Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP( 7857 VAListAddr, 0, "__current_saved_reg_area_pointer_p"); 7858 llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad( 7859 __current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer"); 7860 7861 // Load the saved register area end pointer. 7862 Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP( 7863 VAListAddr, 1, "__saved_reg_area_end_pointer_p"); 7864 llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad( 7865 __saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer"); 7866 7867 // If the size of argument is > 4 bytes, check if the stack 7868 // location is aligned to 8 bytes 7869 if (ArgAlign > 4) { 7870 7871 llvm::Value *__current_saved_reg_area_pointer_int = 7872 CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer, 7873 CGF.Int32Ty); 7874 7875 __current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd( 7876 __current_saved_reg_area_pointer_int, 7877 llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)), 7878 "align_current_saved_reg_area_pointer"); 7879 7880 __current_saved_reg_area_pointer_int = 7881 CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int, 7882 llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign), 7883 "align_current_saved_reg_area_pointer"); 7884 7885 __current_saved_reg_area_pointer = 7886 CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int, 7887 __current_saved_reg_area_pointer->getType(), 7888 "align_current_saved_reg_area_pointer"); 7889 } 7890 7891 llvm::Value *__new_saved_reg_area_pointer = 7892 CGF.Builder.CreateGEP(__current_saved_reg_area_pointer, 7893 llvm::ConstantInt::get(CGF.Int32Ty, ArgSize), 7894 "__new_saved_reg_area_pointer"); 7895 7896 llvm::Value *UsingStack = 0; 7897 UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer, 7898 __saved_reg_area_end_pointer); 7899 7900 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock); 7901 7902 // Argument in saved register area 7903 // Implement the block where argument is in register saved area 7904 CGF.EmitBlock(InRegBlock); 7905 7906 llvm::Type *PTy = CGF.ConvertType(Ty); 7907 llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast( 7908 __current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy)); 7909 7910 CGF.Builder.CreateStore(__new_saved_reg_area_pointer, 7911 __current_saved_reg_area_pointer_p); 7912 7913 CGF.EmitBranch(ContBlock); 7914 7915 // Argument in overflow area 7916 // Implement the block where the argument is in overflow area. 7917 CGF.EmitBlock(OnStackBlock); 7918 7919 // Load the overflow area pointer 7920 Address __overflow_area_pointer_p = 7921 CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p"); 7922 llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad( 7923 __overflow_area_pointer_p, "__overflow_area_pointer"); 7924 7925 // Align the overflow area pointer according to the alignment of the argument 7926 if (ArgAlign > 4) { 7927 llvm::Value *__overflow_area_pointer_int = 7928 CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty); 7929 7930 __overflow_area_pointer_int = 7931 CGF.Builder.CreateAdd(__overflow_area_pointer_int, 7932 llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1), 7933 "align_overflow_area_pointer"); 7934 7935 __overflow_area_pointer_int = 7936 CGF.Builder.CreateAnd(__overflow_area_pointer_int, 7937 llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign), 7938 "align_overflow_area_pointer"); 7939 7940 __overflow_area_pointer = CGF.Builder.CreateIntToPtr( 7941 __overflow_area_pointer_int, __overflow_area_pointer->getType(), 7942 "align_overflow_area_pointer"); 7943 } 7944 7945 // Get the pointer for next argument in overflow area and store it 7946 // to overflow area pointer. 7947 llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP( 7948 __overflow_area_pointer, llvm::ConstantInt::get(CGF.Int32Ty, ArgSize), 7949 "__overflow_area_pointer.next"); 7950 7951 CGF.Builder.CreateStore(__new_overflow_area_pointer, 7952 __overflow_area_pointer_p); 7953 7954 CGF.Builder.CreateStore(__new_overflow_area_pointer, 7955 __current_saved_reg_area_pointer_p); 7956 7957 // Bitcast the overflow area pointer to the type of argument. 7958 llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty); 7959 llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast( 7960 __overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy)); 7961 7962 CGF.EmitBranch(ContBlock); 7963 7964 // Get the correct pointer to load the variable argument 7965 // Implement the ContBlock 7966 CGF.EmitBlock(ContBlock); 7967 7968 llvm::Type *MemPTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); 7969 llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr"); 7970 ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock); 7971 ArgAddr->addIncoming(__overflow_area_p, OnStackBlock); 7972 7973 return Address(ArgAddr, CharUnits::fromQuantity(ArgAlign)); 7974 } 7975 7976 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7977 QualType Ty) const { 7978 7979 if (getTarget().getTriple().isMusl()) 7980 return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty); 7981 7982 return EmitVAArgForHexagon(CGF, VAListAddr, Ty); 7983 } 7984 7985 //===----------------------------------------------------------------------===// 7986 // Lanai ABI Implementation 7987 //===----------------------------------------------------------------------===// 7988 7989 namespace { 7990 class LanaiABIInfo : public DefaultABIInfo { 7991 public: 7992 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 7993 7994 bool shouldUseInReg(QualType Ty, CCState &State) const; 7995 7996 void computeInfo(CGFunctionInfo &FI) const override { 7997 CCState State(FI); 7998 // Lanai uses 4 registers to pass arguments unless the function has the 7999 // regparm attribute set. 8000 if (FI.getHasRegParm()) { 8001 State.FreeRegs = FI.getRegParm(); 8002 } else { 8003 State.FreeRegs = 4; 8004 } 8005 8006 if (!getCXXABI().classifyReturnType(FI)) 8007 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8008 for (auto &I : FI.arguments()) 8009 I.info = classifyArgumentType(I.type, State); 8010 } 8011 8012 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; 8013 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; 8014 }; 8015 } // end anonymous namespace 8016 8017 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const { 8018 unsigned Size = getContext().getTypeSize(Ty); 8019 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U; 8020 8021 if (SizeInRegs == 0) 8022 return false; 8023 8024 if (SizeInRegs > State.FreeRegs) { 8025 State.FreeRegs = 0; 8026 return false; 8027 } 8028 8029 State.FreeRegs -= SizeInRegs; 8030 8031 return true; 8032 } 8033 8034 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal, 8035 CCState &State) const { 8036 if (!ByVal) { 8037 if (State.FreeRegs) { 8038 --State.FreeRegs; // Non-byval indirects just use one pointer. 8039 return getNaturalAlignIndirectInReg(Ty); 8040 } 8041 return getNaturalAlignIndirect(Ty, false); 8042 } 8043 8044 // Compute the byval alignment. 8045 const unsigned MinABIStackAlignInBytes = 4; 8046 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 8047 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true, 8048 /*Realign=*/TypeAlign > 8049 MinABIStackAlignInBytes); 8050 } 8051 8052 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty, 8053 CCState &State) const { 8054 // Check with the C++ ABI first. 8055 const RecordType *RT = Ty->getAs<RecordType>(); 8056 if (RT) { 8057 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 8058 if (RAA == CGCXXABI::RAA_Indirect) { 8059 return getIndirectResult(Ty, /*ByVal=*/false, State); 8060 } else if (RAA == CGCXXABI::RAA_DirectInMemory) { 8061 return getNaturalAlignIndirect(Ty, /*ByRef=*/true); 8062 } 8063 } 8064 8065 if (isAggregateTypeForABI(Ty)) { 8066 // Structures with flexible arrays are always indirect. 8067 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 8068 return getIndirectResult(Ty, /*ByVal=*/true, State); 8069 8070 // Ignore empty structs/unions. 8071 if (isEmptyRecord(getContext(), Ty, true)) 8072 return ABIArgInfo::getIgnore(); 8073 8074 llvm::LLVMContext &LLVMContext = getVMContext(); 8075 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32; 8076 if (SizeInRegs <= State.FreeRegs) { 8077 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 8078 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32); 8079 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 8080 State.FreeRegs -= SizeInRegs; 8081 return ABIArgInfo::getDirectInReg(Result); 8082 } else { 8083 State.FreeRegs = 0; 8084 } 8085 return getIndirectResult(Ty, true, State); 8086 } 8087 8088 // Treat an enum type as its underlying type. 8089 if (const auto *EnumTy = Ty->getAs<EnumType>()) 8090 Ty = EnumTy->getDecl()->getIntegerType(); 8091 8092 bool InReg = shouldUseInReg(Ty, State); 8093 if (Ty->isPromotableIntegerType()) { 8094 if (InReg) 8095 return ABIArgInfo::getDirectInReg(); 8096 return ABIArgInfo::getExtend(Ty); 8097 } 8098 if (InReg) 8099 return ABIArgInfo::getDirectInReg(); 8100 return ABIArgInfo::getDirect(); 8101 } 8102 8103 namespace { 8104 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo { 8105 public: 8106 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 8107 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {} 8108 }; 8109 } 8110 8111 //===----------------------------------------------------------------------===// 8112 // AMDGPU ABI Implementation 8113 //===----------------------------------------------------------------------===// 8114 8115 namespace { 8116 8117 class AMDGPUABIInfo final : public DefaultABIInfo { 8118 private: 8119 static const unsigned MaxNumRegsForArgsRet = 16; 8120 8121 unsigned numRegsForType(QualType Ty) const; 8122 8123 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 8124 bool isHomogeneousAggregateSmallEnough(const Type *Base, 8125 uint64_t Members) const override; 8126 8127 // Coerce HIP pointer arguments from generic pointers to global ones. 8128 llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS, 8129 unsigned ToAS) const { 8130 // Structure types. 8131 if (auto STy = dyn_cast<llvm::StructType>(Ty)) { 8132 SmallVector<llvm::Type *, 8> EltTys; 8133 bool Changed = false; 8134 for (auto T : STy->elements()) { 8135 auto NT = coerceKernelArgumentType(T, FromAS, ToAS); 8136 EltTys.push_back(NT); 8137 Changed |= (NT != T); 8138 } 8139 // Skip if there is no change in element types. 8140 if (!Changed) 8141 return STy; 8142 if (STy->hasName()) 8143 return llvm::StructType::create( 8144 EltTys, (STy->getName() + ".coerce").str(), STy->isPacked()); 8145 return llvm::StructType::get(getVMContext(), EltTys, STy->isPacked()); 8146 } 8147 // Arrary types. 8148 if (auto ATy = dyn_cast<llvm::ArrayType>(Ty)) { 8149 auto T = ATy->getElementType(); 8150 auto NT = coerceKernelArgumentType(T, FromAS, ToAS); 8151 // Skip if there is no change in that element type. 8152 if (NT == T) 8153 return ATy; 8154 return llvm::ArrayType::get(NT, ATy->getNumElements()); 8155 } 8156 // Single value types. 8157 if (Ty->isPointerTy() && Ty->getPointerAddressSpace() == FromAS) 8158 return llvm::PointerType::get( 8159 cast<llvm::PointerType>(Ty)->getElementType(), ToAS); 8160 return Ty; 8161 } 8162 8163 public: 8164 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) : 8165 DefaultABIInfo(CGT) {} 8166 8167 ABIArgInfo classifyReturnType(QualType RetTy) const; 8168 ABIArgInfo classifyKernelArgumentType(QualType Ty) const; 8169 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const; 8170 8171 void computeInfo(CGFunctionInfo &FI) const override; 8172 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8173 QualType Ty) const override; 8174 }; 8175 8176 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 8177 return true; 8178 } 8179 8180 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough( 8181 const Type *Base, uint64_t Members) const { 8182 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32; 8183 8184 // Homogeneous Aggregates may occupy at most 16 registers. 8185 return Members * NumRegs <= MaxNumRegsForArgsRet; 8186 } 8187 8188 /// Estimate number of registers the type will use when passed in registers. 8189 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const { 8190 unsigned NumRegs = 0; 8191 8192 if (const VectorType *VT = Ty->getAs<VectorType>()) { 8193 // Compute from the number of elements. The reported size is based on the 8194 // in-memory size, which includes the padding 4th element for 3-vectors. 8195 QualType EltTy = VT->getElementType(); 8196 unsigned EltSize = getContext().getTypeSize(EltTy); 8197 8198 // 16-bit element vectors should be passed as packed. 8199 if (EltSize == 16) 8200 return (VT->getNumElements() + 1) / 2; 8201 8202 unsigned EltNumRegs = (EltSize + 31) / 32; 8203 return EltNumRegs * VT->getNumElements(); 8204 } 8205 8206 if (const RecordType *RT = Ty->getAs<RecordType>()) { 8207 const RecordDecl *RD = RT->getDecl(); 8208 assert(!RD->hasFlexibleArrayMember()); 8209 8210 for (const FieldDecl *Field : RD->fields()) { 8211 QualType FieldTy = Field->getType(); 8212 NumRegs += numRegsForType(FieldTy); 8213 } 8214 8215 return NumRegs; 8216 } 8217 8218 return (getContext().getTypeSize(Ty) + 31) / 32; 8219 } 8220 8221 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const { 8222 llvm::CallingConv::ID CC = FI.getCallingConvention(); 8223 8224 if (!getCXXABI().classifyReturnType(FI)) 8225 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8226 8227 unsigned NumRegsLeft = MaxNumRegsForArgsRet; 8228 for (auto &Arg : FI.arguments()) { 8229 if (CC == llvm::CallingConv::AMDGPU_KERNEL) { 8230 Arg.info = classifyKernelArgumentType(Arg.type); 8231 } else { 8232 Arg.info = classifyArgumentType(Arg.type, NumRegsLeft); 8233 } 8234 } 8235 } 8236 8237 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8238 QualType Ty) const { 8239 llvm_unreachable("AMDGPU does not support varargs"); 8240 } 8241 8242 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const { 8243 if (isAggregateTypeForABI(RetTy)) { 8244 // Records with non-trivial destructors/copy-constructors should not be 8245 // returned by value. 8246 if (!getRecordArgABI(RetTy, getCXXABI())) { 8247 // Ignore empty structs/unions. 8248 if (isEmptyRecord(getContext(), RetTy, true)) 8249 return ABIArgInfo::getIgnore(); 8250 8251 // Lower single-element structs to just return a regular value. 8252 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 8253 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 8254 8255 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 8256 const RecordDecl *RD = RT->getDecl(); 8257 if (RD->hasFlexibleArrayMember()) 8258 return DefaultABIInfo::classifyReturnType(RetTy); 8259 } 8260 8261 // Pack aggregates <= 4 bytes into single VGPR or pair. 8262 uint64_t Size = getContext().getTypeSize(RetTy); 8263 if (Size <= 16) 8264 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 8265 8266 if (Size <= 32) 8267 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 8268 8269 if (Size <= 64) { 8270 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext()); 8271 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2)); 8272 } 8273 8274 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet) 8275 return ABIArgInfo::getDirect(); 8276 } 8277 } 8278 8279 // Otherwise just do the default thing. 8280 return DefaultABIInfo::classifyReturnType(RetTy); 8281 } 8282 8283 /// For kernels all parameters are really passed in a special buffer. It doesn't 8284 /// make sense to pass anything byval, so everything must be direct. 8285 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const { 8286 Ty = useFirstFieldIfTransparentUnion(Ty); 8287 8288 // TODO: Can we omit empty structs? 8289 8290 llvm::Type *LTy = nullptr; 8291 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 8292 LTy = CGT.ConvertType(QualType(SeltTy, 0)); 8293 8294 if (getContext().getLangOpts().HIP) { 8295 if (!LTy) 8296 LTy = CGT.ConvertType(Ty); 8297 LTy = coerceKernelArgumentType( 8298 LTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default), 8299 /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device)); 8300 } 8301 8302 // If we set CanBeFlattened to true, CodeGen will expand the struct to its 8303 // individual elements, which confuses the Clover OpenCL backend; therefore we 8304 // have to set it to false here. Other args of getDirect() are just defaults. 8305 return ABIArgInfo::getDirect(LTy, 0, nullptr, false); 8306 } 8307 8308 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty, 8309 unsigned &NumRegsLeft) const { 8310 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow"); 8311 8312 Ty = useFirstFieldIfTransparentUnion(Ty); 8313 8314 if (isAggregateTypeForABI(Ty)) { 8315 // Records with non-trivial destructors/copy-constructors should not be 8316 // passed by value. 8317 if (auto RAA = getRecordArgABI(Ty, getCXXABI())) 8318 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 8319 8320 // Ignore empty structs/unions. 8321 if (isEmptyRecord(getContext(), Ty, true)) 8322 return ABIArgInfo::getIgnore(); 8323 8324 // Lower single-element structs to just pass a regular value. TODO: We 8325 // could do reasonable-size multiple-element structs too, using getExpand(), 8326 // though watch out for things like bitfields. 8327 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 8328 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 8329 8330 if (const RecordType *RT = Ty->getAs<RecordType>()) { 8331 const RecordDecl *RD = RT->getDecl(); 8332 if (RD->hasFlexibleArrayMember()) 8333 return DefaultABIInfo::classifyArgumentType(Ty); 8334 } 8335 8336 // Pack aggregates <= 8 bytes into single VGPR or pair. 8337 uint64_t Size = getContext().getTypeSize(Ty); 8338 if (Size <= 64) { 8339 unsigned NumRegs = (Size + 31) / 32; 8340 NumRegsLeft -= std::min(NumRegsLeft, NumRegs); 8341 8342 if (Size <= 16) 8343 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 8344 8345 if (Size <= 32) 8346 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 8347 8348 // XXX: Should this be i64 instead, and should the limit increase? 8349 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext()); 8350 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2)); 8351 } 8352 8353 if (NumRegsLeft > 0) { 8354 unsigned NumRegs = numRegsForType(Ty); 8355 if (NumRegsLeft >= NumRegs) { 8356 NumRegsLeft -= NumRegs; 8357 return ABIArgInfo::getDirect(); 8358 } 8359 } 8360 } 8361 8362 // Otherwise just do the default thing. 8363 ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty); 8364 if (!ArgInfo.isIndirect()) { 8365 unsigned NumRegs = numRegsForType(Ty); 8366 NumRegsLeft -= std::min(NumRegs, NumRegsLeft); 8367 } 8368 8369 return ArgInfo; 8370 } 8371 8372 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo { 8373 public: 8374 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT) 8375 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {} 8376 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8377 CodeGen::CodeGenModule &M) const override; 8378 unsigned getOpenCLKernelCallingConv() const override; 8379 8380 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM, 8381 llvm::PointerType *T, QualType QT) const override; 8382 8383 LangAS getASTAllocaAddressSpace() const override { 8384 return getLangASFromTargetAS( 8385 getABIInfo().getDataLayout().getAllocaAddrSpace()); 8386 } 8387 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, 8388 const VarDecl *D) const override; 8389 llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts, 8390 SyncScope Scope, 8391 llvm::AtomicOrdering Ordering, 8392 llvm::LLVMContext &Ctx) const override; 8393 llvm::Function * 8394 createEnqueuedBlockKernel(CodeGenFunction &CGF, 8395 llvm::Function *BlockInvokeFunc, 8396 llvm::Value *BlockLiteral) const override; 8397 bool shouldEmitStaticExternCAliases() const override; 8398 void setCUDAKernelCallingConvention(const FunctionType *&FT) const override; 8399 }; 8400 } 8401 8402 static bool requiresAMDGPUProtectedVisibility(const Decl *D, 8403 llvm::GlobalValue *GV) { 8404 if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility) 8405 return false; 8406 8407 return D->hasAttr<OpenCLKernelAttr>() || 8408 (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) || 8409 (isa<VarDecl>(D) && 8410 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || 8411 cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() || 8412 cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType())); 8413 } 8414 8415 void AMDGPUTargetCodeGenInfo::setTargetAttributes( 8416 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 8417 if (requiresAMDGPUProtectedVisibility(D, GV)) { 8418 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 8419 GV->setDSOLocal(true); 8420 } 8421 8422 if (GV->isDeclaration()) 8423 return; 8424 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 8425 if (!FD) 8426 return; 8427 8428 llvm::Function *F = cast<llvm::Function>(GV); 8429 8430 const auto *ReqdWGS = M.getLangOpts().OpenCL ? 8431 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr; 8432 8433 8434 const bool IsOpenCLKernel = M.getLangOpts().OpenCL && 8435 FD->hasAttr<OpenCLKernelAttr>(); 8436 const bool IsHIPKernel = M.getLangOpts().HIP && 8437 FD->hasAttr<CUDAGlobalAttr>(); 8438 if ((IsOpenCLKernel || IsHIPKernel) && 8439 (M.getTriple().getOS() == llvm::Triple::AMDHSA)) 8440 F->addFnAttr("amdgpu-implicitarg-num-bytes", "56"); 8441 8442 if (IsHIPKernel) 8443 F->addFnAttr("uniform-work-group-size", "true"); 8444 8445 8446 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>(); 8447 if (ReqdWGS || FlatWGS) { 8448 unsigned Min = 0; 8449 unsigned Max = 0; 8450 if (FlatWGS) { 8451 Min = FlatWGS->getMin() 8452 ->EvaluateKnownConstInt(M.getContext()) 8453 .getExtValue(); 8454 Max = FlatWGS->getMax() 8455 ->EvaluateKnownConstInt(M.getContext()) 8456 .getExtValue(); 8457 } 8458 if (ReqdWGS && Min == 0 && Max == 0) 8459 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim(); 8460 8461 if (Min != 0) { 8462 assert(Min <= Max && "Min must be less than or equal Max"); 8463 8464 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max); 8465 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal); 8466 } else 8467 assert(Max == 0 && "Max must be zero"); 8468 } else if (IsOpenCLKernel || IsHIPKernel) { 8469 // By default, restrict the maximum size to a value specified by 8470 // --gpu-max-threads-per-block=n or its default value. 8471 std::string AttrVal = 8472 std::string("1,") + llvm::utostr(M.getLangOpts().GPUMaxThreadsPerBlock); 8473 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal); 8474 } 8475 8476 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) { 8477 unsigned Min = 8478 Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue(); 8479 unsigned Max = Attr->getMax() ? Attr->getMax() 8480 ->EvaluateKnownConstInt(M.getContext()) 8481 .getExtValue() 8482 : 0; 8483 8484 if (Min != 0) { 8485 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max"); 8486 8487 std::string AttrVal = llvm::utostr(Min); 8488 if (Max != 0) 8489 AttrVal = AttrVal + "," + llvm::utostr(Max); 8490 F->addFnAttr("amdgpu-waves-per-eu", AttrVal); 8491 } else 8492 assert(Max == 0 && "Max must be zero"); 8493 } 8494 8495 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) { 8496 unsigned NumSGPR = Attr->getNumSGPR(); 8497 8498 if (NumSGPR != 0) 8499 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR)); 8500 } 8501 8502 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) { 8503 uint32_t NumVGPR = Attr->getNumVGPR(); 8504 8505 if (NumVGPR != 0) 8506 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR)); 8507 } 8508 } 8509 8510 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const { 8511 return llvm::CallingConv::AMDGPU_KERNEL; 8512 } 8513 8514 // Currently LLVM assumes null pointers always have value 0, 8515 // which results in incorrectly transformed IR. Therefore, instead of 8516 // emitting null pointers in private and local address spaces, a null 8517 // pointer in generic address space is emitted which is casted to a 8518 // pointer in local or private address space. 8519 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer( 8520 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT, 8521 QualType QT) const { 8522 if (CGM.getContext().getTargetNullPointerValue(QT) == 0) 8523 return llvm::ConstantPointerNull::get(PT); 8524 8525 auto &Ctx = CGM.getContext(); 8526 auto NPT = llvm::PointerType::get(PT->getElementType(), 8527 Ctx.getTargetAddressSpace(LangAS::opencl_generic)); 8528 return llvm::ConstantExpr::getAddrSpaceCast( 8529 llvm::ConstantPointerNull::get(NPT), PT); 8530 } 8531 8532 LangAS 8533 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM, 8534 const VarDecl *D) const { 8535 assert(!CGM.getLangOpts().OpenCL && 8536 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && 8537 "Address space agnostic languages only"); 8538 LangAS DefaultGlobalAS = getLangASFromTargetAS( 8539 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global)); 8540 if (!D) 8541 return DefaultGlobalAS; 8542 8543 LangAS AddrSpace = D->getType().getAddressSpace(); 8544 assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace)); 8545 if (AddrSpace != LangAS::Default) 8546 return AddrSpace; 8547 8548 if (CGM.isTypeConstant(D->getType(), false)) { 8549 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace()) 8550 return ConstAS.getValue(); 8551 } 8552 return DefaultGlobalAS; 8553 } 8554 8555 llvm::SyncScope::ID 8556 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts, 8557 SyncScope Scope, 8558 llvm::AtomicOrdering Ordering, 8559 llvm::LLVMContext &Ctx) const { 8560 std::string Name; 8561 switch (Scope) { 8562 case SyncScope::OpenCLWorkGroup: 8563 Name = "workgroup"; 8564 break; 8565 case SyncScope::OpenCLDevice: 8566 Name = "agent"; 8567 break; 8568 case SyncScope::OpenCLAllSVMDevices: 8569 Name = ""; 8570 break; 8571 case SyncScope::OpenCLSubGroup: 8572 Name = "wavefront"; 8573 } 8574 8575 if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) { 8576 if (!Name.empty()) 8577 Name = Twine(Twine(Name) + Twine("-")).str(); 8578 8579 Name = Twine(Twine(Name) + Twine("one-as")).str(); 8580 } 8581 8582 return Ctx.getOrInsertSyncScopeID(Name); 8583 } 8584 8585 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const { 8586 return false; 8587 } 8588 8589 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention( 8590 const FunctionType *&FT) const { 8591 FT = getABIInfo().getContext().adjustFunctionType( 8592 FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel)); 8593 } 8594 8595 //===----------------------------------------------------------------------===// 8596 // SPARC v8 ABI Implementation. 8597 // Based on the SPARC Compliance Definition version 2.4.1. 8598 // 8599 // Ensures that complex values are passed in registers. 8600 // 8601 namespace { 8602 class SparcV8ABIInfo : public DefaultABIInfo { 8603 public: 8604 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 8605 8606 private: 8607 ABIArgInfo classifyReturnType(QualType RetTy) const; 8608 void computeInfo(CGFunctionInfo &FI) const override; 8609 }; 8610 } // end anonymous namespace 8611 8612 8613 ABIArgInfo 8614 SparcV8ABIInfo::classifyReturnType(QualType Ty) const { 8615 if (Ty->isAnyComplexType()) { 8616 return ABIArgInfo::getDirect(); 8617 } 8618 else { 8619 return DefaultABIInfo::classifyReturnType(Ty); 8620 } 8621 } 8622 8623 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const { 8624 8625 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8626 for (auto &Arg : FI.arguments()) 8627 Arg.info = classifyArgumentType(Arg.type); 8628 } 8629 8630 namespace { 8631 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo { 8632 public: 8633 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT) 8634 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {} 8635 }; 8636 } // end anonymous namespace 8637 8638 //===----------------------------------------------------------------------===// 8639 // SPARC v9 ABI Implementation. 8640 // Based on the SPARC Compliance Definition version 2.4.1. 8641 // 8642 // Function arguments a mapped to a nominal "parameter array" and promoted to 8643 // registers depending on their type. Each argument occupies 8 or 16 bytes in 8644 // the array, structs larger than 16 bytes are passed indirectly. 8645 // 8646 // One case requires special care: 8647 // 8648 // struct mixed { 8649 // int i; 8650 // float f; 8651 // }; 8652 // 8653 // When a struct mixed is passed by value, it only occupies 8 bytes in the 8654 // parameter array, but the int is passed in an integer register, and the float 8655 // is passed in a floating point register. This is represented as two arguments 8656 // with the LLVM IR inreg attribute: 8657 // 8658 // declare void f(i32 inreg %i, float inreg %f) 8659 // 8660 // The code generator will only allocate 4 bytes from the parameter array for 8661 // the inreg arguments. All other arguments are allocated a multiple of 8 8662 // bytes. 8663 // 8664 namespace { 8665 class SparcV9ABIInfo : public ABIInfo { 8666 public: 8667 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 8668 8669 private: 8670 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const; 8671 void computeInfo(CGFunctionInfo &FI) const override; 8672 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8673 QualType Ty) const override; 8674 8675 // Coercion type builder for structs passed in registers. The coercion type 8676 // serves two purposes: 8677 // 8678 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned' 8679 // in registers. 8680 // 2. Expose aligned floating point elements as first-level elements, so the 8681 // code generator knows to pass them in floating point registers. 8682 // 8683 // We also compute the InReg flag which indicates that the struct contains 8684 // aligned 32-bit floats. 8685 // 8686 struct CoerceBuilder { 8687 llvm::LLVMContext &Context; 8688 const llvm::DataLayout &DL; 8689 SmallVector<llvm::Type*, 8> Elems; 8690 uint64_t Size; 8691 bool InReg; 8692 8693 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl) 8694 : Context(c), DL(dl), Size(0), InReg(false) {} 8695 8696 // Pad Elems with integers until Size is ToSize. 8697 void pad(uint64_t ToSize) { 8698 assert(ToSize >= Size && "Cannot remove elements"); 8699 if (ToSize == Size) 8700 return; 8701 8702 // Finish the current 64-bit word. 8703 uint64_t Aligned = llvm::alignTo(Size, 64); 8704 if (Aligned > Size && Aligned <= ToSize) { 8705 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size)); 8706 Size = Aligned; 8707 } 8708 8709 // Add whole 64-bit words. 8710 while (Size + 64 <= ToSize) { 8711 Elems.push_back(llvm::Type::getInt64Ty(Context)); 8712 Size += 64; 8713 } 8714 8715 // Final in-word padding. 8716 if (Size < ToSize) { 8717 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size)); 8718 Size = ToSize; 8719 } 8720 } 8721 8722 // Add a floating point element at Offset. 8723 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) { 8724 // Unaligned floats are treated as integers. 8725 if (Offset % Bits) 8726 return; 8727 // The InReg flag is only required if there are any floats < 64 bits. 8728 if (Bits < 64) 8729 InReg = true; 8730 pad(Offset); 8731 Elems.push_back(Ty); 8732 Size = Offset + Bits; 8733 } 8734 8735 // Add a struct type to the coercion type, starting at Offset (in bits). 8736 void addStruct(uint64_t Offset, llvm::StructType *StrTy) { 8737 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy); 8738 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) { 8739 llvm::Type *ElemTy = StrTy->getElementType(i); 8740 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i); 8741 switch (ElemTy->getTypeID()) { 8742 case llvm::Type::StructTyID: 8743 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy)); 8744 break; 8745 case llvm::Type::FloatTyID: 8746 addFloat(ElemOffset, ElemTy, 32); 8747 break; 8748 case llvm::Type::DoubleTyID: 8749 addFloat(ElemOffset, ElemTy, 64); 8750 break; 8751 case llvm::Type::FP128TyID: 8752 addFloat(ElemOffset, ElemTy, 128); 8753 break; 8754 case llvm::Type::PointerTyID: 8755 if (ElemOffset % 64 == 0) { 8756 pad(ElemOffset); 8757 Elems.push_back(ElemTy); 8758 Size += 64; 8759 } 8760 break; 8761 default: 8762 break; 8763 } 8764 } 8765 } 8766 8767 // Check if Ty is a usable substitute for the coercion type. 8768 bool isUsableType(llvm::StructType *Ty) const { 8769 return llvm::makeArrayRef(Elems) == Ty->elements(); 8770 } 8771 8772 // Get the coercion type as a literal struct type. 8773 llvm::Type *getType() const { 8774 if (Elems.size() == 1) 8775 return Elems.front(); 8776 else 8777 return llvm::StructType::get(Context, Elems); 8778 } 8779 }; 8780 }; 8781 } // end anonymous namespace 8782 8783 ABIArgInfo 8784 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const { 8785 if (Ty->isVoidType()) 8786 return ABIArgInfo::getIgnore(); 8787 8788 uint64_t Size = getContext().getTypeSize(Ty); 8789 8790 // Anything too big to fit in registers is passed with an explicit indirect 8791 // pointer / sret pointer. 8792 if (Size > SizeLimit) 8793 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 8794 8795 // Treat an enum type as its underlying type. 8796 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 8797 Ty = EnumTy->getDecl()->getIntegerType(); 8798 8799 // Integer types smaller than a register are extended. 8800 if (Size < 64 && Ty->isIntegerType()) 8801 return ABIArgInfo::getExtend(Ty); 8802 8803 // Other non-aggregates go in registers. 8804 if (!isAggregateTypeForABI(Ty)) 8805 return ABIArgInfo::getDirect(); 8806 8807 // If a C++ object has either a non-trivial copy constructor or a non-trivial 8808 // destructor, it is passed with an explicit indirect pointer / sret pointer. 8809 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 8810 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 8811 8812 // This is a small aggregate type that should be passed in registers. 8813 // Build a coercion type from the LLVM struct type. 8814 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty)); 8815 if (!StrTy) 8816 return ABIArgInfo::getDirect(); 8817 8818 CoerceBuilder CB(getVMContext(), getDataLayout()); 8819 CB.addStruct(0, StrTy); 8820 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64)); 8821 8822 // Try to use the original type for coercion. 8823 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType(); 8824 8825 if (CB.InReg) 8826 return ABIArgInfo::getDirectInReg(CoerceTy); 8827 else 8828 return ABIArgInfo::getDirect(CoerceTy); 8829 } 8830 8831 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8832 QualType Ty) const { 8833 ABIArgInfo AI = classifyType(Ty, 16 * 8); 8834 llvm::Type *ArgTy = CGT.ConvertType(Ty); 8835 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 8836 AI.setCoerceToType(ArgTy); 8837 8838 CharUnits SlotSize = CharUnits::fromQuantity(8); 8839 8840 CGBuilderTy &Builder = CGF.Builder; 8841 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize); 8842 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 8843 8844 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 8845 8846 Address ArgAddr = Address::invalid(); 8847 CharUnits Stride; 8848 switch (AI.getKind()) { 8849 case ABIArgInfo::Expand: 8850 case ABIArgInfo::CoerceAndExpand: 8851 case ABIArgInfo::InAlloca: 8852 llvm_unreachable("Unsupported ABI kind for va_arg"); 8853 8854 case ABIArgInfo::Extend: { 8855 Stride = SlotSize; 8856 CharUnits Offset = SlotSize - TypeInfo.first; 8857 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend"); 8858 break; 8859 } 8860 8861 case ABIArgInfo::Direct: { 8862 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType()); 8863 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize); 8864 ArgAddr = Addr; 8865 break; 8866 } 8867 8868 case ABIArgInfo::Indirect: 8869 Stride = SlotSize; 8870 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect"); 8871 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"), 8872 TypeInfo.second); 8873 break; 8874 8875 case ABIArgInfo::Ignore: 8876 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second); 8877 } 8878 8879 // Update VAList. 8880 Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next"); 8881 Builder.CreateStore(NextPtr.getPointer(), VAListAddr); 8882 8883 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr"); 8884 } 8885 8886 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const { 8887 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8); 8888 for (auto &I : FI.arguments()) 8889 I.info = classifyType(I.type, 16 * 8); 8890 } 8891 8892 namespace { 8893 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo { 8894 public: 8895 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT) 8896 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {} 8897 8898 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 8899 return 14; 8900 } 8901 8902 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 8903 llvm::Value *Address) const override; 8904 }; 8905 } // end anonymous namespace 8906 8907 bool 8908 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 8909 llvm::Value *Address) const { 8910 // This is calculated from the LLVM and GCC tables and verified 8911 // against gcc output. AFAIK all ABIs use the same encoding. 8912 8913 CodeGen::CGBuilderTy &Builder = CGF.Builder; 8914 8915 llvm::IntegerType *i8 = CGF.Int8Ty; 8916 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 8917 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 8918 8919 // 0-31: the 8-byte general-purpose registers 8920 AssignToArrayRange(Builder, Address, Eight8, 0, 31); 8921 8922 // 32-63: f0-31, the 4-byte floating-point registers 8923 AssignToArrayRange(Builder, Address, Four8, 32, 63); 8924 8925 // Y = 64 8926 // PSR = 65 8927 // WIM = 66 8928 // TBR = 67 8929 // PC = 68 8930 // NPC = 69 8931 // FSR = 70 8932 // CSR = 71 8933 AssignToArrayRange(Builder, Address, Eight8, 64, 71); 8934 8935 // 72-87: d0-15, the 8-byte floating-point registers 8936 AssignToArrayRange(Builder, Address, Eight8, 72, 87); 8937 8938 return false; 8939 } 8940 8941 // ARC ABI implementation. 8942 namespace { 8943 8944 class ARCABIInfo : public DefaultABIInfo { 8945 public: 8946 using DefaultABIInfo::DefaultABIInfo; 8947 8948 private: 8949 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8950 QualType Ty) const override; 8951 8952 void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const { 8953 if (!State.FreeRegs) 8954 return; 8955 if (Info.isIndirect() && Info.getInReg()) 8956 State.FreeRegs--; 8957 else if (Info.isDirect() && Info.getInReg()) { 8958 unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32; 8959 if (sz < State.FreeRegs) 8960 State.FreeRegs -= sz; 8961 else 8962 State.FreeRegs = 0; 8963 } 8964 } 8965 8966 void computeInfo(CGFunctionInfo &FI) const override { 8967 CCState State(FI); 8968 // ARC uses 8 registers to pass arguments. 8969 State.FreeRegs = 8; 8970 8971 if (!getCXXABI().classifyReturnType(FI)) 8972 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8973 updateState(FI.getReturnInfo(), FI.getReturnType(), State); 8974 for (auto &I : FI.arguments()) { 8975 I.info = classifyArgumentType(I.type, State.FreeRegs); 8976 updateState(I.info, I.type, State); 8977 } 8978 } 8979 8980 ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const; 8981 ABIArgInfo getIndirectByValue(QualType Ty) const; 8982 ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const; 8983 ABIArgInfo classifyReturnType(QualType RetTy) const; 8984 }; 8985 8986 class ARCTargetCodeGenInfo : public TargetCodeGenInfo { 8987 public: 8988 ARCTargetCodeGenInfo(CodeGenTypes &CGT) 8989 : TargetCodeGenInfo(new ARCABIInfo(CGT)) {} 8990 }; 8991 8992 8993 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const { 8994 return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) : 8995 getNaturalAlignIndirect(Ty, false); 8996 } 8997 8998 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const { 8999 // Compute the byval alignment. 9000 const unsigned MinABIStackAlignInBytes = 4; 9001 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 9002 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true, 9003 TypeAlign > MinABIStackAlignInBytes); 9004 } 9005 9006 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9007 QualType Ty) const { 9008 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 9009 getContext().getTypeInfoInChars(Ty), 9010 CharUnits::fromQuantity(4), true); 9011 } 9012 9013 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty, 9014 uint8_t FreeRegs) const { 9015 // Handle the generic C++ ABI. 9016 const RecordType *RT = Ty->getAs<RecordType>(); 9017 if (RT) { 9018 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 9019 if (RAA == CGCXXABI::RAA_Indirect) 9020 return getIndirectByRef(Ty, FreeRegs > 0); 9021 9022 if (RAA == CGCXXABI::RAA_DirectInMemory) 9023 return getIndirectByValue(Ty); 9024 } 9025 9026 // Treat an enum type as its underlying type. 9027 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 9028 Ty = EnumTy->getDecl()->getIntegerType(); 9029 9030 auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32; 9031 9032 if (isAggregateTypeForABI(Ty)) { 9033 // Structures with flexible arrays are always indirect. 9034 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 9035 return getIndirectByValue(Ty); 9036 9037 // Ignore empty structs/unions. 9038 if (isEmptyRecord(getContext(), Ty, true)) 9039 return ABIArgInfo::getIgnore(); 9040 9041 llvm::LLVMContext &LLVMContext = getVMContext(); 9042 9043 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 9044 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32); 9045 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 9046 9047 return FreeRegs >= SizeInRegs ? 9048 ABIArgInfo::getDirectInReg(Result) : 9049 ABIArgInfo::getDirect(Result, 0, nullptr, false); 9050 } 9051 9052 return Ty->isPromotableIntegerType() ? 9053 (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty) : 9054 ABIArgInfo::getExtend(Ty)) : 9055 (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg() : 9056 ABIArgInfo::getDirect()); 9057 } 9058 9059 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const { 9060 if (RetTy->isAnyComplexType()) 9061 return ABIArgInfo::getDirectInReg(); 9062 9063 // Arguments of size > 4 registers are indirect. 9064 auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32; 9065 if (RetSize > 4) 9066 return getIndirectByRef(RetTy, /*HasFreeRegs*/ true); 9067 9068 return DefaultABIInfo::classifyReturnType(RetTy); 9069 } 9070 9071 } // End anonymous namespace. 9072 9073 //===----------------------------------------------------------------------===// 9074 // XCore ABI Implementation 9075 //===----------------------------------------------------------------------===// 9076 9077 namespace { 9078 9079 /// A SmallStringEnc instance is used to build up the TypeString by passing 9080 /// it by reference between functions that append to it. 9081 typedef llvm::SmallString<128> SmallStringEnc; 9082 9083 /// TypeStringCache caches the meta encodings of Types. 9084 /// 9085 /// The reason for caching TypeStrings is two fold: 9086 /// 1. To cache a type's encoding for later uses; 9087 /// 2. As a means to break recursive member type inclusion. 9088 /// 9089 /// A cache Entry can have a Status of: 9090 /// NonRecursive: The type encoding is not recursive; 9091 /// Recursive: The type encoding is recursive; 9092 /// Incomplete: An incomplete TypeString; 9093 /// IncompleteUsed: An incomplete TypeString that has been used in a 9094 /// Recursive type encoding. 9095 /// 9096 /// A NonRecursive entry will have all of its sub-members expanded as fully 9097 /// as possible. Whilst it may contain types which are recursive, the type 9098 /// itself is not recursive and thus its encoding may be safely used whenever 9099 /// the type is encountered. 9100 /// 9101 /// A Recursive entry will have all of its sub-members expanded as fully as 9102 /// possible. The type itself is recursive and it may contain other types which 9103 /// are recursive. The Recursive encoding must not be used during the expansion 9104 /// of a recursive type's recursive branch. For simplicity the code uses 9105 /// IncompleteCount to reject all usage of Recursive encodings for member types. 9106 /// 9107 /// An Incomplete entry is always a RecordType and only encodes its 9108 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and 9109 /// are placed into the cache during type expansion as a means to identify and 9110 /// handle recursive inclusion of types as sub-members. If there is recursion 9111 /// the entry becomes IncompleteUsed. 9112 /// 9113 /// During the expansion of a RecordType's members: 9114 /// 9115 /// If the cache contains a NonRecursive encoding for the member type, the 9116 /// cached encoding is used; 9117 /// 9118 /// If the cache contains a Recursive encoding for the member type, the 9119 /// cached encoding is 'Swapped' out, as it may be incorrect, and... 9120 /// 9121 /// If the member is a RecordType, an Incomplete encoding is placed into the 9122 /// cache to break potential recursive inclusion of itself as a sub-member; 9123 /// 9124 /// Once a member RecordType has been expanded, its temporary incomplete 9125 /// entry is removed from the cache. If a Recursive encoding was swapped out 9126 /// it is swapped back in; 9127 /// 9128 /// If an incomplete entry is used to expand a sub-member, the incomplete 9129 /// entry is marked as IncompleteUsed. The cache keeps count of how many 9130 /// IncompleteUsed entries it currently contains in IncompleteUsedCount; 9131 /// 9132 /// If a member's encoding is found to be a NonRecursive or Recursive viz: 9133 /// IncompleteUsedCount==0, the member's encoding is added to the cache. 9134 /// Else the member is part of a recursive type and thus the recursion has 9135 /// been exited too soon for the encoding to be correct for the member. 9136 /// 9137 class TypeStringCache { 9138 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed}; 9139 struct Entry { 9140 std::string Str; // The encoded TypeString for the type. 9141 enum Status State; // Information about the encoding in 'Str'. 9142 std::string Swapped; // A temporary place holder for a Recursive encoding 9143 // during the expansion of RecordType's members. 9144 }; 9145 std::map<const IdentifierInfo *, struct Entry> Map; 9146 unsigned IncompleteCount; // Number of Incomplete entries in the Map. 9147 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map. 9148 public: 9149 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {} 9150 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc); 9151 bool removeIncomplete(const IdentifierInfo *ID); 9152 void addIfComplete(const IdentifierInfo *ID, StringRef Str, 9153 bool IsRecursive); 9154 StringRef lookupStr(const IdentifierInfo *ID); 9155 }; 9156 9157 /// TypeString encodings for enum & union fields must be order. 9158 /// FieldEncoding is a helper for this ordering process. 9159 class FieldEncoding { 9160 bool HasName; 9161 std::string Enc; 9162 public: 9163 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {} 9164 StringRef str() { return Enc; } 9165 bool operator<(const FieldEncoding &rhs) const { 9166 if (HasName != rhs.HasName) return HasName; 9167 return Enc < rhs.Enc; 9168 } 9169 }; 9170 9171 class XCoreABIInfo : public DefaultABIInfo { 9172 public: 9173 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 9174 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9175 QualType Ty) const override; 9176 }; 9177 9178 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo { 9179 mutable TypeStringCache TSC; 9180 public: 9181 XCoreTargetCodeGenInfo(CodeGenTypes &CGT) 9182 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {} 9183 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV, 9184 CodeGen::CodeGenModule &M) const override; 9185 }; 9186 9187 } // End anonymous namespace. 9188 9189 // TODO: this implementation is likely now redundant with the default 9190 // EmitVAArg. 9191 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9192 QualType Ty) const { 9193 CGBuilderTy &Builder = CGF.Builder; 9194 9195 // Get the VAList. 9196 CharUnits SlotSize = CharUnits::fromQuantity(4); 9197 Address AP(Builder.CreateLoad(VAListAddr), SlotSize); 9198 9199 // Handle the argument. 9200 ABIArgInfo AI = classifyArgumentType(Ty); 9201 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty); 9202 llvm::Type *ArgTy = CGT.ConvertType(Ty); 9203 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 9204 AI.setCoerceToType(ArgTy); 9205 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 9206 9207 Address Val = Address::invalid(); 9208 CharUnits ArgSize = CharUnits::Zero(); 9209 switch (AI.getKind()) { 9210 case ABIArgInfo::Expand: 9211 case ABIArgInfo::CoerceAndExpand: 9212 case ABIArgInfo::InAlloca: 9213 llvm_unreachable("Unsupported ABI kind for va_arg"); 9214 case ABIArgInfo::Ignore: 9215 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign); 9216 ArgSize = CharUnits::Zero(); 9217 break; 9218 case ABIArgInfo::Extend: 9219 case ABIArgInfo::Direct: 9220 Val = Builder.CreateBitCast(AP, ArgPtrTy); 9221 ArgSize = CharUnits::fromQuantity( 9222 getDataLayout().getTypeAllocSize(AI.getCoerceToType())); 9223 ArgSize = ArgSize.alignTo(SlotSize); 9224 break; 9225 case ABIArgInfo::Indirect: 9226 Val = Builder.CreateElementBitCast(AP, ArgPtrTy); 9227 Val = Address(Builder.CreateLoad(Val), TypeAlign); 9228 ArgSize = SlotSize; 9229 break; 9230 } 9231 9232 // Increment the VAList. 9233 if (!ArgSize.isZero()) { 9234 Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize); 9235 Builder.CreateStore(APN.getPointer(), VAListAddr); 9236 } 9237 9238 return Val; 9239 } 9240 9241 /// During the expansion of a RecordType, an incomplete TypeString is placed 9242 /// into the cache as a means to identify and break recursion. 9243 /// If there is a Recursive encoding in the cache, it is swapped out and will 9244 /// be reinserted by removeIncomplete(). 9245 /// All other types of encoding should have been used rather than arriving here. 9246 void TypeStringCache::addIncomplete(const IdentifierInfo *ID, 9247 std::string StubEnc) { 9248 if (!ID) 9249 return; 9250 Entry &E = Map[ID]; 9251 assert( (E.Str.empty() || E.State == Recursive) && 9252 "Incorrectly use of addIncomplete"); 9253 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()"); 9254 E.Swapped.swap(E.Str); // swap out the Recursive 9255 E.Str.swap(StubEnc); 9256 E.State = Incomplete; 9257 ++IncompleteCount; 9258 } 9259 9260 /// Once the RecordType has been expanded, the temporary incomplete TypeString 9261 /// must be removed from the cache. 9262 /// If a Recursive was swapped out by addIncomplete(), it will be replaced. 9263 /// Returns true if the RecordType was defined recursively. 9264 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) { 9265 if (!ID) 9266 return false; 9267 auto I = Map.find(ID); 9268 assert(I != Map.end() && "Entry not present"); 9269 Entry &E = I->second; 9270 assert( (E.State == Incomplete || 9271 E.State == IncompleteUsed) && 9272 "Entry must be an incomplete type"); 9273 bool IsRecursive = false; 9274 if (E.State == IncompleteUsed) { 9275 // We made use of our Incomplete encoding, thus we are recursive. 9276 IsRecursive = true; 9277 --IncompleteUsedCount; 9278 } 9279 if (E.Swapped.empty()) 9280 Map.erase(I); 9281 else { 9282 // Swap the Recursive back. 9283 E.Swapped.swap(E.Str); 9284 E.Swapped.clear(); 9285 E.State = Recursive; 9286 } 9287 --IncompleteCount; 9288 return IsRecursive; 9289 } 9290 9291 /// Add the encoded TypeString to the cache only if it is NonRecursive or 9292 /// Recursive (viz: all sub-members were expanded as fully as possible). 9293 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str, 9294 bool IsRecursive) { 9295 if (!ID || IncompleteUsedCount) 9296 return; // No key or it is is an incomplete sub-type so don't add. 9297 Entry &E = Map[ID]; 9298 if (IsRecursive && !E.Str.empty()) { 9299 assert(E.State==Recursive && E.Str.size() == Str.size() && 9300 "This is not the same Recursive entry"); 9301 // The parent container was not recursive after all, so we could have used 9302 // this Recursive sub-member entry after all, but we assumed the worse when 9303 // we started viz: IncompleteCount!=0. 9304 return; 9305 } 9306 assert(E.Str.empty() && "Entry already present"); 9307 E.Str = Str.str(); 9308 E.State = IsRecursive? Recursive : NonRecursive; 9309 } 9310 9311 /// Return a cached TypeString encoding for the ID. If there isn't one, or we 9312 /// are recursively expanding a type (IncompleteCount != 0) and the cached 9313 /// encoding is Recursive, return an empty StringRef. 9314 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) { 9315 if (!ID) 9316 return StringRef(); // We have no key. 9317 auto I = Map.find(ID); 9318 if (I == Map.end()) 9319 return StringRef(); // We have no encoding. 9320 Entry &E = I->second; 9321 if (E.State == Recursive && IncompleteCount) 9322 return StringRef(); // We don't use Recursive encodings for member types. 9323 9324 if (E.State == Incomplete) { 9325 // The incomplete type is being used to break out of recursion. 9326 E.State = IncompleteUsed; 9327 ++IncompleteUsedCount; 9328 } 9329 return E.Str; 9330 } 9331 9332 /// The XCore ABI includes a type information section that communicates symbol 9333 /// type information to the linker. The linker uses this information to verify 9334 /// safety/correctness of things such as array bound and pointers et al. 9335 /// The ABI only requires C (and XC) language modules to emit TypeStrings. 9336 /// This type information (TypeString) is emitted into meta data for all global 9337 /// symbols: definitions, declarations, functions & variables. 9338 /// 9339 /// The TypeString carries type, qualifier, name, size & value details. 9340 /// Please see 'Tools Development Guide' section 2.16.2 for format details: 9341 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf 9342 /// The output is tested by test/CodeGen/xcore-stringtype.c. 9343 /// 9344 static bool getTypeString(SmallStringEnc &Enc, const Decl *D, 9345 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC); 9346 9347 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols. 9348 void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV, 9349 CodeGen::CodeGenModule &CGM) const { 9350 SmallStringEnc Enc; 9351 if (getTypeString(Enc, D, CGM, TSC)) { 9352 llvm::LLVMContext &Ctx = CGM.getModule().getContext(); 9353 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV), 9354 llvm::MDString::get(Ctx, Enc.str())}; 9355 llvm::NamedMDNode *MD = 9356 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings"); 9357 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 9358 } 9359 } 9360 9361 //===----------------------------------------------------------------------===// 9362 // SPIR ABI Implementation 9363 //===----------------------------------------------------------------------===// 9364 9365 namespace { 9366 class SPIRTargetCodeGenInfo : public TargetCodeGenInfo { 9367 public: 9368 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 9369 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {} 9370 unsigned getOpenCLKernelCallingConv() const override; 9371 }; 9372 9373 } // End anonymous namespace. 9374 9375 namespace clang { 9376 namespace CodeGen { 9377 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) { 9378 DefaultABIInfo SPIRABI(CGM.getTypes()); 9379 SPIRABI.computeInfo(FI); 9380 } 9381 } 9382 } 9383 9384 unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const { 9385 return llvm::CallingConv::SPIR_KERNEL; 9386 } 9387 9388 static bool appendType(SmallStringEnc &Enc, QualType QType, 9389 const CodeGen::CodeGenModule &CGM, 9390 TypeStringCache &TSC); 9391 9392 /// Helper function for appendRecordType(). 9393 /// Builds a SmallVector containing the encoded field types in declaration 9394 /// order. 9395 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE, 9396 const RecordDecl *RD, 9397 const CodeGen::CodeGenModule &CGM, 9398 TypeStringCache &TSC) { 9399 for (const auto *Field : RD->fields()) { 9400 SmallStringEnc Enc; 9401 Enc += "m("; 9402 Enc += Field->getName(); 9403 Enc += "){"; 9404 if (Field->isBitField()) { 9405 Enc += "b("; 9406 llvm::raw_svector_ostream OS(Enc); 9407 OS << Field->getBitWidthValue(CGM.getContext()); 9408 Enc += ':'; 9409 } 9410 if (!appendType(Enc, Field->getType(), CGM, TSC)) 9411 return false; 9412 if (Field->isBitField()) 9413 Enc += ')'; 9414 Enc += '}'; 9415 FE.emplace_back(!Field->getName().empty(), Enc); 9416 } 9417 return true; 9418 } 9419 9420 /// Appends structure and union types to Enc and adds encoding to cache. 9421 /// Recursively calls appendType (via extractFieldType) for each field. 9422 /// Union types have their fields ordered according to the ABI. 9423 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT, 9424 const CodeGen::CodeGenModule &CGM, 9425 TypeStringCache &TSC, const IdentifierInfo *ID) { 9426 // Append the cached TypeString if we have one. 9427 StringRef TypeString = TSC.lookupStr(ID); 9428 if (!TypeString.empty()) { 9429 Enc += TypeString; 9430 return true; 9431 } 9432 9433 // Start to emit an incomplete TypeString. 9434 size_t Start = Enc.size(); 9435 Enc += (RT->isUnionType()? 'u' : 's'); 9436 Enc += '('; 9437 if (ID) 9438 Enc += ID->getName(); 9439 Enc += "){"; 9440 9441 // We collect all encoded fields and order as necessary. 9442 bool IsRecursive = false; 9443 const RecordDecl *RD = RT->getDecl()->getDefinition(); 9444 if (RD && !RD->field_empty()) { 9445 // An incomplete TypeString stub is placed in the cache for this RecordType 9446 // so that recursive calls to this RecordType will use it whilst building a 9447 // complete TypeString for this RecordType. 9448 SmallVector<FieldEncoding, 16> FE; 9449 std::string StubEnc(Enc.substr(Start).str()); 9450 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString. 9451 TSC.addIncomplete(ID, std::move(StubEnc)); 9452 if (!extractFieldType(FE, RD, CGM, TSC)) { 9453 (void) TSC.removeIncomplete(ID); 9454 return false; 9455 } 9456 IsRecursive = TSC.removeIncomplete(ID); 9457 // The ABI requires unions to be sorted but not structures. 9458 // See FieldEncoding::operator< for sort algorithm. 9459 if (RT->isUnionType()) 9460 llvm::sort(FE); 9461 // We can now complete the TypeString. 9462 unsigned E = FE.size(); 9463 for (unsigned I = 0; I != E; ++I) { 9464 if (I) 9465 Enc += ','; 9466 Enc += FE[I].str(); 9467 } 9468 } 9469 Enc += '}'; 9470 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive); 9471 return true; 9472 } 9473 9474 /// Appends enum types to Enc and adds the encoding to the cache. 9475 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET, 9476 TypeStringCache &TSC, 9477 const IdentifierInfo *ID) { 9478 // Append the cached TypeString if we have one. 9479 StringRef TypeString = TSC.lookupStr(ID); 9480 if (!TypeString.empty()) { 9481 Enc += TypeString; 9482 return true; 9483 } 9484 9485 size_t Start = Enc.size(); 9486 Enc += "e("; 9487 if (ID) 9488 Enc += ID->getName(); 9489 Enc += "){"; 9490 9491 // We collect all encoded enumerations and order them alphanumerically. 9492 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) { 9493 SmallVector<FieldEncoding, 16> FE; 9494 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E; 9495 ++I) { 9496 SmallStringEnc EnumEnc; 9497 EnumEnc += "m("; 9498 EnumEnc += I->getName(); 9499 EnumEnc += "){"; 9500 I->getInitVal().toString(EnumEnc); 9501 EnumEnc += '}'; 9502 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc)); 9503 } 9504 llvm::sort(FE); 9505 unsigned E = FE.size(); 9506 for (unsigned I = 0; I != E; ++I) { 9507 if (I) 9508 Enc += ','; 9509 Enc += FE[I].str(); 9510 } 9511 } 9512 Enc += '}'; 9513 TSC.addIfComplete(ID, Enc.substr(Start), false); 9514 return true; 9515 } 9516 9517 /// Appends type's qualifier to Enc. 9518 /// This is done prior to appending the type's encoding. 9519 static void appendQualifier(SmallStringEnc &Enc, QualType QT) { 9520 // Qualifiers are emitted in alphabetical order. 9521 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"}; 9522 int Lookup = 0; 9523 if (QT.isConstQualified()) 9524 Lookup += 1<<0; 9525 if (QT.isRestrictQualified()) 9526 Lookup += 1<<1; 9527 if (QT.isVolatileQualified()) 9528 Lookup += 1<<2; 9529 Enc += Table[Lookup]; 9530 } 9531 9532 /// Appends built-in types to Enc. 9533 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) { 9534 const char *EncType; 9535 switch (BT->getKind()) { 9536 case BuiltinType::Void: 9537 EncType = "0"; 9538 break; 9539 case BuiltinType::Bool: 9540 EncType = "b"; 9541 break; 9542 case BuiltinType::Char_U: 9543 EncType = "uc"; 9544 break; 9545 case BuiltinType::UChar: 9546 EncType = "uc"; 9547 break; 9548 case BuiltinType::SChar: 9549 EncType = "sc"; 9550 break; 9551 case BuiltinType::UShort: 9552 EncType = "us"; 9553 break; 9554 case BuiltinType::Short: 9555 EncType = "ss"; 9556 break; 9557 case BuiltinType::UInt: 9558 EncType = "ui"; 9559 break; 9560 case BuiltinType::Int: 9561 EncType = "si"; 9562 break; 9563 case BuiltinType::ULong: 9564 EncType = "ul"; 9565 break; 9566 case BuiltinType::Long: 9567 EncType = "sl"; 9568 break; 9569 case BuiltinType::ULongLong: 9570 EncType = "ull"; 9571 break; 9572 case BuiltinType::LongLong: 9573 EncType = "sll"; 9574 break; 9575 case BuiltinType::Float: 9576 EncType = "ft"; 9577 break; 9578 case BuiltinType::Double: 9579 EncType = "d"; 9580 break; 9581 case BuiltinType::LongDouble: 9582 EncType = "ld"; 9583 break; 9584 default: 9585 return false; 9586 } 9587 Enc += EncType; 9588 return true; 9589 } 9590 9591 /// Appends a pointer encoding to Enc before calling appendType for the pointee. 9592 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT, 9593 const CodeGen::CodeGenModule &CGM, 9594 TypeStringCache &TSC) { 9595 Enc += "p("; 9596 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC)) 9597 return false; 9598 Enc += ')'; 9599 return true; 9600 } 9601 9602 /// Appends array encoding to Enc before calling appendType for the element. 9603 static bool appendArrayType(SmallStringEnc &Enc, QualType QT, 9604 const ArrayType *AT, 9605 const CodeGen::CodeGenModule &CGM, 9606 TypeStringCache &TSC, StringRef NoSizeEnc) { 9607 if (AT->getSizeModifier() != ArrayType::Normal) 9608 return false; 9609 Enc += "a("; 9610 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 9611 CAT->getSize().toStringUnsigned(Enc); 9612 else 9613 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "". 9614 Enc += ':'; 9615 // The Qualifiers should be attached to the type rather than the array. 9616 appendQualifier(Enc, QT); 9617 if (!appendType(Enc, AT->getElementType(), CGM, TSC)) 9618 return false; 9619 Enc += ')'; 9620 return true; 9621 } 9622 9623 /// Appends a function encoding to Enc, calling appendType for the return type 9624 /// and the arguments. 9625 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT, 9626 const CodeGen::CodeGenModule &CGM, 9627 TypeStringCache &TSC) { 9628 Enc += "f{"; 9629 if (!appendType(Enc, FT->getReturnType(), CGM, TSC)) 9630 return false; 9631 Enc += "}("; 9632 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) { 9633 // N.B. we are only interested in the adjusted param types. 9634 auto I = FPT->param_type_begin(); 9635 auto E = FPT->param_type_end(); 9636 if (I != E) { 9637 do { 9638 if (!appendType(Enc, *I, CGM, TSC)) 9639 return false; 9640 ++I; 9641 if (I != E) 9642 Enc += ','; 9643 } while (I != E); 9644 if (FPT->isVariadic()) 9645 Enc += ",va"; 9646 } else { 9647 if (FPT->isVariadic()) 9648 Enc += "va"; 9649 else 9650 Enc += '0'; 9651 } 9652 } 9653 Enc += ')'; 9654 return true; 9655 } 9656 9657 /// Handles the type's qualifier before dispatching a call to handle specific 9658 /// type encodings. 9659 static bool appendType(SmallStringEnc &Enc, QualType QType, 9660 const CodeGen::CodeGenModule &CGM, 9661 TypeStringCache &TSC) { 9662 9663 QualType QT = QType.getCanonicalType(); 9664 9665 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) 9666 // The Qualifiers should be attached to the type rather than the array. 9667 // Thus we don't call appendQualifier() here. 9668 return appendArrayType(Enc, QT, AT, CGM, TSC, ""); 9669 9670 appendQualifier(Enc, QT); 9671 9672 if (const BuiltinType *BT = QT->getAs<BuiltinType>()) 9673 return appendBuiltinType(Enc, BT); 9674 9675 if (const PointerType *PT = QT->getAs<PointerType>()) 9676 return appendPointerType(Enc, PT, CGM, TSC); 9677 9678 if (const EnumType *ET = QT->getAs<EnumType>()) 9679 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier()); 9680 9681 if (const RecordType *RT = QT->getAsStructureType()) 9682 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier()); 9683 9684 if (const RecordType *RT = QT->getAsUnionType()) 9685 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier()); 9686 9687 if (const FunctionType *FT = QT->getAs<FunctionType>()) 9688 return appendFunctionType(Enc, FT, CGM, TSC); 9689 9690 return false; 9691 } 9692 9693 static bool getTypeString(SmallStringEnc &Enc, const Decl *D, 9694 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) { 9695 if (!D) 9696 return false; 9697 9698 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 9699 if (FD->getLanguageLinkage() != CLanguageLinkage) 9700 return false; 9701 return appendType(Enc, FD->getType(), CGM, TSC); 9702 } 9703 9704 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 9705 if (VD->getLanguageLinkage() != CLanguageLinkage) 9706 return false; 9707 QualType QT = VD->getType().getCanonicalType(); 9708 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) { 9709 // Global ArrayTypes are given a size of '*' if the size is unknown. 9710 // The Qualifiers should be attached to the type rather than the array. 9711 // Thus we don't call appendQualifier() here. 9712 return appendArrayType(Enc, QT, AT, CGM, TSC, "*"); 9713 } 9714 return appendType(Enc, QT, CGM, TSC); 9715 } 9716 return false; 9717 } 9718 9719 //===----------------------------------------------------------------------===// 9720 // RISCV ABI Implementation 9721 //===----------------------------------------------------------------------===// 9722 9723 namespace { 9724 class RISCVABIInfo : public DefaultABIInfo { 9725 private: 9726 // Size of the integer ('x') registers in bits. 9727 unsigned XLen; 9728 // Size of the floating point ('f') registers in bits. Note that the target 9729 // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target 9730 // with soft float ABI has FLen==0). 9731 unsigned FLen; 9732 static const int NumArgGPRs = 8; 9733 static const int NumArgFPRs = 8; 9734 bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff, 9735 llvm::Type *&Field1Ty, 9736 CharUnits &Field1Off, 9737 llvm::Type *&Field2Ty, 9738 CharUnits &Field2Off) const; 9739 9740 public: 9741 RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen) 9742 : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {} 9743 9744 // DefaultABIInfo's classifyReturnType and classifyArgumentType are 9745 // non-virtual, but computeInfo is virtual, so we overload it. 9746 void computeInfo(CGFunctionInfo &FI) const override; 9747 9748 ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft, 9749 int &ArgFPRsLeft) const; 9750 ABIArgInfo classifyReturnType(QualType RetTy) const; 9751 9752 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9753 QualType Ty) const override; 9754 9755 ABIArgInfo extendType(QualType Ty) const; 9756 9757 bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty, 9758 CharUnits &Field1Off, llvm::Type *&Field2Ty, 9759 CharUnits &Field2Off, int &NeededArgGPRs, 9760 int &NeededArgFPRs) const; 9761 ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty, 9762 CharUnits Field1Off, 9763 llvm::Type *Field2Ty, 9764 CharUnits Field2Off) const; 9765 }; 9766 } // end anonymous namespace 9767 9768 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const { 9769 QualType RetTy = FI.getReturnType(); 9770 if (!getCXXABI().classifyReturnType(FI)) 9771 FI.getReturnInfo() = classifyReturnType(RetTy); 9772 9773 // IsRetIndirect is true if classifyArgumentType indicated the value should 9774 // be passed indirect, or if the type size is a scalar greater than 2*XLen 9775 // and not a complex type with elements <= FLen. e.g. fp128 is passed direct 9776 // in LLVM IR, relying on the backend lowering code to rewrite the argument 9777 // list and pass indirectly on RV32. 9778 bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect; 9779 if (!IsRetIndirect && RetTy->isScalarType() && 9780 getContext().getTypeSize(RetTy) > (2 * XLen)) { 9781 if (RetTy->isComplexType() && FLen) { 9782 QualType EltTy = RetTy->getAs<ComplexType>()->getElementType(); 9783 IsRetIndirect = getContext().getTypeSize(EltTy) > FLen; 9784 } else { 9785 // This is a normal scalar > 2*XLen, such as fp128 on RV32. 9786 IsRetIndirect = true; 9787 } 9788 } 9789 9790 // We must track the number of GPRs used in order to conform to the RISC-V 9791 // ABI, as integer scalars passed in registers should have signext/zeroext 9792 // when promoted, but are anyext if passed on the stack. As GPR usage is 9793 // different for variadic arguments, we must also track whether we are 9794 // examining a vararg or not. 9795 int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs; 9796 int ArgFPRsLeft = FLen ? NumArgFPRs : 0; 9797 int NumFixedArgs = FI.getNumRequiredArgs(); 9798 9799 int ArgNum = 0; 9800 for (auto &ArgInfo : FI.arguments()) { 9801 bool IsFixed = ArgNum < NumFixedArgs; 9802 ArgInfo.info = 9803 classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft); 9804 ArgNum++; 9805 } 9806 } 9807 9808 // Returns true if the struct is a potential candidate for the floating point 9809 // calling convention. If this function returns true, the caller is 9810 // responsible for checking that if there is only a single field then that 9811 // field is a float. 9812 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff, 9813 llvm::Type *&Field1Ty, 9814 CharUnits &Field1Off, 9815 llvm::Type *&Field2Ty, 9816 CharUnits &Field2Off) const { 9817 bool IsInt = Ty->isIntegralOrEnumerationType(); 9818 bool IsFloat = Ty->isRealFloatingType(); 9819 9820 if (IsInt || IsFloat) { 9821 uint64_t Size = getContext().getTypeSize(Ty); 9822 if (IsInt && Size > XLen) 9823 return false; 9824 // Can't be eligible if larger than the FP registers. Half precision isn't 9825 // currently supported on RISC-V and the ABI hasn't been confirmed, so 9826 // default to the integer ABI in that case. 9827 if (IsFloat && (Size > FLen || Size < 32)) 9828 return false; 9829 // Can't be eligible if an integer type was already found (int+int pairs 9830 // are not eligible). 9831 if (IsInt && Field1Ty && Field1Ty->isIntegerTy()) 9832 return false; 9833 if (!Field1Ty) { 9834 Field1Ty = CGT.ConvertType(Ty); 9835 Field1Off = CurOff; 9836 return true; 9837 } 9838 if (!Field2Ty) { 9839 Field2Ty = CGT.ConvertType(Ty); 9840 Field2Off = CurOff; 9841 return true; 9842 } 9843 return false; 9844 } 9845 9846 if (auto CTy = Ty->getAs<ComplexType>()) { 9847 if (Field1Ty) 9848 return false; 9849 QualType EltTy = CTy->getElementType(); 9850 if (getContext().getTypeSize(EltTy) > FLen) 9851 return false; 9852 Field1Ty = CGT.ConvertType(EltTy); 9853 Field1Off = CurOff; 9854 assert(CurOff.isZero() && "Unexpected offset for first field"); 9855 Field2Ty = Field1Ty; 9856 Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy); 9857 return true; 9858 } 9859 9860 if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) { 9861 uint64_t ArraySize = ATy->getSize().getZExtValue(); 9862 QualType EltTy = ATy->getElementType(); 9863 CharUnits EltSize = getContext().getTypeSizeInChars(EltTy); 9864 for (uint64_t i = 0; i < ArraySize; ++i) { 9865 bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty, 9866 Field1Off, Field2Ty, Field2Off); 9867 if (!Ret) 9868 return false; 9869 CurOff += EltSize; 9870 } 9871 return true; 9872 } 9873 9874 if (const auto *RTy = Ty->getAs<RecordType>()) { 9875 // Structures with either a non-trivial destructor or a non-trivial 9876 // copy constructor are not eligible for the FP calling convention. 9877 if (getRecordArgABI(Ty, CGT.getCXXABI())) 9878 return false; 9879 if (isEmptyRecord(getContext(), Ty, true)) 9880 return true; 9881 const RecordDecl *RD = RTy->getDecl(); 9882 // Unions aren't eligible unless they're empty (which is caught above). 9883 if (RD->isUnion()) 9884 return false; 9885 int ZeroWidthBitFieldCount = 0; 9886 for (const FieldDecl *FD : RD->fields()) { 9887 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 9888 uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex()); 9889 QualType QTy = FD->getType(); 9890 if (FD->isBitField()) { 9891 unsigned BitWidth = FD->getBitWidthValue(getContext()); 9892 // Allow a bitfield with a type greater than XLen as long as the 9893 // bitwidth is XLen or less. 9894 if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen) 9895 QTy = getContext().getIntTypeForBitwidth(XLen, false); 9896 if (BitWidth == 0) { 9897 ZeroWidthBitFieldCount++; 9898 continue; 9899 } 9900 } 9901 9902 bool Ret = detectFPCCEligibleStructHelper( 9903 QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits), 9904 Field1Ty, Field1Off, Field2Ty, Field2Off); 9905 if (!Ret) 9906 return false; 9907 9908 // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp 9909 // or int+fp structs, but are ignored for a struct with an fp field and 9910 // any number of zero-width bitfields. 9911 if (Field2Ty && ZeroWidthBitFieldCount > 0) 9912 return false; 9913 } 9914 return Field1Ty != nullptr; 9915 } 9916 9917 return false; 9918 } 9919 9920 // Determine if a struct is eligible for passing according to the floating 9921 // point calling convention (i.e., when flattened it contains a single fp 9922 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and 9923 // NeededArgGPRs are incremented appropriately. 9924 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty, 9925 CharUnits &Field1Off, 9926 llvm::Type *&Field2Ty, 9927 CharUnits &Field2Off, 9928 int &NeededArgGPRs, 9929 int &NeededArgFPRs) const { 9930 Field1Ty = nullptr; 9931 Field2Ty = nullptr; 9932 NeededArgGPRs = 0; 9933 NeededArgFPRs = 0; 9934 bool IsCandidate = detectFPCCEligibleStructHelper( 9935 Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off); 9936 // Not really a candidate if we have a single int but no float. 9937 if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy()) 9938 return false; 9939 if (!IsCandidate) 9940 return false; 9941 if (Field1Ty && Field1Ty->isFloatingPointTy()) 9942 NeededArgFPRs++; 9943 else if (Field1Ty) 9944 NeededArgGPRs++; 9945 if (Field2Ty && Field2Ty->isFloatingPointTy()) 9946 NeededArgFPRs++; 9947 else if (Field2Ty) 9948 NeededArgGPRs++; 9949 return IsCandidate; 9950 } 9951 9952 // Call getCoerceAndExpand for the two-element flattened struct described by 9953 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an 9954 // appropriate coerceToType and unpaddedCoerceToType. 9955 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct( 9956 llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty, 9957 CharUnits Field2Off) const { 9958 SmallVector<llvm::Type *, 3> CoerceElts; 9959 SmallVector<llvm::Type *, 2> UnpaddedCoerceElts; 9960 if (!Field1Off.isZero()) 9961 CoerceElts.push_back(llvm::ArrayType::get( 9962 llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity())); 9963 9964 CoerceElts.push_back(Field1Ty); 9965 UnpaddedCoerceElts.push_back(Field1Ty); 9966 9967 if (!Field2Ty) { 9968 return ABIArgInfo::getCoerceAndExpand( 9969 llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()), 9970 UnpaddedCoerceElts[0]); 9971 } 9972 9973 CharUnits Field2Align = 9974 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty)); 9975 CharUnits Field1Size = 9976 CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty)); 9977 CharUnits Field2OffNoPadNoPack = Field1Size.alignTo(Field2Align); 9978 9979 CharUnits Padding = CharUnits::Zero(); 9980 if (Field2Off > Field2OffNoPadNoPack) 9981 Padding = Field2Off - Field2OffNoPadNoPack; 9982 else if (Field2Off != Field2Align && Field2Off > Field1Size) 9983 Padding = Field2Off - Field1Size; 9984 9985 bool IsPacked = !Field2Off.isMultipleOf(Field2Align); 9986 9987 if (!Padding.isZero()) 9988 CoerceElts.push_back(llvm::ArrayType::get( 9989 llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity())); 9990 9991 CoerceElts.push_back(Field2Ty); 9992 UnpaddedCoerceElts.push_back(Field2Ty); 9993 9994 auto CoerceToType = 9995 llvm::StructType::get(getVMContext(), CoerceElts, IsPacked); 9996 auto UnpaddedCoerceToType = 9997 llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked); 9998 9999 return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType); 10000 } 10001 10002 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed, 10003 int &ArgGPRsLeft, 10004 int &ArgFPRsLeft) const { 10005 assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow"); 10006 Ty = useFirstFieldIfTransparentUnion(Ty); 10007 10008 // Structures with either a non-trivial destructor or a non-trivial 10009 // copy constructor are always passed indirectly. 10010 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 10011 if (ArgGPRsLeft) 10012 ArgGPRsLeft -= 1; 10013 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA == 10014 CGCXXABI::RAA_DirectInMemory); 10015 } 10016 10017 // Ignore empty structs/unions. 10018 if (isEmptyRecord(getContext(), Ty, true)) 10019 return ABIArgInfo::getIgnore(); 10020 10021 uint64_t Size = getContext().getTypeSize(Ty); 10022 10023 // Pass floating point values via FPRs if possible. 10024 if (IsFixed && Ty->isFloatingType() && FLen >= Size && ArgFPRsLeft) { 10025 ArgFPRsLeft--; 10026 return ABIArgInfo::getDirect(); 10027 } 10028 10029 // Complex types for the hard float ABI must be passed direct rather than 10030 // using CoerceAndExpand. 10031 if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) { 10032 QualType EltTy = Ty->castAs<ComplexType>()->getElementType(); 10033 if (getContext().getTypeSize(EltTy) <= FLen) { 10034 ArgFPRsLeft -= 2; 10035 return ABIArgInfo::getDirect(); 10036 } 10037 } 10038 10039 if (IsFixed && FLen && Ty->isStructureOrClassType()) { 10040 llvm::Type *Field1Ty = nullptr; 10041 llvm::Type *Field2Ty = nullptr; 10042 CharUnits Field1Off = CharUnits::Zero(); 10043 CharUnits Field2Off = CharUnits::Zero(); 10044 int NeededArgGPRs; 10045 int NeededArgFPRs; 10046 bool IsCandidate = 10047 detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off, 10048 NeededArgGPRs, NeededArgFPRs); 10049 if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft && 10050 NeededArgFPRs <= ArgFPRsLeft) { 10051 ArgGPRsLeft -= NeededArgGPRs; 10052 ArgFPRsLeft -= NeededArgFPRs; 10053 return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty, 10054 Field2Off); 10055 } 10056 } 10057 10058 uint64_t NeededAlign = getContext().getTypeAlign(Ty); 10059 bool MustUseStack = false; 10060 // Determine the number of GPRs needed to pass the current argument 10061 // according to the ABI. 2*XLen-aligned varargs are passed in "aligned" 10062 // register pairs, so may consume 3 registers. 10063 int NeededArgGPRs = 1; 10064 if (!IsFixed && NeededAlign == 2 * XLen) 10065 NeededArgGPRs = 2 + (ArgGPRsLeft % 2); 10066 else if (Size > XLen && Size <= 2 * XLen) 10067 NeededArgGPRs = 2; 10068 10069 if (NeededArgGPRs > ArgGPRsLeft) { 10070 MustUseStack = true; 10071 NeededArgGPRs = ArgGPRsLeft; 10072 } 10073 10074 ArgGPRsLeft -= NeededArgGPRs; 10075 10076 if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) { 10077 // Treat an enum type as its underlying type. 10078 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 10079 Ty = EnumTy->getDecl()->getIntegerType(); 10080 10081 // All integral types are promoted to XLen width, unless passed on the 10082 // stack. 10083 if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) { 10084 return extendType(Ty); 10085 } 10086 10087 return ABIArgInfo::getDirect(); 10088 } 10089 10090 // Aggregates which are <= 2*XLen will be passed in registers if possible, 10091 // so coerce to integers. 10092 if (Size <= 2 * XLen) { 10093 unsigned Alignment = getContext().getTypeAlign(Ty); 10094 10095 // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is 10096 // required, and a 2-element XLen array if only XLen alignment is required. 10097 if (Size <= XLen) { 10098 return ABIArgInfo::getDirect( 10099 llvm::IntegerType::get(getVMContext(), XLen)); 10100 } else if (Alignment == 2 * XLen) { 10101 return ABIArgInfo::getDirect( 10102 llvm::IntegerType::get(getVMContext(), 2 * XLen)); 10103 } else { 10104 return ABIArgInfo::getDirect(llvm::ArrayType::get( 10105 llvm::IntegerType::get(getVMContext(), XLen), 2)); 10106 } 10107 } 10108 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 10109 } 10110 10111 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const { 10112 if (RetTy->isVoidType()) 10113 return ABIArgInfo::getIgnore(); 10114 10115 int ArgGPRsLeft = 2; 10116 int ArgFPRsLeft = FLen ? 2 : 0; 10117 10118 // The rules for return and argument types are the same, so defer to 10119 // classifyArgumentType. 10120 return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft, 10121 ArgFPRsLeft); 10122 } 10123 10124 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 10125 QualType Ty) const { 10126 CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8); 10127 10128 // Empty records are ignored for parameter passing purposes. 10129 if (isEmptyRecord(getContext(), Ty, true)) { 10130 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize); 10131 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 10132 return Addr; 10133 } 10134 10135 std::pair<CharUnits, CharUnits> SizeAndAlign = 10136 getContext().getTypeInfoInChars(Ty); 10137 10138 // Arguments bigger than 2*Xlen bytes are passed indirectly. 10139 bool IsIndirect = SizeAndAlign.first > 2 * SlotSize; 10140 10141 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, SizeAndAlign, 10142 SlotSize, /*AllowHigherAlign=*/true); 10143 } 10144 10145 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const { 10146 int TySize = getContext().getTypeSize(Ty); 10147 // RV64 ABI requires unsigned 32 bit integers to be sign extended. 10148 if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32) 10149 return ABIArgInfo::getSignExtend(Ty); 10150 return ABIArgInfo::getExtend(Ty); 10151 } 10152 10153 namespace { 10154 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo { 10155 public: 10156 RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, 10157 unsigned FLen) 10158 : TargetCodeGenInfo(new RISCVABIInfo(CGT, XLen, FLen)) {} 10159 10160 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 10161 CodeGen::CodeGenModule &CGM) const override { 10162 const auto *FD = dyn_cast_or_null<FunctionDecl>(D); 10163 if (!FD) return; 10164 10165 const auto *Attr = FD->getAttr<RISCVInterruptAttr>(); 10166 if (!Attr) 10167 return; 10168 10169 const char *Kind; 10170 switch (Attr->getInterrupt()) { 10171 case RISCVInterruptAttr::user: Kind = "user"; break; 10172 case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break; 10173 case RISCVInterruptAttr::machine: Kind = "machine"; break; 10174 } 10175 10176 auto *Fn = cast<llvm::Function>(GV); 10177 10178 Fn->addFnAttr("interrupt", Kind); 10179 } 10180 }; 10181 } // namespace 10182 10183 //===----------------------------------------------------------------------===// 10184 // Driver code 10185 //===----------------------------------------------------------------------===// 10186 10187 bool CodeGenModule::supportsCOMDAT() const { 10188 return getTriple().supportsCOMDAT(); 10189 } 10190 10191 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() { 10192 if (TheTargetCodeGenInfo) 10193 return *TheTargetCodeGenInfo; 10194 10195 // Helper to set the unique_ptr while still keeping the return value. 10196 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & { 10197 this->TheTargetCodeGenInfo.reset(P); 10198 return *P; 10199 }; 10200 10201 const llvm::Triple &Triple = getTarget().getTriple(); 10202 switch (Triple.getArch()) { 10203 default: 10204 return SetCGInfo(new DefaultTargetCodeGenInfo(Types)); 10205 10206 case llvm::Triple::le32: 10207 return SetCGInfo(new PNaClTargetCodeGenInfo(Types)); 10208 case llvm::Triple::mips: 10209 case llvm::Triple::mipsel: 10210 if (Triple.getOS() == llvm::Triple::NaCl) 10211 return SetCGInfo(new PNaClTargetCodeGenInfo(Types)); 10212 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true)); 10213 10214 case llvm::Triple::mips64: 10215 case llvm::Triple::mips64el: 10216 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false)); 10217 10218 case llvm::Triple::avr: 10219 return SetCGInfo(new AVRTargetCodeGenInfo(Types)); 10220 10221 case llvm::Triple::aarch64: 10222 case llvm::Triple::aarch64_32: 10223 case llvm::Triple::aarch64_be: { 10224 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS; 10225 if (getTarget().getABI() == "darwinpcs") 10226 Kind = AArch64ABIInfo::DarwinPCS; 10227 else if (Triple.isOSWindows()) 10228 return SetCGInfo( 10229 new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64)); 10230 10231 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind)); 10232 } 10233 10234 case llvm::Triple::wasm32: 10235 case llvm::Triple::wasm64: { 10236 WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP; 10237 if (getTarget().getABI() == "experimental-mv") 10238 Kind = WebAssemblyABIInfo::ExperimentalMV; 10239 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind)); 10240 } 10241 10242 case llvm::Triple::arm: 10243 case llvm::Triple::armeb: 10244 case llvm::Triple::thumb: 10245 case llvm::Triple::thumbeb: { 10246 if (Triple.getOS() == llvm::Triple::Win32) { 10247 return SetCGInfo( 10248 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP)); 10249 } 10250 10251 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS; 10252 StringRef ABIStr = getTarget().getABI(); 10253 if (ABIStr == "apcs-gnu") 10254 Kind = ARMABIInfo::APCS; 10255 else if (ABIStr == "aapcs16") 10256 Kind = ARMABIInfo::AAPCS16_VFP; 10257 else if (CodeGenOpts.FloatABI == "hard" || 10258 (CodeGenOpts.FloatABI != "soft" && 10259 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF || 10260 Triple.getEnvironment() == llvm::Triple::MuslEABIHF || 10261 Triple.getEnvironment() == llvm::Triple::EABIHF))) 10262 Kind = ARMABIInfo::AAPCS_VFP; 10263 10264 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind)); 10265 } 10266 10267 case llvm::Triple::ppc: 10268 return SetCGInfo( 10269 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft" || 10270 getTarget().hasFeature("spe"))); 10271 case llvm::Triple::ppc64: 10272 if (Triple.isOSBinFormatELF()) { 10273 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1; 10274 if (getTarget().getABI() == "elfv2") 10275 Kind = PPC64_SVR4_ABIInfo::ELFv2; 10276 bool HasQPX = getTarget().getABI() == "elfv1-qpx"; 10277 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 10278 10279 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX, 10280 IsSoftFloat)); 10281 } else 10282 return SetCGInfo(new PPC64TargetCodeGenInfo(Types)); 10283 case llvm::Triple::ppc64le: { 10284 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!"); 10285 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2; 10286 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx") 10287 Kind = PPC64_SVR4_ABIInfo::ELFv1; 10288 bool HasQPX = getTarget().getABI() == "elfv1-qpx"; 10289 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 10290 10291 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX, 10292 IsSoftFloat)); 10293 } 10294 10295 case llvm::Triple::nvptx: 10296 case llvm::Triple::nvptx64: 10297 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types)); 10298 10299 case llvm::Triple::msp430: 10300 return SetCGInfo(new MSP430TargetCodeGenInfo(Types)); 10301 10302 case llvm::Triple::riscv32: 10303 case llvm::Triple::riscv64: { 10304 StringRef ABIStr = getTarget().getABI(); 10305 unsigned XLen = getTarget().getPointerWidth(0); 10306 unsigned ABIFLen = 0; 10307 if (ABIStr.endswith("f")) 10308 ABIFLen = 32; 10309 else if (ABIStr.endswith("d")) 10310 ABIFLen = 64; 10311 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen)); 10312 } 10313 10314 case llvm::Triple::systemz: { 10315 bool SoftFloat = CodeGenOpts.FloatABI == "soft"; 10316 bool HasVector = !SoftFloat && getTarget().getABI() == "vector"; 10317 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat)); 10318 } 10319 10320 case llvm::Triple::tce: 10321 case llvm::Triple::tcele: 10322 return SetCGInfo(new TCETargetCodeGenInfo(Types)); 10323 10324 case llvm::Triple::x86: { 10325 bool IsDarwinVectorABI = Triple.isOSDarwin(); 10326 bool RetSmallStructInRegABI = 10327 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 10328 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing(); 10329 10330 if (Triple.getOS() == llvm::Triple::Win32) { 10331 return SetCGInfo(new WinX86_32TargetCodeGenInfo( 10332 Types, IsDarwinVectorABI, RetSmallStructInRegABI, 10333 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters)); 10334 } else { 10335 return SetCGInfo(new X86_32TargetCodeGenInfo( 10336 Types, IsDarwinVectorABI, RetSmallStructInRegABI, 10337 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters, 10338 CodeGenOpts.FloatABI == "soft")); 10339 } 10340 } 10341 10342 case llvm::Triple::x86_64: { 10343 StringRef ABI = getTarget().getABI(); 10344 X86AVXABILevel AVXLevel = 10345 (ABI == "avx512" 10346 ? X86AVXABILevel::AVX512 10347 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None); 10348 10349 switch (Triple.getOS()) { 10350 case llvm::Triple::Win32: 10351 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel)); 10352 default: 10353 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel)); 10354 } 10355 } 10356 case llvm::Triple::hexagon: 10357 return SetCGInfo(new HexagonTargetCodeGenInfo(Types)); 10358 case llvm::Triple::lanai: 10359 return SetCGInfo(new LanaiTargetCodeGenInfo(Types)); 10360 case llvm::Triple::r600: 10361 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types)); 10362 case llvm::Triple::amdgcn: 10363 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types)); 10364 case llvm::Triple::sparc: 10365 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types)); 10366 case llvm::Triple::sparcv9: 10367 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types)); 10368 case llvm::Triple::xcore: 10369 return SetCGInfo(new XCoreTargetCodeGenInfo(Types)); 10370 case llvm::Triple::arc: 10371 return SetCGInfo(new ARCTargetCodeGenInfo(Types)); 10372 case llvm::Triple::spir: 10373 case llvm::Triple::spir64: 10374 return SetCGInfo(new SPIRTargetCodeGenInfo(Types)); 10375 } 10376 } 10377 10378 /// Create an OpenCL kernel for an enqueued block. 10379 /// 10380 /// The kernel has the same function type as the block invoke function. Its 10381 /// name is the name of the block invoke function postfixed with "_kernel". 10382 /// It simply calls the block invoke function then returns. 10383 llvm::Function * 10384 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF, 10385 llvm::Function *Invoke, 10386 llvm::Value *BlockLiteral) const { 10387 auto *InvokeFT = Invoke->getFunctionType(); 10388 llvm::SmallVector<llvm::Type *, 2> ArgTys; 10389 for (auto &P : InvokeFT->params()) 10390 ArgTys.push_back(P); 10391 auto &C = CGF.getLLVMContext(); 10392 std::string Name = Invoke->getName().str() + "_kernel"; 10393 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false); 10394 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name, 10395 &CGF.CGM.getModule()); 10396 auto IP = CGF.Builder.saveIP(); 10397 auto *BB = llvm::BasicBlock::Create(C, "entry", F); 10398 auto &Builder = CGF.Builder; 10399 Builder.SetInsertPoint(BB); 10400 llvm::SmallVector<llvm::Value *, 2> Args; 10401 for (auto &A : F->args()) 10402 Args.push_back(&A); 10403 Builder.CreateCall(Invoke, Args); 10404 Builder.CreateRetVoid(); 10405 Builder.restoreIP(IP); 10406 return F; 10407 } 10408 10409 /// Create an OpenCL kernel for an enqueued block. 10410 /// 10411 /// The type of the first argument (the block literal) is the struct type 10412 /// of the block literal instead of a pointer type. The first argument 10413 /// (block literal) is passed directly by value to the kernel. The kernel 10414 /// allocates the same type of struct on stack and stores the block literal 10415 /// to it and passes its pointer to the block invoke function. The kernel 10416 /// has "enqueued-block" function attribute and kernel argument metadata. 10417 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel( 10418 CodeGenFunction &CGF, llvm::Function *Invoke, 10419 llvm::Value *BlockLiteral) const { 10420 auto &Builder = CGF.Builder; 10421 auto &C = CGF.getLLVMContext(); 10422 10423 auto *BlockTy = BlockLiteral->getType()->getPointerElementType(); 10424 auto *InvokeFT = Invoke->getFunctionType(); 10425 llvm::SmallVector<llvm::Type *, 2> ArgTys; 10426 llvm::SmallVector<llvm::Metadata *, 8> AddressQuals; 10427 llvm::SmallVector<llvm::Metadata *, 8> AccessQuals; 10428 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames; 10429 llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames; 10430 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals; 10431 llvm::SmallVector<llvm::Metadata *, 8> ArgNames; 10432 10433 ArgTys.push_back(BlockTy); 10434 ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal")); 10435 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0))); 10436 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal")); 10437 ArgTypeQuals.push_back(llvm::MDString::get(C, "")); 10438 AccessQuals.push_back(llvm::MDString::get(C, "none")); 10439 ArgNames.push_back(llvm::MDString::get(C, "block_literal")); 10440 for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) { 10441 ArgTys.push_back(InvokeFT->getParamType(I)); 10442 ArgTypeNames.push_back(llvm::MDString::get(C, "void*")); 10443 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3))); 10444 AccessQuals.push_back(llvm::MDString::get(C, "none")); 10445 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*")); 10446 ArgTypeQuals.push_back(llvm::MDString::get(C, "")); 10447 ArgNames.push_back( 10448 llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str())); 10449 } 10450 std::string Name = Invoke->getName().str() + "_kernel"; 10451 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false); 10452 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name, 10453 &CGF.CGM.getModule()); 10454 F->addFnAttr("enqueued-block"); 10455 auto IP = CGF.Builder.saveIP(); 10456 auto *BB = llvm::BasicBlock::Create(C, "entry", F); 10457 Builder.SetInsertPoint(BB); 10458 const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy); 10459 auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr); 10460 BlockPtr->setAlignment(BlockAlign); 10461 Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign); 10462 auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0)); 10463 llvm::SmallVector<llvm::Value *, 2> Args; 10464 Args.push_back(Cast); 10465 for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I) 10466 Args.push_back(I); 10467 Builder.CreateCall(Invoke, Args); 10468 Builder.CreateRetVoid(); 10469 Builder.restoreIP(IP); 10470 10471 F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals)); 10472 F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals)); 10473 F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames)); 10474 F->setMetadata("kernel_arg_base_type", 10475 llvm::MDNode::get(C, ArgBaseTypeNames)); 10476 F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals)); 10477 if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata) 10478 F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames)); 10479 10480 return F; 10481 } 10482