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 const Module *M = MF->getFunction().getParent(); 492 493 assert(MI->getOperand(0).isReg() && 494 ((Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::X3) || 495 (!Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::R3)) && 496 "GETtls[ld]ADDR[32] must define GPR3"); 497 assert(MI->getOperand(1).isReg() && 498 ((Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::X3) || 499 (!Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::R3)) && 500 "GETtls[ld]ADDR[32] must read GPR3"); 501 502 if (Subtarget->is32BitELFABI() && isPositionIndependent()) 503 Kind = MCSymbolRefExpr::VK_PLT; 504 505 const MCExpr *TlsRef = 506 MCSymbolRefExpr::create(TlsGetAddr, Kind, OutContext); 507 508 // Add 32768 offset to the symbol so we follow up the latest GOT/PLT ABI. 509 if (Kind == MCSymbolRefExpr::VK_PLT && Subtarget->isSecurePlt() && 510 M->getPICLevel() == PICLevel::BigPIC) 511 TlsRef = MCBinaryExpr::createAdd( 512 TlsRef, MCConstantExpr::create(32768, OutContext), OutContext); 513 const MachineOperand &MO = MI->getOperand(2); 514 const GlobalValue *GValue = MO.getGlobal(); 515 MCSymbol *MOSymbol = getSymbol(GValue); 516 const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, VK, OutContext); 517 EmitToStreamer(*OutStreamer, 518 MCInstBuilder(Subtarget->isPPC64() ? 519 PPC::BL8_NOP_TLS : PPC::BL_TLS) 520 .addExpr(TlsRef) 521 .addExpr(SymVar)); 522 } 523 524 /// Map a machine operand for a TOC pseudo-machine instruction to its 525 /// corresponding MCSymbol. 526 static MCSymbol *getMCSymbolForTOCPseudoMO(const MachineOperand &MO, 527 AsmPrinter &AP) { 528 switch (MO.getType()) { 529 case MachineOperand::MO_GlobalAddress: 530 return AP.getSymbol(MO.getGlobal()); 531 case MachineOperand::MO_ConstantPoolIndex: 532 return AP.GetCPISymbol(MO.getIndex()); 533 case MachineOperand::MO_JumpTableIndex: 534 return AP.GetJTISymbol(MO.getIndex()); 535 case MachineOperand::MO_BlockAddress: 536 return AP.GetBlockAddressSymbol(MO.getBlockAddress()); 537 default: 538 llvm_unreachable("Unexpected operand type to get symbol."); 539 } 540 } 541 542 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to 543 /// the current output stream. 544 /// 545 void PPCAsmPrinter::emitInstruction(const MachineInstr *MI) { 546 MCInst TmpInst; 547 const bool IsPPC64 = Subtarget->isPPC64(); 548 const bool IsAIX = Subtarget->isAIXABI(); 549 const Module *M = MF->getFunction().getParent(); 550 PICLevel::Level PL = M->getPICLevel(); 551 552 #ifndef NDEBUG 553 // Validate that SPE and FPU are mutually exclusive in codegen 554 if (!MI->isInlineAsm()) { 555 for (const MachineOperand &MO: MI->operands()) { 556 if (MO.isReg()) { 557 Register Reg = MO.getReg(); 558 if (Subtarget->hasSPE()) { 559 if (PPC::F4RCRegClass.contains(Reg) || 560 PPC::F8RCRegClass.contains(Reg) || 561 PPC::VFRCRegClass.contains(Reg) || 562 PPC::VRRCRegClass.contains(Reg) || 563 PPC::VSFRCRegClass.contains(Reg) || 564 PPC::VSSRCRegClass.contains(Reg) 565 ) 566 llvm_unreachable("SPE targets cannot have FPRegs!"); 567 } else { 568 if (PPC::SPERCRegClass.contains(Reg)) 569 llvm_unreachable("SPE register found in FPU-targeted code!"); 570 } 571 } 572 } 573 } 574 #endif 575 // Lower multi-instruction pseudo operations. 576 switch (MI->getOpcode()) { 577 default: break; 578 case TargetOpcode::DBG_VALUE: 579 llvm_unreachable("Should be handled target independently"); 580 case TargetOpcode::STACKMAP: 581 return LowerSTACKMAP(SM, *MI); 582 case TargetOpcode::PATCHPOINT: 583 return LowerPATCHPOINT(SM, *MI); 584 585 case PPC::MoveGOTtoLR: { 586 // Transform %lr = MoveGOTtoLR 587 // Into this: bl _GLOBAL_OFFSET_TABLE_@local-4 588 // _GLOBAL_OFFSET_TABLE_@local-4 (instruction preceding 589 // _GLOBAL_OFFSET_TABLE_) has exactly one instruction: 590 // blrl 591 // This will return the pointer to _GLOBAL_OFFSET_TABLE_@local 592 MCSymbol *GOTSymbol = 593 OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_")); 594 const MCExpr *OffsExpr = 595 MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol, 596 MCSymbolRefExpr::VK_PPC_LOCAL, 597 OutContext), 598 MCConstantExpr::create(4, OutContext), 599 OutContext); 600 601 // Emit the 'bl'. 602 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL).addExpr(OffsExpr)); 603 return; 604 } 605 case PPC::MovePCtoLR: 606 case PPC::MovePCtoLR8: { 607 // Transform %lr = MovePCtoLR 608 // Into this, where the label is the PIC base: 609 // bl L1$pb 610 // L1$pb: 611 MCSymbol *PICBase = MF->getPICBaseSymbol(); 612 613 // Emit the 'bl'. 614 EmitToStreamer(*OutStreamer, 615 MCInstBuilder(PPC::BL) 616 // FIXME: We would like an efficient form for this, so we 617 // don't have to do a lot of extra uniquing. 618 .addExpr(MCSymbolRefExpr::create(PICBase, OutContext))); 619 620 // Emit the label. 621 OutStreamer->emitLabel(PICBase); 622 return; 623 } 624 case PPC::UpdateGBR: { 625 // Transform %rd = UpdateGBR(%rt, %ri) 626 // Into: lwz %rt, .L0$poff - .L0$pb(%ri) 627 // add %rd, %rt, %ri 628 // or into (if secure plt mode is on): 629 // addis r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@ha 630 // addi r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@l 631 // Get the offset from the GOT Base Register to the GOT 632 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 633 if (Subtarget->isSecurePlt() && isPositionIndependent() ) { 634 unsigned PICR = TmpInst.getOperand(0).getReg(); 635 MCSymbol *BaseSymbol = OutContext.getOrCreateSymbol( 636 M->getPICLevel() == PICLevel::SmallPIC ? "_GLOBAL_OFFSET_TABLE_" 637 : ".LTOC"); 638 const MCExpr *PB = 639 MCSymbolRefExpr::create(MF->getPICBaseSymbol(), OutContext); 640 641 const MCExpr *DeltaExpr = MCBinaryExpr::createSub( 642 MCSymbolRefExpr::create(BaseSymbol, OutContext), PB, OutContext); 643 644 const MCExpr *DeltaHi = PPCMCExpr::createHa(DeltaExpr, OutContext); 645 EmitToStreamer( 646 *OutStreamer, 647 MCInstBuilder(PPC::ADDIS).addReg(PICR).addReg(PICR).addExpr(DeltaHi)); 648 649 const MCExpr *DeltaLo = PPCMCExpr::createLo(DeltaExpr, OutContext); 650 EmitToStreamer( 651 *OutStreamer, 652 MCInstBuilder(PPC::ADDI).addReg(PICR).addReg(PICR).addExpr(DeltaLo)); 653 return; 654 } else { 655 MCSymbol *PICOffset = 656 MF->getInfo<PPCFunctionInfo>()->getPICOffsetSymbol(*MF); 657 TmpInst.setOpcode(PPC::LWZ); 658 const MCExpr *Exp = 659 MCSymbolRefExpr::create(PICOffset, MCSymbolRefExpr::VK_None, OutContext); 660 const MCExpr *PB = 661 MCSymbolRefExpr::create(MF->getPICBaseSymbol(), 662 MCSymbolRefExpr::VK_None, 663 OutContext); 664 const MCOperand TR = TmpInst.getOperand(1); 665 const MCOperand PICR = TmpInst.getOperand(0); 666 667 // Step 1: lwz %rt, .L$poff - .L$pb(%ri) 668 TmpInst.getOperand(1) = 669 MCOperand::createExpr(MCBinaryExpr::createSub(Exp, PB, OutContext)); 670 TmpInst.getOperand(0) = TR; 671 TmpInst.getOperand(2) = PICR; 672 EmitToStreamer(*OutStreamer, TmpInst); 673 674 TmpInst.setOpcode(PPC::ADD4); 675 TmpInst.getOperand(0) = PICR; 676 TmpInst.getOperand(1) = TR; 677 TmpInst.getOperand(2) = PICR; 678 EmitToStreamer(*OutStreamer, TmpInst); 679 return; 680 } 681 } 682 case PPC::LWZtoc: { 683 // Transform %rN = LWZtoc @op1, %r2 684 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 685 686 // Change the opcode to LWZ. 687 TmpInst.setOpcode(PPC::LWZ); 688 689 const MachineOperand &MO = MI->getOperand(1); 690 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) && 691 "Invalid operand for LWZtoc."); 692 693 // Map the operand to its corresponding MCSymbol. 694 const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this); 695 696 // Create a reference to the GOT entry for the symbol. The GOT entry will be 697 // synthesized later. 698 if (PL == PICLevel::SmallPIC && !IsAIX) { 699 const MCExpr *Exp = 700 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_GOT, 701 OutContext); 702 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 703 EmitToStreamer(*OutStreamer, TmpInst); 704 return; 705 } 706 707 // Otherwise, use the TOC. 'TOCEntry' is a label used to reference the 708 // storage allocated in the TOC which contains the address of 709 // 'MOSymbol'. Said TOC entry will be synthesized later. 710 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol); 711 const MCExpr *Exp = 712 MCSymbolRefExpr::create(TOCEntry, MCSymbolRefExpr::VK_None, OutContext); 713 714 // AIX uses the label directly as the lwz displacement operand for 715 // references into the toc section. The displacement value will be generated 716 // relative to the toc-base. 717 if (IsAIX) { 718 assert( 719 TM.getCodeModel() == CodeModel::Small && 720 "This pseudo should only be selected for 32-bit small code model."); 721 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 722 EmitToStreamer(*OutStreamer, TmpInst); 723 return; 724 } 725 726 // Create an explicit subtract expression between the local symbol and 727 // '.LTOC' to manifest the toc-relative offset. 728 const MCExpr *PB = MCSymbolRefExpr::create( 729 OutContext.getOrCreateSymbol(Twine(".LTOC")), OutContext); 730 Exp = MCBinaryExpr::createSub(Exp, PB, OutContext); 731 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 732 EmitToStreamer(*OutStreamer, TmpInst); 733 return; 734 } 735 case PPC::LDtocJTI: 736 case PPC::LDtocCPT: 737 case PPC::LDtocBA: 738 case PPC::LDtoc: { 739 // Transform %x3 = LDtoc @min1, %x2 740 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 741 742 // Change the opcode to LD. 743 TmpInst.setOpcode(PPC::LD); 744 745 const MachineOperand &MO = MI->getOperand(1); 746 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) && 747 "Invalid operand!"); 748 749 // Map the machine operand to its corresponding MCSymbol, then map the 750 // global address operand to be a reference to the TOC entry we will 751 // synthesize later. 752 MCSymbol *TOCEntry = 753 lookUpOrCreateTOCEntry(getMCSymbolForTOCPseudoMO(MO, *this)); 754 755 const MCSymbolRefExpr::VariantKind VK = 756 IsAIX ? MCSymbolRefExpr::VK_None : MCSymbolRefExpr::VK_PPC_TOC; 757 const MCExpr *Exp = 758 MCSymbolRefExpr::create(TOCEntry, VK, OutContext); 759 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 760 EmitToStreamer(*OutStreamer, TmpInst); 761 return; 762 } 763 case PPC::ADDIStocHA: { 764 assert((IsAIX && !IsPPC64 && TM.getCodeModel() == CodeModel::Large) && 765 "This pseudo should only be selected for 32-bit large code model on" 766 " AIX."); 767 768 // Transform %rd = ADDIStocHA %rA, @sym(%r2) 769 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 770 771 // Change the opcode to ADDIS. 772 TmpInst.setOpcode(PPC::ADDIS); 773 774 const MachineOperand &MO = MI->getOperand(2); 775 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) && 776 "Invalid operand for ADDIStocHA."); 777 778 // Map the machine operand to its corresponding MCSymbol. 779 MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this); 780 781 // Always use TOC on AIX. Map the global address operand to be a reference 782 // to the TOC entry we will synthesize later. 'TOCEntry' is a label used to 783 // reference the storage allocated in the TOC which contains the address of 784 // 'MOSymbol'. 785 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol); 786 const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry, 787 MCSymbolRefExpr::VK_PPC_U, 788 OutContext); 789 TmpInst.getOperand(2) = MCOperand::createExpr(Exp); 790 EmitToStreamer(*OutStreamer, TmpInst); 791 return; 792 } 793 case PPC::LWZtocL: { 794 assert(IsAIX && !IsPPC64 && TM.getCodeModel() == CodeModel::Large && 795 "This pseudo should only be selected for 32-bit large code model on" 796 " AIX."); 797 798 // Transform %rd = LWZtocL @sym, %rs. 799 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 800 801 // Change the opcode to lwz. 802 TmpInst.setOpcode(PPC::LWZ); 803 804 const MachineOperand &MO = MI->getOperand(1); 805 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) && 806 "Invalid operand for LWZtocL."); 807 808 // Map the machine operand to its corresponding MCSymbol. 809 MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this); 810 811 // Always use TOC on AIX. Map the global address operand to be a reference 812 // to the TOC entry we will synthesize later. 'TOCEntry' is a label used to 813 // reference the storage allocated in the TOC which contains the address of 814 // 'MOSymbol'. 815 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol); 816 const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry, 817 MCSymbolRefExpr::VK_PPC_L, 818 OutContext); 819 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 820 EmitToStreamer(*OutStreamer, TmpInst); 821 return; 822 } 823 case PPC::ADDIStocHA8: { 824 // Transform %xd = ADDIStocHA8 %x2, @sym 825 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 826 827 // Change the opcode to ADDIS8. If the global address is the address of 828 // an external symbol, is a jump table address, is a block address, or is a 829 // constant pool index with large code model enabled, then generate a TOC 830 // entry and reference that. Otherwise, reference the symbol directly. 831 TmpInst.setOpcode(PPC::ADDIS8); 832 833 const MachineOperand &MO = MI->getOperand(2); 834 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) && 835 "Invalid operand for ADDIStocHA8!"); 836 837 const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this); 838 839 const bool GlobalToc = 840 MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal()); 841 if (GlobalToc || MO.isJTI() || MO.isBlockAddress() || 842 (MO.isCPI() && TM.getCodeModel() == CodeModel::Large)) 843 MOSymbol = lookUpOrCreateTOCEntry(MOSymbol); 844 845 const MCSymbolRefExpr::VariantKind VK = 846 IsAIX ? MCSymbolRefExpr::VK_PPC_U : MCSymbolRefExpr::VK_PPC_TOC_HA; 847 848 const MCExpr *Exp = 849 MCSymbolRefExpr::create(MOSymbol, VK, OutContext); 850 851 if (!MO.isJTI() && MO.getOffset()) 852 Exp = MCBinaryExpr::createAdd(Exp, 853 MCConstantExpr::create(MO.getOffset(), 854 OutContext), 855 OutContext); 856 857 TmpInst.getOperand(2) = MCOperand::createExpr(Exp); 858 EmitToStreamer(*OutStreamer, TmpInst); 859 return; 860 } 861 case PPC::LDtocL: { 862 // Transform %xd = LDtocL @sym, %xs 863 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 864 865 // Change the opcode to LD. If the global address is the address of 866 // an external symbol, is a jump table address, is a block address, or is 867 // a constant pool index with large code model enabled, then generate a 868 // TOC entry and reference that. Otherwise, reference the symbol directly. 869 TmpInst.setOpcode(PPC::LD); 870 871 const MachineOperand &MO = MI->getOperand(1); 872 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || 873 MO.isBlockAddress()) && 874 "Invalid operand for LDtocL!"); 875 876 LLVM_DEBUG(assert( 877 (!MO.isGlobal() || Subtarget->isGVIndirectSymbol(MO.getGlobal())) && 878 "LDtocL used on symbol that could be accessed directly is " 879 "invalid. Must match ADDIStocHA8.")); 880 881 const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this); 882 883 if (!MO.isCPI() || TM.getCodeModel() == CodeModel::Large) 884 MOSymbol = lookUpOrCreateTOCEntry(MOSymbol); 885 886 const MCSymbolRefExpr::VariantKind VK = 887 IsAIX ? MCSymbolRefExpr::VK_PPC_L : MCSymbolRefExpr::VK_PPC_TOC_LO; 888 const MCExpr *Exp = 889 MCSymbolRefExpr::create(MOSymbol, VK, OutContext); 890 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 891 EmitToStreamer(*OutStreamer, TmpInst); 892 return; 893 } 894 case PPC::ADDItocL: { 895 // Transform %xd = ADDItocL %xs, @sym 896 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 897 898 // Change the opcode to ADDI8. If the global address is external, then 899 // generate a TOC entry and reference that. Otherwise, reference the 900 // symbol directly. 901 TmpInst.setOpcode(PPC::ADDI8); 902 903 const MachineOperand &MO = MI->getOperand(2); 904 assert((MO.isGlobal() || MO.isCPI()) && "Invalid operand for ADDItocL."); 905 906 LLVM_DEBUG(assert( 907 !(MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal())) && 908 "Interposable definitions must use indirect access.")); 909 910 const MCExpr *Exp = 911 MCSymbolRefExpr::create(getMCSymbolForTOCPseudoMO(MO, *this), 912 MCSymbolRefExpr::VK_PPC_TOC_LO, OutContext); 913 TmpInst.getOperand(2) = MCOperand::createExpr(Exp); 914 EmitToStreamer(*OutStreamer, TmpInst); 915 return; 916 } 917 case PPC::ADDISgotTprelHA: { 918 // Transform: %xd = ADDISgotTprelHA %x2, @sym 919 // Into: %xd = ADDIS8 %x2, sym@got@tlsgd@ha 920 assert(IsPPC64 && "Not supported for 32-bit PowerPC"); 921 const MachineOperand &MO = MI->getOperand(2); 922 const GlobalValue *GValue = MO.getGlobal(); 923 MCSymbol *MOSymbol = getSymbol(GValue); 924 const MCExpr *SymGotTprel = 925 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA, 926 OutContext); 927 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8) 928 .addReg(MI->getOperand(0).getReg()) 929 .addReg(MI->getOperand(1).getReg()) 930 .addExpr(SymGotTprel)); 931 return; 932 } 933 case PPC::LDgotTprelL: 934 case PPC::LDgotTprelL32: { 935 // Transform %xd = LDgotTprelL @sym, %xs 936 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 937 938 // Change the opcode to LD. 939 TmpInst.setOpcode(IsPPC64 ? PPC::LD : PPC::LWZ); 940 const MachineOperand &MO = MI->getOperand(1); 941 const GlobalValue *GValue = MO.getGlobal(); 942 MCSymbol *MOSymbol = getSymbol(GValue); 943 const MCExpr *Exp = MCSymbolRefExpr::create( 944 MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO 945 : MCSymbolRefExpr::VK_PPC_GOT_TPREL, 946 OutContext); 947 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 948 EmitToStreamer(*OutStreamer, TmpInst); 949 return; 950 } 951 952 case PPC::PPC32PICGOT: { 953 MCSymbol *GOTSymbol = OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_")); 954 MCSymbol *GOTRef = OutContext.createTempSymbol(); 955 MCSymbol *NextInstr = OutContext.createTempSymbol(); 956 957 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL) 958 // FIXME: We would like an efficient form for this, so we don't have to do 959 // a lot of extra uniquing. 960 .addExpr(MCSymbolRefExpr::create(NextInstr, OutContext))); 961 const MCExpr *OffsExpr = 962 MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol, OutContext), 963 MCSymbolRefExpr::create(GOTRef, OutContext), 964 OutContext); 965 OutStreamer->emitLabel(GOTRef); 966 OutStreamer->emitValue(OffsExpr, 4); 967 OutStreamer->emitLabel(NextInstr); 968 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR) 969 .addReg(MI->getOperand(0).getReg())); 970 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LWZ) 971 .addReg(MI->getOperand(1).getReg()) 972 .addImm(0) 973 .addReg(MI->getOperand(0).getReg())); 974 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD4) 975 .addReg(MI->getOperand(0).getReg()) 976 .addReg(MI->getOperand(1).getReg()) 977 .addReg(MI->getOperand(0).getReg())); 978 return; 979 } 980 case PPC::PPC32GOT: { 981 MCSymbol *GOTSymbol = 982 OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_")); 983 const MCExpr *SymGotTlsL = MCSymbolRefExpr::create( 984 GOTSymbol, MCSymbolRefExpr::VK_PPC_LO, OutContext); 985 const MCExpr *SymGotTlsHA = MCSymbolRefExpr::create( 986 GOTSymbol, MCSymbolRefExpr::VK_PPC_HA, OutContext); 987 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI) 988 .addReg(MI->getOperand(0).getReg()) 989 .addExpr(SymGotTlsL)); 990 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS) 991 .addReg(MI->getOperand(0).getReg()) 992 .addReg(MI->getOperand(0).getReg()) 993 .addExpr(SymGotTlsHA)); 994 return; 995 } 996 case PPC::ADDIStlsgdHA: { 997 // Transform: %xd = ADDIStlsgdHA %x2, @sym 998 // Into: %xd = ADDIS8 %x2, sym@got@tlsgd@ha 999 assert(IsPPC64 && "Not supported for 32-bit PowerPC"); 1000 const MachineOperand &MO = MI->getOperand(2); 1001 const GlobalValue *GValue = MO.getGlobal(); 1002 MCSymbol *MOSymbol = getSymbol(GValue); 1003 const MCExpr *SymGotTlsGD = 1004 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA, 1005 OutContext); 1006 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8) 1007 .addReg(MI->getOperand(0).getReg()) 1008 .addReg(MI->getOperand(1).getReg()) 1009 .addExpr(SymGotTlsGD)); 1010 return; 1011 } 1012 case PPC::ADDItlsgdL: 1013 // Transform: %xd = ADDItlsgdL %xs, @sym 1014 // Into: %xd = ADDI8 %xs, sym@got@tlsgd@l 1015 case PPC::ADDItlsgdL32: { 1016 // Transform: %rd = ADDItlsgdL32 %rs, @sym 1017 // Into: %rd = ADDI %rs, sym@got@tlsgd 1018 const MachineOperand &MO = MI->getOperand(2); 1019 const GlobalValue *GValue = MO.getGlobal(); 1020 MCSymbol *MOSymbol = getSymbol(GValue); 1021 const MCExpr *SymGotTlsGD = MCSymbolRefExpr::create( 1022 MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO 1023 : MCSymbolRefExpr::VK_PPC_GOT_TLSGD, 1024 OutContext); 1025 EmitToStreamer(*OutStreamer, 1026 MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI) 1027 .addReg(MI->getOperand(0).getReg()) 1028 .addReg(MI->getOperand(1).getReg()) 1029 .addExpr(SymGotTlsGD)); 1030 return; 1031 } 1032 case PPC::GETtlsADDR: 1033 // Transform: %x3 = GETtlsADDR %x3, @sym 1034 // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsgd) 1035 case PPC::GETtlsADDR32: { 1036 // Transform: %r3 = GETtlsADDR32 %r3, @sym 1037 // Into: BL_TLS __tls_get_addr(sym at tlsgd)@PLT 1038 EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSGD); 1039 return; 1040 } 1041 case PPC::ADDIStlsldHA: { 1042 // Transform: %xd = ADDIStlsldHA %x2, @sym 1043 // Into: %xd = ADDIS8 %x2, sym@got@tlsld@ha 1044 assert(IsPPC64 && "Not supported for 32-bit PowerPC"); 1045 const MachineOperand &MO = MI->getOperand(2); 1046 const GlobalValue *GValue = MO.getGlobal(); 1047 MCSymbol *MOSymbol = getSymbol(GValue); 1048 const MCExpr *SymGotTlsLD = 1049 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA, 1050 OutContext); 1051 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8) 1052 .addReg(MI->getOperand(0).getReg()) 1053 .addReg(MI->getOperand(1).getReg()) 1054 .addExpr(SymGotTlsLD)); 1055 return; 1056 } 1057 case PPC::ADDItlsldL: 1058 // Transform: %xd = ADDItlsldL %xs, @sym 1059 // Into: %xd = ADDI8 %xs, sym@got@tlsld@l 1060 case PPC::ADDItlsldL32: { 1061 // Transform: %rd = ADDItlsldL32 %rs, @sym 1062 // Into: %rd = ADDI %rs, sym@got@tlsld 1063 const MachineOperand &MO = MI->getOperand(2); 1064 const GlobalValue *GValue = MO.getGlobal(); 1065 MCSymbol *MOSymbol = getSymbol(GValue); 1066 const MCExpr *SymGotTlsLD = MCSymbolRefExpr::create( 1067 MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO 1068 : MCSymbolRefExpr::VK_PPC_GOT_TLSLD, 1069 OutContext); 1070 EmitToStreamer(*OutStreamer, 1071 MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI) 1072 .addReg(MI->getOperand(0).getReg()) 1073 .addReg(MI->getOperand(1).getReg()) 1074 .addExpr(SymGotTlsLD)); 1075 return; 1076 } 1077 case PPC::GETtlsldADDR: 1078 // Transform: %x3 = GETtlsldADDR %x3, @sym 1079 // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsld) 1080 case PPC::GETtlsldADDR32: { 1081 // Transform: %r3 = GETtlsldADDR32 %r3, @sym 1082 // Into: BL_TLS __tls_get_addr(sym at tlsld)@PLT 1083 EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSLD); 1084 return; 1085 } 1086 case PPC::ADDISdtprelHA: 1087 // Transform: %xd = ADDISdtprelHA %xs, @sym 1088 // Into: %xd = ADDIS8 %xs, sym@dtprel@ha 1089 case PPC::ADDISdtprelHA32: { 1090 // Transform: %rd = ADDISdtprelHA32 %rs, @sym 1091 // Into: %rd = ADDIS %rs, sym@dtprel@ha 1092 const MachineOperand &MO = MI->getOperand(2); 1093 const GlobalValue *GValue = MO.getGlobal(); 1094 MCSymbol *MOSymbol = getSymbol(GValue); 1095 const MCExpr *SymDtprel = 1096 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_HA, 1097 OutContext); 1098 EmitToStreamer( 1099 *OutStreamer, 1100 MCInstBuilder(IsPPC64 ? PPC::ADDIS8 : PPC::ADDIS) 1101 .addReg(MI->getOperand(0).getReg()) 1102 .addReg(MI->getOperand(1).getReg()) 1103 .addExpr(SymDtprel)); 1104 return; 1105 } 1106 case PPC::ADDIdtprelL: 1107 // Transform: %xd = ADDIdtprelL %xs, @sym 1108 // Into: %xd = ADDI8 %xs, sym@dtprel@l 1109 case PPC::ADDIdtprelL32: { 1110 // Transform: %rd = ADDIdtprelL32 %rs, @sym 1111 // Into: %rd = ADDI %rs, sym@dtprel@l 1112 const MachineOperand &MO = MI->getOperand(2); 1113 const GlobalValue *GValue = MO.getGlobal(); 1114 MCSymbol *MOSymbol = getSymbol(GValue); 1115 const MCExpr *SymDtprel = 1116 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_LO, 1117 OutContext); 1118 EmitToStreamer(*OutStreamer, 1119 MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI) 1120 .addReg(MI->getOperand(0).getReg()) 1121 .addReg(MI->getOperand(1).getReg()) 1122 .addExpr(SymDtprel)); 1123 return; 1124 } 1125 case PPC::MFOCRF: 1126 case PPC::MFOCRF8: 1127 if (!Subtarget->hasMFOCRF()) { 1128 // Transform: %r3 = MFOCRF %cr7 1129 // Into: %r3 = MFCR ;; cr7 1130 unsigned NewOpcode = 1131 MI->getOpcode() == PPC::MFOCRF ? PPC::MFCR : PPC::MFCR8; 1132 OutStreamer->AddComment(PPCInstPrinter:: 1133 getRegisterName(MI->getOperand(1).getReg())); 1134 EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode) 1135 .addReg(MI->getOperand(0).getReg())); 1136 return; 1137 } 1138 break; 1139 case PPC::MTOCRF: 1140 case PPC::MTOCRF8: 1141 if (!Subtarget->hasMFOCRF()) { 1142 // Transform: %cr7 = MTOCRF %r3 1143 // Into: MTCRF mask, %r3 ;; cr7 1144 unsigned NewOpcode = 1145 MI->getOpcode() == PPC::MTOCRF ? PPC::MTCRF : PPC::MTCRF8; 1146 unsigned Mask = 0x80 >> OutContext.getRegisterInfo() 1147 ->getEncodingValue(MI->getOperand(0).getReg()); 1148 OutStreamer->AddComment(PPCInstPrinter:: 1149 getRegisterName(MI->getOperand(0).getReg())); 1150 EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode) 1151 .addImm(Mask) 1152 .addReg(MI->getOperand(1).getReg())); 1153 return; 1154 } 1155 break; 1156 case PPC::LD: 1157 case PPC::STD: 1158 case PPC::LWA_32: 1159 case PPC::LWA: { 1160 // Verify alignment is legal, so we don't create relocations 1161 // that can't be supported. 1162 // FIXME: This test is currently disabled for Darwin. The test 1163 // suite shows a handful of test cases that fail this check for 1164 // Darwin. Those need to be investigated before this sanity test 1165 // can be enabled for those subtargets. 1166 unsigned OpNum = (MI->getOpcode() == PPC::STD) ? 2 : 1; 1167 const MachineOperand &MO = MI->getOperand(OpNum); 1168 if (MO.isGlobal()) { 1169 const DataLayout &DL = MO.getGlobal()->getParent()->getDataLayout(); 1170 if (MO.getGlobal()->getPointerAlignment(DL) < 4) 1171 llvm_unreachable("Global must be word-aligned for LD, STD, LWA!"); 1172 } 1173 // Now process the instruction normally. 1174 break; 1175 } 1176 } 1177 1178 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 1179 EmitToStreamer(*OutStreamer, TmpInst); 1180 } 1181 1182 void PPCLinuxAsmPrinter::emitInstruction(const MachineInstr *MI) { 1183 if (!Subtarget->isPPC64()) 1184 return PPCAsmPrinter::emitInstruction(MI); 1185 1186 switch (MI->getOpcode()) { 1187 default: 1188 return PPCAsmPrinter::emitInstruction(MI); 1189 case TargetOpcode::PATCHABLE_FUNCTION_ENTER: { 1190 // .begin: 1191 // b .end # lis 0, FuncId[16..32] 1192 // nop # li 0, FuncId[0..15] 1193 // std 0, -8(1) 1194 // mflr 0 1195 // bl __xray_FunctionEntry 1196 // mtlr 0 1197 // .end: 1198 // 1199 // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number 1200 // of instructions change. 1201 MCSymbol *BeginOfSled = OutContext.createTempSymbol(); 1202 MCSymbol *EndOfSled = OutContext.createTempSymbol(); 1203 OutStreamer->emitLabel(BeginOfSled); 1204 EmitToStreamer(*OutStreamer, 1205 MCInstBuilder(PPC::B).addExpr( 1206 MCSymbolRefExpr::create(EndOfSled, OutContext))); 1207 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP)); 1208 EmitToStreamer( 1209 *OutStreamer, 1210 MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1)); 1211 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0)); 1212 EmitToStreamer(*OutStreamer, 1213 MCInstBuilder(PPC::BL8_NOP) 1214 .addExpr(MCSymbolRefExpr::create( 1215 OutContext.getOrCreateSymbol("__xray_FunctionEntry"), 1216 OutContext))); 1217 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0)); 1218 OutStreamer->emitLabel(EndOfSled); 1219 recordSled(BeginOfSled, *MI, SledKind::FUNCTION_ENTER, 2); 1220 break; 1221 } 1222 case TargetOpcode::PATCHABLE_RET: { 1223 unsigned RetOpcode = MI->getOperand(0).getImm(); 1224 MCInst RetInst; 1225 RetInst.setOpcode(RetOpcode); 1226 for (const auto &MO : 1227 make_range(std::next(MI->operands_begin()), MI->operands_end())) { 1228 MCOperand MCOp; 1229 if (LowerPPCMachineOperandToMCOperand(MO, MCOp, *this)) 1230 RetInst.addOperand(MCOp); 1231 } 1232 1233 bool IsConditional; 1234 if (RetOpcode == PPC::BCCLR) { 1235 IsConditional = true; 1236 } else if (RetOpcode == PPC::TCRETURNdi8 || RetOpcode == PPC::TCRETURNri8 || 1237 RetOpcode == PPC::TCRETURNai8) { 1238 break; 1239 } else if (RetOpcode == PPC::BLR8 || RetOpcode == PPC::TAILB8) { 1240 IsConditional = false; 1241 } else { 1242 EmitToStreamer(*OutStreamer, RetInst); 1243 break; 1244 } 1245 1246 MCSymbol *FallthroughLabel; 1247 if (IsConditional) { 1248 // Before: 1249 // bgtlr cr0 1250 // 1251 // After: 1252 // ble cr0, .end 1253 // .p2align 3 1254 // .begin: 1255 // blr # lis 0, FuncId[16..32] 1256 // nop # li 0, FuncId[0..15] 1257 // std 0, -8(1) 1258 // mflr 0 1259 // bl __xray_FunctionExit 1260 // mtlr 0 1261 // blr 1262 // .end: 1263 // 1264 // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number 1265 // of instructions change. 1266 FallthroughLabel = OutContext.createTempSymbol(); 1267 EmitToStreamer( 1268 *OutStreamer, 1269 MCInstBuilder(PPC::BCC) 1270 .addImm(PPC::InvertPredicate( 1271 static_cast<PPC::Predicate>(MI->getOperand(1).getImm()))) 1272 .addReg(MI->getOperand(2).getReg()) 1273 .addExpr(MCSymbolRefExpr::create(FallthroughLabel, OutContext))); 1274 RetInst = MCInst(); 1275 RetInst.setOpcode(PPC::BLR8); 1276 } 1277 // .p2align 3 1278 // .begin: 1279 // b(lr)? # lis 0, FuncId[16..32] 1280 // nop # li 0, FuncId[0..15] 1281 // std 0, -8(1) 1282 // mflr 0 1283 // bl __xray_FunctionExit 1284 // mtlr 0 1285 // b(lr)? 1286 // 1287 // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number 1288 // of instructions change. 1289 OutStreamer->emitCodeAlignment(8); 1290 MCSymbol *BeginOfSled = OutContext.createTempSymbol(); 1291 OutStreamer->emitLabel(BeginOfSled); 1292 EmitToStreamer(*OutStreamer, RetInst); 1293 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP)); 1294 EmitToStreamer( 1295 *OutStreamer, 1296 MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1)); 1297 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0)); 1298 EmitToStreamer(*OutStreamer, 1299 MCInstBuilder(PPC::BL8_NOP) 1300 .addExpr(MCSymbolRefExpr::create( 1301 OutContext.getOrCreateSymbol("__xray_FunctionExit"), 1302 OutContext))); 1303 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0)); 1304 EmitToStreamer(*OutStreamer, RetInst); 1305 if (IsConditional) 1306 OutStreamer->emitLabel(FallthroughLabel); 1307 recordSled(BeginOfSled, *MI, SledKind::FUNCTION_EXIT, 2); 1308 break; 1309 } 1310 case TargetOpcode::PATCHABLE_FUNCTION_EXIT: 1311 llvm_unreachable("PATCHABLE_FUNCTION_EXIT should never be emitted"); 1312 case TargetOpcode::PATCHABLE_TAIL_CALL: 1313 // TODO: Define a trampoline `__xray_FunctionTailExit` and differentiate a 1314 // normal function exit from a tail exit. 1315 llvm_unreachable("Tail call is handled in the normal case. See comments " 1316 "around this assert."); 1317 } 1318 } 1319 1320 void PPCLinuxAsmPrinter::emitStartOfAsmFile(Module &M) { 1321 if (static_cast<const PPCTargetMachine &>(TM).isELFv2ABI()) { 1322 PPCTargetStreamer *TS = 1323 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer()); 1324 1325 if (TS) 1326 TS->emitAbiVersion(2); 1327 } 1328 1329 if (static_cast<const PPCTargetMachine &>(TM).isPPC64() || 1330 !isPositionIndependent()) 1331 return AsmPrinter::emitStartOfAsmFile(M); 1332 1333 if (M.getPICLevel() == PICLevel::SmallPIC) 1334 return AsmPrinter::emitStartOfAsmFile(M); 1335 1336 OutStreamer->SwitchSection(OutContext.getELFSection( 1337 ".got2", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC)); 1338 1339 MCSymbol *TOCSym = OutContext.getOrCreateSymbol(Twine(".LTOC")); 1340 MCSymbol *CurrentPos = OutContext.createTempSymbol(); 1341 1342 OutStreamer->emitLabel(CurrentPos); 1343 1344 // The GOT pointer points to the middle of the GOT, in order to reference the 1345 // entire 64kB range. 0x8000 is the midpoint. 1346 const MCExpr *tocExpr = 1347 MCBinaryExpr::createAdd(MCSymbolRefExpr::create(CurrentPos, OutContext), 1348 MCConstantExpr::create(0x8000, OutContext), 1349 OutContext); 1350 1351 OutStreamer->emitAssignment(TOCSym, tocExpr); 1352 1353 OutStreamer->SwitchSection(getObjFileLowering().getTextSection()); 1354 } 1355 1356 void PPCLinuxAsmPrinter::emitFunctionEntryLabel() { 1357 // linux/ppc32 - Normal entry label. 1358 if (!Subtarget->isPPC64() && 1359 (!isPositionIndependent() || 1360 MF->getFunction().getParent()->getPICLevel() == PICLevel::SmallPIC)) 1361 return AsmPrinter::emitFunctionEntryLabel(); 1362 1363 if (!Subtarget->isPPC64()) { 1364 const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>(); 1365 if (PPCFI->usesPICBase() && !Subtarget->isSecurePlt()) { 1366 MCSymbol *RelocSymbol = PPCFI->getPICOffsetSymbol(*MF); 1367 MCSymbol *PICBase = MF->getPICBaseSymbol(); 1368 OutStreamer->emitLabel(RelocSymbol); 1369 1370 const MCExpr *OffsExpr = 1371 MCBinaryExpr::createSub( 1372 MCSymbolRefExpr::create(OutContext.getOrCreateSymbol(Twine(".LTOC")), 1373 OutContext), 1374 MCSymbolRefExpr::create(PICBase, OutContext), 1375 OutContext); 1376 OutStreamer->emitValue(OffsExpr, 4); 1377 OutStreamer->emitLabel(CurrentFnSym); 1378 return; 1379 } else 1380 return AsmPrinter::emitFunctionEntryLabel(); 1381 } 1382 1383 // ELFv2 ABI - Normal entry label. 1384 if (Subtarget->isELFv2ABI()) { 1385 // In the Large code model, we allow arbitrary displacements between 1386 // the text section and its associated TOC section. We place the 1387 // full 8-byte offset to the TOC in memory immediately preceding 1388 // the function global entry point. 1389 if (TM.getCodeModel() == CodeModel::Large 1390 && !MF->getRegInfo().use_empty(PPC::X2)) { 1391 const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>(); 1392 1393 MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC.")); 1394 MCSymbol *GlobalEPSymbol = PPCFI->getGlobalEPSymbol(*MF); 1395 const MCExpr *TOCDeltaExpr = 1396 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext), 1397 MCSymbolRefExpr::create(GlobalEPSymbol, 1398 OutContext), 1399 OutContext); 1400 1401 OutStreamer->emitLabel(PPCFI->getTOCOffsetSymbol(*MF)); 1402 OutStreamer->emitValue(TOCDeltaExpr, 8); 1403 } 1404 return AsmPrinter::emitFunctionEntryLabel(); 1405 } 1406 1407 // Emit an official procedure descriptor. 1408 MCSectionSubPair Current = OutStreamer->getCurrentSection(); 1409 MCSectionELF *Section = OutStreamer->getContext().getELFSection( 1410 ".opd", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC); 1411 OutStreamer->SwitchSection(Section); 1412 OutStreamer->emitLabel(CurrentFnSym); 1413 OutStreamer->emitValueToAlignment(8); 1414 MCSymbol *Symbol1 = CurrentFnSymForSize; 1415 // Generates a R_PPC64_ADDR64 (from FK_DATA_8) relocation for the function 1416 // entry point. 1417 OutStreamer->emitValue(MCSymbolRefExpr::create(Symbol1, OutContext), 1418 8 /*size*/); 1419 MCSymbol *Symbol2 = OutContext.getOrCreateSymbol(StringRef(".TOC.")); 1420 // Generates a R_PPC64_TOC relocation for TOC base insertion. 1421 OutStreamer->emitValue( 1422 MCSymbolRefExpr::create(Symbol2, MCSymbolRefExpr::VK_PPC_TOCBASE, OutContext), 1423 8/*size*/); 1424 // Emit a null environment pointer. 1425 OutStreamer->emitIntValue(0, 8 /* size */); 1426 OutStreamer->SwitchSection(Current.first, Current.second); 1427 } 1428 1429 void PPCLinuxAsmPrinter::emitEndOfAsmFile(Module &M) { 1430 const DataLayout &DL = getDataLayout(); 1431 1432 bool isPPC64 = DL.getPointerSizeInBits() == 64; 1433 1434 PPCTargetStreamer *TS = 1435 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer()); 1436 1437 if (!TOC.empty()) { 1438 const char *Name = isPPC64 ? ".toc" : ".got2"; 1439 MCSectionELF *Section = OutContext.getELFSection( 1440 Name, ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC); 1441 OutStreamer->SwitchSection(Section); 1442 if (!isPPC64) 1443 OutStreamer->emitValueToAlignment(4); 1444 1445 for (const auto &TOCMapPair : TOC) { 1446 const MCSymbol *const TOCEntryTarget = TOCMapPair.first; 1447 MCSymbol *const TOCEntryLabel = TOCMapPair.second; 1448 1449 OutStreamer->emitLabel(TOCEntryLabel); 1450 if (isPPC64 && TS != nullptr) 1451 TS->emitTCEntry(*TOCEntryTarget); 1452 else 1453 OutStreamer->emitSymbolValue(TOCEntryTarget, 4); 1454 } 1455 } 1456 1457 PPCAsmPrinter::emitEndOfAsmFile(M); 1458 } 1459 1460 /// EmitFunctionBodyStart - Emit a global entry point prefix for ELFv2. 1461 void PPCLinuxAsmPrinter::emitFunctionBodyStart() { 1462 // In the ELFv2 ABI, in functions that use the TOC register, we need to 1463 // provide two entry points. The ABI guarantees that when calling the 1464 // local entry point, r2 is set up by the caller to contain the TOC base 1465 // for this function, and when calling the global entry point, r12 is set 1466 // up by the caller to hold the address of the global entry point. We 1467 // thus emit a prefix sequence along the following lines: 1468 // 1469 // func: 1470 // .Lfunc_gepNN: 1471 // # global entry point 1472 // addis r2,r12,(.TOC.-.Lfunc_gepNN)@ha 1473 // addi r2,r2,(.TOC.-.Lfunc_gepNN)@l 1474 // .Lfunc_lepNN: 1475 // .localentry func, .Lfunc_lepNN-.Lfunc_gepNN 1476 // # local entry point, followed by function body 1477 // 1478 // For the Large code model, we create 1479 // 1480 // .Lfunc_tocNN: 1481 // .quad .TOC.-.Lfunc_gepNN # done by EmitFunctionEntryLabel 1482 // func: 1483 // .Lfunc_gepNN: 1484 // # global entry point 1485 // ld r2,.Lfunc_tocNN-.Lfunc_gepNN(r12) 1486 // add r2,r2,r12 1487 // .Lfunc_lepNN: 1488 // .localentry func, .Lfunc_lepNN-.Lfunc_gepNN 1489 // # local entry point, followed by function body 1490 // 1491 // This ensures we have r2 set up correctly while executing the function 1492 // body, no matter which entry point is called. 1493 const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>(); 1494 const bool UsesX2OrR2 = !MF->getRegInfo().use_empty(PPC::X2) || 1495 !MF->getRegInfo().use_empty(PPC::R2); 1496 const bool PCrelGEPRequired = Subtarget->isUsingPCRelativeCalls() && 1497 UsesX2OrR2 && PPCFI->usesTOCBasePtr(); 1498 const bool NonPCrelGEPRequired = !Subtarget->isUsingPCRelativeCalls() && 1499 Subtarget->isELFv2ABI() && UsesX2OrR2; 1500 1501 // Only do all that if the function uses R2 as the TOC pointer 1502 // in the first place. We don't need the global entry point if the 1503 // function uses R2 as an allocatable register. 1504 if (NonPCrelGEPRequired || PCrelGEPRequired) { 1505 // Note: The logic here must be synchronized with the code in the 1506 // branch-selection pass which sets the offset of the first block in the 1507 // function. This matters because it affects the alignment. 1508 MCSymbol *GlobalEntryLabel = PPCFI->getGlobalEPSymbol(*MF); 1509 OutStreamer->emitLabel(GlobalEntryLabel); 1510 const MCSymbolRefExpr *GlobalEntryLabelExp = 1511 MCSymbolRefExpr::create(GlobalEntryLabel, OutContext); 1512 1513 if (TM.getCodeModel() != CodeModel::Large) { 1514 MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC.")); 1515 const MCExpr *TOCDeltaExpr = 1516 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext), 1517 GlobalEntryLabelExp, OutContext); 1518 1519 const MCExpr *TOCDeltaHi = PPCMCExpr::createHa(TOCDeltaExpr, OutContext); 1520 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS) 1521 .addReg(PPC::X2) 1522 .addReg(PPC::X12) 1523 .addExpr(TOCDeltaHi)); 1524 1525 const MCExpr *TOCDeltaLo = PPCMCExpr::createLo(TOCDeltaExpr, OutContext); 1526 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDI) 1527 .addReg(PPC::X2) 1528 .addReg(PPC::X2) 1529 .addExpr(TOCDeltaLo)); 1530 } else { 1531 MCSymbol *TOCOffset = PPCFI->getTOCOffsetSymbol(*MF); 1532 const MCExpr *TOCOffsetDeltaExpr = 1533 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCOffset, OutContext), 1534 GlobalEntryLabelExp, OutContext); 1535 1536 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD) 1537 .addReg(PPC::X2) 1538 .addExpr(TOCOffsetDeltaExpr) 1539 .addReg(PPC::X12)); 1540 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD8) 1541 .addReg(PPC::X2) 1542 .addReg(PPC::X2) 1543 .addReg(PPC::X12)); 1544 } 1545 1546 MCSymbol *LocalEntryLabel = PPCFI->getLocalEPSymbol(*MF); 1547 OutStreamer->emitLabel(LocalEntryLabel); 1548 const MCSymbolRefExpr *LocalEntryLabelExp = 1549 MCSymbolRefExpr::create(LocalEntryLabel, OutContext); 1550 const MCExpr *LocalOffsetExp = 1551 MCBinaryExpr::createSub(LocalEntryLabelExp, 1552 GlobalEntryLabelExp, OutContext); 1553 1554 PPCTargetStreamer *TS = 1555 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer()); 1556 1557 if (TS) 1558 TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym), LocalOffsetExp); 1559 } else if (Subtarget->isUsingPCRelativeCalls()) { 1560 // When generating the entry point for a function we have a few scenarios 1561 // based on whether or not that function uses R2 and whether or not that 1562 // function makes calls (or is a leaf function). 1563 // 1) A leaf function that does not use R2 (or treats it as callee-saved 1564 // and preserves it). In this case st_other=0 and both 1565 // the local and global entry points for the function are the same. 1566 // No special entry point code is required. 1567 // 2) A function uses the TOC pointer R2. This function may or may not have 1568 // calls. In this case st_other=[2,6] and the global and local entry 1569 // points are different. Code to correctly setup the TOC pointer in R2 1570 // is put between the global and local entry points. This case is 1571 // covered by the if statatement above. 1572 // 3) A function does not use the TOC pointer R2 but does have calls. 1573 // In this case st_other=1 since we do not know whether or not any 1574 // of the callees clobber R2. This case is dealt with in this else if 1575 // block. Tail calls are considered calls and the st_other should also 1576 // be set to 1 in that case as well. 1577 // 4) The function does not use the TOC pointer but R2 is used inside 1578 // the function. In this case st_other=1 once again. 1579 // 5) This function uses inline asm. We mark R2 as reserved if the function 1580 // has inline asm as we have to assume that it may be used. 1581 if (MF->getFrameInfo().hasCalls() || MF->getFrameInfo().hasTailCall() || 1582 MF->hasInlineAsm() || (!PPCFI->usesTOCBasePtr() && UsesX2OrR2)) { 1583 PPCTargetStreamer *TS = 1584 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer()); 1585 if (TS) 1586 TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym), 1587 MCConstantExpr::create(1, OutContext)); 1588 } 1589 } 1590 } 1591 1592 /// EmitFunctionBodyEnd - Print the traceback table before the .size 1593 /// directive. 1594 /// 1595 void PPCLinuxAsmPrinter::emitFunctionBodyEnd() { 1596 // Only the 64-bit target requires a traceback table. For now, 1597 // we only emit the word of zeroes that GDB requires to find 1598 // the end of the function, and zeroes for the eight-byte 1599 // mandatory fields. 1600 // FIXME: We should fill in the eight-byte mandatory fields as described in 1601 // the PPC64 ELF ABI (this is a low-priority item because GDB does not 1602 // currently make use of these fields). 1603 if (Subtarget->isPPC64()) { 1604 OutStreamer->emitIntValue(0, 4/*size*/); 1605 OutStreamer->emitIntValue(0, 8/*size*/); 1606 } 1607 } 1608 1609 void PPCAIXAsmPrinter::emitLinkage(const GlobalValue *GV, 1610 MCSymbol *GVSym) const { 1611 1612 assert(MAI->hasVisibilityOnlyWithLinkage() && 1613 "AIX's linkage directives take a visibility setting."); 1614 1615 MCSymbolAttr LinkageAttr = MCSA_Invalid; 1616 switch (GV->getLinkage()) { 1617 case GlobalValue::ExternalLinkage: 1618 LinkageAttr = GV->isDeclaration() ? MCSA_Extern : MCSA_Global; 1619 break; 1620 case GlobalValue::LinkOnceAnyLinkage: 1621 case GlobalValue::LinkOnceODRLinkage: 1622 case GlobalValue::WeakAnyLinkage: 1623 case GlobalValue::WeakODRLinkage: 1624 case GlobalValue::ExternalWeakLinkage: 1625 LinkageAttr = MCSA_Weak; 1626 break; 1627 case GlobalValue::AvailableExternallyLinkage: 1628 LinkageAttr = MCSA_Extern; 1629 break; 1630 case GlobalValue::PrivateLinkage: 1631 return; 1632 case GlobalValue::InternalLinkage: 1633 assert(GV->getVisibility() == GlobalValue::DefaultVisibility && 1634 "InternalLinkage should not have other visibility setting."); 1635 LinkageAttr = MCSA_LGlobal; 1636 break; 1637 case GlobalValue::AppendingLinkage: 1638 llvm_unreachable("Should never emit this"); 1639 case GlobalValue::CommonLinkage: 1640 llvm_unreachable("CommonLinkage of XCOFF should not come to this path"); 1641 } 1642 1643 assert(LinkageAttr != MCSA_Invalid && "LinkageAttr should not MCSA_Invalid."); 1644 1645 MCSymbolAttr VisibilityAttr = MCSA_Invalid; 1646 switch (GV->getVisibility()) { 1647 1648 // TODO: "exported" and "internal" Visibility needs to go here. 1649 case GlobalValue::DefaultVisibility: 1650 break; 1651 case GlobalValue::HiddenVisibility: 1652 VisibilityAttr = MAI->getHiddenVisibilityAttr(); 1653 break; 1654 case GlobalValue::ProtectedVisibility: 1655 VisibilityAttr = MAI->getProtectedVisibilityAttr(); 1656 break; 1657 } 1658 1659 OutStreamer->emitXCOFFSymbolLinkageWithVisibility(GVSym, LinkageAttr, 1660 VisibilityAttr); 1661 } 1662 1663 void PPCAIXAsmPrinter::SetupMachineFunction(MachineFunction &MF) { 1664 // Setup CurrentFnDescSym and its containing csect. 1665 MCSectionXCOFF *FnDescSec = 1666 cast<MCSectionXCOFF>(getObjFileLowering().getSectionForFunctionDescriptor( 1667 &MF.getFunction(), TM)); 1668 FnDescSec->setAlignment(Align(Subtarget->isPPC64() ? 8 : 4)); 1669 1670 CurrentFnDescSym = FnDescSec->getQualNameSymbol(); 1671 1672 return AsmPrinter::SetupMachineFunction(MF); 1673 } 1674 1675 void PPCAIXAsmPrinter::ValidateGV(const GlobalVariable *GV) { 1676 // Early error checking limiting what is supported. 1677 if (GV->isThreadLocal()) 1678 report_fatal_error("Thread local not yet supported on AIX."); 1679 1680 if (GV->hasSection()) 1681 report_fatal_error("Custom section for Data not yet supported."); 1682 1683 if (GV->hasComdat()) 1684 report_fatal_error("COMDAT not yet supported by AIX."); 1685 } 1686 1687 static bool isSpecialLLVMGlobalArrayToSkip(const GlobalVariable *GV) { 1688 return GV->hasAppendingLinkage() && 1689 StringSwitch<bool>(GV->getName()) 1690 // TODO: Linker could still eliminate the GV if we just skip 1691 // handling llvm.used array. Skipping them for now until we or the 1692 // AIX OS team come up with a good solution. 1693 .Case("llvm.used", true) 1694 // It's correct to just skip llvm.compiler.used array here. 1695 .Case("llvm.compiler.used", true) 1696 .Default(false); 1697 } 1698 1699 static bool isSpecialLLVMGlobalArrayForStaticInit(const GlobalVariable *GV) { 1700 return StringSwitch<bool>(GV->getName()) 1701 .Cases("llvm.global_ctors", "llvm.global_dtors", true) 1702 .Default(false); 1703 } 1704 1705 void PPCAIXAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) { 1706 // Special LLVM global arrays have been handled at the initialization. 1707 if (isSpecialLLVMGlobalArrayToSkip(GV) || isSpecialLLVMGlobalArrayForStaticInit(GV)) 1708 return; 1709 1710 assert(!GV->getName().startswith("llvm.") && 1711 "Unhandled intrinsic global variable."); 1712 ValidateGV(GV); 1713 1714 MCSymbolXCOFF *GVSym = cast<MCSymbolXCOFF>(getSymbol(GV)); 1715 1716 if (GV->isDeclarationForLinker()) { 1717 emitLinkage(GV, GVSym); 1718 return; 1719 } 1720 1721 SectionKind GVKind = getObjFileLowering().getKindForGlobal(GV, TM); 1722 if (!GVKind.isGlobalWriteableData() && !GVKind.isReadOnly()) 1723 report_fatal_error("Encountered a global variable kind that is " 1724 "not supported yet."); 1725 1726 MCSectionXCOFF *Csect = cast<MCSectionXCOFF>( 1727 getObjFileLowering().SectionForGlobal(GV, GVKind, TM)); 1728 1729 // Switch to the containing csect. 1730 OutStreamer->SwitchSection(Csect); 1731 1732 const DataLayout &DL = GV->getParent()->getDataLayout(); 1733 1734 // Handle common symbols. 1735 if (GVKind.isCommon() || GVKind.isBSSLocal()) { 1736 Align Alignment = GV->getAlign().getValueOr(DL.getPreferredAlign(GV)); 1737 uint64_t Size = DL.getTypeAllocSize(GV->getType()->getElementType()); 1738 GVSym->setStorageClass( 1739 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GV)); 1740 1741 if (GVKind.isBSSLocal()) 1742 OutStreamer->emitXCOFFLocalCommonSymbol( 1743 OutContext.getOrCreateSymbol(GVSym->getUnqualifiedName()), Size, 1744 GVSym, Alignment.value()); 1745 else 1746 OutStreamer->emitCommonSymbol(GVSym, Size, Alignment.value()); 1747 return; 1748 } 1749 1750 MCSymbol *EmittedInitSym = GVSym; 1751 emitLinkage(GV, EmittedInitSym); 1752 emitAlignment(getGVAlignment(GV, DL), GV); 1753 OutStreamer->emitLabel(EmittedInitSym); 1754 // Emit aliasing label for global variable. 1755 llvm::for_each(GOAliasMap[GV], [this](const GlobalAlias *Alias) { 1756 OutStreamer->emitLabel(getSymbol(Alias)); 1757 }); 1758 emitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer()); 1759 } 1760 1761 void PPCAIXAsmPrinter::emitFunctionDescriptor() { 1762 const DataLayout &DL = getDataLayout(); 1763 const unsigned PointerSize = DL.getPointerSizeInBits() == 64 ? 8 : 4; 1764 1765 MCSectionSubPair Current = OutStreamer->getCurrentSection(); 1766 // Emit function descriptor. 1767 OutStreamer->SwitchSection( 1768 cast<MCSymbolXCOFF>(CurrentFnDescSym)->getRepresentedCsect()); 1769 1770 // Emit aliasing label for function descriptor csect. 1771 llvm::for_each(GOAliasMap[&MF->getFunction()], 1772 [this](const GlobalAlias *Alias) { 1773 OutStreamer->emitLabel(getSymbol(Alias)); 1774 }); 1775 1776 // Emit function entry point address. 1777 OutStreamer->emitValue(MCSymbolRefExpr::create(CurrentFnSym, OutContext), 1778 PointerSize); 1779 // Emit TOC base address. 1780 const MCSymbol *TOCBaseSym = 1781 cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection()) 1782 ->getQualNameSymbol(); 1783 OutStreamer->emitValue(MCSymbolRefExpr::create(TOCBaseSym, OutContext), 1784 PointerSize); 1785 // Emit a null environment pointer. 1786 OutStreamer->emitIntValue(0, PointerSize); 1787 1788 OutStreamer->SwitchSection(Current.first, Current.second); 1789 } 1790 1791 void PPCAIXAsmPrinter::emitFunctionEntryLabel() { 1792 // It's not necessary to emit the label when we have individual 1793 // function in its own csect. 1794 if (!TM.getFunctionSections()) 1795 PPCAsmPrinter::emitFunctionEntryLabel(); 1796 1797 // Emit aliasing label for function entry point label. 1798 llvm::for_each( 1799 GOAliasMap[&MF->getFunction()], [this](const GlobalAlias *Alias) { 1800 OutStreamer->emitLabel( 1801 getObjFileLowering().getFunctionEntryPointSymbol(Alias, TM)); 1802 }); 1803 } 1804 1805 void PPCAIXAsmPrinter::emitEndOfAsmFile(Module &M) { 1806 // If there are no functions in this module, we will never need to reference 1807 // the TOC base. 1808 if (M.empty()) 1809 return; 1810 1811 // Switch to section to emit TOC base. 1812 OutStreamer->SwitchSection(getObjFileLowering().getTOCBaseSection()); 1813 1814 PPCTargetStreamer *TS = 1815 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer()); 1816 1817 const unsigned EntryByteSize = Subtarget->isPPC64() ? 8 : 4; 1818 const unsigned TOCEntriesByteSize = TOC.size() * EntryByteSize; 1819 // TODO: If TOC entries' size is larger than 32768, then we run out of 1820 // positive displacement to reach the TOC entry. We need to decide how to 1821 // handle entries' size larger than that later. 1822 if (TOCEntriesByteSize > 32767) { 1823 report_fatal_error("Handling of TOC entry displacement larger than 32767 " 1824 "is not yet implemented."); 1825 } 1826 1827 for (auto &I : TOC) { 1828 // Setup the csect for the current TC entry. 1829 MCSectionXCOFF *TCEntry = cast<MCSectionXCOFF>( 1830 getObjFileLowering().getSectionForTOCEntry(I.first, TM)); 1831 OutStreamer->SwitchSection(TCEntry); 1832 1833 OutStreamer->emitLabel(I.second); 1834 if (TS != nullptr) 1835 TS->emitTCEntry(*I.first); 1836 } 1837 } 1838 1839 bool PPCAIXAsmPrinter::doInitialization(Module &M) { 1840 const bool Result = PPCAsmPrinter::doInitialization(M); 1841 1842 auto setCsectAlignment = [this](const GlobalObject *GO) { 1843 // Declarations have 0 alignment which is set by default. 1844 if (GO->isDeclarationForLinker()) 1845 return; 1846 1847 SectionKind GOKind = getObjFileLowering().getKindForGlobal(GO, TM); 1848 MCSectionXCOFF *Csect = cast<MCSectionXCOFF>( 1849 getObjFileLowering().SectionForGlobal(GO, GOKind, TM)); 1850 1851 Align GOAlign = getGVAlignment(GO, GO->getParent()->getDataLayout()); 1852 if (GOAlign > Csect->getAlignment()) 1853 Csect->setAlignment(GOAlign); 1854 }; 1855 1856 // We need to know, up front, the alignment of csects for the assembly path, 1857 // because once a .csect directive gets emitted, we could not change the 1858 // alignment value on it. 1859 for (const auto &G : M.globals()) { 1860 if (isSpecialLLVMGlobalArrayToSkip(&G)) 1861 continue; 1862 1863 if (isSpecialLLVMGlobalArrayForStaticInit(&G)) { 1864 // Generate a format indicator and a unique module id to be a part of 1865 // the sinit and sterm function names. 1866 if (FormatIndicatorAndUniqueModId.empty()) { 1867 std::string UniqueModuleId = getUniqueModuleId(&M); 1868 if (UniqueModuleId.compare("") != 0) 1869 // TODO: Use source file full path to generate the unique module id 1870 // and add a format indicator as a part of function name in case we 1871 // will support more than one format. 1872 FormatIndicatorAndUniqueModId = "clang_" + UniqueModuleId.substr(1); 1873 else 1874 // Use the Pid and current time as the unique module id when we cannot 1875 // generate one based on a module's strong external symbols. 1876 // FIXME: Adjust the comment accordingly after we use source file full 1877 // path instead. 1878 FormatIndicatorAndUniqueModId = 1879 "clangPidTime_" + llvm::itostr(sys::Process::getProcessId()) + 1880 "_" + llvm::itostr(time(nullptr)); 1881 } 1882 1883 emitSpecialLLVMGlobal(&G); 1884 continue; 1885 } 1886 1887 setCsectAlignment(&G); 1888 } 1889 1890 for (const auto &F : M) 1891 setCsectAlignment(&F); 1892 1893 // Construct an aliasing list for each GlobalObject. 1894 for (const auto &Alias : M.aliases()) { 1895 const GlobalObject *Base = Alias.getBaseObject(); 1896 if (!Base) 1897 report_fatal_error( 1898 "alias without a base object is not yet supported on AIX"); 1899 GOAliasMap[Base].push_back(&Alias); 1900 } 1901 1902 return Result; 1903 } 1904 1905 void PPCAIXAsmPrinter::emitInstruction(const MachineInstr *MI) { 1906 switch (MI->getOpcode()) { 1907 default: 1908 break; 1909 case PPC::BL8: 1910 case PPC::BL: 1911 case PPC::BL8_NOP: 1912 case PPC::BL_NOP: { 1913 const MachineOperand &MO = MI->getOperand(0); 1914 if (MO.isSymbol()) { 1915 MCSymbolXCOFF *S = 1916 cast<MCSymbolXCOFF>(OutContext.getOrCreateSymbol(MO.getSymbolName())); 1917 ExtSymSDNodeSymbols.insert(S); 1918 } 1919 } break; 1920 case PPC::BL_TLS: 1921 case PPC::BL8_TLS: 1922 case PPC::BL8_TLS_: 1923 case PPC::BL8_NOP_TLS: 1924 report_fatal_error("TLS call not yet implemented"); 1925 case PPC::TAILB: 1926 case PPC::TAILB8: 1927 case PPC::TAILBA: 1928 case PPC::TAILBA8: 1929 case PPC::TAILBCTR: 1930 case PPC::TAILBCTR8: 1931 if (MI->getOperand(0).isSymbol()) 1932 report_fatal_error("Tail call for extern symbol not yet supported."); 1933 break; 1934 } 1935 return PPCAsmPrinter::emitInstruction(MI); 1936 } 1937 1938 bool PPCAIXAsmPrinter::doFinalization(Module &M) { 1939 for (MCSymbol *Sym : ExtSymSDNodeSymbols) 1940 OutStreamer->emitSymbolAttribute(Sym, MCSA_Extern); 1941 return PPCAsmPrinter::doFinalization(M); 1942 } 1943 1944 void PPCAIXAsmPrinter::emitXXStructorList(const DataLayout &DL, 1945 const Constant *List, bool IsCtor) { 1946 SmallVector<Structor, 8> Structors; 1947 preprocessXXStructorList(DL, List, Structors); 1948 if (Structors.empty()) 1949 return; 1950 1951 unsigned Index = 0; 1952 for (Structor &S : Structors) { 1953 if (S.Priority != 65535) 1954 report_fatal_error( 1955 "prioritized sinit and sterm functions are not yet supported on AIX"); 1956 1957 llvm::GlobalAlias::create( 1958 GlobalValue::ExternalLinkage, 1959 (IsCtor ? llvm::Twine("__sinit") : llvm::Twine("__sterm")) + 1960 llvm::Twine("80000000_", FormatIndicatorAndUniqueModId) + 1961 llvm::Twine("_", llvm::utostr(Index++)), 1962 cast<Function>(S.Func)); 1963 } 1964 } 1965 1966 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code 1967 /// for a MachineFunction to the given output stream, in a format that the 1968 /// Darwin assembler can deal with. 1969 /// 1970 static AsmPrinter * 1971 createPPCAsmPrinterPass(TargetMachine &tm, 1972 std::unique_ptr<MCStreamer> &&Streamer) { 1973 if (tm.getTargetTriple().isOSAIX()) 1974 return new PPCAIXAsmPrinter(tm, std::move(Streamer)); 1975 1976 return new PPCLinuxAsmPrinter(tm, std::move(Streamer)); 1977 } 1978 1979 // Force static initialization. 1980 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializePowerPCAsmPrinter() { 1981 TargetRegistry::RegisterAsmPrinter(getThePPC32Target(), 1982 createPPCAsmPrinterPass); 1983 TargetRegistry::RegisterAsmPrinter(getThePPC64Target(), 1984 createPPCAsmPrinterPass); 1985 TargetRegistry::RegisterAsmPrinter(getThePPC64LETarget(), 1986 createPPCAsmPrinterPass); 1987 } 1988