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/MCExpr.h"
38 #include "llvm/MC/MCSectionMachO.h"
39 #include "llvm/MC/MCStreamer.h"
40 #include "llvm/MC/MCSymbol.h"
41 #include "llvm/Target/Mangler.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #include "llvm/Target/TargetInstrInfo.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/Target/TargetRegistry.h"
46 #include "llvm/Support/MathExtras.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/ADT/StringExtras.h"
50 #include "llvm/ADT/StringSet.h"
51 #include "llvm/ADT/SmallString.h"
55 class PPCAsmPrinter : public AsmPrinter {
57 DenseMap<MCSymbol*, MCSymbol*> TOC;
58 const PPCSubtarget &Subtarget;
61 explicit PPCAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
62 : AsmPrinter(TM, Streamer),
63 Subtarget(TM.getSubtarget<PPCSubtarget>()), LabelID(0) {}
65 virtual const char *getPassName() const {
66 return "PowerPC Assembly Printer";
69 PPCTargetMachine &getTM() {
70 return static_cast<PPCTargetMachine&>(TM);
73 unsigned enumRegToMachineReg(unsigned enumReg) {
75 default: llvm_unreachable("Unhandled register!");
76 case PPC::CR0: return 0;
77 case PPC::CR1: return 1;
78 case PPC::CR2: return 2;
79 case PPC::CR3: return 3;
80 case PPC::CR4: return 4;
81 case PPC::CR5: return 5;
82 case PPC::CR6: return 6;
83 case PPC::CR7: return 7;
88 /// printInstruction - This method is automatically generated by tablegen
89 /// from the instruction set description. This method returns true if the
90 /// machine instruction was sufficiently described to print it, otherwise it
92 void printInstruction(const MachineInstr *MI, raw_ostream &O);
93 static const char *getRegisterName(unsigned RegNo);
96 virtual void EmitInstruction(const MachineInstr *MI);
97 void printOp(const MachineOperand &MO, raw_ostream &O);
99 /// stripRegisterPrefix - This method strips the character prefix from a
100 /// register name so that only the number is left. Used by for linux asm.
101 const char *stripRegisterPrefix(const char *RegName) {
102 switch (RegName[0]) {
105 case 'v': return RegName + 1;
106 case 'c': if (RegName[1] == 'r') return RegName + 2;
112 /// printRegister - Print register according to target requirements.
114 void printRegister(const MachineOperand &MO, bool R0AsZero, raw_ostream &O){
115 unsigned RegNo = MO.getReg();
116 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
118 // If we should use 0 for R0.
119 if (R0AsZero && RegNo == PPC::R0) {
124 const char *RegName = getRegisterName(RegNo);
125 // Linux assembler (Others?) does not take register mnemonics.
126 // FIXME - What about special registers used in mfspr/mtspr?
127 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
131 void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
132 const MachineOperand &MO = MI->getOperand(OpNo);
134 printRegister(MO, false, O);
135 } else if (MO.isImm()) {
142 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
143 unsigned AsmVariant, const char *ExtraCode,
145 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
146 unsigned AsmVariant, const char *ExtraCode,
150 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,
158 unsigned char value = MI->getOperand(OpNo).getImm();
159 assert(value <= 31 && "Invalid u5imm argument!");
160 O << (unsigned int)value;
162 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo,
164 unsigned char value = MI->getOperand(OpNo).getImm();
165 assert(value <= 63 && "Invalid u6imm argument!");
166 O << (unsigned int)value;
168 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo,
170 O << (short)MI->getOperand(OpNo).getImm();
172 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo,
174 O << (unsigned short)MI->getOperand(OpNo).getImm();
176 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo,
178 if (MI->getOperand(OpNo).isImm()) {
179 O << (short)(MI->getOperand(OpNo).getImm()*4);
182 printOp(MI->getOperand(OpNo), O);
183 if (TM.getRelocationModel() == Reloc::PIC_)
184 O << "-\"L" << getFunctionNumber() << "$pb\")";
189 void printBranchOperand(const MachineInstr *MI, unsigned OpNo,
191 // Branches can take an immediate operand. This is used by the branch
192 // selection pass to print $+8, an eight byte displacement from the PC.
193 if (MI->getOperand(OpNo).isImm()) {
194 O << "$+" << MI->getOperand(OpNo).getImm()*4;
196 printOp(MI->getOperand(OpNo), O);
199 void printCallOperand(const MachineInstr *MI, unsigned OpNo,
201 const MachineOperand &MO = MI->getOperand(OpNo);
202 if (TM.getRelocationModel() != Reloc::Static) {
203 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
204 GlobalValue *GV = MO.getGlobal();
205 if (GV->isDeclaration() || GV->isWeakForLinker()) {
206 // Dynamically-resolved functions need a stub for the function.
207 MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$stub");
208 MachineModuleInfoImpl::StubValueTy &StubSym =
209 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
210 if (StubSym.getPointer() == 0)
211 StubSym = MachineModuleInfoImpl::
212 StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
217 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
218 SmallString<128> TempNameStr;
219 TempNameStr += StringRef(MO.getSymbolName());
220 TempNameStr += StringRef("$stub");
222 MCSymbol *Sym = GetExternalSymbolSymbol(TempNameStr.str());
223 MachineModuleInfoImpl::StubValueTy &StubSym =
224 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
225 if (StubSym.getPointer() == 0)
226 StubSym = MachineModuleInfoImpl::
227 StubValueTy(GetExternalSymbolSymbol(MO.getSymbolName()), true);
233 printOp(MI->getOperand(OpNo), O);
235 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo,
237 O << (int)MI->getOperand(OpNo).getImm()*4;
239 void printPICLabel(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
240 O << "\"L" << getFunctionNumber() << "$pb\"\n";
241 O << "\"L" << getFunctionNumber() << "$pb\":";
243 void printSymbolHi(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
244 if (MI->getOperand(OpNo).isImm()) {
245 printS16ImmOperand(MI, OpNo, O);
247 if (Subtarget.isDarwin()) O << "ha16(";
248 printOp(MI->getOperand(OpNo), O);
249 if (TM.getRelocationModel() == Reloc::PIC_)
250 O << "-\"L" << getFunctionNumber() << "$pb\"";
251 if (Subtarget.isDarwin())
257 void printSymbolLo(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
258 if (MI->getOperand(OpNo).isImm()) {
259 printS16ImmOperand(MI, OpNo, O);
261 if (Subtarget.isDarwin()) O << "lo16(";
262 printOp(MI->getOperand(OpNo), O);
263 if (TM.getRelocationModel() == Reloc::PIC_)
264 O << "-\"L" << getFunctionNumber() << "$pb\"";
265 if (Subtarget.isDarwin())
271 void printcrbitm(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
272 unsigned CCReg = MI->getOperand(OpNo).getReg();
273 unsigned RegNo = enumRegToMachineReg(CCReg);
274 O << (0x80 >> RegNo);
276 // The new addressing mode printers.
277 void printMemRegImm(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
278 printSymbolLo(MI, OpNo, O);
280 if (MI->getOperand(OpNo+1).isReg() &&
281 MI->getOperand(OpNo+1).getReg() == PPC::R0)
284 printOperand(MI, OpNo+1, O);
287 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo,
289 if (MI->getOperand(OpNo).isImm())
290 printS16X4ImmOperand(MI, OpNo, O);
292 printSymbolLo(MI, OpNo, O);
294 if (MI->getOperand(OpNo+1).isReg() &&
295 MI->getOperand(OpNo+1).getReg() == PPC::R0)
298 printOperand(MI, OpNo+1, O);
302 void printMemRegReg(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
303 // When used as the base register, r0 reads constant zero rather than
304 // the value contained in the register. For this reason, the darwin
305 // assembler requires that we print r0 as 0 (no r) when used as the base.
306 const MachineOperand &MO = MI->getOperand(OpNo);
307 printRegister(MO, true, O);
309 printOperand(MI, OpNo+1, O);
312 void printTOCEntryLabel(const MachineInstr *MI, unsigned OpNo,
314 const MachineOperand &MO = MI->getOperand(OpNo);
315 assert(MO.getType() == MachineOperand::MO_GlobalAddress);
316 MCSymbol *Sym = Mang->getSymbol(MO.getGlobal());
318 // Map symbol -> label of TOC entry.
319 MCSymbol *&TOCEntry = TOC[Sym];
321 TOCEntry = OutContext.
322 GetOrCreateSymbol(StringRef(MAI->getPrivateGlobalPrefix()) +
323 "C" + Twine(LabelID++));
325 O << *TOCEntry << "@toc";
328 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
329 raw_ostream &O, const char *Modifier);
332 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
333 class PPCLinuxAsmPrinter : public PPCAsmPrinter {
335 explicit PPCLinuxAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
336 : PPCAsmPrinter(TM, Streamer) {}
338 virtual const char *getPassName() const {
339 return "Linux PPC Assembly Printer";
342 bool doFinalization(Module &M);
344 virtual void EmitFunctionEntryLabel();
346 void getAnalysisUsage(AnalysisUsage &AU) const {
347 AU.addRequired<DwarfWriter>();
348 PPCAsmPrinter::getAnalysisUsage(AU);
352 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
354 class PPCDarwinAsmPrinter : public PPCAsmPrinter {
356 explicit PPCDarwinAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
357 : PPCAsmPrinter(TM, Streamer) {}
359 virtual const char *getPassName() const {
360 return "Darwin PPC Assembly Printer";
363 bool doFinalization(Module &M);
364 void EmitStartOfAsmFile(Module &M);
366 void EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs);
368 void getAnalysisUsage(AnalysisUsage &AU) const {
369 AU.setPreservesAll();
370 AU.addRequired<MachineModuleInfo>();
371 AU.addRequired<DwarfWriter>();
372 PPCAsmPrinter::getAnalysisUsage(AU);
375 } // end of anonymous namespace
377 // Include the auto-generated portion of the assembly writer
378 #include "PPCGenAsmWriter.inc"
380 void PPCAsmPrinter::printOp(const MachineOperand &MO, raw_ostream &O) {
381 switch (MO.getType()) {
382 case MachineOperand::MO_Immediate:
383 llvm_unreachable("printOp() does not handle immediate values");
385 case MachineOperand::MO_MachineBasicBlock:
386 O << *MO.getMBB()->getSymbol();
388 case MachineOperand::MO_JumpTableIndex:
389 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
390 << '_' << MO.getIndex();
391 // FIXME: PIC relocation model
393 case MachineOperand::MO_ConstantPoolIndex:
394 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
395 << '_' << MO.getIndex();
397 case MachineOperand::MO_BlockAddress:
398 O << *GetBlockAddressSymbol(MO.getBlockAddress());
400 case MachineOperand::MO_ExternalSymbol: {
401 // Computing the address of an external symbol, not calling it.
402 if (TM.getRelocationModel() == Reloc::Static) {
403 O << *GetExternalSymbolSymbol(MO.getSymbolName());
408 OutContext.GetOrCreateSymbol(StringRef(MAI->getGlobalPrefix())+
409 MO.getSymbolName()+"$non_lazy_ptr");
410 MachineModuleInfoImpl::StubValueTy &StubSym =
411 MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(NLPSym);
412 if (StubSym.getPointer() == 0)
413 StubSym = MachineModuleInfoImpl::
414 StubValueTy(GetExternalSymbolSymbol(MO.getSymbolName()), true);
419 case MachineOperand::MO_GlobalAddress: {
420 // Computing the address of a global symbol, not calling it.
421 GlobalValue *GV = MO.getGlobal();
422 MCSymbol *SymToPrint;
424 // External or weakly linked global variables need non-lazily-resolved stubs
425 if (TM.getRelocationModel() != Reloc::Static &&
426 (GV->isDeclaration() || GV->isWeakForLinker())) {
427 if (!GV->hasHiddenVisibility()) {
428 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
429 MachineModuleInfoImpl::StubValueTy &StubSym =
430 MMI->getObjFileInfo<MachineModuleInfoMachO>()
431 .getGVStubEntry(SymToPrint);
432 if (StubSym.getPointer() == 0)
433 StubSym = MachineModuleInfoImpl::
434 StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
435 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
436 GV->hasAvailableExternallyLinkage()) {
437 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
439 MachineModuleInfoImpl::StubValueTy &StubSym =
440 MMI->getObjFileInfo<MachineModuleInfoMachO>().
441 getHiddenGVStubEntry(SymToPrint);
442 if (StubSym.getPointer() == 0)
443 StubSym = MachineModuleInfoImpl::
444 StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
446 SymToPrint = Mang->getSymbol(GV);
449 SymToPrint = Mang->getSymbol(GV);
454 printOffset(MO.getOffset(), O);
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, raw_ostream &O) {
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, O);
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, O);
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,
508 if (ExtraCode && ExtraCode[0])
509 return true; // Unknown modifier.
510 assert (MI->getOperand(OpNo).isReg());
512 printOperand(MI, OpNo, O);
517 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
518 raw_ostream &O, const char *Modifier){
519 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
520 unsigned Code = MI->getOperand(OpNo).getImm();
521 if (!strcmp(Modifier, "cc")) {
522 switch ((PPC::Predicate)Code) {
523 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
524 case PPC::PRED_LT: O << "lt"; return;
525 case PPC::PRED_LE: O << "le"; return;
526 case PPC::PRED_EQ: O << "eq"; return;
527 case PPC::PRED_GE: O << "ge"; return;
528 case PPC::PRED_GT: O << "gt"; return;
529 case PPC::PRED_NE: O << "ne"; return;
530 case PPC::PRED_UN: O << "un"; return;
531 case PPC::PRED_NU: O << "nu"; return;
535 assert(!strcmp(Modifier, "reg") &&
536 "Need to specify 'cc' or 'reg' as predicate op modifier!");
537 // Don't print the register for 'always'.
538 if (Code == PPC::PRED_ALWAYS) return;
539 printOperand(MI, OpNo+1, O);
544 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
545 /// the current output stream.
547 void PPCAsmPrinter::EmitInstruction(const MachineInstr *MI) {
548 SmallString<128> Str;
549 raw_svector_ostream O(Str);
551 // Check for slwi/srwi mnemonics.
552 if (MI->getOpcode() == PPC::RLWINM) {
553 unsigned char SH = MI->getOperand(2).getImm();
554 unsigned char MB = MI->getOperand(3).getImm();
555 unsigned char ME = MI->getOperand(4).getImm();
556 bool useSubstituteMnemonic = false;
557 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
558 O << "\tslwi "; useSubstituteMnemonic = true;
560 if (SH <= 31 && MB == (32-SH) && ME == 31) {
561 O << "\tsrwi "; useSubstituteMnemonic = true;
564 if (useSubstituteMnemonic) {
565 printOperand(MI, 0, O);
567 printOperand(MI, 1, O);
568 O << ", " << (unsigned int)SH;
569 OutStreamer.EmitRawText(O.str());
574 if ((MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) &&
575 MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
577 printOperand(MI, 0, O);
579 printOperand(MI, 1, O);
580 OutStreamer.EmitRawText(O.str());
584 if (MI->getOpcode() == PPC::RLDICR) {
585 unsigned char SH = MI->getOperand(2).getImm();
586 unsigned char ME = MI->getOperand(3).getImm();
587 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
590 printOperand(MI, 0, O);
592 printOperand(MI, 1, O);
593 O << ", " << (unsigned int)SH;
594 OutStreamer.EmitRawText(O.str());
599 printInstruction(MI, O);
600 OutStreamer.EmitRawText(O.str());
603 void PPCLinuxAsmPrinter::EmitFunctionEntryLabel() {
604 if (!Subtarget.isPPC64()) // linux/ppc32 - Normal entry label.
605 return AsmPrinter::EmitFunctionEntryLabel();
607 // Emit an official procedure descriptor.
608 // FIXME 64-bit SVR4: Use MCSection here!
609 OutStreamer.EmitRawText(StringRef("\t.section\t\".opd\",\"aw\""));
610 OutStreamer.EmitRawText(StringRef("\t.align 3"));
611 OutStreamer.EmitLabel(CurrentFnSym);
612 OutStreamer.EmitRawText("\t.quad .L." + Twine(CurrentFnSym->getName()) +
614 OutStreamer.EmitRawText(StringRef("\t.previous"));
615 OutStreamer.EmitRawText(".L." + Twine(CurrentFnSym->getName()) + ":");
619 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
620 const TargetData *TD = TM.getTargetData();
622 bool isPPC64 = TD->getPointerSizeInBits() == 64;
624 if (isPPC64 && !TOC.empty()) {
625 // FIXME 64-bit SVR4: Use MCSection here?
626 OutStreamer.EmitRawText(StringRef("\t.section\t\".toc\",\"aw\""));
628 // FIXME: This is nondeterminstic!
629 for (DenseMap<MCSymbol*, MCSymbol*>::iterator I = TOC.begin(),
630 E = TOC.end(); I != E; ++I) {
631 OutStreamer.EmitLabel(I->second);
632 OutStreamer.EmitRawText("\t.tc " + Twine(I->first->getName()) +
633 "[TC]," + I->first->getName());
637 return AsmPrinter::doFinalization(M);
640 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
641 static const char *const CPUDirectives[] = {
653 unsigned Directive = Subtarget.getDarwinDirective();
654 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
655 Directive = PPC::DIR_970;
656 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
657 Directive = PPC::DIR_7400;
658 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
659 Directive = PPC::DIR_64;
660 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
661 OutStreamer.EmitRawText("\t.machine " + Twine(CPUDirectives[Directive]));
663 // Prime text sections so they are adjacent. This reduces the likelihood a
664 // large data or debug section causes a branch to exceed 16M limit.
665 TargetLoweringObjectFileMachO &TLOFMacho =
666 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
667 OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
668 if (TM.getRelocationModel() == Reloc::PIC_) {
669 OutStreamer.SwitchSection(
670 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
671 MCSectionMachO::S_SYMBOL_STUBS |
672 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
673 32, SectionKind::getText()));
674 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
675 OutStreamer.SwitchSection(
676 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
677 MCSectionMachO::S_SYMBOL_STUBS |
678 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
679 16, SectionKind::getText()));
681 OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
684 static MCSymbol *GetLazyPtr(MCSymbol *Sym, MCContext &Ctx) {
685 // Remove $stub suffix, add $lazy_ptr.
686 SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end()-5);
687 TmpStr += "$lazy_ptr";
688 return Ctx.GetOrCreateSymbol(TmpStr.str());
691 static MCSymbol *GetAnonSym(MCSymbol *Sym, MCContext &Ctx) {
692 // Add $tmp suffix to $stub, yielding $stub$tmp.
693 SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end());
695 return Ctx.GetOrCreateSymbol(TmpStr.str());
698 void PPCDarwinAsmPrinter::
699 EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs) {
700 bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
702 TargetLoweringObjectFileMachO &TLOFMacho =
703 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
705 // .lazy_symbol_pointer
706 const MCSection *LSPSection = TLOFMacho.getLazySymbolPointerSection();
708 // Output stubs for dynamically-linked functions
709 if (TM.getRelocationModel() == Reloc::PIC_) {
710 const MCSection *StubSection =
711 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
712 MCSectionMachO::S_SYMBOL_STUBS |
713 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
714 32, SectionKind::getText());
715 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
716 OutStreamer.SwitchSection(StubSection);
719 MCSymbol *Stub = Stubs[i].first;
720 MCSymbol *RawSym = Stubs[i].second.getPointer();
721 MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
722 MCSymbol *AnonSymbol = GetAnonSym(Stub, OutContext);
724 OutStreamer.EmitLabel(Stub);
725 OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
726 // FIXME: MCize this.
727 OutStreamer.EmitRawText(StringRef("\tmflr r0"));
728 OutStreamer.EmitRawText("\tbcl 20,31," + Twine(AnonSymbol->getName()));
729 OutStreamer.EmitLabel(AnonSymbol);
730 OutStreamer.EmitRawText(StringRef("\tmflr r11"));
731 OutStreamer.EmitRawText("\taddis r11,r11,ha16("+Twine(LazyPtr->getName())+
732 "-" + AnonSymbol->getName() + ")");
733 OutStreamer.EmitRawText(StringRef("\tmtlr r0"));
736 OutStreamer.EmitRawText("\tldu r12,lo16(" + Twine(LazyPtr->getName()) +
737 "-" + AnonSymbol->getName() + ")(r11)");
739 OutStreamer.EmitRawText("\tlwzu r12,lo16(" + Twine(LazyPtr->getName()) +
740 "-" + AnonSymbol->getName() + ")(r11)");
741 OutStreamer.EmitRawText(StringRef("\tmtctr r12"));
742 OutStreamer.EmitRawText(StringRef("\tbctr"));
744 OutStreamer.SwitchSection(LSPSection);
745 OutStreamer.EmitLabel(LazyPtr);
746 OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
749 OutStreamer.EmitRawText(StringRef("\t.quad dyld_stub_binding_helper"));
751 OutStreamer.EmitRawText(StringRef("\t.long dyld_stub_binding_helper"));
753 OutStreamer.AddBlankLine();
757 const MCSection *StubSection =
758 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
759 MCSectionMachO::S_SYMBOL_STUBS |
760 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
761 16, SectionKind::getText());
762 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
763 MCSymbol *Stub = Stubs[i].first;
764 MCSymbol *RawSym = Stubs[i].second.getPointer();
765 MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
767 OutStreamer.SwitchSection(StubSection);
769 OutStreamer.EmitLabel(Stub);
770 OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
771 OutStreamer.EmitRawText("\tlis r11,ha16(" + Twine(LazyPtr->getName()) +")");
773 OutStreamer.EmitRawText("\tldu r12,lo16(" + Twine(LazyPtr->getName()) +
776 OutStreamer.EmitRawText("\tlwzu r12,lo16(" + Twine(LazyPtr->getName()) +
778 OutStreamer.EmitRawText(StringRef("\tmtctr r12"));
779 OutStreamer.EmitRawText(StringRef("\tbctr"));
780 OutStreamer.SwitchSection(LSPSection);
781 OutStreamer.EmitLabel(LazyPtr);
782 OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
785 OutStreamer.EmitRawText(StringRef("\t.quad dyld_stub_binding_helper"));
787 OutStreamer.EmitRawText(StringRef("\t.long dyld_stub_binding_helper"));
790 OutStreamer.AddBlankLine();
794 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
795 bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
797 // Darwin/PPC always uses mach-o.
798 TargetLoweringObjectFileMachO &TLOFMacho =
799 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
800 MachineModuleInfoMachO &MMIMacho =
801 MMI->getObjFileInfo<MachineModuleInfoMachO>();
803 MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetFnStubList();
805 EmitFunctionStubs(Stubs);
807 if (MAI->doesSupportExceptionHandling() && MMI) {
808 // Add the (possibly multiple) personalities to the set of global values.
809 // Only referenced functions get into the Personalities list.
810 const std::vector<Function *> &Personalities = MMI->getPersonalities();
811 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
812 E = Personalities.end(); I != E; ++I) {
814 MCSymbol *NLPSym = GetSymbolWithGlobalValueBase(*I, "$non_lazy_ptr");
815 MachineModuleInfoImpl::StubValueTy &StubSym =
816 MMIMacho.getGVStubEntry(NLPSym);
817 StubSym = MachineModuleInfoImpl::StubValueTy(Mang->getSymbol(*I), true);
822 // Output stubs for dynamically-linked functions.
823 Stubs = MMIMacho.GetGVStubList();
825 // Output macho stubs for external and common global variables.
826 if (!Stubs.empty()) {
827 // Switch with ".non_lazy_symbol_pointer" directive.
828 OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
829 EmitAlignment(isPPC64 ? 3 : 2);
831 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
833 OutStreamer.EmitLabel(Stubs[i].first);
834 // .indirect_symbol _foo
835 MachineModuleInfoImpl::StubValueTy &MCSym = Stubs[i].second;
836 OutStreamer.EmitSymbolAttribute(MCSym.getPointer(), MCSA_IndirectSymbol);
839 // External to current translation unit.
840 OutStreamer.EmitIntValue(0, isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
842 // Internal to current translation unit.
844 // When we place the LSDA into the TEXT section, the type info pointers
845 // need to be indirect and pc-rel. We accomplish this by using NLPs.
846 // However, sometimes the types are local to the file. So we need to
847 // fill in the value for the NLP in those cases.
848 OutStreamer.EmitValue(MCSymbolRefExpr::Create(MCSym.getPointer(),
850 isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
854 OutStreamer.AddBlankLine();
857 Stubs = MMIMacho.GetHiddenGVStubList();
858 if (!Stubs.empty()) {
859 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
860 EmitAlignment(isPPC64 ? 3 : 2);
862 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
864 OutStreamer.EmitLabel(Stubs[i].first);
866 OutStreamer.EmitValue(MCSymbolRefExpr::
867 Create(Stubs[i].second.getPointer(),
869 isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
873 OutStreamer.AddBlankLine();
876 // Funny Darwin hack: This flag tells the linker that no global symbols
877 // contain code that falls through to other global symbols (e.g. the obvious
878 // implementation of multiple entry points). If this doesn't occur, the
879 // linker can safely perform dead code stripping. Since LLVM never generates
880 // code that does this, it is always safe to set.
881 OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
883 return AsmPrinter::doFinalization(M);
886 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
887 /// for a MachineFunction to the given output stream, in a format that the
888 /// Darwin assembler can deal with.
890 static AsmPrinter *createPPCAsmPrinterPass(TargetMachine &tm,
891 MCStreamer &Streamer) {
892 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
894 if (Subtarget->isDarwin())
895 return new PPCDarwinAsmPrinter(tm, Streamer);
896 return new PPCLinuxAsmPrinter(tm, Streamer);
899 // Force static initialization.
900 extern "C" void LLVMInitializePowerPCAsmPrinter() {
901 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
902 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);