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