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