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/CodeGen/TargetLoweringObjectFileImpl.h"
35 #include "llvm/MC/MCAsmInfo.h"
36 #include "llvm/MC/MCContext.h"
37 #include "llvm/MC/MCSectionMachO.h"
38 #include "llvm/MC/MCStreamer.h"
39 #include "llvm/MC/MCSymbol.h"
40 #include "llvm/Target/Mangler.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 MachineModuleInfoImpl::StubValueTy &StubSym =
202 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
203 if (StubSym.getPointer() == 0)
204 StubSym = MachineModuleInfoImpl::
205 StubValueTy(GetGlobalValueSymbol(GV),!GV->hasInternalLinkage());
210 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
211 SmallString<128> TempNameStr;
212 TempNameStr += StringRef(MO.getSymbolName());
213 TempNameStr += StringRef("$stub");
215 MCSymbol *Sym = GetExternalSymbolSymbol(TempNameStr.str());
216 MachineModuleInfoImpl::StubValueTy &StubSym =
217 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
218 if (StubSym.getPointer() == 0)
219 StubSym = MachineModuleInfoImpl::
220 StubValueTy(GetExternalSymbolSymbol(MO.getSymbolName()), true);
226 printOp(MI->getOperand(OpNo));
228 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
229 O << (int)MI->getOperand(OpNo).getImm()*4;
231 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
232 O << "\"L" << getFunctionNumber() << "$pb\"\n";
233 O << "\"L" << getFunctionNumber() << "$pb\":";
235 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
236 if (MI->getOperand(OpNo).isImm()) {
237 printS16ImmOperand(MI, OpNo);
239 if (Subtarget.isDarwin()) O << "ha16(";
240 printOp(MI->getOperand(OpNo));
241 if (TM.getRelocationModel() == Reloc::PIC_)
242 O << "-\"L" << getFunctionNumber() << "$pb\"";
243 if (Subtarget.isDarwin())
249 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
250 if (MI->getOperand(OpNo).isImm()) {
251 printS16ImmOperand(MI, OpNo);
253 if (Subtarget.isDarwin()) O << "lo16(";
254 printOp(MI->getOperand(OpNo));
255 if (TM.getRelocationModel() == Reloc::PIC_)
256 O << "-\"L" << getFunctionNumber() << "$pb\"";
257 if (Subtarget.isDarwin())
263 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
264 unsigned CCReg = MI->getOperand(OpNo).getReg();
265 unsigned RegNo = enumRegToMachineReg(CCReg);
266 O << (0x80 >> RegNo);
268 // The new addressing mode printers.
269 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
270 printSymbolLo(MI, OpNo);
272 if (MI->getOperand(OpNo+1).isReg() &&
273 MI->getOperand(OpNo+1).getReg() == PPC::R0)
276 printOperand(MI, OpNo+1);
279 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
280 if (MI->getOperand(OpNo).isImm())
281 printS16X4ImmOperand(MI, OpNo);
283 printSymbolLo(MI, OpNo);
285 if (MI->getOperand(OpNo+1).isReg() &&
286 MI->getOperand(OpNo+1).getReg() == PPC::R0)
289 printOperand(MI, OpNo+1);
293 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
294 // When used as the base register, r0 reads constant zero rather than
295 // the value contained in the register. For this reason, the darwin
296 // assembler requires that we print r0 as 0 (no r) when used as the base.
297 const MachineOperand &MO = MI->getOperand(OpNo);
298 printRegister(MO, true);
300 printOperand(MI, OpNo+1);
303 void printTOCEntryLabel(const MachineInstr *MI, unsigned OpNo) {
304 const MachineOperand &MO = MI->getOperand(OpNo);
306 assert(MO.getType() == MachineOperand::MO_GlobalAddress);
308 const MCSymbol *Sym = GetGlobalValueSymbol(MO.getGlobal());
310 // Map symbol -> label of TOC entry.
311 const MCSymbol *&TOCEntry = TOC[Sym];
313 TOCEntry = OutContext.
314 GetOrCreateTemporarySymbol(StringRef(MAI->getPrivateGlobalPrefix()) +
315 "C" + Twine(LabelID++));
317 O << *TOCEntry << "@toc";
320 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
321 const char *Modifier);
324 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
325 class PPCLinuxAsmPrinter : public PPCAsmPrinter {
327 explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
328 MCContext &Ctx, MCStreamer &Streamer,
330 : PPCAsmPrinter(O, TM, Ctx, Streamer, T) {}
332 virtual const char *getPassName() const {
333 return "Linux PPC Assembly Printer";
336 bool doFinalization(Module &M);
338 virtual void EmitFunctionEntryLabel();
340 void getAnalysisUsage(AnalysisUsage &AU) const {
341 AU.setPreservesAll();
342 AU.addRequired<MachineModuleInfo>();
343 AU.addRequired<DwarfWriter>();
344 PPCAsmPrinter::getAnalysisUsage(AU);
348 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
350 class PPCDarwinAsmPrinter : public PPCAsmPrinter {
351 formatted_raw_ostream &OS;
353 explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
354 MCContext &Ctx, MCStreamer &Streamer,
356 : PPCAsmPrinter(O, TM, Ctx, Streamer, T), OS(O) {}
358 virtual const char *getPassName() const {
359 return "Darwin PPC Assembly Printer";
362 bool doFinalization(Module &M);
363 void EmitStartOfAsmFile(Module &M);
365 void EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs);
367 void getAnalysisUsage(AnalysisUsage &AU) const {
368 AU.setPreservesAll();
369 AU.addRequired<MachineModuleInfo>();
370 AU.addRequired<DwarfWriter>();
371 PPCAsmPrinter::getAnalysisUsage(AU);
374 } // end of anonymous namespace
376 // Include the auto-generated portion of the assembly writer
377 #include "PPCGenAsmWriter.inc"
379 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
380 switch (MO.getType()) {
381 case MachineOperand::MO_Immediate:
382 llvm_unreachable("printOp() does not handle immediate values");
384 case MachineOperand::MO_MachineBasicBlock:
385 O << *MO.getMBB()->getSymbol(OutContext);
387 case MachineOperand::MO_JumpTableIndex:
388 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
389 << '_' << MO.getIndex();
390 // FIXME: PIC relocation model
392 case MachineOperand::MO_ConstantPoolIndex:
393 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
394 << '_' << MO.getIndex();
396 case MachineOperand::MO_BlockAddress:
397 O << *GetBlockAddressSymbol(MO.getBlockAddress());
399 case MachineOperand::MO_ExternalSymbol: {
400 // Computing the address of an external symbol, not calling it.
401 if (TM.getRelocationModel() == Reloc::Static) {
402 O << *GetExternalSymbolSymbol(MO.getSymbolName());
407 OutContext.GetOrCreateSymbol(StringRef(MAI->getGlobalPrefix())+
408 MO.getSymbolName()+"$non_lazy_ptr");
409 MachineModuleInfoImpl::StubValueTy &StubSym =
410 MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(NLPSym);
411 if (StubSym.getPointer() == 0)
412 StubSym = MachineModuleInfoImpl::
413 StubValueTy(GetExternalSymbolSymbol(MO.getSymbolName()), true);
418 case MachineOperand::MO_GlobalAddress: {
419 // Computing the address of a global symbol, not calling it.
420 GlobalValue *GV = MO.getGlobal();
421 MCSymbol *SymToPrint;
423 // External or weakly linked global variables need non-lazily-resolved stubs
424 if (TM.getRelocationModel() != Reloc::Static &&
425 (GV->isDeclaration() || GV->isWeakForLinker())) {
426 if (!GV->hasHiddenVisibility()) {
427 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
428 MachineModuleInfoImpl::StubValueTy &StubSym =
429 MMI->getObjFileInfo<MachineModuleInfoMachO>()
430 .getGVStubEntry(SymToPrint);
431 if (StubSym.getPointer() == 0)
432 StubSym = MachineModuleInfoImpl::
433 StubValueTy(GetGlobalValueSymbol(GV), !GV->hasInternalLinkage());
434 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
435 GV->hasAvailableExternallyLinkage()) {
436 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
438 MachineModuleInfoImpl::StubValueTy &StubSym =
439 MMI->getObjFileInfo<MachineModuleInfoMachO>().
440 getHiddenGVStubEntry(SymToPrint);
441 if (StubSym.getPointer() == 0)
442 StubSym = MachineModuleInfoImpl::
443 StubValueTy(GetGlobalValueSymbol(GV),
444 !GV->hasInternalLinkage());
446 SymToPrint = GetGlobalValueSymbol(GV);
449 SymToPrint = GetGlobalValueSymbol(GV);
454 printOffset(MO.getOffset());
459 O << "<unknown operand type: " << MO.getType() << ">";
464 /// PrintAsmOperand - Print out an operand for an inline asm expression.
466 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
468 const char *ExtraCode) {
469 // Does this asm operand have a single letter operand modifier?
470 if (ExtraCode && ExtraCode[0]) {
471 if (ExtraCode[1] != 0) return true; // Unknown modifier.
473 switch (ExtraCode[0]) {
474 default: return true; // Unknown modifier.
475 case 'c': // Don't print "$" before a global var name or constant.
476 // PPC never has a prefix.
477 printOperand(MI, OpNo);
479 case 'L': // Write second word of DImode reference.
480 // Verify that this operand has two consecutive registers.
481 if (!MI->getOperand(OpNo).isReg() ||
482 OpNo+1 == MI->getNumOperands() ||
483 !MI->getOperand(OpNo+1).isReg())
485 ++OpNo; // Return the high-part.
488 // Write 'i' if an integer constant, otherwise nothing. Used to print
490 if (MI->getOperand(OpNo).isImm())
496 printOperand(MI, OpNo);
500 // At the moment, all inline asm memory operands are a single register.
501 // In any case, the output of this routine should always be just one
502 // assembler operand.
504 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
506 const char *ExtraCode) {
507 if (ExtraCode && ExtraCode[0])
508 return true; // Unknown modifier.
509 assert (MI->getOperand(OpNo).isReg());
511 printOperand(MI, OpNo);
516 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
517 const char *Modifier) {
518 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
519 unsigned Code = MI->getOperand(OpNo).getImm();
520 if (!strcmp(Modifier, "cc")) {
521 switch ((PPC::Predicate)Code) {
522 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
523 case PPC::PRED_LT: O << "lt"; return;
524 case PPC::PRED_LE: O << "le"; return;
525 case PPC::PRED_EQ: O << "eq"; return;
526 case PPC::PRED_GE: O << "ge"; return;
527 case PPC::PRED_GT: O << "gt"; return;
528 case PPC::PRED_NE: O << "ne"; return;
529 case PPC::PRED_UN: O << "un"; return;
530 case PPC::PRED_NU: O << "nu"; return;
534 assert(!strcmp(Modifier, "reg") &&
535 "Need to specify 'cc' or 'reg' as predicate op modifier!");
536 // Don't print the register for 'always'.
537 if (Code == PPC::PRED_ALWAYS) return;
538 printOperand(MI, OpNo+1);
543 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
544 /// the current output stream.
546 void PPCAsmPrinter::EmitInstruction(const MachineInstr *MI) {
547 // Check for slwi/srwi mnemonics.
548 if (MI->getOpcode() == PPC::RLWINM) {
549 unsigned char SH = MI->getOperand(2).getImm();
550 unsigned char MB = MI->getOperand(3).getImm();
551 unsigned char ME = MI->getOperand(4).getImm();
552 bool useSubstituteMnemonic = false;
553 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
554 O << "\tslwi "; useSubstituteMnemonic = true;
556 if (SH <= 31 && MB == (32-SH) && ME == 31) {
557 O << "\tsrwi "; useSubstituteMnemonic = true;
560 if (useSubstituteMnemonic) {
564 O << ", " << (unsigned int)SH;
565 OutStreamer.AddBlankLine();
570 if ((MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) &&
571 MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
576 OutStreamer.AddBlankLine();
580 if (MI->getOpcode() == PPC::RLDICR) {
581 unsigned char SH = MI->getOperand(2).getImm();
582 unsigned char ME = MI->getOperand(3).getImm();
583 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
589 O << ", " << (unsigned int)SH;
590 OutStreamer.AddBlankLine();
595 printInstruction(MI);
596 OutStreamer.AddBlankLine();
599 void PPCLinuxAsmPrinter::EmitFunctionEntryLabel() {
600 if (!Subtarget.isPPC64()) // linux/ppc32 - Normal entry label.
601 return AsmPrinter::EmitFunctionEntryLabel();
603 // Emit an official procedure descriptor.
604 // FIXME 64-bit SVR4: Use MCSection here!
605 O << "\t.section\t\".opd\",\"aw\"\n";
607 OutStreamer.EmitLabel(CurrentFnSym);
608 O << "\t.quad .L." << *CurrentFnSym << ",.TOC.@tocbase\n";
609 O << "\t.previous\n";
610 O << ".L." << *CurrentFnSym << ":\n";
614 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
615 const TargetData *TD = TM.getTargetData();
617 bool isPPC64 = TD->getPointerSizeInBits() == 64;
619 if (isPPC64 && !TOC.empty()) {
620 // FIXME 64-bit SVR4: Use MCSection here?
621 O << "\t.section\t\".toc\",\"aw\"\n";
623 // FIXME: This is nondeterminstic!
624 for (DenseMap<const MCSymbol*, const MCSymbol*>::iterator I = TOC.begin(),
625 E = TOC.end(); I != E; ++I) {
626 O << *I->second << ":\n";
627 O << "\t.tc " << *I->first << "[TC]," << *I->first << '\n';
631 return AsmPrinter::doFinalization(M);
634 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
635 static const char *const CPUDirectives[] = {
647 unsigned Directive = Subtarget.getDarwinDirective();
648 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
649 Directive = PPC::DIR_970;
650 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
651 Directive = PPC::DIR_7400;
652 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
653 Directive = PPC::DIR_64;
654 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
655 O << "\t.machine " << CPUDirectives[Directive] << '\n';
657 // Prime text sections so they are adjacent. This reduces the likelihood a
658 // large data or debug section causes a branch to exceed 16M limit.
659 TargetLoweringObjectFileMachO &TLOFMacho =
660 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
661 OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
662 if (TM.getRelocationModel() == Reloc::PIC_) {
663 OutStreamer.SwitchSection(
664 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
665 MCSectionMachO::S_SYMBOL_STUBS |
666 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
667 32, SectionKind::getText()));
668 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
669 OutStreamer.SwitchSection(
670 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
671 MCSectionMachO::S_SYMBOL_STUBS |
672 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
673 16, SectionKind::getText()));
675 OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
678 static const MCSymbol *GetLazyPtr(const MCSymbol *Sym, MCContext &Ctx) {
679 // Remove $stub suffix, add $lazy_ptr.
680 SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end()-5);
681 TmpStr += "$lazy_ptr";
682 return Ctx.GetOrCreateTemporarySymbol(TmpStr.str());
685 static const MCSymbol *GetAnonSym(const MCSymbol *Sym, MCContext &Ctx) {
686 // Add $tmp suffix to $stub, yielding $stub$tmp.
687 SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end());
689 return Ctx.GetOrCreateTemporarySymbol(TmpStr.str());
692 void PPCDarwinAsmPrinter::
693 EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs) {
694 bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
696 TargetLoweringObjectFileMachO &TLOFMacho =
697 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
699 // .lazy_symbol_pointer
700 const MCSection *LSPSection = TLOFMacho.getLazySymbolPointerSection();
702 // Output stubs for dynamically-linked functions
703 if (TM.getRelocationModel() == Reloc::PIC_) {
704 const MCSection *StubSection =
705 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
706 MCSectionMachO::S_SYMBOL_STUBS |
707 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
708 32, SectionKind::getText());
709 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
710 OutStreamer.SwitchSection(StubSection);
713 const MCSymbol *Stub = Stubs[i].first;
714 const MCSymbol *RawSym = Stubs[i].second.getPointer();
715 const MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
716 const MCSymbol *AnonSymbol = GetAnonSym(Stub, OutContext);
719 O << "\t.indirect_symbol " << *RawSym << '\n';
721 O << "\tbcl 20,31," << *AnonSymbol << '\n';
722 O << *AnonSymbol << ":\n";
724 O << "\taddis r11,r11,ha16(" << *LazyPtr << '-' << *AnonSymbol
727 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(" << *LazyPtr
728 << '-' << *AnonSymbol << ")(r11)\n";
729 O << "\tmtctr r12\n";
732 OutStreamer.SwitchSection(LSPSection);
733 O << *LazyPtr << ":\n";
734 O << "\t.indirect_symbol " << *RawSym << '\n';
735 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
741 const MCSection *StubSection =
742 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
743 MCSectionMachO::S_SYMBOL_STUBS |
744 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
745 16, SectionKind::getText());
746 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
747 const MCSymbol *Stub = Stubs[i].first;
748 const MCSymbol *RawSym = Stubs[i].second.getPointer();
749 const MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
751 OutStreamer.SwitchSection(StubSection);
754 O << "\t.indirect_symbol " << *RawSym << '\n';
755 O << "\tlis r11,ha16(" << *LazyPtr << ")\n";
756 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(" << *LazyPtr
758 O << "\tmtctr r12\n";
760 OutStreamer.SwitchSection(LSPSection);
761 O << *LazyPtr << ":\n";
762 O << "\t.indirect_symbol " << *RawSym << '\n';
763 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
770 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
771 bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
773 // Darwin/PPC always uses mach-o.
774 TargetLoweringObjectFileMachO &TLOFMacho =
775 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
776 MachineModuleInfoMachO &MMIMacho =
777 MMI->getObjFileInfo<MachineModuleInfoMachO>();
779 MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetFnStubList();
781 EmitFunctionStubs(Stubs);
783 if (MAI->doesSupportExceptionHandling() && MMI) {
784 // Add the (possibly multiple) personalities to the set of global values.
785 // Only referenced functions get into the Personalities list.
786 const std::vector<Function *> &Personalities = MMI->getPersonalities();
787 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
788 E = Personalities.end(); I != E; ++I) {
790 MCSymbol *NLPSym = GetSymbolWithGlobalValueBase(*I, "$non_lazy_ptr");
791 MachineModuleInfoImpl::StubValueTy &StubSym =
792 MMIMacho.getGVStubEntry(NLPSym);
793 StubSym = MachineModuleInfoImpl::
794 StubValueTy(GetGlobalValueSymbol(*I), true);
799 // Output stubs for dynamically-linked functions.
800 Stubs = MMIMacho.GetGVStubList();
802 // Output macho stubs for external and common global variables.
803 if (!Stubs.empty()) {
804 // Switch with ".non_lazy_symbol_pointer" directive.
805 OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
806 EmitAlignment(isPPC64 ? 3 : 2);
808 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
809 O << *Stubs[i].first << ":\n";
810 O << "\t.indirect_symbol " << *Stubs[i].second.getPointer() << '\n';
811 // FIXME: This should use the "GV is external" bit.
812 O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
816 Stubs = MMIMacho.GetHiddenGVStubList();
817 if (!Stubs.empty()) {
818 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
819 EmitAlignment(isPPC64 ? 3 : 2);
821 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
822 O << *Stubs[i].first << ":\n";
823 O << (isPPC64 ? "\t.quad\t" : "\t.long\t")
824 << *Stubs[i].second.getPointer() << '\n';
828 // Funny Darwin hack: This flag tells the linker that no global symbols
829 // contain code that falls through to other global symbols (e.g. the obvious
830 // implementation of multiple entry points). If this doesn't occur, the
831 // linker can safely perform dead code stripping. Since LLVM never generates
832 // code that does this, it is always safe to set.
833 OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
835 return AsmPrinter::doFinalization(M);
840 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
841 /// for a MachineFunction to the given output stream, in a format that the
842 /// Darwin assembler can deal with.
844 static AsmPrinter *createPPCAsmPrinterPass(formatted_raw_ostream &o,
846 MCContext &Ctx, MCStreamer &Streamer,
847 const MCAsmInfo *tai) {
848 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
850 if (Subtarget->isDarwin())
851 return new PPCDarwinAsmPrinter(o, tm, Ctx, Streamer, tai);
852 return new PPCLinuxAsmPrinter(o, tm, Ctx, Streamer, tai);
855 // Force static initialization.
856 extern "C" void LLVMInitializePowerPCAsmPrinter() {
857 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
858 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);