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