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