1 //===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly --------=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to PowerPC assembly language. This printer is
12 // the output mechanism used by `llc'.
14 // Documentation at http://developer.apple.com/documentation/DeveloperTools/
15 // Reference/Assembler/ASMIntroduction/chapter_1_section_1.html
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "asmprinter"
21 #include "PPCPredicates.h"
22 #include "PPCTargetMachine.h"
23 #include "PPCSubtarget.h"
24 #include "llvm/Constants.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/Module.h"
27 #include "llvm/Assembly/Writer.h"
28 #include "llvm/CodeGen/AsmPrinter.h"
29 #include "llvm/CodeGen/DwarfWriter.h"
30 #include "llvm/CodeGen/MachineFunctionPass.h"
31 #include "llvm/CodeGen/MachineInstr.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCContext.h"
36 #include "llvm/MC/MCSectionMachO.h"
37 #include "llvm/MC/MCStreamer.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/Target/Mangler.h"
40 #include "llvm/Target/TargetLoweringObjectFile.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetInstrInfo.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include "llvm/Target/TargetRegistry.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/FormattedStream.h"
50 #include "llvm/ADT/StringExtras.h"
51 #include "llvm/ADT/StringSet.h"
52 #include "llvm/ADT/SmallString.h"
56 class PPCAsmPrinter : public AsmPrinter {
58 DenseMap<const MCSymbol*, const MCSymbol*> TOC;
59 const PPCSubtarget &Subtarget;
62 explicit PPCAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
63 MCContext &Ctx, MCStreamer &Streamer,
65 : AsmPrinter(O, TM, Ctx, Streamer, T),
66 Subtarget(TM.getSubtarget<PPCSubtarget>()), LabelID(0) {}
68 virtual const char *getPassName() const {
69 return "PowerPC Assembly Printer";
72 PPCTargetMachine &getTM() {
73 return static_cast<PPCTargetMachine&>(TM);
76 unsigned enumRegToMachineReg(unsigned enumReg) {
78 default: llvm_unreachable("Unhandled register!");
79 case PPC::CR0: return 0;
80 case PPC::CR1: return 1;
81 case PPC::CR2: return 2;
82 case PPC::CR3: return 3;
83 case PPC::CR4: return 4;
84 case PPC::CR5: return 5;
85 case PPC::CR6: return 6;
86 case PPC::CR7: return 7;
91 /// printInstruction - This method is automatically generated by tablegen
92 /// from the instruction set description. This method returns true if the
93 /// machine instruction was sufficiently described to print it, otherwise it
95 void printInstruction(const MachineInstr *MI);
96 static const char *getRegisterName(unsigned RegNo);
99 virtual void EmitInstruction(const MachineInstr *MI);
100 void printOp(const MachineOperand &MO);
102 /// stripRegisterPrefix - This method strips the character prefix from a
103 /// register name so that only the number is left. Used by for linux asm.
104 const char *stripRegisterPrefix(const char *RegName) {
105 switch (RegName[0]) {
108 case 'v': return RegName + 1;
109 case 'c': if (RegName[1] == 'r') return RegName + 2;
115 /// printRegister - Print register according to target requirements.
117 void printRegister(const MachineOperand &MO, bool R0AsZero) {
118 unsigned RegNo = MO.getReg();
119 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
121 // If we should use 0 for R0.
122 if (R0AsZero && RegNo == PPC::R0) {
127 const char *RegName = getRegisterName(RegNo);
128 // Linux assembler (Others?) does not take register mnemonics.
129 // FIXME - What about special registers used in mfspr/mtspr?
130 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
134 void printOperand(const MachineInstr *MI, unsigned OpNo) {
135 const MachineOperand &MO = MI->getOperand(OpNo);
137 printRegister(MO, false);
138 } else if (MO.isImm()) {
145 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
146 unsigned AsmVariant, const char *ExtraCode);
147 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
148 unsigned AsmVariant, const char *ExtraCode);
151 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
152 char value = MI->getOperand(OpNo).getImm();
153 value = (value << (32-5)) >> (32-5);
156 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
157 unsigned char value = MI->getOperand(OpNo).getImm();
158 assert(value <= 31 && "Invalid u5imm argument!");
159 O << (unsigned int)value;
161 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
162 unsigned char value = MI->getOperand(OpNo).getImm();
163 assert(value <= 63 && "Invalid u6imm argument!");
164 O << (unsigned int)value;
166 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
167 O << (short)MI->getOperand(OpNo).getImm();
169 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
170 O << (unsigned short)MI->getOperand(OpNo).getImm();
172 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
173 if (MI->getOperand(OpNo).isImm()) {
174 O << (short)(MI->getOperand(OpNo).getImm()*4);
177 printOp(MI->getOperand(OpNo));
178 if (TM.getRelocationModel() == Reloc::PIC_)
179 O << "-\"L" << getFunctionNumber() << "$pb\")";
184 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
185 // Branches can take an immediate operand. This is used by the branch
186 // selection pass to print $+8, an eight byte displacement from the PC.
187 if (MI->getOperand(OpNo).isImm()) {
188 O << "$+" << MI->getOperand(OpNo).getImm()*4;
190 printOp(MI->getOperand(OpNo));
193 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
194 const MachineOperand &MO = MI->getOperand(OpNo);
195 if (TM.getRelocationModel() != Reloc::Static) {
196 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
197 GlobalValue *GV = MO.getGlobal();
198 if (GV->isDeclaration() || GV->isWeakForLinker()) {
199 // Dynamically-resolved functions need a stub for the function.
200 MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$stub");
201 const MCSymbol *&StubSym =
202 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
204 StubSym = GetGlobalValueSymbol(GV);
209 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
210 SmallString<128> TempNameStr;
211 TempNameStr += StringRef(MO.getSymbolName());
212 TempNameStr += StringRef("$stub");
214 const MCSymbol *Sym = GetExternalSymbolSymbol(TempNameStr.str());
215 const MCSymbol *&StubSym =
216 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
218 StubSym = GetExternalSymbolSymbol(MO.getSymbolName());
224 printOp(MI->getOperand(OpNo));
226 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
227 O << (int)MI->getOperand(OpNo).getImm()*4;
229 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
230 O << "\"L" << getFunctionNumber() << "$pb\"\n";
231 O << "\"L" << getFunctionNumber() << "$pb\":";
233 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
234 if (MI->getOperand(OpNo).isImm()) {
235 printS16ImmOperand(MI, OpNo);
237 if (Subtarget.isDarwin()) O << "ha16(";
238 printOp(MI->getOperand(OpNo));
239 if (TM.getRelocationModel() == Reloc::PIC_)
240 O << "-\"L" << getFunctionNumber() << "$pb\"";
241 if (Subtarget.isDarwin())
247 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
248 if (MI->getOperand(OpNo).isImm()) {
249 printS16ImmOperand(MI, OpNo);
251 if (Subtarget.isDarwin()) O << "lo16(";
252 printOp(MI->getOperand(OpNo));
253 if (TM.getRelocationModel() == Reloc::PIC_)
254 O << "-\"L" << getFunctionNumber() << "$pb\"";
255 if (Subtarget.isDarwin())
261 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
262 unsigned CCReg = MI->getOperand(OpNo).getReg();
263 unsigned RegNo = enumRegToMachineReg(CCReg);
264 O << (0x80 >> RegNo);
266 // The new addressing mode printers.
267 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
268 printSymbolLo(MI, OpNo);
270 if (MI->getOperand(OpNo+1).isReg() &&
271 MI->getOperand(OpNo+1).getReg() == PPC::R0)
274 printOperand(MI, OpNo+1);
277 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
278 if (MI->getOperand(OpNo).isImm())
279 printS16X4ImmOperand(MI, OpNo);
281 printSymbolLo(MI, OpNo);
283 if (MI->getOperand(OpNo+1).isReg() &&
284 MI->getOperand(OpNo+1).getReg() == PPC::R0)
287 printOperand(MI, OpNo+1);
291 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
292 // When used as the base register, r0 reads constant zero rather than
293 // the value contained in the register. For this reason, the darwin
294 // assembler requires that we print r0 as 0 (no r) when used as the base.
295 const MachineOperand &MO = MI->getOperand(OpNo);
296 printRegister(MO, true);
298 printOperand(MI, OpNo+1);
301 void printTOCEntryLabel(const MachineInstr *MI, unsigned OpNo) {
302 const MachineOperand &MO = MI->getOperand(OpNo);
304 assert(MO.getType() == MachineOperand::MO_GlobalAddress);
306 const MCSymbol *Sym = GetGlobalValueSymbol(MO.getGlobal());
308 // Map symbol -> label of TOC entry.
309 const MCSymbol *&TOCEntry = TOC[Sym];
311 TOCEntry = OutContext.
312 GetOrCreateSymbol(StringRef(MAI->getPrivateGlobalPrefix()) + "C" +
315 O << *TOCEntry << "@toc";
318 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
319 const char *Modifier);
322 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
323 class PPCLinuxAsmPrinter : public PPCAsmPrinter {
325 explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
326 MCContext &Ctx, MCStreamer &Streamer,
328 : PPCAsmPrinter(O, TM, Ctx, Streamer, T) {}
330 virtual const char *getPassName() const {
331 return "Linux PPC Assembly Printer";
334 bool doFinalization(Module &M);
336 virtual void EmitFunctionEntryLabel();
338 void getAnalysisUsage(AnalysisUsage &AU) const {
339 AU.setPreservesAll();
340 AU.addRequired<MachineModuleInfo>();
341 AU.addRequired<DwarfWriter>();
342 PPCAsmPrinter::getAnalysisUsage(AU);
346 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
348 class PPCDarwinAsmPrinter : public PPCAsmPrinter {
349 formatted_raw_ostream &OS;
351 explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
352 MCContext &Ctx, MCStreamer &Streamer,
354 : PPCAsmPrinter(O, TM, Ctx, Streamer, T), OS(O) {}
356 virtual const char *getPassName() const {
357 return "Darwin PPC Assembly Printer";
360 bool doFinalization(Module &M);
361 void EmitStartOfAsmFile(Module &M);
363 void EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs);
365 void getAnalysisUsage(AnalysisUsage &AU) const {
366 AU.setPreservesAll();
367 AU.addRequired<MachineModuleInfo>();
368 AU.addRequired<DwarfWriter>();
369 PPCAsmPrinter::getAnalysisUsage(AU);
372 } // end of anonymous namespace
374 // Include the auto-generated portion of the assembly writer
375 #include "PPCGenAsmWriter.inc"
377 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
378 switch (MO.getType()) {
379 case MachineOperand::MO_Immediate:
380 llvm_unreachable("printOp() does not handle immediate values");
382 case MachineOperand::MO_MachineBasicBlock:
383 O << *MO.getMBB()->getSymbol(OutContext);
385 case MachineOperand::MO_JumpTableIndex:
386 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
387 << '_' << MO.getIndex();
388 // FIXME: PIC relocation model
390 case MachineOperand::MO_ConstantPoolIndex:
391 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
392 << '_' << MO.getIndex();
394 case MachineOperand::MO_BlockAddress:
395 O << *GetBlockAddressSymbol(MO.getBlockAddress());
397 case MachineOperand::MO_ExternalSymbol: {
398 // Computing the address of an external symbol, not calling it.
399 if (TM.getRelocationModel() == Reloc::Static) {
400 O << *GetExternalSymbolSymbol(MO.getSymbolName());
404 const MCSymbol *NLPSym =
405 OutContext.GetOrCreateSymbol(StringRef(MAI->getGlobalPrefix())+
406 MO.getSymbolName()+"$non_lazy_ptr");
407 const MCSymbol *&StubSym =
408 MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(NLPSym);
410 StubSym = GetExternalSymbolSymbol(MO.getSymbolName());
415 case MachineOperand::MO_GlobalAddress: {
416 // Computing the address of a global symbol, not calling it.
417 GlobalValue *GV = MO.getGlobal();
418 MCSymbol *SymToPrint;
420 // External or weakly linked global variables need non-lazily-resolved stubs
421 if (TM.getRelocationModel() != Reloc::Static &&
422 (GV->isDeclaration() || GV->isWeakForLinker())) {
423 if (!GV->hasHiddenVisibility()) {
424 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
425 const MCSymbol *&StubSym =
426 MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(SymToPrint);
428 StubSym = GetGlobalValueSymbol(GV);
429 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
430 GV->hasAvailableExternallyLinkage()) {
431 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
433 const MCSymbol *&StubSym =
434 MMI->getObjFileInfo<MachineModuleInfoMachO>().
435 getHiddenGVStubEntry(SymToPrint);
437 StubSym = GetGlobalValueSymbol(GV);
439 SymToPrint = GetGlobalValueSymbol(GV);
442 SymToPrint = GetGlobalValueSymbol(GV);
447 printOffset(MO.getOffset());
452 O << "<unknown operand type: " << MO.getType() << ">";
457 /// PrintAsmOperand - Print out an operand for an inline asm expression.
459 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
461 const char *ExtraCode) {
462 // Does this asm operand have a single letter operand modifier?
463 if (ExtraCode && ExtraCode[0]) {
464 if (ExtraCode[1] != 0) return true; // Unknown modifier.
466 switch (ExtraCode[0]) {
467 default: return true; // Unknown modifier.
468 case 'c': // Don't print "$" before a global var name or constant.
469 // PPC never has a prefix.
470 printOperand(MI, OpNo);
472 case 'L': // Write second word of DImode reference.
473 // Verify that this operand has two consecutive registers.
474 if (!MI->getOperand(OpNo).isReg() ||
475 OpNo+1 == MI->getNumOperands() ||
476 !MI->getOperand(OpNo+1).isReg())
478 ++OpNo; // Return the high-part.
481 // Write 'i' if an integer constant, otherwise nothing. Used to print
483 if (MI->getOperand(OpNo).isImm())
489 printOperand(MI, OpNo);
493 // At the moment, all inline asm memory operands are a single register.
494 // In any case, the output of this routine should always be just one
495 // assembler operand.
497 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
499 const char *ExtraCode) {
500 if (ExtraCode && ExtraCode[0])
501 return true; // Unknown modifier.
502 assert (MI->getOperand(OpNo).isReg());
504 printOperand(MI, OpNo);
509 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
510 const char *Modifier) {
511 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
512 unsigned Code = MI->getOperand(OpNo).getImm();
513 if (!strcmp(Modifier, "cc")) {
514 switch ((PPC::Predicate)Code) {
515 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
516 case PPC::PRED_LT: O << "lt"; return;
517 case PPC::PRED_LE: O << "le"; return;
518 case PPC::PRED_EQ: O << "eq"; return;
519 case PPC::PRED_GE: O << "ge"; return;
520 case PPC::PRED_GT: O << "gt"; return;
521 case PPC::PRED_NE: O << "ne"; return;
522 case PPC::PRED_UN: O << "un"; return;
523 case PPC::PRED_NU: O << "nu"; return;
527 assert(!strcmp(Modifier, "reg") &&
528 "Need to specify 'cc' or 'reg' as predicate op modifier!");
529 // Don't print the register for 'always'.
530 if (Code == PPC::PRED_ALWAYS) return;
531 printOperand(MI, OpNo+1);
536 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
537 /// the current output stream.
539 void PPCAsmPrinter::EmitInstruction(const MachineInstr *MI) {
540 // Check for slwi/srwi mnemonics.
541 if (MI->getOpcode() == PPC::RLWINM) {
542 unsigned char SH = MI->getOperand(2).getImm();
543 unsigned char MB = MI->getOperand(3).getImm();
544 unsigned char ME = MI->getOperand(4).getImm();
545 bool useSubstituteMnemonic = false;
546 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
547 O << "\tslwi "; useSubstituteMnemonic = true;
549 if (SH <= 31 && MB == (32-SH) && ME == 31) {
550 O << "\tsrwi "; useSubstituteMnemonic = true;
553 if (useSubstituteMnemonic) {
557 O << ", " << (unsigned int)SH;
562 if ((MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) &&
563 MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
571 if (MI->getOpcode() == PPC::RLDICR) {
572 unsigned char SH = MI->getOperand(2).getImm();
573 unsigned char ME = MI->getOperand(3).getImm();
574 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
580 O << ", " << (unsigned int)SH;
585 printInstruction(MI);
588 void PPCLinuxAsmPrinter::EmitFunctionEntryLabel() {
589 if (!Subtarget.isPPC64()) // linux/ppc32 - Normal entry label.
590 return AsmPrinter::EmitFunctionEntryLabel();
592 // Emit an official procedure descriptor.
593 // FIXME 64-bit SVR4: Use MCSection here!
594 O << "\t.section\t\".opd\",\"aw\"\n";
596 OutStreamer.EmitLabel(CurrentFnSym);
597 O << "\t.quad .L." << *CurrentFnSym << ",.TOC.@tocbase\n";
598 O << "\t.previous\n";
599 O << ".L." << *CurrentFnSym << ":\n";
603 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
604 const TargetData *TD = TM.getTargetData();
606 bool isPPC64 = TD->getPointerSizeInBits() == 64;
608 if (isPPC64 && !TOC.empty()) {
609 // FIXME 64-bit SVR4: Use MCSection here?
610 O << "\t.section\t\".toc\",\"aw\"\n";
612 // FIXME: This is nondeterminstic!
613 for (DenseMap<const MCSymbol*, const MCSymbol*>::iterator I = TOC.begin(),
614 E = TOC.end(); I != E; ++I) {
615 O << *I->second << ":\n";
616 O << "\t.tc " << *I->first << "[TC]," << *I->first << '\n';
620 return AsmPrinter::doFinalization(M);
623 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
624 static const char *const CPUDirectives[] = {
636 unsigned Directive = Subtarget.getDarwinDirective();
637 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
638 Directive = PPC::DIR_970;
639 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
640 Directive = PPC::DIR_7400;
641 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
642 Directive = PPC::DIR_64;
643 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
644 O << "\t.machine " << CPUDirectives[Directive] << '\n';
646 // Prime text sections so they are adjacent. This reduces the likelihood a
647 // large data or debug section causes a branch to exceed 16M limit.
648 TargetLoweringObjectFileMachO &TLOFMacho =
649 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
650 OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
651 if (TM.getRelocationModel() == Reloc::PIC_) {
652 OutStreamer.SwitchSection(
653 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
654 MCSectionMachO::S_SYMBOL_STUBS |
655 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
656 32, SectionKind::getText()));
657 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
658 OutStreamer.SwitchSection(
659 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
660 MCSectionMachO::S_SYMBOL_STUBS |
661 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
662 16, SectionKind::getText()));
664 OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
667 static const MCSymbol *GetLazyPtr(const MCSymbol *Sym, MCContext &Ctx) {
668 // Remove $stub suffix, add $lazy_ptr.
669 SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end()-5);
670 TmpStr += "$lazy_ptr";
671 return Ctx.GetOrCreateSymbol(TmpStr.str());
674 static const MCSymbol *GetAnonSym(const MCSymbol *Sym, MCContext &Ctx) {
675 // Add $tmp suffix to $stub, yielding $stub$tmp.
676 SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end());
678 return Ctx.GetOrCreateSymbol(TmpStr.str());
681 void PPCDarwinAsmPrinter::
682 EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs) {
683 bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
685 TargetLoweringObjectFileMachO &TLOFMacho =
686 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
688 // .lazy_symbol_pointer
689 const MCSection *LSPSection = TLOFMacho.getLazySymbolPointerSection();
691 // Output stubs for dynamically-linked functions
692 if (TM.getRelocationModel() == Reloc::PIC_) {
693 const MCSection *StubSection =
694 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
695 MCSectionMachO::S_SYMBOL_STUBS |
696 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
697 32, SectionKind::getText());
698 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
699 OutStreamer.SwitchSection(StubSection);
702 const MCSymbol *Stub = Stubs[i].first;
703 const MCSymbol *RawSym = Stubs[i].second;
704 const MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
705 const MCSymbol *AnonSymbol = GetAnonSym(Stub, OutContext);
708 O << "\t.indirect_symbol " << *RawSym << '\n';
710 O << "\tbcl 20,31," << *AnonSymbol << '\n';
711 O << *AnonSymbol << ":\n";
713 O << "\taddis r11,r11,ha16(" << *LazyPtr << '-' << *AnonSymbol
716 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(" << *LazyPtr
717 << '-' << *AnonSymbol << ")(r11)\n";
718 O << "\tmtctr r12\n";
721 OutStreamer.SwitchSection(LSPSection);
722 O << *LazyPtr << ":\n";
723 O << "\t.indirect_symbol " << *RawSym << '\n';
724 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
730 const MCSection *StubSection =
731 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
732 MCSectionMachO::S_SYMBOL_STUBS |
733 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
734 16, SectionKind::getText());
735 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
736 const MCSymbol *Stub = Stubs[i].first;
737 const MCSymbol *RawSym = Stubs[i].second;
738 const MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
740 OutStreamer.SwitchSection(StubSection);
743 O << "\t.indirect_symbol " << *RawSym << '\n';
744 O << "\tlis r11,ha16(" << *LazyPtr << ")\n";
745 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(" << *LazyPtr
747 O << "\tmtctr r12\n";
749 OutStreamer.SwitchSection(LSPSection);
750 O << *LazyPtr << ":\n";
751 O << "\t.indirect_symbol " << *RawSym << '\n';
752 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
759 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
760 bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
762 // Darwin/PPC always uses mach-o.
763 TargetLoweringObjectFileMachO &TLOFMacho =
764 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
765 MachineModuleInfoMachO &MMIMacho =
766 MMI->getObjFileInfo<MachineModuleInfoMachO>();
768 MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetFnStubList();
770 EmitFunctionStubs(Stubs);
772 if (MAI->doesSupportExceptionHandling() && MMI) {
773 // Add the (possibly multiple) personalities to the set of global values.
774 // Only referenced functions get into the Personalities list.
775 const std::vector<Function *> &Personalities = MMI->getPersonalities();
776 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
777 E = Personalities.end(); I != E; ++I) {
779 const MCSymbol *NLPSym =
780 GetSymbolWithGlobalValueBase(*I, "$non_lazy_ptr");
781 const MCSymbol *&StubSym = MMIMacho.getGVStubEntry(NLPSym);
782 StubSym = GetGlobalValueSymbol(*I);
787 // Output stubs for dynamically-linked functions.
788 Stubs = MMIMacho.GetGVStubList();
790 // Output macho stubs for external and common global variables.
791 if (!Stubs.empty()) {
792 // Switch with ".non_lazy_symbol_pointer" directive.
793 OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
794 EmitAlignment(isPPC64 ? 3 : 2);
796 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
797 O << *Stubs[i].first << ":\n";
798 O << "\t.indirect_symbol " << *Stubs[i].second << '\n';
799 O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
803 Stubs = MMIMacho.GetHiddenGVStubList();
804 if (!Stubs.empty()) {
805 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
806 EmitAlignment(isPPC64 ? 3 : 2);
808 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
809 O << *Stubs[i].first << ":\n";
810 O << (isPPC64 ? "\t.quad\t" : "\t.long\t") << *Stubs[i].second << '\n';
814 // Funny Darwin hack: This flag tells the linker that no global symbols
815 // contain code that falls through to other global symbols (e.g. the obvious
816 // implementation of multiple entry points). If this doesn't occur, the
817 // linker can safely perform dead code stripping. Since LLVM never generates
818 // code that does this, it is always safe to set.
819 OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
821 return AsmPrinter::doFinalization(M);
826 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
827 /// for a MachineFunction to the given output stream, in a format that the
828 /// Darwin assembler can deal with.
830 static AsmPrinter *createPPCAsmPrinterPass(formatted_raw_ostream &o,
832 MCContext &Ctx, MCStreamer &Streamer,
833 const MCAsmInfo *tai) {
834 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
836 if (Subtarget->isDarwin())
837 return new PPCDarwinAsmPrinter(o, tm, Ctx, Streamer, tai);
838 return new PPCLinuxAsmPrinter(o, tm, Ctx, Streamer, tai);
841 // Force static initialization.
842 extern "C" void LLVMInitializePowerPCAsmPrinter() {
843 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
844 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);