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