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