1 //===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly ------===//
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
7 //===----------------------------------------------------------------------===//
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'.
13 // Documentation at http://developer.apple.com/documentation/DeveloperTools/
14 // Reference/Assembler/ASMIntroduction/chapter_1_section_1.html
16 //===----------------------------------------------------------------------===//
18 #include "MCTargetDesc/PPCInstPrinter.h"
19 #include "MCTargetDesc/PPCMCExpr.h"
20 #include "MCTargetDesc/PPCMCTargetDesc.h"
21 #include "MCTargetDesc/PPCPredicates.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/StringRef.h"
31 #include "llvm/ADT/Triple.h"
32 #include "llvm/ADT/Twine.h"
33 #include "llvm/BinaryFormat/ELF.h"
34 #include "llvm/BinaryFormat/MachO.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/MCExpr.h"
51 #include "llvm/MC/MCInst.h"
52 #include "llvm/MC/MCInstBuilder.h"
53 #include "llvm/MC/MCSectionELF.h"
54 #include "llvm/MC/MCSectionMachO.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/TargetRegistry.h"
66 #include "llvm/Support/raw_ostream.h"
67 #include "llvm/Target/TargetMachine.h"
76 #define DEBUG_TYPE "asmprinter"
80 class PPCAsmPrinter : public AsmPrinter {
82 MapVector<const MCSymbol *, MCSymbol *> TOC;
83 const PPCSubtarget *Subtarget = nullptr;
87 explicit PPCAsmPrinter(TargetMachine &TM,
88 std::unique_ptr<MCStreamer> Streamer)
89 : AsmPrinter(TM, std::move(Streamer)), SM(*this) {}
91 StringRef getPassName() const override { return "PowerPC Assembly Printer"; }
93 MCSymbol *lookUpOrCreateTOCEntry(const MCSymbol *Sym);
95 bool doInitialization(Module &M) override {
98 return AsmPrinter::doInitialization(M);
101 void emitInstruction(const MachineInstr *MI) override;
103 /// This function is for PrintAsmOperand and PrintAsmMemoryOperand,
104 /// invoked by EmitMSInlineAsmStr and EmitGCCInlineAsmStr only.
105 /// The \p MI would be INLINEASM ONLY.
106 void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O);
108 void PrintSymbolOperand(const MachineOperand &MO, raw_ostream &O) override;
109 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
110 const char *ExtraCode, raw_ostream &O) override;
111 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
112 const char *ExtraCode, raw_ostream &O) override;
114 void emitEndOfAsmFile(Module &M) override;
116 void LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI);
117 void LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI);
118 void EmitTlsCall(const MachineInstr *MI, MCSymbolRefExpr::VariantKind VK);
119 bool runOnMachineFunction(MachineFunction &MF) override {
120 Subtarget = &MF.getSubtarget<PPCSubtarget>();
121 bool Changed = AsmPrinter::runOnMachineFunction(MF);
127 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
128 class PPCLinuxAsmPrinter : public PPCAsmPrinter {
130 explicit PPCLinuxAsmPrinter(TargetMachine &TM,
131 std::unique_ptr<MCStreamer> Streamer)
132 : PPCAsmPrinter(TM, std::move(Streamer)) {}
134 StringRef getPassName() const override {
135 return "Linux PPC Assembly Printer";
138 void emitStartOfAsmFile(Module &M) override;
139 void emitEndOfAsmFile(Module &) override;
141 void emitFunctionEntryLabel() override;
143 void emitFunctionBodyStart() override;
144 void emitFunctionBodyEnd() override;
145 void emitInstruction(const MachineInstr *MI) override;
148 class PPCAIXAsmPrinter : public PPCAsmPrinter {
150 static void ValidateGV(const GlobalVariable *GV);
153 PPCAIXAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
154 : PPCAsmPrinter(TM, std::move(Streamer)) {
155 if (MAI->isLittleEndian())
157 "cannot create AIX PPC Assembly Printer for a little-endian target");
160 StringRef getPassName() const override { return "AIX PPC Assembly Printer"; }
162 bool doInitialization(Module &M) override;
164 void SetupMachineFunction(MachineFunction &MF) override;
166 void emitGlobalVariable(const GlobalVariable *GV) override;
168 void emitFunctionDescriptor() override;
170 void emitEndOfAsmFile(Module &) override;
172 void emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const override;
175 } // end anonymous namespace
177 void PPCAsmPrinter::PrintSymbolOperand(const MachineOperand &MO,
179 // Computing the address of a global symbol, not calling it.
180 const GlobalValue *GV = MO.getGlobal();
181 getSymbol(GV)->print(O, MAI);
182 printOffset(MO.getOffset(), O);
185 void PPCAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
187 const DataLayout &DL = getDataLayout();
188 const MachineOperand &MO = MI->getOperand(OpNo);
190 switch (MO.getType()) {
191 case MachineOperand::MO_Register: {
192 // The MI is INLINEASM ONLY and UseVSXReg is always false.
193 const char *RegName = PPCInstPrinter::getRegisterName(MO.getReg());
195 // Linux assembler (Others?) does not take register mnemonics.
196 // FIXME - What about special registers used in mfspr/mtspr?
197 O << PPCRegisterInfo::stripRegisterPrefix(RegName);
200 case MachineOperand::MO_Immediate:
204 case MachineOperand::MO_MachineBasicBlock:
205 MO.getMBB()->getSymbol()->print(O, MAI);
207 case MachineOperand::MO_ConstantPoolIndex:
208 O << DL.getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
211 case MachineOperand::MO_BlockAddress:
212 GetBlockAddressSymbol(MO.getBlockAddress())->print(O, MAI);
214 case MachineOperand::MO_GlobalAddress: {
215 PrintSymbolOperand(MO, O);
220 O << "<unknown operand type: " << (unsigned)MO.getType() << ">";
225 /// PrintAsmOperand - Print out an operand for an inline asm expression.
227 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
228 const char *ExtraCode, raw_ostream &O) {
229 // Does this asm operand have a single letter operand modifier?
230 if (ExtraCode && ExtraCode[0]) {
231 if (ExtraCode[1] != 0) return true; // Unknown modifier.
233 switch (ExtraCode[0]) {
235 // See if this is a generic print operand
236 return AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, O);
237 case 'L': // Write second word of DImode reference.
238 // Verify that this operand has two consecutive registers.
239 if (!MI->getOperand(OpNo).isReg() ||
240 OpNo+1 == MI->getNumOperands() ||
241 !MI->getOperand(OpNo+1).isReg())
243 ++OpNo; // Return the high-part.
246 // Write 'i' if an integer constant, otherwise nothing. Used to print
248 if (MI->getOperand(OpNo).isImm())
252 if(!MI->getOperand(OpNo).isReg())
254 // This operand uses VSX numbering.
255 // If the operand is a VMX register, convert it to a VSX register.
256 Register Reg = MI->getOperand(OpNo).getReg();
257 if (PPCInstrInfo::isVRRegister(Reg))
258 Reg = PPC::VSX32 + (Reg - PPC::V0);
259 else if (PPCInstrInfo::isVFRegister(Reg))
260 Reg = PPC::VSX32 + (Reg - PPC::VF0);
262 RegName = PPCInstPrinter::getRegisterName(Reg);
263 RegName = PPCRegisterInfo::stripRegisterPrefix(RegName);
269 printOperand(MI, OpNo, O);
273 // At the moment, all inline asm memory operands are a single register.
274 // In any case, the output of this routine should always be just one
275 // assembler operand.
277 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
278 const char *ExtraCode,
280 if (ExtraCode && ExtraCode[0]) {
281 if (ExtraCode[1] != 0) return true; // Unknown modifier.
283 switch (ExtraCode[0]) {
284 default: return true; // Unknown modifier.
285 case 'L': // A memory reference to the upper word of a double word op.
286 O << getDataLayout().getPointerSize() << "(";
287 printOperand(MI, OpNo, O);
290 case 'y': // A memory reference for an X-form instruction
292 printOperand(MI, OpNo, O);
294 case 'U': // Print 'u' for update form.
295 case 'X': // Print 'x' for indexed form.
296 // FIXME: Currently for PowerPC memory operands are always loaded
297 // into a register, so we never get an update or indexed form.
298 // This is bad even for offset forms, since even if we know we
299 // have a value in -16(r1), we will generate a load into r<n>
300 // and then load from 0(r<n>). Until that issue is fixed,
301 // tolerate 'U' and 'X' but don't output anything.
302 assert(MI->getOperand(OpNo).isReg());
307 assert(MI->getOperand(OpNo).isReg());
309 printOperand(MI, OpNo, O);
314 /// lookUpOrCreateTOCEntry -- Given a symbol, look up whether a TOC entry
315 /// exists for it. If not, create one. Then return a symbol that references
317 MCSymbol *PPCAsmPrinter::lookUpOrCreateTOCEntry(const MCSymbol *Sym) {
318 MCSymbol *&TOCEntry = TOC[Sym];
320 TOCEntry = createTempSymbol("C");
324 void PPCAsmPrinter::emitEndOfAsmFile(Module &M) {
328 void PPCAsmPrinter::LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI) {
329 unsigned NumNOPBytes = MI.getOperand(1).getImm();
331 auto &Ctx = OutStreamer->getContext();
332 MCSymbol *MILabel = Ctx.createTempSymbol();
333 OutStreamer->emitLabel(MILabel);
335 SM.recordStackMap(*MILabel, MI);
336 assert(NumNOPBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
338 // Scan ahead to trim the shadow.
339 const MachineBasicBlock &MBB = *MI.getParent();
340 MachineBasicBlock::const_iterator MII(MI);
342 while (NumNOPBytes > 0) {
343 if (MII == MBB.end() || MII->isCall() ||
344 MII->getOpcode() == PPC::DBG_VALUE ||
345 MII->getOpcode() == TargetOpcode::PATCHPOINT ||
346 MII->getOpcode() == TargetOpcode::STACKMAP)
353 for (unsigned i = 0; i < NumNOPBytes; i += 4)
354 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
357 // Lower a patchpoint of the form:
358 // [<def>], <id>, <numBytes>, <target>, <numArgs>
359 void PPCAsmPrinter::LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI) {
360 auto &Ctx = OutStreamer->getContext();
361 MCSymbol *MILabel = Ctx.createTempSymbol();
362 OutStreamer->emitLabel(MILabel);
364 SM.recordPatchPoint(*MILabel, MI);
365 PatchPointOpers Opers(&MI);
367 unsigned EncodedBytes = 0;
368 const MachineOperand &CalleeMO = Opers.getCallTarget();
370 if (CalleeMO.isImm()) {
371 int64_t CallTarget = CalleeMO.getImm();
373 assert((CallTarget & 0xFFFFFFFFFFFF) == CallTarget &&
374 "High 16 bits of call target should be zero.");
375 Register ScratchReg = MI.getOperand(Opers.getNextScratchIdx()).getReg();
377 // Materialize the jump address:
378 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI8)
380 .addImm((CallTarget >> 32) & 0xFFFF));
382 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::RLDIC)
385 .addImm(32).addImm(16));
387 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORIS8)
390 .addImm((CallTarget >> 16) & 0xFFFF));
392 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORI8)
395 .addImm(CallTarget & 0xFFFF));
397 // Save the current TOC pointer before the remote call.
398 int TOCSaveOffset = Subtarget->getFrameLowering()->getTOCSaveOffset();
399 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::STD)
401 .addImm(TOCSaveOffset)
405 // If we're on ELFv1, then we need to load the actual function pointer
406 // from the function descriptor.
407 if (!Subtarget->isELFv2ABI()) {
408 // Load the new TOC pointer and the function address, but not r11
409 // (needing this is rare, and loading it here would prevent passing it
410 // via a 'nest' parameter.
411 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
414 .addReg(ScratchReg));
416 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
419 .addReg(ScratchReg));
423 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTCTR8)
424 .addReg(ScratchReg));
426 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BCTRL8));
429 // Restore the TOC pointer after the call.
430 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
432 .addImm(TOCSaveOffset)
436 } else if (CalleeMO.isGlobal()) {
437 const GlobalValue *GValue = CalleeMO.getGlobal();
438 MCSymbol *MOSymbol = getSymbol(GValue);
439 const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, OutContext);
441 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL8_NOP)
446 // Each instruction is 4 bytes.
450 unsigned NumBytes = Opers.getNumPatchBytes();
451 assert(NumBytes >= EncodedBytes &&
452 "Patchpoint can't request size less than the length of a call.");
453 assert((NumBytes - EncodedBytes) % 4 == 0 &&
454 "Invalid number of NOP bytes requested!");
455 for (unsigned i = EncodedBytes; i < NumBytes; i += 4)
456 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
459 /// EmitTlsCall -- Given a GETtls[ld]ADDR[32] instruction, print a
460 /// call to __tls_get_addr to the current output stream.
461 void PPCAsmPrinter::EmitTlsCall(const MachineInstr *MI,
462 MCSymbolRefExpr::VariantKind VK) {
463 StringRef Name = "__tls_get_addr";
464 MCSymbol *TlsGetAddr = OutContext.getOrCreateSymbol(Name);
465 MCSymbolRefExpr::VariantKind Kind = MCSymbolRefExpr::VK_None;
466 const Module *M = MF->getFunction().getParent();
468 assert(MI->getOperand(0).isReg() &&
469 ((Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::X3) ||
470 (!Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::R3)) &&
471 "GETtls[ld]ADDR[32] must define GPR3");
472 assert(MI->getOperand(1).isReg() &&
473 ((Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::X3) ||
474 (!Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::R3)) &&
475 "GETtls[ld]ADDR[32] must read GPR3");
477 if (Subtarget->is32BitELFABI() && isPositionIndependent())
478 Kind = MCSymbolRefExpr::VK_PLT;
480 const MCExpr *TlsRef =
481 MCSymbolRefExpr::create(TlsGetAddr, Kind, OutContext);
483 // Add 32768 offset to the symbol so we follow up the latest GOT/PLT ABI.
484 if (Kind == MCSymbolRefExpr::VK_PLT && Subtarget->isSecurePlt() &&
485 M->getPICLevel() == PICLevel::BigPIC)
486 TlsRef = MCBinaryExpr::createAdd(
487 TlsRef, MCConstantExpr::create(32768, OutContext), OutContext);
488 const MachineOperand &MO = MI->getOperand(2);
489 const GlobalValue *GValue = MO.getGlobal();
490 MCSymbol *MOSymbol = getSymbol(GValue);
491 const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
492 EmitToStreamer(*OutStreamer,
493 MCInstBuilder(Subtarget->isPPC64() ?
494 PPC::BL8_NOP_TLS : PPC::BL_TLS)
499 /// Map a machine operand for a TOC pseudo-machine instruction to its
500 /// corresponding MCSymbol.
501 static MCSymbol *getMCSymbolForTOCPseudoMO(const MachineOperand &MO,
503 switch (MO.getType()) {
504 case MachineOperand::MO_GlobalAddress:
505 return AP.getSymbol(MO.getGlobal());
506 case MachineOperand::MO_ConstantPoolIndex:
507 return AP.GetCPISymbol(MO.getIndex());
508 case MachineOperand::MO_JumpTableIndex:
509 return AP.GetJTISymbol(MO.getIndex());
510 case MachineOperand::MO_BlockAddress:
511 return AP.GetBlockAddressSymbol(MO.getBlockAddress());
513 llvm_unreachable("Unexpected operand type to get symbol.");
517 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
518 /// the current output stream.
520 void PPCAsmPrinter::emitInstruction(const MachineInstr *MI) {
522 const bool IsPPC64 = Subtarget->isPPC64();
523 const bool IsAIX = Subtarget->isAIXABI();
524 const Module *M = MF->getFunction().getParent();
525 PICLevel::Level PL = M->getPICLevel();
528 // Validate that SPE and FPU are mutually exclusive in codegen
529 if (!MI->isInlineAsm()) {
530 for (const MachineOperand &MO: MI->operands()) {
532 Register Reg = MO.getReg();
533 if (Subtarget->hasSPE()) {
534 if (PPC::F4RCRegClass.contains(Reg) ||
535 PPC::F8RCRegClass.contains(Reg) ||
536 PPC::QBRCRegClass.contains(Reg) ||
537 PPC::QFRCRegClass.contains(Reg) ||
538 PPC::QSRCRegClass.contains(Reg) ||
539 PPC::VFRCRegClass.contains(Reg) ||
540 PPC::VRRCRegClass.contains(Reg) ||
541 PPC::VSFRCRegClass.contains(Reg) ||
542 PPC::VSSRCRegClass.contains(Reg)
544 llvm_unreachable("SPE targets cannot have FPRegs!");
546 if (PPC::SPERCRegClass.contains(Reg))
547 llvm_unreachable("SPE register found in FPU-targeted code!");
553 // Lower multi-instruction pseudo operations.
554 switch (MI->getOpcode()) {
556 case TargetOpcode::DBG_VALUE:
557 llvm_unreachable("Should be handled target independently");
558 case TargetOpcode::STACKMAP:
559 return LowerSTACKMAP(SM, *MI);
560 case TargetOpcode::PATCHPOINT:
561 return LowerPATCHPOINT(SM, *MI);
563 case PPC::MoveGOTtoLR: {
564 // Transform %lr = MoveGOTtoLR
565 // Into this: bl _GLOBAL_OFFSET_TABLE_@local-4
566 // _GLOBAL_OFFSET_TABLE_@local-4 (instruction preceding
567 // _GLOBAL_OFFSET_TABLE_) has exactly one instruction:
569 // This will return the pointer to _GLOBAL_OFFSET_TABLE_@local
570 MCSymbol *GOTSymbol =
571 OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
572 const MCExpr *OffsExpr =
573 MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol,
574 MCSymbolRefExpr::VK_PPC_LOCAL,
576 MCConstantExpr::create(4, OutContext),
580 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL).addExpr(OffsExpr));
583 case PPC::MovePCtoLR:
584 case PPC::MovePCtoLR8: {
585 // Transform %lr = MovePCtoLR
586 // Into this, where the label is the PIC base:
589 MCSymbol *PICBase = MF->getPICBaseSymbol();
592 EmitToStreamer(*OutStreamer,
593 MCInstBuilder(PPC::BL)
594 // FIXME: We would like an efficient form for this, so we
595 // don't have to do a lot of extra uniquing.
596 .addExpr(MCSymbolRefExpr::create(PICBase, OutContext)));
599 OutStreamer->emitLabel(PICBase);
602 case PPC::UpdateGBR: {
603 // Transform %rd = UpdateGBR(%rt, %ri)
604 // Into: lwz %rt, .L0$poff - .L0$pb(%ri)
606 // or into (if secure plt mode is on):
607 // addis r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@ha
608 // addi r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@l
609 // Get the offset from the GOT Base Register to the GOT
610 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
611 if (Subtarget->isSecurePlt() && isPositionIndependent() ) {
612 unsigned PICR = TmpInst.getOperand(0).getReg();
613 MCSymbol *BaseSymbol = OutContext.getOrCreateSymbol(
614 M->getPICLevel() == PICLevel::SmallPIC ? "_GLOBAL_OFFSET_TABLE_"
617 MCSymbolRefExpr::create(MF->getPICBaseSymbol(), OutContext);
619 const MCExpr *DeltaExpr = MCBinaryExpr::createSub(
620 MCSymbolRefExpr::create(BaseSymbol, OutContext), PB, OutContext);
622 const MCExpr *DeltaHi = PPCMCExpr::createHa(DeltaExpr, OutContext);
625 MCInstBuilder(PPC::ADDIS).addReg(PICR).addReg(PICR).addExpr(DeltaHi));
627 const MCExpr *DeltaLo = PPCMCExpr::createLo(DeltaExpr, OutContext);
630 MCInstBuilder(PPC::ADDI).addReg(PICR).addReg(PICR).addExpr(DeltaLo));
633 MCSymbol *PICOffset =
634 MF->getInfo<PPCFunctionInfo>()->getPICOffsetSymbol(*MF);
635 TmpInst.setOpcode(PPC::LWZ);
637 MCSymbolRefExpr::create(PICOffset, MCSymbolRefExpr::VK_None, OutContext);
639 MCSymbolRefExpr::create(MF->getPICBaseSymbol(),
640 MCSymbolRefExpr::VK_None,
642 const MCOperand TR = TmpInst.getOperand(1);
643 const MCOperand PICR = TmpInst.getOperand(0);
645 // Step 1: lwz %rt, .L$poff - .L$pb(%ri)
646 TmpInst.getOperand(1) =
647 MCOperand::createExpr(MCBinaryExpr::createSub(Exp, PB, OutContext));
648 TmpInst.getOperand(0) = TR;
649 TmpInst.getOperand(2) = PICR;
650 EmitToStreamer(*OutStreamer, TmpInst);
652 TmpInst.setOpcode(PPC::ADD4);
653 TmpInst.getOperand(0) = PICR;
654 TmpInst.getOperand(1) = TR;
655 TmpInst.getOperand(2) = PICR;
656 EmitToStreamer(*OutStreamer, TmpInst);
661 // Transform %rN = LWZtoc @op1, %r2
662 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
664 // Change the opcode to LWZ.
665 TmpInst.setOpcode(PPC::LWZ);
667 const MachineOperand &MO = MI->getOperand(1);
668 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
669 "Invalid operand for LWZtoc.");
671 // Map the operand to its corresponding MCSymbol.
672 const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
674 // Create a reference to the GOT entry for the symbol. The GOT entry will be
675 // synthesized later.
676 if (PL == PICLevel::SmallPIC && !IsAIX) {
678 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_GOT,
680 TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
681 EmitToStreamer(*OutStreamer, TmpInst);
685 // Otherwise, use the TOC. 'TOCEntry' is a label used to reference the
686 // storage allocated in the TOC which contains the address of
687 // 'MOSymbol'. Said TOC entry will be synthesized later.
688 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol);
690 MCSymbolRefExpr::create(TOCEntry, MCSymbolRefExpr::VK_None, OutContext);
692 // AIX uses the label directly as the lwz displacement operand for
693 // references into the toc section. The displacement value will be generated
694 // relative to the toc-base.
697 TM.getCodeModel() == CodeModel::Small &&
698 "This pseudo should only be selected for 32-bit small code model.");
699 TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
700 EmitToStreamer(*OutStreamer, TmpInst);
704 // Create an explicit subtract expression between the local symbol and
705 // '.LTOC' to manifest the toc-relative offset.
706 const MCExpr *PB = MCSymbolRefExpr::create(
707 OutContext.getOrCreateSymbol(Twine(".LTOC")), OutContext);
708 Exp = MCBinaryExpr::createSub(Exp, PB, OutContext);
709 TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
710 EmitToStreamer(*OutStreamer, TmpInst);
717 // Transform %x3 = LDtoc @min1, %x2
718 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
720 // Change the opcode to LD.
721 TmpInst.setOpcode(PPC::LD);
723 const MachineOperand &MO = MI->getOperand(1);
724 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
727 // Map the machine operand to its corresponding MCSymbol, then map the
728 // global address operand to be a reference to the TOC entry we will
731 lookUpOrCreateTOCEntry(getMCSymbolForTOCPseudoMO(MO, *this));
733 const MCSymbolRefExpr::VariantKind VK =
734 IsAIX ? MCSymbolRefExpr::VK_None : MCSymbolRefExpr::VK_PPC_TOC;
736 MCSymbolRefExpr::create(TOCEntry, VK, OutContext);
737 TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
738 EmitToStreamer(*OutStreamer, TmpInst);
741 case PPC::ADDIStocHA: {
742 assert((IsAIX && !IsPPC64 && TM.getCodeModel() == CodeModel::Large) &&
743 "This pseudo should only be selected for 32-bit large code model on"
746 // Transform %rd = ADDIStocHA %rA, @sym(%r2)
747 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
749 // Change the opcode to ADDIS.
750 TmpInst.setOpcode(PPC::ADDIS);
752 const MachineOperand &MO = MI->getOperand(2);
753 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
754 "Invalid operand for ADDIStocHA.");
756 // Map the machine operand to its corresponding MCSymbol.
757 MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
759 // Always use TOC on AIX. Map the global address operand to be a reference
760 // to the TOC entry we will synthesize later. 'TOCEntry' is a label used to
761 // reference the storage allocated in the TOC which contains the address of
763 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol);
764 const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry,
765 MCSymbolRefExpr::VK_PPC_U,
767 TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
768 EmitToStreamer(*OutStreamer, TmpInst);
772 assert(IsAIX && !IsPPC64 && TM.getCodeModel() == CodeModel::Large &&
773 "This pseudo should only be selected for 32-bit large code model on"
776 // Transform %rd = LWZtocL @sym, %rs.
777 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
779 // Change the opcode to lwz.
780 TmpInst.setOpcode(PPC::LWZ);
782 const MachineOperand &MO = MI->getOperand(1);
783 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
784 "Invalid operand for LWZtocL.");
786 // Map the machine operand to its corresponding MCSymbol.
787 MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
789 // Always use TOC on AIX. Map the global address operand to be a reference
790 // to the TOC entry we will synthesize later. 'TOCEntry' is a label used to
791 // reference the storage allocated in the TOC which contains the address of
793 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol);
794 const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry,
795 MCSymbolRefExpr::VK_PPC_L,
797 TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
798 EmitToStreamer(*OutStreamer, TmpInst);
801 case PPC::ADDIStocHA8: {
802 // Transform %xd = ADDIStocHA8 %x2, @sym
803 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
805 // Change the opcode to ADDIS8. If the global address is the address of
806 // an external symbol, is a jump table address, is a block address, or is a
807 // constant pool index with large code model enabled, then generate a TOC
808 // entry and reference that. Otherwise, reference the symbol directly.
809 TmpInst.setOpcode(PPC::ADDIS8);
811 const MachineOperand &MO = MI->getOperand(2);
812 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
813 "Invalid operand for ADDIStocHA8!");
815 const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
817 const bool GlobalToc =
818 MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal());
819 if (GlobalToc || MO.isJTI() || MO.isBlockAddress() ||
820 (MO.isCPI() && TM.getCodeModel() == CodeModel::Large))
821 MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
823 const MCSymbolRefExpr::VariantKind VK =
824 IsAIX ? MCSymbolRefExpr::VK_PPC_U : MCSymbolRefExpr::VK_PPC_TOC_HA;
827 MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
829 if (!MO.isJTI() && MO.getOffset())
830 Exp = MCBinaryExpr::createAdd(Exp,
831 MCConstantExpr::create(MO.getOffset(),
835 TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
836 EmitToStreamer(*OutStreamer, TmpInst);
840 // Transform %xd = LDtocL @sym, %xs
841 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
843 // Change the opcode to LD. If the global address is the address of
844 // an external symbol, is a jump table address, is a block address, or is
845 // a constant pool index with large code model enabled, then generate a
846 // TOC entry and reference that. Otherwise, reference the symbol directly.
847 TmpInst.setOpcode(PPC::LD);
849 const MachineOperand &MO = MI->getOperand(1);
850 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() ||
851 MO.isBlockAddress()) &&
852 "Invalid operand for LDtocL!");
855 (!MO.isGlobal() || Subtarget->isGVIndirectSymbol(MO.getGlobal())) &&
856 "LDtocL used on symbol that could be accessed directly is "
857 "invalid. Must match ADDIStocHA8."));
859 const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
861 if (!MO.isCPI() || TM.getCodeModel() == CodeModel::Large)
862 MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
864 const MCSymbolRefExpr::VariantKind VK =
865 IsAIX ? MCSymbolRefExpr::VK_PPC_L : MCSymbolRefExpr::VK_PPC_TOC_LO;
867 MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
868 TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
869 EmitToStreamer(*OutStreamer, TmpInst);
872 case PPC::ADDItocL: {
873 // Transform %xd = ADDItocL %xs, @sym
874 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
876 // Change the opcode to ADDI8. If the global address is external, then
877 // generate a TOC entry and reference that. Otherwise, reference the
879 TmpInst.setOpcode(PPC::ADDI8);
881 const MachineOperand &MO = MI->getOperand(2);
882 assert((MO.isGlobal() || MO.isCPI()) && "Invalid operand for ADDItocL.");
885 !(MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal())) &&
886 "Interposable definitions must use indirect access."));
889 MCSymbolRefExpr::create(getMCSymbolForTOCPseudoMO(MO, *this),
890 MCSymbolRefExpr::VK_PPC_TOC_LO, OutContext);
891 TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
892 EmitToStreamer(*OutStreamer, TmpInst);
895 case PPC::ADDISgotTprelHA: {
896 // Transform: %xd = ADDISgotTprelHA %x2, @sym
897 // Into: %xd = ADDIS8 %x2, sym@got@tlsgd@ha
898 assert(IsPPC64 && "Not supported for 32-bit PowerPC");
899 const MachineOperand &MO = MI->getOperand(2);
900 const GlobalValue *GValue = MO.getGlobal();
901 MCSymbol *MOSymbol = getSymbol(GValue);
902 const MCExpr *SymGotTprel =
903 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA,
905 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
906 .addReg(MI->getOperand(0).getReg())
907 .addReg(MI->getOperand(1).getReg())
908 .addExpr(SymGotTprel));
911 case PPC::LDgotTprelL:
912 case PPC::LDgotTprelL32: {
913 // Transform %xd = LDgotTprelL @sym, %xs
914 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
916 // Change the opcode to LD.
917 TmpInst.setOpcode(IsPPC64 ? PPC::LD : PPC::LWZ);
918 const MachineOperand &MO = MI->getOperand(1);
919 const GlobalValue *GValue = MO.getGlobal();
920 MCSymbol *MOSymbol = getSymbol(GValue);
921 const MCExpr *Exp = MCSymbolRefExpr::create(
922 MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO
923 : MCSymbolRefExpr::VK_PPC_GOT_TPREL,
925 TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
926 EmitToStreamer(*OutStreamer, TmpInst);
930 case PPC::PPC32PICGOT: {
931 MCSymbol *GOTSymbol = OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
932 MCSymbol *GOTRef = OutContext.createTempSymbol();
933 MCSymbol *NextInstr = OutContext.createTempSymbol();
935 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL)
936 // FIXME: We would like an efficient form for this, so we don't have to do
937 // a lot of extra uniquing.
938 .addExpr(MCSymbolRefExpr::create(NextInstr, OutContext)));
939 const MCExpr *OffsExpr =
940 MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol, OutContext),
941 MCSymbolRefExpr::create(GOTRef, OutContext),
943 OutStreamer->emitLabel(GOTRef);
944 OutStreamer->emitValue(OffsExpr, 4);
945 OutStreamer->emitLabel(NextInstr);
946 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR)
947 .addReg(MI->getOperand(0).getReg()));
948 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LWZ)
949 .addReg(MI->getOperand(1).getReg())
951 .addReg(MI->getOperand(0).getReg()));
952 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD4)
953 .addReg(MI->getOperand(0).getReg())
954 .addReg(MI->getOperand(1).getReg())
955 .addReg(MI->getOperand(0).getReg()));
958 case PPC::PPC32GOT: {
959 MCSymbol *GOTSymbol =
960 OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
961 const MCExpr *SymGotTlsL = MCSymbolRefExpr::create(
962 GOTSymbol, MCSymbolRefExpr::VK_PPC_LO, OutContext);
963 const MCExpr *SymGotTlsHA = MCSymbolRefExpr::create(
964 GOTSymbol, MCSymbolRefExpr::VK_PPC_HA, OutContext);
965 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI)
966 .addReg(MI->getOperand(0).getReg())
967 .addExpr(SymGotTlsL));
968 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
969 .addReg(MI->getOperand(0).getReg())
970 .addReg(MI->getOperand(0).getReg())
971 .addExpr(SymGotTlsHA));
974 case PPC::ADDIStlsgdHA: {
975 // Transform: %xd = ADDIStlsgdHA %x2, @sym
976 // Into: %xd = ADDIS8 %x2, sym@got@tlsgd@ha
977 assert(IsPPC64 && "Not supported for 32-bit PowerPC");
978 const MachineOperand &MO = MI->getOperand(2);
979 const GlobalValue *GValue = MO.getGlobal();
980 MCSymbol *MOSymbol = getSymbol(GValue);
981 const MCExpr *SymGotTlsGD =
982 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA,
984 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
985 .addReg(MI->getOperand(0).getReg())
986 .addReg(MI->getOperand(1).getReg())
987 .addExpr(SymGotTlsGD));
990 case PPC::ADDItlsgdL:
991 // Transform: %xd = ADDItlsgdL %xs, @sym
992 // Into: %xd = ADDI8 %xs, sym@got@tlsgd@l
993 case PPC::ADDItlsgdL32: {
994 // Transform: %rd = ADDItlsgdL32 %rs, @sym
995 // Into: %rd = ADDI %rs, sym@got@tlsgd
996 const MachineOperand &MO = MI->getOperand(2);
997 const GlobalValue *GValue = MO.getGlobal();
998 MCSymbol *MOSymbol = getSymbol(GValue);
999 const MCExpr *SymGotTlsGD = MCSymbolRefExpr::create(
1000 MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO
1001 : MCSymbolRefExpr::VK_PPC_GOT_TLSGD,
1003 EmitToStreamer(*OutStreamer,
1004 MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
1005 .addReg(MI->getOperand(0).getReg())
1006 .addReg(MI->getOperand(1).getReg())
1007 .addExpr(SymGotTlsGD));
1010 case PPC::GETtlsADDR:
1011 // Transform: %x3 = GETtlsADDR %x3, @sym
1012 // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsgd)
1013 case PPC::GETtlsADDR32: {
1014 // Transform: %r3 = GETtlsADDR32 %r3, @sym
1015 // Into: BL_TLS __tls_get_addr(sym at tlsgd)@PLT
1016 EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSGD);
1019 case PPC::ADDIStlsldHA: {
1020 // Transform: %xd = ADDIStlsldHA %x2, @sym
1021 // Into: %xd = ADDIS8 %x2, sym@got@tlsld@ha
1022 assert(IsPPC64 && "Not supported for 32-bit PowerPC");
1023 const MachineOperand &MO = MI->getOperand(2);
1024 const GlobalValue *GValue = MO.getGlobal();
1025 MCSymbol *MOSymbol = getSymbol(GValue);
1026 const MCExpr *SymGotTlsLD =
1027 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA,
1029 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
1030 .addReg(MI->getOperand(0).getReg())
1031 .addReg(MI->getOperand(1).getReg())
1032 .addExpr(SymGotTlsLD));
1035 case PPC::ADDItlsldL:
1036 // Transform: %xd = ADDItlsldL %xs, @sym
1037 // Into: %xd = ADDI8 %xs, sym@got@tlsld@l
1038 case PPC::ADDItlsldL32: {
1039 // Transform: %rd = ADDItlsldL32 %rs, @sym
1040 // Into: %rd = ADDI %rs, sym@got@tlsld
1041 const MachineOperand &MO = MI->getOperand(2);
1042 const GlobalValue *GValue = MO.getGlobal();
1043 MCSymbol *MOSymbol = getSymbol(GValue);
1044 const MCExpr *SymGotTlsLD = MCSymbolRefExpr::create(
1045 MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO
1046 : MCSymbolRefExpr::VK_PPC_GOT_TLSLD,
1048 EmitToStreamer(*OutStreamer,
1049 MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
1050 .addReg(MI->getOperand(0).getReg())
1051 .addReg(MI->getOperand(1).getReg())
1052 .addExpr(SymGotTlsLD));
1055 case PPC::GETtlsldADDR:
1056 // Transform: %x3 = GETtlsldADDR %x3, @sym
1057 // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsld)
1058 case PPC::GETtlsldADDR32: {
1059 // Transform: %r3 = GETtlsldADDR32 %r3, @sym
1060 // Into: BL_TLS __tls_get_addr(sym at tlsld)@PLT
1061 EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSLD);
1064 case PPC::ADDISdtprelHA:
1065 // Transform: %xd = ADDISdtprelHA %xs, @sym
1066 // Into: %xd = ADDIS8 %xs, sym@dtprel@ha
1067 case PPC::ADDISdtprelHA32: {
1068 // Transform: %rd = ADDISdtprelHA32 %rs, @sym
1069 // Into: %rd = ADDIS %rs, sym@dtprel@ha
1070 const MachineOperand &MO = MI->getOperand(2);
1071 const GlobalValue *GValue = MO.getGlobal();
1072 MCSymbol *MOSymbol = getSymbol(GValue);
1073 const MCExpr *SymDtprel =
1074 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_HA,
1078 MCInstBuilder(IsPPC64 ? PPC::ADDIS8 : PPC::ADDIS)
1079 .addReg(MI->getOperand(0).getReg())
1080 .addReg(MI->getOperand(1).getReg())
1081 .addExpr(SymDtprel));
1084 case PPC::ADDIdtprelL:
1085 // Transform: %xd = ADDIdtprelL %xs, @sym
1086 // Into: %xd = ADDI8 %xs, sym@dtprel@l
1087 case PPC::ADDIdtprelL32: {
1088 // Transform: %rd = ADDIdtprelL32 %rs, @sym
1089 // Into: %rd = ADDI %rs, sym@dtprel@l
1090 const MachineOperand &MO = MI->getOperand(2);
1091 const GlobalValue *GValue = MO.getGlobal();
1092 MCSymbol *MOSymbol = getSymbol(GValue);
1093 const MCExpr *SymDtprel =
1094 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_LO,
1096 EmitToStreamer(*OutStreamer,
1097 MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
1098 .addReg(MI->getOperand(0).getReg())
1099 .addReg(MI->getOperand(1).getReg())
1100 .addExpr(SymDtprel));
1105 if (!Subtarget->hasMFOCRF()) {
1106 // Transform: %r3 = MFOCRF %cr7
1107 // Into: %r3 = MFCR ;; cr7
1108 unsigned NewOpcode =
1109 MI->getOpcode() == PPC::MFOCRF ? PPC::MFCR : PPC::MFCR8;
1110 OutStreamer->AddComment(PPCInstPrinter::
1111 getRegisterName(MI->getOperand(1).getReg()));
1112 EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode)
1113 .addReg(MI->getOperand(0).getReg()));
1119 if (!Subtarget->hasMFOCRF()) {
1120 // Transform: %cr7 = MTOCRF %r3
1121 // Into: MTCRF mask, %r3 ;; cr7
1122 unsigned NewOpcode =
1123 MI->getOpcode() == PPC::MTOCRF ? PPC::MTCRF : PPC::MTCRF8;
1124 unsigned Mask = 0x80 >> OutContext.getRegisterInfo()
1125 ->getEncodingValue(MI->getOperand(0).getReg());
1126 OutStreamer->AddComment(PPCInstPrinter::
1127 getRegisterName(MI->getOperand(0).getReg()));
1128 EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode)
1130 .addReg(MI->getOperand(1).getReg()));
1138 // Verify alignment is legal, so we don't create relocations
1139 // that can't be supported.
1140 // FIXME: This test is currently disabled for Darwin. The test
1141 // suite shows a handful of test cases that fail this check for
1142 // Darwin. Those need to be investigated before this sanity test
1143 // can be enabled for those subtargets.
1144 unsigned OpNum = (MI->getOpcode() == PPC::STD) ? 2 : 1;
1145 const MachineOperand &MO = MI->getOperand(OpNum);
1146 if (MO.isGlobal()) {
1147 const DataLayout &DL = MO.getGlobal()->getParent()->getDataLayout();
1148 if (MO.getGlobal()->getPointerAlignment(DL) < 4)
1149 llvm_unreachable("Global must be word-aligned for LD, STD, LWA!");
1151 // Now process the instruction normally.
1156 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1157 EmitToStreamer(*OutStreamer, TmpInst);
1160 void PPCLinuxAsmPrinter::emitInstruction(const MachineInstr *MI) {
1161 if (!Subtarget->isPPC64())
1162 return PPCAsmPrinter::emitInstruction(MI);
1164 switch (MI->getOpcode()) {
1166 return PPCAsmPrinter::emitInstruction(MI);
1167 case TargetOpcode::PATCHABLE_FUNCTION_ENTER: {
1169 // b .end # lis 0, FuncId[16..32]
1170 // nop # li 0, FuncId[0..15]
1173 // bl __xray_FunctionEntry
1177 // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1178 // of instructions change.
1179 MCSymbol *BeginOfSled = OutContext.createTempSymbol();
1180 MCSymbol *EndOfSled = OutContext.createTempSymbol();
1181 OutStreamer->emitLabel(BeginOfSled);
1182 EmitToStreamer(*OutStreamer,
1183 MCInstBuilder(PPC::B).addExpr(
1184 MCSymbolRefExpr::create(EndOfSled, OutContext)));
1185 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
1188 MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1));
1189 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0));
1190 EmitToStreamer(*OutStreamer,
1191 MCInstBuilder(PPC::BL8_NOP)
1192 .addExpr(MCSymbolRefExpr::create(
1193 OutContext.getOrCreateSymbol("__xray_FunctionEntry"),
1195 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0));
1196 OutStreamer->emitLabel(EndOfSled);
1197 recordSled(BeginOfSled, *MI, SledKind::FUNCTION_ENTER, 2);
1200 case TargetOpcode::PATCHABLE_RET: {
1201 unsigned RetOpcode = MI->getOperand(0).getImm();
1203 RetInst.setOpcode(RetOpcode);
1204 for (const auto &MO :
1205 make_range(std::next(MI->operands_begin()), MI->operands_end())) {
1207 if (LowerPPCMachineOperandToMCOperand(MO, MCOp, *this))
1208 RetInst.addOperand(MCOp);
1212 if (RetOpcode == PPC::BCCLR) {
1213 IsConditional = true;
1214 } else if (RetOpcode == PPC::TCRETURNdi8 || RetOpcode == PPC::TCRETURNri8 ||
1215 RetOpcode == PPC::TCRETURNai8) {
1217 } else if (RetOpcode == PPC::BLR8 || RetOpcode == PPC::TAILB8) {
1218 IsConditional = false;
1220 EmitToStreamer(*OutStreamer, RetInst);
1224 MCSymbol *FallthroughLabel;
1225 if (IsConditional) {
1233 // blr # lis 0, FuncId[16..32]
1234 // nop # li 0, FuncId[0..15]
1237 // bl __xray_FunctionExit
1242 // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1243 // of instructions change.
1244 FallthroughLabel = OutContext.createTempSymbol();
1247 MCInstBuilder(PPC::BCC)
1248 .addImm(PPC::InvertPredicate(
1249 static_cast<PPC::Predicate>(MI->getOperand(1).getImm())))
1250 .addReg(MI->getOperand(2).getReg())
1251 .addExpr(MCSymbolRefExpr::create(FallthroughLabel, OutContext)));
1253 RetInst.setOpcode(PPC::BLR8);
1257 // b(lr)? # lis 0, FuncId[16..32]
1258 // nop # li 0, FuncId[0..15]
1261 // bl __xray_FunctionExit
1265 // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1266 // of instructions change.
1267 OutStreamer->emitCodeAlignment(8);
1268 MCSymbol *BeginOfSled = OutContext.createTempSymbol();
1269 OutStreamer->emitLabel(BeginOfSled);
1270 EmitToStreamer(*OutStreamer, RetInst);
1271 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
1274 MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1));
1275 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0));
1276 EmitToStreamer(*OutStreamer,
1277 MCInstBuilder(PPC::BL8_NOP)
1278 .addExpr(MCSymbolRefExpr::create(
1279 OutContext.getOrCreateSymbol("__xray_FunctionExit"),
1281 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0));
1282 EmitToStreamer(*OutStreamer, RetInst);
1284 OutStreamer->emitLabel(FallthroughLabel);
1285 recordSled(BeginOfSled, *MI, SledKind::FUNCTION_EXIT, 2);
1288 case TargetOpcode::PATCHABLE_FUNCTION_EXIT:
1289 llvm_unreachable("PATCHABLE_FUNCTION_EXIT should never be emitted");
1290 case TargetOpcode::PATCHABLE_TAIL_CALL:
1291 // TODO: Define a trampoline `__xray_FunctionTailExit` and differentiate a
1292 // normal function exit from a tail exit.
1293 llvm_unreachable("Tail call is handled in the normal case. See comments "
1294 "around this assert.");
1298 void PPCLinuxAsmPrinter::emitStartOfAsmFile(Module &M) {
1299 if (static_cast<const PPCTargetMachine &>(TM).isELFv2ABI()) {
1300 PPCTargetStreamer *TS =
1301 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1304 TS->emitAbiVersion(2);
1307 if (static_cast<const PPCTargetMachine &>(TM).isPPC64() ||
1308 !isPositionIndependent())
1309 return AsmPrinter::emitStartOfAsmFile(M);
1311 if (M.getPICLevel() == PICLevel::SmallPIC)
1312 return AsmPrinter::emitStartOfAsmFile(M);
1314 OutStreamer->SwitchSection(OutContext.getELFSection(
1315 ".got2", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC));
1317 MCSymbol *TOCSym = OutContext.getOrCreateSymbol(Twine(".LTOC"));
1318 MCSymbol *CurrentPos = OutContext.createTempSymbol();
1320 OutStreamer->emitLabel(CurrentPos);
1322 // The GOT pointer points to the middle of the GOT, in order to reference the
1323 // entire 64kB range. 0x8000 is the midpoint.
1324 const MCExpr *tocExpr =
1325 MCBinaryExpr::createAdd(MCSymbolRefExpr::create(CurrentPos, OutContext),
1326 MCConstantExpr::create(0x8000, OutContext),
1329 OutStreamer->emitAssignment(TOCSym, tocExpr);
1331 OutStreamer->SwitchSection(getObjFileLowering().getTextSection());
1334 void PPCLinuxAsmPrinter::emitFunctionEntryLabel() {
1335 // linux/ppc32 - Normal entry label.
1336 if (!Subtarget->isPPC64() &&
1337 (!isPositionIndependent() ||
1338 MF->getFunction().getParent()->getPICLevel() == PICLevel::SmallPIC))
1339 return AsmPrinter::emitFunctionEntryLabel();
1341 if (!Subtarget->isPPC64()) {
1342 const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1343 if (PPCFI->usesPICBase() && !Subtarget->isSecurePlt()) {
1344 MCSymbol *RelocSymbol = PPCFI->getPICOffsetSymbol(*MF);
1345 MCSymbol *PICBase = MF->getPICBaseSymbol();
1346 OutStreamer->emitLabel(RelocSymbol);
1348 const MCExpr *OffsExpr =
1349 MCBinaryExpr::createSub(
1350 MCSymbolRefExpr::create(OutContext.getOrCreateSymbol(Twine(".LTOC")),
1352 MCSymbolRefExpr::create(PICBase, OutContext),
1354 OutStreamer->emitValue(OffsExpr, 4);
1355 OutStreamer->emitLabel(CurrentFnSym);
1358 return AsmPrinter::emitFunctionEntryLabel();
1361 // ELFv2 ABI - Normal entry label.
1362 if (Subtarget->isELFv2ABI()) {
1363 // In the Large code model, we allow arbitrary displacements between
1364 // the text section and its associated TOC section. We place the
1365 // full 8-byte offset to the TOC in memory immediately preceding
1366 // the function global entry point.
1367 if (TM.getCodeModel() == CodeModel::Large
1368 && !MF->getRegInfo().use_empty(PPC::X2)) {
1369 const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1371 MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1372 MCSymbol *GlobalEPSymbol = PPCFI->getGlobalEPSymbol(*MF);
1373 const MCExpr *TOCDeltaExpr =
1374 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext),
1375 MCSymbolRefExpr::create(GlobalEPSymbol,
1379 OutStreamer->emitLabel(PPCFI->getTOCOffsetSymbol(*MF));
1380 OutStreamer->emitValue(TOCDeltaExpr, 8);
1382 return AsmPrinter::emitFunctionEntryLabel();
1385 // Emit an official procedure descriptor.
1386 MCSectionSubPair Current = OutStreamer->getCurrentSection();
1387 MCSectionELF *Section = OutStreamer->getContext().getELFSection(
1388 ".opd", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
1389 OutStreamer->SwitchSection(Section);
1390 OutStreamer->emitLabel(CurrentFnSym);
1391 OutStreamer->emitValueToAlignment(8);
1392 MCSymbol *Symbol1 = CurrentFnSymForSize;
1393 // Generates a R_PPC64_ADDR64 (from FK_DATA_8) relocation for the function
1395 OutStreamer->emitValue(MCSymbolRefExpr::create(Symbol1, OutContext),
1397 MCSymbol *Symbol2 = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1398 // Generates a R_PPC64_TOC relocation for TOC base insertion.
1399 OutStreamer->emitValue(
1400 MCSymbolRefExpr::create(Symbol2, MCSymbolRefExpr::VK_PPC_TOCBASE, OutContext),
1402 // Emit a null environment pointer.
1403 OutStreamer->emitIntValue(0, 8 /* size */);
1404 OutStreamer->SwitchSection(Current.first, Current.second);
1407 void PPCLinuxAsmPrinter::emitEndOfAsmFile(Module &M) {
1408 const DataLayout &DL = getDataLayout();
1410 bool isPPC64 = DL.getPointerSizeInBits() == 64;
1412 PPCTargetStreamer *TS =
1413 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1416 const char *Name = isPPC64 ? ".toc" : ".got2";
1417 MCSectionELF *Section = OutContext.getELFSection(
1418 Name, ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
1419 OutStreamer->SwitchSection(Section);
1421 OutStreamer->emitValueToAlignment(4);
1423 for (const auto &TOCMapPair : TOC) {
1424 const MCSymbol *const TOCEntryTarget = TOCMapPair.first;
1425 MCSymbol *const TOCEntryLabel = TOCMapPair.second;
1427 OutStreamer->emitLabel(TOCEntryLabel);
1428 if (isPPC64 && TS != nullptr)
1429 TS->emitTCEntry(*TOCEntryTarget);
1431 OutStreamer->emitSymbolValue(TOCEntryTarget, 4);
1435 PPCAsmPrinter::emitEndOfAsmFile(M);
1438 /// EmitFunctionBodyStart - Emit a global entry point prefix for ELFv2.
1439 void PPCLinuxAsmPrinter::emitFunctionBodyStart() {
1440 // In the ELFv2 ABI, in functions that use the TOC register, we need to
1441 // provide two entry points. The ABI guarantees that when calling the
1442 // local entry point, r2 is set up by the caller to contain the TOC base
1443 // for this function, and when calling the global entry point, r12 is set
1444 // up by the caller to hold the address of the global entry point. We
1445 // thus emit a prefix sequence along the following lines:
1449 // # global entry point
1450 // addis r2,r12,(.TOC.-.Lfunc_gepNN)@ha
1451 // addi r2,r2,(.TOC.-.Lfunc_gepNN)@l
1453 // .localentry func, .Lfunc_lepNN-.Lfunc_gepNN
1454 // # local entry point, followed by function body
1456 // For the Large code model, we create
1459 // .quad .TOC.-.Lfunc_gepNN # done by EmitFunctionEntryLabel
1462 // # global entry point
1463 // ld r2,.Lfunc_tocNN-.Lfunc_gepNN(r12)
1466 // .localentry func, .Lfunc_lepNN-.Lfunc_gepNN
1467 // # local entry point, followed by function body
1469 // This ensures we have r2 set up correctly while executing the function
1470 // body, no matter which entry point is called.
1471 const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1472 const bool UsesX2OrR2 = !MF->getRegInfo().use_empty(PPC::X2) ||
1473 !MF->getRegInfo().use_empty(PPC::R2);
1474 const bool PCrelGEPRequired = Subtarget->isUsingPCRelativeCalls() &&
1475 UsesX2OrR2 && PPCFI->usesTOCBasePtr();
1476 const bool NonPCrelGEPRequired = !Subtarget->isUsingPCRelativeCalls() &&
1477 Subtarget->isELFv2ABI() && UsesX2OrR2;
1479 // Only do all that if the function uses R2 as the TOC pointer
1480 // in the first place. We don't need the global entry point if the
1481 // function uses R2 as an allocatable register.
1482 if (NonPCrelGEPRequired || PCrelGEPRequired) {
1483 // Note: The logic here must be synchronized with the code in the
1484 // branch-selection pass which sets the offset of the first block in the
1485 // function. This matters because it affects the alignment.
1486 MCSymbol *GlobalEntryLabel = PPCFI->getGlobalEPSymbol(*MF);
1487 OutStreamer->emitLabel(GlobalEntryLabel);
1488 const MCSymbolRefExpr *GlobalEntryLabelExp =
1489 MCSymbolRefExpr::create(GlobalEntryLabel, OutContext);
1491 if (TM.getCodeModel() != CodeModel::Large) {
1492 MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1493 const MCExpr *TOCDeltaExpr =
1494 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext),
1495 GlobalEntryLabelExp, OutContext);
1497 const MCExpr *TOCDeltaHi = PPCMCExpr::createHa(TOCDeltaExpr, OutContext);
1498 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
1501 .addExpr(TOCDeltaHi));
1503 const MCExpr *TOCDeltaLo = PPCMCExpr::createLo(TOCDeltaExpr, OutContext);
1504 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDI)
1507 .addExpr(TOCDeltaLo));
1509 MCSymbol *TOCOffset = PPCFI->getTOCOffsetSymbol(*MF);
1510 const MCExpr *TOCOffsetDeltaExpr =
1511 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCOffset, OutContext),
1512 GlobalEntryLabelExp, OutContext);
1514 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
1516 .addExpr(TOCOffsetDeltaExpr)
1518 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD8)
1524 MCSymbol *LocalEntryLabel = PPCFI->getLocalEPSymbol(*MF);
1525 OutStreamer->emitLabel(LocalEntryLabel);
1526 const MCSymbolRefExpr *LocalEntryLabelExp =
1527 MCSymbolRefExpr::create(LocalEntryLabel, OutContext);
1528 const MCExpr *LocalOffsetExp =
1529 MCBinaryExpr::createSub(LocalEntryLabelExp,
1530 GlobalEntryLabelExp, OutContext);
1532 PPCTargetStreamer *TS =
1533 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1536 TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym), LocalOffsetExp);
1537 } else if (Subtarget->isUsingPCRelativeCalls()) {
1538 // When generating the entry point for a function we have a few scenarios
1539 // based on whether or not that function uses R2 and whether or not that
1540 // function makes calls (or is a leaf function).
1541 // 1) A leaf function that does not use R2 (or treats it as callee-saved
1542 // and preserves it). In this case st_other=0 and both
1543 // the local and global entry points for the function are the same.
1544 // No special entry point code is required.
1545 // 2) A function uses the TOC pointer R2. This function may or may not have
1546 // calls. In this case st_other=[2,6] and the global and local entry
1547 // points are different. Code to correctly setup the TOC pointer in R2
1548 // is put between the global and local entry points. This case is
1549 // covered by the if statatement above.
1550 // 3) A function does not use the TOC pointer R2 but does have calls.
1551 // In this case st_other=1 since we do not know whether or not any
1552 // of the callees clobber R2. This case is dealt with in this else if
1553 // block. Tail calls are considered calls and the st_other should also
1554 // be set to 1 in that case as well.
1555 // 4) The function does not use the TOC pointer but R2 is used inside
1556 // the function. In this case st_other=1 once again.
1557 // 5) This function uses inline asm. We mark R2 as reserved if the function
1558 // has inline asm as we have to assume that it may be used.
1559 if (MF->getFrameInfo().hasCalls() || MF->getFrameInfo().hasTailCall() ||
1560 MF->hasInlineAsm() || (!PPCFI->usesTOCBasePtr() && UsesX2OrR2)) {
1561 PPCTargetStreamer *TS =
1562 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1564 TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym),
1565 MCConstantExpr::create(1, OutContext));
1570 /// EmitFunctionBodyEnd - Print the traceback table before the .size
1573 void PPCLinuxAsmPrinter::emitFunctionBodyEnd() {
1574 // Only the 64-bit target requires a traceback table. For now,
1575 // we only emit the word of zeroes that GDB requires to find
1576 // the end of the function, and zeroes for the eight-byte
1577 // mandatory fields.
1578 // FIXME: We should fill in the eight-byte mandatory fields as described in
1579 // the PPC64 ELF ABI (this is a low-priority item because GDB does not
1580 // currently make use of these fields).
1581 if (Subtarget->isPPC64()) {
1582 OutStreamer->emitIntValue(0, 4/*size*/);
1583 OutStreamer->emitIntValue(0, 8/*size*/);
1587 void PPCAIXAsmPrinter::emitLinkage(const GlobalValue *GV,
1588 MCSymbol *GVSym) const {
1590 assert(MAI->hasVisibilityOnlyWithLinkage() &&
1591 "AIX's linkage directives take a visibility setting.");
1593 MCSymbolAttr LinkageAttr = MCSA_Invalid;
1594 switch (GV->getLinkage()) {
1595 case GlobalValue::ExternalLinkage:
1596 LinkageAttr = GV->isDeclaration() ? MCSA_Extern : MCSA_Global;
1598 case GlobalValue::LinkOnceAnyLinkage:
1599 case GlobalValue::LinkOnceODRLinkage:
1600 case GlobalValue::WeakAnyLinkage:
1601 case GlobalValue::WeakODRLinkage:
1602 case GlobalValue::ExternalWeakLinkage:
1603 LinkageAttr = MCSA_Weak;
1605 case GlobalValue::AvailableExternallyLinkage:
1606 LinkageAttr = MCSA_Extern;
1608 case GlobalValue::PrivateLinkage:
1610 case GlobalValue::InternalLinkage:
1611 assert(GV->getVisibility() == GlobalValue::DefaultVisibility &&
1612 "InternalLinkage should not have other visibility setting.");
1613 LinkageAttr = MCSA_LGlobal;
1615 case GlobalValue::AppendingLinkage:
1616 llvm_unreachable("Should never emit this");
1617 case GlobalValue::CommonLinkage:
1618 llvm_unreachable("CommonLinkage of XCOFF should not come to this path");
1621 assert(LinkageAttr != MCSA_Invalid && "LinkageAttr should not MCSA_Invalid.");
1623 MCSymbolAttr VisibilityAttr = MCSA_Invalid;
1624 switch (GV->getVisibility()) {
1626 // TODO: "exported" and "internal" Visibility needs to go here.
1627 case GlobalValue::DefaultVisibility:
1629 case GlobalValue::HiddenVisibility:
1630 VisibilityAttr = MAI->getHiddenVisibilityAttr();
1632 case GlobalValue::ProtectedVisibility:
1633 VisibilityAttr = MAI->getProtectedVisibilityAttr();
1637 OutStreamer->emitXCOFFSymbolLinkageWithVisibility(GVSym, LinkageAttr,
1641 void PPCAIXAsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1642 // Setup CurrentFnDescSym and its containing csect.
1643 MCSectionXCOFF *FnDescSec =
1644 cast<MCSectionXCOFF>(getObjFileLowering().getSectionForFunctionDescriptor(
1645 &MF.getFunction(), TM));
1646 FnDescSec->setAlignment(Align(Subtarget->isPPC64() ? 8 : 4));
1648 CurrentFnDescSym = FnDescSec->getQualNameSymbol();
1650 return AsmPrinter::SetupMachineFunction(MF);
1653 void PPCAIXAsmPrinter::ValidateGV(const GlobalVariable *GV) {
1654 // Early error checking limiting what is supported.
1655 if (GV->isThreadLocal())
1656 report_fatal_error("Thread local not yet supported on AIX.");
1658 if (GV->hasSection())
1659 report_fatal_error("Custom section for Data not yet supported.");
1661 if (GV->hasComdat())
1662 report_fatal_error("COMDAT not yet supported by AIX.");
1665 static bool isSpecialLLVMGlobalArrayForStaticInit(const GlobalVariable *GV) {
1666 return StringSwitch<bool>(GV->getName())
1667 .Cases("llvm.global_ctors", "llvm.global_dtors", true)
1671 void PPCAIXAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) {
1674 // TODO: Update the handling of global arrays for static init when we support
1675 // the ".ref" directive.
1676 // Otherwise, we can skip these arrays, because the AIX linker collects
1677 // static init functions simply based on their name.
1678 if (isSpecialLLVMGlobalArrayForStaticInit(GV))
1681 // Create the symbol, set its storage class.
1682 MCSymbolXCOFF *GVSym = cast<MCSymbolXCOFF>(getSymbol(GV));
1683 GVSym->setStorageClass(
1684 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GV));
1686 if (GV->isDeclarationForLinker()) {
1687 emitLinkage(GV, GVSym);
1691 SectionKind GVKind = getObjFileLowering().getKindForGlobal(GV, TM);
1692 if (!GVKind.isGlobalWriteableData() && !GVKind.isReadOnly())
1693 report_fatal_error("Encountered a global variable kind that is "
1694 "not supported yet.");
1696 MCSectionXCOFF *Csect = cast<MCSectionXCOFF>(
1697 getObjFileLowering().SectionForGlobal(GV, GVKind, TM));
1699 // Switch to the containing csect.
1700 OutStreamer->SwitchSection(Csect);
1702 const DataLayout &DL = GV->getParent()->getDataLayout();
1704 // Handle common symbols.
1705 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
1706 Align Alignment = GV->getAlign().getValueOr(DL.getPreferredAlign(GV));
1707 uint64_t Size = DL.getTypeAllocSize(GV->getType()->getElementType());
1709 if (GVKind.isBSSLocal())
1710 OutStreamer->emitXCOFFLocalCommonSymbol(
1711 OutContext.getOrCreateSymbol(GVSym->getUnqualifiedName()), Size,
1712 GVSym, Alignment.value());
1714 OutStreamer->emitCommonSymbol(GVSym, Size, Alignment.value());
1718 MCSymbol *EmittedInitSym = GVSym;
1719 emitLinkage(GV, EmittedInitSym);
1720 emitAlignment(getGVAlignment(GV, DL), GV);
1721 OutStreamer->emitLabel(EmittedInitSym);
1722 emitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer());
1725 void PPCAIXAsmPrinter::emitFunctionDescriptor() {
1726 const DataLayout &DL = getDataLayout();
1727 const unsigned PointerSize = DL.getPointerSizeInBits() == 64 ? 8 : 4;
1729 MCSectionSubPair Current = OutStreamer->getCurrentSection();
1730 // Emit function descriptor.
1731 OutStreamer->SwitchSection(
1732 cast<MCSymbolXCOFF>(CurrentFnDescSym)->getRepresentedCsect());
1733 // Emit function entry point address.
1734 OutStreamer->emitValue(MCSymbolRefExpr::create(CurrentFnSym, OutContext),
1736 // Emit TOC base address.
1737 const MCSymbol *TOCBaseSym =
1738 cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection())
1739 ->getQualNameSymbol();
1740 OutStreamer->emitValue(MCSymbolRefExpr::create(TOCBaseSym, OutContext),
1742 // Emit a null environment pointer.
1743 OutStreamer->emitIntValue(0, PointerSize);
1745 OutStreamer->SwitchSection(Current.first, Current.second);
1748 void PPCAIXAsmPrinter::emitEndOfAsmFile(Module &M) {
1749 // If there are no functions in this module, we will never need to reference
1754 // Switch to section to emit TOC base.
1755 OutStreamer->SwitchSection(getObjFileLowering().getTOCBaseSection());
1757 PPCTargetStreamer *TS =
1758 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1760 const unsigned EntryByteSize = Subtarget->isPPC64() ? 8 : 4;
1761 const unsigned TOCEntriesByteSize = TOC.size() * EntryByteSize;
1762 // TODO: If TOC entries' size is larger than 32768, then we run out of
1763 // positive displacement to reach the TOC entry. We need to decide how to
1764 // handle entries' size larger than that later.
1765 if (TOCEntriesByteSize > 32767) {
1766 report_fatal_error("Handling of TOC entry displacement larger than 32767 "
1767 "is not yet implemented.");
1770 for (auto &I : TOC) {
1771 // Setup the csect for the current TC entry.
1772 MCSectionXCOFF *TCEntry = cast<MCSectionXCOFF>(
1773 getObjFileLowering().getSectionForTOCEntry(I.first));
1774 OutStreamer->SwitchSection(TCEntry);
1776 OutStreamer->emitLabel(I.second);
1778 TS->emitTCEntry(*I.first);
1782 bool PPCAIXAsmPrinter::doInitialization(Module &M) {
1783 if (M.alias_size() > 0u)
1785 "module has aliases, which LLVM does not yet support for AIX");
1787 const bool Result = PPCAsmPrinter::doInitialization(M);
1789 auto setCsectAlignment = [this](const GlobalObject *GO) {
1790 // Declarations have 0 alignment which is set by default.
1791 if (GO->isDeclarationForLinker())
1794 SectionKind GOKind = getObjFileLowering().getKindForGlobal(GO, TM);
1795 MCSectionXCOFF *Csect = cast<MCSectionXCOFF>(
1796 getObjFileLowering().SectionForGlobal(GO, GOKind, TM));
1798 Align GOAlign = getGVAlignment(GO, GO->getParent()->getDataLayout());
1799 if (GOAlign > Csect->getAlignment())
1800 Csect->setAlignment(GOAlign);
1803 // We need to know, up front, the alignment of csects for the assembly path,
1804 // because once a .csect directive gets emitted, we could not change the
1805 // alignment value on it.
1806 for (const auto &G : M.globals())
1807 setCsectAlignment(&G);
1809 for (const auto &F : M)
1810 setCsectAlignment(&F);
1815 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1816 /// for a MachineFunction to the given output stream, in a format that the
1817 /// Darwin assembler can deal with.
1820 createPPCAsmPrinterPass(TargetMachine &tm,
1821 std::unique_ptr<MCStreamer> &&Streamer) {
1822 if (tm.getTargetTriple().isOSAIX())
1823 return new PPCAIXAsmPrinter(tm, std::move(Streamer));
1825 return new PPCLinuxAsmPrinter(tm, std::move(Streamer));
1828 // Force static initialization.
1829 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializePowerPCAsmPrinter() {
1830 TargetRegistry::RegisterAsmPrinter(getThePPC32Target(),
1831 createPPCAsmPrinterPass);
1832 TargetRegistry::RegisterAsmPrinter(getThePPC64Target(),
1833 createPPCAsmPrinterPass);
1834 TargetRegistry::RegisterAsmPrinter(getThePPC64LETarget(),
1835 createPPCAsmPrinterPass);