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 "CodeGenFunction.h" 19 #include "clang/AST/RecordLayout.h" 20 #include "clang/CodeGen/CGFunctionInfo.h" 21 #include "clang/Frontend/CodeGenOptions.h" 22 #include "llvm/ADT/Triple.h" 23 #include "llvm/IR/DataLayout.h" 24 #include "llvm/IR/Type.h" 25 #include "llvm/Support/raw_ostream.h" 26 using namespace clang; 27 using namespace CodeGen; 28 29 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder, 30 llvm::Value *Array, 31 llvm::Value *Value, 32 unsigned FirstIndex, 33 unsigned LastIndex) { 34 // Alternatively, we could emit this as a loop in the source. 35 for (unsigned I = FirstIndex; I <= LastIndex; ++I) { 36 llvm::Value *Cell = Builder.CreateConstInBoundsGEP1_32(Array, I); 37 Builder.CreateStore(Value, Cell); 38 } 39 } 40 41 static bool isAggregateTypeForABI(QualType T) { 42 return !CodeGenFunction::hasScalarEvaluationKind(T) || 43 T->isMemberFunctionPointerType(); 44 } 45 46 ABIInfo::~ABIInfo() {} 47 48 static bool isRecordReturnIndirect(const RecordType *RT, 49 CGCXXABI &CXXABI) { 50 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 51 if (!RD) 52 return false; 53 return CXXABI.isReturnTypeIndirect(RD); 54 } 55 56 57 static bool isRecordReturnIndirect(QualType T, CGCXXABI &CXXABI) { 58 const RecordType *RT = T->getAs<RecordType>(); 59 if (!RT) 60 return false; 61 return isRecordReturnIndirect(RT, CXXABI); 62 } 63 64 static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT, 65 CGCXXABI &CXXABI) { 66 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 67 if (!RD) 68 return CGCXXABI::RAA_Default; 69 return CXXABI.getRecordArgABI(RD); 70 } 71 72 static CGCXXABI::RecordArgABI getRecordArgABI(QualType T, 73 CGCXXABI &CXXABI) { 74 const RecordType *RT = T->getAs<RecordType>(); 75 if (!RT) 76 return CGCXXABI::RAA_Default; 77 return getRecordArgABI(RT, CXXABI); 78 } 79 80 CGCXXABI &ABIInfo::getCXXABI() const { 81 return CGT.getCXXABI(); 82 } 83 84 ASTContext &ABIInfo::getContext() const { 85 return CGT.getContext(); 86 } 87 88 llvm::LLVMContext &ABIInfo::getVMContext() const { 89 return CGT.getLLVMContext(); 90 } 91 92 const llvm::DataLayout &ABIInfo::getDataLayout() const { 93 return CGT.getDataLayout(); 94 } 95 96 const TargetInfo &ABIInfo::getTarget() const { 97 return CGT.getTarget(); 98 } 99 100 void ABIArgInfo::dump() const { 101 raw_ostream &OS = llvm::errs(); 102 OS << "(ABIArgInfo Kind="; 103 switch (TheKind) { 104 case Direct: 105 OS << "Direct Type="; 106 if (llvm::Type *Ty = getCoerceToType()) 107 Ty->print(OS); 108 else 109 OS << "null"; 110 break; 111 case Extend: 112 OS << "Extend"; 113 break; 114 case Ignore: 115 OS << "Ignore"; 116 break; 117 case InAlloca: 118 OS << "InAlloca Offset=" << getInAllocaFieldIndex(); 119 break; 120 case Indirect: 121 OS << "Indirect Align=" << getIndirectAlign() 122 << " ByVal=" << getIndirectByVal() 123 << " Realign=" << getIndirectRealign(); 124 break; 125 case Expand: 126 OS << "Expand"; 127 break; 128 } 129 OS << ")\n"; 130 } 131 132 TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; } 133 134 // If someone can figure out a general rule for this, that would be great. 135 // It's probably just doomed to be platform-dependent, though. 136 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const { 137 // Verified for: 138 // x86-64 FreeBSD, Linux, Darwin 139 // x86-32 FreeBSD, Linux, Darwin 140 // PowerPC Linux, Darwin 141 // ARM Darwin (*not* EABI) 142 // AArch64 Linux 143 return 32; 144 } 145 146 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args, 147 const FunctionNoProtoType *fnType) const { 148 // The following conventions are known to require this to be false: 149 // x86_stdcall 150 // MIPS 151 // For everything else, we just prefer false unless we opt out. 152 return false; 153 } 154 155 void 156 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib, 157 llvm::SmallString<24> &Opt) const { 158 // This assumes the user is passing a library name like "rt" instead of a 159 // filename like "librt.a/so", and that they don't care whether it's static or 160 // dynamic. 161 Opt = "-l"; 162 Opt += Lib; 163 } 164 165 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays); 166 167 /// isEmptyField - Return true iff a the field is "empty", that is it 168 /// is an unnamed bit-field or an (array of) empty record(s). 169 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD, 170 bool AllowArrays) { 171 if (FD->isUnnamedBitfield()) 172 return true; 173 174 QualType FT = FD->getType(); 175 176 // Constant arrays of empty records count as empty, strip them off. 177 // Constant arrays of zero length always count as empty. 178 if (AllowArrays) 179 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 180 if (AT->getSize() == 0) 181 return true; 182 FT = AT->getElementType(); 183 } 184 185 const RecordType *RT = FT->getAs<RecordType>(); 186 if (!RT) 187 return false; 188 189 // C++ record fields are never empty, at least in the Itanium ABI. 190 // 191 // FIXME: We should use a predicate for whether this behavior is true in the 192 // current ABI. 193 if (isa<CXXRecordDecl>(RT->getDecl())) 194 return false; 195 196 return isEmptyRecord(Context, FT, AllowArrays); 197 } 198 199 /// isEmptyRecord - Return true iff a structure contains only empty 200 /// fields. Note that a structure with a flexible array member is not 201 /// considered empty. 202 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) { 203 const RecordType *RT = T->getAs<RecordType>(); 204 if (!RT) 205 return 0; 206 const RecordDecl *RD = RT->getDecl(); 207 if (RD->hasFlexibleArrayMember()) 208 return false; 209 210 // If this is a C++ record, check the bases first. 211 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 212 for (const auto &I : CXXRD->bases()) 213 if (!isEmptyRecord(Context, I.getType(), true)) 214 return false; 215 216 for (const auto *I : RD->fields()) 217 if (!isEmptyField(Context, I, AllowArrays)) 218 return false; 219 return true; 220 } 221 222 /// isSingleElementStruct - Determine if a structure is a "single 223 /// element struct", i.e. it has exactly one non-empty field or 224 /// exactly one field which is itself a single element 225 /// struct. Structures with flexible array members are never 226 /// considered single element structs. 227 /// 228 /// \return The field declaration for the single non-empty field, if 229 /// it exists. 230 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) { 231 const RecordType *RT = T->getAsStructureType(); 232 if (!RT) 233 return 0; 234 235 const RecordDecl *RD = RT->getDecl(); 236 if (RD->hasFlexibleArrayMember()) 237 return 0; 238 239 const Type *Found = 0; 240 241 // If this is a C++ record, check the bases first. 242 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 243 for (const auto &I : CXXRD->bases()) { 244 // Ignore empty records. 245 if (isEmptyRecord(Context, I.getType(), true)) 246 continue; 247 248 // If we already found an element then this isn't a single-element struct. 249 if (Found) 250 return 0; 251 252 // If this is non-empty and not a single element struct, the composite 253 // cannot be a single element struct. 254 Found = isSingleElementStruct(I.getType(), Context); 255 if (!Found) 256 return 0; 257 } 258 } 259 260 // Check for single element. 261 for (const auto *FD : RD->fields()) { 262 QualType FT = FD->getType(); 263 264 // Ignore empty fields. 265 if (isEmptyField(Context, FD, true)) 266 continue; 267 268 // If we already found an element then this isn't a single-element 269 // struct. 270 if (Found) 271 return 0; 272 273 // Treat single element arrays as the element. 274 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 275 if (AT->getSize().getZExtValue() != 1) 276 break; 277 FT = AT->getElementType(); 278 } 279 280 if (!isAggregateTypeForABI(FT)) { 281 Found = FT.getTypePtr(); 282 } else { 283 Found = isSingleElementStruct(FT, Context); 284 if (!Found) 285 return 0; 286 } 287 } 288 289 // We don't consider a struct a single-element struct if it has 290 // padding beyond the element type. 291 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T)) 292 return 0; 293 294 return Found; 295 } 296 297 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) { 298 // Treat complex types as the element type. 299 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 300 Ty = CTy->getElementType(); 301 302 // Check for a type which we know has a simple scalar argument-passing 303 // convention without any padding. (We're specifically looking for 32 304 // and 64-bit integer and integer-equivalents, float, and double.) 305 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() && 306 !Ty->isEnumeralType() && !Ty->isBlockPointerType()) 307 return false; 308 309 uint64_t Size = Context.getTypeSize(Ty); 310 return Size == 32 || Size == 64; 311 } 312 313 /// canExpandIndirectArgument - Test whether an argument type which is to be 314 /// passed indirectly (on the stack) would have the equivalent layout if it was 315 /// expanded into separate arguments. If so, we prefer to do the latter to avoid 316 /// inhibiting optimizations. 317 /// 318 // FIXME: This predicate is missing many cases, currently it just follows 319 // llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We 320 // should probably make this smarter, or better yet make the LLVM backend 321 // capable of handling it. 322 static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) { 323 // We can only expand structure types. 324 const RecordType *RT = Ty->getAs<RecordType>(); 325 if (!RT) 326 return false; 327 328 // We can only expand (C) structures. 329 // 330 // FIXME: This needs to be generalized to handle classes as well. 331 const RecordDecl *RD = RT->getDecl(); 332 if (!RD->isStruct() || isa<CXXRecordDecl>(RD)) 333 return false; 334 335 uint64_t Size = 0; 336 337 for (const auto *FD : RD->fields()) { 338 if (!is32Or64BitBasicType(FD->getType(), Context)) 339 return false; 340 341 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know 342 // how to expand them yet, and the predicate for telling if a bitfield still 343 // counts as "basic" is more complicated than what we were doing previously. 344 if (FD->isBitField()) 345 return false; 346 347 Size += Context.getTypeSize(FD->getType()); 348 } 349 350 // Make sure there are not any holes in the struct. 351 if (Size != Context.getTypeSize(Ty)) 352 return false; 353 354 return true; 355 } 356 357 namespace { 358 /// DefaultABIInfo - The default implementation for ABI specific 359 /// details. This implementation provides information which results in 360 /// self-consistent and sensible LLVM IR generation, but does not 361 /// conform to any particular ABI. 362 class DefaultABIInfo : public ABIInfo { 363 public: 364 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 365 366 ABIArgInfo classifyReturnType(QualType RetTy) const; 367 ABIArgInfo classifyArgumentType(QualType RetTy) const; 368 369 void computeInfo(CGFunctionInfo &FI) const override { 370 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 371 for (auto &I : FI.arguments()) 372 I.info = classifyArgumentType(I.type); 373 } 374 375 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 376 CodeGenFunction &CGF) const override; 377 }; 378 379 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo { 380 public: 381 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 382 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {} 383 }; 384 385 llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 386 CodeGenFunction &CGF) const { 387 return 0; 388 } 389 390 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const { 391 if (isAggregateTypeForABI(Ty)) { 392 // Records with non-trivial destructors/constructors should not be passed 393 // by value. 394 if (isRecordReturnIndirect(Ty, getCXXABI())) 395 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 396 397 return ABIArgInfo::getIndirect(0); 398 } 399 400 // Treat an enum type as its underlying type. 401 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 402 Ty = EnumTy->getDecl()->getIntegerType(); 403 404 return (Ty->isPromotableIntegerType() ? 405 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 406 } 407 408 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const { 409 if (RetTy->isVoidType()) 410 return ABIArgInfo::getIgnore(); 411 412 if (isAggregateTypeForABI(RetTy)) 413 return ABIArgInfo::getIndirect(0); 414 415 // Treat an enum type as its underlying type. 416 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 417 RetTy = EnumTy->getDecl()->getIntegerType(); 418 419 return (RetTy->isPromotableIntegerType() ? 420 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 421 } 422 423 //===----------------------------------------------------------------------===// 424 // le32/PNaCl bitcode ABI Implementation 425 // 426 // This is a simplified version of the x86_32 ABI. Arguments and return values 427 // are always passed on the stack. 428 //===----------------------------------------------------------------------===// 429 430 class PNaClABIInfo : public ABIInfo { 431 public: 432 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 433 434 ABIArgInfo classifyReturnType(QualType RetTy) const; 435 ABIArgInfo classifyArgumentType(QualType RetTy) const; 436 437 void computeInfo(CGFunctionInfo &FI) const override; 438 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 439 CodeGenFunction &CGF) const override; 440 }; 441 442 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo { 443 public: 444 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 445 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {} 446 }; 447 448 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const { 449 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 450 451 for (auto &I : FI.arguments()) 452 I.info = classifyArgumentType(I.type); 453 } 454 455 llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 456 CodeGenFunction &CGF) const { 457 return 0; 458 } 459 460 /// \brief Classify argument of given type \p Ty. 461 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const { 462 if (isAggregateTypeForABI(Ty)) { 463 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 464 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 465 return ABIArgInfo::getIndirect(0); 466 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) { 467 // Treat an enum type as its underlying type. 468 Ty = EnumTy->getDecl()->getIntegerType(); 469 } else if (Ty->isFloatingType()) { 470 // Floating-point types don't go inreg. 471 return ABIArgInfo::getDirect(); 472 } 473 474 return (Ty->isPromotableIntegerType() ? 475 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 476 } 477 478 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const { 479 if (RetTy->isVoidType()) 480 return ABIArgInfo::getIgnore(); 481 482 // In the PNaCl ABI we always return records/structures on the stack. 483 if (isAggregateTypeForABI(RetTy)) 484 return ABIArgInfo::getIndirect(0); 485 486 // Treat an enum type as its underlying type. 487 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 488 RetTy = EnumTy->getDecl()->getIntegerType(); 489 490 return (RetTy->isPromotableIntegerType() ? 491 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 492 } 493 494 /// IsX86_MMXType - Return true if this is an MMX type. 495 bool IsX86_MMXType(llvm::Type *IRType) { 496 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>. 497 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 && 498 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() && 499 IRType->getScalarSizeInBits() != 64; 500 } 501 502 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 503 StringRef Constraint, 504 llvm::Type* Ty) { 505 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) { 506 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) { 507 // Invalid MMX constraint 508 return 0; 509 } 510 511 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext()); 512 } 513 514 // No operation needed 515 return Ty; 516 } 517 518 //===----------------------------------------------------------------------===// 519 // X86-32 ABI Implementation 520 //===----------------------------------------------------------------------===// 521 522 /// \brief Similar to llvm::CCState, but for Clang. 523 struct CCState { 524 CCState(unsigned CC) : CC(CC), FreeRegs(0) {} 525 526 unsigned CC; 527 unsigned FreeRegs; 528 unsigned StackOffset; 529 bool UseInAlloca; 530 }; 531 532 /// X86_32ABIInfo - The X86-32 ABI information. 533 class X86_32ABIInfo : public ABIInfo { 534 enum Class { 535 Integer, 536 Float 537 }; 538 539 static const unsigned MinABIStackAlignInBytes = 4; 540 541 bool IsDarwinVectorABI; 542 bool IsSmallStructInRegABI; 543 bool IsWin32StructABI; 544 unsigned DefaultNumRegisterParameters; 545 546 static bool isRegisterSize(unsigned Size) { 547 return (Size == 8 || Size == 16 || Size == 32 || Size == 64); 548 } 549 550 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context, 551 bool IsInstanceMethod) const; 552 553 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 554 /// such that the argument will be passed in memory. 555 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; 556 557 ABIArgInfo getIndirectReturnResult(CCState &State) const; 558 559 /// \brief Return the alignment to use for the given type on the stack. 560 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const; 561 562 Class classify(QualType Ty) const; 563 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State, 564 bool IsInstanceMethod) const; 565 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; 566 bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const; 567 568 /// \brief Rewrite the function info so that all memory arguments use 569 /// inalloca. 570 void rewriteWithInAlloca(CGFunctionInfo &FI) const; 571 572 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields, 573 unsigned &StackOffset, ABIArgInfo &Info, 574 QualType Type) const; 575 576 public: 577 578 void computeInfo(CGFunctionInfo &FI) const override; 579 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 580 CodeGenFunction &CGF) const override; 581 582 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w, 583 unsigned r) 584 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p), 585 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {} 586 }; 587 588 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo { 589 public: 590 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 591 bool d, bool p, bool w, unsigned r) 592 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {} 593 594 static bool isStructReturnInRegABI( 595 const llvm::Triple &Triple, const CodeGenOptions &Opts); 596 597 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 598 CodeGen::CodeGenModule &CGM) const override; 599 600 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 601 // Darwin uses different dwarf register numbers for EH. 602 if (CGM.getTarget().getTriple().isOSDarwin()) return 5; 603 return 4; 604 } 605 606 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 607 llvm::Value *Address) const override; 608 609 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 610 StringRef Constraint, 611 llvm::Type* Ty) const override { 612 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 613 } 614 615 llvm::Constant * 616 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { 617 unsigned Sig = (0xeb << 0) | // jmp rel8 618 (0x06 << 8) | // .+0x08 619 ('F' << 16) | 620 ('T' << 24); 621 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 622 } 623 624 }; 625 626 } 627 628 /// shouldReturnTypeInRegister - Determine if the given type should be 629 /// passed in a register (for the Darwin ABI). 630 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty, ASTContext &Context, 631 bool IsInstanceMethod) const { 632 uint64_t Size = Context.getTypeSize(Ty); 633 634 // Type must be register sized. 635 if (!isRegisterSize(Size)) 636 return false; 637 638 if (Ty->isVectorType()) { 639 // 64- and 128- bit vectors inside structures are not returned in 640 // registers. 641 if (Size == 64 || Size == 128) 642 return false; 643 644 return true; 645 } 646 647 // If this is a builtin, pointer, enum, complex type, member pointer, or 648 // member function pointer it is ok. 649 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() || 650 Ty->isAnyComplexType() || Ty->isEnumeralType() || 651 Ty->isBlockPointerType() || Ty->isMemberPointerType()) 652 return true; 653 654 // Arrays are treated like records. 655 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) 656 return shouldReturnTypeInRegister(AT->getElementType(), Context, 657 IsInstanceMethod); 658 659 // Otherwise, it must be a record type. 660 const RecordType *RT = Ty->getAs<RecordType>(); 661 if (!RT) return false; 662 663 // FIXME: Traverse bases here too. 664 665 // For thiscall conventions, structures will never be returned in 666 // a register. This is for compatibility with the MSVC ABI 667 if (IsWin32StructABI && IsInstanceMethod && RT->isStructureType()) 668 return false; 669 670 // Structure types are passed in register if all fields would be 671 // passed in a register. 672 for (const auto *FD : RT->getDecl()->fields()) { 673 // Empty fields are ignored. 674 if (isEmptyField(Context, FD, true)) 675 continue; 676 677 // Check fields recursively. 678 if (!shouldReturnTypeInRegister(FD->getType(), Context, IsInstanceMethod)) 679 return false; 680 } 681 return true; 682 } 683 684 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(CCState &State) const { 685 // If the return value is indirect, then the hidden argument is consuming one 686 // integer register. 687 if (State.FreeRegs) { 688 --State.FreeRegs; 689 return ABIArgInfo::getIndirectInReg(/*Align=*/0, /*ByVal=*/false); 690 } 691 return ABIArgInfo::getIndirect(/*Align=*/0, /*ByVal=*/false); 692 } 693 694 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, CCState &State, 695 bool IsInstanceMethod) const { 696 if (RetTy->isVoidType()) 697 return ABIArgInfo::getIgnore(); 698 699 if (const VectorType *VT = RetTy->getAs<VectorType>()) { 700 // On Darwin, some vectors are returned in registers. 701 if (IsDarwinVectorABI) { 702 uint64_t Size = getContext().getTypeSize(RetTy); 703 704 // 128-bit vectors are a special case; they are returned in 705 // registers and we need to make sure to pick a type the LLVM 706 // backend will like. 707 if (Size == 128) 708 return ABIArgInfo::getDirect(llvm::VectorType::get( 709 llvm::Type::getInt64Ty(getVMContext()), 2)); 710 711 // Always return in register if it fits in a general purpose 712 // register, or if it is 64 bits and has a single element. 713 if ((Size == 8 || Size == 16 || Size == 32) || 714 (Size == 64 && VT->getNumElements() == 1)) 715 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 716 Size)); 717 718 return getIndirectReturnResult(State); 719 } 720 721 return ABIArgInfo::getDirect(); 722 } 723 724 if (isAggregateTypeForABI(RetTy)) { 725 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 726 if (isRecordReturnIndirect(RT, getCXXABI())) 727 return getIndirectReturnResult(State); 728 729 // Structures with flexible arrays are always indirect. 730 if (RT->getDecl()->hasFlexibleArrayMember()) 731 return getIndirectReturnResult(State); 732 } 733 734 // If specified, structs and unions are always indirect. 735 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType()) 736 return getIndirectReturnResult(State); 737 738 // Small structures which are register sized are generally returned 739 // in a register. 740 if (shouldReturnTypeInRegister(RetTy, getContext(), IsInstanceMethod)) { 741 uint64_t Size = getContext().getTypeSize(RetTy); 742 743 // As a special-case, if the struct is a "single-element" struct, and 744 // the field is of type "float" or "double", return it in a 745 // floating-point register. (MSVC does not apply this special case.) 746 // We apply a similar transformation for pointer types to improve the 747 // quality of the generated IR. 748 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 749 if ((!IsWin32StructABI && SeltTy->isRealFloatingType()) 750 || SeltTy->hasPointerRepresentation()) 751 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 752 753 // FIXME: We should be able to narrow this integer in cases with dead 754 // padding. 755 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size)); 756 } 757 758 return getIndirectReturnResult(State); 759 } 760 761 // Treat an enum type as its underlying type. 762 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 763 RetTy = EnumTy->getDecl()->getIntegerType(); 764 765 return (RetTy->isPromotableIntegerType() ? 766 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 767 } 768 769 static bool isSSEVectorType(ASTContext &Context, QualType Ty) { 770 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128; 771 } 772 773 static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) { 774 const RecordType *RT = Ty->getAs<RecordType>(); 775 if (!RT) 776 return 0; 777 const RecordDecl *RD = RT->getDecl(); 778 779 // If this is a C++ record, check the bases first. 780 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 781 for (const auto &I : CXXRD->bases()) 782 if (!isRecordWithSSEVectorType(Context, I.getType())) 783 return false; 784 785 for (const auto *i : RD->fields()) { 786 QualType FT = i->getType(); 787 788 if (isSSEVectorType(Context, FT)) 789 return true; 790 791 if (isRecordWithSSEVectorType(Context, FT)) 792 return true; 793 } 794 795 return false; 796 } 797 798 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty, 799 unsigned Align) const { 800 // Otherwise, if the alignment is less than or equal to the minimum ABI 801 // alignment, just use the default; the backend will handle this. 802 if (Align <= MinABIStackAlignInBytes) 803 return 0; // Use default alignment. 804 805 // On non-Darwin, the stack type alignment is always 4. 806 if (!IsDarwinVectorABI) { 807 // Set explicit alignment, since we may need to realign the top. 808 return MinABIStackAlignInBytes; 809 } 810 811 // Otherwise, if the type contains an SSE vector type, the alignment is 16. 812 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) || 813 isRecordWithSSEVectorType(getContext(), Ty))) 814 return 16; 815 816 return MinABIStackAlignInBytes; 817 } 818 819 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal, 820 CCState &State) const { 821 if (!ByVal) { 822 if (State.FreeRegs) { 823 --State.FreeRegs; // Non-byval indirects just use one pointer. 824 return ABIArgInfo::getIndirectInReg(0, false); 825 } 826 return ABIArgInfo::getIndirect(0, false); 827 } 828 829 // Compute the byval alignment. 830 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 831 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign); 832 if (StackAlign == 0) 833 return ABIArgInfo::getIndirect(4, /*ByVal=*/true); 834 835 // If the stack alignment is less than the type alignment, realign the 836 // argument. 837 bool Realign = TypeAlign > StackAlign; 838 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true, Realign); 839 } 840 841 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const { 842 const Type *T = isSingleElementStruct(Ty, getContext()); 843 if (!T) 844 T = Ty.getTypePtr(); 845 846 if (const BuiltinType *BT = T->getAs<BuiltinType>()) { 847 BuiltinType::Kind K = BT->getKind(); 848 if (K == BuiltinType::Float || K == BuiltinType::Double) 849 return Float; 850 } 851 return Integer; 852 } 853 854 bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State, 855 bool &NeedsPadding) const { 856 NeedsPadding = false; 857 Class C = classify(Ty); 858 if (C == Float) 859 return false; 860 861 unsigned Size = getContext().getTypeSize(Ty); 862 unsigned SizeInRegs = (Size + 31) / 32; 863 864 if (SizeInRegs == 0) 865 return false; 866 867 if (SizeInRegs > State.FreeRegs) { 868 State.FreeRegs = 0; 869 return false; 870 } 871 872 State.FreeRegs -= SizeInRegs; 873 874 if (State.CC == llvm::CallingConv::X86_FastCall) { 875 if (Size > 32) 876 return false; 877 878 if (Ty->isIntegralOrEnumerationType()) 879 return true; 880 881 if (Ty->isPointerType()) 882 return true; 883 884 if (Ty->isReferenceType()) 885 return true; 886 887 if (State.FreeRegs) 888 NeedsPadding = true; 889 890 return false; 891 } 892 893 return true; 894 } 895 896 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, 897 CCState &State) const { 898 // FIXME: Set alignment on indirect arguments. 899 if (isAggregateTypeForABI(Ty)) { 900 if (const RecordType *RT = Ty->getAs<RecordType>()) { 901 // Check with the C++ ABI first. 902 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 903 if (RAA == CGCXXABI::RAA_Indirect) { 904 return getIndirectResult(Ty, false, State); 905 } else if (RAA == CGCXXABI::RAA_DirectInMemory) { 906 // The field index doesn't matter, we'll fix it up later. 907 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0); 908 } 909 910 // Structs are always byval on win32, regardless of what they contain. 911 if (IsWin32StructABI) 912 return getIndirectResult(Ty, true, State); 913 914 // Structures with flexible arrays are always indirect. 915 if (RT->getDecl()->hasFlexibleArrayMember()) 916 return getIndirectResult(Ty, true, State); 917 } 918 919 // Ignore empty structs/unions. 920 if (isEmptyRecord(getContext(), Ty, true)) 921 return ABIArgInfo::getIgnore(); 922 923 llvm::LLVMContext &LLVMContext = getVMContext(); 924 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 925 bool NeedsPadding; 926 if (shouldUseInReg(Ty, State, NeedsPadding)) { 927 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32; 928 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32); 929 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 930 return ABIArgInfo::getDirectInReg(Result); 931 } 932 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : 0; 933 934 // Expand small (<= 128-bit) record types when we know that the stack layout 935 // of those arguments will match the struct. This is important because the 936 // LLVM backend isn't smart enough to remove byval, which inhibits many 937 // optimizations. 938 if (getContext().getTypeSize(Ty) <= 4*32 && 939 canExpandIndirectArgument(Ty, getContext())) 940 return ABIArgInfo::getExpandWithPadding( 941 State.CC == llvm::CallingConv::X86_FastCall, PaddingType); 942 943 return getIndirectResult(Ty, true, State); 944 } 945 946 if (const VectorType *VT = Ty->getAs<VectorType>()) { 947 // On Darwin, some vectors are passed in memory, we handle this by passing 948 // it as an i8/i16/i32/i64. 949 if (IsDarwinVectorABI) { 950 uint64_t Size = getContext().getTypeSize(Ty); 951 if ((Size == 8 || Size == 16 || Size == 32) || 952 (Size == 64 && VT->getNumElements() == 1)) 953 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 954 Size)); 955 } 956 957 if (IsX86_MMXType(CGT.ConvertType(Ty))) 958 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64)); 959 960 return ABIArgInfo::getDirect(); 961 } 962 963 964 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 965 Ty = EnumTy->getDecl()->getIntegerType(); 966 967 bool NeedsPadding; 968 bool InReg = shouldUseInReg(Ty, State, NeedsPadding); 969 970 if (Ty->isPromotableIntegerType()) { 971 if (InReg) 972 return ABIArgInfo::getExtendInReg(); 973 return ABIArgInfo::getExtend(); 974 } 975 if (InReg) 976 return ABIArgInfo::getDirectInReg(); 977 return ABIArgInfo::getDirect(); 978 } 979 980 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const { 981 CCState State(FI.getCallingConvention()); 982 if (State.CC == llvm::CallingConv::X86_FastCall) 983 State.FreeRegs = 2; 984 else if (FI.getHasRegParm()) 985 State.FreeRegs = FI.getRegParm(); 986 else 987 State.FreeRegs = DefaultNumRegisterParameters; 988 989 FI.getReturnInfo() = 990 classifyReturnType(FI.getReturnType(), State, FI.isInstanceMethod()); 991 992 // On win32, use the x86_cdeclmethodcc convention for cdecl methods that use 993 // sret. This convention swaps the order of the first two parameters behind 994 // the scenes to match MSVC. 995 if (IsWin32StructABI && FI.isInstanceMethod() && 996 FI.getCallingConvention() == llvm::CallingConv::C && 997 FI.getReturnInfo().isIndirect()) 998 FI.setEffectiveCallingConvention(llvm::CallingConv::X86_CDeclMethod); 999 1000 bool UsedInAlloca = false; 1001 for (auto &I : FI.arguments()) { 1002 I.info = classifyArgumentType(I.type, State); 1003 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca); 1004 } 1005 1006 // If we needed to use inalloca for any argument, do a second pass and rewrite 1007 // all the memory arguments to use inalloca. 1008 if (UsedInAlloca) 1009 rewriteWithInAlloca(FI); 1010 } 1011 1012 void 1013 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields, 1014 unsigned &StackOffset, 1015 ABIArgInfo &Info, QualType Type) const { 1016 // Insert padding bytes to respect alignment. For x86_32, each argument is 4 1017 // byte aligned. 1018 unsigned Align = 4U; 1019 if (Info.getKind() == ABIArgInfo::Indirect && Info.getIndirectByVal()) 1020 Align = std::max(Align, Info.getIndirectAlign()); 1021 if (StackOffset & (Align - 1)) { 1022 unsigned OldOffset = StackOffset; 1023 StackOffset = llvm::RoundUpToAlignment(StackOffset, Align); 1024 unsigned NumBytes = StackOffset - OldOffset; 1025 assert(NumBytes); 1026 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext()); 1027 Ty = llvm::ArrayType::get(Ty, NumBytes); 1028 FrameFields.push_back(Ty); 1029 } 1030 1031 Info = ABIArgInfo::getInAlloca(FrameFields.size()); 1032 FrameFields.push_back(CGT.ConvertTypeForMem(Type)); 1033 StackOffset += getContext().getTypeSizeInChars(Type).getQuantity(); 1034 } 1035 1036 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const { 1037 assert(IsWin32StructABI && "inalloca only supported on win32"); 1038 1039 // Build a packed struct type for all of the arguments in memory. 1040 SmallVector<llvm::Type *, 6> FrameFields; 1041 1042 unsigned StackOffset = 0; 1043 1044 // Put the sret parameter into the inalloca struct if it's in memory. 1045 ABIArgInfo &Ret = FI.getReturnInfo(); 1046 if (Ret.isIndirect() && !Ret.getInReg()) { 1047 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType()); 1048 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy); 1049 // On Windows, the hidden sret parameter is always returned in eax. 1050 Ret.setInAllocaSRet(IsWin32StructABI); 1051 } 1052 1053 // Skip the 'this' parameter in ecx. 1054 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end(); 1055 if (FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall) 1056 ++I; 1057 1058 // Put arguments passed in memory into the struct. 1059 for (; I != E; ++I) { 1060 1061 // Leave ignored and inreg arguments alone. 1062 switch (I->info.getKind()) { 1063 case ABIArgInfo::Indirect: 1064 assert(I->info.getIndirectByVal()); 1065 break; 1066 case ABIArgInfo::Ignore: 1067 continue; 1068 case ABIArgInfo::Direct: 1069 case ABIArgInfo::Extend: 1070 if (I->info.getInReg()) 1071 continue; 1072 break; 1073 default: 1074 break; 1075 } 1076 1077 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); 1078 } 1079 1080 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields, 1081 /*isPacked=*/true)); 1082 } 1083 1084 llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 1085 CodeGenFunction &CGF) const { 1086 llvm::Type *BPP = CGF.Int8PtrPtrTy; 1087 1088 CGBuilderTy &Builder = CGF.Builder; 1089 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, 1090 "ap"); 1091 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 1092 1093 // Compute if the address needs to be aligned 1094 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity(); 1095 Align = getTypeStackAlignInBytes(Ty, Align); 1096 Align = std::max(Align, 4U); 1097 if (Align > 4) { 1098 // addr = (addr + align - 1) & -align; 1099 llvm::Value *Offset = 1100 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1); 1101 Addr = CGF.Builder.CreateGEP(Addr, Offset); 1102 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr, 1103 CGF.Int32Ty); 1104 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align); 1105 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask), 1106 Addr->getType(), 1107 "ap.cur.aligned"); 1108 } 1109 1110 llvm::Type *PTy = 1111 llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 1112 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy); 1113 1114 uint64_t Offset = 1115 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align); 1116 llvm::Value *NextAddr = 1117 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), 1118 "ap.next"); 1119 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 1120 1121 return AddrTyped; 1122 } 1123 1124 void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D, 1125 llvm::GlobalValue *GV, 1126 CodeGen::CodeGenModule &CGM) const { 1127 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1128 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 1129 // Get the LLVM function. 1130 llvm::Function *Fn = cast<llvm::Function>(GV); 1131 1132 // Now add the 'alignstack' attribute with a value of 16. 1133 llvm::AttrBuilder B; 1134 B.addStackAlignmentAttr(16); 1135 Fn->addAttributes(llvm::AttributeSet::FunctionIndex, 1136 llvm::AttributeSet::get(CGM.getLLVMContext(), 1137 llvm::AttributeSet::FunctionIndex, 1138 B)); 1139 } 1140 } 1141 } 1142 1143 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable( 1144 CodeGen::CodeGenFunction &CGF, 1145 llvm::Value *Address) const { 1146 CodeGen::CGBuilderTy &Builder = CGF.Builder; 1147 1148 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 1149 1150 // 0-7 are the eight integer registers; the order is different 1151 // on Darwin (for EH), but the range is the same. 1152 // 8 is %eip. 1153 AssignToArrayRange(Builder, Address, Four8, 0, 8); 1154 1155 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) { 1156 // 12-16 are st(0..4). Not sure why we stop at 4. 1157 // These have size 16, which is sizeof(long double) on 1158 // platforms with 8-byte alignment for that type. 1159 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16); 1160 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16); 1161 1162 } else { 1163 // 9 is %eflags, which doesn't get a size on Darwin for some 1164 // reason. 1165 Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9)); 1166 1167 // 11-16 are st(0..5). Not sure why we stop at 5. 1168 // These have size 12, which is sizeof(long double) on 1169 // platforms with 4-byte alignment for that type. 1170 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12); 1171 AssignToArrayRange(Builder, Address, Twelve8, 11, 16); 1172 } 1173 1174 return false; 1175 } 1176 1177 //===----------------------------------------------------------------------===// 1178 // X86-64 ABI Implementation 1179 //===----------------------------------------------------------------------===// 1180 1181 1182 namespace { 1183 /// X86_64ABIInfo - The X86_64 ABI information. 1184 class X86_64ABIInfo : public ABIInfo { 1185 enum Class { 1186 Integer = 0, 1187 SSE, 1188 SSEUp, 1189 X87, 1190 X87Up, 1191 ComplexX87, 1192 NoClass, 1193 Memory 1194 }; 1195 1196 /// merge - Implement the X86_64 ABI merging algorithm. 1197 /// 1198 /// Merge an accumulating classification \arg Accum with a field 1199 /// classification \arg Field. 1200 /// 1201 /// \param Accum - The accumulating classification. This should 1202 /// always be either NoClass or the result of a previous merge 1203 /// call. In addition, this should never be Memory (the caller 1204 /// should just return Memory for the aggregate). 1205 static Class merge(Class Accum, Class Field); 1206 1207 /// postMerge - Implement the X86_64 ABI post merging algorithm. 1208 /// 1209 /// Post merger cleanup, reduces a malformed Hi and Lo pair to 1210 /// final MEMORY or SSE classes when necessary. 1211 /// 1212 /// \param AggregateSize - The size of the current aggregate in 1213 /// the classification process. 1214 /// 1215 /// \param Lo - The classification for the parts of the type 1216 /// residing in the low word of the containing object. 1217 /// 1218 /// \param Hi - The classification for the parts of the type 1219 /// residing in the higher words of the containing object. 1220 /// 1221 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const; 1222 1223 /// classify - Determine the x86_64 register classes in which the 1224 /// given type T should be passed. 1225 /// 1226 /// \param Lo - The classification for the parts of the type 1227 /// residing in the low word of the containing object. 1228 /// 1229 /// \param Hi - The classification for the parts of the type 1230 /// residing in the high word of the containing object. 1231 /// 1232 /// \param OffsetBase - The bit offset of this type in the 1233 /// containing object. Some parameters are classified different 1234 /// depending on whether they straddle an eightbyte boundary. 1235 /// 1236 /// \param isNamedArg - Whether the argument in question is a "named" 1237 /// argument, as used in AMD64-ABI 3.5.7. 1238 /// 1239 /// If a word is unused its result will be NoClass; if a type should 1240 /// be passed in Memory then at least the classification of \arg Lo 1241 /// will be Memory. 1242 /// 1243 /// The \arg Lo class will be NoClass iff the argument is ignored. 1244 /// 1245 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will 1246 /// also be ComplexX87. 1247 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi, 1248 bool isNamedArg) const; 1249 1250 llvm::Type *GetByteVectorType(QualType Ty) const; 1251 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType, 1252 unsigned IROffset, QualType SourceTy, 1253 unsigned SourceOffset) const; 1254 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType, 1255 unsigned IROffset, QualType SourceTy, 1256 unsigned SourceOffset) const; 1257 1258 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 1259 /// such that the argument will be returned in memory. 1260 ABIArgInfo getIndirectReturnResult(QualType Ty) const; 1261 1262 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 1263 /// such that the argument will be passed in memory. 1264 /// 1265 /// \param freeIntRegs - The number of free integer registers remaining 1266 /// available. 1267 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const; 1268 1269 ABIArgInfo classifyReturnType(QualType RetTy) const; 1270 1271 ABIArgInfo classifyArgumentType(QualType Ty, 1272 unsigned freeIntRegs, 1273 unsigned &neededInt, 1274 unsigned &neededSSE, 1275 bool isNamedArg) const; 1276 1277 bool IsIllegalVectorType(QualType Ty) const; 1278 1279 /// The 0.98 ABI revision clarified a lot of ambiguities, 1280 /// unfortunately in ways that were not always consistent with 1281 /// certain previous compilers. In particular, platforms which 1282 /// required strict binary compatibility with older versions of GCC 1283 /// may need to exempt themselves. 1284 bool honorsRevision0_98() const { 1285 return !getTarget().getTriple().isOSDarwin(); 1286 } 1287 1288 bool HasAVX; 1289 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on 1290 // 64-bit hardware. 1291 bool Has64BitPointers; 1292 1293 public: 1294 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) : 1295 ABIInfo(CGT), HasAVX(hasavx), 1296 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) { 1297 } 1298 1299 bool isPassedUsingAVXType(QualType type) const { 1300 unsigned neededInt, neededSSE; 1301 // The freeIntRegs argument doesn't matter here. 1302 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE, 1303 /*isNamedArg*/true); 1304 if (info.isDirect()) { 1305 llvm::Type *ty = info.getCoerceToType(); 1306 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty)) 1307 return (vectorTy->getBitWidth() > 128); 1308 } 1309 return false; 1310 } 1311 1312 void computeInfo(CGFunctionInfo &FI) const override; 1313 1314 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 1315 CodeGenFunction &CGF) const override; 1316 }; 1317 1318 /// WinX86_64ABIInfo - The Windows X86_64 ABI information. 1319 class WinX86_64ABIInfo : public ABIInfo { 1320 1321 ABIArgInfo classify(QualType Ty, bool IsReturnType) const; 1322 1323 public: 1324 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 1325 1326 void computeInfo(CGFunctionInfo &FI) const override; 1327 1328 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 1329 CodeGenFunction &CGF) const override; 1330 }; 1331 1332 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo { 1333 public: 1334 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX) 1335 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)) {} 1336 1337 const X86_64ABIInfo &getABIInfo() const { 1338 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo()); 1339 } 1340 1341 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 1342 return 7; 1343 } 1344 1345 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 1346 llvm::Value *Address) const override { 1347 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 1348 1349 // 0-15 are the 16 integer registers. 1350 // 16 is %rip. 1351 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 1352 return false; 1353 } 1354 1355 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 1356 StringRef Constraint, 1357 llvm::Type* Ty) const override { 1358 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 1359 } 1360 1361 bool isNoProtoCallVariadic(const CallArgList &args, 1362 const FunctionNoProtoType *fnType) const override { 1363 // The default CC on x86-64 sets %al to the number of SSA 1364 // registers used, and GCC sets this when calling an unprototyped 1365 // function, so we override the default behavior. However, don't do 1366 // that when AVX types are involved: the ABI explicitly states it is 1367 // undefined, and it doesn't work in practice because of how the ABI 1368 // defines varargs anyway. 1369 if (fnType->getCallConv() == CC_C) { 1370 bool HasAVXType = false; 1371 for (CallArgList::const_iterator 1372 it = args.begin(), ie = args.end(); it != ie; ++it) { 1373 if (getABIInfo().isPassedUsingAVXType(it->Ty)) { 1374 HasAVXType = true; 1375 break; 1376 } 1377 } 1378 1379 if (!HasAVXType) 1380 return true; 1381 } 1382 1383 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType); 1384 } 1385 1386 llvm::Constant * 1387 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { 1388 unsigned Sig = (0xeb << 0) | // jmp rel8 1389 (0x0a << 8) | // .+0x0c 1390 ('F' << 16) | 1391 ('T' << 24); 1392 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 1393 } 1394 1395 }; 1396 1397 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) { 1398 // If the argument does not end in .lib, automatically add the suffix. This 1399 // matches the behavior of MSVC. 1400 std::string ArgStr = Lib; 1401 if (!Lib.endswith_lower(".lib")) 1402 ArgStr += ".lib"; 1403 return ArgStr; 1404 } 1405 1406 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo { 1407 public: 1408 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 1409 bool d, bool p, bool w, unsigned RegParms) 1410 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {} 1411 1412 void getDependentLibraryOption(llvm::StringRef Lib, 1413 llvm::SmallString<24> &Opt) const override { 1414 Opt = "/DEFAULTLIB:"; 1415 Opt += qualifyWindowsLibrary(Lib); 1416 } 1417 1418 void getDetectMismatchOption(llvm::StringRef Name, 1419 llvm::StringRef Value, 1420 llvm::SmallString<32> &Opt) const override { 1421 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 1422 } 1423 }; 1424 1425 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo { 1426 public: 1427 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 1428 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {} 1429 1430 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 1431 return 7; 1432 } 1433 1434 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 1435 llvm::Value *Address) const override { 1436 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 1437 1438 // 0-15 are the 16 integer registers. 1439 // 16 is %rip. 1440 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 1441 return false; 1442 } 1443 1444 void getDependentLibraryOption(llvm::StringRef Lib, 1445 llvm::SmallString<24> &Opt) const override { 1446 Opt = "/DEFAULTLIB:"; 1447 Opt += qualifyWindowsLibrary(Lib); 1448 } 1449 1450 void getDetectMismatchOption(llvm::StringRef Name, 1451 llvm::StringRef Value, 1452 llvm::SmallString<32> &Opt) const override { 1453 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 1454 } 1455 }; 1456 1457 } 1458 1459 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo, 1460 Class &Hi) const { 1461 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done: 1462 // 1463 // (a) If one of the classes is Memory, the whole argument is passed in 1464 // memory. 1465 // 1466 // (b) If X87UP is not preceded by X87, the whole argument is passed in 1467 // memory. 1468 // 1469 // (c) If the size of the aggregate exceeds two eightbytes and the first 1470 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole 1471 // argument is passed in memory. NOTE: This is necessary to keep the 1472 // ABI working for processors that don't support the __m256 type. 1473 // 1474 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE. 1475 // 1476 // Some of these are enforced by the merging logic. Others can arise 1477 // only with unions; for example: 1478 // union { _Complex double; unsigned; } 1479 // 1480 // Note that clauses (b) and (c) were added in 0.98. 1481 // 1482 if (Hi == Memory) 1483 Lo = Memory; 1484 if (Hi == X87Up && Lo != X87 && honorsRevision0_98()) 1485 Lo = Memory; 1486 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp)) 1487 Lo = Memory; 1488 if (Hi == SSEUp && Lo != SSE) 1489 Hi = SSE; 1490 } 1491 1492 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) { 1493 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is 1494 // classified recursively so that always two fields are 1495 // considered. The resulting class is calculated according to 1496 // the classes of the fields in the eightbyte: 1497 // 1498 // (a) If both classes are equal, this is the resulting class. 1499 // 1500 // (b) If one of the classes is NO_CLASS, the resulting class is 1501 // the other class. 1502 // 1503 // (c) If one of the classes is MEMORY, the result is the MEMORY 1504 // class. 1505 // 1506 // (d) If one of the classes is INTEGER, the result is the 1507 // INTEGER. 1508 // 1509 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class, 1510 // MEMORY is used as class. 1511 // 1512 // (f) Otherwise class SSE is used. 1513 1514 // Accum should never be memory (we should have returned) or 1515 // ComplexX87 (because this cannot be passed in a structure). 1516 assert((Accum != Memory && Accum != ComplexX87) && 1517 "Invalid accumulated classification during merge."); 1518 if (Accum == Field || Field == NoClass) 1519 return Accum; 1520 if (Field == Memory) 1521 return Memory; 1522 if (Accum == NoClass) 1523 return Field; 1524 if (Accum == Integer || Field == Integer) 1525 return Integer; 1526 if (Field == X87 || Field == X87Up || Field == ComplexX87 || 1527 Accum == X87 || Accum == X87Up) 1528 return Memory; 1529 return SSE; 1530 } 1531 1532 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase, 1533 Class &Lo, Class &Hi, bool isNamedArg) const { 1534 // FIXME: This code can be simplified by introducing a simple value class for 1535 // Class pairs with appropriate constructor methods for the various 1536 // situations. 1537 1538 // FIXME: Some of the split computations are wrong; unaligned vectors 1539 // shouldn't be passed in registers for example, so there is no chance they 1540 // can straddle an eightbyte. Verify & simplify. 1541 1542 Lo = Hi = NoClass; 1543 1544 Class &Current = OffsetBase < 64 ? Lo : Hi; 1545 Current = Memory; 1546 1547 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 1548 BuiltinType::Kind k = BT->getKind(); 1549 1550 if (k == BuiltinType::Void) { 1551 Current = NoClass; 1552 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) { 1553 Lo = Integer; 1554 Hi = Integer; 1555 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) { 1556 Current = Integer; 1557 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) || 1558 (k == BuiltinType::LongDouble && 1559 getTarget().getTriple().isOSNaCl())) { 1560 Current = SSE; 1561 } else if (k == BuiltinType::LongDouble) { 1562 Lo = X87; 1563 Hi = X87Up; 1564 } 1565 // FIXME: _Decimal32 and _Decimal64 are SSE. 1566 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp). 1567 return; 1568 } 1569 1570 if (const EnumType *ET = Ty->getAs<EnumType>()) { 1571 // Classify the underlying integer type. 1572 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg); 1573 return; 1574 } 1575 1576 if (Ty->hasPointerRepresentation()) { 1577 Current = Integer; 1578 return; 1579 } 1580 1581 if (Ty->isMemberPointerType()) { 1582 if (Ty->isMemberFunctionPointerType() && Has64BitPointers) 1583 Lo = Hi = Integer; 1584 else 1585 Current = Integer; 1586 return; 1587 } 1588 1589 if (const VectorType *VT = Ty->getAs<VectorType>()) { 1590 uint64_t Size = getContext().getTypeSize(VT); 1591 if (Size == 32) { 1592 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x 1593 // float> as integer. 1594 Current = Integer; 1595 1596 // If this type crosses an eightbyte boundary, it should be 1597 // split. 1598 uint64_t EB_Real = (OffsetBase) / 64; 1599 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64; 1600 if (EB_Real != EB_Imag) 1601 Hi = Lo; 1602 } else if (Size == 64) { 1603 // gcc passes <1 x double> in memory. :( 1604 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) 1605 return; 1606 1607 // gcc passes <1 x long long> as INTEGER. 1608 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) || 1609 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) || 1610 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) || 1611 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong)) 1612 Current = Integer; 1613 else 1614 Current = SSE; 1615 1616 // If this type crosses an eightbyte boundary, it should be 1617 // split. 1618 if (OffsetBase && OffsetBase != 64) 1619 Hi = Lo; 1620 } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) { 1621 // Arguments of 256-bits are split into four eightbyte chunks. The 1622 // least significant one belongs to class SSE and all the others to class 1623 // SSEUP. The original Lo and Hi design considers that types can't be 1624 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense. 1625 // This design isn't correct for 256-bits, but since there're no cases 1626 // where the upper parts would need to be inspected, avoid adding 1627 // complexity and just consider Hi to match the 64-256 part. 1628 // 1629 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in 1630 // registers if they are "named", i.e. not part of the "..." of a 1631 // variadic function. 1632 Lo = SSE; 1633 Hi = SSEUp; 1634 } 1635 return; 1636 } 1637 1638 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 1639 QualType ET = getContext().getCanonicalType(CT->getElementType()); 1640 1641 uint64_t Size = getContext().getTypeSize(Ty); 1642 if (ET->isIntegralOrEnumerationType()) { 1643 if (Size <= 64) 1644 Current = Integer; 1645 else if (Size <= 128) 1646 Lo = Hi = Integer; 1647 } else if (ET == getContext().FloatTy) 1648 Current = SSE; 1649 else if (ET == getContext().DoubleTy || 1650 (ET == getContext().LongDoubleTy && 1651 getTarget().getTriple().isOSNaCl())) 1652 Lo = Hi = SSE; 1653 else if (ET == getContext().LongDoubleTy) 1654 Current = ComplexX87; 1655 1656 // If this complex type crosses an eightbyte boundary then it 1657 // should be split. 1658 uint64_t EB_Real = (OffsetBase) / 64; 1659 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64; 1660 if (Hi == NoClass && EB_Real != EB_Imag) 1661 Hi = Lo; 1662 1663 return; 1664 } 1665 1666 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 1667 // Arrays are treated like structures. 1668 1669 uint64_t Size = getContext().getTypeSize(Ty); 1670 1671 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 1672 // than four eightbytes, ..., it has class MEMORY. 1673 if (Size > 256) 1674 return; 1675 1676 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned 1677 // fields, it has class MEMORY. 1678 // 1679 // Only need to check alignment of array base. 1680 if (OffsetBase % getContext().getTypeAlign(AT->getElementType())) 1681 return; 1682 1683 // Otherwise implement simplified merge. We could be smarter about 1684 // this, but it isn't worth it and would be harder to verify. 1685 Current = NoClass; 1686 uint64_t EltSize = getContext().getTypeSize(AT->getElementType()); 1687 uint64_t ArraySize = AT->getSize().getZExtValue(); 1688 1689 // The only case a 256-bit wide vector could be used is when the array 1690 // contains a single 256-bit element. Since Lo and Hi logic isn't extended 1691 // to work for sizes wider than 128, early check and fallback to memory. 1692 if (Size > 128 && EltSize != 256) 1693 return; 1694 1695 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) { 1696 Class FieldLo, FieldHi; 1697 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg); 1698 Lo = merge(Lo, FieldLo); 1699 Hi = merge(Hi, FieldHi); 1700 if (Lo == Memory || Hi == Memory) 1701 break; 1702 } 1703 1704 postMerge(Size, Lo, Hi); 1705 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification."); 1706 return; 1707 } 1708 1709 if (const RecordType *RT = Ty->getAs<RecordType>()) { 1710 uint64_t Size = getContext().getTypeSize(Ty); 1711 1712 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 1713 // than four eightbytes, ..., it has class MEMORY. 1714 if (Size > 256) 1715 return; 1716 1717 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial 1718 // copy constructor or a non-trivial destructor, it is passed by invisible 1719 // reference. 1720 if (getRecordArgABI(RT, getCXXABI())) 1721 return; 1722 1723 const RecordDecl *RD = RT->getDecl(); 1724 1725 // Assume variable sized types are passed in memory. 1726 if (RD->hasFlexibleArrayMember()) 1727 return; 1728 1729 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 1730 1731 // Reset Lo class, this will be recomputed. 1732 Current = NoClass; 1733 1734 // If this is a C++ record, classify the bases first. 1735 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 1736 for (const auto &I : CXXRD->bases()) { 1737 assert(!I.isVirtual() && !I.getType()->isDependentType() && 1738 "Unexpected base class!"); 1739 const CXXRecordDecl *Base = 1740 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 1741 1742 // Classify this field. 1743 // 1744 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a 1745 // single eightbyte, each is classified separately. Each eightbyte gets 1746 // initialized to class NO_CLASS. 1747 Class FieldLo, FieldHi; 1748 uint64_t Offset = 1749 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base)); 1750 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg); 1751 Lo = merge(Lo, FieldLo); 1752 Hi = merge(Hi, FieldHi); 1753 if (Lo == Memory || Hi == Memory) 1754 break; 1755 } 1756 } 1757 1758 // Classify the fields one at a time, merging the results. 1759 unsigned idx = 0; 1760 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 1761 i != e; ++i, ++idx) { 1762 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 1763 bool BitField = i->isBitField(); 1764 1765 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than 1766 // four eightbytes, or it contains unaligned fields, it has class MEMORY. 1767 // 1768 // The only case a 256-bit wide vector could be used is when the struct 1769 // contains a single 256-bit element. Since Lo and Hi logic isn't extended 1770 // to work for sizes wider than 128, early check and fallback to memory. 1771 // 1772 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) { 1773 Lo = Memory; 1774 return; 1775 } 1776 // Note, skip this test for bit-fields, see below. 1777 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) { 1778 Lo = Memory; 1779 return; 1780 } 1781 1782 // Classify this field. 1783 // 1784 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate 1785 // exceeds a single eightbyte, each is classified 1786 // separately. Each eightbyte gets initialized to class 1787 // NO_CLASS. 1788 Class FieldLo, FieldHi; 1789 1790 // Bit-fields require special handling, they do not force the 1791 // structure to be passed in memory even if unaligned, and 1792 // therefore they can straddle an eightbyte. 1793 if (BitField) { 1794 // Ignore padding bit-fields. 1795 if (i->isUnnamedBitfield()) 1796 continue; 1797 1798 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 1799 uint64_t Size = i->getBitWidthValue(getContext()); 1800 1801 uint64_t EB_Lo = Offset / 64; 1802 uint64_t EB_Hi = (Offset + Size - 1) / 64; 1803 1804 if (EB_Lo) { 1805 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes."); 1806 FieldLo = NoClass; 1807 FieldHi = Integer; 1808 } else { 1809 FieldLo = Integer; 1810 FieldHi = EB_Hi ? Integer : NoClass; 1811 } 1812 } else 1813 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg); 1814 Lo = merge(Lo, FieldLo); 1815 Hi = merge(Hi, FieldHi); 1816 if (Lo == Memory || Hi == Memory) 1817 break; 1818 } 1819 1820 postMerge(Size, Lo, Hi); 1821 } 1822 } 1823 1824 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const { 1825 // If this is a scalar LLVM value then assume LLVM will pass it in the right 1826 // place naturally. 1827 if (!isAggregateTypeForABI(Ty)) { 1828 // Treat an enum type as its underlying type. 1829 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 1830 Ty = EnumTy->getDecl()->getIntegerType(); 1831 1832 return (Ty->isPromotableIntegerType() ? 1833 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 1834 } 1835 1836 return ABIArgInfo::getIndirect(0); 1837 } 1838 1839 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const { 1840 if (const VectorType *VecTy = Ty->getAs<VectorType>()) { 1841 uint64_t Size = getContext().getTypeSize(VecTy); 1842 unsigned LargestVector = HasAVX ? 256 : 128; 1843 if (Size <= 64 || Size > LargestVector) 1844 return true; 1845 } 1846 1847 return false; 1848 } 1849 1850 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty, 1851 unsigned freeIntRegs) const { 1852 // If this is a scalar LLVM value then assume LLVM will pass it in the right 1853 // place naturally. 1854 // 1855 // This assumption is optimistic, as there could be free registers available 1856 // when we need to pass this argument in memory, and LLVM could try to pass 1857 // the argument in the free register. This does not seem to happen currently, 1858 // but this code would be much safer if we could mark the argument with 1859 // 'onstack'. See PR12193. 1860 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) { 1861 // Treat an enum type as its underlying type. 1862 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 1863 Ty = EnumTy->getDecl()->getIntegerType(); 1864 1865 return (Ty->isPromotableIntegerType() ? 1866 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 1867 } 1868 1869 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 1870 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 1871 1872 // Compute the byval alignment. We specify the alignment of the byval in all 1873 // cases so that the mid-level optimizer knows the alignment of the byval. 1874 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U); 1875 1876 // Attempt to avoid passing indirect results using byval when possible. This 1877 // is important for good codegen. 1878 // 1879 // We do this by coercing the value into a scalar type which the backend can 1880 // handle naturally (i.e., without using byval). 1881 // 1882 // For simplicity, we currently only do this when we have exhausted all of the 1883 // free integer registers. Doing this when there are free integer registers 1884 // would require more care, as we would have to ensure that the coerced value 1885 // did not claim the unused register. That would require either reording the 1886 // arguments to the function (so that any subsequent inreg values came first), 1887 // or only doing this optimization when there were no following arguments that 1888 // might be inreg. 1889 // 1890 // We currently expect it to be rare (particularly in well written code) for 1891 // arguments to be passed on the stack when there are still free integer 1892 // registers available (this would typically imply large structs being passed 1893 // by value), so this seems like a fair tradeoff for now. 1894 // 1895 // We can revisit this if the backend grows support for 'onstack' parameter 1896 // attributes. See PR12193. 1897 if (freeIntRegs == 0) { 1898 uint64_t Size = getContext().getTypeSize(Ty); 1899 1900 // If this type fits in an eightbyte, coerce it into the matching integral 1901 // type, which will end up on the stack (with alignment 8). 1902 if (Align == 8 && Size <= 64) 1903 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 1904 Size)); 1905 } 1906 1907 return ABIArgInfo::getIndirect(Align); 1908 } 1909 1910 /// GetByteVectorType - The ABI specifies that a value should be passed in an 1911 /// full vector XMM/YMM register. Pick an LLVM IR type that will be passed as a 1912 /// vector register. 1913 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const { 1914 llvm::Type *IRType = CGT.ConvertType(Ty); 1915 1916 // Wrapper structs that just contain vectors are passed just like vectors, 1917 // strip them off if present. 1918 llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType); 1919 while (STy && STy->getNumElements() == 1) { 1920 IRType = STy->getElementType(0); 1921 STy = dyn_cast<llvm::StructType>(IRType); 1922 } 1923 1924 // If the preferred type is a 16-byte vector, prefer to pass it. 1925 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){ 1926 llvm::Type *EltTy = VT->getElementType(); 1927 unsigned BitWidth = VT->getBitWidth(); 1928 if ((BitWidth >= 128 && BitWidth <= 256) && 1929 (EltTy->isFloatTy() || EltTy->isDoubleTy() || 1930 EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) || 1931 EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) || 1932 EltTy->isIntegerTy(128))) 1933 return VT; 1934 } 1935 1936 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2); 1937 } 1938 1939 /// BitsContainNoUserData - Return true if the specified [start,end) bit range 1940 /// is known to either be off the end of the specified type or being in 1941 /// alignment padding. The user type specified is known to be at most 128 bits 1942 /// in size, and have passed through X86_64ABIInfo::classify with a successful 1943 /// classification that put one of the two halves in the INTEGER class. 1944 /// 1945 /// It is conservatively correct to return false. 1946 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit, 1947 unsigned EndBit, ASTContext &Context) { 1948 // If the bytes being queried are off the end of the type, there is no user 1949 // data hiding here. This handles analysis of builtins, vectors and other 1950 // types that don't contain interesting padding. 1951 unsigned TySize = (unsigned)Context.getTypeSize(Ty); 1952 if (TySize <= StartBit) 1953 return true; 1954 1955 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { 1956 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType()); 1957 unsigned NumElts = (unsigned)AT->getSize().getZExtValue(); 1958 1959 // Check each element to see if the element overlaps with the queried range. 1960 for (unsigned i = 0; i != NumElts; ++i) { 1961 // If the element is after the span we care about, then we're done.. 1962 unsigned EltOffset = i*EltSize; 1963 if (EltOffset >= EndBit) break; 1964 1965 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0; 1966 if (!BitsContainNoUserData(AT->getElementType(), EltStart, 1967 EndBit-EltOffset, Context)) 1968 return false; 1969 } 1970 // If it overlaps no elements, then it is safe to process as padding. 1971 return true; 1972 } 1973 1974 if (const RecordType *RT = Ty->getAs<RecordType>()) { 1975 const RecordDecl *RD = RT->getDecl(); 1976 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 1977 1978 // If this is a C++ record, check the bases first. 1979 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 1980 for (const auto &I : CXXRD->bases()) { 1981 assert(!I.isVirtual() && !I.getType()->isDependentType() && 1982 "Unexpected base class!"); 1983 const CXXRecordDecl *Base = 1984 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 1985 1986 // If the base is after the span we care about, ignore it. 1987 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base)); 1988 if (BaseOffset >= EndBit) continue; 1989 1990 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0; 1991 if (!BitsContainNoUserData(I.getType(), BaseStart, 1992 EndBit-BaseOffset, Context)) 1993 return false; 1994 } 1995 } 1996 1997 // Verify that no field has data that overlaps the region of interest. Yes 1998 // this could be sped up a lot by being smarter about queried fields, 1999 // however we're only looking at structs up to 16 bytes, so we don't care 2000 // much. 2001 unsigned idx = 0; 2002 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 2003 i != e; ++i, ++idx) { 2004 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx); 2005 2006 // If we found a field after the region we care about, then we're done. 2007 if (FieldOffset >= EndBit) break; 2008 2009 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0; 2010 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset, 2011 Context)) 2012 return false; 2013 } 2014 2015 // If nothing in this record overlapped the area of interest, then we're 2016 // clean. 2017 return true; 2018 } 2019 2020 return false; 2021 } 2022 2023 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a 2024 /// float member at the specified offset. For example, {int,{float}} has a 2025 /// float at offset 4. It is conservatively correct for this routine to return 2026 /// false. 2027 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset, 2028 const llvm::DataLayout &TD) { 2029 // Base case if we find a float. 2030 if (IROffset == 0 && IRType->isFloatTy()) 2031 return true; 2032 2033 // If this is a struct, recurse into the field at the specified offset. 2034 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 2035 const llvm::StructLayout *SL = TD.getStructLayout(STy); 2036 unsigned Elt = SL->getElementContainingOffset(IROffset); 2037 IROffset -= SL->getElementOffset(Elt); 2038 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD); 2039 } 2040 2041 // If this is an array, recurse into the field at the specified offset. 2042 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 2043 llvm::Type *EltTy = ATy->getElementType(); 2044 unsigned EltSize = TD.getTypeAllocSize(EltTy); 2045 IROffset -= IROffset/EltSize*EltSize; 2046 return ContainsFloatAtOffset(EltTy, IROffset, TD); 2047 } 2048 2049 return false; 2050 } 2051 2052 2053 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the 2054 /// low 8 bytes of an XMM register, corresponding to the SSE class. 2055 llvm::Type *X86_64ABIInfo:: 2056 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset, 2057 QualType SourceTy, unsigned SourceOffset) const { 2058 // The only three choices we have are either double, <2 x float>, or float. We 2059 // pass as float if the last 4 bytes is just padding. This happens for 2060 // structs that contain 3 floats. 2061 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32, 2062 SourceOffset*8+64, getContext())) 2063 return llvm::Type::getFloatTy(getVMContext()); 2064 2065 // We want to pass as <2 x float> if the LLVM IR type contains a float at 2066 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the 2067 // case. 2068 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) && 2069 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout())) 2070 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2); 2071 2072 return llvm::Type::getDoubleTy(getVMContext()); 2073 } 2074 2075 2076 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in 2077 /// an 8-byte GPR. This means that we either have a scalar or we are talking 2078 /// about the high or low part of an up-to-16-byte struct. This routine picks 2079 /// the best LLVM IR type to represent this, which may be i64 or may be anything 2080 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*, 2081 /// etc). 2082 /// 2083 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for 2084 /// the source type. IROffset is an offset in bytes into the LLVM IR type that 2085 /// the 8-byte value references. PrefType may be null. 2086 /// 2087 /// SourceTy is the source level type for the entire argument. SourceOffset is 2088 /// an offset into this that we're processing (which is always either 0 or 8). 2089 /// 2090 llvm::Type *X86_64ABIInfo:: 2091 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset, 2092 QualType SourceTy, unsigned SourceOffset) const { 2093 // If we're dealing with an un-offset LLVM IR type, then it means that we're 2094 // returning an 8-byte unit starting with it. See if we can safely use it. 2095 if (IROffset == 0) { 2096 // Pointers and int64's always fill the 8-byte unit. 2097 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) || 2098 IRType->isIntegerTy(64)) 2099 return IRType; 2100 2101 // If we have a 1/2/4-byte integer, we can use it only if the rest of the 2102 // goodness in the source type is just tail padding. This is allowed to 2103 // kick in for struct {double,int} on the int, but not on 2104 // struct{double,int,int} because we wouldn't return the second int. We 2105 // have to do this analysis on the source type because we can't depend on 2106 // unions being lowered a specific way etc. 2107 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) || 2108 IRType->isIntegerTy(32) || 2109 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) { 2110 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 : 2111 cast<llvm::IntegerType>(IRType)->getBitWidth(); 2112 2113 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth, 2114 SourceOffset*8+64, getContext())) 2115 return IRType; 2116 } 2117 } 2118 2119 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 2120 // If this is a struct, recurse into the field at the specified offset. 2121 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy); 2122 if (IROffset < SL->getSizeInBytes()) { 2123 unsigned FieldIdx = SL->getElementContainingOffset(IROffset); 2124 IROffset -= SL->getElementOffset(FieldIdx); 2125 2126 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset, 2127 SourceTy, SourceOffset); 2128 } 2129 } 2130 2131 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 2132 llvm::Type *EltTy = ATy->getElementType(); 2133 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy); 2134 unsigned EltOffset = IROffset/EltSize*EltSize; 2135 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy, 2136 SourceOffset); 2137 } 2138 2139 // Okay, we don't have any better idea of what to pass, so we pass this in an 2140 // integer register that isn't too big to fit the rest of the struct. 2141 unsigned TySizeInBytes = 2142 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity(); 2143 2144 assert(TySizeInBytes != SourceOffset && "Empty field?"); 2145 2146 // It is always safe to classify this as an integer type up to i64 that 2147 // isn't larger than the structure. 2148 return llvm::IntegerType::get(getVMContext(), 2149 std::min(TySizeInBytes-SourceOffset, 8U)*8); 2150 } 2151 2152 2153 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally 2154 /// be used as elements of a two register pair to pass or return, return a 2155 /// first class aggregate to represent them. For example, if the low part of 2156 /// a by-value argument should be passed as i32* and the high part as float, 2157 /// return {i32*, float}. 2158 static llvm::Type * 2159 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi, 2160 const llvm::DataLayout &TD) { 2161 // In order to correctly satisfy the ABI, we need to the high part to start 2162 // at offset 8. If the high and low parts we inferred are both 4-byte types 2163 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have 2164 // the second element at offset 8. Check for this: 2165 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo); 2166 unsigned HiAlign = TD.getABITypeAlignment(Hi); 2167 unsigned HiStart = llvm::DataLayout::RoundUpAlignment(LoSize, HiAlign); 2168 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!"); 2169 2170 // To handle this, we have to increase the size of the low part so that the 2171 // second element will start at an 8 byte offset. We can't increase the size 2172 // of the second element because it might make us access off the end of the 2173 // struct. 2174 if (HiStart != 8) { 2175 // There are only two sorts of types the ABI generation code can produce for 2176 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32. 2177 // Promote these to a larger type. 2178 if (Lo->isFloatTy()) 2179 Lo = llvm::Type::getDoubleTy(Lo->getContext()); 2180 else { 2181 assert(Lo->isIntegerTy() && "Invalid/unknown lo type"); 2182 Lo = llvm::Type::getInt64Ty(Lo->getContext()); 2183 } 2184 } 2185 2186 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL); 2187 2188 2189 // Verify that the second element is at an 8-byte offset. 2190 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 && 2191 "Invalid x86-64 argument pair!"); 2192 return Result; 2193 } 2194 2195 ABIArgInfo X86_64ABIInfo:: 2196 classifyReturnType(QualType RetTy) const { 2197 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the 2198 // classification algorithm. 2199 X86_64ABIInfo::Class Lo, Hi; 2200 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true); 2201 2202 // Check some invariants. 2203 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 2204 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 2205 2206 llvm::Type *ResType = 0; 2207 switch (Lo) { 2208 case NoClass: 2209 if (Hi == NoClass) 2210 return ABIArgInfo::getIgnore(); 2211 // If the low part is just padding, it takes no register, leave ResType 2212 // null. 2213 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 2214 "Unknown missing lo part"); 2215 break; 2216 2217 case SSEUp: 2218 case X87Up: 2219 llvm_unreachable("Invalid classification for lo word."); 2220 2221 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via 2222 // hidden argument. 2223 case Memory: 2224 return getIndirectReturnResult(RetTy); 2225 2226 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next 2227 // available register of the sequence %rax, %rdx is used. 2228 case Integer: 2229 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 2230 2231 // If we have a sign or zero extended integer, make sure to return Extend 2232 // so that the parameter gets the right LLVM IR attributes. 2233 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 2234 // Treat an enum type as its underlying type. 2235 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 2236 RetTy = EnumTy->getDecl()->getIntegerType(); 2237 2238 if (RetTy->isIntegralOrEnumerationType() && 2239 RetTy->isPromotableIntegerType()) 2240 return ABIArgInfo::getExtend(); 2241 } 2242 break; 2243 2244 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next 2245 // available SSE register of the sequence %xmm0, %xmm1 is used. 2246 case SSE: 2247 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 2248 break; 2249 2250 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is 2251 // returned on the X87 stack in %st0 as 80-bit x87 number. 2252 case X87: 2253 ResType = llvm::Type::getX86_FP80Ty(getVMContext()); 2254 break; 2255 2256 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real 2257 // part of the value is returned in %st0 and the imaginary part in 2258 // %st1. 2259 case ComplexX87: 2260 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification."); 2261 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()), 2262 llvm::Type::getX86_FP80Ty(getVMContext()), 2263 NULL); 2264 break; 2265 } 2266 2267 llvm::Type *HighPart = 0; 2268 switch (Hi) { 2269 // Memory was handled previously and X87 should 2270 // never occur as a hi class. 2271 case Memory: 2272 case X87: 2273 llvm_unreachable("Invalid classification for hi word."); 2274 2275 case ComplexX87: // Previously handled. 2276 case NoClass: 2277 break; 2278 2279 case Integer: 2280 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 2281 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 2282 return ABIArgInfo::getDirect(HighPart, 8); 2283 break; 2284 case SSE: 2285 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 2286 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 2287 return ABIArgInfo::getDirect(HighPart, 8); 2288 break; 2289 2290 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte 2291 // is passed in the next available eightbyte chunk if the last used 2292 // vector register. 2293 // 2294 // SSEUP should always be preceded by SSE, just widen. 2295 case SSEUp: 2296 assert(Lo == SSE && "Unexpected SSEUp classification."); 2297 ResType = GetByteVectorType(RetTy); 2298 break; 2299 2300 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is 2301 // returned together with the previous X87 value in %st0. 2302 case X87Up: 2303 // If X87Up is preceded by X87, we don't need to do 2304 // anything. However, in some cases with unions it may not be 2305 // preceded by X87. In such situations we follow gcc and pass the 2306 // extra bits in an SSE reg. 2307 if (Lo != X87) { 2308 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 2309 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 2310 return ABIArgInfo::getDirect(HighPart, 8); 2311 } 2312 break; 2313 } 2314 2315 // If a high part was specified, merge it together with the low part. It is 2316 // known to pass in the high eightbyte of the result. We do this by forming a 2317 // first class struct aggregate with the high and low part: {low, high} 2318 if (HighPart) 2319 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 2320 2321 return ABIArgInfo::getDirect(ResType); 2322 } 2323 2324 ABIArgInfo X86_64ABIInfo::classifyArgumentType( 2325 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE, 2326 bool isNamedArg) 2327 const 2328 { 2329 X86_64ABIInfo::Class Lo, Hi; 2330 classify(Ty, 0, Lo, Hi, isNamedArg); 2331 2332 // Check some invariants. 2333 // FIXME: Enforce these by construction. 2334 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 2335 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 2336 2337 neededInt = 0; 2338 neededSSE = 0; 2339 llvm::Type *ResType = 0; 2340 switch (Lo) { 2341 case NoClass: 2342 if (Hi == NoClass) 2343 return ABIArgInfo::getIgnore(); 2344 // If the low part is just padding, it takes no register, leave ResType 2345 // null. 2346 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 2347 "Unknown missing lo part"); 2348 break; 2349 2350 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument 2351 // on the stack. 2352 case Memory: 2353 2354 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or 2355 // COMPLEX_X87, it is passed in memory. 2356 case X87: 2357 case ComplexX87: 2358 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect) 2359 ++neededInt; 2360 return getIndirectResult(Ty, freeIntRegs); 2361 2362 case SSEUp: 2363 case X87Up: 2364 llvm_unreachable("Invalid classification for lo word."); 2365 2366 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next 2367 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 2368 // and %r9 is used. 2369 case Integer: 2370 ++neededInt; 2371 2372 // Pick an 8-byte type based on the preferred type. 2373 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0); 2374 2375 // If we have a sign or zero extended integer, make sure to return Extend 2376 // so that the parameter gets the right LLVM IR attributes. 2377 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 2378 // Treat an enum type as its underlying type. 2379 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 2380 Ty = EnumTy->getDecl()->getIntegerType(); 2381 2382 if (Ty->isIntegralOrEnumerationType() && 2383 Ty->isPromotableIntegerType()) 2384 return ABIArgInfo::getExtend(); 2385 } 2386 2387 break; 2388 2389 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next 2390 // available SSE register is used, the registers are taken in the 2391 // order from %xmm0 to %xmm7. 2392 case SSE: { 2393 llvm::Type *IRType = CGT.ConvertType(Ty); 2394 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0); 2395 ++neededSSE; 2396 break; 2397 } 2398 } 2399 2400 llvm::Type *HighPart = 0; 2401 switch (Hi) { 2402 // Memory was handled previously, ComplexX87 and X87 should 2403 // never occur as hi classes, and X87Up must be preceded by X87, 2404 // which is passed in memory. 2405 case Memory: 2406 case X87: 2407 case ComplexX87: 2408 llvm_unreachable("Invalid classification for hi word."); 2409 2410 case NoClass: break; 2411 2412 case Integer: 2413 ++neededInt; 2414 // Pick an 8-byte type based on the preferred type. 2415 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 2416 2417 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 2418 return ABIArgInfo::getDirect(HighPart, 8); 2419 break; 2420 2421 // X87Up generally doesn't occur here (long double is passed in 2422 // memory), except in situations involving unions. 2423 case X87Up: 2424 case SSE: 2425 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 2426 2427 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 2428 return ABIArgInfo::getDirect(HighPart, 8); 2429 2430 ++neededSSE; 2431 break; 2432 2433 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the 2434 // eightbyte is passed in the upper half of the last used SSE 2435 // register. This only happens when 128-bit vectors are passed. 2436 case SSEUp: 2437 assert(Lo == SSE && "Unexpected SSEUp classification"); 2438 ResType = GetByteVectorType(Ty); 2439 break; 2440 } 2441 2442 // If a high part was specified, merge it together with the low part. It is 2443 // known to pass in the high eightbyte of the result. We do this by forming a 2444 // first class struct aggregate with the high and low part: {low, high} 2445 if (HighPart) 2446 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 2447 2448 return ABIArgInfo::getDirect(ResType); 2449 } 2450 2451 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 2452 2453 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 2454 2455 // Keep track of the number of assigned registers. 2456 unsigned freeIntRegs = 6, freeSSERegs = 8; 2457 2458 // If the return value is indirect, then the hidden argument is consuming one 2459 // integer register. 2460 if (FI.getReturnInfo().isIndirect()) 2461 --freeIntRegs; 2462 2463 bool isVariadic = FI.isVariadic(); 2464 unsigned numRequiredArgs = 0; 2465 if (isVariadic) 2466 numRequiredArgs = FI.getRequiredArgs().getNumRequiredArgs(); 2467 2468 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers 2469 // get assigned (in left-to-right order) for passing as follows... 2470 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 2471 it != ie; ++it) { 2472 bool isNamedArg = true; 2473 if (isVariadic) 2474 isNamedArg = (it - FI.arg_begin()) < 2475 static_cast<signed>(numRequiredArgs); 2476 2477 unsigned neededInt, neededSSE; 2478 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt, 2479 neededSSE, isNamedArg); 2480 2481 // AMD64-ABI 3.2.3p3: If there are no registers available for any 2482 // eightbyte of an argument, the whole argument is passed on the 2483 // stack. If registers have already been assigned for some 2484 // eightbytes of such an argument, the assignments get reverted. 2485 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) { 2486 freeIntRegs -= neededInt; 2487 freeSSERegs -= neededSSE; 2488 } else { 2489 it->info = getIndirectResult(it->type, freeIntRegs); 2490 } 2491 } 2492 } 2493 2494 static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr, 2495 QualType Ty, 2496 CodeGenFunction &CGF) { 2497 llvm::Value *overflow_arg_area_p = 2498 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p"); 2499 llvm::Value *overflow_arg_area = 2500 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area"); 2501 2502 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16 2503 // byte boundary if alignment needed by type exceeds 8 byte boundary. 2504 // It isn't stated explicitly in the standard, but in practice we use 2505 // alignment greater than 16 where necessary. 2506 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8; 2507 if (Align > 8) { 2508 // overflow_arg_area = (overflow_arg_area + align - 1) & -align; 2509 llvm::Value *Offset = 2510 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1); 2511 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset); 2512 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area, 2513 CGF.Int64Ty); 2514 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align); 2515 overflow_arg_area = 2516 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask), 2517 overflow_arg_area->getType(), 2518 "overflow_arg_area.align"); 2519 } 2520 2521 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area. 2522 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 2523 llvm::Value *Res = 2524 CGF.Builder.CreateBitCast(overflow_arg_area, 2525 llvm::PointerType::getUnqual(LTy)); 2526 2527 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to: 2528 // l->overflow_arg_area + sizeof(type). 2529 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to 2530 // an 8 byte boundary. 2531 2532 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8; 2533 llvm::Value *Offset = 2534 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7); 2535 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset, 2536 "overflow_arg_area.next"); 2537 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p); 2538 2539 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type. 2540 return Res; 2541 } 2542 2543 llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 2544 CodeGenFunction &CGF) const { 2545 // Assume that va_list type is correct; should be pointer to LLVM type: 2546 // struct { 2547 // i32 gp_offset; 2548 // i32 fp_offset; 2549 // i8* overflow_arg_area; 2550 // i8* reg_save_area; 2551 // }; 2552 unsigned neededInt, neededSSE; 2553 2554 Ty = CGF.getContext().getCanonicalType(Ty); 2555 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE, 2556 /*isNamedArg*/false); 2557 2558 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed 2559 // in the registers. If not go to step 7. 2560 if (!neededInt && !neededSSE) 2561 return EmitVAArgFromMemory(VAListAddr, Ty, CGF); 2562 2563 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of 2564 // general purpose registers needed to pass type and num_fp to hold 2565 // the number of floating point registers needed. 2566 2567 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into 2568 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or 2569 // l->fp_offset > 304 - num_fp * 16 go to step 7. 2570 // 2571 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of 2572 // register save space). 2573 2574 llvm::Value *InRegs = 0; 2575 llvm::Value *gp_offset_p = 0, *gp_offset = 0; 2576 llvm::Value *fp_offset_p = 0, *fp_offset = 0; 2577 if (neededInt) { 2578 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p"); 2579 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset"); 2580 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8); 2581 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp"); 2582 } 2583 2584 if (neededSSE) { 2585 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p"); 2586 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset"); 2587 llvm::Value *FitsInFP = 2588 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16); 2589 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp"); 2590 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP; 2591 } 2592 2593 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 2594 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 2595 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 2596 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 2597 2598 // Emit code to load the value if it was passed in registers. 2599 2600 CGF.EmitBlock(InRegBlock); 2601 2602 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with 2603 // an offset of l->gp_offset and/or l->fp_offset. This may require 2604 // copying to a temporary location in case the parameter is passed 2605 // in different register classes or requires an alignment greater 2606 // than 8 for general purpose registers and 16 for XMM registers. 2607 // 2608 // FIXME: This really results in shameful code when we end up needing to 2609 // collect arguments from different places; often what should result in a 2610 // simple assembling of a structure from scattered addresses has many more 2611 // loads than necessary. Can we clean this up? 2612 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 2613 llvm::Value *RegAddr = 2614 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3), 2615 "reg_save_area"); 2616 if (neededInt && neededSSE) { 2617 // FIXME: Cleanup. 2618 assert(AI.isDirect() && "Unexpected ABI info for mixed regs"); 2619 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType()); 2620 llvm::Value *Tmp = CGF.CreateMemTemp(Ty); 2621 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo()); 2622 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs"); 2623 llvm::Type *TyLo = ST->getElementType(0); 2624 llvm::Type *TyHi = ST->getElementType(1); 2625 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) && 2626 "Unexpected ABI info for mixed regs"); 2627 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo); 2628 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi); 2629 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset); 2630 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset); 2631 llvm::Value *RegLoAddr = TyLo->isFloatingPointTy() ? FPAddr : GPAddr; 2632 llvm::Value *RegHiAddr = TyLo->isFloatingPointTy() ? GPAddr : FPAddr; 2633 llvm::Value *V = 2634 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo)); 2635 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 2636 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi)); 2637 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 2638 2639 RegAddr = CGF.Builder.CreateBitCast(Tmp, 2640 llvm::PointerType::getUnqual(LTy)); 2641 } else if (neededInt) { 2642 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset); 2643 RegAddr = CGF.Builder.CreateBitCast(RegAddr, 2644 llvm::PointerType::getUnqual(LTy)); 2645 2646 // Copy to a temporary if necessary to ensure the appropriate alignment. 2647 std::pair<CharUnits, CharUnits> SizeAlign = 2648 CGF.getContext().getTypeInfoInChars(Ty); 2649 uint64_t TySize = SizeAlign.first.getQuantity(); 2650 unsigned TyAlign = SizeAlign.second.getQuantity(); 2651 if (TyAlign > 8) { 2652 llvm::Value *Tmp = CGF.CreateMemTemp(Ty); 2653 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false); 2654 RegAddr = Tmp; 2655 } 2656 } else if (neededSSE == 1) { 2657 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset); 2658 RegAddr = CGF.Builder.CreateBitCast(RegAddr, 2659 llvm::PointerType::getUnqual(LTy)); 2660 } else { 2661 assert(neededSSE == 2 && "Invalid number of needed registers!"); 2662 // SSE registers are spaced 16 bytes apart in the register save 2663 // area, we need to collect the two eightbytes together. 2664 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset); 2665 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16); 2666 llvm::Type *DoubleTy = CGF.DoubleTy; 2667 llvm::Type *DblPtrTy = 2668 llvm::PointerType::getUnqual(DoubleTy); 2669 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, NULL); 2670 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty); 2671 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo()); 2672 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo, 2673 DblPtrTy)); 2674 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 2675 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi, 2676 DblPtrTy)); 2677 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 2678 RegAddr = CGF.Builder.CreateBitCast(Tmp, 2679 llvm::PointerType::getUnqual(LTy)); 2680 } 2681 2682 // AMD64-ABI 3.5.7p5: Step 5. Set: 2683 // l->gp_offset = l->gp_offset + num_gp * 8 2684 // l->fp_offset = l->fp_offset + num_fp * 16. 2685 if (neededInt) { 2686 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8); 2687 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset), 2688 gp_offset_p); 2689 } 2690 if (neededSSE) { 2691 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16); 2692 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset), 2693 fp_offset_p); 2694 } 2695 CGF.EmitBranch(ContBlock); 2696 2697 // Emit code to load the value if it was passed in memory. 2698 2699 CGF.EmitBlock(InMemBlock); 2700 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF); 2701 2702 // Return the appropriate result. 2703 2704 CGF.EmitBlock(ContBlock); 2705 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2, 2706 "vaarg.addr"); 2707 ResAddr->addIncoming(RegAddr, InRegBlock); 2708 ResAddr->addIncoming(MemAddr, InMemBlock); 2709 return ResAddr; 2710 } 2711 2712 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, bool IsReturnType) const { 2713 2714 if (Ty->isVoidType()) 2715 return ABIArgInfo::getIgnore(); 2716 2717 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 2718 Ty = EnumTy->getDecl()->getIntegerType(); 2719 2720 uint64_t Size = getContext().getTypeSize(Ty); 2721 2722 if (const RecordType *RT = Ty->getAs<RecordType>()) { 2723 if (IsReturnType) { 2724 if (isRecordReturnIndirect(RT, getCXXABI())) 2725 return ABIArgInfo::getIndirect(0, false); 2726 } else { 2727 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI())) 2728 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 2729 } 2730 2731 if (RT->getDecl()->hasFlexibleArrayMember()) 2732 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 2733 2734 // FIXME: mingw-w64-gcc emits 128-bit struct as i128 2735 if (Size == 128 && getTarget().getTriple().getOS() == llvm::Triple::MinGW32) 2736 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 2737 Size)); 2738 2739 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 2740 // not 1, 2, 4, or 8 bytes, must be passed by reference." 2741 if (Size <= 64 && 2742 (Size & (Size - 1)) == 0) 2743 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 2744 Size)); 2745 2746 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 2747 } 2748 2749 if (Ty->isPromotableIntegerType()) 2750 return ABIArgInfo::getExtend(); 2751 2752 return ABIArgInfo::getDirect(); 2753 } 2754 2755 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 2756 2757 QualType RetTy = FI.getReturnType(); 2758 FI.getReturnInfo() = classify(RetTy, true); 2759 2760 for (auto &I : FI.arguments()) 2761 I.info = classify(I.type, false); 2762 } 2763 2764 llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 2765 CodeGenFunction &CGF) const { 2766 llvm::Type *BPP = CGF.Int8PtrPtrTy; 2767 2768 CGBuilderTy &Builder = CGF.Builder; 2769 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, 2770 "ap"); 2771 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 2772 llvm::Type *PTy = 2773 llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 2774 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy); 2775 2776 uint64_t Offset = 2777 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8); 2778 llvm::Value *NextAddr = 2779 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), 2780 "ap.next"); 2781 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 2782 2783 return AddrTyped; 2784 } 2785 2786 namespace { 2787 2788 class NaClX86_64ABIInfo : public ABIInfo { 2789 public: 2790 NaClX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX) 2791 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, HasAVX) {} 2792 void computeInfo(CGFunctionInfo &FI) const override; 2793 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 2794 CodeGenFunction &CGF) const override; 2795 private: 2796 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv. 2797 X86_64ABIInfo NInfo; // Used for everything else. 2798 }; 2799 2800 class NaClX86_64TargetCodeGenInfo : public TargetCodeGenInfo { 2801 public: 2802 NaClX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX) 2803 : TargetCodeGenInfo(new NaClX86_64ABIInfo(CGT, HasAVX)) {} 2804 }; 2805 2806 } 2807 2808 void NaClX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 2809 if (FI.getASTCallingConvention() == CC_PnaclCall) 2810 PInfo.computeInfo(FI); 2811 else 2812 NInfo.computeInfo(FI); 2813 } 2814 2815 llvm::Value *NaClX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 2816 CodeGenFunction &CGF) const { 2817 // Always use the native convention; calling pnacl-style varargs functions 2818 // is unuspported. 2819 return NInfo.EmitVAArg(VAListAddr, Ty, CGF); 2820 } 2821 2822 2823 // PowerPC-32 2824 2825 namespace { 2826 class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo { 2827 public: 2828 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {} 2829 2830 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 2831 // This is recovered from gcc output. 2832 return 1; // r1 is the dedicated stack pointer 2833 } 2834 2835 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2836 llvm::Value *Address) const override; 2837 }; 2838 2839 } 2840 2841 bool 2842 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2843 llvm::Value *Address) const { 2844 // This is calculated from the LLVM and GCC tables and verified 2845 // against gcc output. AFAIK all ABIs use the same encoding. 2846 2847 CodeGen::CGBuilderTy &Builder = CGF.Builder; 2848 2849 llvm::IntegerType *i8 = CGF.Int8Ty; 2850 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 2851 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 2852 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16); 2853 2854 // 0-31: r0-31, the 4-byte general-purpose registers 2855 AssignToArrayRange(Builder, Address, Four8, 0, 31); 2856 2857 // 32-63: fp0-31, the 8-byte floating-point registers 2858 AssignToArrayRange(Builder, Address, Eight8, 32, 63); 2859 2860 // 64-76 are various 4-byte special-purpose registers: 2861 // 64: mq 2862 // 65: lr 2863 // 66: ctr 2864 // 67: ap 2865 // 68-75 cr0-7 2866 // 76: xer 2867 AssignToArrayRange(Builder, Address, Four8, 64, 76); 2868 2869 // 77-108: v0-31, the 16-byte vector registers 2870 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108); 2871 2872 // 109: vrsave 2873 // 110: vscr 2874 // 111: spe_acc 2875 // 112: spefscr 2876 // 113: sfp 2877 AssignToArrayRange(Builder, Address, Four8, 109, 113); 2878 2879 return false; 2880 } 2881 2882 // PowerPC-64 2883 2884 namespace { 2885 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information. 2886 class PPC64_SVR4_ABIInfo : public DefaultABIInfo { 2887 2888 public: 2889 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 2890 2891 bool isPromotableTypeForABI(QualType Ty) const; 2892 2893 ABIArgInfo classifyReturnType(QualType RetTy) const; 2894 ABIArgInfo classifyArgumentType(QualType Ty) const; 2895 2896 // TODO: We can add more logic to computeInfo to improve performance. 2897 // Example: For aggregate arguments that fit in a register, we could 2898 // use getDirectInReg (as is done below for structs containing a single 2899 // floating-point value) to avoid pushing them to memory on function 2900 // entry. This would require changing the logic in PPCISelLowering 2901 // when lowering the parameters in the caller and args in the callee. 2902 void computeInfo(CGFunctionInfo &FI) const override { 2903 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 2904 for (auto &I : FI.arguments()) { 2905 // We rely on the default argument classification for the most part. 2906 // One exception: An aggregate containing a single floating-point 2907 // or vector item must be passed in a register if one is available. 2908 const Type *T = isSingleElementStruct(I.type, getContext()); 2909 if (T) { 2910 const BuiltinType *BT = T->getAs<BuiltinType>(); 2911 if (T->isVectorType() || (BT && BT->isFloatingPoint())) { 2912 QualType QT(T, 0); 2913 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT)); 2914 continue; 2915 } 2916 } 2917 I.info = classifyArgumentType(I.type); 2918 } 2919 } 2920 2921 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 2922 CodeGenFunction &CGF) const override; 2923 }; 2924 2925 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo { 2926 public: 2927 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT) 2928 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT)) {} 2929 2930 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 2931 // This is recovered from gcc output. 2932 return 1; // r1 is the dedicated stack pointer 2933 } 2934 2935 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2936 llvm::Value *Address) const override; 2937 }; 2938 2939 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo { 2940 public: 2941 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {} 2942 2943 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 2944 // This is recovered from gcc output. 2945 return 1; // r1 is the dedicated stack pointer 2946 } 2947 2948 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2949 llvm::Value *Address) const override; 2950 }; 2951 2952 } 2953 2954 // Return true if the ABI requires Ty to be passed sign- or zero- 2955 // extended to 64 bits. 2956 bool 2957 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const { 2958 // Treat an enum type as its underlying type. 2959 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 2960 Ty = EnumTy->getDecl()->getIntegerType(); 2961 2962 // Promotable integer types are required to be promoted by the ABI. 2963 if (Ty->isPromotableIntegerType()) 2964 return true; 2965 2966 // In addition to the usual promotable integer types, we also need to 2967 // extend all 32-bit types, since the ABI requires promotion to 64 bits. 2968 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 2969 switch (BT->getKind()) { 2970 case BuiltinType::Int: 2971 case BuiltinType::UInt: 2972 return true; 2973 default: 2974 break; 2975 } 2976 2977 return false; 2978 } 2979 2980 ABIArgInfo 2981 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const { 2982 if (Ty->isAnyComplexType()) 2983 return ABIArgInfo::getDirect(); 2984 2985 if (isAggregateTypeForABI(Ty)) { 2986 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 2987 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 2988 2989 return ABIArgInfo::getIndirect(0); 2990 } 2991 2992 return (isPromotableTypeForABI(Ty) ? 2993 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 2994 } 2995 2996 ABIArgInfo 2997 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const { 2998 if (RetTy->isVoidType()) 2999 return ABIArgInfo::getIgnore(); 3000 3001 if (RetTy->isAnyComplexType()) 3002 return ABIArgInfo::getDirect(); 3003 3004 if (isAggregateTypeForABI(RetTy)) 3005 return ABIArgInfo::getIndirect(0); 3006 3007 return (isPromotableTypeForABI(RetTy) ? 3008 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 3009 } 3010 3011 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine. 3012 llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr, 3013 QualType Ty, 3014 CodeGenFunction &CGF) const { 3015 llvm::Type *BP = CGF.Int8PtrTy; 3016 llvm::Type *BPP = CGF.Int8PtrPtrTy; 3017 3018 CGBuilderTy &Builder = CGF.Builder; 3019 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); 3020 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 3021 3022 // Update the va_list pointer. The pointer should be bumped by the 3023 // size of the object. We can trust getTypeSize() except for a complex 3024 // type whose base type is smaller than a doubleword. For these, the 3025 // size of the object is 16 bytes; see below for further explanation. 3026 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8; 3027 QualType BaseTy; 3028 unsigned CplxBaseSize = 0; 3029 3030 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 3031 BaseTy = CTy->getElementType(); 3032 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8; 3033 if (CplxBaseSize < 8) 3034 SizeInBytes = 16; 3035 } 3036 3037 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8); 3038 llvm::Value *NextAddr = 3039 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), 3040 "ap.next"); 3041 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 3042 3043 // If we have a complex type and the base type is smaller than 8 bytes, 3044 // the ABI calls for the real and imaginary parts to be right-adjusted 3045 // in separate doublewords. However, Clang expects us to produce a 3046 // pointer to a structure with the two parts packed tightly. So generate 3047 // loads of the real and imaginary parts relative to the va_list pointer, 3048 // and store them to a temporary structure. 3049 if (CplxBaseSize && CplxBaseSize < 8) { 3050 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty); 3051 llvm::Value *ImagAddr = RealAddr; 3052 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize)); 3053 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize)); 3054 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy)); 3055 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy); 3056 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy); 3057 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal"); 3058 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag"); 3059 llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty), 3060 "vacplx"); 3061 llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real"); 3062 llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag"); 3063 Builder.CreateStore(Real, RealPtr, false); 3064 Builder.CreateStore(Imag, ImagPtr, false); 3065 return Ptr; 3066 } 3067 3068 // If the argument is smaller than 8 bytes, it is right-adjusted in 3069 // its doubleword slot. Adjust the pointer to pick it up from the 3070 // correct offset. 3071 if (SizeInBytes < 8) { 3072 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty); 3073 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes)); 3074 Addr = Builder.CreateIntToPtr(AddrAsInt, BP); 3075 } 3076 3077 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 3078 return Builder.CreateBitCast(Addr, PTy); 3079 } 3080 3081 static bool 3082 PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 3083 llvm::Value *Address) { 3084 // This is calculated from the LLVM and GCC tables and verified 3085 // against gcc output. AFAIK all ABIs use the same encoding. 3086 3087 CodeGen::CGBuilderTy &Builder = CGF.Builder; 3088 3089 llvm::IntegerType *i8 = CGF.Int8Ty; 3090 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 3091 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 3092 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16); 3093 3094 // 0-31: r0-31, the 8-byte general-purpose registers 3095 AssignToArrayRange(Builder, Address, Eight8, 0, 31); 3096 3097 // 32-63: fp0-31, the 8-byte floating-point registers 3098 AssignToArrayRange(Builder, Address, Eight8, 32, 63); 3099 3100 // 64-76 are various 4-byte special-purpose registers: 3101 // 64: mq 3102 // 65: lr 3103 // 66: ctr 3104 // 67: ap 3105 // 68-75 cr0-7 3106 // 76: xer 3107 AssignToArrayRange(Builder, Address, Four8, 64, 76); 3108 3109 // 77-108: v0-31, the 16-byte vector registers 3110 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108); 3111 3112 // 109: vrsave 3113 // 110: vscr 3114 // 111: spe_acc 3115 // 112: spefscr 3116 // 113: sfp 3117 AssignToArrayRange(Builder, Address, Four8, 109, 113); 3118 3119 return false; 3120 } 3121 3122 bool 3123 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable( 3124 CodeGen::CodeGenFunction &CGF, 3125 llvm::Value *Address) const { 3126 3127 return PPC64_initDwarfEHRegSizeTable(CGF, Address); 3128 } 3129 3130 bool 3131 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 3132 llvm::Value *Address) const { 3133 3134 return PPC64_initDwarfEHRegSizeTable(CGF, Address); 3135 } 3136 3137 //===----------------------------------------------------------------------===// 3138 // ARM ABI Implementation 3139 //===----------------------------------------------------------------------===// 3140 3141 namespace { 3142 3143 class ARMABIInfo : public ABIInfo { 3144 public: 3145 enum ABIKind { 3146 APCS = 0, 3147 AAPCS = 1, 3148 AAPCS_VFP 3149 }; 3150 3151 private: 3152 ABIKind Kind; 3153 mutable int VFPRegs[16]; 3154 const unsigned NumVFPs; 3155 const unsigned NumGPRs; 3156 mutable unsigned AllocatedGPRs; 3157 mutable unsigned AllocatedVFPs; 3158 3159 public: 3160 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind), 3161 NumVFPs(16), NumGPRs(4) { 3162 setRuntimeCC(); 3163 resetAllocatedRegs(); 3164 } 3165 3166 bool isEABI() const { 3167 switch (getTarget().getTriple().getEnvironment()) { 3168 case llvm::Triple::Android: 3169 case llvm::Triple::EABI: 3170 case llvm::Triple::EABIHF: 3171 case llvm::Triple::GNUEABI: 3172 case llvm::Triple::GNUEABIHF: 3173 return true; 3174 default: 3175 return false; 3176 } 3177 } 3178 3179 bool isEABIHF() const { 3180 switch (getTarget().getTriple().getEnvironment()) { 3181 case llvm::Triple::EABIHF: 3182 case llvm::Triple::GNUEABIHF: 3183 return true; 3184 default: 3185 return false; 3186 } 3187 } 3188 3189 ABIKind getABIKind() const { return Kind; } 3190 3191 private: 3192 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const; 3193 ABIArgInfo classifyArgumentType(QualType RetTy, bool &IsHA, bool isVariadic, 3194 bool &IsCPRC) const; 3195 bool isIllegalVectorType(QualType Ty) const; 3196 3197 void computeInfo(CGFunctionInfo &FI) const override; 3198 3199 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3200 CodeGenFunction &CGF) const override; 3201 3202 llvm::CallingConv::ID getLLVMDefaultCC() const; 3203 llvm::CallingConv::ID getABIDefaultCC() const; 3204 void setRuntimeCC(); 3205 3206 void markAllocatedGPRs(unsigned Alignment, unsigned NumRequired) const; 3207 void markAllocatedVFPs(unsigned Alignment, unsigned NumRequired) const; 3208 void resetAllocatedRegs(void) const; 3209 }; 3210 3211 class ARMTargetCodeGenInfo : public TargetCodeGenInfo { 3212 public: 3213 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) 3214 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {} 3215 3216 const ARMABIInfo &getABIInfo() const { 3217 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo()); 3218 } 3219 3220 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 3221 return 13; 3222 } 3223 3224 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 3225 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue"; 3226 } 3227 3228 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 3229 llvm::Value *Address) const override { 3230 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 3231 3232 // 0-15 are the 16 integer registers. 3233 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15); 3234 return false; 3235 } 3236 3237 unsigned getSizeOfUnwindException() const override { 3238 if (getABIInfo().isEABI()) return 88; 3239 return TargetCodeGenInfo::getSizeOfUnwindException(); 3240 } 3241 3242 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 3243 CodeGen::CodeGenModule &CGM) const override { 3244 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 3245 if (!FD) 3246 return; 3247 3248 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>(); 3249 if (!Attr) 3250 return; 3251 3252 const char *Kind; 3253 switch (Attr->getInterrupt()) { 3254 case ARMInterruptAttr::Generic: Kind = ""; break; 3255 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break; 3256 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break; 3257 case ARMInterruptAttr::SWI: Kind = "SWI"; break; 3258 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break; 3259 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break; 3260 } 3261 3262 llvm::Function *Fn = cast<llvm::Function>(GV); 3263 3264 Fn->addFnAttr("interrupt", Kind); 3265 3266 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS) 3267 return; 3268 3269 // AAPCS guarantees that sp will be 8-byte aligned on any public interface, 3270 // however this is not necessarily true on taking any interrupt. Instruct 3271 // the backend to perform a realignment as part of the function prologue. 3272 llvm::AttrBuilder B; 3273 B.addStackAlignmentAttr(8); 3274 Fn->addAttributes(llvm::AttributeSet::FunctionIndex, 3275 llvm::AttributeSet::get(CGM.getLLVMContext(), 3276 llvm::AttributeSet::FunctionIndex, 3277 B)); 3278 } 3279 3280 }; 3281 3282 } 3283 3284 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const { 3285 // To correctly handle Homogeneous Aggregate, we need to keep track of the 3286 // VFP registers allocated so far. 3287 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive 3288 // VFP registers of the appropriate type unallocated then the argument is 3289 // allocated to the lowest-numbered sequence of such registers. 3290 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are 3291 // unallocated are marked as unavailable. 3292 resetAllocatedRegs(); 3293 3294 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic()); 3295 for (auto &I : FI.arguments()) { 3296 unsigned PreAllocationVFPs = AllocatedVFPs; 3297 unsigned PreAllocationGPRs = AllocatedGPRs; 3298 bool IsHA = false; 3299 bool IsCPRC = false; 3300 // 6.1.2.3 There is one VFP co-processor register class using registers 3301 // s0-s15 (d0-d7) for passing arguments. 3302 I.info = classifyArgumentType(I.type, IsHA, FI.isVariadic(), IsCPRC); 3303 assert((IsCPRC || !IsHA) && "Homogeneous aggregates must be CPRCs"); 3304 // If we do not have enough VFP registers for the HA, any VFP registers 3305 // that are unallocated are marked as unavailable. To achieve this, we add 3306 // padding of (NumVFPs - PreAllocationVFP) floats. 3307 // Note that IsHA will only be set when using the AAPCS-VFP calling convention, 3308 // and the callee is not variadic. 3309 if (IsHA && AllocatedVFPs > NumVFPs && PreAllocationVFPs < NumVFPs) { 3310 llvm::Type *PaddingTy = llvm::ArrayType::get( 3311 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocationVFPs); 3312 I.info = ABIArgInfo::getExpandWithPadding(false, PaddingTy); 3313 } 3314 3315 // If we have allocated some arguments onto the stack (due to running 3316 // out of VFP registers), we cannot split an argument between GPRs and 3317 // the stack. If this situation occurs, we add padding to prevent the 3318 // GPRs from being used. In this situiation, the current argument could 3319 // only be allocated by rule C.8, so rule C.6 would mark these GPRs as 3320 // unusable anyway. 3321 const bool StackUsed = PreAllocationGPRs > NumGPRs || PreAllocationVFPs > NumVFPs; 3322 if (!IsCPRC && PreAllocationGPRs < NumGPRs && AllocatedGPRs > NumGPRs && StackUsed) { 3323 llvm::Type *PaddingTy = llvm::ArrayType::get( 3324 llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreAllocationGPRs); 3325 I.info = ABIArgInfo::getExpandWithPadding(false, PaddingTy); 3326 } 3327 } 3328 3329 // Always honor user-specified calling convention. 3330 if (FI.getCallingConvention() != llvm::CallingConv::C) 3331 return; 3332 3333 llvm::CallingConv::ID cc = getRuntimeCC(); 3334 if (cc != llvm::CallingConv::C) 3335 FI.setEffectiveCallingConvention(cc); 3336 } 3337 3338 /// Return the default calling convention that LLVM will use. 3339 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const { 3340 // The default calling convention that LLVM will infer. 3341 if (isEABIHF()) 3342 return llvm::CallingConv::ARM_AAPCS_VFP; 3343 else if (isEABI()) 3344 return llvm::CallingConv::ARM_AAPCS; 3345 else 3346 return llvm::CallingConv::ARM_APCS; 3347 } 3348 3349 /// Return the calling convention that our ABI would like us to use 3350 /// as the C calling convention. 3351 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const { 3352 switch (getABIKind()) { 3353 case APCS: return llvm::CallingConv::ARM_APCS; 3354 case AAPCS: return llvm::CallingConv::ARM_AAPCS; 3355 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 3356 } 3357 llvm_unreachable("bad ABI kind"); 3358 } 3359 3360 void ARMABIInfo::setRuntimeCC() { 3361 assert(getRuntimeCC() == llvm::CallingConv::C); 3362 3363 // Don't muddy up the IR with a ton of explicit annotations if 3364 // they'd just match what LLVM will infer from the triple. 3365 llvm::CallingConv::ID abiCC = getABIDefaultCC(); 3366 if (abiCC != getLLVMDefaultCC()) 3367 RuntimeCC = abiCC; 3368 } 3369 3370 /// isHomogeneousAggregate - Return true if a type is an AAPCS-VFP homogeneous 3371 /// aggregate. If HAMembers is non-null, the number of base elements 3372 /// contained in the type is returned through it; this is used for the 3373 /// recursive calls that check aggregate component types. 3374 static bool isHomogeneousAggregate(QualType Ty, const Type *&Base, 3375 ASTContext &Context, 3376 uint64_t *HAMembers = 0) { 3377 uint64_t Members = 0; 3378 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { 3379 if (!isHomogeneousAggregate(AT->getElementType(), Base, Context, &Members)) 3380 return false; 3381 Members *= AT->getSize().getZExtValue(); 3382 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 3383 const RecordDecl *RD = RT->getDecl(); 3384 if (RD->hasFlexibleArrayMember()) 3385 return false; 3386 3387 Members = 0; 3388 for (const auto *FD : RD->fields()) { 3389 uint64_t FldMembers; 3390 if (!isHomogeneousAggregate(FD->getType(), Base, Context, &FldMembers)) 3391 return false; 3392 3393 Members = (RD->isUnion() ? 3394 std::max(Members, FldMembers) : Members + FldMembers); 3395 } 3396 } else { 3397 Members = 1; 3398 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 3399 Members = 2; 3400 Ty = CT->getElementType(); 3401 } 3402 3403 // Homogeneous aggregates for AAPCS-VFP must have base types of float, 3404 // double, or 64-bit or 128-bit vectors. 3405 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 3406 if (BT->getKind() != BuiltinType::Float && 3407 BT->getKind() != BuiltinType::Double && 3408 BT->getKind() != BuiltinType::LongDouble) 3409 return false; 3410 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 3411 unsigned VecSize = Context.getTypeSize(VT); 3412 if (VecSize != 64 && VecSize != 128) 3413 return false; 3414 } else { 3415 return false; 3416 } 3417 3418 // The base type must be the same for all members. Vector types of the 3419 // same total size are treated as being equivalent here. 3420 const Type *TyPtr = Ty.getTypePtr(); 3421 if (!Base) 3422 Base = TyPtr; 3423 3424 if (Base != TyPtr) { 3425 // Homogeneous aggregates are defined as containing members with the 3426 // same machine type. There are two cases in which two members have 3427 // different TypePtrs but the same machine type: 3428 3429 // 1) Vectors of the same length, regardless of the type and number 3430 // of their members. 3431 const bool SameLengthVectors = Base->isVectorType() && TyPtr->isVectorType() 3432 && (Context.getTypeSize(Base) == Context.getTypeSize(TyPtr)); 3433 3434 // 2) In the 32-bit AAPCS, `double' and `long double' have the same 3435 // machine type. This is not the case for the 64-bit AAPCS. 3436 const bool SameSizeDoubles = 3437 ( ( Base->isSpecificBuiltinType(BuiltinType::Double) 3438 && TyPtr->isSpecificBuiltinType(BuiltinType::LongDouble)) 3439 || ( Base->isSpecificBuiltinType(BuiltinType::LongDouble) 3440 && TyPtr->isSpecificBuiltinType(BuiltinType::Double))) 3441 && (Context.getTypeSize(Base) == Context.getTypeSize(TyPtr)); 3442 3443 if (!SameLengthVectors && !SameSizeDoubles) 3444 return false; 3445 } 3446 } 3447 3448 // Homogeneous Aggregates can have at most 4 members of the base type. 3449 if (HAMembers) 3450 *HAMembers = Members; 3451 3452 return (Members > 0 && Members <= 4); 3453 } 3454 3455 /// markAllocatedVFPs - update VFPRegs according to the alignment and 3456 /// number of VFP registers (unit is S register) requested. 3457 void ARMABIInfo::markAllocatedVFPs(unsigned Alignment, 3458 unsigned NumRequired) const { 3459 // Early Exit. 3460 if (AllocatedVFPs >= 16) { 3461 // We use AllocatedVFP > 16 to signal that some CPRCs were allocated on 3462 // the stack. 3463 AllocatedVFPs = 17; 3464 return; 3465 } 3466 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive 3467 // VFP registers of the appropriate type unallocated then the argument is 3468 // allocated to the lowest-numbered sequence of such registers. 3469 for (unsigned I = 0; I < 16; I += Alignment) { 3470 bool FoundSlot = true; 3471 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++) 3472 if (J >= 16 || VFPRegs[J]) { 3473 FoundSlot = false; 3474 break; 3475 } 3476 if (FoundSlot) { 3477 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++) 3478 VFPRegs[J] = 1; 3479 AllocatedVFPs += NumRequired; 3480 return; 3481 } 3482 } 3483 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are 3484 // unallocated are marked as unavailable. 3485 for (unsigned I = 0; I < 16; I++) 3486 VFPRegs[I] = 1; 3487 AllocatedVFPs = 17; // We do not have enough VFP registers. 3488 } 3489 3490 /// Update AllocatedGPRs to record the number of general purpose registers 3491 /// which have been allocated. It is valid for AllocatedGPRs to go above 4, 3492 /// this represents arguments being stored on the stack. 3493 void ARMABIInfo::markAllocatedGPRs(unsigned Alignment, 3494 unsigned NumRequired) const { 3495 assert((Alignment == 1 || Alignment == 2) && "Alignment must be 4 or 8 bytes"); 3496 3497 if (Alignment == 2 && AllocatedGPRs & 0x1) 3498 AllocatedGPRs += 1; 3499 3500 AllocatedGPRs += NumRequired; 3501 } 3502 3503 void ARMABIInfo::resetAllocatedRegs(void) const { 3504 AllocatedGPRs = 0; 3505 AllocatedVFPs = 0; 3506 for (unsigned i = 0; i < NumVFPs; ++i) 3507 VFPRegs[i] = 0; 3508 } 3509 3510 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool &IsHA, 3511 bool isVariadic, 3512 bool &IsCPRC) const { 3513 // We update number of allocated VFPs according to 3514 // 6.1.2.1 The following argument types are VFP CPRCs: 3515 // A single-precision floating-point type (including promoted 3516 // half-precision types); A double-precision floating-point type; 3517 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate 3518 // with a Base Type of a single- or double-precision floating-point type, 3519 // 64-bit containerized vectors or 128-bit containerized vectors with one 3520 // to four Elements. 3521 3522 // Handle illegal vector types here. 3523 if (isIllegalVectorType(Ty)) { 3524 uint64_t Size = getContext().getTypeSize(Ty); 3525 if (Size <= 32) { 3526 llvm::Type *ResType = 3527 llvm::Type::getInt32Ty(getVMContext()); 3528 markAllocatedGPRs(1, 1); 3529 return ABIArgInfo::getDirect(ResType); 3530 } 3531 if (Size == 64) { 3532 llvm::Type *ResType = llvm::VectorType::get( 3533 llvm::Type::getInt32Ty(getVMContext()), 2); 3534 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic){ 3535 markAllocatedGPRs(2, 2); 3536 } else { 3537 markAllocatedVFPs(2, 2); 3538 IsCPRC = true; 3539 } 3540 return ABIArgInfo::getDirect(ResType); 3541 } 3542 if (Size == 128) { 3543 llvm::Type *ResType = llvm::VectorType::get( 3544 llvm::Type::getInt32Ty(getVMContext()), 4); 3545 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic) { 3546 markAllocatedGPRs(2, 4); 3547 } else { 3548 markAllocatedVFPs(4, 4); 3549 IsCPRC = true; 3550 } 3551 return ABIArgInfo::getDirect(ResType); 3552 } 3553 markAllocatedGPRs(1, 1); 3554 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 3555 } 3556 // Update VFPRegs for legal vector types. 3557 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) { 3558 if (const VectorType *VT = Ty->getAs<VectorType>()) { 3559 uint64_t Size = getContext().getTypeSize(VT); 3560 // Size of a legal vector should be power of 2 and above 64. 3561 markAllocatedVFPs(Size >= 128 ? 4 : 2, Size / 32); 3562 IsCPRC = true; 3563 } 3564 } 3565 // Update VFPRegs for floating point types. 3566 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) { 3567 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 3568 if (BT->getKind() == BuiltinType::Half || 3569 BT->getKind() == BuiltinType::Float) { 3570 markAllocatedVFPs(1, 1); 3571 IsCPRC = true; 3572 } 3573 if (BT->getKind() == BuiltinType::Double || 3574 BT->getKind() == BuiltinType::LongDouble) { 3575 markAllocatedVFPs(2, 2); 3576 IsCPRC = true; 3577 } 3578 } 3579 } 3580 3581 if (!isAggregateTypeForABI(Ty)) { 3582 // Treat an enum type as its underlying type. 3583 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) { 3584 Ty = EnumTy->getDecl()->getIntegerType(); 3585 } 3586 3587 unsigned Size = getContext().getTypeSize(Ty); 3588 if (!IsCPRC) 3589 markAllocatedGPRs(Size > 32 ? 2 : 1, (Size + 31) / 32); 3590 return (Ty->isPromotableIntegerType() ? 3591 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 3592 } 3593 3594 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 3595 markAllocatedGPRs(1, 1); 3596 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 3597 } 3598 3599 // Ignore empty records. 3600 if (isEmptyRecord(getContext(), Ty, true)) 3601 return ABIArgInfo::getIgnore(); 3602 3603 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) { 3604 // Homogeneous Aggregates need to be expanded when we can fit the aggregate 3605 // into VFP registers. 3606 const Type *Base = 0; 3607 uint64_t Members = 0; 3608 if (isHomogeneousAggregate(Ty, Base, getContext(), &Members)) { 3609 assert(Base && "Base class should be set for homogeneous aggregate"); 3610 // Base can be a floating-point or a vector. 3611 if (Base->isVectorType()) { 3612 // ElementSize is in number of floats. 3613 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4; 3614 markAllocatedVFPs(ElementSize, 3615 Members * ElementSize); 3616 } else if (Base->isSpecificBuiltinType(BuiltinType::Float)) 3617 markAllocatedVFPs(1, Members); 3618 else { 3619 assert(Base->isSpecificBuiltinType(BuiltinType::Double) || 3620 Base->isSpecificBuiltinType(BuiltinType::LongDouble)); 3621 markAllocatedVFPs(2, Members * 2); 3622 } 3623 IsHA = true; 3624 IsCPRC = true; 3625 return ABIArgInfo::getExpand(); 3626 } 3627 } 3628 3629 // Support byval for ARM. 3630 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at 3631 // most 8-byte. We realign the indirect argument if type alignment is bigger 3632 // than ABI alignment. 3633 uint64_t ABIAlign = 4; 3634 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8; 3635 if (getABIKind() == ARMABIInfo::AAPCS_VFP || 3636 getABIKind() == ARMABIInfo::AAPCS) 3637 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8); 3638 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) { 3639 // Update Allocated GPRs 3640 markAllocatedGPRs(1, 1); 3641 return ABIArgInfo::getIndirect(TyAlign, /*ByVal=*/true, 3642 /*Realign=*/TyAlign > ABIAlign); 3643 } 3644 3645 // Otherwise, pass by coercing to a structure of the appropriate size. 3646 llvm::Type* ElemTy; 3647 unsigned SizeRegs; 3648 // FIXME: Try to match the types of the arguments more accurately where 3649 // we can. 3650 if (getContext().getTypeAlign(Ty) <= 32) { 3651 ElemTy = llvm::Type::getInt32Ty(getVMContext()); 3652 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32; 3653 markAllocatedGPRs(1, SizeRegs); 3654 } else { 3655 ElemTy = llvm::Type::getInt64Ty(getVMContext()); 3656 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64; 3657 markAllocatedGPRs(2, SizeRegs * 2); 3658 } 3659 3660 llvm::Type *STy = 3661 llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL); 3662 return ABIArgInfo::getDirect(STy); 3663 } 3664 3665 static bool isIntegerLikeType(QualType Ty, ASTContext &Context, 3666 llvm::LLVMContext &VMContext) { 3667 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure 3668 // is called integer-like if its size is less than or equal to one word, and 3669 // the offset of each of its addressable sub-fields is zero. 3670 3671 uint64_t Size = Context.getTypeSize(Ty); 3672 3673 // Check that the type fits in a word. 3674 if (Size > 32) 3675 return false; 3676 3677 // FIXME: Handle vector types! 3678 if (Ty->isVectorType()) 3679 return false; 3680 3681 // Float types are never treated as "integer like". 3682 if (Ty->isRealFloatingType()) 3683 return false; 3684 3685 // If this is a builtin or pointer type then it is ok. 3686 if (Ty->getAs<BuiltinType>() || Ty->isPointerType()) 3687 return true; 3688 3689 // Small complex integer types are "integer like". 3690 if (const ComplexType *CT = Ty->getAs<ComplexType>()) 3691 return isIntegerLikeType(CT->getElementType(), Context, VMContext); 3692 3693 // Single element and zero sized arrays should be allowed, by the definition 3694 // above, but they are not. 3695 3696 // Otherwise, it must be a record type. 3697 const RecordType *RT = Ty->getAs<RecordType>(); 3698 if (!RT) return false; 3699 3700 // Ignore records with flexible arrays. 3701 const RecordDecl *RD = RT->getDecl(); 3702 if (RD->hasFlexibleArrayMember()) 3703 return false; 3704 3705 // Check that all sub-fields are at offset 0, and are themselves "integer 3706 // like". 3707 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 3708 3709 bool HadField = false; 3710 unsigned idx = 0; 3711 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3712 i != e; ++i, ++idx) { 3713 const FieldDecl *FD = *i; 3714 3715 // Bit-fields are not addressable, we only need to verify they are "integer 3716 // like". We still have to disallow a subsequent non-bitfield, for example: 3717 // struct { int : 0; int x } 3718 // is non-integer like according to gcc. 3719 if (FD->isBitField()) { 3720 if (!RD->isUnion()) 3721 HadField = true; 3722 3723 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 3724 return false; 3725 3726 continue; 3727 } 3728 3729 // Check if this field is at offset 0. 3730 if (Layout.getFieldOffset(idx) != 0) 3731 return false; 3732 3733 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 3734 return false; 3735 3736 // Only allow at most one field in a structure. This doesn't match the 3737 // wording above, but follows gcc in situations with a field following an 3738 // empty structure. 3739 if (!RD->isUnion()) { 3740 if (HadField) 3741 return false; 3742 3743 HadField = true; 3744 } 3745 } 3746 3747 return true; 3748 } 3749 3750 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, 3751 bool isVariadic) const { 3752 if (RetTy->isVoidType()) 3753 return ABIArgInfo::getIgnore(); 3754 3755 // Large vector types should be returned via memory. 3756 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) { 3757 markAllocatedGPRs(1, 1); 3758 return ABIArgInfo::getIndirect(0); 3759 } 3760 3761 if (!isAggregateTypeForABI(RetTy)) { 3762 // Treat an enum type as its underlying type. 3763 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 3764 RetTy = EnumTy->getDecl()->getIntegerType(); 3765 3766 return (RetTy->isPromotableIntegerType() ? 3767 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 3768 } 3769 3770 // Structures with either a non-trivial destructor or a non-trivial 3771 // copy constructor are always indirect. 3772 if (isRecordReturnIndirect(RetTy, getCXXABI())) { 3773 markAllocatedGPRs(1, 1); 3774 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 3775 } 3776 3777 // Are we following APCS? 3778 if (getABIKind() == APCS) { 3779 if (isEmptyRecord(getContext(), RetTy, false)) 3780 return ABIArgInfo::getIgnore(); 3781 3782 // Complex types are all returned as packed integers. 3783 // 3784 // FIXME: Consider using 2 x vector types if the back end handles them 3785 // correctly. 3786 if (RetTy->isAnyComplexType()) 3787 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 3788 getContext().getTypeSize(RetTy))); 3789 3790 // Integer like structures are returned in r0. 3791 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) { 3792 // Return in the smallest viable integer type. 3793 uint64_t Size = getContext().getTypeSize(RetTy); 3794 if (Size <= 8) 3795 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 3796 if (Size <= 16) 3797 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 3798 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 3799 } 3800 3801 // Otherwise return in memory. 3802 markAllocatedGPRs(1, 1); 3803 return ABIArgInfo::getIndirect(0); 3804 } 3805 3806 // Otherwise this is an AAPCS variant. 3807 3808 if (isEmptyRecord(getContext(), RetTy, true)) 3809 return ABIArgInfo::getIgnore(); 3810 3811 // Check for homogeneous aggregates with AAPCS-VFP. 3812 if (getABIKind() == AAPCS_VFP && !isVariadic) { 3813 const Type *Base = 0; 3814 if (isHomogeneousAggregate(RetTy, Base, getContext())) { 3815 assert(Base && "Base class should be set for homogeneous aggregate"); 3816 // Homogeneous Aggregates are returned directly. 3817 return ABIArgInfo::getDirect(); 3818 } 3819 } 3820 3821 // Aggregates <= 4 bytes are returned in r0; other aggregates 3822 // are returned indirectly. 3823 uint64_t Size = getContext().getTypeSize(RetTy); 3824 if (Size <= 32) { 3825 // Return in the smallest viable integer type. 3826 if (Size <= 8) 3827 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 3828 if (Size <= 16) 3829 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 3830 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 3831 } 3832 3833 markAllocatedGPRs(1, 1); 3834 return ABIArgInfo::getIndirect(0); 3835 } 3836 3837 /// isIllegalVector - check whether Ty is an illegal vector type. 3838 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const { 3839 if (const VectorType *VT = Ty->getAs<VectorType>()) { 3840 // Check whether VT is legal. 3841 unsigned NumElements = VT->getNumElements(); 3842 uint64_t Size = getContext().getTypeSize(VT); 3843 // NumElements should be power of 2. 3844 if ((NumElements & (NumElements - 1)) != 0) 3845 return true; 3846 // Size should be greater than 32 bits. 3847 return Size <= 32; 3848 } 3849 return false; 3850 } 3851 3852 llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3853 CodeGenFunction &CGF) const { 3854 llvm::Type *BP = CGF.Int8PtrTy; 3855 llvm::Type *BPP = CGF.Int8PtrPtrTy; 3856 3857 CGBuilderTy &Builder = CGF.Builder; 3858 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); 3859 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 3860 3861 if (isEmptyRecord(getContext(), Ty, true)) { 3862 // These are ignored for parameter passing purposes. 3863 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 3864 return Builder.CreateBitCast(Addr, PTy); 3865 } 3866 3867 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8; 3868 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8; 3869 bool IsIndirect = false; 3870 3871 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for 3872 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte. 3873 if (getABIKind() == ARMABIInfo::AAPCS_VFP || 3874 getABIKind() == ARMABIInfo::AAPCS) 3875 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8); 3876 else 3877 TyAlign = 4; 3878 // Use indirect if size of the illegal vector is bigger than 16 bytes. 3879 if (isIllegalVectorType(Ty) && Size > 16) { 3880 IsIndirect = true; 3881 Size = 4; 3882 TyAlign = 4; 3883 } 3884 3885 // Handle address alignment for ABI alignment > 4 bytes. 3886 if (TyAlign > 4) { 3887 assert((TyAlign & (TyAlign - 1)) == 0 && 3888 "Alignment is not power of 2!"); 3889 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty); 3890 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1)); 3891 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1))); 3892 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align"); 3893 } 3894 3895 uint64_t Offset = 3896 llvm::RoundUpToAlignment(Size, 4); 3897 llvm::Value *NextAddr = 3898 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), 3899 "ap.next"); 3900 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 3901 3902 if (IsIndirect) 3903 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP)); 3904 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) { 3905 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur 3906 // may not be correctly aligned for the vector type. We create an aligned 3907 // temporary space and copy the content over from ap.cur to the temporary 3908 // space. This is necessary if the natural alignment of the type is greater 3909 // than the ABI alignment. 3910 llvm::Type *I8PtrTy = Builder.getInt8PtrTy(); 3911 CharUnits CharSize = getContext().getTypeSizeInChars(Ty); 3912 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty), 3913 "var.align"); 3914 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy); 3915 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy); 3916 Builder.CreateMemCpy(Dst, Src, 3917 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()), 3918 TyAlign, false); 3919 Addr = AlignedTemp; //The content is in aligned location. 3920 } 3921 llvm::Type *PTy = 3922 llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 3923 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy); 3924 3925 return AddrTyped; 3926 } 3927 3928 namespace { 3929 3930 class NaClARMABIInfo : public ABIInfo { 3931 public: 3932 NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind) 3933 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {} 3934 void computeInfo(CGFunctionInfo &FI) const override; 3935 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3936 CodeGenFunction &CGF) const override; 3937 private: 3938 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv. 3939 ARMABIInfo NInfo; // Used for everything else. 3940 }; 3941 3942 class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo { 3943 public: 3944 NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind) 3945 : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {} 3946 }; 3947 3948 } 3949 3950 void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const { 3951 if (FI.getASTCallingConvention() == CC_PnaclCall) 3952 PInfo.computeInfo(FI); 3953 else 3954 static_cast<const ABIInfo&>(NInfo).computeInfo(FI); 3955 } 3956 3957 llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3958 CodeGenFunction &CGF) const { 3959 // Always use the native convention; calling pnacl-style varargs functions 3960 // is unsupported. 3961 return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF); 3962 } 3963 3964 //===----------------------------------------------------------------------===// 3965 // AArch64 ABI Implementation 3966 //===----------------------------------------------------------------------===// 3967 3968 namespace { 3969 3970 class AArch64ABIInfo : public ABIInfo { 3971 public: 3972 AArch64ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 3973 3974 private: 3975 // The AArch64 PCS is explicit about return types and argument types being 3976 // handled identically, so we don't need to draw a distinction between 3977 // Argument and Return classification. 3978 ABIArgInfo classifyGenericType(QualType Ty, int &FreeIntRegs, 3979 int &FreeVFPRegs) const; 3980 3981 ABIArgInfo tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded, bool IsInt, 3982 llvm::Type *DirectTy = 0) const; 3983 3984 void computeInfo(CGFunctionInfo &FI) const override; 3985 3986 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3987 CodeGenFunction &CGF) const override; 3988 }; 3989 3990 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo { 3991 public: 3992 AArch64TargetCodeGenInfo(CodeGenTypes &CGT) 3993 :TargetCodeGenInfo(new AArch64ABIInfo(CGT)) {} 3994 3995 const AArch64ABIInfo &getABIInfo() const { 3996 return static_cast<const AArch64ABIInfo&>(TargetCodeGenInfo::getABIInfo()); 3997 } 3998 3999 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4000 return 31; 4001 } 4002 4003 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4004 llvm::Value *Address) const override { 4005 // 0-31 are x0-x30 and sp: 8 bytes each 4006 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 4007 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 31); 4008 4009 // 64-95 are v0-v31: 16 bytes each 4010 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16); 4011 AssignToArrayRange(CGF.Builder, Address, Sixteen8, 64, 95); 4012 4013 return false; 4014 } 4015 4016 }; 4017 4018 } 4019 4020 void AArch64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 4021 int FreeIntRegs = 8, FreeVFPRegs = 8; 4022 4023 FI.getReturnInfo() = classifyGenericType(FI.getReturnType(), 4024 FreeIntRegs, FreeVFPRegs); 4025 4026 FreeIntRegs = FreeVFPRegs = 8; 4027 for (auto &I : FI.arguments()) { 4028 I.info = classifyGenericType(I.type, FreeIntRegs, FreeVFPRegs); 4029 4030 } 4031 } 4032 4033 ABIArgInfo 4034 AArch64ABIInfo::tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded, 4035 bool IsInt, llvm::Type *DirectTy) const { 4036 if (FreeRegs >= RegsNeeded) { 4037 FreeRegs -= RegsNeeded; 4038 return ABIArgInfo::getDirect(DirectTy); 4039 } 4040 4041 llvm::Type *Padding = 0; 4042 4043 // We need padding so that later arguments don't get filled in anyway. That 4044 // wouldn't happen if only ByVal arguments followed in the same category, but 4045 // a large structure will simply seem to be a pointer as far as LLVM is 4046 // concerned. 4047 if (FreeRegs > 0) { 4048 if (IsInt) 4049 Padding = llvm::Type::getInt64Ty(getVMContext()); 4050 else 4051 Padding = llvm::Type::getFloatTy(getVMContext()); 4052 4053 // Either [N x i64] or [N x float]. 4054 Padding = llvm::ArrayType::get(Padding, FreeRegs); 4055 FreeRegs = 0; 4056 } 4057 4058 return ABIArgInfo::getIndirect(getContext().getTypeAlign(Ty) / 8, 4059 /*IsByVal=*/ true, /*Realign=*/ false, 4060 Padding); 4061 } 4062 4063 4064 ABIArgInfo AArch64ABIInfo::classifyGenericType(QualType Ty, 4065 int &FreeIntRegs, 4066 int &FreeVFPRegs) const { 4067 // Can only occurs for return, but harmless otherwise. 4068 if (Ty->isVoidType()) 4069 return ABIArgInfo::getIgnore(); 4070 4071 // Large vector types should be returned via memory. There's no such concept 4072 // in the ABI, but they'd be over 16 bytes anyway so no matter how they're 4073 // classified they'd go into memory (see B.3). 4074 if (Ty->isVectorType() && getContext().getTypeSize(Ty) > 128) { 4075 if (FreeIntRegs > 0) 4076 --FreeIntRegs; 4077 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 4078 } 4079 4080 // All non-aggregate LLVM types have a concrete ABI representation so they can 4081 // be passed directly. After this block we're guaranteed to be in a 4082 // complicated case. 4083 if (!isAggregateTypeForABI(Ty)) { 4084 // Treat an enum type as its underlying type. 4085 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4086 Ty = EnumTy->getDecl()->getIntegerType(); 4087 4088 if (Ty->isFloatingType() || Ty->isVectorType()) 4089 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ false); 4090 4091 assert(getContext().getTypeSize(Ty) <= 128 && 4092 "unexpectedly large scalar type"); 4093 4094 int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1; 4095 4096 // If the type may need padding registers to ensure "alignment", we must be 4097 // careful when this is accounted for. Increasing the effective size covers 4098 // all cases. 4099 if (getContext().getTypeAlign(Ty) == 128) 4100 RegsNeeded += FreeIntRegs % 2 != 0; 4101 4102 return tryUseRegs(Ty, FreeIntRegs, RegsNeeded, /*IsInt=*/ true); 4103 } 4104 4105 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 4106 if (FreeIntRegs > 0 && RAA == CGCXXABI::RAA_Indirect) 4107 --FreeIntRegs; 4108 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 4109 } 4110 4111 if (isEmptyRecord(getContext(), Ty, true)) { 4112 if (!getContext().getLangOpts().CPlusPlus) { 4113 // Empty structs outside C++ mode are a GNU extension, so no ABI can 4114 // possibly tell us what to do. It turns out (I believe) that GCC ignores 4115 // the object for parameter-passsing purposes. 4116 return ABIArgInfo::getIgnore(); 4117 } 4118 4119 // The combination of C++98 9p5 (sizeof(struct) != 0) and the pseudocode 4120 // description of va_arg in the PCS require that an empty struct does 4121 // actually occupy space for parameter-passing. I'm hoping for a 4122 // clarification giving an explicit paragraph to point to in future. 4123 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ true, 4124 llvm::Type::getInt8Ty(getVMContext())); 4125 } 4126 4127 // Homogeneous vector aggregates get passed in registers or on the stack. 4128 const Type *Base = 0; 4129 uint64_t NumMembers = 0; 4130 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)) { 4131 assert(Base && "Base class should be set for homogeneous aggregate"); 4132 // Homogeneous aggregates are passed and returned directly. 4133 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ NumMembers, 4134 /*IsInt=*/ false); 4135 } 4136 4137 uint64_t Size = getContext().getTypeSize(Ty); 4138 if (Size <= 128) { 4139 // Small structs can use the same direct type whether they're in registers 4140 // or on the stack. 4141 llvm::Type *BaseTy; 4142 unsigned NumBases; 4143 int SizeInRegs = (Size + 63) / 64; 4144 4145 if (getContext().getTypeAlign(Ty) == 128) { 4146 BaseTy = llvm::Type::getIntNTy(getVMContext(), 128); 4147 NumBases = 1; 4148 4149 // If the type may need padding registers to ensure "alignment", we must 4150 // be careful when this is accounted for. Increasing the effective size 4151 // covers all cases. 4152 SizeInRegs += FreeIntRegs % 2 != 0; 4153 } else { 4154 BaseTy = llvm::Type::getInt64Ty(getVMContext()); 4155 NumBases = SizeInRegs; 4156 } 4157 llvm::Type *DirectTy = llvm::ArrayType::get(BaseTy, NumBases); 4158 4159 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ SizeInRegs, 4160 /*IsInt=*/ true, DirectTy); 4161 } 4162 4163 // If the aggregate is > 16 bytes, it's passed and returned indirectly. In 4164 // LLVM terms the return uses an "sret" pointer, but that's handled elsewhere. 4165 --FreeIntRegs; 4166 return ABIArgInfo::getIndirect(0, /* byVal = */ false); 4167 } 4168 4169 llvm::Value *AArch64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 4170 CodeGenFunction &CGF) const { 4171 // The AArch64 va_list type and handling is specified in the Procedure Call 4172 // Standard, section B.4: 4173 // 4174 // struct { 4175 // void *__stack; 4176 // void *__gr_top; 4177 // void *__vr_top; 4178 // int __gr_offs; 4179 // int __vr_offs; 4180 // }; 4181 4182 int FreeIntRegs = 8, FreeVFPRegs = 8; 4183 Ty = CGF.getContext().getCanonicalType(Ty); 4184 ABIArgInfo AI = classifyGenericType(Ty, FreeIntRegs, FreeVFPRegs); 4185 4186 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg"); 4187 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 4188 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack"); 4189 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 4190 4191 llvm::Value *reg_offs_p = 0, *reg_offs = 0; 4192 int reg_top_index; 4193 int RegSize; 4194 if (FreeIntRegs < 8) { 4195 assert(FreeVFPRegs == 8 && "Arguments never split between int & VFP regs"); 4196 // 3 is the field number of __gr_offs 4197 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p"); 4198 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs"); 4199 reg_top_index = 1; // field number for __gr_top 4200 RegSize = 8 * (8 - FreeIntRegs); 4201 } else { 4202 assert(FreeVFPRegs < 8 && "Argument must go in VFP or int regs"); 4203 // 4 is the field number of __vr_offs. 4204 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p"); 4205 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs"); 4206 reg_top_index = 2; // field number for __vr_top 4207 RegSize = 16 * (8 - FreeVFPRegs); 4208 } 4209 4210 //======================================= 4211 // Find out where argument was passed 4212 //======================================= 4213 4214 // If reg_offs >= 0 we're already using the stack for this type of 4215 // argument. We don't want to keep updating reg_offs (in case it overflows, 4216 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves 4217 // whatever they get). 4218 llvm::Value *UsingStack = 0; 4219 UsingStack = CGF.Builder.CreateICmpSGE(reg_offs, 4220 llvm::ConstantInt::get(CGF.Int32Ty, 0)); 4221 4222 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock); 4223 4224 // Otherwise, at least some kind of argument could go in these registers, the 4225 // quesiton is whether this particular type is too big. 4226 CGF.EmitBlock(MaybeRegBlock); 4227 4228 // Integer arguments may need to correct register alignment (for example a 4229 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we 4230 // align __gr_offs to calculate the potential address. 4231 if (FreeIntRegs < 8 && AI.isDirect() && getContext().getTypeAlign(Ty) > 64) { 4232 int Align = getContext().getTypeAlign(Ty) / 8; 4233 4234 reg_offs = CGF.Builder.CreateAdd(reg_offs, 4235 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1), 4236 "align_regoffs"); 4237 reg_offs = CGF.Builder.CreateAnd(reg_offs, 4238 llvm::ConstantInt::get(CGF.Int32Ty, -Align), 4239 "aligned_regoffs"); 4240 } 4241 4242 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list. 4243 llvm::Value *NewOffset = 0; 4244 NewOffset = CGF.Builder.CreateAdd(reg_offs, 4245 llvm::ConstantInt::get(CGF.Int32Ty, RegSize), 4246 "new_reg_offs"); 4247 CGF.Builder.CreateStore(NewOffset, reg_offs_p); 4248 4249 // Now we're in a position to decide whether this argument really was in 4250 // registers or not. 4251 llvm::Value *InRegs = 0; 4252 InRegs = CGF.Builder.CreateICmpSLE(NewOffset, 4253 llvm::ConstantInt::get(CGF.Int32Ty, 0), 4254 "inreg"); 4255 4256 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock); 4257 4258 //======================================= 4259 // Argument was in registers 4260 //======================================= 4261 4262 // Now we emit the code for if the argument was originally passed in 4263 // registers. First start the appropriate block: 4264 CGF.EmitBlock(InRegBlock); 4265 4266 llvm::Value *reg_top_p = 0, *reg_top = 0; 4267 reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p"); 4268 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top"); 4269 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs); 4270 llvm::Value *RegAddr = 0; 4271 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); 4272 4273 if (!AI.isDirect()) { 4274 // If it's been passed indirectly (actually a struct), whatever we find from 4275 // stored registers or on the stack will actually be a struct **. 4276 MemTy = llvm::PointerType::getUnqual(MemTy); 4277 } 4278 4279 const Type *Base = 0; 4280 uint64_t NumMembers; 4281 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers) 4282 && NumMembers > 1) { 4283 // Homogeneous aggregates passed in registers will have their elements split 4284 // and stored 16-bytes apart regardless of size (they're notionally in qN, 4285 // qN+1, ...). We reload and store into a temporary local variable 4286 // contiguously. 4287 assert(AI.isDirect() && "Homogeneous aggregates should be passed directly"); 4288 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0)); 4289 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers); 4290 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy); 4291 int Offset = 0; 4292 4293 if (CGF.CGM.getDataLayout().isBigEndian() && 4294 getContext().getTypeSize(Base) < 128) 4295 Offset = 16 - getContext().getTypeSize(Base)/8; 4296 for (unsigned i = 0; i < NumMembers; ++i) { 4297 llvm::Value *BaseOffset = llvm::ConstantInt::get(CGF.Int32Ty, 4298 16 * i + Offset); 4299 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset); 4300 LoadAddr = CGF.Builder.CreateBitCast(LoadAddr, 4301 llvm::PointerType::getUnqual(BaseTy)); 4302 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i); 4303 4304 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr); 4305 CGF.Builder.CreateStore(Elem, StoreAddr); 4306 } 4307 4308 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy); 4309 } else { 4310 // Otherwise the object is contiguous in memory 4311 unsigned BeAlign = reg_top_index == 2 ? 16 : 8; 4312 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) && 4313 getContext().getTypeSize(Ty) < (BeAlign * 8)) { 4314 int Offset = BeAlign - getContext().getTypeSize(Ty)/8; 4315 BaseAddr = CGF.Builder.CreatePtrToInt(BaseAddr, CGF.Int64Ty); 4316 4317 BaseAddr = CGF.Builder.CreateAdd(BaseAddr, 4318 llvm::ConstantInt::get(CGF.Int64Ty, 4319 Offset), 4320 "align_be"); 4321 4322 BaseAddr = CGF.Builder.CreateIntToPtr(BaseAddr, CGF.Int8PtrTy); 4323 } 4324 4325 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy); 4326 } 4327 4328 CGF.EmitBranch(ContBlock); 4329 4330 //======================================= 4331 // Argument was on the stack 4332 //======================================= 4333 CGF.EmitBlock(OnStackBlock); 4334 4335 llvm::Value *stack_p = 0, *OnStackAddr = 0; 4336 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p"); 4337 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack"); 4338 4339 // Again, stack arguments may need realigmnent. In this case both integer and 4340 // floating-point ones might be affected. 4341 if (AI.isDirect() && getContext().getTypeAlign(Ty) > 64) { 4342 int Align = getContext().getTypeAlign(Ty) / 8; 4343 4344 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty); 4345 4346 OnStackAddr = CGF.Builder.CreateAdd(OnStackAddr, 4347 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1), 4348 "align_stack"); 4349 OnStackAddr = CGF.Builder.CreateAnd(OnStackAddr, 4350 llvm::ConstantInt::get(CGF.Int64Ty, -Align), 4351 "align_stack"); 4352 4353 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy); 4354 } 4355 4356 uint64_t StackSize; 4357 if (AI.isDirect()) 4358 StackSize = getContext().getTypeSize(Ty) / 8; 4359 else 4360 StackSize = 8; 4361 4362 // All stack slots are 8 bytes 4363 StackSize = llvm::RoundUpToAlignment(StackSize, 8); 4364 4365 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize); 4366 llvm::Value *NewStack = CGF.Builder.CreateGEP(OnStackAddr, StackSizeC, 4367 "new_stack"); 4368 4369 // Write the new value of __stack for the next call to va_arg 4370 CGF.Builder.CreateStore(NewStack, stack_p); 4371 4372 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) && 4373 getContext().getTypeSize(Ty) < 64 ) { 4374 int Offset = 8 - getContext().getTypeSize(Ty)/8; 4375 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty); 4376 4377 OnStackAddr = CGF.Builder.CreateAdd(OnStackAddr, 4378 llvm::ConstantInt::get(CGF.Int64Ty, 4379 Offset), 4380 "align_be"); 4381 4382 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy); 4383 } 4384 4385 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy); 4386 4387 CGF.EmitBranch(ContBlock); 4388 4389 //======================================= 4390 // Tidy up 4391 //======================================= 4392 CGF.EmitBlock(ContBlock); 4393 4394 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr"); 4395 ResAddr->addIncoming(RegAddr, InRegBlock); 4396 ResAddr->addIncoming(OnStackAddr, OnStackBlock); 4397 4398 if (AI.isDirect()) 4399 return ResAddr; 4400 4401 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"); 4402 } 4403 4404 //===----------------------------------------------------------------------===// 4405 // NVPTX ABI Implementation 4406 //===----------------------------------------------------------------------===// 4407 4408 namespace { 4409 4410 class NVPTXABIInfo : public ABIInfo { 4411 public: 4412 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 4413 4414 ABIArgInfo classifyReturnType(QualType RetTy) const; 4415 ABIArgInfo classifyArgumentType(QualType Ty) const; 4416 4417 void computeInfo(CGFunctionInfo &FI) const override; 4418 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 4419 CodeGenFunction &CFG) const override; 4420 }; 4421 4422 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo { 4423 public: 4424 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT) 4425 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {} 4426 4427 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 4428 CodeGen::CodeGenModule &M) const override; 4429 private: 4430 static void addKernelMetadata(llvm::Function *F); 4431 }; 4432 4433 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const { 4434 if (RetTy->isVoidType()) 4435 return ABIArgInfo::getIgnore(); 4436 4437 // note: this is different from default ABI 4438 if (!RetTy->isScalarType()) 4439 return ABIArgInfo::getDirect(); 4440 4441 // Treat an enum type as its underlying type. 4442 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 4443 RetTy = EnumTy->getDecl()->getIntegerType(); 4444 4445 return (RetTy->isPromotableIntegerType() ? 4446 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 4447 } 4448 4449 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const { 4450 // Treat an enum type as its underlying type. 4451 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4452 Ty = EnumTy->getDecl()->getIntegerType(); 4453 4454 return (Ty->isPromotableIntegerType() ? 4455 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 4456 } 4457 4458 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const { 4459 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4460 for (auto &I : FI.arguments()) 4461 I.info = classifyArgumentType(I.type); 4462 4463 // Always honor user-specified calling convention. 4464 if (FI.getCallingConvention() != llvm::CallingConv::C) 4465 return; 4466 4467 FI.setEffectiveCallingConvention(getRuntimeCC()); 4468 } 4469 4470 llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 4471 CodeGenFunction &CFG) const { 4472 llvm_unreachable("NVPTX does not support varargs"); 4473 } 4474 4475 void NVPTXTargetCodeGenInfo:: 4476 SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 4477 CodeGen::CodeGenModule &M) const{ 4478 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 4479 if (!FD) return; 4480 4481 llvm::Function *F = cast<llvm::Function>(GV); 4482 4483 // Perform special handling in OpenCL mode 4484 if (M.getLangOpts().OpenCL) { 4485 // Use OpenCL function attributes to check for kernel functions 4486 // By default, all functions are device functions 4487 if (FD->hasAttr<OpenCLKernelAttr>()) { 4488 // OpenCL __kernel functions get kernel metadata 4489 addKernelMetadata(F); 4490 // And kernel functions are not subject to inlining 4491 F->addFnAttr(llvm::Attribute::NoInline); 4492 } 4493 } 4494 4495 // Perform special handling in CUDA mode. 4496 if (M.getLangOpts().CUDA) { 4497 // CUDA __global__ functions get a kernel metadata entry. Since 4498 // __global__ functions cannot be called from the device, we do not 4499 // need to set the noinline attribute. 4500 if (FD->hasAttr<CUDAGlobalAttr>()) 4501 addKernelMetadata(F); 4502 } 4503 } 4504 4505 void NVPTXTargetCodeGenInfo::addKernelMetadata(llvm::Function *F) { 4506 llvm::Module *M = F->getParent(); 4507 llvm::LLVMContext &Ctx = M->getContext(); 4508 4509 // Get "nvvm.annotations" metadata node 4510 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations"); 4511 4512 // Create !{<func-ref>, metadata !"kernel", i32 1} node 4513 llvm::SmallVector<llvm::Value *, 3> MDVals; 4514 MDVals.push_back(F); 4515 MDVals.push_back(llvm::MDString::get(Ctx, "kernel")); 4516 MDVals.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1)); 4517 4518 // Append metadata to nvvm.annotations 4519 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 4520 } 4521 4522 } 4523 4524 //===----------------------------------------------------------------------===// 4525 // SystemZ ABI Implementation 4526 //===----------------------------------------------------------------------===// 4527 4528 namespace { 4529 4530 class SystemZABIInfo : public ABIInfo { 4531 public: 4532 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 4533 4534 bool isPromotableIntegerType(QualType Ty) const; 4535 bool isCompoundType(QualType Ty) const; 4536 bool isFPArgumentType(QualType Ty) const; 4537 4538 ABIArgInfo classifyReturnType(QualType RetTy) const; 4539 ABIArgInfo classifyArgumentType(QualType ArgTy) const; 4540 4541 void computeInfo(CGFunctionInfo &FI) const override { 4542 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4543 for (auto &I : FI.arguments()) 4544 I.info = classifyArgumentType(I.type); 4545 } 4546 4547 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 4548 CodeGenFunction &CGF) const override; 4549 }; 4550 4551 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo { 4552 public: 4553 SystemZTargetCodeGenInfo(CodeGenTypes &CGT) 4554 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {} 4555 }; 4556 4557 } 4558 4559 bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const { 4560 // Treat an enum type as its underlying type. 4561 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4562 Ty = EnumTy->getDecl()->getIntegerType(); 4563 4564 // Promotable integer types are required to be promoted by the ABI. 4565 if (Ty->isPromotableIntegerType()) 4566 return true; 4567 4568 // 32-bit values must also be promoted. 4569 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 4570 switch (BT->getKind()) { 4571 case BuiltinType::Int: 4572 case BuiltinType::UInt: 4573 return true; 4574 default: 4575 return false; 4576 } 4577 return false; 4578 } 4579 4580 bool SystemZABIInfo::isCompoundType(QualType Ty) const { 4581 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty); 4582 } 4583 4584 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const { 4585 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 4586 switch (BT->getKind()) { 4587 case BuiltinType::Float: 4588 case BuiltinType::Double: 4589 return true; 4590 default: 4591 return false; 4592 } 4593 4594 if (const RecordType *RT = Ty->getAsStructureType()) { 4595 const RecordDecl *RD = RT->getDecl(); 4596 bool Found = false; 4597 4598 // If this is a C++ record, check the bases first. 4599 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 4600 for (const auto &I : CXXRD->bases()) { 4601 QualType Base = I.getType(); 4602 4603 // Empty bases don't affect things either way. 4604 if (isEmptyRecord(getContext(), Base, true)) 4605 continue; 4606 4607 if (Found) 4608 return false; 4609 Found = isFPArgumentType(Base); 4610 if (!Found) 4611 return false; 4612 } 4613 4614 // Check the fields. 4615 for (const auto *FD : RD->fields()) { 4616 // Empty bitfields don't affect things either way. 4617 // Unlike isSingleElementStruct(), empty structure and array fields 4618 // do count. So do anonymous bitfields that aren't zero-sized. 4619 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0) 4620 return true; 4621 4622 // Unlike isSingleElementStruct(), arrays do not count. 4623 // Nested isFPArgumentType structures still do though. 4624 if (Found) 4625 return false; 4626 Found = isFPArgumentType(FD->getType()); 4627 if (!Found) 4628 return false; 4629 } 4630 4631 // Unlike isSingleElementStruct(), trailing padding is allowed. 4632 // An 8-byte aligned struct s { float f; } is passed as a double. 4633 return Found; 4634 } 4635 4636 return false; 4637 } 4638 4639 llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 4640 CodeGenFunction &CGF) const { 4641 // Assume that va_list type is correct; should be pointer to LLVM type: 4642 // struct { 4643 // i64 __gpr; 4644 // i64 __fpr; 4645 // i8 *__overflow_arg_area; 4646 // i8 *__reg_save_area; 4647 // }; 4648 4649 // Every argument occupies 8 bytes and is passed by preference in either 4650 // GPRs or FPRs. 4651 Ty = CGF.getContext().getCanonicalType(Ty); 4652 ABIArgInfo AI = classifyArgumentType(Ty); 4653 bool InFPRs = isFPArgumentType(Ty); 4654 4655 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); 4656 bool IsIndirect = AI.isIndirect(); 4657 unsigned UnpaddedBitSize; 4658 if (IsIndirect) { 4659 APTy = llvm::PointerType::getUnqual(APTy); 4660 UnpaddedBitSize = 64; 4661 } else 4662 UnpaddedBitSize = getContext().getTypeSize(Ty); 4663 unsigned PaddedBitSize = 64; 4664 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size."); 4665 4666 unsigned PaddedSize = PaddedBitSize / 8; 4667 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8; 4668 4669 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding; 4670 if (InFPRs) { 4671 MaxRegs = 4; // Maximum of 4 FPR arguments 4672 RegCountField = 1; // __fpr 4673 RegSaveIndex = 16; // save offset for f0 4674 RegPadding = 0; // floats are passed in the high bits of an FPR 4675 } else { 4676 MaxRegs = 5; // Maximum of 5 GPR arguments 4677 RegCountField = 0; // __gpr 4678 RegSaveIndex = 2; // save offset for r2 4679 RegPadding = Padding; // values are passed in the low bits of a GPR 4680 } 4681 4682 llvm::Value *RegCountPtr = 4683 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr"); 4684 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count"); 4685 llvm::Type *IndexTy = RegCount->getType(); 4686 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs); 4687 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV, 4688 "fits_in_regs"); 4689 4690 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 4691 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 4692 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 4693 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 4694 4695 // Emit code to load the value if it was passed in registers. 4696 CGF.EmitBlock(InRegBlock); 4697 4698 // Work out the address of an argument register. 4699 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize); 4700 llvm::Value *ScaledRegCount = 4701 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count"); 4702 llvm::Value *RegBase = 4703 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding); 4704 llvm::Value *RegOffset = 4705 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset"); 4706 llvm::Value *RegSaveAreaPtr = 4707 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr"); 4708 llvm::Value *RegSaveArea = 4709 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area"); 4710 llvm::Value *RawRegAddr = 4711 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr"); 4712 llvm::Value *RegAddr = 4713 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr"); 4714 4715 // Update the register count 4716 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1); 4717 llvm::Value *NewRegCount = 4718 CGF.Builder.CreateAdd(RegCount, One, "reg_count"); 4719 CGF.Builder.CreateStore(NewRegCount, RegCountPtr); 4720 CGF.EmitBranch(ContBlock); 4721 4722 // Emit code to load the value if it was passed in memory. 4723 CGF.EmitBlock(InMemBlock); 4724 4725 // Work out the address of a stack argument. 4726 llvm::Value *OverflowArgAreaPtr = 4727 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr"); 4728 llvm::Value *OverflowArgArea = 4729 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"); 4730 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding); 4731 llvm::Value *RawMemAddr = 4732 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr"); 4733 llvm::Value *MemAddr = 4734 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr"); 4735 4736 // Update overflow_arg_area_ptr pointer 4737 llvm::Value *NewOverflowArgArea = 4738 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area"); 4739 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); 4740 CGF.EmitBranch(ContBlock); 4741 4742 // Return the appropriate result. 4743 CGF.EmitBlock(ContBlock); 4744 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr"); 4745 ResAddr->addIncoming(RegAddr, InRegBlock); 4746 ResAddr->addIncoming(MemAddr, InMemBlock); 4747 4748 if (IsIndirect) 4749 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg"); 4750 4751 return ResAddr; 4752 } 4753 4754 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI( 4755 const llvm::Triple &Triple, const CodeGenOptions &Opts) { 4756 assert(Triple.getArch() == llvm::Triple::x86); 4757 4758 switch (Opts.getStructReturnConvention()) { 4759 case CodeGenOptions::SRCK_Default: 4760 break; 4761 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return 4762 return false; 4763 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return 4764 return true; 4765 } 4766 4767 if (Triple.isOSDarwin()) 4768 return true; 4769 4770 switch (Triple.getOS()) { 4771 case llvm::Triple::Cygwin: 4772 case llvm::Triple::MinGW32: 4773 case llvm::Triple::AuroraUX: 4774 case llvm::Triple::DragonFly: 4775 case llvm::Triple::FreeBSD: 4776 case llvm::Triple::OpenBSD: 4777 case llvm::Triple::Bitrig: 4778 case llvm::Triple::Win32: 4779 return true; 4780 default: 4781 return false; 4782 } 4783 } 4784 4785 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const { 4786 if (RetTy->isVoidType()) 4787 return ABIArgInfo::getIgnore(); 4788 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64) 4789 return ABIArgInfo::getIndirect(0); 4790 return (isPromotableIntegerType(RetTy) ? 4791 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 4792 } 4793 4794 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const { 4795 // Handle the generic C++ ABI. 4796 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 4797 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 4798 4799 // Integers and enums are extended to full register width. 4800 if (isPromotableIntegerType(Ty)) 4801 return ABIArgInfo::getExtend(); 4802 4803 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly. 4804 uint64_t Size = getContext().getTypeSize(Ty); 4805 if (Size != 8 && Size != 16 && Size != 32 && Size != 64) 4806 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 4807 4808 // Handle small structures. 4809 if (const RecordType *RT = Ty->getAs<RecordType>()) { 4810 // Structures with flexible arrays have variable length, so really 4811 // fail the size test above. 4812 const RecordDecl *RD = RT->getDecl(); 4813 if (RD->hasFlexibleArrayMember()) 4814 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 4815 4816 // The structure is passed as an unextended integer, a float, or a double. 4817 llvm::Type *PassTy; 4818 if (isFPArgumentType(Ty)) { 4819 assert(Size == 32 || Size == 64); 4820 if (Size == 32) 4821 PassTy = llvm::Type::getFloatTy(getVMContext()); 4822 else 4823 PassTy = llvm::Type::getDoubleTy(getVMContext()); 4824 } else 4825 PassTy = llvm::IntegerType::get(getVMContext(), Size); 4826 return ABIArgInfo::getDirect(PassTy); 4827 } 4828 4829 // Non-structure compounds are passed indirectly. 4830 if (isCompoundType(Ty)) 4831 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 4832 4833 return ABIArgInfo::getDirect(0); 4834 } 4835 4836 //===----------------------------------------------------------------------===// 4837 // MSP430 ABI Implementation 4838 //===----------------------------------------------------------------------===// 4839 4840 namespace { 4841 4842 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo { 4843 public: 4844 MSP430TargetCodeGenInfo(CodeGenTypes &CGT) 4845 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {} 4846 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 4847 CodeGen::CodeGenModule &M) const override; 4848 }; 4849 4850 } 4851 4852 void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D, 4853 llvm::GlobalValue *GV, 4854 CodeGen::CodeGenModule &M) const { 4855 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 4856 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) { 4857 // Handle 'interrupt' attribute: 4858 llvm::Function *F = cast<llvm::Function>(GV); 4859 4860 // Step 1: Set ISR calling convention. 4861 F->setCallingConv(llvm::CallingConv::MSP430_INTR); 4862 4863 // Step 2: Add attributes goodness. 4864 F->addFnAttr(llvm::Attribute::NoInline); 4865 4866 // Step 3: Emit ISR vector alias. 4867 unsigned Num = attr->getNumber() / 2; 4868 new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage, 4869 "__isr_" + Twine(Num), 4870 GV, &M.getModule()); 4871 } 4872 } 4873 } 4874 4875 //===----------------------------------------------------------------------===// 4876 // MIPS ABI Implementation. This works for both little-endian and 4877 // big-endian variants. 4878 //===----------------------------------------------------------------------===// 4879 4880 namespace { 4881 class MipsABIInfo : public ABIInfo { 4882 bool IsO32; 4883 unsigned MinABIStackAlignInBytes, StackAlignInBytes; 4884 void CoerceToIntArgs(uint64_t TySize, 4885 SmallVectorImpl<llvm::Type *> &ArgList) const; 4886 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const; 4887 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const; 4888 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const; 4889 public: 4890 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) : 4891 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8), 4892 StackAlignInBytes(IsO32 ? 8 : 16) {} 4893 4894 ABIArgInfo classifyReturnType(QualType RetTy) const; 4895 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const; 4896 void computeInfo(CGFunctionInfo &FI) const override; 4897 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 4898 CodeGenFunction &CGF) const override; 4899 }; 4900 4901 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo { 4902 unsigned SizeOfUnwindException; 4903 public: 4904 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32) 4905 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)), 4906 SizeOfUnwindException(IsO32 ? 24 : 32) {} 4907 4908 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 4909 return 29; 4910 } 4911 4912 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 4913 CodeGen::CodeGenModule &CGM) const override { 4914 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 4915 if (!FD) return; 4916 llvm::Function *Fn = cast<llvm::Function>(GV); 4917 if (FD->hasAttr<Mips16Attr>()) { 4918 Fn->addFnAttr("mips16"); 4919 } 4920 else if (FD->hasAttr<NoMips16Attr>()) { 4921 Fn->addFnAttr("nomips16"); 4922 } 4923 } 4924 4925 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4926 llvm::Value *Address) const override; 4927 4928 unsigned getSizeOfUnwindException() const override { 4929 return SizeOfUnwindException; 4930 } 4931 }; 4932 } 4933 4934 void MipsABIInfo::CoerceToIntArgs(uint64_t TySize, 4935 SmallVectorImpl<llvm::Type *> &ArgList) const { 4936 llvm::IntegerType *IntTy = 4937 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8); 4938 4939 // Add (TySize / MinABIStackAlignInBytes) args of IntTy. 4940 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N) 4941 ArgList.push_back(IntTy); 4942 4943 // If necessary, add one more integer type to ArgList. 4944 unsigned R = TySize % (MinABIStackAlignInBytes * 8); 4945 4946 if (R) 4947 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R)); 4948 } 4949 4950 // In N32/64, an aligned double precision floating point field is passed in 4951 // a register. 4952 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const { 4953 SmallVector<llvm::Type*, 8> ArgList, IntArgList; 4954 4955 if (IsO32) { 4956 CoerceToIntArgs(TySize, ArgList); 4957 return llvm::StructType::get(getVMContext(), ArgList); 4958 } 4959 4960 if (Ty->isComplexType()) 4961 return CGT.ConvertType(Ty); 4962 4963 const RecordType *RT = Ty->getAs<RecordType>(); 4964 4965 // Unions/vectors are passed in integer registers. 4966 if (!RT || !RT->isStructureOrClassType()) { 4967 CoerceToIntArgs(TySize, ArgList); 4968 return llvm::StructType::get(getVMContext(), ArgList); 4969 } 4970 4971 const RecordDecl *RD = RT->getDecl(); 4972 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 4973 assert(!(TySize % 8) && "Size of structure must be multiple of 8."); 4974 4975 uint64_t LastOffset = 0; 4976 unsigned idx = 0; 4977 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64); 4978 4979 // Iterate over fields in the struct/class and check if there are any aligned 4980 // double fields. 4981 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 4982 i != e; ++i, ++idx) { 4983 const QualType Ty = i->getType(); 4984 const BuiltinType *BT = Ty->getAs<BuiltinType>(); 4985 4986 if (!BT || BT->getKind() != BuiltinType::Double) 4987 continue; 4988 4989 uint64_t Offset = Layout.getFieldOffset(idx); 4990 if (Offset % 64) // Ignore doubles that are not aligned. 4991 continue; 4992 4993 // Add ((Offset - LastOffset) / 64) args of type i64. 4994 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j) 4995 ArgList.push_back(I64); 4996 4997 // Add double type. 4998 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext())); 4999 LastOffset = Offset + 64; 5000 } 5001 5002 CoerceToIntArgs(TySize - LastOffset, IntArgList); 5003 ArgList.append(IntArgList.begin(), IntArgList.end()); 5004 5005 return llvm::StructType::get(getVMContext(), ArgList); 5006 } 5007 5008 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset, 5009 uint64_t Offset) const { 5010 if (OrigOffset + MinABIStackAlignInBytes > Offset) 5011 return 0; 5012 5013 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8); 5014 } 5015 5016 ABIArgInfo 5017 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const { 5018 uint64_t OrigOffset = Offset; 5019 uint64_t TySize = getContext().getTypeSize(Ty); 5020 uint64_t Align = getContext().getTypeAlign(Ty) / 8; 5021 5022 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes), 5023 (uint64_t)StackAlignInBytes); 5024 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align); 5025 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8; 5026 5027 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) { 5028 // Ignore empty aggregates. 5029 if (TySize == 0) 5030 return ABIArgInfo::getIgnore(); 5031 5032 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 5033 Offset = OrigOffset + MinABIStackAlignInBytes; 5034 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 5035 } 5036 5037 // If we have reached here, aggregates are passed directly by coercing to 5038 // another structure type. Padding is inserted if the offset of the 5039 // aggregate is unaligned. 5040 return ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0, 5041 getPaddingType(OrigOffset, CurrOffset)); 5042 } 5043 5044 // Treat an enum type as its underlying type. 5045 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 5046 Ty = EnumTy->getDecl()->getIntegerType(); 5047 5048 if (Ty->isPromotableIntegerType()) 5049 return ABIArgInfo::getExtend(); 5050 5051 return ABIArgInfo::getDirect( 5052 0, 0, IsO32 ? 0 : getPaddingType(OrigOffset, CurrOffset)); 5053 } 5054 5055 llvm::Type* 5056 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const { 5057 const RecordType *RT = RetTy->getAs<RecordType>(); 5058 SmallVector<llvm::Type*, 8> RTList; 5059 5060 if (RT && RT->isStructureOrClassType()) { 5061 const RecordDecl *RD = RT->getDecl(); 5062 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 5063 unsigned FieldCnt = Layout.getFieldCount(); 5064 5065 // N32/64 returns struct/classes in floating point registers if the 5066 // following conditions are met: 5067 // 1. The size of the struct/class is no larger than 128-bit. 5068 // 2. The struct/class has one or two fields all of which are floating 5069 // point types. 5070 // 3. The offset of the first field is zero (this follows what gcc does). 5071 // 5072 // Any other composite results are returned in integer registers. 5073 // 5074 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) { 5075 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end(); 5076 for (; b != e; ++b) { 5077 const BuiltinType *BT = b->getType()->getAs<BuiltinType>(); 5078 5079 if (!BT || !BT->isFloatingPoint()) 5080 break; 5081 5082 RTList.push_back(CGT.ConvertType(b->getType())); 5083 } 5084 5085 if (b == e) 5086 return llvm::StructType::get(getVMContext(), RTList, 5087 RD->hasAttr<PackedAttr>()); 5088 5089 RTList.clear(); 5090 } 5091 } 5092 5093 CoerceToIntArgs(Size, RTList); 5094 return llvm::StructType::get(getVMContext(), RTList); 5095 } 5096 5097 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const { 5098 uint64_t Size = getContext().getTypeSize(RetTy); 5099 5100 if (RetTy->isVoidType() || Size == 0) 5101 return ABIArgInfo::getIgnore(); 5102 5103 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) { 5104 if (isRecordReturnIndirect(RetTy, getCXXABI())) 5105 return ABIArgInfo::getIndirect(0); 5106 5107 if (Size <= 128) { 5108 if (RetTy->isAnyComplexType()) 5109 return ABIArgInfo::getDirect(); 5110 5111 // O32 returns integer vectors in registers. 5112 if (IsO32 && RetTy->isVectorType() && !RetTy->hasFloatingRepresentation()) 5113 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size)); 5114 5115 if (!IsO32) 5116 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size)); 5117 } 5118 5119 return ABIArgInfo::getIndirect(0); 5120 } 5121 5122 // Treat an enum type as its underlying type. 5123 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 5124 RetTy = EnumTy->getDecl()->getIntegerType(); 5125 5126 return (RetTy->isPromotableIntegerType() ? 5127 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 5128 } 5129 5130 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const { 5131 ABIArgInfo &RetInfo = FI.getReturnInfo(); 5132 RetInfo = classifyReturnType(FI.getReturnType()); 5133 5134 // Check if a pointer to an aggregate is passed as a hidden argument. 5135 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0; 5136 5137 for (auto &I : FI.arguments()) 5138 I.info = classifyArgumentType(I.type, Offset); 5139 } 5140 5141 llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 5142 CodeGenFunction &CGF) const { 5143 llvm::Type *BP = CGF.Int8PtrTy; 5144 llvm::Type *BPP = CGF.Int8PtrPtrTy; 5145 5146 CGBuilderTy &Builder = CGF.Builder; 5147 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); 5148 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 5149 int64_t TypeAlign = getContext().getTypeAlign(Ty) / 8; 5150 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 5151 llvm::Value *AddrTyped; 5152 unsigned PtrWidth = getTarget().getPointerWidth(0); 5153 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty; 5154 5155 if (TypeAlign > MinABIStackAlignInBytes) { 5156 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy); 5157 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1); 5158 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign); 5159 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc); 5160 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask); 5161 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy); 5162 } 5163 else 5164 AddrTyped = Builder.CreateBitCast(Addr, PTy); 5165 5166 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP); 5167 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes); 5168 uint64_t Offset = 5169 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign); 5170 llvm::Value *NextAddr = 5171 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset), 5172 "ap.next"); 5173 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 5174 5175 return AddrTyped; 5176 } 5177 5178 bool 5179 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5180 llvm::Value *Address) const { 5181 // This information comes from gcc's implementation, which seems to 5182 // as canonical as it gets. 5183 5184 // Everything on MIPS is 4 bytes. Double-precision FP registers 5185 // are aliased to pairs of single-precision FP registers. 5186 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 5187 5188 // 0-31 are the general purpose registers, $0 - $31. 5189 // 32-63 are the floating-point registers, $f0 - $f31. 5190 // 64 and 65 are the multiply/divide registers, $hi and $lo. 5191 // 66 is the (notional, I think) register for signal-handler return. 5192 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65); 5193 5194 // 67-74 are the floating-point status registers, $fcc0 - $fcc7. 5195 // They are one bit wide and ignored here. 5196 5197 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31. 5198 // (coprocessor 1 is the FP unit) 5199 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31. 5200 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31. 5201 // 176-181 are the DSP accumulator registers. 5202 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181); 5203 return false; 5204 } 5205 5206 //===----------------------------------------------------------------------===// 5207 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults. 5208 // Currently subclassed only to implement custom OpenCL C function attribute 5209 // handling. 5210 //===----------------------------------------------------------------------===// 5211 5212 namespace { 5213 5214 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo { 5215 public: 5216 TCETargetCodeGenInfo(CodeGenTypes &CGT) 5217 : DefaultTargetCodeGenInfo(CGT) {} 5218 5219 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5220 CodeGen::CodeGenModule &M) const override; 5221 }; 5222 5223 void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D, 5224 llvm::GlobalValue *GV, 5225 CodeGen::CodeGenModule &M) const { 5226 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 5227 if (!FD) return; 5228 5229 llvm::Function *F = cast<llvm::Function>(GV); 5230 5231 if (M.getLangOpts().OpenCL) { 5232 if (FD->hasAttr<OpenCLKernelAttr>()) { 5233 // OpenCL C Kernel functions are not subject to inlining 5234 F->addFnAttr(llvm::Attribute::NoInline); 5235 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>(); 5236 if (Attr) { 5237 // Convert the reqd_work_group_size() attributes to metadata. 5238 llvm::LLVMContext &Context = F->getContext(); 5239 llvm::NamedMDNode *OpenCLMetadata = 5240 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info"); 5241 5242 SmallVector<llvm::Value*, 5> Operands; 5243 Operands.push_back(F); 5244 5245 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty, 5246 llvm::APInt(32, Attr->getXDim()))); 5247 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty, 5248 llvm::APInt(32, Attr->getYDim()))); 5249 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty, 5250 llvm::APInt(32, Attr->getZDim()))); 5251 5252 // Add a boolean constant operand for "required" (true) or "hint" (false) 5253 // for implementing the work_group_size_hint attr later. Currently 5254 // always true as the hint is not yet implemented. 5255 Operands.push_back(llvm::ConstantInt::getTrue(Context)); 5256 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands)); 5257 } 5258 } 5259 } 5260 } 5261 5262 } 5263 5264 //===----------------------------------------------------------------------===// 5265 // Hexagon ABI Implementation 5266 //===----------------------------------------------------------------------===// 5267 5268 namespace { 5269 5270 class HexagonABIInfo : public ABIInfo { 5271 5272 5273 public: 5274 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 5275 5276 private: 5277 5278 ABIArgInfo classifyReturnType(QualType RetTy) const; 5279 ABIArgInfo classifyArgumentType(QualType RetTy) const; 5280 5281 void computeInfo(CGFunctionInfo &FI) const override; 5282 5283 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 5284 CodeGenFunction &CGF) const override; 5285 }; 5286 5287 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo { 5288 public: 5289 HexagonTargetCodeGenInfo(CodeGenTypes &CGT) 5290 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {} 5291 5292 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 5293 return 29; 5294 } 5295 }; 5296 5297 } 5298 5299 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const { 5300 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 5301 for (auto &I : FI.arguments()) 5302 I.info = classifyArgumentType(I.type); 5303 } 5304 5305 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const { 5306 if (!isAggregateTypeForABI(Ty)) { 5307 // Treat an enum type as its underlying type. 5308 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 5309 Ty = EnumTy->getDecl()->getIntegerType(); 5310 5311 return (Ty->isPromotableIntegerType() ? 5312 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 5313 } 5314 5315 // Ignore empty records. 5316 if (isEmptyRecord(getContext(), Ty, true)) 5317 return ABIArgInfo::getIgnore(); 5318 5319 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 5320 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 5321 5322 uint64_t Size = getContext().getTypeSize(Ty); 5323 if (Size > 64) 5324 return ABIArgInfo::getIndirect(0, /*ByVal=*/true); 5325 // Pass in the smallest viable integer type. 5326 else if (Size > 32) 5327 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext())); 5328 else if (Size > 16) 5329 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 5330 else if (Size > 8) 5331 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 5332 else 5333 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 5334 } 5335 5336 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const { 5337 if (RetTy->isVoidType()) 5338 return ABIArgInfo::getIgnore(); 5339 5340 // Large vector types should be returned via memory. 5341 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64) 5342 return ABIArgInfo::getIndirect(0); 5343 5344 if (!isAggregateTypeForABI(RetTy)) { 5345 // Treat an enum type as its underlying type. 5346 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 5347 RetTy = EnumTy->getDecl()->getIntegerType(); 5348 5349 return (RetTy->isPromotableIntegerType() ? 5350 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 5351 } 5352 5353 // Structures with either a non-trivial destructor or a non-trivial 5354 // copy constructor are always indirect. 5355 if (isRecordReturnIndirect(RetTy, getCXXABI())) 5356 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 5357 5358 if (isEmptyRecord(getContext(), RetTy, true)) 5359 return ABIArgInfo::getIgnore(); 5360 5361 // Aggregates <= 8 bytes are returned in r0; other aggregates 5362 // are returned indirectly. 5363 uint64_t Size = getContext().getTypeSize(RetTy); 5364 if (Size <= 64) { 5365 // Return in the smallest viable integer type. 5366 if (Size <= 8) 5367 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 5368 if (Size <= 16) 5369 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 5370 if (Size <= 32) 5371 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 5372 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext())); 5373 } 5374 5375 return ABIArgInfo::getIndirect(0, /*ByVal=*/true); 5376 } 5377 5378 llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 5379 CodeGenFunction &CGF) const { 5380 // FIXME: Need to handle alignment 5381 llvm::Type *BPP = CGF.Int8PtrPtrTy; 5382 5383 CGBuilderTy &Builder = CGF.Builder; 5384 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, 5385 "ap"); 5386 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 5387 llvm::Type *PTy = 5388 llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 5389 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy); 5390 5391 uint64_t Offset = 5392 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4); 5393 llvm::Value *NextAddr = 5394 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), 5395 "ap.next"); 5396 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 5397 5398 return AddrTyped; 5399 } 5400 5401 5402 //===----------------------------------------------------------------------===// 5403 // SPARC v9 ABI Implementation. 5404 // Based on the SPARC Compliance Definition version 2.4.1. 5405 // 5406 // Function arguments a mapped to a nominal "parameter array" and promoted to 5407 // registers depending on their type. Each argument occupies 8 or 16 bytes in 5408 // the array, structs larger than 16 bytes are passed indirectly. 5409 // 5410 // One case requires special care: 5411 // 5412 // struct mixed { 5413 // int i; 5414 // float f; 5415 // }; 5416 // 5417 // When a struct mixed is passed by value, it only occupies 8 bytes in the 5418 // parameter array, but the int is passed in an integer register, and the float 5419 // is passed in a floating point register. This is represented as two arguments 5420 // with the LLVM IR inreg attribute: 5421 // 5422 // declare void f(i32 inreg %i, float inreg %f) 5423 // 5424 // The code generator will only allocate 4 bytes from the parameter array for 5425 // the inreg arguments. All other arguments are allocated a multiple of 8 5426 // bytes. 5427 // 5428 namespace { 5429 class SparcV9ABIInfo : public ABIInfo { 5430 public: 5431 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 5432 5433 private: 5434 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const; 5435 void computeInfo(CGFunctionInfo &FI) const override; 5436 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 5437 CodeGenFunction &CGF) const override; 5438 5439 // Coercion type builder for structs passed in registers. The coercion type 5440 // serves two purposes: 5441 // 5442 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned' 5443 // in registers. 5444 // 2. Expose aligned floating point elements as first-level elements, so the 5445 // code generator knows to pass them in floating point registers. 5446 // 5447 // We also compute the InReg flag which indicates that the struct contains 5448 // aligned 32-bit floats. 5449 // 5450 struct CoerceBuilder { 5451 llvm::LLVMContext &Context; 5452 const llvm::DataLayout &DL; 5453 SmallVector<llvm::Type*, 8> Elems; 5454 uint64_t Size; 5455 bool InReg; 5456 5457 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl) 5458 : Context(c), DL(dl), Size(0), InReg(false) {} 5459 5460 // Pad Elems with integers until Size is ToSize. 5461 void pad(uint64_t ToSize) { 5462 assert(ToSize >= Size && "Cannot remove elements"); 5463 if (ToSize == Size) 5464 return; 5465 5466 // Finish the current 64-bit word. 5467 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64); 5468 if (Aligned > Size && Aligned <= ToSize) { 5469 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size)); 5470 Size = Aligned; 5471 } 5472 5473 // Add whole 64-bit words. 5474 while (Size + 64 <= ToSize) { 5475 Elems.push_back(llvm::Type::getInt64Ty(Context)); 5476 Size += 64; 5477 } 5478 5479 // Final in-word padding. 5480 if (Size < ToSize) { 5481 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size)); 5482 Size = ToSize; 5483 } 5484 } 5485 5486 // Add a floating point element at Offset. 5487 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) { 5488 // Unaligned floats are treated as integers. 5489 if (Offset % Bits) 5490 return; 5491 // The InReg flag is only required if there are any floats < 64 bits. 5492 if (Bits < 64) 5493 InReg = true; 5494 pad(Offset); 5495 Elems.push_back(Ty); 5496 Size = Offset + Bits; 5497 } 5498 5499 // Add a struct type to the coercion type, starting at Offset (in bits). 5500 void addStruct(uint64_t Offset, llvm::StructType *StrTy) { 5501 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy); 5502 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) { 5503 llvm::Type *ElemTy = StrTy->getElementType(i); 5504 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i); 5505 switch (ElemTy->getTypeID()) { 5506 case llvm::Type::StructTyID: 5507 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy)); 5508 break; 5509 case llvm::Type::FloatTyID: 5510 addFloat(ElemOffset, ElemTy, 32); 5511 break; 5512 case llvm::Type::DoubleTyID: 5513 addFloat(ElemOffset, ElemTy, 64); 5514 break; 5515 case llvm::Type::FP128TyID: 5516 addFloat(ElemOffset, ElemTy, 128); 5517 break; 5518 case llvm::Type::PointerTyID: 5519 if (ElemOffset % 64 == 0) { 5520 pad(ElemOffset); 5521 Elems.push_back(ElemTy); 5522 Size += 64; 5523 } 5524 break; 5525 default: 5526 break; 5527 } 5528 } 5529 } 5530 5531 // Check if Ty is a usable substitute for the coercion type. 5532 bool isUsableType(llvm::StructType *Ty) const { 5533 if (Ty->getNumElements() != Elems.size()) 5534 return false; 5535 for (unsigned i = 0, e = Elems.size(); i != e; ++i) 5536 if (Elems[i] != Ty->getElementType(i)) 5537 return false; 5538 return true; 5539 } 5540 5541 // Get the coercion type as a literal struct type. 5542 llvm::Type *getType() const { 5543 if (Elems.size() == 1) 5544 return Elems.front(); 5545 else 5546 return llvm::StructType::get(Context, Elems); 5547 } 5548 }; 5549 }; 5550 } // end anonymous namespace 5551 5552 ABIArgInfo 5553 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const { 5554 if (Ty->isVoidType()) 5555 return ABIArgInfo::getIgnore(); 5556 5557 uint64_t Size = getContext().getTypeSize(Ty); 5558 5559 // Anything too big to fit in registers is passed with an explicit indirect 5560 // pointer / sret pointer. 5561 if (Size > SizeLimit) 5562 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 5563 5564 // Treat an enum type as its underlying type. 5565 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 5566 Ty = EnumTy->getDecl()->getIntegerType(); 5567 5568 // Integer types smaller than a register are extended. 5569 if (Size < 64 && Ty->isIntegerType()) 5570 return ABIArgInfo::getExtend(); 5571 5572 // Other non-aggregates go in registers. 5573 if (!isAggregateTypeForABI(Ty)) 5574 return ABIArgInfo::getDirect(); 5575 5576 // If a C++ object has either a non-trivial copy constructor or a non-trivial 5577 // destructor, it is passed with an explicit indirect pointer / sret pointer. 5578 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 5579 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 5580 5581 // This is a small aggregate type that should be passed in registers. 5582 // Build a coercion type from the LLVM struct type. 5583 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty)); 5584 if (!StrTy) 5585 return ABIArgInfo::getDirect(); 5586 5587 CoerceBuilder CB(getVMContext(), getDataLayout()); 5588 CB.addStruct(0, StrTy); 5589 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64)); 5590 5591 // Try to use the original type for coercion. 5592 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType(); 5593 5594 if (CB.InReg) 5595 return ABIArgInfo::getDirectInReg(CoerceTy); 5596 else 5597 return ABIArgInfo::getDirect(CoerceTy); 5598 } 5599 5600 llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 5601 CodeGenFunction &CGF) const { 5602 ABIArgInfo AI = classifyType(Ty, 16 * 8); 5603 llvm::Type *ArgTy = CGT.ConvertType(Ty); 5604 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 5605 AI.setCoerceToType(ArgTy); 5606 5607 llvm::Type *BPP = CGF.Int8PtrPtrTy; 5608 CGBuilderTy &Builder = CGF.Builder; 5609 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); 5610 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 5611 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 5612 llvm::Value *ArgAddr; 5613 unsigned Stride; 5614 5615 switch (AI.getKind()) { 5616 case ABIArgInfo::Expand: 5617 case ABIArgInfo::InAlloca: 5618 llvm_unreachable("Unsupported ABI kind for va_arg"); 5619 5620 case ABIArgInfo::Extend: 5621 Stride = 8; 5622 ArgAddr = Builder 5623 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy), 5624 "extend"); 5625 break; 5626 5627 case ABIArgInfo::Direct: 5628 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType()); 5629 ArgAddr = Addr; 5630 break; 5631 5632 case ABIArgInfo::Indirect: 5633 Stride = 8; 5634 ArgAddr = Builder.CreateBitCast(Addr, 5635 llvm::PointerType::getUnqual(ArgPtrTy), 5636 "indirect"); 5637 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg"); 5638 break; 5639 5640 case ABIArgInfo::Ignore: 5641 return llvm::UndefValue::get(ArgPtrTy); 5642 } 5643 5644 // Update VAList. 5645 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next"); 5646 Builder.CreateStore(Addr, VAListAddrAsBPP); 5647 5648 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr"); 5649 } 5650 5651 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const { 5652 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8); 5653 for (auto &I : FI.arguments()) 5654 I.info = classifyType(I.type, 16 * 8); 5655 } 5656 5657 namespace { 5658 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo { 5659 public: 5660 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT) 5661 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {} 5662 5663 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 5664 return 14; 5665 } 5666 5667 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5668 llvm::Value *Address) const override; 5669 }; 5670 } // end anonymous namespace 5671 5672 bool 5673 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5674 llvm::Value *Address) const { 5675 // This is calculated from the LLVM and GCC tables and verified 5676 // against gcc output. AFAIK all ABIs use the same encoding. 5677 5678 CodeGen::CGBuilderTy &Builder = CGF.Builder; 5679 5680 llvm::IntegerType *i8 = CGF.Int8Ty; 5681 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 5682 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 5683 5684 // 0-31: the 8-byte general-purpose registers 5685 AssignToArrayRange(Builder, Address, Eight8, 0, 31); 5686 5687 // 32-63: f0-31, the 4-byte floating-point registers 5688 AssignToArrayRange(Builder, Address, Four8, 32, 63); 5689 5690 // Y = 64 5691 // PSR = 65 5692 // WIM = 66 5693 // TBR = 67 5694 // PC = 68 5695 // NPC = 69 5696 // FSR = 70 5697 // CSR = 71 5698 AssignToArrayRange(Builder, Address, Eight8, 64, 71); 5699 5700 // 72-87: d0-15, the 8-byte floating-point registers 5701 AssignToArrayRange(Builder, Address, Eight8, 72, 87); 5702 5703 return false; 5704 } 5705 5706 5707 //===----------------------------------------------------------------------===// 5708 // XCore ABI Implementation 5709 //===----------------------------------------------------------------------===// 5710 namespace { 5711 class XCoreABIInfo : public DefaultABIInfo { 5712 public: 5713 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 5714 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 5715 CodeGenFunction &CGF) const override; 5716 }; 5717 5718 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo { 5719 public: 5720 XCoreTargetCodeGenInfo(CodeGenTypes &CGT) 5721 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {} 5722 }; 5723 } // End anonymous namespace. 5724 5725 llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 5726 CodeGenFunction &CGF) const { 5727 CGBuilderTy &Builder = CGF.Builder; 5728 5729 // Get the VAList. 5730 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, 5731 CGF.Int8PtrPtrTy); 5732 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP); 5733 5734 // Handle the argument. 5735 ABIArgInfo AI = classifyArgumentType(Ty); 5736 llvm::Type *ArgTy = CGT.ConvertType(Ty); 5737 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 5738 AI.setCoerceToType(ArgTy); 5739 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 5740 llvm::Value *Val; 5741 uint64_t ArgSize = 0; 5742 switch (AI.getKind()) { 5743 case ABIArgInfo::Expand: 5744 case ABIArgInfo::InAlloca: 5745 llvm_unreachable("Unsupported ABI kind for va_arg"); 5746 case ABIArgInfo::Ignore: 5747 Val = llvm::UndefValue::get(ArgPtrTy); 5748 ArgSize = 0; 5749 break; 5750 case ABIArgInfo::Extend: 5751 case ABIArgInfo::Direct: 5752 Val = Builder.CreatePointerCast(AP, ArgPtrTy); 5753 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType()); 5754 if (ArgSize < 4) 5755 ArgSize = 4; 5756 break; 5757 case ABIArgInfo::Indirect: 5758 llvm::Value *ArgAddr; 5759 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy)); 5760 ArgAddr = Builder.CreateLoad(ArgAddr); 5761 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy); 5762 ArgSize = 4; 5763 break; 5764 } 5765 5766 // Increment the VAList. 5767 if (ArgSize) { 5768 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize); 5769 Builder.CreateStore(APN, VAListAddrAsBPP); 5770 } 5771 return Val; 5772 } 5773 5774 //===----------------------------------------------------------------------===// 5775 // Driver code 5776 //===----------------------------------------------------------------------===// 5777 5778 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() { 5779 if (TheTargetCodeGenInfo) 5780 return *TheTargetCodeGenInfo; 5781 5782 const llvm::Triple &Triple = getTarget().getTriple(); 5783 switch (Triple.getArch()) { 5784 default: 5785 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types)); 5786 5787 case llvm::Triple::le32: 5788 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types)); 5789 case llvm::Triple::mips: 5790 case llvm::Triple::mipsel: 5791 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true)); 5792 5793 case llvm::Triple::mips64: 5794 case llvm::Triple::mips64el: 5795 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false)); 5796 5797 case llvm::Triple::aarch64: 5798 case llvm::Triple::aarch64_be: 5799 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types)); 5800 5801 case llvm::Triple::arm: 5802 case llvm::Triple::thumb: 5803 { 5804 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS; 5805 if (strcmp(getTarget().getABI(), "apcs-gnu") == 0) 5806 Kind = ARMABIInfo::APCS; 5807 else if (CodeGenOpts.FloatABI == "hard" || 5808 (CodeGenOpts.FloatABI != "soft" && 5809 Triple.getEnvironment() == llvm::Triple::GNUEABIHF)) 5810 Kind = ARMABIInfo::AAPCS_VFP; 5811 5812 switch (Triple.getOS()) { 5813 case llvm::Triple::NaCl: 5814 return *(TheTargetCodeGenInfo = 5815 new NaClARMTargetCodeGenInfo(Types, Kind)); 5816 default: 5817 return *(TheTargetCodeGenInfo = 5818 new ARMTargetCodeGenInfo(Types, Kind)); 5819 } 5820 } 5821 5822 case llvm::Triple::ppc: 5823 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types)); 5824 case llvm::Triple::ppc64: 5825 if (Triple.isOSBinFormatELF()) 5826 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types)); 5827 else 5828 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types)); 5829 case llvm::Triple::ppc64le: 5830 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!"); 5831 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types)); 5832 5833 case llvm::Triple::nvptx: 5834 case llvm::Triple::nvptx64: 5835 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types)); 5836 5837 case llvm::Triple::msp430: 5838 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types)); 5839 5840 case llvm::Triple::systemz: 5841 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types)); 5842 5843 case llvm::Triple::tce: 5844 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types)); 5845 5846 case llvm::Triple::x86: { 5847 bool IsDarwinVectorABI = Triple.isOSDarwin(); 5848 bool IsSmallStructInRegABI = 5849 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 5850 bool IsWin32FloatStructABI = (Triple.getOS() == llvm::Triple::Win32); 5851 5852 if (Triple.getOS() == llvm::Triple::Win32) { 5853 return *(TheTargetCodeGenInfo = 5854 new WinX86_32TargetCodeGenInfo(Types, 5855 IsDarwinVectorABI, IsSmallStructInRegABI, 5856 IsWin32FloatStructABI, 5857 CodeGenOpts.NumRegisterParameters)); 5858 } else { 5859 return *(TheTargetCodeGenInfo = 5860 new X86_32TargetCodeGenInfo(Types, 5861 IsDarwinVectorABI, IsSmallStructInRegABI, 5862 IsWin32FloatStructABI, 5863 CodeGenOpts.NumRegisterParameters)); 5864 } 5865 } 5866 5867 case llvm::Triple::x86_64: { 5868 bool HasAVX = strcmp(getTarget().getABI(), "avx") == 0; 5869 5870 switch (Triple.getOS()) { 5871 case llvm::Triple::Win32: 5872 case llvm::Triple::MinGW32: 5873 case llvm::Triple::Cygwin: 5874 return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types)); 5875 case llvm::Triple::NaCl: 5876 return *(TheTargetCodeGenInfo = new NaClX86_64TargetCodeGenInfo(Types, 5877 HasAVX)); 5878 default: 5879 return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types, 5880 HasAVX)); 5881 } 5882 } 5883 case llvm::Triple::hexagon: 5884 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types)); 5885 case llvm::Triple::sparcv9: 5886 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types)); 5887 case llvm::Triple::xcore: 5888 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types)); 5889 5890 } 5891 } 5892