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