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