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/BinaryFormat/MachO.h" 36 #include "llvm/CodeGen/AsmPrinter.h" 37 #include "llvm/CodeGen/MachineBasicBlock.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/MCSectionMachO.h" 57 #include "llvm/MC/MCSectionXCOFF.h" 58 #include "llvm/MC/MCStreamer.h" 59 #include "llvm/MC/MCSymbol.h" 60 #include "llvm/MC/MCSymbolELF.h" 61 #include "llvm/MC/MCSymbolXCOFF.h" 62 #include "llvm/MC/SectionKind.h" 63 #include "llvm/Support/Casting.h" 64 #include "llvm/Support/CodeGen.h" 65 #include "llvm/Support/Debug.h" 66 #include "llvm/Support/ErrorHandling.h" 67 #include "llvm/Support/Process.h" 68 #include "llvm/Support/TargetRegistry.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 80 #define DEBUG_TYPE "asmprinter" 81 82 namespace { 83 84 class PPCAsmPrinter : public AsmPrinter { 85 protected: 86 MapVector<const MCSymbol *, MCSymbol *> TOC; 87 const PPCSubtarget *Subtarget = nullptr; 88 StackMaps SM; 89 90 public: 91 explicit PPCAsmPrinter(TargetMachine &TM, 92 std::unique_ptr<MCStreamer> Streamer) 93 : AsmPrinter(TM, std::move(Streamer)), SM(*this) {} 94 95 StringRef getPassName() const override { return "PowerPC Assembly Printer"; } 96 97 MCSymbol *lookUpOrCreateTOCEntry(const MCSymbol *Sym); 98 99 bool doInitialization(Module &M) override { 100 if (!TOC.empty()) 101 TOC.clear(); 102 return AsmPrinter::doInitialization(M); 103 } 104 105 void emitInstruction(const MachineInstr *MI) override; 106 107 /// This function is for PrintAsmOperand and PrintAsmMemoryOperand, 108 /// invoked by EmitMSInlineAsmStr and EmitGCCInlineAsmStr only. 109 /// The \p MI would be INLINEASM ONLY. 110 void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O); 111 112 void PrintSymbolOperand(const MachineOperand &MO, raw_ostream &O) override; 113 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 114 const char *ExtraCode, raw_ostream &O) override; 115 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, 116 const char *ExtraCode, raw_ostream &O) override; 117 118 void emitEndOfAsmFile(Module &M) override; 119 120 void LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI); 121 void LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI); 122 void EmitTlsCall(const MachineInstr *MI, MCSymbolRefExpr::VariantKind VK); 123 bool runOnMachineFunction(MachineFunction &MF) override { 124 Subtarget = &MF.getSubtarget<PPCSubtarget>(); 125 bool Changed = AsmPrinter::runOnMachineFunction(MF); 126 emitXRayTable(); 127 return Changed; 128 } 129 }; 130 131 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux 132 class PPCLinuxAsmPrinter : public PPCAsmPrinter { 133 public: 134 explicit PPCLinuxAsmPrinter(TargetMachine &TM, 135 std::unique_ptr<MCStreamer> Streamer) 136 : PPCAsmPrinter(TM, std::move(Streamer)) {} 137 138 StringRef getPassName() const override { 139 return "Linux PPC Assembly Printer"; 140 } 141 142 void emitStartOfAsmFile(Module &M) override; 143 void emitEndOfAsmFile(Module &) override; 144 145 void emitFunctionEntryLabel() override; 146 147 void emitFunctionBodyStart() override; 148 void emitFunctionBodyEnd() override; 149 void emitInstruction(const MachineInstr *MI) override; 150 }; 151 152 class PPCAIXAsmPrinter : public PPCAsmPrinter { 153 private: 154 /// Symbols lowered from ExternalSymbolSDNodes, we will need to emit extern 155 /// linkage for them in AIX. 156 SmallPtrSet<MCSymbol *, 8> ExtSymSDNodeSymbols; 157 158 /// A format indicator and unique trailing identifier to form part of the 159 /// sinit/sterm function names. 160 std::string FormatIndicatorAndUniqueModId; 161 162 static void ValidateGV(const GlobalVariable *GV); 163 // Record a list of GlobalAlias associated with a GlobalObject. 164 // This is used for AIX's extra-label-at-definition aliasing strategy. 165 DenseMap<const GlobalObject *, SmallVector<const GlobalAlias *, 1>> 166 GOAliasMap; 167 168 public: 169 PPCAIXAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer) 170 : PPCAsmPrinter(TM, std::move(Streamer)) { 171 if (MAI->isLittleEndian()) 172 report_fatal_error( 173 "cannot create AIX PPC Assembly Printer for a little-endian target"); 174 } 175 176 StringRef getPassName() const override { return "AIX PPC Assembly Printer"; } 177 178 bool doInitialization(Module &M) override; 179 180 void emitXXStructorList(const DataLayout &DL, const Constant *List, 181 bool IsCtor) override; 182 183 void SetupMachineFunction(MachineFunction &MF) override; 184 185 void emitGlobalVariable(const GlobalVariable *GV) override; 186 187 void emitFunctionDescriptor() override; 188 189 void emitFunctionEntryLabel() override; 190 191 void emitEndOfAsmFile(Module &) override; 192 193 void emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const override; 194 195 void emitInstruction(const MachineInstr *MI) override; 196 197 bool doFinalization(Module &M) override; 198 }; 199 200 } // end anonymous namespace 201 202 void PPCAsmPrinter::PrintSymbolOperand(const MachineOperand &MO, 203 raw_ostream &O) { 204 // Computing the address of a global symbol, not calling it. 205 const GlobalValue *GV = MO.getGlobal(); 206 getSymbol(GV)->print(O, MAI); 207 printOffset(MO.getOffset(), O); 208 } 209 210 void PPCAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo, 211 raw_ostream &O) { 212 const DataLayout &DL = getDataLayout(); 213 const MachineOperand &MO = MI->getOperand(OpNo); 214 215 switch (MO.getType()) { 216 case MachineOperand::MO_Register: { 217 // The MI is INLINEASM ONLY and UseVSXReg is always false. 218 const char *RegName = PPCInstPrinter::getRegisterName(MO.getReg()); 219 220 // Linux assembler (Others?) does not take register mnemonics. 221 // FIXME - What about special registers used in mfspr/mtspr? 222 O << PPCRegisterInfo::stripRegisterPrefix(RegName); 223 return; 224 } 225 case MachineOperand::MO_Immediate: 226 O << MO.getImm(); 227 return; 228 229 case MachineOperand::MO_MachineBasicBlock: 230 MO.getMBB()->getSymbol()->print(O, MAI); 231 return; 232 case MachineOperand::MO_ConstantPoolIndex: 233 O << DL.getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_' 234 << MO.getIndex(); 235 return; 236 case MachineOperand::MO_BlockAddress: 237 GetBlockAddressSymbol(MO.getBlockAddress())->print(O, MAI); 238 return; 239 case MachineOperand::MO_GlobalAddress: { 240 PrintSymbolOperand(MO, O); 241 return; 242 } 243 244 default: 245 O << "<unknown operand type: " << (unsigned)MO.getType() << ">"; 246 return; 247 } 248 } 249 250 /// PrintAsmOperand - Print out an operand for an inline asm expression. 251 /// 252 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 253 const char *ExtraCode, raw_ostream &O) { 254 // Does this asm operand have a single letter operand modifier? 255 if (ExtraCode && ExtraCode[0]) { 256 if (ExtraCode[1] != 0) return true; // Unknown modifier. 257 258 switch (ExtraCode[0]) { 259 default: 260 // See if this is a generic print operand 261 return AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, O); 262 case 'L': // Write second word of DImode reference. 263 // Verify that this operand has two consecutive registers. 264 if (!MI->getOperand(OpNo).isReg() || 265 OpNo+1 == MI->getNumOperands() || 266 !MI->getOperand(OpNo+1).isReg()) 267 return true; 268 ++OpNo; // Return the high-part. 269 break; 270 case 'I': 271 // Write 'i' if an integer constant, otherwise nothing. Used to print 272 // addi vs add, etc. 273 if (MI->getOperand(OpNo).isImm()) 274 O << "i"; 275 return false; 276 case 'x': 277 if(!MI->getOperand(OpNo).isReg()) 278 return true; 279 // This operand uses VSX numbering. 280 // If the operand is a VMX register, convert it to a VSX register. 281 Register Reg = MI->getOperand(OpNo).getReg(); 282 if (PPCInstrInfo::isVRRegister(Reg)) 283 Reg = PPC::VSX32 + (Reg - PPC::V0); 284 else if (PPCInstrInfo::isVFRegister(Reg)) 285 Reg = PPC::VSX32 + (Reg - PPC::VF0); 286 const char *RegName; 287 RegName = PPCInstPrinter::getRegisterName(Reg); 288 RegName = PPCRegisterInfo::stripRegisterPrefix(RegName); 289 O << RegName; 290 return false; 291 } 292 } 293 294 printOperand(MI, OpNo, O); 295 return false; 296 } 297 298 // At the moment, all inline asm memory operands are a single register. 299 // In any case, the output of this routine should always be just one 300 // assembler operand. 301 302 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, 303 const char *ExtraCode, 304 raw_ostream &O) { 305 if (ExtraCode && ExtraCode[0]) { 306 if (ExtraCode[1] != 0) return true; // Unknown modifier. 307 308 switch (ExtraCode[0]) { 309 default: return true; // Unknown modifier. 310 case 'L': // A memory reference to the upper word of a double word op. 311 O << getDataLayout().getPointerSize() << "("; 312 printOperand(MI, OpNo, O); 313 O << ")"; 314 return false; 315 case 'y': // A memory reference for an X-form instruction 316 O << "0, "; 317 printOperand(MI, OpNo, O); 318 return false; 319 case 'U': // Print 'u' for update form. 320 case 'X': // Print 'x' for indexed form. 321 // FIXME: Currently for PowerPC memory operands are always loaded 322 // into a register, so we never get an update or indexed form. 323 // This is bad even for offset forms, since even if we know we 324 // have a value in -16(r1), we will generate a load into r<n> 325 // and then load from 0(r<n>). Until that issue is fixed, 326 // tolerate 'U' and 'X' but don't output anything. 327 assert(MI->getOperand(OpNo).isReg()); 328 return false; 329 } 330 } 331 332 assert(MI->getOperand(OpNo).isReg()); 333 O << "0("; 334 printOperand(MI, OpNo, O); 335 O << ")"; 336 return false; 337 } 338 339 /// lookUpOrCreateTOCEntry -- Given a symbol, look up whether a TOC entry 340 /// exists for it. If not, create one. Then return a symbol that references 341 /// the TOC entry. 342 MCSymbol *PPCAsmPrinter::lookUpOrCreateTOCEntry(const MCSymbol *Sym) { 343 MCSymbol *&TOCEntry = TOC[Sym]; 344 if (!TOCEntry) 345 TOCEntry = createTempSymbol("C"); 346 return TOCEntry; 347 } 348 349 void PPCAsmPrinter::emitEndOfAsmFile(Module &M) { 350 emitStackMaps(SM); 351 } 352 353 void PPCAsmPrinter::LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI) { 354 unsigned NumNOPBytes = MI.getOperand(1).getImm(); 355 356 auto &Ctx = OutStreamer->getContext(); 357 MCSymbol *MILabel = Ctx.createTempSymbol(); 358 OutStreamer->emitLabel(MILabel); 359 360 SM.recordStackMap(*MILabel, MI); 361 assert(NumNOPBytes % 4 == 0 && "Invalid number of NOP bytes requested!"); 362 363 // Scan ahead to trim the shadow. 364 const MachineBasicBlock &MBB = *MI.getParent(); 365 MachineBasicBlock::const_iterator MII(MI); 366 ++MII; 367 while (NumNOPBytes > 0) { 368 if (MII == MBB.end() || MII->isCall() || 369 MII->getOpcode() == PPC::DBG_VALUE || 370 MII->getOpcode() == TargetOpcode::PATCHPOINT || 371 MII->getOpcode() == TargetOpcode::STACKMAP) 372 break; 373 ++MII; 374 NumNOPBytes -= 4; 375 } 376 377 // Emit nops. 378 for (unsigned i = 0; i < NumNOPBytes; i += 4) 379 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP)); 380 } 381 382 // Lower a patchpoint of the form: 383 // [<def>], <id>, <numBytes>, <target>, <numArgs> 384 void PPCAsmPrinter::LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI) { 385 auto &Ctx = OutStreamer->getContext(); 386 MCSymbol *MILabel = Ctx.createTempSymbol(); 387 OutStreamer->emitLabel(MILabel); 388 389 SM.recordPatchPoint(*MILabel, MI); 390 PatchPointOpers Opers(&MI); 391 392 unsigned EncodedBytes = 0; 393 const MachineOperand &CalleeMO = Opers.getCallTarget(); 394 395 if (CalleeMO.isImm()) { 396 int64_t CallTarget = CalleeMO.getImm(); 397 if (CallTarget) { 398 assert((CallTarget & 0xFFFFFFFFFFFF) == CallTarget && 399 "High 16 bits of call target should be zero."); 400 Register ScratchReg = MI.getOperand(Opers.getNextScratchIdx()).getReg(); 401 EncodedBytes = 0; 402 // Materialize the jump address: 403 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI8) 404 .addReg(ScratchReg) 405 .addImm((CallTarget >> 32) & 0xFFFF)); 406 ++EncodedBytes; 407 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::RLDIC) 408 .addReg(ScratchReg) 409 .addReg(ScratchReg) 410 .addImm(32).addImm(16)); 411 ++EncodedBytes; 412 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORIS8) 413 .addReg(ScratchReg) 414 .addReg(ScratchReg) 415 .addImm((CallTarget >> 16) & 0xFFFF)); 416 ++EncodedBytes; 417 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORI8) 418 .addReg(ScratchReg) 419 .addReg(ScratchReg) 420 .addImm(CallTarget & 0xFFFF)); 421 422 // Save the current TOC pointer before the remote call. 423 int TOCSaveOffset = Subtarget->getFrameLowering()->getTOCSaveOffset(); 424 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::STD) 425 .addReg(PPC::X2) 426 .addImm(TOCSaveOffset) 427 .addReg(PPC::X1)); 428 ++EncodedBytes; 429 430 // If we're on ELFv1, then we need to load the actual function pointer 431 // from the function descriptor. 432 if (!Subtarget->isELFv2ABI()) { 433 // Load the new TOC pointer and the function address, but not r11 434 // (needing this is rare, and loading it here would prevent passing it 435 // via a 'nest' parameter. 436 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD) 437 .addReg(PPC::X2) 438 .addImm(8) 439 .addReg(ScratchReg)); 440 ++EncodedBytes; 441 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD) 442 .addReg(ScratchReg) 443 .addImm(0) 444 .addReg(ScratchReg)); 445 ++EncodedBytes; 446 } 447 448 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTCTR8) 449 .addReg(ScratchReg)); 450 ++EncodedBytes; 451 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BCTRL8)); 452 ++EncodedBytes; 453 454 // Restore the TOC pointer after the call. 455 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD) 456 .addReg(PPC::X2) 457 .addImm(TOCSaveOffset) 458 .addReg(PPC::X1)); 459 ++EncodedBytes; 460 } 461 } else if (CalleeMO.isGlobal()) { 462 const GlobalValue *GValue = CalleeMO.getGlobal(); 463 MCSymbol *MOSymbol = getSymbol(GValue); 464 const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, OutContext); 465 466 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL8_NOP) 467 .addExpr(SymVar)); 468 EncodedBytes += 2; 469 } 470 471 // Each instruction is 4 bytes. 472 EncodedBytes *= 4; 473 474 // Emit padding. 475 unsigned NumBytes = Opers.getNumPatchBytes(); 476 assert(NumBytes >= EncodedBytes && 477 "Patchpoint can't request size less than the length of a call."); 478 assert((NumBytes - EncodedBytes) % 4 == 0 && 479 "Invalid number of NOP bytes requested!"); 480 for (unsigned i = EncodedBytes; i < NumBytes; i += 4) 481 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP)); 482 } 483 484 /// EmitTlsCall -- Given a GETtls[ld]ADDR[32] instruction, print a 485 /// call to __tls_get_addr to the current output stream. 486 void PPCAsmPrinter::EmitTlsCall(const MachineInstr *MI, 487 MCSymbolRefExpr::VariantKind VK) { 488 StringRef Name = "__tls_get_addr"; 489 MCSymbol *TlsGetAddr = OutContext.getOrCreateSymbol(Name); 490 MCSymbolRefExpr::VariantKind Kind = MCSymbolRefExpr::VK_None; 491 unsigned Opcode = PPC::BL8_NOP_TLS; 492 493 assert(MI->getNumOperands() >= 3 && "Expecting at least 3 operands from MI"); 494 if (MI->getOperand(2).getTargetFlags() == PPCII::MO_GOT_TLSGD_PCREL_FLAG || 495 MI->getOperand(2).getTargetFlags() == PPCII::MO_GOT_TLSLD_PCREL_FLAG) { 496 Kind = MCSymbolRefExpr::VK_PPC_NOTOC; 497 Opcode = PPC::BL8_NOTOC_TLS; 498 } 499 const Module *M = MF->getFunction().getParent(); 500 501 assert(MI->getOperand(0).isReg() && 502 ((Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::X3) || 503 (!Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::R3)) && 504 "GETtls[ld]ADDR[32] must define GPR3"); 505 assert(MI->getOperand(1).isReg() && 506 ((Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::X3) || 507 (!Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::R3)) && 508 "GETtls[ld]ADDR[32] must read GPR3"); 509 510 if (Subtarget->is32BitELFABI() && isPositionIndependent()) 511 Kind = MCSymbolRefExpr::VK_PLT; 512 513 const MCExpr *TlsRef = 514 MCSymbolRefExpr::create(TlsGetAddr, Kind, OutContext); 515 516 // Add 32768 offset to the symbol so we follow up the latest GOT/PLT ABI. 517 if (Kind == MCSymbolRefExpr::VK_PLT && Subtarget->isSecurePlt() && 518 M->getPICLevel() == PICLevel::BigPIC) 519 TlsRef = MCBinaryExpr::createAdd( 520 TlsRef, MCConstantExpr::create(32768, OutContext), OutContext); 521 const MachineOperand &MO = MI->getOperand(2); 522 const GlobalValue *GValue = MO.getGlobal(); 523 MCSymbol *MOSymbol = getSymbol(GValue); 524 const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, VK, OutContext); 525 EmitToStreamer(*OutStreamer, 526 MCInstBuilder(Subtarget->isPPC64() ? Opcode 527 : (unsigned)PPC::BL_TLS) 528 .addExpr(TlsRef) 529 .addExpr(SymVar)); 530 } 531 532 /// Map a machine operand for a TOC pseudo-machine instruction to its 533 /// corresponding MCSymbol. 534 static MCSymbol *getMCSymbolForTOCPseudoMO(const MachineOperand &MO, 535 AsmPrinter &AP) { 536 switch (MO.getType()) { 537 case MachineOperand::MO_GlobalAddress: 538 return AP.getSymbol(MO.getGlobal()); 539 case MachineOperand::MO_ConstantPoolIndex: 540 return AP.GetCPISymbol(MO.getIndex()); 541 case MachineOperand::MO_JumpTableIndex: 542 return AP.GetJTISymbol(MO.getIndex()); 543 case MachineOperand::MO_BlockAddress: 544 return AP.GetBlockAddressSymbol(MO.getBlockAddress()); 545 default: 546 llvm_unreachable("Unexpected operand type to get symbol."); 547 } 548 } 549 550 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to 551 /// the current output stream. 552 /// 553 void PPCAsmPrinter::emitInstruction(const MachineInstr *MI) { 554 MCInst TmpInst; 555 const bool IsPPC64 = Subtarget->isPPC64(); 556 const bool IsAIX = Subtarget->isAIXABI(); 557 const Module *M = MF->getFunction().getParent(); 558 PICLevel::Level PL = M->getPICLevel(); 559 560 #ifndef NDEBUG 561 // Validate that SPE and FPU are mutually exclusive in codegen 562 if (!MI->isInlineAsm()) { 563 for (const MachineOperand &MO: MI->operands()) { 564 if (MO.isReg()) { 565 Register Reg = MO.getReg(); 566 if (Subtarget->hasSPE()) { 567 if (PPC::F4RCRegClass.contains(Reg) || 568 PPC::F8RCRegClass.contains(Reg) || 569 PPC::VFRCRegClass.contains(Reg) || 570 PPC::VRRCRegClass.contains(Reg) || 571 PPC::VSFRCRegClass.contains(Reg) || 572 PPC::VSSRCRegClass.contains(Reg) 573 ) 574 llvm_unreachable("SPE targets cannot have FPRegs!"); 575 } else { 576 if (PPC::SPERCRegClass.contains(Reg)) 577 llvm_unreachable("SPE register found in FPU-targeted code!"); 578 } 579 } 580 } 581 } 582 #endif 583 584 auto getTOCRelocAdjustedExprForXCOFF = [this](const MCExpr *Expr, 585 ptrdiff_t OriginalOffset) { 586 // Apply an offset to the TOC-based expression such that the adjusted 587 // notional offset from the TOC base (to be encoded into the instruction's D 588 // or DS field) is the signed 16-bit truncation of the original notional 589 // offset from the TOC base. 590 // This is consistent with the treatment used both by XL C/C++ and 591 // by AIX ld -r. 592 ptrdiff_t Adjustment = 593 OriginalOffset - llvm::SignExtend32<16>(OriginalOffset); 594 return MCBinaryExpr::createAdd( 595 Expr, MCConstantExpr::create(-Adjustment, OutContext), OutContext); 596 }; 597 598 auto getTOCEntryLoadingExprForXCOFF = 599 [IsPPC64, getTOCRelocAdjustedExprForXCOFF, 600 this](const MCSymbol *MOSymbol, const MCExpr *Expr) -> const MCExpr * { 601 const unsigned EntryByteSize = IsPPC64 ? 8 : 4; 602 const auto TOCEntryIter = TOC.find(MOSymbol); 603 assert(TOCEntryIter != TOC.end() && 604 "Could not find the TOC entry for this symbol."); 605 const ptrdiff_t EntryDistanceFromTOCBase = 606 (TOCEntryIter - TOC.begin()) * EntryByteSize; 607 constexpr int16_t PositiveTOCRange = INT16_MAX; 608 609 if (EntryDistanceFromTOCBase > PositiveTOCRange) 610 return getTOCRelocAdjustedExprForXCOFF(Expr, EntryDistanceFromTOCBase); 611 612 return Expr; 613 }; 614 615 // Lower multi-instruction pseudo operations. 616 switch (MI->getOpcode()) { 617 default: break; 618 case TargetOpcode::DBG_VALUE: 619 llvm_unreachable("Should be handled target independently"); 620 case TargetOpcode::STACKMAP: 621 return LowerSTACKMAP(SM, *MI); 622 case TargetOpcode::PATCHPOINT: 623 return LowerPATCHPOINT(SM, *MI); 624 625 case PPC::MoveGOTtoLR: { 626 // Transform %lr = MoveGOTtoLR 627 // Into this: bl _GLOBAL_OFFSET_TABLE_@local-4 628 // _GLOBAL_OFFSET_TABLE_@local-4 (instruction preceding 629 // _GLOBAL_OFFSET_TABLE_) has exactly one instruction: 630 // blrl 631 // This will return the pointer to _GLOBAL_OFFSET_TABLE_@local 632 MCSymbol *GOTSymbol = 633 OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_")); 634 const MCExpr *OffsExpr = 635 MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol, 636 MCSymbolRefExpr::VK_PPC_LOCAL, 637 OutContext), 638 MCConstantExpr::create(4, OutContext), 639 OutContext); 640 641 // Emit the 'bl'. 642 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL).addExpr(OffsExpr)); 643 return; 644 } 645 case PPC::MovePCtoLR: 646 case PPC::MovePCtoLR8: { 647 // Transform %lr = MovePCtoLR 648 // Into this, where the label is the PIC base: 649 // bl L1$pb 650 // L1$pb: 651 MCSymbol *PICBase = MF->getPICBaseSymbol(); 652 653 // Emit the 'bl'. 654 EmitToStreamer(*OutStreamer, 655 MCInstBuilder(PPC::BL) 656 // FIXME: We would like an efficient form for this, so we 657 // don't have to do a lot of extra uniquing. 658 .addExpr(MCSymbolRefExpr::create(PICBase, OutContext))); 659 660 // Emit the label. 661 OutStreamer->emitLabel(PICBase); 662 return; 663 } 664 case PPC::UpdateGBR: { 665 // Transform %rd = UpdateGBR(%rt, %ri) 666 // Into: lwz %rt, .L0$poff - .L0$pb(%ri) 667 // add %rd, %rt, %ri 668 // or into (if secure plt mode is on): 669 // addis r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@ha 670 // addi r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@l 671 // Get the offset from the GOT Base Register to the GOT 672 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 673 if (Subtarget->isSecurePlt() && isPositionIndependent() ) { 674 unsigned PICR = TmpInst.getOperand(0).getReg(); 675 MCSymbol *BaseSymbol = OutContext.getOrCreateSymbol( 676 M->getPICLevel() == PICLevel::SmallPIC ? "_GLOBAL_OFFSET_TABLE_" 677 : ".LTOC"); 678 const MCExpr *PB = 679 MCSymbolRefExpr::create(MF->getPICBaseSymbol(), OutContext); 680 681 const MCExpr *DeltaExpr = MCBinaryExpr::createSub( 682 MCSymbolRefExpr::create(BaseSymbol, OutContext), PB, OutContext); 683 684 const MCExpr *DeltaHi = PPCMCExpr::createHa(DeltaExpr, OutContext); 685 EmitToStreamer( 686 *OutStreamer, 687 MCInstBuilder(PPC::ADDIS).addReg(PICR).addReg(PICR).addExpr(DeltaHi)); 688 689 const MCExpr *DeltaLo = PPCMCExpr::createLo(DeltaExpr, OutContext); 690 EmitToStreamer( 691 *OutStreamer, 692 MCInstBuilder(PPC::ADDI).addReg(PICR).addReg(PICR).addExpr(DeltaLo)); 693 return; 694 } else { 695 MCSymbol *PICOffset = 696 MF->getInfo<PPCFunctionInfo>()->getPICOffsetSymbol(*MF); 697 TmpInst.setOpcode(PPC::LWZ); 698 const MCExpr *Exp = 699 MCSymbolRefExpr::create(PICOffset, MCSymbolRefExpr::VK_None, OutContext); 700 const MCExpr *PB = 701 MCSymbolRefExpr::create(MF->getPICBaseSymbol(), 702 MCSymbolRefExpr::VK_None, 703 OutContext); 704 const MCOperand TR = TmpInst.getOperand(1); 705 const MCOperand PICR = TmpInst.getOperand(0); 706 707 // Step 1: lwz %rt, .L$poff - .L$pb(%ri) 708 TmpInst.getOperand(1) = 709 MCOperand::createExpr(MCBinaryExpr::createSub(Exp, PB, OutContext)); 710 TmpInst.getOperand(0) = TR; 711 TmpInst.getOperand(2) = PICR; 712 EmitToStreamer(*OutStreamer, TmpInst); 713 714 TmpInst.setOpcode(PPC::ADD4); 715 TmpInst.getOperand(0) = PICR; 716 TmpInst.getOperand(1) = TR; 717 TmpInst.getOperand(2) = PICR; 718 EmitToStreamer(*OutStreamer, TmpInst); 719 return; 720 } 721 } 722 case PPC::LWZtoc: { 723 // Transform %rN = LWZtoc @op1, %r2 724 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 725 726 // Change the opcode to LWZ. 727 TmpInst.setOpcode(PPC::LWZ); 728 729 const MachineOperand &MO = MI->getOperand(1); 730 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) && 731 "Invalid operand for LWZtoc."); 732 733 // Map the operand to its corresponding MCSymbol. 734 const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this); 735 736 // Create a reference to the GOT entry for the symbol. The GOT entry will be 737 // synthesized later. 738 if (PL == PICLevel::SmallPIC && !IsAIX) { 739 const MCExpr *Exp = 740 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_GOT, 741 OutContext); 742 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 743 EmitToStreamer(*OutStreamer, TmpInst); 744 return; 745 } 746 747 // Otherwise, use the TOC. 'TOCEntry' is a label used to reference the 748 // storage allocated in the TOC which contains the address of 749 // 'MOSymbol'. Said TOC entry will be synthesized later. 750 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol); 751 const MCExpr *Exp = 752 MCSymbolRefExpr::create(TOCEntry, MCSymbolRefExpr::VK_None, OutContext); 753 754 // AIX uses the label directly as the lwz displacement operand for 755 // references into the toc section. The displacement value will be generated 756 // relative to the toc-base. 757 if (IsAIX) { 758 assert( 759 TM.getCodeModel() == CodeModel::Small && 760 "This pseudo should only be selected for 32-bit small code model."); 761 Exp = getTOCEntryLoadingExprForXCOFF(MOSymbol, Exp); 762 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 763 EmitToStreamer(*OutStreamer, TmpInst); 764 return; 765 } 766 767 // Create an explicit subtract expression between the local symbol and 768 // '.LTOC' to manifest the toc-relative offset. 769 const MCExpr *PB = MCSymbolRefExpr::create( 770 OutContext.getOrCreateSymbol(Twine(".LTOC")), OutContext); 771 Exp = MCBinaryExpr::createSub(Exp, PB, OutContext); 772 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 773 EmitToStreamer(*OutStreamer, TmpInst); 774 return; 775 } 776 case PPC::LDtocJTI: 777 case PPC::LDtocCPT: 778 case PPC::LDtocBA: 779 case PPC::LDtoc: { 780 // Transform %x3 = LDtoc @min1, %x2 781 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 782 783 // Change the opcode to LD. 784 TmpInst.setOpcode(PPC::LD); 785 786 const MachineOperand &MO = MI->getOperand(1); 787 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) && 788 "Invalid operand!"); 789 790 // Map the operand to its corresponding MCSymbol. 791 const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this); 792 793 // Map the machine operand to its corresponding MCSymbol, then map the 794 // global address operand to be a reference to the TOC entry we will 795 // synthesize later. 796 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol); 797 798 const MCSymbolRefExpr::VariantKind VK = 799 IsAIX ? MCSymbolRefExpr::VK_None : MCSymbolRefExpr::VK_PPC_TOC; 800 const MCExpr *Exp = 801 MCSymbolRefExpr::create(TOCEntry, VK, OutContext); 802 TmpInst.getOperand(1) = MCOperand::createExpr( 803 IsAIX ? getTOCEntryLoadingExprForXCOFF(MOSymbol, Exp) : Exp); 804 EmitToStreamer(*OutStreamer, TmpInst); 805 return; 806 } 807 case PPC::ADDIStocHA: { 808 assert((IsAIX && !IsPPC64 && TM.getCodeModel() == CodeModel::Large) && 809 "This pseudo should only be selected for 32-bit large code model on" 810 " AIX."); 811 812 // Transform %rd = ADDIStocHA %rA, @sym(%r2) 813 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 814 815 // Change the opcode to ADDIS. 816 TmpInst.setOpcode(PPC::ADDIS); 817 818 const MachineOperand &MO = MI->getOperand(2); 819 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) && 820 "Invalid operand for ADDIStocHA."); 821 822 // Map the machine operand to its corresponding MCSymbol. 823 MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this); 824 825 // Always use TOC on AIX. Map the global address operand to be a reference 826 // to the TOC entry we will synthesize later. 'TOCEntry' is a label used to 827 // reference the storage allocated in the TOC which contains the address of 828 // 'MOSymbol'. 829 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol); 830 const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry, 831 MCSymbolRefExpr::VK_PPC_U, 832 OutContext); 833 TmpInst.getOperand(2) = MCOperand::createExpr(Exp); 834 EmitToStreamer(*OutStreamer, TmpInst); 835 return; 836 } 837 case PPC::LWZtocL: { 838 assert(IsAIX && !IsPPC64 && TM.getCodeModel() == CodeModel::Large && 839 "This pseudo should only be selected for 32-bit large code model on" 840 " AIX."); 841 842 // Transform %rd = LWZtocL @sym, %rs. 843 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 844 845 // Change the opcode to lwz. 846 TmpInst.setOpcode(PPC::LWZ); 847 848 const MachineOperand &MO = MI->getOperand(1); 849 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) && 850 "Invalid operand for LWZtocL."); 851 852 // Map the machine operand to its corresponding MCSymbol. 853 MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this); 854 855 // Always use TOC on AIX. Map the global address operand to be a reference 856 // to the TOC entry we will synthesize later. 'TOCEntry' is a label used to 857 // reference the storage allocated in the TOC which contains the address of 858 // 'MOSymbol'. 859 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol); 860 const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry, 861 MCSymbolRefExpr::VK_PPC_L, 862 OutContext); 863 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 864 EmitToStreamer(*OutStreamer, TmpInst); 865 return; 866 } 867 case PPC::ADDIStocHA8: { 868 // Transform %xd = ADDIStocHA8 %x2, @sym 869 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 870 871 // Change the opcode to ADDIS8. If the global address is the address of 872 // an external symbol, is a jump table address, is a block address, or is a 873 // constant pool index with large code model enabled, then generate a TOC 874 // entry and reference that. Otherwise, reference the symbol directly. 875 TmpInst.setOpcode(PPC::ADDIS8); 876 877 const MachineOperand &MO = MI->getOperand(2); 878 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) && 879 "Invalid operand for ADDIStocHA8!"); 880 881 const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this); 882 883 const bool GlobalToc = 884 MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal()); 885 if (GlobalToc || MO.isJTI() || MO.isBlockAddress() || 886 (MO.isCPI() && TM.getCodeModel() == CodeModel::Large)) 887 MOSymbol = lookUpOrCreateTOCEntry(MOSymbol); 888 889 const MCSymbolRefExpr::VariantKind VK = 890 IsAIX ? MCSymbolRefExpr::VK_PPC_U : MCSymbolRefExpr::VK_PPC_TOC_HA; 891 892 const MCExpr *Exp = 893 MCSymbolRefExpr::create(MOSymbol, VK, OutContext); 894 895 if (!MO.isJTI() && MO.getOffset()) 896 Exp = MCBinaryExpr::createAdd(Exp, 897 MCConstantExpr::create(MO.getOffset(), 898 OutContext), 899 OutContext); 900 901 TmpInst.getOperand(2) = MCOperand::createExpr(Exp); 902 EmitToStreamer(*OutStreamer, TmpInst); 903 return; 904 } 905 case PPC::LDtocL: { 906 // Transform %xd = LDtocL @sym, %xs 907 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 908 909 // Change the opcode to LD. If the global address is the address of 910 // an external symbol, is a jump table address, is a block address, or is 911 // a constant pool index with large code model enabled, then generate a 912 // TOC entry and reference that. Otherwise, reference the symbol directly. 913 TmpInst.setOpcode(PPC::LD); 914 915 const MachineOperand &MO = MI->getOperand(1); 916 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || 917 MO.isBlockAddress()) && 918 "Invalid operand for LDtocL!"); 919 920 LLVM_DEBUG(assert( 921 (!MO.isGlobal() || Subtarget->isGVIndirectSymbol(MO.getGlobal())) && 922 "LDtocL used on symbol that could be accessed directly is " 923 "invalid. Must match ADDIStocHA8.")); 924 925 const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this); 926 927 if (!MO.isCPI() || TM.getCodeModel() == CodeModel::Large) 928 MOSymbol = lookUpOrCreateTOCEntry(MOSymbol); 929 930 const MCSymbolRefExpr::VariantKind VK = 931 IsAIX ? MCSymbolRefExpr::VK_PPC_L : MCSymbolRefExpr::VK_PPC_TOC_LO; 932 const MCExpr *Exp = 933 MCSymbolRefExpr::create(MOSymbol, VK, OutContext); 934 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 935 EmitToStreamer(*OutStreamer, TmpInst); 936 return; 937 } 938 case PPC::ADDItocL: { 939 // Transform %xd = ADDItocL %xs, @sym 940 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 941 942 // Change the opcode to ADDI8. If the global address is external, then 943 // generate a TOC entry and reference that. Otherwise, reference the 944 // symbol directly. 945 TmpInst.setOpcode(PPC::ADDI8); 946 947 const MachineOperand &MO = MI->getOperand(2); 948 assert((MO.isGlobal() || MO.isCPI()) && "Invalid operand for ADDItocL."); 949 950 LLVM_DEBUG(assert( 951 !(MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal())) && 952 "Interposable definitions must use indirect access.")); 953 954 const MCExpr *Exp = 955 MCSymbolRefExpr::create(getMCSymbolForTOCPseudoMO(MO, *this), 956 MCSymbolRefExpr::VK_PPC_TOC_LO, OutContext); 957 TmpInst.getOperand(2) = MCOperand::createExpr(Exp); 958 EmitToStreamer(*OutStreamer, TmpInst); 959 return; 960 } 961 case PPC::ADDISgotTprelHA: { 962 // Transform: %xd = ADDISgotTprelHA %x2, @sym 963 // Into: %xd = ADDIS8 %x2, sym@got@tlsgd@ha 964 assert(IsPPC64 && "Not supported for 32-bit PowerPC"); 965 const MachineOperand &MO = MI->getOperand(2); 966 const GlobalValue *GValue = MO.getGlobal(); 967 MCSymbol *MOSymbol = getSymbol(GValue); 968 const MCExpr *SymGotTprel = 969 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA, 970 OutContext); 971 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8) 972 .addReg(MI->getOperand(0).getReg()) 973 .addReg(MI->getOperand(1).getReg()) 974 .addExpr(SymGotTprel)); 975 return; 976 } 977 case PPC::LDgotTprelL: 978 case PPC::LDgotTprelL32: { 979 // Transform %xd = LDgotTprelL @sym, %xs 980 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 981 982 // Change the opcode to LD. 983 TmpInst.setOpcode(IsPPC64 ? PPC::LD : PPC::LWZ); 984 const MachineOperand &MO = MI->getOperand(1); 985 const GlobalValue *GValue = MO.getGlobal(); 986 MCSymbol *MOSymbol = getSymbol(GValue); 987 const MCExpr *Exp = MCSymbolRefExpr::create( 988 MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO 989 : MCSymbolRefExpr::VK_PPC_GOT_TPREL, 990 OutContext); 991 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 992 EmitToStreamer(*OutStreamer, TmpInst); 993 return; 994 } 995 996 case PPC::PPC32PICGOT: { 997 MCSymbol *GOTSymbol = OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_")); 998 MCSymbol *GOTRef = OutContext.createTempSymbol(); 999 MCSymbol *NextInstr = OutContext.createTempSymbol(); 1000 1001 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL) 1002 // FIXME: We would like an efficient form for this, so we don't have to do 1003 // a lot of extra uniquing. 1004 .addExpr(MCSymbolRefExpr::create(NextInstr, OutContext))); 1005 const MCExpr *OffsExpr = 1006 MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol, OutContext), 1007 MCSymbolRefExpr::create(GOTRef, OutContext), 1008 OutContext); 1009 OutStreamer->emitLabel(GOTRef); 1010 OutStreamer->emitValue(OffsExpr, 4); 1011 OutStreamer->emitLabel(NextInstr); 1012 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR) 1013 .addReg(MI->getOperand(0).getReg())); 1014 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LWZ) 1015 .addReg(MI->getOperand(1).getReg()) 1016 .addImm(0) 1017 .addReg(MI->getOperand(0).getReg())); 1018 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD4) 1019 .addReg(MI->getOperand(0).getReg()) 1020 .addReg(MI->getOperand(1).getReg()) 1021 .addReg(MI->getOperand(0).getReg())); 1022 return; 1023 } 1024 case PPC::PPC32GOT: { 1025 MCSymbol *GOTSymbol = 1026 OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_")); 1027 const MCExpr *SymGotTlsL = MCSymbolRefExpr::create( 1028 GOTSymbol, MCSymbolRefExpr::VK_PPC_LO, OutContext); 1029 const MCExpr *SymGotTlsHA = MCSymbolRefExpr::create( 1030 GOTSymbol, MCSymbolRefExpr::VK_PPC_HA, OutContext); 1031 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI) 1032 .addReg(MI->getOperand(0).getReg()) 1033 .addExpr(SymGotTlsL)); 1034 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS) 1035 .addReg(MI->getOperand(0).getReg()) 1036 .addReg(MI->getOperand(0).getReg()) 1037 .addExpr(SymGotTlsHA)); 1038 return; 1039 } 1040 case PPC::ADDIStlsgdHA: { 1041 // Transform: %xd = ADDIStlsgdHA %x2, @sym 1042 // Into: %xd = ADDIS8 %x2, sym@got@tlsgd@ha 1043 assert(IsPPC64 && "Not supported for 32-bit PowerPC"); 1044 const MachineOperand &MO = MI->getOperand(2); 1045 const GlobalValue *GValue = MO.getGlobal(); 1046 MCSymbol *MOSymbol = getSymbol(GValue); 1047 const MCExpr *SymGotTlsGD = 1048 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA, 1049 OutContext); 1050 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8) 1051 .addReg(MI->getOperand(0).getReg()) 1052 .addReg(MI->getOperand(1).getReg()) 1053 .addExpr(SymGotTlsGD)); 1054 return; 1055 } 1056 case PPC::ADDItlsgdL: 1057 // Transform: %xd = ADDItlsgdL %xs, @sym 1058 // Into: %xd = ADDI8 %xs, sym@got@tlsgd@l 1059 case PPC::ADDItlsgdL32: { 1060 // Transform: %rd = ADDItlsgdL32 %rs, @sym 1061 // Into: %rd = ADDI %rs, sym@got@tlsgd 1062 const MachineOperand &MO = MI->getOperand(2); 1063 const GlobalValue *GValue = MO.getGlobal(); 1064 MCSymbol *MOSymbol = getSymbol(GValue); 1065 const MCExpr *SymGotTlsGD = MCSymbolRefExpr::create( 1066 MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO 1067 : MCSymbolRefExpr::VK_PPC_GOT_TLSGD, 1068 OutContext); 1069 EmitToStreamer(*OutStreamer, 1070 MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI) 1071 .addReg(MI->getOperand(0).getReg()) 1072 .addReg(MI->getOperand(1).getReg()) 1073 .addExpr(SymGotTlsGD)); 1074 return; 1075 } 1076 case PPC::GETtlsADDR: 1077 // Transform: %x3 = GETtlsADDR %x3, @sym 1078 // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsgd) 1079 case PPC::GETtlsADDRPCREL: 1080 case PPC::GETtlsADDR32: { 1081 // Transform: %r3 = GETtlsADDR32 %r3, @sym 1082 // Into: BL_TLS __tls_get_addr(sym at tlsgd)@PLT 1083 EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSGD); 1084 return; 1085 } 1086 case PPC::ADDIStlsldHA: { 1087 // Transform: %xd = ADDIStlsldHA %x2, @sym 1088 // Into: %xd = ADDIS8 %x2, sym@got@tlsld@ha 1089 assert(IsPPC64 && "Not supported for 32-bit PowerPC"); 1090 const MachineOperand &MO = MI->getOperand(2); 1091 const GlobalValue *GValue = MO.getGlobal(); 1092 MCSymbol *MOSymbol = getSymbol(GValue); 1093 const MCExpr *SymGotTlsLD = 1094 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA, 1095 OutContext); 1096 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8) 1097 .addReg(MI->getOperand(0).getReg()) 1098 .addReg(MI->getOperand(1).getReg()) 1099 .addExpr(SymGotTlsLD)); 1100 return; 1101 } 1102 case PPC::ADDItlsldL: 1103 // Transform: %xd = ADDItlsldL %xs, @sym 1104 // Into: %xd = ADDI8 %xs, sym@got@tlsld@l 1105 case PPC::ADDItlsldL32: { 1106 // Transform: %rd = ADDItlsldL32 %rs, @sym 1107 // Into: %rd = ADDI %rs, sym@got@tlsld 1108 const MachineOperand &MO = MI->getOperand(2); 1109 const GlobalValue *GValue = MO.getGlobal(); 1110 MCSymbol *MOSymbol = getSymbol(GValue); 1111 const MCExpr *SymGotTlsLD = MCSymbolRefExpr::create( 1112 MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO 1113 : MCSymbolRefExpr::VK_PPC_GOT_TLSLD, 1114 OutContext); 1115 EmitToStreamer(*OutStreamer, 1116 MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI) 1117 .addReg(MI->getOperand(0).getReg()) 1118 .addReg(MI->getOperand(1).getReg()) 1119 .addExpr(SymGotTlsLD)); 1120 return; 1121 } 1122 case PPC::GETtlsldADDR: 1123 // Transform: %x3 = GETtlsldADDR %x3, @sym 1124 // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsld) 1125 case PPC::GETtlsldADDRPCREL: 1126 case PPC::GETtlsldADDR32: { 1127 // Transform: %r3 = GETtlsldADDR32 %r3, @sym 1128 // Into: BL_TLS __tls_get_addr(sym at tlsld)@PLT 1129 EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSLD); 1130 return; 1131 } 1132 case PPC::ADDISdtprelHA: 1133 // Transform: %xd = ADDISdtprelHA %xs, @sym 1134 // Into: %xd = ADDIS8 %xs, sym@dtprel@ha 1135 case PPC::ADDISdtprelHA32: { 1136 // Transform: %rd = ADDISdtprelHA32 %rs, @sym 1137 // Into: %rd = ADDIS %rs, sym@dtprel@ha 1138 const MachineOperand &MO = MI->getOperand(2); 1139 const GlobalValue *GValue = MO.getGlobal(); 1140 MCSymbol *MOSymbol = getSymbol(GValue); 1141 const MCExpr *SymDtprel = 1142 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_HA, 1143 OutContext); 1144 EmitToStreamer( 1145 *OutStreamer, 1146 MCInstBuilder(IsPPC64 ? PPC::ADDIS8 : PPC::ADDIS) 1147 .addReg(MI->getOperand(0).getReg()) 1148 .addReg(MI->getOperand(1).getReg()) 1149 .addExpr(SymDtprel)); 1150 return; 1151 } 1152 case PPC::PADDIdtprel: { 1153 // Transform: %rd = PADDIdtprel %rs, @sym 1154 // Into: %rd = PADDI8 %rs, sym@dtprel 1155 const MachineOperand &MO = MI->getOperand(2); 1156 const GlobalValue *GValue = MO.getGlobal(); 1157 MCSymbol *MOSymbol = getSymbol(GValue); 1158 const MCExpr *SymDtprel = MCSymbolRefExpr::create( 1159 MOSymbol, MCSymbolRefExpr::VK_DTPREL, OutContext); 1160 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::PADDI8) 1161 .addReg(MI->getOperand(0).getReg()) 1162 .addReg(MI->getOperand(1).getReg()) 1163 .addExpr(SymDtprel)); 1164 return; 1165 } 1166 1167 case PPC::ADDIdtprelL: 1168 // Transform: %xd = ADDIdtprelL %xs, @sym 1169 // Into: %xd = ADDI8 %xs, sym@dtprel@l 1170 case PPC::ADDIdtprelL32: { 1171 // Transform: %rd = ADDIdtprelL32 %rs, @sym 1172 // Into: %rd = ADDI %rs, sym@dtprel@l 1173 const MachineOperand &MO = MI->getOperand(2); 1174 const GlobalValue *GValue = MO.getGlobal(); 1175 MCSymbol *MOSymbol = getSymbol(GValue); 1176 const MCExpr *SymDtprel = 1177 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_LO, 1178 OutContext); 1179 EmitToStreamer(*OutStreamer, 1180 MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI) 1181 .addReg(MI->getOperand(0).getReg()) 1182 .addReg(MI->getOperand(1).getReg()) 1183 .addExpr(SymDtprel)); 1184 return; 1185 } 1186 case PPC::MFOCRF: 1187 case PPC::MFOCRF8: 1188 if (!Subtarget->hasMFOCRF()) { 1189 // Transform: %r3 = MFOCRF %cr7 1190 // Into: %r3 = MFCR ;; cr7 1191 unsigned NewOpcode = 1192 MI->getOpcode() == PPC::MFOCRF ? PPC::MFCR : PPC::MFCR8; 1193 OutStreamer->AddComment(PPCInstPrinter:: 1194 getRegisterName(MI->getOperand(1).getReg())); 1195 EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode) 1196 .addReg(MI->getOperand(0).getReg())); 1197 return; 1198 } 1199 break; 1200 case PPC::MTOCRF: 1201 case PPC::MTOCRF8: 1202 if (!Subtarget->hasMFOCRF()) { 1203 // Transform: %cr7 = MTOCRF %r3 1204 // Into: MTCRF mask, %r3 ;; cr7 1205 unsigned NewOpcode = 1206 MI->getOpcode() == PPC::MTOCRF ? PPC::MTCRF : PPC::MTCRF8; 1207 unsigned Mask = 0x80 >> OutContext.getRegisterInfo() 1208 ->getEncodingValue(MI->getOperand(0).getReg()); 1209 OutStreamer->AddComment(PPCInstPrinter:: 1210 getRegisterName(MI->getOperand(0).getReg())); 1211 EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode) 1212 .addImm(Mask) 1213 .addReg(MI->getOperand(1).getReg())); 1214 return; 1215 } 1216 break; 1217 case PPC::LD: 1218 case PPC::STD: 1219 case PPC::LWA_32: 1220 case PPC::LWA: { 1221 // Verify alignment is legal, so we don't create relocations 1222 // that can't be supported. 1223 // FIXME: This test is currently disabled for Darwin. The test 1224 // suite shows a handful of test cases that fail this check for 1225 // Darwin. Those need to be investigated before this sanity test 1226 // can be enabled for those subtargets. 1227 unsigned OpNum = (MI->getOpcode() == PPC::STD) ? 2 : 1; 1228 const MachineOperand &MO = MI->getOperand(OpNum); 1229 if (MO.isGlobal()) { 1230 const DataLayout &DL = MO.getGlobal()->getParent()->getDataLayout(); 1231 if (MO.getGlobal()->getPointerAlignment(DL) < 4) 1232 llvm_unreachable("Global must be word-aligned for LD, STD, LWA!"); 1233 } 1234 // Now process the instruction normally. 1235 break; 1236 } 1237 } 1238 1239 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 1240 EmitToStreamer(*OutStreamer, TmpInst); 1241 } 1242 1243 void PPCLinuxAsmPrinter::emitInstruction(const MachineInstr *MI) { 1244 if (!Subtarget->isPPC64()) 1245 return PPCAsmPrinter::emitInstruction(MI); 1246 1247 switch (MI->getOpcode()) { 1248 default: 1249 return PPCAsmPrinter::emitInstruction(MI); 1250 case TargetOpcode::PATCHABLE_FUNCTION_ENTER: { 1251 // .begin: 1252 // b .end # lis 0, FuncId[16..32] 1253 // nop # li 0, FuncId[0..15] 1254 // std 0, -8(1) 1255 // mflr 0 1256 // bl __xray_FunctionEntry 1257 // mtlr 0 1258 // .end: 1259 // 1260 // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number 1261 // of instructions change. 1262 MCSymbol *BeginOfSled = OutContext.createTempSymbol(); 1263 MCSymbol *EndOfSled = OutContext.createTempSymbol(); 1264 OutStreamer->emitLabel(BeginOfSled); 1265 EmitToStreamer(*OutStreamer, 1266 MCInstBuilder(PPC::B).addExpr( 1267 MCSymbolRefExpr::create(EndOfSled, OutContext))); 1268 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP)); 1269 EmitToStreamer( 1270 *OutStreamer, 1271 MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1)); 1272 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0)); 1273 EmitToStreamer(*OutStreamer, 1274 MCInstBuilder(PPC::BL8_NOP) 1275 .addExpr(MCSymbolRefExpr::create( 1276 OutContext.getOrCreateSymbol("__xray_FunctionEntry"), 1277 OutContext))); 1278 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0)); 1279 OutStreamer->emitLabel(EndOfSled); 1280 recordSled(BeginOfSled, *MI, SledKind::FUNCTION_ENTER, 2); 1281 break; 1282 } 1283 case TargetOpcode::PATCHABLE_RET: { 1284 unsigned RetOpcode = MI->getOperand(0).getImm(); 1285 MCInst RetInst; 1286 RetInst.setOpcode(RetOpcode); 1287 for (const auto &MO : 1288 make_range(std::next(MI->operands_begin()), MI->operands_end())) { 1289 MCOperand MCOp; 1290 if (LowerPPCMachineOperandToMCOperand(MO, MCOp, *this)) 1291 RetInst.addOperand(MCOp); 1292 } 1293 1294 bool IsConditional; 1295 if (RetOpcode == PPC::BCCLR) { 1296 IsConditional = true; 1297 } else if (RetOpcode == PPC::TCRETURNdi8 || RetOpcode == PPC::TCRETURNri8 || 1298 RetOpcode == PPC::TCRETURNai8) { 1299 break; 1300 } else if (RetOpcode == PPC::BLR8 || RetOpcode == PPC::TAILB8) { 1301 IsConditional = false; 1302 } else { 1303 EmitToStreamer(*OutStreamer, RetInst); 1304 break; 1305 } 1306 1307 MCSymbol *FallthroughLabel; 1308 if (IsConditional) { 1309 // Before: 1310 // bgtlr cr0 1311 // 1312 // After: 1313 // ble cr0, .end 1314 // .p2align 3 1315 // .begin: 1316 // blr # lis 0, FuncId[16..32] 1317 // nop # li 0, FuncId[0..15] 1318 // std 0, -8(1) 1319 // mflr 0 1320 // bl __xray_FunctionExit 1321 // mtlr 0 1322 // blr 1323 // .end: 1324 // 1325 // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number 1326 // of instructions change. 1327 FallthroughLabel = OutContext.createTempSymbol(); 1328 EmitToStreamer( 1329 *OutStreamer, 1330 MCInstBuilder(PPC::BCC) 1331 .addImm(PPC::InvertPredicate( 1332 static_cast<PPC::Predicate>(MI->getOperand(1).getImm()))) 1333 .addReg(MI->getOperand(2).getReg()) 1334 .addExpr(MCSymbolRefExpr::create(FallthroughLabel, OutContext))); 1335 RetInst = MCInst(); 1336 RetInst.setOpcode(PPC::BLR8); 1337 } 1338 // .p2align 3 1339 // .begin: 1340 // b(lr)? # lis 0, FuncId[16..32] 1341 // nop # li 0, FuncId[0..15] 1342 // std 0, -8(1) 1343 // mflr 0 1344 // bl __xray_FunctionExit 1345 // mtlr 0 1346 // b(lr)? 1347 // 1348 // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number 1349 // of instructions change. 1350 OutStreamer->emitCodeAlignment(8); 1351 MCSymbol *BeginOfSled = OutContext.createTempSymbol(); 1352 OutStreamer->emitLabel(BeginOfSled); 1353 EmitToStreamer(*OutStreamer, RetInst); 1354 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP)); 1355 EmitToStreamer( 1356 *OutStreamer, 1357 MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1)); 1358 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0)); 1359 EmitToStreamer(*OutStreamer, 1360 MCInstBuilder(PPC::BL8_NOP) 1361 .addExpr(MCSymbolRefExpr::create( 1362 OutContext.getOrCreateSymbol("__xray_FunctionExit"), 1363 OutContext))); 1364 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0)); 1365 EmitToStreamer(*OutStreamer, RetInst); 1366 if (IsConditional) 1367 OutStreamer->emitLabel(FallthroughLabel); 1368 recordSled(BeginOfSled, *MI, SledKind::FUNCTION_EXIT, 2); 1369 break; 1370 } 1371 case TargetOpcode::PATCHABLE_FUNCTION_EXIT: 1372 llvm_unreachable("PATCHABLE_FUNCTION_EXIT should never be emitted"); 1373 case TargetOpcode::PATCHABLE_TAIL_CALL: 1374 // TODO: Define a trampoline `__xray_FunctionTailExit` and differentiate a 1375 // normal function exit from a tail exit. 1376 llvm_unreachable("Tail call is handled in the normal case. See comments " 1377 "around this assert."); 1378 } 1379 } 1380 1381 void PPCLinuxAsmPrinter::emitStartOfAsmFile(Module &M) { 1382 if (static_cast<const PPCTargetMachine &>(TM).isELFv2ABI()) { 1383 PPCTargetStreamer *TS = 1384 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer()); 1385 1386 if (TS) 1387 TS->emitAbiVersion(2); 1388 } 1389 1390 if (static_cast<const PPCTargetMachine &>(TM).isPPC64() || 1391 !isPositionIndependent()) 1392 return AsmPrinter::emitStartOfAsmFile(M); 1393 1394 if (M.getPICLevel() == PICLevel::SmallPIC) 1395 return AsmPrinter::emitStartOfAsmFile(M); 1396 1397 OutStreamer->SwitchSection(OutContext.getELFSection( 1398 ".got2", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC)); 1399 1400 MCSymbol *TOCSym = OutContext.getOrCreateSymbol(Twine(".LTOC")); 1401 MCSymbol *CurrentPos = OutContext.createTempSymbol(); 1402 1403 OutStreamer->emitLabel(CurrentPos); 1404 1405 // The GOT pointer points to the middle of the GOT, in order to reference the 1406 // entire 64kB range. 0x8000 is the midpoint. 1407 const MCExpr *tocExpr = 1408 MCBinaryExpr::createAdd(MCSymbolRefExpr::create(CurrentPos, OutContext), 1409 MCConstantExpr::create(0x8000, OutContext), 1410 OutContext); 1411 1412 OutStreamer->emitAssignment(TOCSym, tocExpr); 1413 1414 OutStreamer->SwitchSection(getObjFileLowering().getTextSection()); 1415 } 1416 1417 void PPCLinuxAsmPrinter::emitFunctionEntryLabel() { 1418 // linux/ppc32 - Normal entry label. 1419 if (!Subtarget->isPPC64() && 1420 (!isPositionIndependent() || 1421 MF->getFunction().getParent()->getPICLevel() == PICLevel::SmallPIC)) 1422 return AsmPrinter::emitFunctionEntryLabel(); 1423 1424 if (!Subtarget->isPPC64()) { 1425 const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>(); 1426 if (PPCFI->usesPICBase() && !Subtarget->isSecurePlt()) { 1427 MCSymbol *RelocSymbol = PPCFI->getPICOffsetSymbol(*MF); 1428 MCSymbol *PICBase = MF->getPICBaseSymbol(); 1429 OutStreamer->emitLabel(RelocSymbol); 1430 1431 const MCExpr *OffsExpr = 1432 MCBinaryExpr::createSub( 1433 MCSymbolRefExpr::create(OutContext.getOrCreateSymbol(Twine(".LTOC")), 1434 OutContext), 1435 MCSymbolRefExpr::create(PICBase, OutContext), 1436 OutContext); 1437 OutStreamer->emitValue(OffsExpr, 4); 1438 OutStreamer->emitLabel(CurrentFnSym); 1439 return; 1440 } else 1441 return AsmPrinter::emitFunctionEntryLabel(); 1442 } 1443 1444 // ELFv2 ABI - Normal entry label. 1445 if (Subtarget->isELFv2ABI()) { 1446 // In the Large code model, we allow arbitrary displacements between 1447 // the text section and its associated TOC section. We place the 1448 // full 8-byte offset to the TOC in memory immediately preceding 1449 // the function global entry point. 1450 if (TM.getCodeModel() == CodeModel::Large 1451 && !MF->getRegInfo().use_empty(PPC::X2)) { 1452 const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>(); 1453 1454 MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC.")); 1455 MCSymbol *GlobalEPSymbol = PPCFI->getGlobalEPSymbol(*MF); 1456 const MCExpr *TOCDeltaExpr = 1457 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext), 1458 MCSymbolRefExpr::create(GlobalEPSymbol, 1459 OutContext), 1460 OutContext); 1461 1462 OutStreamer->emitLabel(PPCFI->getTOCOffsetSymbol(*MF)); 1463 OutStreamer->emitValue(TOCDeltaExpr, 8); 1464 } 1465 return AsmPrinter::emitFunctionEntryLabel(); 1466 } 1467 1468 // Emit an official procedure descriptor. 1469 MCSectionSubPair Current = OutStreamer->getCurrentSection(); 1470 MCSectionELF *Section = OutStreamer->getContext().getELFSection( 1471 ".opd", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC); 1472 OutStreamer->SwitchSection(Section); 1473 OutStreamer->emitLabel(CurrentFnSym); 1474 OutStreamer->emitValueToAlignment(8); 1475 MCSymbol *Symbol1 = CurrentFnSymForSize; 1476 // Generates a R_PPC64_ADDR64 (from FK_DATA_8) relocation for the function 1477 // entry point. 1478 OutStreamer->emitValue(MCSymbolRefExpr::create(Symbol1, OutContext), 1479 8 /*size*/); 1480 MCSymbol *Symbol2 = OutContext.getOrCreateSymbol(StringRef(".TOC.")); 1481 // Generates a R_PPC64_TOC relocation for TOC base insertion. 1482 OutStreamer->emitValue( 1483 MCSymbolRefExpr::create(Symbol2, MCSymbolRefExpr::VK_PPC_TOCBASE, OutContext), 1484 8/*size*/); 1485 // Emit a null environment pointer. 1486 OutStreamer->emitIntValue(0, 8 /* size */); 1487 OutStreamer->SwitchSection(Current.first, Current.second); 1488 } 1489 1490 void PPCLinuxAsmPrinter::emitEndOfAsmFile(Module &M) { 1491 const DataLayout &DL = getDataLayout(); 1492 1493 bool isPPC64 = DL.getPointerSizeInBits() == 64; 1494 1495 PPCTargetStreamer *TS = 1496 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer()); 1497 1498 if (!TOC.empty()) { 1499 const char *Name = isPPC64 ? ".toc" : ".got2"; 1500 MCSectionELF *Section = OutContext.getELFSection( 1501 Name, ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC); 1502 OutStreamer->SwitchSection(Section); 1503 if (!isPPC64) 1504 OutStreamer->emitValueToAlignment(4); 1505 1506 for (const auto &TOCMapPair : TOC) { 1507 const MCSymbol *const TOCEntryTarget = TOCMapPair.first; 1508 MCSymbol *const TOCEntryLabel = TOCMapPair.second; 1509 1510 OutStreamer->emitLabel(TOCEntryLabel); 1511 if (isPPC64 && TS != nullptr) 1512 TS->emitTCEntry(*TOCEntryTarget); 1513 else 1514 OutStreamer->emitSymbolValue(TOCEntryTarget, 4); 1515 } 1516 } 1517 1518 PPCAsmPrinter::emitEndOfAsmFile(M); 1519 } 1520 1521 /// EmitFunctionBodyStart - Emit a global entry point prefix for ELFv2. 1522 void PPCLinuxAsmPrinter::emitFunctionBodyStart() { 1523 // In the ELFv2 ABI, in functions that use the TOC register, we need to 1524 // provide two entry points. The ABI guarantees that when calling the 1525 // local entry point, r2 is set up by the caller to contain the TOC base 1526 // for this function, and when calling the global entry point, r12 is set 1527 // up by the caller to hold the address of the global entry point. We 1528 // thus emit a prefix sequence along the following lines: 1529 // 1530 // func: 1531 // .Lfunc_gepNN: 1532 // # global entry point 1533 // addis r2,r12,(.TOC.-.Lfunc_gepNN)@ha 1534 // addi r2,r2,(.TOC.-.Lfunc_gepNN)@l 1535 // .Lfunc_lepNN: 1536 // .localentry func, .Lfunc_lepNN-.Lfunc_gepNN 1537 // # local entry point, followed by function body 1538 // 1539 // For the Large code model, we create 1540 // 1541 // .Lfunc_tocNN: 1542 // .quad .TOC.-.Lfunc_gepNN # done by EmitFunctionEntryLabel 1543 // func: 1544 // .Lfunc_gepNN: 1545 // # global entry point 1546 // ld r2,.Lfunc_tocNN-.Lfunc_gepNN(r12) 1547 // add r2,r2,r12 1548 // .Lfunc_lepNN: 1549 // .localentry func, .Lfunc_lepNN-.Lfunc_gepNN 1550 // # local entry point, followed by function body 1551 // 1552 // This ensures we have r2 set up correctly while executing the function 1553 // body, no matter which entry point is called. 1554 const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>(); 1555 const bool UsesX2OrR2 = !MF->getRegInfo().use_empty(PPC::X2) || 1556 !MF->getRegInfo().use_empty(PPC::R2); 1557 const bool PCrelGEPRequired = Subtarget->isUsingPCRelativeCalls() && 1558 UsesX2OrR2 && PPCFI->usesTOCBasePtr(); 1559 const bool NonPCrelGEPRequired = !Subtarget->isUsingPCRelativeCalls() && 1560 Subtarget->isELFv2ABI() && UsesX2OrR2; 1561 1562 // Only do all that if the function uses R2 as the TOC pointer 1563 // in the first place. We don't need the global entry point if the 1564 // function uses R2 as an allocatable register. 1565 if (NonPCrelGEPRequired || PCrelGEPRequired) { 1566 // Note: The logic here must be synchronized with the code in the 1567 // branch-selection pass which sets the offset of the first block in the 1568 // function. This matters because it affects the alignment. 1569 MCSymbol *GlobalEntryLabel = PPCFI->getGlobalEPSymbol(*MF); 1570 OutStreamer->emitLabel(GlobalEntryLabel); 1571 const MCSymbolRefExpr *GlobalEntryLabelExp = 1572 MCSymbolRefExpr::create(GlobalEntryLabel, OutContext); 1573 1574 if (TM.getCodeModel() != CodeModel::Large) { 1575 MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC.")); 1576 const MCExpr *TOCDeltaExpr = 1577 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext), 1578 GlobalEntryLabelExp, OutContext); 1579 1580 const MCExpr *TOCDeltaHi = PPCMCExpr::createHa(TOCDeltaExpr, OutContext); 1581 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS) 1582 .addReg(PPC::X2) 1583 .addReg(PPC::X12) 1584 .addExpr(TOCDeltaHi)); 1585 1586 const MCExpr *TOCDeltaLo = PPCMCExpr::createLo(TOCDeltaExpr, OutContext); 1587 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDI) 1588 .addReg(PPC::X2) 1589 .addReg(PPC::X2) 1590 .addExpr(TOCDeltaLo)); 1591 } else { 1592 MCSymbol *TOCOffset = PPCFI->getTOCOffsetSymbol(*MF); 1593 const MCExpr *TOCOffsetDeltaExpr = 1594 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCOffset, OutContext), 1595 GlobalEntryLabelExp, OutContext); 1596 1597 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD) 1598 .addReg(PPC::X2) 1599 .addExpr(TOCOffsetDeltaExpr) 1600 .addReg(PPC::X12)); 1601 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD8) 1602 .addReg(PPC::X2) 1603 .addReg(PPC::X2) 1604 .addReg(PPC::X12)); 1605 } 1606 1607 MCSymbol *LocalEntryLabel = PPCFI->getLocalEPSymbol(*MF); 1608 OutStreamer->emitLabel(LocalEntryLabel); 1609 const MCSymbolRefExpr *LocalEntryLabelExp = 1610 MCSymbolRefExpr::create(LocalEntryLabel, OutContext); 1611 const MCExpr *LocalOffsetExp = 1612 MCBinaryExpr::createSub(LocalEntryLabelExp, 1613 GlobalEntryLabelExp, OutContext); 1614 1615 PPCTargetStreamer *TS = 1616 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer()); 1617 1618 if (TS) 1619 TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym), LocalOffsetExp); 1620 } else if (Subtarget->isUsingPCRelativeCalls()) { 1621 // When generating the entry point for a function we have a few scenarios 1622 // based on whether or not that function uses R2 and whether or not that 1623 // function makes calls (or is a leaf function). 1624 // 1) A leaf function that does not use R2 (or treats it as callee-saved 1625 // and preserves it). In this case st_other=0 and both 1626 // the local and global entry points for the function are the same. 1627 // No special entry point code is required. 1628 // 2) A function uses the TOC pointer R2. This function may or may not have 1629 // calls. In this case st_other=[2,6] and the global and local entry 1630 // points are different. Code to correctly setup the TOC pointer in R2 1631 // is put between the global and local entry points. This case is 1632 // covered by the if statatement above. 1633 // 3) A function does not use the TOC pointer R2 but does have calls. 1634 // In this case st_other=1 since we do not know whether or not any 1635 // of the callees clobber R2. This case is dealt with in this else if 1636 // block. Tail calls are considered calls and the st_other should also 1637 // be set to 1 in that case as well. 1638 // 4) The function does not use the TOC pointer but R2 is used inside 1639 // the function. In this case st_other=1 once again. 1640 // 5) This function uses inline asm. We mark R2 as reserved if the function 1641 // has inline asm as we have to assume that it may be used. 1642 if (MF->getFrameInfo().hasCalls() || MF->getFrameInfo().hasTailCall() || 1643 MF->hasInlineAsm() || (!PPCFI->usesTOCBasePtr() && UsesX2OrR2)) { 1644 PPCTargetStreamer *TS = 1645 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer()); 1646 if (TS) 1647 TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym), 1648 MCConstantExpr::create(1, OutContext)); 1649 } 1650 } 1651 } 1652 1653 /// EmitFunctionBodyEnd - Print the traceback table before the .size 1654 /// directive. 1655 /// 1656 void PPCLinuxAsmPrinter::emitFunctionBodyEnd() { 1657 // Only the 64-bit target requires a traceback table. For now, 1658 // we only emit the word of zeroes that GDB requires to find 1659 // the end of the function, and zeroes for the eight-byte 1660 // mandatory fields. 1661 // FIXME: We should fill in the eight-byte mandatory fields as described in 1662 // the PPC64 ELF ABI (this is a low-priority item because GDB does not 1663 // currently make use of these fields). 1664 if (Subtarget->isPPC64()) { 1665 OutStreamer->emitIntValue(0, 4/*size*/); 1666 OutStreamer->emitIntValue(0, 8/*size*/); 1667 } 1668 } 1669 1670 void PPCAIXAsmPrinter::emitLinkage(const GlobalValue *GV, 1671 MCSymbol *GVSym) const { 1672 1673 assert(MAI->hasVisibilityOnlyWithLinkage() && 1674 "AIX's linkage directives take a visibility setting."); 1675 1676 MCSymbolAttr LinkageAttr = MCSA_Invalid; 1677 switch (GV->getLinkage()) { 1678 case GlobalValue::ExternalLinkage: 1679 LinkageAttr = GV->isDeclaration() ? MCSA_Extern : MCSA_Global; 1680 break; 1681 case GlobalValue::LinkOnceAnyLinkage: 1682 case GlobalValue::LinkOnceODRLinkage: 1683 case GlobalValue::WeakAnyLinkage: 1684 case GlobalValue::WeakODRLinkage: 1685 case GlobalValue::ExternalWeakLinkage: 1686 LinkageAttr = MCSA_Weak; 1687 break; 1688 case GlobalValue::AvailableExternallyLinkage: 1689 LinkageAttr = MCSA_Extern; 1690 break; 1691 case GlobalValue::PrivateLinkage: 1692 return; 1693 case GlobalValue::InternalLinkage: 1694 assert(GV->getVisibility() == GlobalValue::DefaultVisibility && 1695 "InternalLinkage should not have other visibility setting."); 1696 LinkageAttr = MCSA_LGlobal; 1697 break; 1698 case GlobalValue::AppendingLinkage: 1699 llvm_unreachable("Should never emit this"); 1700 case GlobalValue::CommonLinkage: 1701 llvm_unreachable("CommonLinkage of XCOFF should not come to this path"); 1702 } 1703 1704 assert(LinkageAttr != MCSA_Invalid && "LinkageAttr should not MCSA_Invalid."); 1705 1706 MCSymbolAttr VisibilityAttr = MCSA_Invalid; 1707 if (!TM.getIgnoreXCOFFVisibility()) { 1708 switch (GV->getVisibility()) { 1709 1710 // TODO: "exported" and "internal" Visibility needs to go here. 1711 case GlobalValue::DefaultVisibility: 1712 break; 1713 case GlobalValue::HiddenVisibility: 1714 VisibilityAttr = MAI->getHiddenVisibilityAttr(); 1715 break; 1716 case GlobalValue::ProtectedVisibility: 1717 VisibilityAttr = MAI->getProtectedVisibilityAttr(); 1718 break; 1719 } 1720 } 1721 1722 OutStreamer->emitXCOFFSymbolLinkageWithVisibility(GVSym, LinkageAttr, 1723 VisibilityAttr); 1724 } 1725 1726 void PPCAIXAsmPrinter::SetupMachineFunction(MachineFunction &MF) { 1727 // Setup CurrentFnDescSym and its containing csect. 1728 MCSectionXCOFF *FnDescSec = 1729 cast<MCSectionXCOFF>(getObjFileLowering().getSectionForFunctionDescriptor( 1730 &MF.getFunction(), TM)); 1731 FnDescSec->setAlignment(Align(Subtarget->isPPC64() ? 8 : 4)); 1732 1733 CurrentFnDescSym = FnDescSec->getQualNameSymbol(); 1734 1735 return AsmPrinter::SetupMachineFunction(MF); 1736 } 1737 1738 void PPCAIXAsmPrinter::ValidateGV(const GlobalVariable *GV) { 1739 // Early error checking limiting what is supported. 1740 if (GV->isThreadLocal()) 1741 report_fatal_error("Thread local not yet supported on AIX."); 1742 1743 if (GV->hasComdat()) 1744 report_fatal_error("COMDAT not yet supported by AIX."); 1745 } 1746 1747 static bool isSpecialLLVMGlobalArrayToSkip(const GlobalVariable *GV) { 1748 return GV->hasAppendingLinkage() && 1749 StringSwitch<bool>(GV->getName()) 1750 // TODO: Linker could still eliminate the GV if we just skip 1751 // handling llvm.used array. Skipping them for now until we or the 1752 // AIX OS team come up with a good solution. 1753 .Case("llvm.used", true) 1754 // It's correct to just skip llvm.compiler.used array here. 1755 .Case("llvm.compiler.used", true) 1756 .Default(false); 1757 } 1758 1759 static bool isSpecialLLVMGlobalArrayForStaticInit(const GlobalVariable *GV) { 1760 return StringSwitch<bool>(GV->getName()) 1761 .Cases("llvm.global_ctors", "llvm.global_dtors", true) 1762 .Default(false); 1763 } 1764 1765 void PPCAIXAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) { 1766 // Special LLVM global arrays have been handled at the initialization. 1767 if (isSpecialLLVMGlobalArrayToSkip(GV) || isSpecialLLVMGlobalArrayForStaticInit(GV)) 1768 return; 1769 1770 assert(!GV->getName().startswith("llvm.") && 1771 "Unhandled intrinsic global variable."); 1772 ValidateGV(GV); 1773 1774 MCSymbolXCOFF *GVSym = cast<MCSymbolXCOFF>(getSymbol(GV)); 1775 1776 if (GV->isDeclarationForLinker()) { 1777 emitLinkage(GV, GVSym); 1778 return; 1779 } 1780 1781 SectionKind GVKind = getObjFileLowering().getKindForGlobal(GV, TM); 1782 if (!GVKind.isGlobalWriteableData() && !GVKind.isReadOnly()) 1783 report_fatal_error("Encountered a global variable kind that is " 1784 "not supported yet."); 1785 1786 MCSectionXCOFF *Csect = cast<MCSectionXCOFF>( 1787 getObjFileLowering().SectionForGlobal(GV, GVKind, TM)); 1788 1789 // Switch to the containing csect. 1790 OutStreamer->SwitchSection(Csect); 1791 1792 const DataLayout &DL = GV->getParent()->getDataLayout(); 1793 1794 // Handle common symbols. 1795 if (GVKind.isCommon() || GVKind.isBSSLocal()) { 1796 Align Alignment = GV->getAlign().getValueOr(DL.getPreferredAlign(GV)); 1797 uint64_t Size = DL.getTypeAllocSize(GV->getType()->getElementType()); 1798 GVSym->setStorageClass( 1799 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GV)); 1800 1801 if (GVKind.isBSSLocal()) 1802 OutStreamer->emitXCOFFLocalCommonSymbol( 1803 OutContext.getOrCreateSymbol(GVSym->getSymbolTableName()), Size, 1804 GVSym, Alignment.value()); 1805 else 1806 OutStreamer->emitCommonSymbol(GVSym, Size, Alignment.value()); 1807 return; 1808 } 1809 1810 MCSymbol *EmittedInitSym = GVSym; 1811 emitLinkage(GV, EmittedInitSym); 1812 emitAlignment(getGVAlignment(GV, DL), GV); 1813 1814 // When -fdata-sections is enabled, every GlobalVariable will 1815 // be put into its own csect; therefore, label is not necessary here. 1816 if (!TM.getDataSections() || GV->hasSection()) { 1817 OutStreamer->emitLabel(EmittedInitSym); 1818 } 1819 1820 // Emit aliasing label for global variable. 1821 llvm::for_each(GOAliasMap[GV], [this](const GlobalAlias *Alias) { 1822 OutStreamer->emitLabel(getSymbol(Alias)); 1823 }); 1824 1825 emitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer()); 1826 } 1827 1828 void PPCAIXAsmPrinter::emitFunctionDescriptor() { 1829 const DataLayout &DL = getDataLayout(); 1830 const unsigned PointerSize = DL.getPointerSizeInBits() == 64 ? 8 : 4; 1831 1832 MCSectionSubPair Current = OutStreamer->getCurrentSection(); 1833 // Emit function descriptor. 1834 OutStreamer->SwitchSection( 1835 cast<MCSymbolXCOFF>(CurrentFnDescSym)->getRepresentedCsect()); 1836 1837 // Emit aliasing label for function descriptor csect. 1838 llvm::for_each(GOAliasMap[&MF->getFunction()], 1839 [this](const GlobalAlias *Alias) { 1840 OutStreamer->emitLabel(getSymbol(Alias)); 1841 }); 1842 1843 // Emit function entry point address. 1844 OutStreamer->emitValue(MCSymbolRefExpr::create(CurrentFnSym, OutContext), 1845 PointerSize); 1846 // Emit TOC base address. 1847 const MCSymbol *TOCBaseSym = 1848 cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection()) 1849 ->getQualNameSymbol(); 1850 OutStreamer->emitValue(MCSymbolRefExpr::create(TOCBaseSym, OutContext), 1851 PointerSize); 1852 // Emit a null environment pointer. 1853 OutStreamer->emitIntValue(0, PointerSize); 1854 1855 OutStreamer->SwitchSection(Current.first, Current.second); 1856 } 1857 1858 void PPCAIXAsmPrinter::emitFunctionEntryLabel() { 1859 // It's not necessary to emit the label when we have individual 1860 // function in its own csect. 1861 if (!TM.getFunctionSections()) 1862 PPCAsmPrinter::emitFunctionEntryLabel(); 1863 1864 // Emit aliasing label for function entry point label. 1865 llvm::for_each( 1866 GOAliasMap[&MF->getFunction()], [this](const GlobalAlias *Alias) { 1867 OutStreamer->emitLabel( 1868 getObjFileLowering().getFunctionEntryPointSymbol(Alias, TM)); 1869 }); 1870 } 1871 1872 void PPCAIXAsmPrinter::emitEndOfAsmFile(Module &M) { 1873 // If there are no functions in this module, we will never need to reference 1874 // the TOC base. 1875 if (M.empty()) 1876 return; 1877 1878 // Switch to section to emit TOC base. 1879 OutStreamer->SwitchSection(getObjFileLowering().getTOCBaseSection()); 1880 1881 PPCTargetStreamer *TS = 1882 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer()); 1883 1884 for (auto &I : TOC) { 1885 // Setup the csect for the current TC entry. 1886 MCSectionXCOFF *TCEntry = cast<MCSectionXCOFF>( 1887 getObjFileLowering().getSectionForTOCEntry(I.first, TM)); 1888 OutStreamer->SwitchSection(TCEntry); 1889 1890 OutStreamer->emitLabel(I.second); 1891 if (TS != nullptr) 1892 TS->emitTCEntry(*I.first); 1893 } 1894 } 1895 1896 bool PPCAIXAsmPrinter::doInitialization(Module &M) { 1897 const bool Result = PPCAsmPrinter::doInitialization(M); 1898 1899 auto setCsectAlignment = [this](const GlobalObject *GO) { 1900 // Declarations have 0 alignment which is set by default. 1901 if (GO->isDeclarationForLinker()) 1902 return; 1903 1904 SectionKind GOKind = getObjFileLowering().getKindForGlobal(GO, TM); 1905 MCSectionXCOFF *Csect = cast<MCSectionXCOFF>( 1906 getObjFileLowering().SectionForGlobal(GO, GOKind, TM)); 1907 1908 Align GOAlign = getGVAlignment(GO, GO->getParent()->getDataLayout()); 1909 if (GOAlign > Csect->getAlignment()) 1910 Csect->setAlignment(GOAlign); 1911 }; 1912 1913 // We need to know, up front, the alignment of csects for the assembly path, 1914 // because once a .csect directive gets emitted, we could not change the 1915 // alignment value on it. 1916 for (const auto &G : M.globals()) { 1917 if (isSpecialLLVMGlobalArrayToSkip(&G)) 1918 continue; 1919 1920 if (isSpecialLLVMGlobalArrayForStaticInit(&G)) { 1921 // Generate a format indicator and a unique module id to be a part of 1922 // the sinit and sterm function names. 1923 if (FormatIndicatorAndUniqueModId.empty()) { 1924 std::string UniqueModuleId = getUniqueModuleId(&M); 1925 if (UniqueModuleId.compare("") != 0) 1926 // TODO: Use source file full path to generate the unique module id 1927 // and add a format indicator as a part of function name in case we 1928 // will support more than one format. 1929 FormatIndicatorAndUniqueModId = "clang_" + UniqueModuleId.substr(1); 1930 else 1931 // Use the Pid and current time as the unique module id when we cannot 1932 // generate one based on a module's strong external symbols. 1933 // FIXME: Adjust the comment accordingly after we use source file full 1934 // path instead. 1935 FormatIndicatorAndUniqueModId = 1936 "clangPidTime_" + llvm::itostr(sys::Process::getProcessId()) + 1937 "_" + llvm::itostr(time(nullptr)); 1938 } 1939 1940 emitSpecialLLVMGlobal(&G); 1941 continue; 1942 } 1943 1944 setCsectAlignment(&G); 1945 } 1946 1947 for (const auto &F : M) 1948 setCsectAlignment(&F); 1949 1950 // Construct an aliasing list for each GlobalObject. 1951 for (const auto &Alias : M.aliases()) { 1952 const GlobalObject *Base = Alias.getBaseObject(); 1953 if (!Base) 1954 report_fatal_error( 1955 "alias without a base object is not yet supported on AIX"); 1956 GOAliasMap[Base].push_back(&Alias); 1957 } 1958 1959 return Result; 1960 } 1961 1962 void PPCAIXAsmPrinter::emitInstruction(const MachineInstr *MI) { 1963 switch (MI->getOpcode()) { 1964 default: 1965 break; 1966 case PPC::BL8: 1967 case PPC::BL: 1968 case PPC::BL8_NOP: 1969 case PPC::BL_NOP: { 1970 const MachineOperand &MO = MI->getOperand(0); 1971 if (MO.isSymbol()) { 1972 MCSymbolXCOFF *S = 1973 cast<MCSymbolXCOFF>(OutContext.getOrCreateSymbol(MO.getSymbolName())); 1974 ExtSymSDNodeSymbols.insert(S); 1975 } 1976 } break; 1977 case PPC::BL_TLS: 1978 case PPC::BL8_TLS: 1979 case PPC::BL8_TLS_: 1980 case PPC::BL8_NOP_TLS: 1981 report_fatal_error("TLS call not yet implemented"); 1982 case PPC::TAILB: 1983 case PPC::TAILB8: 1984 case PPC::TAILBA: 1985 case PPC::TAILBA8: 1986 case PPC::TAILBCTR: 1987 case PPC::TAILBCTR8: 1988 if (MI->getOperand(0).isSymbol()) 1989 report_fatal_error("Tail call for extern symbol not yet supported."); 1990 break; 1991 } 1992 return PPCAsmPrinter::emitInstruction(MI); 1993 } 1994 1995 bool PPCAIXAsmPrinter::doFinalization(Module &M) { 1996 for (MCSymbol *Sym : ExtSymSDNodeSymbols) 1997 OutStreamer->emitSymbolAttribute(Sym, MCSA_Extern); 1998 return PPCAsmPrinter::doFinalization(M); 1999 } 2000 2001 static unsigned mapToSinitPriority(int P) { 2002 if (P < 0 || P > 65535) 2003 report_fatal_error("invalid init priority"); 2004 2005 if (P <= 20) 2006 return P; 2007 2008 if (P < 81) 2009 return 20 + (P - 20) * 16; 2010 2011 if (P <= 1124) 2012 return 1004 + (P - 81); 2013 2014 if (P < 64512) 2015 return 2047 + (P - 1124) * 33878; 2016 2017 return 2147482625u + (P - 64512); 2018 } 2019 2020 static std::string convertToSinitPriority(int Priority) { 2021 // This helper function converts clang init priority to values used in sinit 2022 // and sterm functions. 2023 // 2024 // The conversion strategies are: 2025 // We map the reserved clang/gnu priority range [0, 100] into the sinit/sterm 2026 // reserved priority range [0, 1023] by 2027 // - directly mapping the first 21 and the last 20 elements of the ranges 2028 // - linear interpolating the intermediate values with a step size of 16. 2029 // 2030 // We map the non reserved clang/gnu priority range of [101, 65535] into the 2031 // sinit/sterm priority range [1024, 2147483648] by: 2032 // - directly mapping the first and the last 1024 elements of the ranges 2033 // - linear interpolating the intermediate values with a step size of 33878. 2034 unsigned int P = mapToSinitPriority(Priority); 2035 2036 std::string PrioritySuffix; 2037 llvm::raw_string_ostream os(PrioritySuffix); 2038 os << llvm::format_hex_no_prefix(P, 8); 2039 os.flush(); 2040 return PrioritySuffix; 2041 } 2042 2043 void PPCAIXAsmPrinter::emitXXStructorList(const DataLayout &DL, 2044 const Constant *List, bool IsCtor) { 2045 SmallVector<Structor, 8> Structors; 2046 preprocessXXStructorList(DL, List, Structors); 2047 if (Structors.empty()) 2048 return; 2049 2050 unsigned Index = 0; 2051 for (Structor &S : Structors) { 2052 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(S.Func)) 2053 S.Func = CE->getOperand(0); 2054 2055 llvm::GlobalAlias::create( 2056 GlobalValue::ExternalLinkage, 2057 (IsCtor ? llvm::Twine("__sinit") : llvm::Twine("__sterm")) + 2058 llvm::Twine(convertToSinitPriority(S.Priority)) + 2059 llvm::Twine("_", FormatIndicatorAndUniqueModId) + 2060 llvm::Twine("_", llvm::utostr(Index++)), 2061 cast<Function>(S.Func)); 2062 } 2063 } 2064 2065 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code 2066 /// for a MachineFunction to the given output stream, in a format that the 2067 /// Darwin assembler can deal with. 2068 /// 2069 static AsmPrinter * 2070 createPPCAsmPrinterPass(TargetMachine &tm, 2071 std::unique_ptr<MCStreamer> &&Streamer) { 2072 if (tm.getTargetTriple().isOSAIX()) 2073 return new PPCAIXAsmPrinter(tm, std::move(Streamer)); 2074 2075 return new PPCLinuxAsmPrinter(tm, std::move(Streamer)); 2076 } 2077 2078 // Force static initialization. 2079 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializePowerPCAsmPrinter() { 2080 TargetRegistry::RegisterAsmPrinter(getThePPC32Target(), 2081 createPPCAsmPrinterPass); 2082 TargetRegistry::RegisterAsmPrinter(getThePPC64Target(), 2083 createPPCAsmPrinterPass); 2084 TargetRegistry::RegisterAsmPrinter(getThePPC64LETarget(), 2085 createPPCAsmPrinterPass); 2086 } 2087