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