1 //===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly ------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains a printer that converts from our internal representation 10 // of machine-dependent LLVM code to PowerPC assembly language. This printer is 11 // the output mechanism used by `llc'. 12 // 13 // Documentation at http://developer.apple.com/documentation/DeveloperTools/ 14 // Reference/Assembler/ASMIntroduction/chapter_1_section_1.html 15 // 16 //===----------------------------------------------------------------------===// 17 18 #include "MCTargetDesc/PPCInstPrinter.h" 19 #include "MCTargetDesc/PPCMCExpr.h" 20 #include "MCTargetDesc/PPCMCTargetDesc.h" 21 #include "MCTargetDesc/PPCPredicates.h" 22 #include "PPC.h" 23 #include "PPCInstrInfo.h" 24 #include "PPCMachineFunctionInfo.h" 25 #include "PPCSubtarget.h" 26 #include "PPCTargetMachine.h" 27 #include "PPCTargetStreamer.h" 28 #include "TargetInfo/PowerPCTargetInfo.h" 29 #include "llvm/ADT/MapVector.h" 30 #include "llvm/ADT/SmallPtrSet.h" 31 #include "llvm/ADT/StringRef.h" 32 #include "llvm/ADT/Triple.h" 33 #include "llvm/ADT/Twine.h" 34 #include "llvm/BinaryFormat/ELF.h" 35 #include "llvm/CodeGen/AsmPrinter.h" 36 #include "llvm/CodeGen/MachineBasicBlock.h" 37 #include "llvm/CodeGen/MachineFrameInfo.h" 38 #include "llvm/CodeGen/MachineFunction.h" 39 #include "llvm/CodeGen/MachineInstr.h" 40 #include "llvm/CodeGen/MachineModuleInfoImpls.h" 41 #include "llvm/CodeGen/MachineOperand.h" 42 #include "llvm/CodeGen/MachineRegisterInfo.h" 43 #include "llvm/CodeGen/StackMaps.h" 44 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 45 #include "llvm/IR/DataLayout.h" 46 #include "llvm/IR/GlobalValue.h" 47 #include "llvm/IR/GlobalVariable.h" 48 #include "llvm/IR/Module.h" 49 #include "llvm/MC/MCAsmInfo.h" 50 #include "llvm/MC/MCContext.h" 51 #include "llvm/MC/MCDirectives.h" 52 #include "llvm/MC/MCExpr.h" 53 #include "llvm/MC/MCInst.h" 54 #include "llvm/MC/MCInstBuilder.h" 55 #include "llvm/MC/MCSectionELF.h" 56 #include "llvm/MC/MCSectionXCOFF.h" 57 #include "llvm/MC/MCStreamer.h" 58 #include "llvm/MC/MCSymbol.h" 59 #include "llvm/MC/MCSymbolELF.h" 60 #include "llvm/MC/MCSymbolXCOFF.h" 61 #include "llvm/MC/SectionKind.h" 62 #include "llvm/MC/TargetRegistry.h" 63 #include "llvm/Support/Casting.h" 64 #include "llvm/Support/CodeGen.h" 65 #include "llvm/Support/Debug.h" 66 #include "llvm/Support/Error.h" 67 #include "llvm/Support/ErrorHandling.h" 68 #include "llvm/Support/Process.h" 69 #include "llvm/Support/raw_ostream.h" 70 #include "llvm/Target/TargetMachine.h" 71 #include "llvm/Transforms/Utils/ModuleUtils.h" 72 #include <algorithm> 73 #include <cassert> 74 #include <cstdint> 75 #include <memory> 76 #include <new> 77 78 using namespace llvm; 79 using namespace llvm::XCOFF; 80 81 #define DEBUG_TYPE "asmprinter" 82 83 static cl::opt<bool> EnableSSPCanaryBitInTB( 84 "aix-ssp-tb-bit", cl::init(false), 85 cl::desc("Enable Passing SSP Canary info in Trackback on AIX"), cl::Hidden); 86 87 // Specialize DenseMapInfo to allow 88 // std::pair<const MCSymbol *, MCSymbolRefExpr::VariantKind> in DenseMap. 89 // This specialization is needed here because that type is used as keys in the 90 // map representing TOC entries. 91 namespace llvm { 92 template <> 93 struct DenseMapInfo<std::pair<const MCSymbol *, MCSymbolRefExpr::VariantKind>> { 94 using TOCKey = std::pair<const MCSymbol *, MCSymbolRefExpr::VariantKind>; 95 96 static inline TOCKey getEmptyKey() { 97 return {nullptr, MCSymbolRefExpr::VariantKind::VK_None}; 98 } 99 static inline TOCKey getTombstoneKey() { 100 return {nullptr, MCSymbolRefExpr::VariantKind::VK_Invalid}; 101 } 102 static unsigned getHashValue(const TOCKey &PairVal) { 103 return detail::combineHashValue( 104 DenseMapInfo<const MCSymbol *>::getHashValue(PairVal.first), 105 DenseMapInfo<int>::getHashValue(PairVal.second)); 106 } 107 static bool isEqual(const TOCKey &A, const TOCKey &B) { return A == B; } 108 }; 109 } // end namespace llvm 110 111 namespace { 112 113 enum { 114 // GNU attribute tags for PowerPC ABI 115 Tag_GNU_Power_ABI_FP = 4, 116 Tag_GNU_Power_ABI_Vector = 8, 117 Tag_GNU_Power_ABI_Struct_Return = 12, 118 119 // GNU attribute values for PowerPC float ABI, as combination of two parts 120 Val_GNU_Power_ABI_NoFloat = 0b00, 121 Val_GNU_Power_ABI_HardFloat_DP = 0b01, 122 Val_GNU_Power_ABI_SoftFloat_DP = 0b10, 123 Val_GNU_Power_ABI_HardFloat_SP = 0b11, 124 125 Val_GNU_Power_ABI_LDBL_IBM128 = 0b0100, 126 Val_GNU_Power_ABI_LDBL_64 = 0b1000, 127 Val_GNU_Power_ABI_LDBL_IEEE128 = 0b1100, 128 }; 129 130 class PPCAsmPrinter : public AsmPrinter { 131 protected: 132 // For TLS on AIX, we need to be able to identify TOC entries of specific 133 // VariantKind so we can add the right relocations when we generate the 134 // entries. So each entry is represented by a pair of MCSymbol and 135 // VariantKind. For example, we need to be able to identify the following 136 // entry as a TLSGD entry so we can add the @m relocation: 137 // .tc .i[TC],i[TL]@m 138 // By default, VK_None is used for the VariantKind. 139 MapVector<std::pair<const MCSymbol *, MCSymbolRefExpr::VariantKind>, 140 MCSymbol *> 141 TOC; 142 const PPCSubtarget *Subtarget = nullptr; 143 StackMaps SM; 144 145 public: 146 explicit PPCAsmPrinter(TargetMachine &TM, 147 std::unique_ptr<MCStreamer> Streamer) 148 : AsmPrinter(TM, std::move(Streamer)), SM(*this) {} 149 150 StringRef getPassName() const override { return "PowerPC Assembly Printer"; } 151 152 MCSymbol *lookUpOrCreateTOCEntry(const MCSymbol *Sym, 153 MCSymbolRefExpr::VariantKind Kind = 154 MCSymbolRefExpr::VariantKind::VK_None); 155 156 bool doInitialization(Module &M) override { 157 if (!TOC.empty()) 158 TOC.clear(); 159 return AsmPrinter::doInitialization(M); 160 } 161 162 void emitInstruction(const MachineInstr *MI) override; 163 164 /// This function is for PrintAsmOperand and PrintAsmMemoryOperand, 165 /// invoked by EmitMSInlineAsmStr and EmitGCCInlineAsmStr only. 166 /// The \p MI would be INLINEASM ONLY. 167 void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O); 168 169 void PrintSymbolOperand(const MachineOperand &MO, raw_ostream &O) override; 170 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 171 const char *ExtraCode, raw_ostream &O) override; 172 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, 173 const char *ExtraCode, raw_ostream &O) override; 174 175 void emitEndOfAsmFile(Module &M) override; 176 177 void LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI); 178 void LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI); 179 void EmitTlsCall(const MachineInstr *MI, MCSymbolRefExpr::VariantKind VK); 180 bool runOnMachineFunction(MachineFunction &MF) override { 181 Subtarget = &MF.getSubtarget<PPCSubtarget>(); 182 bool Changed = AsmPrinter::runOnMachineFunction(MF); 183 emitXRayTable(); 184 return Changed; 185 } 186 }; 187 188 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux 189 class PPCLinuxAsmPrinter : public PPCAsmPrinter { 190 public: 191 explicit PPCLinuxAsmPrinter(TargetMachine &TM, 192 std::unique_ptr<MCStreamer> Streamer) 193 : PPCAsmPrinter(TM, std::move(Streamer)) {} 194 195 StringRef getPassName() const override { 196 return "Linux PPC Assembly Printer"; 197 } 198 199 void emitGNUAttributes(Module &M); 200 201 void emitStartOfAsmFile(Module &M) override; 202 void emitEndOfAsmFile(Module &) override; 203 204 void emitFunctionEntryLabel() override; 205 206 void emitFunctionBodyStart() override; 207 void emitFunctionBodyEnd() override; 208 void emitInstruction(const MachineInstr *MI) override; 209 }; 210 211 class PPCAIXAsmPrinter : public PPCAsmPrinter { 212 private: 213 /// Symbols lowered from ExternalSymbolSDNodes, we will need to emit extern 214 /// linkage for them in AIX. 215 SmallPtrSet<MCSymbol *, 8> ExtSymSDNodeSymbols; 216 217 /// A format indicator and unique trailing identifier to form part of the 218 /// sinit/sterm function names. 219 std::string FormatIndicatorAndUniqueModId; 220 221 // Record a list of GlobalAlias associated with a GlobalObject. 222 // This is used for AIX's extra-label-at-definition aliasing strategy. 223 DenseMap<const GlobalObject *, SmallVector<const GlobalAlias *, 1>> 224 GOAliasMap; 225 226 uint16_t getNumberOfVRSaved(); 227 void emitTracebackTable(); 228 229 SmallVector<const GlobalVariable *, 8> TOCDataGlobalVars; 230 231 void emitGlobalVariableHelper(const GlobalVariable *); 232 233 // Get the offset of an alias based on its AliaseeObject. 234 uint64_t getAliasOffset(const Constant *C); 235 236 public: 237 PPCAIXAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer) 238 : PPCAsmPrinter(TM, std::move(Streamer)) { 239 if (MAI->isLittleEndian()) 240 report_fatal_error( 241 "cannot create AIX PPC Assembly Printer for a little-endian target"); 242 } 243 244 StringRef getPassName() const override { return "AIX PPC Assembly Printer"; } 245 246 bool doInitialization(Module &M) override; 247 248 void emitXXStructorList(const DataLayout &DL, const Constant *List, 249 bool IsCtor) override; 250 251 void SetupMachineFunction(MachineFunction &MF) override; 252 253 void emitGlobalVariable(const GlobalVariable *GV) override; 254 255 void emitFunctionDescriptor() override; 256 257 void emitFunctionEntryLabel() override; 258 259 void emitFunctionBodyEnd() override; 260 261 void emitPGORefs(); 262 263 void emitEndOfAsmFile(Module &) override; 264 265 void emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const override; 266 267 void emitInstruction(const MachineInstr *MI) override; 268 269 bool doFinalization(Module &M) override; 270 271 void emitTTypeReference(const GlobalValue *GV, unsigned Encoding) override; 272 }; 273 274 } // end anonymous namespace 275 276 void PPCAsmPrinter::PrintSymbolOperand(const MachineOperand &MO, 277 raw_ostream &O) { 278 // Computing the address of a global symbol, not calling it. 279 const GlobalValue *GV = MO.getGlobal(); 280 getSymbol(GV)->print(O, MAI); 281 printOffset(MO.getOffset(), O); 282 } 283 284 void PPCAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo, 285 raw_ostream &O) { 286 const DataLayout &DL = getDataLayout(); 287 const MachineOperand &MO = MI->getOperand(OpNo); 288 289 switch (MO.getType()) { 290 case MachineOperand::MO_Register: { 291 // The MI is INLINEASM ONLY and UseVSXReg is always false. 292 const char *RegName = PPCInstPrinter::getRegisterName(MO.getReg()); 293 294 // Linux assembler (Others?) does not take register mnemonics. 295 // FIXME - What about special registers used in mfspr/mtspr? 296 O << PPCRegisterInfo::stripRegisterPrefix(RegName); 297 return; 298 } 299 case MachineOperand::MO_Immediate: 300 O << MO.getImm(); 301 return; 302 303 case MachineOperand::MO_MachineBasicBlock: 304 MO.getMBB()->getSymbol()->print(O, MAI); 305 return; 306 case MachineOperand::MO_ConstantPoolIndex: 307 O << DL.getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_' 308 << MO.getIndex(); 309 return; 310 case MachineOperand::MO_BlockAddress: 311 GetBlockAddressSymbol(MO.getBlockAddress())->print(O, MAI); 312 return; 313 case MachineOperand::MO_GlobalAddress: { 314 PrintSymbolOperand(MO, O); 315 return; 316 } 317 318 default: 319 O << "<unknown operand type: " << (unsigned)MO.getType() << ">"; 320 return; 321 } 322 } 323 324 /// PrintAsmOperand - Print out an operand for an inline asm expression. 325 /// 326 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 327 const char *ExtraCode, raw_ostream &O) { 328 // Does this asm operand have a single letter operand modifier? 329 if (ExtraCode && ExtraCode[0]) { 330 if (ExtraCode[1] != 0) return true; // Unknown modifier. 331 332 switch (ExtraCode[0]) { 333 default: 334 // See if this is a generic print operand 335 return AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, O); 336 case 'L': // Write second word of DImode reference. 337 // Verify that this operand has two consecutive registers. 338 if (!MI->getOperand(OpNo).isReg() || 339 OpNo+1 == MI->getNumOperands() || 340 !MI->getOperand(OpNo+1).isReg()) 341 return true; 342 ++OpNo; // Return the high-part. 343 break; 344 case 'I': 345 // Write 'i' if an integer constant, otherwise nothing. Used to print 346 // addi vs add, etc. 347 if (MI->getOperand(OpNo).isImm()) 348 O << "i"; 349 return false; 350 case 'x': 351 if(!MI->getOperand(OpNo).isReg()) 352 return true; 353 // This operand uses VSX numbering. 354 // If the operand is a VMX register, convert it to a VSX register. 355 Register Reg = MI->getOperand(OpNo).getReg(); 356 if (PPCInstrInfo::isVRRegister(Reg)) 357 Reg = PPC::VSX32 + (Reg - PPC::V0); 358 else if (PPCInstrInfo::isVFRegister(Reg)) 359 Reg = PPC::VSX32 + (Reg - PPC::VF0); 360 const char *RegName; 361 RegName = PPCInstPrinter::getRegisterName(Reg); 362 RegName = PPCRegisterInfo::stripRegisterPrefix(RegName); 363 O << RegName; 364 return false; 365 } 366 } 367 368 printOperand(MI, OpNo, O); 369 return false; 370 } 371 372 // At the moment, all inline asm memory operands are a single register. 373 // In any case, the output of this routine should always be just one 374 // assembler operand. 375 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, 376 const char *ExtraCode, 377 raw_ostream &O) { 378 if (ExtraCode && ExtraCode[0]) { 379 if (ExtraCode[1] != 0) return true; // Unknown modifier. 380 381 switch (ExtraCode[0]) { 382 default: return true; // Unknown modifier. 383 case 'L': // A memory reference to the upper word of a double word op. 384 O << getDataLayout().getPointerSize() << "("; 385 printOperand(MI, OpNo, O); 386 O << ")"; 387 return false; 388 case 'y': // A memory reference for an X-form instruction 389 O << "0, "; 390 printOperand(MI, OpNo, O); 391 return false; 392 case 'I': 393 // Write 'i' if an integer constant, otherwise nothing. Used to print 394 // addi vs add, etc. 395 if (MI->getOperand(OpNo).isImm()) 396 O << "i"; 397 return false; 398 case 'U': // Print 'u' for update form. 399 case 'X': // Print 'x' for indexed form. 400 // FIXME: Currently for PowerPC memory operands are always loaded 401 // into a register, so we never get an update or indexed form. 402 // This is bad even for offset forms, since even if we know we 403 // have a value in -16(r1), we will generate a load into r<n> 404 // and then load from 0(r<n>). Until that issue is fixed, 405 // tolerate 'U' and 'X' but don't output anything. 406 assert(MI->getOperand(OpNo).isReg()); 407 return false; 408 } 409 } 410 411 assert(MI->getOperand(OpNo).isReg()); 412 O << "0("; 413 printOperand(MI, OpNo, O); 414 O << ")"; 415 return false; 416 } 417 418 /// lookUpOrCreateTOCEntry -- Given a symbol, look up whether a TOC entry 419 /// exists for it. If not, create one. Then return a symbol that references 420 /// the TOC entry. 421 MCSymbol * 422 PPCAsmPrinter::lookUpOrCreateTOCEntry(const MCSymbol *Sym, 423 MCSymbolRefExpr::VariantKind Kind) { 424 MCSymbol *&TOCEntry = TOC[{Sym, Kind}]; 425 if (!TOCEntry) 426 TOCEntry = createTempSymbol("C"); 427 return TOCEntry; 428 } 429 430 void PPCAsmPrinter::emitEndOfAsmFile(Module &M) { 431 emitStackMaps(SM); 432 } 433 434 void PPCAsmPrinter::LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI) { 435 unsigned NumNOPBytes = MI.getOperand(1).getImm(); 436 437 auto &Ctx = OutStreamer->getContext(); 438 MCSymbol *MILabel = Ctx.createTempSymbol(); 439 OutStreamer->emitLabel(MILabel); 440 441 SM.recordStackMap(*MILabel, MI); 442 assert(NumNOPBytes % 4 == 0 && "Invalid number of NOP bytes requested!"); 443 444 // Scan ahead to trim the shadow. 445 const MachineBasicBlock &MBB = *MI.getParent(); 446 MachineBasicBlock::const_iterator MII(MI); 447 ++MII; 448 while (NumNOPBytes > 0) { 449 if (MII == MBB.end() || MII->isCall() || 450 MII->getOpcode() == PPC::DBG_VALUE || 451 MII->getOpcode() == TargetOpcode::PATCHPOINT || 452 MII->getOpcode() == TargetOpcode::STACKMAP) 453 break; 454 ++MII; 455 NumNOPBytes -= 4; 456 } 457 458 // Emit nops. 459 for (unsigned i = 0; i < NumNOPBytes; i += 4) 460 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP)); 461 } 462 463 // Lower a patchpoint of the form: 464 // [<def>], <id>, <numBytes>, <target>, <numArgs> 465 void PPCAsmPrinter::LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI) { 466 auto &Ctx = OutStreamer->getContext(); 467 MCSymbol *MILabel = Ctx.createTempSymbol(); 468 OutStreamer->emitLabel(MILabel); 469 470 SM.recordPatchPoint(*MILabel, MI); 471 PatchPointOpers Opers(&MI); 472 473 unsigned EncodedBytes = 0; 474 const MachineOperand &CalleeMO = Opers.getCallTarget(); 475 476 if (CalleeMO.isImm()) { 477 int64_t CallTarget = CalleeMO.getImm(); 478 if (CallTarget) { 479 assert((CallTarget & 0xFFFFFFFFFFFF) == CallTarget && 480 "High 16 bits of call target should be zero."); 481 Register ScratchReg = MI.getOperand(Opers.getNextScratchIdx()).getReg(); 482 EncodedBytes = 0; 483 // Materialize the jump address: 484 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI8) 485 .addReg(ScratchReg) 486 .addImm((CallTarget >> 32) & 0xFFFF)); 487 ++EncodedBytes; 488 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::RLDIC) 489 .addReg(ScratchReg) 490 .addReg(ScratchReg) 491 .addImm(32).addImm(16)); 492 ++EncodedBytes; 493 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORIS8) 494 .addReg(ScratchReg) 495 .addReg(ScratchReg) 496 .addImm((CallTarget >> 16) & 0xFFFF)); 497 ++EncodedBytes; 498 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORI8) 499 .addReg(ScratchReg) 500 .addReg(ScratchReg) 501 .addImm(CallTarget & 0xFFFF)); 502 503 // Save the current TOC pointer before the remote call. 504 int TOCSaveOffset = Subtarget->getFrameLowering()->getTOCSaveOffset(); 505 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::STD) 506 .addReg(PPC::X2) 507 .addImm(TOCSaveOffset) 508 .addReg(PPC::X1)); 509 ++EncodedBytes; 510 511 // If we're on ELFv1, then we need to load the actual function pointer 512 // from the function descriptor. 513 if (!Subtarget->isELFv2ABI()) { 514 // Load the new TOC pointer and the function address, but not r11 515 // (needing this is rare, and loading it here would prevent passing it 516 // via a 'nest' parameter. 517 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD) 518 .addReg(PPC::X2) 519 .addImm(8) 520 .addReg(ScratchReg)); 521 ++EncodedBytes; 522 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD) 523 .addReg(ScratchReg) 524 .addImm(0) 525 .addReg(ScratchReg)); 526 ++EncodedBytes; 527 } 528 529 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTCTR8) 530 .addReg(ScratchReg)); 531 ++EncodedBytes; 532 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BCTRL8)); 533 ++EncodedBytes; 534 535 // Restore the TOC pointer after the call. 536 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD) 537 .addReg(PPC::X2) 538 .addImm(TOCSaveOffset) 539 .addReg(PPC::X1)); 540 ++EncodedBytes; 541 } 542 } else if (CalleeMO.isGlobal()) { 543 const GlobalValue *GValue = CalleeMO.getGlobal(); 544 MCSymbol *MOSymbol = getSymbol(GValue); 545 const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, OutContext); 546 547 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL8_NOP) 548 .addExpr(SymVar)); 549 EncodedBytes += 2; 550 } 551 552 // Each instruction is 4 bytes. 553 EncodedBytes *= 4; 554 555 // Emit padding. 556 unsigned NumBytes = Opers.getNumPatchBytes(); 557 assert(NumBytes >= EncodedBytes && 558 "Patchpoint can't request size less than the length of a call."); 559 assert((NumBytes - EncodedBytes) % 4 == 0 && 560 "Invalid number of NOP bytes requested!"); 561 for (unsigned i = EncodedBytes; i < NumBytes; i += 4) 562 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP)); 563 } 564 565 /// This helper function creates the TlsGetAddr MCSymbol for AIX. We will 566 /// create the csect and use the qual-name symbol instead of creating just the 567 /// external symbol. 568 static MCSymbol *createMCSymbolForTlsGetAddr(MCContext &Ctx) { 569 return Ctx 570 .getXCOFFSection(".__tls_get_addr", SectionKind::getText(), 571 XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER)) 572 ->getQualNameSymbol(); 573 } 574 575 /// EmitTlsCall -- Given a GETtls[ld]ADDR[32] instruction, print a 576 /// call to __tls_get_addr to the current output stream. 577 void PPCAsmPrinter::EmitTlsCall(const MachineInstr *MI, 578 MCSymbolRefExpr::VariantKind VK) { 579 MCSymbolRefExpr::VariantKind Kind = MCSymbolRefExpr::VK_None; 580 unsigned Opcode = PPC::BL8_NOP_TLS; 581 582 assert(MI->getNumOperands() >= 3 && "Expecting at least 3 operands from MI"); 583 if (MI->getOperand(2).getTargetFlags() == PPCII::MO_GOT_TLSGD_PCREL_FLAG || 584 MI->getOperand(2).getTargetFlags() == PPCII::MO_GOT_TLSLD_PCREL_FLAG) { 585 Kind = MCSymbolRefExpr::VK_PPC_NOTOC; 586 Opcode = PPC::BL8_NOTOC_TLS; 587 } 588 const Module *M = MF->getFunction().getParent(); 589 590 assert(MI->getOperand(0).isReg() && 591 ((Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::X3) || 592 (!Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::R3)) && 593 "GETtls[ld]ADDR[32] must define GPR3"); 594 assert(MI->getOperand(1).isReg() && 595 ((Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::X3) || 596 (!Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::R3)) && 597 "GETtls[ld]ADDR[32] must read GPR3"); 598 599 if (Subtarget->isAIXABI()) { 600 // On AIX, the variable offset should already be in R4 and the region handle 601 // should already be in R3. 602 // For TLSGD, which currently is the only supported access model, we only 603 // need to generate an absolute branch to .__tls_get_addr. 604 Register VarOffsetReg = Subtarget->isPPC64() ? PPC::X4 : PPC::R4; 605 (void)VarOffsetReg; 606 assert(MI->getOperand(2).isReg() && 607 MI->getOperand(2).getReg() == VarOffsetReg && 608 "GETtls[ld]ADDR[32] must read GPR4"); 609 MCSymbol *TlsGetAddr = createMCSymbolForTlsGetAddr(OutContext); 610 const MCExpr *TlsRef = MCSymbolRefExpr::create( 611 TlsGetAddr, MCSymbolRefExpr::VK_None, OutContext); 612 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BLA).addExpr(TlsRef)); 613 return; 614 } 615 616 MCSymbol *TlsGetAddr = OutContext.getOrCreateSymbol("__tls_get_addr"); 617 618 if (Subtarget->is32BitELFABI() && isPositionIndependent()) 619 Kind = MCSymbolRefExpr::VK_PLT; 620 621 const MCExpr *TlsRef = 622 MCSymbolRefExpr::create(TlsGetAddr, Kind, OutContext); 623 624 // Add 32768 offset to the symbol so we follow up the latest GOT/PLT ABI. 625 if (Kind == MCSymbolRefExpr::VK_PLT && Subtarget->isSecurePlt() && 626 M->getPICLevel() == PICLevel::BigPIC) 627 TlsRef = MCBinaryExpr::createAdd( 628 TlsRef, MCConstantExpr::create(32768, OutContext), OutContext); 629 const MachineOperand &MO = MI->getOperand(2); 630 const GlobalValue *GValue = MO.getGlobal(); 631 MCSymbol *MOSymbol = getSymbol(GValue); 632 const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, VK, OutContext); 633 EmitToStreamer(*OutStreamer, 634 MCInstBuilder(Subtarget->isPPC64() ? Opcode 635 : (unsigned)PPC::BL_TLS) 636 .addExpr(TlsRef) 637 .addExpr(SymVar)); 638 } 639 640 /// Map a machine operand for a TOC pseudo-machine instruction to its 641 /// corresponding MCSymbol. 642 static MCSymbol *getMCSymbolForTOCPseudoMO(const MachineOperand &MO, 643 AsmPrinter &AP) { 644 switch (MO.getType()) { 645 case MachineOperand::MO_GlobalAddress: 646 return AP.getSymbol(MO.getGlobal()); 647 case MachineOperand::MO_ConstantPoolIndex: 648 return AP.GetCPISymbol(MO.getIndex()); 649 case MachineOperand::MO_JumpTableIndex: 650 return AP.GetJTISymbol(MO.getIndex()); 651 case MachineOperand::MO_BlockAddress: 652 return AP.GetBlockAddressSymbol(MO.getBlockAddress()); 653 default: 654 llvm_unreachable("Unexpected operand type to get symbol."); 655 } 656 } 657 658 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to 659 /// the current output stream. 660 /// 661 void PPCAsmPrinter::emitInstruction(const MachineInstr *MI) { 662 PPC_MC::verifyInstructionPredicates(MI->getOpcode(), 663 getSubtargetInfo().getFeatureBits()); 664 665 MCInst TmpInst; 666 const bool IsPPC64 = Subtarget->isPPC64(); 667 const bool IsAIX = Subtarget->isAIXABI(); 668 const Module *M = MF->getFunction().getParent(); 669 PICLevel::Level PL = M->getPICLevel(); 670 671 #ifndef NDEBUG 672 // Validate that SPE and FPU are mutually exclusive in codegen 673 if (!MI->isInlineAsm()) { 674 for (const MachineOperand &MO: MI->operands()) { 675 if (MO.isReg()) { 676 Register Reg = MO.getReg(); 677 if (Subtarget->hasSPE()) { 678 if (PPC::F4RCRegClass.contains(Reg) || 679 PPC::F8RCRegClass.contains(Reg) || 680 PPC::VFRCRegClass.contains(Reg) || 681 PPC::VRRCRegClass.contains(Reg) || 682 PPC::VSFRCRegClass.contains(Reg) || 683 PPC::VSSRCRegClass.contains(Reg) 684 ) 685 llvm_unreachable("SPE targets cannot have FPRegs!"); 686 } else { 687 if (PPC::SPERCRegClass.contains(Reg)) 688 llvm_unreachable("SPE register found in FPU-targeted code!"); 689 } 690 } 691 } 692 } 693 #endif 694 695 auto getTOCRelocAdjustedExprForXCOFF = [this](const MCExpr *Expr, 696 ptrdiff_t OriginalOffset) { 697 // Apply an offset to the TOC-based expression such that the adjusted 698 // notional offset from the TOC base (to be encoded into the instruction's D 699 // or DS field) is the signed 16-bit truncation of the original notional 700 // offset from the TOC base. 701 // This is consistent with the treatment used both by XL C/C++ and 702 // by AIX ld -r. 703 ptrdiff_t Adjustment = 704 OriginalOffset - llvm::SignExtend32<16>(OriginalOffset); 705 return MCBinaryExpr::createAdd( 706 Expr, MCConstantExpr::create(-Adjustment, OutContext), OutContext); 707 }; 708 709 auto getTOCEntryLoadingExprForXCOFF = 710 [IsPPC64, getTOCRelocAdjustedExprForXCOFF, 711 this](const MCSymbol *MOSymbol, const MCExpr *Expr, 712 MCSymbolRefExpr::VariantKind VK = 713 MCSymbolRefExpr::VariantKind::VK_None) -> const MCExpr * { 714 const unsigned EntryByteSize = IsPPC64 ? 8 : 4; 715 const auto TOCEntryIter = TOC.find({MOSymbol, VK}); 716 assert(TOCEntryIter != TOC.end() && 717 "Could not find the TOC entry for this symbol."); 718 const ptrdiff_t EntryDistanceFromTOCBase = 719 (TOCEntryIter - TOC.begin()) * EntryByteSize; 720 constexpr int16_t PositiveTOCRange = INT16_MAX; 721 722 if (EntryDistanceFromTOCBase > PositiveTOCRange) 723 return getTOCRelocAdjustedExprForXCOFF(Expr, EntryDistanceFromTOCBase); 724 725 return Expr; 726 }; 727 auto GetVKForMO = [&](const MachineOperand &MO) { 728 // For GD TLS access on AIX, we have two TOC entries for the symbol (one for 729 // the variable offset and the other for the region handle). They are 730 // differentiated by MO_TLSGD_FLAG and MO_TLSGDM_FLAG. 731 if (MO.getTargetFlags() & PPCII::MO_TLSGDM_FLAG) 732 return MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSGDM; 733 if (MO.getTargetFlags() & PPCII::MO_TLSGD_FLAG) 734 return MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSGD; 735 return MCSymbolRefExpr::VariantKind::VK_None; 736 }; 737 738 // Lower multi-instruction pseudo operations. 739 switch (MI->getOpcode()) { 740 default: break; 741 case TargetOpcode::DBG_VALUE: 742 llvm_unreachable("Should be handled target independently"); 743 case TargetOpcode::STACKMAP: 744 return LowerSTACKMAP(SM, *MI); 745 case TargetOpcode::PATCHPOINT: 746 return LowerPATCHPOINT(SM, *MI); 747 748 case PPC::MoveGOTtoLR: { 749 // Transform %lr = MoveGOTtoLR 750 // Into this: bl _GLOBAL_OFFSET_TABLE_@local-4 751 // _GLOBAL_OFFSET_TABLE_@local-4 (instruction preceding 752 // _GLOBAL_OFFSET_TABLE_) has exactly one instruction: 753 // blrl 754 // This will return the pointer to _GLOBAL_OFFSET_TABLE_@local 755 MCSymbol *GOTSymbol = 756 OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_")); 757 const MCExpr *OffsExpr = 758 MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol, 759 MCSymbolRefExpr::VK_PPC_LOCAL, 760 OutContext), 761 MCConstantExpr::create(4, OutContext), 762 OutContext); 763 764 // Emit the 'bl'. 765 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL).addExpr(OffsExpr)); 766 return; 767 } 768 case PPC::MovePCtoLR: 769 case PPC::MovePCtoLR8: { 770 // Transform %lr = MovePCtoLR 771 // Into this, where the label is the PIC base: 772 // bl L1$pb 773 // L1$pb: 774 MCSymbol *PICBase = MF->getPICBaseSymbol(); 775 776 // Emit the 'bl'. 777 EmitToStreamer(*OutStreamer, 778 MCInstBuilder(PPC::BL) 779 // FIXME: We would like an efficient form for this, so we 780 // don't have to do a lot of extra uniquing. 781 .addExpr(MCSymbolRefExpr::create(PICBase, OutContext))); 782 783 // Emit the label. 784 OutStreamer->emitLabel(PICBase); 785 return; 786 } 787 case PPC::UpdateGBR: { 788 // Transform %rd = UpdateGBR(%rt, %ri) 789 // Into: lwz %rt, .L0$poff - .L0$pb(%ri) 790 // add %rd, %rt, %ri 791 // or into (if secure plt mode is on): 792 // addis r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@ha 793 // addi r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@l 794 // Get the offset from the GOT Base Register to the GOT 795 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 796 if (Subtarget->isSecurePlt() && isPositionIndependent() ) { 797 unsigned PICR = TmpInst.getOperand(0).getReg(); 798 MCSymbol *BaseSymbol = OutContext.getOrCreateSymbol( 799 M->getPICLevel() == PICLevel::SmallPIC ? "_GLOBAL_OFFSET_TABLE_" 800 : ".LTOC"); 801 const MCExpr *PB = 802 MCSymbolRefExpr::create(MF->getPICBaseSymbol(), OutContext); 803 804 const MCExpr *DeltaExpr = MCBinaryExpr::createSub( 805 MCSymbolRefExpr::create(BaseSymbol, OutContext), PB, OutContext); 806 807 const MCExpr *DeltaHi = PPCMCExpr::createHa(DeltaExpr, OutContext); 808 EmitToStreamer( 809 *OutStreamer, 810 MCInstBuilder(PPC::ADDIS).addReg(PICR).addReg(PICR).addExpr(DeltaHi)); 811 812 const MCExpr *DeltaLo = PPCMCExpr::createLo(DeltaExpr, OutContext); 813 EmitToStreamer( 814 *OutStreamer, 815 MCInstBuilder(PPC::ADDI).addReg(PICR).addReg(PICR).addExpr(DeltaLo)); 816 return; 817 } else { 818 MCSymbol *PICOffset = 819 MF->getInfo<PPCFunctionInfo>()->getPICOffsetSymbol(*MF); 820 TmpInst.setOpcode(PPC::LWZ); 821 const MCExpr *Exp = 822 MCSymbolRefExpr::create(PICOffset, MCSymbolRefExpr::VK_None, OutContext); 823 const MCExpr *PB = 824 MCSymbolRefExpr::create(MF->getPICBaseSymbol(), 825 MCSymbolRefExpr::VK_None, 826 OutContext); 827 const MCOperand TR = TmpInst.getOperand(1); 828 const MCOperand PICR = TmpInst.getOperand(0); 829 830 // Step 1: lwz %rt, .L$poff - .L$pb(%ri) 831 TmpInst.getOperand(1) = 832 MCOperand::createExpr(MCBinaryExpr::createSub(Exp, PB, OutContext)); 833 TmpInst.getOperand(0) = TR; 834 TmpInst.getOperand(2) = PICR; 835 EmitToStreamer(*OutStreamer, TmpInst); 836 837 TmpInst.setOpcode(PPC::ADD4); 838 TmpInst.getOperand(0) = PICR; 839 TmpInst.getOperand(1) = TR; 840 TmpInst.getOperand(2) = PICR; 841 EmitToStreamer(*OutStreamer, TmpInst); 842 return; 843 } 844 } 845 case PPC::LWZtoc: { 846 // Transform %rN = LWZtoc @op1, %r2 847 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 848 849 // Change the opcode to LWZ. 850 TmpInst.setOpcode(PPC::LWZ); 851 852 const MachineOperand &MO = MI->getOperand(1); 853 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) && 854 "Invalid operand for LWZtoc."); 855 856 // Map the operand to its corresponding MCSymbol. 857 const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this); 858 859 // Create a reference to the GOT entry for the symbol. The GOT entry will be 860 // synthesized later. 861 if (PL == PICLevel::SmallPIC && !IsAIX) { 862 const MCExpr *Exp = 863 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_GOT, 864 OutContext); 865 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 866 EmitToStreamer(*OutStreamer, TmpInst); 867 return; 868 } 869 870 MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO); 871 872 // Otherwise, use the TOC. 'TOCEntry' is a label used to reference the 873 // storage allocated in the TOC which contains the address of 874 // 'MOSymbol'. Said TOC entry will be synthesized later. 875 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol, VK); 876 const MCExpr *Exp = 877 MCSymbolRefExpr::create(TOCEntry, MCSymbolRefExpr::VK_None, OutContext); 878 879 // AIX uses the label directly as the lwz displacement operand for 880 // references into the toc section. The displacement value will be generated 881 // relative to the toc-base. 882 if (IsAIX) { 883 assert( 884 TM.getCodeModel() == CodeModel::Small && 885 "This pseudo should only be selected for 32-bit small code model."); 886 Exp = getTOCEntryLoadingExprForXCOFF(MOSymbol, Exp, VK); 887 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 888 889 // Print MO for better readability 890 if (isVerbose()) 891 OutStreamer->getCommentOS() << MO << '\n'; 892 EmitToStreamer(*OutStreamer, TmpInst); 893 return; 894 } 895 896 // Create an explicit subtract expression between the local symbol and 897 // '.LTOC' to manifest the toc-relative offset. 898 const MCExpr *PB = MCSymbolRefExpr::create( 899 OutContext.getOrCreateSymbol(Twine(".LTOC")), OutContext); 900 Exp = MCBinaryExpr::createSub(Exp, PB, OutContext); 901 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 902 EmitToStreamer(*OutStreamer, TmpInst); 903 return; 904 } 905 case PPC::ADDItoc: 906 case PPC::ADDItoc8: { 907 assert(IsAIX && TM.getCodeModel() == CodeModel::Small && 908 "PseudoOp only valid for small code model AIX"); 909 910 // Transform %rN = ADDItoc/8 @op1, %r2. 911 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 912 913 // Change the opcode to load address. 914 TmpInst.setOpcode((!IsPPC64) ? (PPC::LA) : (PPC::LA8)); 915 916 const MachineOperand &MO = MI->getOperand(1); 917 assert(MO.isGlobal() && "Invalid operand for ADDItoc[8]."); 918 919 // Map the operand to its corresponding MCSymbol. 920 const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this); 921 922 const MCExpr *Exp = 923 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_None, OutContext); 924 925 TmpInst.getOperand(1) = TmpInst.getOperand(2); 926 TmpInst.getOperand(2) = MCOperand::createExpr(Exp); 927 EmitToStreamer(*OutStreamer, TmpInst); 928 return; 929 } 930 case PPC::LDtocJTI: 931 case PPC::LDtocCPT: 932 case PPC::LDtocBA: 933 case PPC::LDtoc: { 934 // Transform %x3 = LDtoc @min1, %x2 935 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 936 937 // Change the opcode to LD. 938 TmpInst.setOpcode(PPC::LD); 939 940 const MachineOperand &MO = MI->getOperand(1); 941 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) && 942 "Invalid operand!"); 943 944 // Map the operand to its corresponding MCSymbol. 945 const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this); 946 947 MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO); 948 949 // Map the machine operand to its corresponding MCSymbol, then map the 950 // global address operand to be a reference to the TOC entry we will 951 // synthesize later. 952 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol, VK); 953 954 MCSymbolRefExpr::VariantKind VKExpr = 955 IsAIX ? MCSymbolRefExpr::VK_None : MCSymbolRefExpr::VK_PPC_TOC; 956 const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry, VKExpr, OutContext); 957 TmpInst.getOperand(1) = MCOperand::createExpr( 958 IsAIX ? getTOCEntryLoadingExprForXCOFF(MOSymbol, Exp, VK) : Exp); 959 960 // Print MO for better readability 961 if (isVerbose() && IsAIX) 962 OutStreamer->getCommentOS() << MO << '\n'; 963 EmitToStreamer(*OutStreamer, TmpInst); 964 return; 965 } 966 case PPC::ADDIStocHA: { 967 assert((IsAIX && !IsPPC64 && TM.getCodeModel() == CodeModel::Large) && 968 "This pseudo should only be selected for 32-bit large code model on" 969 " AIX."); 970 971 // Transform %rd = ADDIStocHA %rA, @sym(%r2) 972 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 973 974 // Change the opcode to ADDIS. 975 TmpInst.setOpcode(PPC::ADDIS); 976 977 const MachineOperand &MO = MI->getOperand(2); 978 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) && 979 "Invalid operand for ADDIStocHA."); 980 981 // Map the machine operand to its corresponding MCSymbol. 982 MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this); 983 984 MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO); 985 986 // Always use TOC on AIX. Map the global address operand to be a reference 987 // to the TOC entry we will synthesize later. 'TOCEntry' is a label used to 988 // reference the storage allocated in the TOC which contains the address of 989 // 'MOSymbol'. 990 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol, VK); 991 const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry, 992 MCSymbolRefExpr::VK_PPC_U, 993 OutContext); 994 TmpInst.getOperand(2) = MCOperand::createExpr(Exp); 995 EmitToStreamer(*OutStreamer, TmpInst); 996 return; 997 } 998 case PPC::LWZtocL: { 999 assert(IsAIX && !IsPPC64 && TM.getCodeModel() == CodeModel::Large && 1000 "This pseudo should only be selected for 32-bit large code model on" 1001 " AIX."); 1002 1003 // Transform %rd = LWZtocL @sym, %rs. 1004 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 1005 1006 // Change the opcode to lwz. 1007 TmpInst.setOpcode(PPC::LWZ); 1008 1009 const MachineOperand &MO = MI->getOperand(1); 1010 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) && 1011 "Invalid operand for LWZtocL."); 1012 1013 // Map the machine operand to its corresponding MCSymbol. 1014 MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this); 1015 1016 MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO); 1017 1018 // Always use TOC on AIX. Map the global address operand to be a reference 1019 // to the TOC entry we will synthesize later. 'TOCEntry' is a label used to 1020 // reference the storage allocated in the TOC which contains the address of 1021 // 'MOSymbol'. 1022 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol, VK); 1023 const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry, 1024 MCSymbolRefExpr::VK_PPC_L, 1025 OutContext); 1026 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 1027 EmitToStreamer(*OutStreamer, TmpInst); 1028 return; 1029 } 1030 case PPC::ADDIStocHA8: { 1031 // Transform %xd = ADDIStocHA8 %x2, @sym 1032 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 1033 1034 // Change the opcode to ADDIS8. If the global address is the address of 1035 // an external symbol, is a jump table address, is a block address, or is a 1036 // constant pool index with large code model enabled, then generate a TOC 1037 // entry and reference that. Otherwise, reference the symbol directly. 1038 TmpInst.setOpcode(PPC::ADDIS8); 1039 1040 const MachineOperand &MO = MI->getOperand(2); 1041 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) && 1042 "Invalid operand for ADDIStocHA8!"); 1043 1044 const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this); 1045 1046 MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO); 1047 1048 const bool GlobalToc = 1049 MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal()); 1050 if (GlobalToc || MO.isJTI() || MO.isBlockAddress() || 1051 (MO.isCPI() && TM.getCodeModel() == CodeModel::Large)) 1052 MOSymbol = lookUpOrCreateTOCEntry(MOSymbol, VK); 1053 1054 VK = IsAIX ? MCSymbolRefExpr::VK_PPC_U : MCSymbolRefExpr::VK_PPC_TOC_HA; 1055 1056 const MCExpr *Exp = 1057 MCSymbolRefExpr::create(MOSymbol, VK, OutContext); 1058 1059 if (!MO.isJTI() && MO.getOffset()) 1060 Exp = MCBinaryExpr::createAdd(Exp, 1061 MCConstantExpr::create(MO.getOffset(), 1062 OutContext), 1063 OutContext); 1064 1065 TmpInst.getOperand(2) = MCOperand::createExpr(Exp); 1066 EmitToStreamer(*OutStreamer, TmpInst); 1067 return; 1068 } 1069 case PPC::LDtocL: { 1070 // Transform %xd = LDtocL @sym, %xs 1071 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 1072 1073 // Change the opcode to LD. If the global address is the address of 1074 // an external symbol, is a jump table address, is a block address, or is 1075 // a constant pool index with large code model enabled, then generate a 1076 // TOC entry and reference that. Otherwise, reference the symbol directly. 1077 TmpInst.setOpcode(PPC::LD); 1078 1079 const MachineOperand &MO = MI->getOperand(1); 1080 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || 1081 MO.isBlockAddress()) && 1082 "Invalid operand for LDtocL!"); 1083 1084 LLVM_DEBUG(assert( 1085 (!MO.isGlobal() || Subtarget->isGVIndirectSymbol(MO.getGlobal())) && 1086 "LDtocL used on symbol that could be accessed directly is " 1087 "invalid. Must match ADDIStocHA8.")); 1088 1089 const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this); 1090 1091 MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO); 1092 1093 if (!MO.isCPI() || TM.getCodeModel() == CodeModel::Large) 1094 MOSymbol = lookUpOrCreateTOCEntry(MOSymbol, VK); 1095 1096 VK = IsAIX ? MCSymbolRefExpr::VK_PPC_L : MCSymbolRefExpr::VK_PPC_TOC_LO; 1097 const MCExpr *Exp = 1098 MCSymbolRefExpr::create(MOSymbol, VK, OutContext); 1099 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 1100 EmitToStreamer(*OutStreamer, TmpInst); 1101 return; 1102 } 1103 case PPC::ADDItocL: { 1104 // Transform %xd = ADDItocL %xs, @sym 1105 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 1106 1107 // Change the opcode to ADDI8. If the global address is external, then 1108 // generate a TOC entry and reference that. Otherwise, reference the 1109 // symbol directly. 1110 TmpInst.setOpcode(PPC::ADDI8); 1111 1112 const MachineOperand &MO = MI->getOperand(2); 1113 assert((MO.isGlobal() || MO.isCPI()) && "Invalid operand for ADDItocL."); 1114 1115 LLVM_DEBUG(assert( 1116 !(MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal())) && 1117 "Interposable definitions must use indirect access.")); 1118 1119 const MCExpr *Exp = 1120 MCSymbolRefExpr::create(getMCSymbolForTOCPseudoMO(MO, *this), 1121 MCSymbolRefExpr::VK_PPC_TOC_LO, OutContext); 1122 TmpInst.getOperand(2) = MCOperand::createExpr(Exp); 1123 EmitToStreamer(*OutStreamer, TmpInst); 1124 return; 1125 } 1126 case PPC::ADDISgotTprelHA: { 1127 // Transform: %xd = ADDISgotTprelHA %x2, @sym 1128 // Into: %xd = ADDIS8 %x2, sym@got@tlsgd@ha 1129 assert(IsPPC64 && "Not supported for 32-bit PowerPC"); 1130 const MachineOperand &MO = MI->getOperand(2); 1131 const GlobalValue *GValue = MO.getGlobal(); 1132 MCSymbol *MOSymbol = getSymbol(GValue); 1133 const MCExpr *SymGotTprel = 1134 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA, 1135 OutContext); 1136 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8) 1137 .addReg(MI->getOperand(0).getReg()) 1138 .addReg(MI->getOperand(1).getReg()) 1139 .addExpr(SymGotTprel)); 1140 return; 1141 } 1142 case PPC::LDgotTprelL: 1143 case PPC::LDgotTprelL32: { 1144 // Transform %xd = LDgotTprelL @sym, %xs 1145 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 1146 1147 // Change the opcode to LD. 1148 TmpInst.setOpcode(IsPPC64 ? PPC::LD : PPC::LWZ); 1149 const MachineOperand &MO = MI->getOperand(1); 1150 const GlobalValue *GValue = MO.getGlobal(); 1151 MCSymbol *MOSymbol = getSymbol(GValue); 1152 const MCExpr *Exp = MCSymbolRefExpr::create( 1153 MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO 1154 : MCSymbolRefExpr::VK_PPC_GOT_TPREL, 1155 OutContext); 1156 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 1157 EmitToStreamer(*OutStreamer, TmpInst); 1158 return; 1159 } 1160 1161 case PPC::PPC32PICGOT: { 1162 MCSymbol *GOTSymbol = OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_")); 1163 MCSymbol *GOTRef = OutContext.createTempSymbol(); 1164 MCSymbol *NextInstr = OutContext.createTempSymbol(); 1165 1166 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL) 1167 // FIXME: We would like an efficient form for this, so we don't have to do 1168 // a lot of extra uniquing. 1169 .addExpr(MCSymbolRefExpr::create(NextInstr, OutContext))); 1170 const MCExpr *OffsExpr = 1171 MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol, OutContext), 1172 MCSymbolRefExpr::create(GOTRef, OutContext), 1173 OutContext); 1174 OutStreamer->emitLabel(GOTRef); 1175 OutStreamer->emitValue(OffsExpr, 4); 1176 OutStreamer->emitLabel(NextInstr); 1177 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR) 1178 .addReg(MI->getOperand(0).getReg())); 1179 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LWZ) 1180 .addReg(MI->getOperand(1).getReg()) 1181 .addImm(0) 1182 .addReg(MI->getOperand(0).getReg())); 1183 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD4) 1184 .addReg(MI->getOperand(0).getReg()) 1185 .addReg(MI->getOperand(1).getReg()) 1186 .addReg(MI->getOperand(0).getReg())); 1187 return; 1188 } 1189 case PPC::PPC32GOT: { 1190 MCSymbol *GOTSymbol = 1191 OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_")); 1192 const MCExpr *SymGotTlsL = MCSymbolRefExpr::create( 1193 GOTSymbol, MCSymbolRefExpr::VK_PPC_LO, OutContext); 1194 const MCExpr *SymGotTlsHA = MCSymbolRefExpr::create( 1195 GOTSymbol, MCSymbolRefExpr::VK_PPC_HA, OutContext); 1196 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI) 1197 .addReg(MI->getOperand(0).getReg()) 1198 .addExpr(SymGotTlsL)); 1199 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS) 1200 .addReg(MI->getOperand(0).getReg()) 1201 .addReg(MI->getOperand(0).getReg()) 1202 .addExpr(SymGotTlsHA)); 1203 return; 1204 } 1205 case PPC::ADDIStlsgdHA: { 1206 // Transform: %xd = ADDIStlsgdHA %x2, @sym 1207 // Into: %xd = ADDIS8 %x2, sym@got@tlsgd@ha 1208 assert(IsPPC64 && "Not supported for 32-bit PowerPC"); 1209 const MachineOperand &MO = MI->getOperand(2); 1210 const GlobalValue *GValue = MO.getGlobal(); 1211 MCSymbol *MOSymbol = getSymbol(GValue); 1212 const MCExpr *SymGotTlsGD = 1213 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA, 1214 OutContext); 1215 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8) 1216 .addReg(MI->getOperand(0).getReg()) 1217 .addReg(MI->getOperand(1).getReg()) 1218 .addExpr(SymGotTlsGD)); 1219 return; 1220 } 1221 case PPC::ADDItlsgdL: 1222 // Transform: %xd = ADDItlsgdL %xs, @sym 1223 // Into: %xd = ADDI8 %xs, sym@got@tlsgd@l 1224 case PPC::ADDItlsgdL32: { 1225 // Transform: %rd = ADDItlsgdL32 %rs, @sym 1226 // Into: %rd = ADDI %rs, sym@got@tlsgd 1227 const MachineOperand &MO = MI->getOperand(2); 1228 const GlobalValue *GValue = MO.getGlobal(); 1229 MCSymbol *MOSymbol = getSymbol(GValue); 1230 const MCExpr *SymGotTlsGD = MCSymbolRefExpr::create( 1231 MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO 1232 : MCSymbolRefExpr::VK_PPC_GOT_TLSGD, 1233 OutContext); 1234 EmitToStreamer(*OutStreamer, 1235 MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI) 1236 .addReg(MI->getOperand(0).getReg()) 1237 .addReg(MI->getOperand(1).getReg()) 1238 .addExpr(SymGotTlsGD)); 1239 return; 1240 } 1241 case PPC::GETtlsADDR: 1242 // Transform: %x3 = GETtlsADDR %x3, @sym 1243 // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsgd) 1244 case PPC::GETtlsADDRPCREL: 1245 case PPC::GETtlsADDR32AIX: 1246 case PPC::GETtlsADDR64AIX: 1247 // Transform: %r3 = GETtlsADDRNNAIX %r3, %r4 (for NN == 32/64). 1248 // Into: BLA .__tls_get_addr() 1249 // Unlike on Linux, there is no symbol or relocation needed for this call. 1250 case PPC::GETtlsADDR32: { 1251 // Transform: %r3 = GETtlsADDR32 %r3, @sym 1252 // Into: BL_TLS __tls_get_addr(sym at tlsgd)@PLT 1253 EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSGD); 1254 return; 1255 } 1256 case PPC::ADDIStlsldHA: { 1257 // Transform: %xd = ADDIStlsldHA %x2, @sym 1258 // Into: %xd = ADDIS8 %x2, sym@got@tlsld@ha 1259 assert(IsPPC64 && "Not supported for 32-bit PowerPC"); 1260 const MachineOperand &MO = MI->getOperand(2); 1261 const GlobalValue *GValue = MO.getGlobal(); 1262 MCSymbol *MOSymbol = getSymbol(GValue); 1263 const MCExpr *SymGotTlsLD = 1264 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA, 1265 OutContext); 1266 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8) 1267 .addReg(MI->getOperand(0).getReg()) 1268 .addReg(MI->getOperand(1).getReg()) 1269 .addExpr(SymGotTlsLD)); 1270 return; 1271 } 1272 case PPC::ADDItlsldL: 1273 // Transform: %xd = ADDItlsldL %xs, @sym 1274 // Into: %xd = ADDI8 %xs, sym@got@tlsld@l 1275 case PPC::ADDItlsldL32: { 1276 // Transform: %rd = ADDItlsldL32 %rs, @sym 1277 // Into: %rd = ADDI %rs, sym@got@tlsld 1278 const MachineOperand &MO = MI->getOperand(2); 1279 const GlobalValue *GValue = MO.getGlobal(); 1280 MCSymbol *MOSymbol = getSymbol(GValue); 1281 const MCExpr *SymGotTlsLD = MCSymbolRefExpr::create( 1282 MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO 1283 : MCSymbolRefExpr::VK_PPC_GOT_TLSLD, 1284 OutContext); 1285 EmitToStreamer(*OutStreamer, 1286 MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI) 1287 .addReg(MI->getOperand(0).getReg()) 1288 .addReg(MI->getOperand(1).getReg()) 1289 .addExpr(SymGotTlsLD)); 1290 return; 1291 } 1292 case PPC::GETtlsldADDR: 1293 // Transform: %x3 = GETtlsldADDR %x3, @sym 1294 // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsld) 1295 case PPC::GETtlsldADDRPCREL: 1296 case PPC::GETtlsldADDR32: { 1297 // Transform: %r3 = GETtlsldADDR32 %r3, @sym 1298 // Into: BL_TLS __tls_get_addr(sym at tlsld)@PLT 1299 EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSLD); 1300 return; 1301 } 1302 case PPC::ADDISdtprelHA: 1303 // Transform: %xd = ADDISdtprelHA %xs, @sym 1304 // Into: %xd = ADDIS8 %xs, sym@dtprel@ha 1305 case PPC::ADDISdtprelHA32: { 1306 // Transform: %rd = ADDISdtprelHA32 %rs, @sym 1307 // Into: %rd = ADDIS %rs, sym@dtprel@ha 1308 const MachineOperand &MO = MI->getOperand(2); 1309 const GlobalValue *GValue = MO.getGlobal(); 1310 MCSymbol *MOSymbol = getSymbol(GValue); 1311 const MCExpr *SymDtprel = 1312 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_HA, 1313 OutContext); 1314 EmitToStreamer( 1315 *OutStreamer, 1316 MCInstBuilder(IsPPC64 ? PPC::ADDIS8 : PPC::ADDIS) 1317 .addReg(MI->getOperand(0).getReg()) 1318 .addReg(MI->getOperand(1).getReg()) 1319 .addExpr(SymDtprel)); 1320 return; 1321 } 1322 case PPC::PADDIdtprel: { 1323 // Transform: %rd = PADDIdtprel %rs, @sym 1324 // Into: %rd = PADDI8 %rs, sym@dtprel 1325 const MachineOperand &MO = MI->getOperand(2); 1326 const GlobalValue *GValue = MO.getGlobal(); 1327 MCSymbol *MOSymbol = getSymbol(GValue); 1328 const MCExpr *SymDtprel = MCSymbolRefExpr::create( 1329 MOSymbol, MCSymbolRefExpr::VK_DTPREL, OutContext); 1330 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::PADDI8) 1331 .addReg(MI->getOperand(0).getReg()) 1332 .addReg(MI->getOperand(1).getReg()) 1333 .addExpr(SymDtprel)); 1334 return; 1335 } 1336 1337 case PPC::ADDIdtprelL: 1338 // Transform: %xd = ADDIdtprelL %xs, @sym 1339 // Into: %xd = ADDI8 %xs, sym@dtprel@l 1340 case PPC::ADDIdtprelL32: { 1341 // Transform: %rd = ADDIdtprelL32 %rs, @sym 1342 // Into: %rd = ADDI %rs, sym@dtprel@l 1343 const MachineOperand &MO = MI->getOperand(2); 1344 const GlobalValue *GValue = MO.getGlobal(); 1345 MCSymbol *MOSymbol = getSymbol(GValue); 1346 const MCExpr *SymDtprel = 1347 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_LO, 1348 OutContext); 1349 EmitToStreamer(*OutStreamer, 1350 MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI) 1351 .addReg(MI->getOperand(0).getReg()) 1352 .addReg(MI->getOperand(1).getReg()) 1353 .addExpr(SymDtprel)); 1354 return; 1355 } 1356 case PPC::MFOCRF: 1357 case PPC::MFOCRF8: 1358 if (!Subtarget->hasMFOCRF()) { 1359 // Transform: %r3 = MFOCRF %cr7 1360 // Into: %r3 = MFCR ;; cr7 1361 unsigned NewOpcode = 1362 MI->getOpcode() == PPC::MFOCRF ? PPC::MFCR : PPC::MFCR8; 1363 OutStreamer->AddComment(PPCInstPrinter:: 1364 getRegisterName(MI->getOperand(1).getReg())); 1365 EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode) 1366 .addReg(MI->getOperand(0).getReg())); 1367 return; 1368 } 1369 break; 1370 case PPC::MTOCRF: 1371 case PPC::MTOCRF8: 1372 if (!Subtarget->hasMFOCRF()) { 1373 // Transform: %cr7 = MTOCRF %r3 1374 // Into: MTCRF mask, %r3 ;; cr7 1375 unsigned NewOpcode = 1376 MI->getOpcode() == PPC::MTOCRF ? PPC::MTCRF : PPC::MTCRF8; 1377 unsigned Mask = 0x80 >> OutContext.getRegisterInfo() 1378 ->getEncodingValue(MI->getOperand(0).getReg()); 1379 OutStreamer->AddComment(PPCInstPrinter:: 1380 getRegisterName(MI->getOperand(0).getReg())); 1381 EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode) 1382 .addImm(Mask) 1383 .addReg(MI->getOperand(1).getReg())); 1384 return; 1385 } 1386 break; 1387 case PPC::LD: 1388 case PPC::STD: 1389 case PPC::LWA_32: 1390 case PPC::LWA: { 1391 // Verify alignment is legal, so we don't create relocations 1392 // that can't be supported. 1393 unsigned OpNum = (MI->getOpcode() == PPC::STD) ? 2 : 1; 1394 const MachineOperand &MO = MI->getOperand(OpNum); 1395 if (MO.isGlobal()) { 1396 const DataLayout &DL = MO.getGlobal()->getParent()->getDataLayout(); 1397 if (MO.getGlobal()->getPointerAlignment(DL) < 4) 1398 llvm_unreachable("Global must be word-aligned for LD, STD, LWA!"); 1399 } 1400 // Now process the instruction normally. 1401 break; 1402 } 1403 case PPC::PseudoEIEIO: { 1404 EmitToStreamer( 1405 *OutStreamer, 1406 MCInstBuilder(PPC::ORI).addReg(PPC::X2).addReg(PPC::X2).addImm(0)); 1407 EmitToStreamer( 1408 *OutStreamer, 1409 MCInstBuilder(PPC::ORI).addReg(PPC::X2).addReg(PPC::X2).addImm(0)); 1410 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::EnforceIEIO)); 1411 return; 1412 } 1413 } 1414 1415 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 1416 EmitToStreamer(*OutStreamer, TmpInst); 1417 } 1418 1419 void PPCLinuxAsmPrinter::emitGNUAttributes(Module &M) { 1420 // Emit float ABI into GNU attribute 1421 Metadata *MD = M.getModuleFlag("float-abi"); 1422 MDString *FloatABI = dyn_cast_or_null<MDString>(MD); 1423 if (!FloatABI) 1424 return; 1425 StringRef flt = FloatABI->getString(); 1426 // TODO: Support emitting soft-fp and hard double/single attributes. 1427 if (flt == "doubledouble") 1428 OutStreamer->emitGNUAttribute(Tag_GNU_Power_ABI_FP, 1429 Val_GNU_Power_ABI_HardFloat_DP | 1430 Val_GNU_Power_ABI_LDBL_IBM128); 1431 else if (flt == "ieeequad") 1432 OutStreamer->emitGNUAttribute(Tag_GNU_Power_ABI_FP, 1433 Val_GNU_Power_ABI_HardFloat_DP | 1434 Val_GNU_Power_ABI_LDBL_IEEE128); 1435 else if (flt == "ieeedouble") 1436 OutStreamer->emitGNUAttribute(Tag_GNU_Power_ABI_FP, 1437 Val_GNU_Power_ABI_HardFloat_DP | 1438 Val_GNU_Power_ABI_LDBL_64); 1439 } 1440 1441 void PPCLinuxAsmPrinter::emitInstruction(const MachineInstr *MI) { 1442 if (!Subtarget->isPPC64()) 1443 return PPCAsmPrinter::emitInstruction(MI); 1444 1445 switch (MI->getOpcode()) { 1446 default: 1447 return PPCAsmPrinter::emitInstruction(MI); 1448 case TargetOpcode::PATCHABLE_FUNCTION_ENTER: { 1449 // .begin: 1450 // b .end # lis 0, FuncId[16..32] 1451 // nop # li 0, FuncId[0..15] 1452 // std 0, -8(1) 1453 // mflr 0 1454 // bl __xray_FunctionEntry 1455 // mtlr 0 1456 // .end: 1457 // 1458 // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number 1459 // of instructions change. 1460 MCSymbol *BeginOfSled = OutContext.createTempSymbol(); 1461 MCSymbol *EndOfSled = OutContext.createTempSymbol(); 1462 OutStreamer->emitLabel(BeginOfSled); 1463 EmitToStreamer(*OutStreamer, 1464 MCInstBuilder(PPC::B).addExpr( 1465 MCSymbolRefExpr::create(EndOfSled, OutContext))); 1466 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP)); 1467 EmitToStreamer( 1468 *OutStreamer, 1469 MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1)); 1470 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0)); 1471 EmitToStreamer(*OutStreamer, 1472 MCInstBuilder(PPC::BL8_NOP) 1473 .addExpr(MCSymbolRefExpr::create( 1474 OutContext.getOrCreateSymbol("__xray_FunctionEntry"), 1475 OutContext))); 1476 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0)); 1477 OutStreamer->emitLabel(EndOfSled); 1478 recordSled(BeginOfSled, *MI, SledKind::FUNCTION_ENTER, 2); 1479 break; 1480 } 1481 case TargetOpcode::PATCHABLE_RET: { 1482 unsigned RetOpcode = MI->getOperand(0).getImm(); 1483 MCInst RetInst; 1484 RetInst.setOpcode(RetOpcode); 1485 for (const auto &MO : llvm::drop_begin(MI->operands())) { 1486 MCOperand MCOp; 1487 if (LowerPPCMachineOperandToMCOperand(MO, MCOp, *this)) 1488 RetInst.addOperand(MCOp); 1489 } 1490 1491 bool IsConditional; 1492 if (RetOpcode == PPC::BCCLR) { 1493 IsConditional = true; 1494 } else if (RetOpcode == PPC::TCRETURNdi8 || RetOpcode == PPC::TCRETURNri8 || 1495 RetOpcode == PPC::TCRETURNai8) { 1496 break; 1497 } else if (RetOpcode == PPC::BLR8 || RetOpcode == PPC::TAILB8) { 1498 IsConditional = false; 1499 } else { 1500 EmitToStreamer(*OutStreamer, RetInst); 1501 break; 1502 } 1503 1504 MCSymbol *FallthroughLabel; 1505 if (IsConditional) { 1506 // Before: 1507 // bgtlr cr0 1508 // 1509 // After: 1510 // ble cr0, .end 1511 // .p2align 3 1512 // .begin: 1513 // blr # lis 0, FuncId[16..32] 1514 // nop # li 0, FuncId[0..15] 1515 // std 0, -8(1) 1516 // mflr 0 1517 // bl __xray_FunctionExit 1518 // mtlr 0 1519 // blr 1520 // .end: 1521 // 1522 // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number 1523 // of instructions change. 1524 FallthroughLabel = OutContext.createTempSymbol(); 1525 EmitToStreamer( 1526 *OutStreamer, 1527 MCInstBuilder(PPC::BCC) 1528 .addImm(PPC::InvertPredicate( 1529 static_cast<PPC::Predicate>(MI->getOperand(1).getImm()))) 1530 .addReg(MI->getOperand(2).getReg()) 1531 .addExpr(MCSymbolRefExpr::create(FallthroughLabel, OutContext))); 1532 RetInst = MCInst(); 1533 RetInst.setOpcode(PPC::BLR8); 1534 } 1535 // .p2align 3 1536 // .begin: 1537 // b(lr)? # lis 0, FuncId[16..32] 1538 // nop # li 0, FuncId[0..15] 1539 // std 0, -8(1) 1540 // mflr 0 1541 // bl __xray_FunctionExit 1542 // mtlr 0 1543 // b(lr)? 1544 // 1545 // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number 1546 // of instructions change. 1547 OutStreamer->emitCodeAlignment(8, &getSubtargetInfo()); 1548 MCSymbol *BeginOfSled = OutContext.createTempSymbol(); 1549 OutStreamer->emitLabel(BeginOfSled); 1550 EmitToStreamer(*OutStreamer, RetInst); 1551 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP)); 1552 EmitToStreamer( 1553 *OutStreamer, 1554 MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1)); 1555 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0)); 1556 EmitToStreamer(*OutStreamer, 1557 MCInstBuilder(PPC::BL8_NOP) 1558 .addExpr(MCSymbolRefExpr::create( 1559 OutContext.getOrCreateSymbol("__xray_FunctionExit"), 1560 OutContext))); 1561 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0)); 1562 EmitToStreamer(*OutStreamer, RetInst); 1563 if (IsConditional) 1564 OutStreamer->emitLabel(FallthroughLabel); 1565 recordSled(BeginOfSled, *MI, SledKind::FUNCTION_EXIT, 2); 1566 break; 1567 } 1568 case TargetOpcode::PATCHABLE_FUNCTION_EXIT: 1569 llvm_unreachable("PATCHABLE_FUNCTION_EXIT should never be emitted"); 1570 case TargetOpcode::PATCHABLE_TAIL_CALL: 1571 // TODO: Define a trampoline `__xray_FunctionTailExit` and differentiate a 1572 // normal function exit from a tail exit. 1573 llvm_unreachable("Tail call is handled in the normal case. See comments " 1574 "around this assert."); 1575 } 1576 } 1577 1578 void PPCLinuxAsmPrinter::emitStartOfAsmFile(Module &M) { 1579 if (static_cast<const PPCTargetMachine &>(TM).isELFv2ABI()) { 1580 PPCTargetStreamer *TS = 1581 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer()); 1582 1583 if (TS) 1584 TS->emitAbiVersion(2); 1585 } 1586 1587 if (static_cast<const PPCTargetMachine &>(TM).isPPC64() || 1588 !isPositionIndependent()) 1589 return AsmPrinter::emitStartOfAsmFile(M); 1590 1591 if (M.getPICLevel() == PICLevel::SmallPIC) 1592 return AsmPrinter::emitStartOfAsmFile(M); 1593 1594 OutStreamer->switchSection(OutContext.getELFSection( 1595 ".got2", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC)); 1596 1597 MCSymbol *TOCSym = OutContext.getOrCreateSymbol(Twine(".LTOC")); 1598 MCSymbol *CurrentPos = OutContext.createTempSymbol(); 1599 1600 OutStreamer->emitLabel(CurrentPos); 1601 1602 // The GOT pointer points to the middle of the GOT, in order to reference the 1603 // entire 64kB range. 0x8000 is the midpoint. 1604 const MCExpr *tocExpr = 1605 MCBinaryExpr::createAdd(MCSymbolRefExpr::create(CurrentPos, OutContext), 1606 MCConstantExpr::create(0x8000, OutContext), 1607 OutContext); 1608 1609 OutStreamer->emitAssignment(TOCSym, tocExpr); 1610 1611 OutStreamer->switchSection(getObjFileLowering().getTextSection()); 1612 } 1613 1614 void PPCLinuxAsmPrinter::emitFunctionEntryLabel() { 1615 // linux/ppc32 - Normal entry label. 1616 if (!Subtarget->isPPC64() && 1617 (!isPositionIndependent() || 1618 MF->getFunction().getParent()->getPICLevel() == PICLevel::SmallPIC)) 1619 return AsmPrinter::emitFunctionEntryLabel(); 1620 1621 if (!Subtarget->isPPC64()) { 1622 const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>(); 1623 if (PPCFI->usesPICBase() && !Subtarget->isSecurePlt()) { 1624 MCSymbol *RelocSymbol = PPCFI->getPICOffsetSymbol(*MF); 1625 MCSymbol *PICBase = MF->getPICBaseSymbol(); 1626 OutStreamer->emitLabel(RelocSymbol); 1627 1628 const MCExpr *OffsExpr = 1629 MCBinaryExpr::createSub( 1630 MCSymbolRefExpr::create(OutContext.getOrCreateSymbol(Twine(".LTOC")), 1631 OutContext), 1632 MCSymbolRefExpr::create(PICBase, OutContext), 1633 OutContext); 1634 OutStreamer->emitValue(OffsExpr, 4); 1635 OutStreamer->emitLabel(CurrentFnSym); 1636 return; 1637 } else 1638 return AsmPrinter::emitFunctionEntryLabel(); 1639 } 1640 1641 // ELFv2 ABI - Normal entry label. 1642 if (Subtarget->isELFv2ABI()) { 1643 // In the Large code model, we allow arbitrary displacements between 1644 // the text section and its associated TOC section. We place the 1645 // full 8-byte offset to the TOC in memory immediately preceding 1646 // the function global entry point. 1647 if (TM.getCodeModel() == CodeModel::Large 1648 && !MF->getRegInfo().use_empty(PPC::X2)) { 1649 const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>(); 1650 1651 MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC.")); 1652 MCSymbol *GlobalEPSymbol = PPCFI->getGlobalEPSymbol(*MF); 1653 const MCExpr *TOCDeltaExpr = 1654 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext), 1655 MCSymbolRefExpr::create(GlobalEPSymbol, 1656 OutContext), 1657 OutContext); 1658 1659 OutStreamer->emitLabel(PPCFI->getTOCOffsetSymbol(*MF)); 1660 OutStreamer->emitValue(TOCDeltaExpr, 8); 1661 } 1662 return AsmPrinter::emitFunctionEntryLabel(); 1663 } 1664 1665 // Emit an official procedure descriptor. 1666 MCSectionSubPair Current = OutStreamer->getCurrentSection(); 1667 MCSectionELF *Section = OutStreamer->getContext().getELFSection( 1668 ".opd", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC); 1669 OutStreamer->switchSection(Section); 1670 OutStreamer->emitLabel(CurrentFnSym); 1671 OutStreamer->emitValueToAlignment(8); 1672 MCSymbol *Symbol1 = CurrentFnSymForSize; 1673 // Generates a R_PPC64_ADDR64 (from FK_DATA_8) relocation for the function 1674 // entry point. 1675 OutStreamer->emitValue(MCSymbolRefExpr::create(Symbol1, OutContext), 1676 8 /*size*/); 1677 MCSymbol *Symbol2 = OutContext.getOrCreateSymbol(StringRef(".TOC.")); 1678 // Generates a R_PPC64_TOC relocation for TOC base insertion. 1679 OutStreamer->emitValue( 1680 MCSymbolRefExpr::create(Symbol2, MCSymbolRefExpr::VK_PPC_TOCBASE, OutContext), 1681 8/*size*/); 1682 // Emit a null environment pointer. 1683 OutStreamer->emitIntValue(0, 8 /* size */); 1684 OutStreamer->switchSection(Current.first, Current.second); 1685 } 1686 1687 void PPCLinuxAsmPrinter::emitEndOfAsmFile(Module &M) { 1688 const DataLayout &DL = getDataLayout(); 1689 1690 bool isPPC64 = DL.getPointerSizeInBits() == 64; 1691 1692 PPCTargetStreamer *TS = 1693 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer()); 1694 1695 emitGNUAttributes(M); 1696 1697 if (!TOC.empty()) { 1698 const char *Name = isPPC64 ? ".toc" : ".got2"; 1699 MCSectionELF *Section = OutContext.getELFSection( 1700 Name, ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC); 1701 OutStreamer->switchSection(Section); 1702 if (!isPPC64) 1703 OutStreamer->emitValueToAlignment(4); 1704 1705 for (const auto &TOCMapPair : TOC) { 1706 const MCSymbol *const TOCEntryTarget = TOCMapPair.first.first; 1707 MCSymbol *const TOCEntryLabel = TOCMapPair.second; 1708 1709 OutStreamer->emitLabel(TOCEntryLabel); 1710 if (isPPC64 && TS != nullptr) 1711 TS->emitTCEntry(*TOCEntryTarget, TOCMapPair.first.second); 1712 else 1713 OutStreamer->emitSymbolValue(TOCEntryTarget, 4); 1714 } 1715 } 1716 1717 PPCAsmPrinter::emitEndOfAsmFile(M); 1718 } 1719 1720 /// EmitFunctionBodyStart - Emit a global entry point prefix for ELFv2. 1721 void PPCLinuxAsmPrinter::emitFunctionBodyStart() { 1722 // In the ELFv2 ABI, in functions that use the TOC register, we need to 1723 // provide two entry points. The ABI guarantees that when calling the 1724 // local entry point, r2 is set up by the caller to contain the TOC base 1725 // for this function, and when calling the global entry point, r12 is set 1726 // up by the caller to hold the address of the global entry point. We 1727 // thus emit a prefix sequence along the following lines: 1728 // 1729 // func: 1730 // .Lfunc_gepNN: 1731 // # global entry point 1732 // addis r2,r12,(.TOC.-.Lfunc_gepNN)@ha 1733 // addi r2,r2,(.TOC.-.Lfunc_gepNN)@l 1734 // .Lfunc_lepNN: 1735 // .localentry func, .Lfunc_lepNN-.Lfunc_gepNN 1736 // # local entry point, followed by function body 1737 // 1738 // For the Large code model, we create 1739 // 1740 // .Lfunc_tocNN: 1741 // .quad .TOC.-.Lfunc_gepNN # done by EmitFunctionEntryLabel 1742 // func: 1743 // .Lfunc_gepNN: 1744 // # global entry point 1745 // ld r2,.Lfunc_tocNN-.Lfunc_gepNN(r12) 1746 // add r2,r2,r12 1747 // .Lfunc_lepNN: 1748 // .localentry func, .Lfunc_lepNN-.Lfunc_gepNN 1749 // # local entry point, followed by function body 1750 // 1751 // This ensures we have r2 set up correctly while executing the function 1752 // body, no matter which entry point is called. 1753 const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>(); 1754 const bool UsesX2OrR2 = !MF->getRegInfo().use_empty(PPC::X2) || 1755 !MF->getRegInfo().use_empty(PPC::R2); 1756 const bool PCrelGEPRequired = Subtarget->isUsingPCRelativeCalls() && 1757 UsesX2OrR2 && PPCFI->usesTOCBasePtr(); 1758 const bool NonPCrelGEPRequired = !Subtarget->isUsingPCRelativeCalls() && 1759 Subtarget->isELFv2ABI() && UsesX2OrR2; 1760 1761 // Only do all that if the function uses R2 as the TOC pointer 1762 // in the first place. We don't need the global entry point if the 1763 // function uses R2 as an allocatable register. 1764 if (NonPCrelGEPRequired || PCrelGEPRequired) { 1765 // Note: The logic here must be synchronized with the code in the 1766 // branch-selection pass which sets the offset of the first block in the 1767 // function. This matters because it affects the alignment. 1768 MCSymbol *GlobalEntryLabel = PPCFI->getGlobalEPSymbol(*MF); 1769 OutStreamer->emitLabel(GlobalEntryLabel); 1770 const MCSymbolRefExpr *GlobalEntryLabelExp = 1771 MCSymbolRefExpr::create(GlobalEntryLabel, OutContext); 1772 1773 if (TM.getCodeModel() != CodeModel::Large) { 1774 MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC.")); 1775 const MCExpr *TOCDeltaExpr = 1776 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext), 1777 GlobalEntryLabelExp, OutContext); 1778 1779 const MCExpr *TOCDeltaHi = PPCMCExpr::createHa(TOCDeltaExpr, OutContext); 1780 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS) 1781 .addReg(PPC::X2) 1782 .addReg(PPC::X12) 1783 .addExpr(TOCDeltaHi)); 1784 1785 const MCExpr *TOCDeltaLo = PPCMCExpr::createLo(TOCDeltaExpr, OutContext); 1786 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDI) 1787 .addReg(PPC::X2) 1788 .addReg(PPC::X2) 1789 .addExpr(TOCDeltaLo)); 1790 } else { 1791 MCSymbol *TOCOffset = PPCFI->getTOCOffsetSymbol(*MF); 1792 const MCExpr *TOCOffsetDeltaExpr = 1793 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCOffset, OutContext), 1794 GlobalEntryLabelExp, OutContext); 1795 1796 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD) 1797 .addReg(PPC::X2) 1798 .addExpr(TOCOffsetDeltaExpr) 1799 .addReg(PPC::X12)); 1800 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD8) 1801 .addReg(PPC::X2) 1802 .addReg(PPC::X2) 1803 .addReg(PPC::X12)); 1804 } 1805 1806 MCSymbol *LocalEntryLabel = PPCFI->getLocalEPSymbol(*MF); 1807 OutStreamer->emitLabel(LocalEntryLabel); 1808 const MCSymbolRefExpr *LocalEntryLabelExp = 1809 MCSymbolRefExpr::create(LocalEntryLabel, OutContext); 1810 const MCExpr *LocalOffsetExp = 1811 MCBinaryExpr::createSub(LocalEntryLabelExp, 1812 GlobalEntryLabelExp, OutContext); 1813 1814 PPCTargetStreamer *TS = 1815 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer()); 1816 1817 if (TS) 1818 TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym), LocalOffsetExp); 1819 } else if (Subtarget->isUsingPCRelativeCalls()) { 1820 // When generating the entry point for a function we have a few scenarios 1821 // based on whether or not that function uses R2 and whether or not that 1822 // function makes calls (or is a leaf function). 1823 // 1) A leaf function that does not use R2 (or treats it as callee-saved 1824 // and preserves it). In this case st_other=0 and both 1825 // the local and global entry points for the function are the same. 1826 // No special entry point code is required. 1827 // 2) A function uses the TOC pointer R2. This function may or may not have 1828 // calls. In this case st_other=[2,6] and the global and local entry 1829 // points are different. Code to correctly setup the TOC pointer in R2 1830 // is put between the global and local entry points. This case is 1831 // covered by the if statatement above. 1832 // 3) A function does not use the TOC pointer R2 but does have calls. 1833 // In this case st_other=1 since we do not know whether or not any 1834 // of the callees clobber R2. This case is dealt with in this else if 1835 // block. Tail calls are considered calls and the st_other should also 1836 // be set to 1 in that case as well. 1837 // 4) The function does not use the TOC pointer but R2 is used inside 1838 // the function. In this case st_other=1 once again. 1839 // 5) This function uses inline asm. We mark R2 as reserved if the function 1840 // has inline asm as we have to assume that it may be used. 1841 if (MF->getFrameInfo().hasCalls() || MF->getFrameInfo().hasTailCall() || 1842 MF->hasInlineAsm() || (!PPCFI->usesTOCBasePtr() && UsesX2OrR2)) { 1843 PPCTargetStreamer *TS = 1844 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer()); 1845 if (TS) 1846 TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym), 1847 MCConstantExpr::create(1, OutContext)); 1848 } 1849 } 1850 } 1851 1852 /// EmitFunctionBodyEnd - Print the traceback table before the .size 1853 /// directive. 1854 /// 1855 void PPCLinuxAsmPrinter::emitFunctionBodyEnd() { 1856 // Only the 64-bit target requires a traceback table. For now, 1857 // we only emit the word of zeroes that GDB requires to find 1858 // the end of the function, and zeroes for the eight-byte 1859 // mandatory fields. 1860 // FIXME: We should fill in the eight-byte mandatory fields as described in 1861 // the PPC64 ELF ABI (this is a low-priority item because GDB does not 1862 // currently make use of these fields). 1863 if (Subtarget->isPPC64()) { 1864 OutStreamer->emitIntValue(0, 4/*size*/); 1865 OutStreamer->emitIntValue(0, 8/*size*/); 1866 } 1867 } 1868 1869 void PPCAIXAsmPrinter::emitLinkage(const GlobalValue *GV, 1870 MCSymbol *GVSym) const { 1871 1872 assert(MAI->hasVisibilityOnlyWithLinkage() && 1873 "AIX's linkage directives take a visibility setting."); 1874 1875 MCSymbolAttr LinkageAttr = MCSA_Invalid; 1876 switch (GV->getLinkage()) { 1877 case GlobalValue::ExternalLinkage: 1878 LinkageAttr = GV->isDeclaration() ? MCSA_Extern : MCSA_Global; 1879 break; 1880 case GlobalValue::LinkOnceAnyLinkage: 1881 case GlobalValue::LinkOnceODRLinkage: 1882 case GlobalValue::WeakAnyLinkage: 1883 case GlobalValue::WeakODRLinkage: 1884 case GlobalValue::ExternalWeakLinkage: 1885 LinkageAttr = MCSA_Weak; 1886 break; 1887 case GlobalValue::AvailableExternallyLinkage: 1888 LinkageAttr = MCSA_Extern; 1889 break; 1890 case GlobalValue::PrivateLinkage: 1891 return; 1892 case GlobalValue::InternalLinkage: 1893 assert(GV->getVisibility() == GlobalValue::DefaultVisibility && 1894 "InternalLinkage should not have other visibility setting."); 1895 LinkageAttr = MCSA_LGlobal; 1896 break; 1897 case GlobalValue::AppendingLinkage: 1898 llvm_unreachable("Should never emit this"); 1899 case GlobalValue::CommonLinkage: 1900 llvm_unreachable("CommonLinkage of XCOFF should not come to this path"); 1901 } 1902 1903 assert(LinkageAttr != MCSA_Invalid && "LinkageAttr should not MCSA_Invalid."); 1904 1905 MCSymbolAttr VisibilityAttr = MCSA_Invalid; 1906 if (!TM.getIgnoreXCOFFVisibility()) { 1907 if (GV->hasDLLExportStorageClass() && !GV->hasDefaultVisibility()) 1908 report_fatal_error( 1909 "Cannot not be both dllexport and non-default visibility"); 1910 switch (GV->getVisibility()) { 1911 1912 // TODO: "internal" Visibility needs to go here. 1913 case GlobalValue::DefaultVisibility: 1914 if (GV->hasDLLExportStorageClass()) 1915 VisibilityAttr = MAI->getExportedVisibilityAttr(); 1916 break; 1917 case GlobalValue::HiddenVisibility: 1918 VisibilityAttr = MAI->getHiddenVisibilityAttr(); 1919 break; 1920 case GlobalValue::ProtectedVisibility: 1921 VisibilityAttr = MAI->getProtectedVisibilityAttr(); 1922 break; 1923 } 1924 } 1925 1926 OutStreamer->emitXCOFFSymbolLinkageWithVisibility(GVSym, LinkageAttr, 1927 VisibilityAttr); 1928 } 1929 1930 void PPCAIXAsmPrinter::SetupMachineFunction(MachineFunction &MF) { 1931 // Setup CurrentFnDescSym and its containing csect. 1932 MCSectionXCOFF *FnDescSec = 1933 cast<MCSectionXCOFF>(getObjFileLowering().getSectionForFunctionDescriptor( 1934 &MF.getFunction(), TM)); 1935 FnDescSec->setAlignment(Align(Subtarget->isPPC64() ? 8 : 4)); 1936 1937 CurrentFnDescSym = FnDescSec->getQualNameSymbol(); 1938 1939 return AsmPrinter::SetupMachineFunction(MF); 1940 } 1941 1942 uint16_t PPCAIXAsmPrinter::getNumberOfVRSaved() { 1943 // Calculate the number of VRs be saved. 1944 // Vector registers 20 through 31 are marked as reserved and cannot be used 1945 // in the default ABI. 1946 const PPCSubtarget &Subtarget = MF->getSubtarget<PPCSubtarget>(); 1947 if (Subtarget.isAIXABI() && Subtarget.hasAltivec() && 1948 TM.getAIXExtendedAltivecABI()) { 1949 const MachineRegisterInfo &MRI = MF->getRegInfo(); 1950 for (unsigned Reg = PPC::V20; Reg <= PPC::V31; ++Reg) 1951 if (MRI.isPhysRegModified(Reg)) 1952 // Number of VRs saved. 1953 return PPC::V31 - Reg + 1; 1954 } 1955 return 0; 1956 } 1957 1958 void PPCAIXAsmPrinter::emitFunctionBodyEnd() { 1959 1960 if (!TM.getXCOFFTracebackTable()) 1961 return; 1962 1963 emitTracebackTable(); 1964 1965 // If ShouldEmitEHBlock returns true, then the eh info table 1966 // will be emitted via `AIXException::endFunction`. Otherwise, we 1967 // need to emit a dumy eh info table when VRs are saved. We could not 1968 // consolidate these two places into one because there is no easy way 1969 // to access register information in `AIXException` class. 1970 if (!TargetLoweringObjectFileXCOFF::ShouldEmitEHBlock(MF) && 1971 (getNumberOfVRSaved() > 0)) { 1972 // Emit dummy EH Info Table. 1973 OutStreamer->switchSection(getObjFileLowering().getCompactUnwindSection()); 1974 MCSymbol *EHInfoLabel = 1975 TargetLoweringObjectFileXCOFF::getEHInfoTableSymbol(MF); 1976 OutStreamer->emitLabel(EHInfoLabel); 1977 1978 // Version number. 1979 OutStreamer->emitInt32(0); 1980 1981 const DataLayout &DL = MMI->getModule()->getDataLayout(); 1982 const unsigned PointerSize = DL.getPointerSize(); 1983 // Add necessary paddings in 64 bit mode. 1984 OutStreamer->emitValueToAlignment(PointerSize); 1985 1986 OutStreamer->emitIntValue(0, PointerSize); 1987 OutStreamer->emitIntValue(0, PointerSize); 1988 OutStreamer->switchSection(MF->getSection()); 1989 } 1990 } 1991 1992 void PPCAIXAsmPrinter::emitTracebackTable() { 1993 1994 // Create a symbol for the end of function. 1995 MCSymbol *FuncEnd = createTempSymbol(MF->getName()); 1996 OutStreamer->emitLabel(FuncEnd); 1997 1998 OutStreamer->AddComment("Traceback table begin"); 1999 // Begin with a fullword of zero. 2000 OutStreamer->emitIntValueInHexWithPadding(0, 4 /*size*/); 2001 2002 SmallString<128> CommentString; 2003 raw_svector_ostream CommentOS(CommentString); 2004 2005 auto EmitComment = [&]() { 2006 OutStreamer->AddComment(CommentOS.str()); 2007 CommentString.clear(); 2008 }; 2009 2010 auto EmitCommentAndValue = [&](uint64_t Value, int Size) { 2011 EmitComment(); 2012 OutStreamer->emitIntValueInHexWithPadding(Value, Size); 2013 }; 2014 2015 unsigned int Version = 0; 2016 CommentOS << "Version = " << Version; 2017 EmitCommentAndValue(Version, 1); 2018 2019 // There is a lack of information in the IR to assist with determining the 2020 // source language. AIX exception handling mechanism would only search for 2021 // personality routine and LSDA area when such language supports exception 2022 // handling. So to be conservatively correct and allow runtime to do its job, 2023 // we need to set it to C++ for now. 2024 TracebackTable::LanguageID LanguageIdentifier = 2025 TracebackTable::CPlusPlus; // C++ 2026 2027 CommentOS << "Language = " 2028 << getNameForTracebackTableLanguageId(LanguageIdentifier); 2029 EmitCommentAndValue(LanguageIdentifier, 1); 2030 2031 // This is only populated for the third and fourth bytes. 2032 uint32_t FirstHalfOfMandatoryField = 0; 2033 2034 // Emit the 3rd byte of the mandatory field. 2035 2036 // We always set traceback offset bit to true. 2037 FirstHalfOfMandatoryField |= TracebackTable::HasTraceBackTableOffsetMask; 2038 2039 const PPCFunctionInfo *FI = MF->getInfo<PPCFunctionInfo>(); 2040 const MachineRegisterInfo &MRI = MF->getRegInfo(); 2041 2042 // Check the function uses floating-point processor instructions or not 2043 for (unsigned Reg = PPC::F0; Reg <= PPC::F31; ++Reg) { 2044 if (MRI.isPhysRegUsed(Reg, /* SkipRegMaskTest */ true)) { 2045 FirstHalfOfMandatoryField |= TracebackTable::IsFloatingPointPresentMask; 2046 break; 2047 } 2048 } 2049 2050 #define GENBOOLCOMMENT(Prefix, V, Field) \ 2051 CommentOS << (Prefix) << ((V) & (TracebackTable::Field##Mask) ? "+" : "-") \ 2052 << #Field 2053 2054 #define GENVALUECOMMENT(PrefixAndName, V, Field) \ 2055 CommentOS << (PrefixAndName) << " = " \ 2056 << static_cast<unsigned>(((V) & (TracebackTable::Field##Mask)) >> \ 2057 (TracebackTable::Field##Shift)) 2058 2059 GENBOOLCOMMENT("", FirstHalfOfMandatoryField, IsGlobaLinkage); 2060 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsOutOfLineEpilogOrPrologue); 2061 EmitComment(); 2062 2063 GENBOOLCOMMENT("", FirstHalfOfMandatoryField, HasTraceBackTableOffset); 2064 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsInternalProcedure); 2065 EmitComment(); 2066 2067 GENBOOLCOMMENT("", FirstHalfOfMandatoryField, HasControlledStorage); 2068 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsTOCless); 2069 EmitComment(); 2070 2071 GENBOOLCOMMENT("", FirstHalfOfMandatoryField, IsFloatingPointPresent); 2072 EmitComment(); 2073 GENBOOLCOMMENT("", FirstHalfOfMandatoryField, 2074 IsFloatingPointOperationLogOrAbortEnabled); 2075 EmitComment(); 2076 2077 OutStreamer->emitIntValueInHexWithPadding( 2078 (FirstHalfOfMandatoryField & 0x0000ff00) >> 8, 1); 2079 2080 // Set the 4th byte of the mandatory field. 2081 FirstHalfOfMandatoryField |= TracebackTable::IsFunctionNamePresentMask; 2082 2083 const PPCRegisterInfo *RegInfo = 2084 static_cast<const PPCRegisterInfo *>(Subtarget->getRegisterInfo()); 2085 Register FrameReg = RegInfo->getFrameRegister(*MF); 2086 if (FrameReg == (Subtarget->isPPC64() ? PPC::X31 : PPC::R31)) 2087 FirstHalfOfMandatoryField |= TracebackTable::IsAllocaUsedMask; 2088 2089 const SmallVectorImpl<Register> &MustSaveCRs = FI->getMustSaveCRs(); 2090 if (!MustSaveCRs.empty()) 2091 FirstHalfOfMandatoryField |= TracebackTable::IsCRSavedMask; 2092 2093 if (FI->mustSaveLR()) 2094 FirstHalfOfMandatoryField |= TracebackTable::IsLRSavedMask; 2095 2096 GENBOOLCOMMENT("", FirstHalfOfMandatoryField, IsInterruptHandler); 2097 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsFunctionNamePresent); 2098 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsAllocaUsed); 2099 EmitComment(); 2100 GENVALUECOMMENT("OnConditionDirective", FirstHalfOfMandatoryField, 2101 OnConditionDirective); 2102 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsCRSaved); 2103 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsLRSaved); 2104 EmitComment(); 2105 OutStreamer->emitIntValueInHexWithPadding((FirstHalfOfMandatoryField & 0xff), 2106 1); 2107 2108 // Set the 5th byte of mandatory field. 2109 uint32_t SecondHalfOfMandatoryField = 0; 2110 2111 // Always store back chain. 2112 SecondHalfOfMandatoryField |= TracebackTable::IsBackChainStoredMask; 2113 2114 uint32_t FPRSaved = 0; 2115 for (unsigned Reg = PPC::F14; Reg <= PPC::F31; ++Reg) { 2116 if (MRI.isPhysRegModified(Reg)) { 2117 FPRSaved = PPC::F31 - Reg + 1; 2118 break; 2119 } 2120 } 2121 SecondHalfOfMandatoryField |= (FPRSaved << TracebackTable::FPRSavedShift) & 2122 TracebackTable::FPRSavedMask; 2123 GENBOOLCOMMENT("", SecondHalfOfMandatoryField, IsBackChainStored); 2124 GENBOOLCOMMENT(", ", SecondHalfOfMandatoryField, IsFixup); 2125 GENVALUECOMMENT(", NumOfFPRsSaved", SecondHalfOfMandatoryField, FPRSaved); 2126 EmitComment(); 2127 OutStreamer->emitIntValueInHexWithPadding( 2128 (SecondHalfOfMandatoryField & 0xff000000) >> 24, 1); 2129 2130 // Set the 6th byte of mandatory field. 2131 2132 // Check whether has Vector Instruction,We only treat instructions uses vector 2133 // register as vector instructions. 2134 bool HasVectorInst = false; 2135 for (unsigned Reg = PPC::V0; Reg <= PPC::V31; ++Reg) 2136 if (MRI.isPhysRegUsed(Reg, /* SkipRegMaskTest */ true)) { 2137 // Has VMX instruction. 2138 HasVectorInst = true; 2139 break; 2140 } 2141 2142 if (FI->hasVectorParms() || HasVectorInst) 2143 SecondHalfOfMandatoryField |= TracebackTable::HasVectorInfoMask; 2144 2145 uint16_t NumOfVRSaved = getNumberOfVRSaved(); 2146 bool ShouldEmitEHBlock = 2147 TargetLoweringObjectFileXCOFF::ShouldEmitEHBlock(MF) || NumOfVRSaved > 0; 2148 2149 if (ShouldEmitEHBlock) 2150 SecondHalfOfMandatoryField |= TracebackTable::HasExtensionTableMask; 2151 2152 uint32_t GPRSaved = 0; 2153 2154 // X13 is reserved under 64-bit environment. 2155 unsigned GPRBegin = Subtarget->isPPC64() ? PPC::X14 : PPC::R13; 2156 unsigned GPREnd = Subtarget->isPPC64() ? PPC::X31 : PPC::R31; 2157 2158 for (unsigned Reg = GPRBegin; Reg <= GPREnd; ++Reg) { 2159 if (MRI.isPhysRegModified(Reg)) { 2160 GPRSaved = GPREnd - Reg + 1; 2161 break; 2162 } 2163 } 2164 2165 SecondHalfOfMandatoryField |= (GPRSaved << TracebackTable::GPRSavedShift) & 2166 TracebackTable::GPRSavedMask; 2167 2168 GENBOOLCOMMENT("", SecondHalfOfMandatoryField, HasExtensionTable); 2169 GENBOOLCOMMENT(", ", SecondHalfOfMandatoryField, HasVectorInfo); 2170 GENVALUECOMMENT(", NumOfGPRsSaved", SecondHalfOfMandatoryField, GPRSaved); 2171 EmitComment(); 2172 OutStreamer->emitIntValueInHexWithPadding( 2173 (SecondHalfOfMandatoryField & 0x00ff0000) >> 16, 1); 2174 2175 // Set the 7th byte of mandatory field. 2176 uint32_t NumberOfFixedParms = FI->getFixedParmsNum(); 2177 SecondHalfOfMandatoryField |= 2178 (NumberOfFixedParms << TracebackTable::NumberOfFixedParmsShift) & 2179 TracebackTable::NumberOfFixedParmsMask; 2180 GENVALUECOMMENT("NumberOfFixedParms", SecondHalfOfMandatoryField, 2181 NumberOfFixedParms); 2182 EmitComment(); 2183 OutStreamer->emitIntValueInHexWithPadding( 2184 (SecondHalfOfMandatoryField & 0x0000ff00) >> 8, 1); 2185 2186 // Set the 8th byte of mandatory field. 2187 2188 // Always set parameter on stack. 2189 SecondHalfOfMandatoryField |= TracebackTable::HasParmsOnStackMask; 2190 2191 uint32_t NumberOfFPParms = FI->getFloatingPointParmsNum(); 2192 SecondHalfOfMandatoryField |= 2193 (NumberOfFPParms << TracebackTable::NumberOfFloatingPointParmsShift) & 2194 TracebackTable::NumberOfFloatingPointParmsMask; 2195 2196 GENVALUECOMMENT("NumberOfFPParms", SecondHalfOfMandatoryField, 2197 NumberOfFloatingPointParms); 2198 GENBOOLCOMMENT(", ", SecondHalfOfMandatoryField, HasParmsOnStack); 2199 EmitComment(); 2200 OutStreamer->emitIntValueInHexWithPadding(SecondHalfOfMandatoryField & 0xff, 2201 1); 2202 2203 // Generate the optional fields of traceback table. 2204 2205 // Parameter type. 2206 if (NumberOfFixedParms || NumberOfFPParms) { 2207 uint32_t ParmsTypeValue = FI->getParmsType(); 2208 2209 Expected<SmallString<32>> ParmsType = 2210 FI->hasVectorParms() 2211 ? XCOFF::parseParmsTypeWithVecInfo( 2212 ParmsTypeValue, NumberOfFixedParms, NumberOfFPParms, 2213 FI->getVectorParmsNum()) 2214 : XCOFF::parseParmsType(ParmsTypeValue, NumberOfFixedParms, 2215 NumberOfFPParms); 2216 2217 assert(ParmsType && toString(ParmsType.takeError()).c_str()); 2218 if (ParmsType) { 2219 CommentOS << "Parameter type = " << ParmsType.get(); 2220 EmitComment(); 2221 } 2222 OutStreamer->emitIntValueInHexWithPadding(ParmsTypeValue, 2223 sizeof(ParmsTypeValue)); 2224 } 2225 // Traceback table offset. 2226 OutStreamer->AddComment("Function size"); 2227 if (FirstHalfOfMandatoryField & TracebackTable::HasTraceBackTableOffsetMask) { 2228 MCSymbol *FuncSectSym = getObjFileLowering().getFunctionEntryPointSymbol( 2229 &(MF->getFunction()), TM); 2230 OutStreamer->emitAbsoluteSymbolDiff(FuncEnd, FuncSectSym, 4); 2231 } 2232 2233 // Since we unset the Int_Handler. 2234 if (FirstHalfOfMandatoryField & TracebackTable::IsInterruptHandlerMask) 2235 report_fatal_error("Hand_Mask not implement yet"); 2236 2237 if (FirstHalfOfMandatoryField & TracebackTable::HasControlledStorageMask) 2238 report_fatal_error("Ctl_Info not implement yet"); 2239 2240 if (FirstHalfOfMandatoryField & TracebackTable::IsFunctionNamePresentMask) { 2241 StringRef Name = MF->getName().substr(0, INT16_MAX); 2242 int16_t NameLength = Name.size(); 2243 CommentOS << "Function name len = " 2244 << static_cast<unsigned int>(NameLength); 2245 EmitCommentAndValue(NameLength, 2); 2246 OutStreamer->AddComment("Function Name"); 2247 OutStreamer->emitBytes(Name); 2248 } 2249 2250 if (FirstHalfOfMandatoryField & TracebackTable::IsAllocaUsedMask) { 2251 uint8_t AllocReg = XCOFF::AllocRegNo; 2252 OutStreamer->AddComment("AllocaUsed"); 2253 OutStreamer->emitIntValueInHex(AllocReg, sizeof(AllocReg)); 2254 } 2255 2256 if (SecondHalfOfMandatoryField & TracebackTable::HasVectorInfoMask) { 2257 uint16_t VRData = 0; 2258 if (NumOfVRSaved) { 2259 // Number of VRs saved. 2260 VRData |= (NumOfVRSaved << TracebackTable::NumberOfVRSavedShift) & 2261 TracebackTable::NumberOfVRSavedMask; 2262 // This bit is supposed to set only when the special register 2263 // VRSAVE is saved on stack. 2264 // However, IBM XL compiler sets the bit when any vector registers 2265 // are saved on the stack. We will follow XL's behavior on AIX 2266 // so that we don't get surprise behavior change for C code. 2267 VRData |= TracebackTable::IsVRSavedOnStackMask; 2268 } 2269 2270 // Set has_varargs. 2271 if (FI->getVarArgsFrameIndex()) 2272 VRData |= TracebackTable::HasVarArgsMask; 2273 2274 // Vector parameters number. 2275 unsigned VectorParmsNum = FI->getVectorParmsNum(); 2276 VRData |= (VectorParmsNum << TracebackTable::NumberOfVectorParmsShift) & 2277 TracebackTable::NumberOfVectorParmsMask; 2278 2279 if (HasVectorInst) 2280 VRData |= TracebackTable::HasVMXInstructionMask; 2281 2282 GENVALUECOMMENT("NumOfVRsSaved", VRData, NumberOfVRSaved); 2283 GENBOOLCOMMENT(", ", VRData, IsVRSavedOnStack); 2284 GENBOOLCOMMENT(", ", VRData, HasVarArgs); 2285 EmitComment(); 2286 OutStreamer->emitIntValueInHexWithPadding((VRData & 0xff00) >> 8, 1); 2287 2288 GENVALUECOMMENT("NumOfVectorParams", VRData, NumberOfVectorParms); 2289 GENBOOLCOMMENT(", ", VRData, HasVMXInstruction); 2290 EmitComment(); 2291 OutStreamer->emitIntValueInHexWithPadding(VRData & 0x00ff, 1); 2292 2293 uint32_t VecParmTypeValue = FI->getVecExtParmsType(); 2294 2295 Expected<SmallString<32>> VecParmsType = 2296 XCOFF::parseVectorParmsType(VecParmTypeValue, VectorParmsNum); 2297 assert(VecParmsType && toString(VecParmsType.takeError()).c_str()); 2298 if (VecParmsType) { 2299 CommentOS << "Vector Parameter type = " << VecParmsType.get(); 2300 EmitComment(); 2301 } 2302 OutStreamer->emitIntValueInHexWithPadding(VecParmTypeValue, 2303 sizeof(VecParmTypeValue)); 2304 // Padding 2 bytes. 2305 CommentOS << "Padding"; 2306 EmitCommentAndValue(0, 2); 2307 } 2308 2309 uint8_t ExtensionTableFlag = 0; 2310 if (SecondHalfOfMandatoryField & TracebackTable::HasExtensionTableMask) { 2311 if (ShouldEmitEHBlock) 2312 ExtensionTableFlag |= ExtendedTBTableFlag::TB_EH_INFO; 2313 if (EnableSSPCanaryBitInTB && 2314 TargetLoweringObjectFileXCOFF::ShouldSetSSPCanaryBitInTB(MF)) 2315 ExtensionTableFlag |= ExtendedTBTableFlag::TB_SSP_CANARY; 2316 2317 CommentOS << "ExtensionTableFlag = " 2318 << getExtendedTBTableFlagString(ExtensionTableFlag); 2319 EmitCommentAndValue(ExtensionTableFlag, sizeof(ExtensionTableFlag)); 2320 } 2321 2322 if (ExtensionTableFlag & ExtendedTBTableFlag::TB_EH_INFO) { 2323 auto &Ctx = OutStreamer->getContext(); 2324 MCSymbol *EHInfoSym = 2325 TargetLoweringObjectFileXCOFF::getEHInfoTableSymbol(MF); 2326 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(EHInfoSym); 2327 const MCSymbol *TOCBaseSym = 2328 cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection()) 2329 ->getQualNameSymbol(); 2330 const MCExpr *Exp = 2331 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCEntry, Ctx), 2332 MCSymbolRefExpr::create(TOCBaseSym, Ctx), Ctx); 2333 2334 const DataLayout &DL = getDataLayout(); 2335 OutStreamer->emitValueToAlignment(4); 2336 OutStreamer->AddComment("EHInfo Table"); 2337 OutStreamer->emitValue(Exp, DL.getPointerSize()); 2338 } 2339 #undef GENBOOLCOMMENT 2340 #undef GENVALUECOMMENT 2341 } 2342 2343 static bool isSpecialLLVMGlobalArrayToSkip(const GlobalVariable *GV) { 2344 return GV->hasAppendingLinkage() && 2345 StringSwitch<bool>(GV->getName()) 2346 // TODO: Linker could still eliminate the GV if we just skip 2347 // handling llvm.used array. Skipping them for now until we or the 2348 // AIX OS team come up with a good solution. 2349 .Case("llvm.used", true) 2350 // It's correct to just skip llvm.compiler.used array here. 2351 .Case("llvm.compiler.used", true) 2352 .Default(false); 2353 } 2354 2355 static bool isSpecialLLVMGlobalArrayForStaticInit(const GlobalVariable *GV) { 2356 return StringSwitch<bool>(GV->getName()) 2357 .Cases("llvm.global_ctors", "llvm.global_dtors", true) 2358 .Default(false); 2359 } 2360 2361 uint64_t PPCAIXAsmPrinter::getAliasOffset(const Constant *C) { 2362 if (auto *GA = dyn_cast<GlobalAlias>(C)) 2363 return getAliasOffset(GA->getAliasee()); 2364 if (auto *CE = dyn_cast<ConstantExpr>(C)) { 2365 const MCExpr *LowC = lowerConstant(CE); 2366 const MCBinaryExpr *CBE = dyn_cast<MCBinaryExpr>(LowC); 2367 if (!CBE) 2368 return 0; 2369 if (CBE->getOpcode() != MCBinaryExpr::Add) 2370 report_fatal_error("Only adding an offset is supported now."); 2371 auto *RHS = dyn_cast<MCConstantExpr>(CBE->getRHS()); 2372 if (!RHS) 2373 report_fatal_error("Unable to get the offset of alias."); 2374 return RHS->getValue(); 2375 } 2376 return 0; 2377 } 2378 2379 void PPCAIXAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) { 2380 // Special LLVM global arrays have been handled at the initialization. 2381 if (isSpecialLLVMGlobalArrayToSkip(GV) || isSpecialLLVMGlobalArrayForStaticInit(GV)) 2382 return; 2383 2384 // If the Global Variable has the toc-data attribute, it needs to be emitted 2385 // when we emit the .toc section. 2386 if (GV->hasAttribute("toc-data")) { 2387 TOCDataGlobalVars.push_back(GV); 2388 return; 2389 } 2390 2391 emitGlobalVariableHelper(GV); 2392 } 2393 2394 void PPCAIXAsmPrinter::emitGlobalVariableHelper(const GlobalVariable *GV) { 2395 assert(!GV->getName().startswith("llvm.") && 2396 "Unhandled intrinsic global variable."); 2397 2398 if (GV->hasComdat()) 2399 report_fatal_error("COMDAT not yet supported by AIX."); 2400 2401 MCSymbolXCOFF *GVSym = cast<MCSymbolXCOFF>(getSymbol(GV)); 2402 2403 if (GV->isDeclarationForLinker()) { 2404 emitLinkage(GV, GVSym); 2405 return; 2406 } 2407 2408 SectionKind GVKind = getObjFileLowering().getKindForGlobal(GV, TM); 2409 if (!GVKind.isGlobalWriteableData() && !GVKind.isReadOnly() && 2410 !GVKind.isThreadLocal()) // Checks for both ThreadData and ThreadBSS. 2411 report_fatal_error("Encountered a global variable kind that is " 2412 "not supported yet."); 2413 2414 // Print GV in verbose mode 2415 if (isVerbose()) { 2416 if (GV->hasInitializer()) { 2417 GV->printAsOperand(OutStreamer->getCommentOS(), 2418 /*PrintType=*/false, GV->getParent()); 2419 OutStreamer->getCommentOS() << '\n'; 2420 } 2421 } 2422 2423 MCSectionXCOFF *Csect = cast<MCSectionXCOFF>( 2424 getObjFileLowering().SectionForGlobal(GV, GVKind, TM)); 2425 2426 // Switch to the containing csect. 2427 OutStreamer->switchSection(Csect); 2428 2429 const DataLayout &DL = GV->getParent()->getDataLayout(); 2430 2431 // Handle common and zero-initialized local symbols. 2432 if (GV->hasCommonLinkage() || GVKind.isBSSLocal() || 2433 GVKind.isThreadBSSLocal()) { 2434 Align Alignment = GV->getAlign().value_or(DL.getPreferredAlign(GV)); 2435 uint64_t Size = DL.getTypeAllocSize(GV->getValueType()); 2436 GVSym->setStorageClass( 2437 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GV)); 2438 2439 if (GVKind.isBSSLocal() || GVKind.isThreadBSSLocal()) 2440 OutStreamer->emitXCOFFLocalCommonSymbol( 2441 OutContext.getOrCreateSymbol(GVSym->getSymbolTableName()), Size, 2442 GVSym, Alignment.value()); 2443 else 2444 OutStreamer->emitCommonSymbol(GVSym, Size, Alignment.value()); 2445 return; 2446 } 2447 2448 MCSymbol *EmittedInitSym = GVSym; 2449 2450 // Emit linkage for the global variable and its aliases. 2451 emitLinkage(GV, EmittedInitSym); 2452 for (const GlobalAlias *GA : GOAliasMap[GV]) 2453 emitLinkage(GA, getSymbol(GA)); 2454 2455 emitAlignment(getGVAlignment(GV, DL), GV); 2456 2457 // When -fdata-sections is enabled, every GlobalVariable will 2458 // be put into its own csect; therefore, label is not necessary here. 2459 if (!TM.getDataSections() || GV->hasSection()) 2460 OutStreamer->emitLabel(EmittedInitSym); 2461 2462 // No alias to emit. 2463 if (!GOAliasMap[GV].size()) { 2464 emitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer()); 2465 return; 2466 } 2467 2468 // Aliases with the same offset should be aligned. Record the list of aliases 2469 // associated with the offset. 2470 AliasMapTy AliasList; 2471 for (const GlobalAlias *GA : GOAliasMap[GV]) 2472 AliasList[getAliasOffset(GA->getAliasee())].push_back(GA); 2473 2474 // Emit alias label and element value for global variable. 2475 emitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer(), 2476 &AliasList); 2477 } 2478 2479 void PPCAIXAsmPrinter::emitFunctionDescriptor() { 2480 const DataLayout &DL = getDataLayout(); 2481 const unsigned PointerSize = DL.getPointerSizeInBits() == 64 ? 8 : 4; 2482 2483 MCSectionSubPair Current = OutStreamer->getCurrentSection(); 2484 // Emit function descriptor. 2485 OutStreamer->switchSection( 2486 cast<MCSymbolXCOFF>(CurrentFnDescSym)->getRepresentedCsect()); 2487 2488 // Emit aliasing label for function descriptor csect. 2489 for (const GlobalAlias *Alias : GOAliasMap[&MF->getFunction()]) 2490 OutStreamer->emitLabel(getSymbol(Alias)); 2491 2492 // Emit function entry point address. 2493 OutStreamer->emitValue(MCSymbolRefExpr::create(CurrentFnSym, OutContext), 2494 PointerSize); 2495 // Emit TOC base address. 2496 const MCSymbol *TOCBaseSym = 2497 cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection()) 2498 ->getQualNameSymbol(); 2499 OutStreamer->emitValue(MCSymbolRefExpr::create(TOCBaseSym, OutContext), 2500 PointerSize); 2501 // Emit a null environment pointer. 2502 OutStreamer->emitIntValue(0, PointerSize); 2503 2504 OutStreamer->switchSection(Current.first, Current.second); 2505 } 2506 2507 void PPCAIXAsmPrinter::emitFunctionEntryLabel() { 2508 // It's not necessary to emit the label when we have individual 2509 // function in its own csect. 2510 if (!TM.getFunctionSections()) 2511 PPCAsmPrinter::emitFunctionEntryLabel(); 2512 2513 // Emit aliasing label for function entry point label. 2514 for (const GlobalAlias *Alias : GOAliasMap[&MF->getFunction()]) 2515 OutStreamer->emitLabel( 2516 getObjFileLowering().getFunctionEntryPointSymbol(Alias, TM)); 2517 } 2518 2519 void PPCAIXAsmPrinter::emitPGORefs() { 2520 if (OutContext.hasXCOFFSection( 2521 "__llvm_prf_cnts", 2522 XCOFF::CsectProperties(XCOFF::XMC_RW, XCOFF::XTY_SD))) { 2523 MCSection *CntsSection = OutContext.getXCOFFSection( 2524 "__llvm_prf_cnts", SectionKind::getData(), 2525 XCOFF::CsectProperties(XCOFF::XMC_RW, XCOFF::XTY_SD), 2526 /*MultiSymbolsAllowed*/ true); 2527 2528 OutStreamer->switchSection(CntsSection); 2529 if (OutContext.hasXCOFFSection( 2530 "__llvm_prf_data", 2531 XCOFF::CsectProperties(XCOFF::XMC_RW, XCOFF::XTY_SD))) 2532 OutStreamer->emitXCOFFRefDirective("__llvm_prf_data[RW]"); 2533 if (OutContext.hasXCOFFSection( 2534 "__llvm_prf_names", 2535 XCOFF::CsectProperties(XCOFF::XMC_RO, XCOFF::XTY_SD))) 2536 OutStreamer->emitXCOFFRefDirective("__llvm_prf_names[RO]"); 2537 if (OutContext.hasXCOFFSection( 2538 "__llvm_prf_vnds", 2539 XCOFF::CsectProperties(XCOFF::XMC_RW, XCOFF::XTY_SD))) 2540 OutStreamer->emitXCOFFRefDirective("__llvm_prf_vnds[RW]"); 2541 } 2542 } 2543 2544 void PPCAIXAsmPrinter::emitEndOfAsmFile(Module &M) { 2545 // If there are no functions and there are no toc-data definitions in this 2546 // module, we will never need to reference the TOC base. 2547 if (M.empty() && TOCDataGlobalVars.empty()) 2548 return; 2549 2550 emitPGORefs(); 2551 2552 // Switch to section to emit TOC base. 2553 OutStreamer->switchSection(getObjFileLowering().getTOCBaseSection()); 2554 2555 PPCTargetStreamer *TS = 2556 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer()); 2557 2558 for (auto &I : TOC) { 2559 MCSectionXCOFF *TCEntry; 2560 // Setup the csect for the current TC entry. If the variant kind is 2561 // VK_PPC_AIX_TLSGDM the entry represents the region handle, we create a 2562 // new symbol to prefix the name with a dot. 2563 if (I.first.second == MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSGDM) { 2564 SmallString<128> Name; 2565 StringRef Prefix = "."; 2566 Name += Prefix; 2567 Name += I.first.first->getName(); 2568 MCSymbol *S = OutContext.getOrCreateSymbol(Name); 2569 TCEntry = cast<MCSectionXCOFF>( 2570 getObjFileLowering().getSectionForTOCEntry(S, TM)); 2571 } else { 2572 TCEntry = cast<MCSectionXCOFF>( 2573 getObjFileLowering().getSectionForTOCEntry(I.first.first, TM)); 2574 } 2575 OutStreamer->switchSection(TCEntry); 2576 2577 OutStreamer->emitLabel(I.second); 2578 if (TS != nullptr) 2579 TS->emitTCEntry(*I.first.first, I.first.second); 2580 } 2581 2582 for (const auto *GV : TOCDataGlobalVars) 2583 emitGlobalVariableHelper(GV); 2584 } 2585 2586 bool PPCAIXAsmPrinter::doInitialization(Module &M) { 2587 const bool Result = PPCAsmPrinter::doInitialization(M); 2588 2589 auto setCsectAlignment = [this](const GlobalObject *GO) { 2590 // Declarations have 0 alignment which is set by default. 2591 if (GO->isDeclarationForLinker()) 2592 return; 2593 2594 SectionKind GOKind = getObjFileLowering().getKindForGlobal(GO, TM); 2595 MCSectionXCOFF *Csect = cast<MCSectionXCOFF>( 2596 getObjFileLowering().SectionForGlobal(GO, GOKind, TM)); 2597 2598 Align GOAlign = getGVAlignment(GO, GO->getParent()->getDataLayout()); 2599 if (GOAlign > Csect->getAlignment()) 2600 Csect->setAlignment(GOAlign); 2601 }; 2602 2603 // We need to know, up front, the alignment of csects for the assembly path, 2604 // because once a .csect directive gets emitted, we could not change the 2605 // alignment value on it. 2606 for (const auto &G : M.globals()) { 2607 if (isSpecialLLVMGlobalArrayToSkip(&G)) 2608 continue; 2609 2610 if (isSpecialLLVMGlobalArrayForStaticInit(&G)) { 2611 // Generate a format indicator and a unique module id to be a part of 2612 // the sinit and sterm function names. 2613 if (FormatIndicatorAndUniqueModId.empty()) { 2614 std::string UniqueModuleId = getUniqueModuleId(&M); 2615 if (UniqueModuleId != "") 2616 // TODO: Use source file full path to generate the unique module id 2617 // and add a format indicator as a part of function name in case we 2618 // will support more than one format. 2619 FormatIndicatorAndUniqueModId = "clang_" + UniqueModuleId.substr(1); 2620 else 2621 // Use the Pid and current time as the unique module id when we cannot 2622 // generate one based on a module's strong external symbols. 2623 // FIXME: Adjust the comment accordingly after we use source file full 2624 // path instead. 2625 FormatIndicatorAndUniqueModId = 2626 "clangPidTime_" + llvm::itostr(sys::Process::getProcessId()) + 2627 "_" + llvm::itostr(time(nullptr)); 2628 } 2629 2630 emitSpecialLLVMGlobal(&G); 2631 continue; 2632 } 2633 2634 setCsectAlignment(&G); 2635 } 2636 2637 for (const auto &F : M) 2638 setCsectAlignment(&F); 2639 2640 // Construct an aliasing list for each GlobalObject. 2641 for (const auto &Alias : M.aliases()) { 2642 const GlobalObject *Base = Alias.getAliaseeObject(); 2643 if (!Base) 2644 report_fatal_error( 2645 "alias without a base object is not yet supported on AIX"); 2646 GOAliasMap[Base].push_back(&Alias); 2647 } 2648 2649 return Result; 2650 } 2651 2652 void PPCAIXAsmPrinter::emitInstruction(const MachineInstr *MI) { 2653 switch (MI->getOpcode()) { 2654 default: 2655 break; 2656 case PPC::GETtlsADDR64AIX: 2657 case PPC::GETtlsADDR32AIX: { 2658 // The reference to .__tls_get_addr is unknown to the assembler 2659 // so we need to emit an external symbol reference. 2660 MCSymbol *TlsGetAddr = createMCSymbolForTlsGetAddr(OutContext); 2661 ExtSymSDNodeSymbols.insert(TlsGetAddr); 2662 break; 2663 } 2664 case PPC::BL8: 2665 case PPC::BL: 2666 case PPC::BL8_NOP: 2667 case PPC::BL_NOP: { 2668 const MachineOperand &MO = MI->getOperand(0); 2669 if (MO.isSymbol()) { 2670 MCSymbolXCOFF *S = 2671 cast<MCSymbolXCOFF>(OutContext.getOrCreateSymbol(MO.getSymbolName())); 2672 ExtSymSDNodeSymbols.insert(S); 2673 } 2674 } break; 2675 case PPC::BL_TLS: 2676 case PPC::BL8_TLS: 2677 case PPC::BL8_TLS_: 2678 case PPC::BL8_NOP_TLS: 2679 report_fatal_error("TLS call not yet implemented"); 2680 case PPC::TAILB: 2681 case PPC::TAILB8: 2682 case PPC::TAILBA: 2683 case PPC::TAILBA8: 2684 case PPC::TAILBCTR: 2685 case PPC::TAILBCTR8: 2686 if (MI->getOperand(0).isSymbol()) 2687 report_fatal_error("Tail call for extern symbol not yet supported."); 2688 break; 2689 case PPC::DST: 2690 case PPC::DST64: 2691 case PPC::DSTT: 2692 case PPC::DSTT64: 2693 case PPC::DSTST: 2694 case PPC::DSTST64: 2695 case PPC::DSTSTT: 2696 case PPC::DSTSTT64: 2697 EmitToStreamer( 2698 *OutStreamer, 2699 MCInstBuilder(PPC::ORI).addReg(PPC::R0).addReg(PPC::R0).addImm(0)); 2700 return; 2701 } 2702 return PPCAsmPrinter::emitInstruction(MI); 2703 } 2704 2705 bool PPCAIXAsmPrinter::doFinalization(Module &M) { 2706 // Do streamer related finalization for DWARF. 2707 if (!MAI->usesDwarfFileAndLocDirectives() && MMI->hasDebugInfo()) 2708 OutStreamer->doFinalizationAtSectionEnd( 2709 OutStreamer->getContext().getObjectFileInfo()->getTextSection()); 2710 2711 for (MCSymbol *Sym : ExtSymSDNodeSymbols) 2712 OutStreamer->emitSymbolAttribute(Sym, MCSA_Extern); 2713 return PPCAsmPrinter::doFinalization(M); 2714 } 2715 2716 static unsigned mapToSinitPriority(int P) { 2717 if (P < 0 || P > 65535) 2718 report_fatal_error("invalid init priority"); 2719 2720 if (P <= 20) 2721 return P; 2722 2723 if (P < 81) 2724 return 20 + (P - 20) * 16; 2725 2726 if (P <= 1124) 2727 return 1004 + (P - 81); 2728 2729 if (P < 64512) 2730 return 2047 + (P - 1124) * 33878; 2731 2732 return 2147482625u + (P - 64512); 2733 } 2734 2735 static std::string convertToSinitPriority(int Priority) { 2736 // This helper function converts clang init priority to values used in sinit 2737 // and sterm functions. 2738 // 2739 // The conversion strategies are: 2740 // We map the reserved clang/gnu priority range [0, 100] into the sinit/sterm 2741 // reserved priority range [0, 1023] by 2742 // - directly mapping the first 21 and the last 20 elements of the ranges 2743 // - linear interpolating the intermediate values with a step size of 16. 2744 // 2745 // We map the non reserved clang/gnu priority range of [101, 65535] into the 2746 // sinit/sterm priority range [1024, 2147483648] by: 2747 // - directly mapping the first and the last 1024 elements of the ranges 2748 // - linear interpolating the intermediate values with a step size of 33878. 2749 unsigned int P = mapToSinitPriority(Priority); 2750 2751 std::string PrioritySuffix; 2752 llvm::raw_string_ostream os(PrioritySuffix); 2753 os << llvm::format_hex_no_prefix(P, 8); 2754 os.flush(); 2755 return PrioritySuffix; 2756 } 2757 2758 void PPCAIXAsmPrinter::emitXXStructorList(const DataLayout &DL, 2759 const Constant *List, bool IsCtor) { 2760 SmallVector<Structor, 8> Structors; 2761 preprocessXXStructorList(DL, List, Structors); 2762 if (Structors.empty()) 2763 return; 2764 2765 unsigned Index = 0; 2766 for (Structor &S : Structors) { 2767 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(S.Func)) 2768 S.Func = CE->getOperand(0); 2769 2770 llvm::GlobalAlias::create( 2771 GlobalValue::ExternalLinkage, 2772 (IsCtor ? llvm::Twine("__sinit") : llvm::Twine("__sterm")) + 2773 llvm::Twine(convertToSinitPriority(S.Priority)) + 2774 llvm::Twine("_", FormatIndicatorAndUniqueModId) + 2775 llvm::Twine("_", llvm::utostr(Index++)), 2776 cast<Function>(S.Func)); 2777 } 2778 } 2779 2780 void PPCAIXAsmPrinter::emitTTypeReference(const GlobalValue *GV, 2781 unsigned Encoding) { 2782 if (GV) { 2783 MCSymbol *TypeInfoSym = TM.getSymbol(GV); 2784 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(TypeInfoSym); 2785 const MCSymbol *TOCBaseSym = 2786 cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection()) 2787 ->getQualNameSymbol(); 2788 auto &Ctx = OutStreamer->getContext(); 2789 const MCExpr *Exp = 2790 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCEntry, Ctx), 2791 MCSymbolRefExpr::create(TOCBaseSym, Ctx), Ctx); 2792 OutStreamer->emitValue(Exp, GetSizeOfEncodedValue(Encoding)); 2793 } else 2794 OutStreamer->emitIntValue(0, GetSizeOfEncodedValue(Encoding)); 2795 } 2796 2797 // Return a pass that prints the PPC assembly code for a MachineFunction to the 2798 // given output stream. 2799 static AsmPrinter * 2800 createPPCAsmPrinterPass(TargetMachine &tm, 2801 std::unique_ptr<MCStreamer> &&Streamer) { 2802 if (tm.getTargetTriple().isOSAIX()) 2803 return new PPCAIXAsmPrinter(tm, std::move(Streamer)); 2804 2805 return new PPCLinuxAsmPrinter(tm, std::move(Streamer)); 2806 } 2807 2808 // Force static initialization. 2809 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializePowerPCAsmPrinter() { 2810 TargetRegistry::RegisterAsmPrinter(getThePPC32Target(), 2811 createPPCAsmPrinterPass); 2812 TargetRegistry::RegisterAsmPrinter(getThePPC32LETarget(), 2813 createPPCAsmPrinterPass); 2814 TargetRegistry::RegisterAsmPrinter(getThePPC64Target(), 2815 createPPCAsmPrinterPass); 2816 TargetRegistry::RegisterAsmPrinter(getThePPC64LETarget(), 2817 createPPCAsmPrinterPass); 2818 } 2819