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/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/FormattedStream.h"
51 #include "llvm/ADT/StringExtras.h"
52 #include "llvm/ADT/StringSet.h"
53 #include "llvm/ADT/SmallString.h"
57 class PPCAsmPrinter : public AsmPrinter {
59 DenseMap<const MCSymbol*, const MCSymbol*> TOC;
60 const PPCSubtarget &Subtarget;
63 explicit PPCAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
64 MCContext &Ctx, MCStreamer &Streamer,
66 : AsmPrinter(O, TM, Ctx, Streamer, T),
67 Subtarget(TM.getSubtarget<PPCSubtarget>()), LabelID(0) {}
69 virtual const char *getPassName() const {
70 return "PowerPC Assembly Printer";
73 PPCTargetMachine &getTM() {
74 return static_cast<PPCTargetMachine&>(TM);
77 unsigned enumRegToMachineReg(unsigned enumReg) {
79 default: llvm_unreachable("Unhandled register!");
80 case PPC::CR0: return 0;
81 case PPC::CR1: return 1;
82 case PPC::CR2: return 2;
83 case PPC::CR3: return 3;
84 case PPC::CR4: return 4;
85 case PPC::CR5: return 5;
86 case PPC::CR6: return 6;
87 case PPC::CR7: return 7;
92 /// printInstruction - This method is automatically generated by tablegen
93 /// from the instruction set description. This method returns true if the
94 /// machine instruction was sufficiently described to print it, otherwise it
96 void printInstruction(const MachineInstr *MI);
97 static const char *getRegisterName(unsigned RegNo);
100 virtual void EmitInstruction(const MachineInstr *MI);
101 void printOp(const MachineOperand &MO);
103 /// stripRegisterPrefix - This method strips the character prefix from a
104 /// register name so that only the number is left. Used by for linux asm.
105 const char *stripRegisterPrefix(const char *RegName) {
106 switch (RegName[0]) {
109 case 'v': return RegName + 1;
110 case 'c': if (RegName[1] == 'r') return RegName + 2;
116 /// printRegister - Print register according to target requirements.
118 void printRegister(const MachineOperand &MO, bool R0AsZero) {
119 unsigned RegNo = MO.getReg();
120 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
122 // If we should use 0 for R0.
123 if (R0AsZero && RegNo == PPC::R0) {
128 const char *RegName = getRegisterName(RegNo);
129 // Linux assembler (Others?) does not take register mnemonics.
130 // FIXME - What about special registers used in mfspr/mtspr?
131 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
135 void printOperand(const MachineInstr *MI, unsigned OpNo) {
136 const MachineOperand &MO = MI->getOperand(OpNo);
138 printRegister(MO, false);
139 } else if (MO.isImm()) {
146 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
147 unsigned AsmVariant, const char *ExtraCode);
148 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
149 unsigned AsmVariant, const char *ExtraCode);
152 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
153 char value = MI->getOperand(OpNo).getImm();
154 value = (value << (32-5)) >> (32-5);
157 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) {
163 unsigned char value = MI->getOperand(OpNo).getImm();
164 assert(value <= 63 && "Invalid u6imm argument!");
165 O << (unsigned int)value;
167 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
168 O << (short)MI->getOperand(OpNo).getImm();
170 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
171 O << (unsigned short)MI->getOperand(OpNo).getImm();
173 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
174 if (MI->getOperand(OpNo).isImm()) {
175 O << (short)(MI->getOperand(OpNo).getImm()*4);
178 printOp(MI->getOperand(OpNo));
179 if (TM.getRelocationModel() == Reloc::PIC_)
180 O << "-\"L" << getFunctionNumber() << "$pb\")";
185 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
186 // Branches can take an immediate operand. This is used by the branch
187 // selection pass to print $+8, an eight byte displacement from the PC.
188 if (MI->getOperand(OpNo).isImm()) {
189 O << "$+" << MI->getOperand(OpNo).getImm()*4;
191 printOp(MI->getOperand(OpNo));
194 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
195 const MachineOperand &MO = MI->getOperand(OpNo);
196 if (TM.getRelocationModel() != Reloc::Static) {
197 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
198 GlobalValue *GV = MO.getGlobal();
199 if (GV->isDeclaration() || GV->isWeakForLinker()) {
200 // Dynamically-resolved functions need a stub for the function.
201 MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$stub");
202 MachineModuleInfoImpl::StubValueTy &StubSym =
203 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
204 if (StubSym.getPointer() == 0)
205 StubSym = MachineModuleInfoImpl::
206 StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
211 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
212 SmallString<128> TempNameStr;
213 TempNameStr += StringRef(MO.getSymbolName());
214 TempNameStr += StringRef("$stub");
216 MCSymbol *Sym = GetExternalSymbolSymbol(TempNameStr.str());
217 MachineModuleInfoImpl::StubValueTy &StubSym =
218 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
219 if (StubSym.getPointer() == 0)
220 StubSym = MachineModuleInfoImpl::
221 StubValueTy(GetExternalSymbolSymbol(MO.getSymbolName()), true);
227 printOp(MI->getOperand(OpNo));
229 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
230 O << (int)MI->getOperand(OpNo).getImm()*4;
232 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
233 O << "\"L" << getFunctionNumber() << "$pb\"\n";
234 O << "\"L" << getFunctionNumber() << "$pb\":";
236 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
237 if (MI->getOperand(OpNo).isImm()) {
238 printS16ImmOperand(MI, OpNo);
240 if (Subtarget.isDarwin()) O << "ha16(";
241 printOp(MI->getOperand(OpNo));
242 if (TM.getRelocationModel() == Reloc::PIC_)
243 O << "-\"L" << getFunctionNumber() << "$pb\"";
244 if (Subtarget.isDarwin())
250 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
251 if (MI->getOperand(OpNo).isImm()) {
252 printS16ImmOperand(MI, OpNo);
254 if (Subtarget.isDarwin()) O << "lo16(";
255 printOp(MI->getOperand(OpNo));
256 if (TM.getRelocationModel() == Reloc::PIC_)
257 O << "-\"L" << getFunctionNumber() << "$pb\"";
258 if (Subtarget.isDarwin())
264 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
265 unsigned CCReg = MI->getOperand(OpNo).getReg();
266 unsigned RegNo = enumRegToMachineReg(CCReg);
267 O << (0x80 >> RegNo);
269 // The new addressing mode printers.
270 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
271 printSymbolLo(MI, OpNo);
273 if (MI->getOperand(OpNo+1).isReg() &&
274 MI->getOperand(OpNo+1).getReg() == PPC::R0)
277 printOperand(MI, OpNo+1);
280 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
281 if (MI->getOperand(OpNo).isImm())
282 printS16X4ImmOperand(MI, OpNo);
284 printSymbolLo(MI, OpNo);
286 if (MI->getOperand(OpNo+1).isReg() &&
287 MI->getOperand(OpNo+1).getReg() == PPC::R0)
290 printOperand(MI, OpNo+1);
294 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
295 // When used as the base register, r0 reads constant zero rather than
296 // the value contained in the register. For this reason, the darwin
297 // assembler requires that we print r0 as 0 (no r) when used as the base.
298 const MachineOperand &MO = MI->getOperand(OpNo);
299 printRegister(MO, true);
301 printOperand(MI, OpNo+1);
304 void printTOCEntryLabel(const MachineInstr *MI, unsigned OpNo) {
305 const MachineOperand &MO = MI->getOperand(OpNo);
306 assert(MO.getType() == MachineOperand::MO_GlobalAddress);
307 const MCSymbol *Sym = Mang->getSymbol(MO.getGlobal());
309 // Map symbol -> label of TOC entry.
310 const MCSymbol *&TOCEntry = TOC[Sym];
312 TOCEntry = OutContext.
313 GetOrCreateTemporarySymbol(StringRef(MAI->getPrivateGlobalPrefix()) +
314 "C" + Twine(LabelID++));
316 O << *TOCEntry << "@toc";
319 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
320 const char *Modifier);
323 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
324 class PPCLinuxAsmPrinter : public PPCAsmPrinter {
326 explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
327 MCContext &Ctx, MCStreamer &Streamer,
329 : PPCAsmPrinter(O, TM, Ctx, Streamer, T) {}
331 virtual const char *getPassName() const {
332 return "Linux PPC Assembly Printer";
335 bool doFinalization(Module &M);
337 virtual void EmitFunctionEntryLabel();
339 void getAnalysisUsage(AnalysisUsage &AU) const {
340 AU.setPreservesAll();
341 AU.addRequired<MachineModuleInfo>();
342 AU.addRequired<DwarfWriter>();
343 PPCAsmPrinter::getAnalysisUsage(AU);
347 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
349 class PPCDarwinAsmPrinter : public PPCAsmPrinter {
350 formatted_raw_ostream &OS;
352 explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
353 MCContext &Ctx, MCStreamer &Streamer,
355 : PPCAsmPrinter(O, TM, Ctx, Streamer, T), OS(O) {}
357 virtual const char *getPassName() const {
358 return "Darwin PPC Assembly Printer";
361 bool doFinalization(Module &M);
362 void EmitStartOfAsmFile(Module &M);
364 void EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs);
366 void getAnalysisUsage(AnalysisUsage &AU) const {
367 AU.setPreservesAll();
368 AU.addRequired<MachineModuleInfo>();
369 AU.addRequired<DwarfWriter>();
370 PPCAsmPrinter::getAnalysisUsage(AU);
373 } // end of anonymous namespace
375 // Include the auto-generated portion of the assembly writer
376 #include "PPCGenAsmWriter.inc"
378 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
379 switch (MO.getType()) {
380 case MachineOperand::MO_Immediate:
381 llvm_unreachable("printOp() does not handle immediate values");
383 case MachineOperand::MO_MachineBasicBlock:
384 O << *MO.getMBB()->getSymbol(OutContext);
386 case MachineOperand::MO_JumpTableIndex:
387 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
388 << '_' << MO.getIndex();
389 // FIXME: PIC relocation model
391 case MachineOperand::MO_ConstantPoolIndex:
392 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
393 << '_' << MO.getIndex();
395 case MachineOperand::MO_BlockAddress:
396 O << *GetBlockAddressSymbol(MO.getBlockAddress());
398 case MachineOperand::MO_ExternalSymbol: {
399 // Computing the address of an external symbol, not calling it.
400 if (TM.getRelocationModel() == Reloc::Static) {
401 O << *GetExternalSymbolSymbol(MO.getSymbolName());
406 OutContext.GetOrCreateSymbol(StringRef(MAI->getGlobalPrefix())+
407 MO.getSymbolName()+"$non_lazy_ptr");
408 MachineModuleInfoImpl::StubValueTy &StubSym =
409 MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(NLPSym);
410 if (StubSym.getPointer() == 0)
411 StubSym = MachineModuleInfoImpl::
412 StubValueTy(GetExternalSymbolSymbol(MO.getSymbolName()), true);
417 case MachineOperand::MO_GlobalAddress: {
418 // Computing the address of a global symbol, not calling it.
419 GlobalValue *GV = MO.getGlobal();
420 MCSymbol *SymToPrint;
422 // External or weakly linked global variables need non-lazily-resolved stubs
423 if (TM.getRelocationModel() != Reloc::Static &&
424 (GV->isDeclaration() || GV->isWeakForLinker())) {
425 if (!GV->hasHiddenVisibility()) {
426 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
427 MachineModuleInfoImpl::StubValueTy &StubSym =
428 MMI->getObjFileInfo<MachineModuleInfoMachO>()
429 .getGVStubEntry(SymToPrint);
430 if (StubSym.getPointer() == 0)
431 StubSym = MachineModuleInfoImpl::
432 StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
433 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
434 GV->hasAvailableExternallyLinkage()) {
435 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
437 MachineModuleInfoImpl::StubValueTy &StubSym =
438 MMI->getObjFileInfo<MachineModuleInfoMachO>().
439 getHiddenGVStubEntry(SymToPrint);
440 if (StubSym.getPointer() == 0)
441 StubSym = MachineModuleInfoImpl::
442 StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
444 SymToPrint = Mang->getSymbol(GV);
447 SymToPrint = Mang->getSymbol(GV);
452 printOffset(MO.getOffset());
457 O << "<unknown operand type: " << MO.getType() << ">";
462 /// PrintAsmOperand - Print out an operand for an inline asm expression.
464 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
466 const char *ExtraCode) {
467 // Does this asm operand have a single letter operand modifier?
468 if (ExtraCode && ExtraCode[0]) {
469 if (ExtraCode[1] != 0) return true; // Unknown modifier.
471 switch (ExtraCode[0]) {
472 default: return true; // Unknown modifier.
473 case 'c': // Don't print "$" before a global var name or constant.
474 // PPC never has a prefix.
475 printOperand(MI, OpNo);
477 case 'L': // Write second word of DImode reference.
478 // Verify that this operand has two consecutive registers.
479 if (!MI->getOperand(OpNo).isReg() ||
480 OpNo+1 == MI->getNumOperands() ||
481 !MI->getOperand(OpNo+1).isReg())
483 ++OpNo; // Return the high-part.
486 // Write 'i' if an integer constant, otherwise nothing. Used to print
488 if (MI->getOperand(OpNo).isImm())
494 printOperand(MI, OpNo);
498 // At the moment, all inline asm memory operands are a single register.
499 // In any case, the output of this routine should always be just one
500 // assembler operand.
502 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
504 const char *ExtraCode) {
505 if (ExtraCode && ExtraCode[0])
506 return true; // Unknown modifier.
507 assert (MI->getOperand(OpNo).isReg());
509 printOperand(MI, OpNo);
514 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
515 const char *Modifier) {
516 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
517 unsigned Code = MI->getOperand(OpNo).getImm();
518 if (!strcmp(Modifier, "cc")) {
519 switch ((PPC::Predicate)Code) {
520 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
521 case PPC::PRED_LT: O << "lt"; return;
522 case PPC::PRED_LE: O << "le"; return;
523 case PPC::PRED_EQ: O << "eq"; return;
524 case PPC::PRED_GE: O << "ge"; return;
525 case PPC::PRED_GT: O << "gt"; return;
526 case PPC::PRED_NE: O << "ne"; return;
527 case PPC::PRED_UN: O << "un"; return;
528 case PPC::PRED_NU: O << "nu"; return;
532 assert(!strcmp(Modifier, "reg") &&
533 "Need to specify 'cc' or 'reg' as predicate op modifier!");
534 // Don't print the register for 'always'.
535 if (Code == PPC::PRED_ALWAYS) return;
536 printOperand(MI, OpNo+1);
541 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
542 /// the current output stream.
544 void PPCAsmPrinter::EmitInstruction(const MachineInstr *MI) {
545 // Check for slwi/srwi mnemonics.
546 if (MI->getOpcode() == PPC::RLWINM) {
547 unsigned char SH = MI->getOperand(2).getImm();
548 unsigned char MB = MI->getOperand(3).getImm();
549 unsigned char ME = MI->getOperand(4).getImm();
550 bool useSubstituteMnemonic = false;
551 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
552 O << "\tslwi "; useSubstituteMnemonic = true;
554 if (SH <= 31 && MB == (32-SH) && ME == 31) {
555 O << "\tsrwi "; useSubstituteMnemonic = true;
558 if (useSubstituteMnemonic) {
562 O << ", " << (unsigned int)SH;
563 OutStreamer.AddBlankLine();
568 if ((MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) &&
569 MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
574 OutStreamer.AddBlankLine();
578 if (MI->getOpcode() == PPC::RLDICR) {
579 unsigned char SH = MI->getOperand(2).getImm();
580 unsigned char ME = MI->getOperand(3).getImm();
581 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
587 O << ", " << (unsigned int)SH;
588 OutStreamer.AddBlankLine();
593 printInstruction(MI);
594 OutStreamer.AddBlankLine();
597 void PPCLinuxAsmPrinter::EmitFunctionEntryLabel() {
598 if (!Subtarget.isPPC64()) // linux/ppc32 - Normal entry label.
599 return AsmPrinter::EmitFunctionEntryLabel();
601 // Emit an official procedure descriptor.
602 // FIXME 64-bit SVR4: Use MCSection here!
603 O << "\t.section\t\".opd\",\"aw\"\n";
605 OutStreamer.EmitLabel(CurrentFnSym);
606 O << "\t.quad .L." << *CurrentFnSym << ",.TOC.@tocbase\n";
607 O << "\t.previous\n";
608 O << ".L." << *CurrentFnSym << ":\n";
612 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
613 const TargetData *TD = TM.getTargetData();
615 bool isPPC64 = TD->getPointerSizeInBits() == 64;
617 if (isPPC64 && !TOC.empty()) {
618 // FIXME 64-bit SVR4: Use MCSection here?
619 O << "\t.section\t\".toc\",\"aw\"\n";
621 // FIXME: This is nondeterminstic!
622 for (DenseMap<const MCSymbol*, const MCSymbol*>::iterator I = TOC.begin(),
623 E = TOC.end(); I != E; ++I) {
624 O << *I->second << ":\n";
625 O << "\t.tc " << *I->first << "[TC]," << *I->first << '\n';
629 return AsmPrinter::doFinalization(M);
632 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
633 static const char *const CPUDirectives[] = {
645 unsigned Directive = Subtarget.getDarwinDirective();
646 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
647 Directive = PPC::DIR_970;
648 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
649 Directive = PPC::DIR_7400;
650 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
651 Directive = PPC::DIR_64;
652 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
653 O << "\t.machine " << CPUDirectives[Directive] << '\n';
655 // Prime text sections so they are adjacent. This reduces the likelihood a
656 // large data or debug section causes a branch to exceed 16M limit.
657 TargetLoweringObjectFileMachO &TLOFMacho =
658 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
659 OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
660 if (TM.getRelocationModel() == Reloc::PIC_) {
661 OutStreamer.SwitchSection(
662 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
663 MCSectionMachO::S_SYMBOL_STUBS |
664 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
665 32, SectionKind::getText()));
666 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
667 OutStreamer.SwitchSection(
668 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
669 MCSectionMachO::S_SYMBOL_STUBS |
670 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
671 16, SectionKind::getText()));
673 OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
676 static const MCSymbol *GetLazyPtr(const MCSymbol *Sym, MCContext &Ctx) {
677 // Remove $stub suffix, add $lazy_ptr.
678 SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end()-5);
679 TmpStr += "$lazy_ptr";
680 return Ctx.GetOrCreateTemporarySymbol(TmpStr.str());
683 static const MCSymbol *GetAnonSym(const MCSymbol *Sym, MCContext &Ctx) {
684 // Add $tmp suffix to $stub, yielding $stub$tmp.
685 SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end());
687 return Ctx.GetOrCreateTemporarySymbol(TmpStr.str());
690 void PPCDarwinAsmPrinter::
691 EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs) {
692 bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
694 TargetLoweringObjectFileMachO &TLOFMacho =
695 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
697 // .lazy_symbol_pointer
698 const MCSection *LSPSection = TLOFMacho.getLazySymbolPointerSection();
700 // Output stubs for dynamically-linked functions
701 if (TM.getRelocationModel() == Reloc::PIC_) {
702 const MCSection *StubSection =
703 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
704 MCSectionMachO::S_SYMBOL_STUBS |
705 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
706 32, SectionKind::getText());
707 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
708 OutStreamer.SwitchSection(StubSection);
711 const MCSymbol *Stub = Stubs[i].first;
712 const MCSymbol *RawSym = Stubs[i].second.getPointer();
713 const MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
714 const MCSymbol *AnonSymbol = GetAnonSym(Stub, OutContext);
717 O << "\t.indirect_symbol " << *RawSym << '\n';
719 O << "\tbcl 20,31," << *AnonSymbol << '\n';
720 O << *AnonSymbol << ":\n";
722 O << "\taddis r11,r11,ha16(" << *LazyPtr << '-' << *AnonSymbol
725 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(" << *LazyPtr
726 << '-' << *AnonSymbol << ")(r11)\n";
727 O << "\tmtctr r12\n";
730 OutStreamer.SwitchSection(LSPSection);
731 O << *LazyPtr << ":\n";
732 O << "\t.indirect_symbol " << *RawSym << '\n';
733 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
739 const MCSection *StubSection =
740 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
741 MCSectionMachO::S_SYMBOL_STUBS |
742 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
743 16, SectionKind::getText());
744 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
745 const MCSymbol *Stub = Stubs[i].first;
746 const MCSymbol *RawSym = Stubs[i].second.getPointer();
747 const MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
749 OutStreamer.SwitchSection(StubSection);
752 O << "\t.indirect_symbol " << *RawSym << '\n';
753 O << "\tlis r11,ha16(" << *LazyPtr << ")\n";
754 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(" << *LazyPtr
756 O << "\tmtctr r12\n";
758 OutStreamer.SwitchSection(LSPSection);
759 O << *LazyPtr << ":\n";
760 O << "\t.indirect_symbol " << *RawSym << '\n';
761 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
768 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
769 bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
771 // Darwin/PPC always uses mach-o.
772 TargetLoweringObjectFileMachO &TLOFMacho =
773 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
774 MachineModuleInfoMachO &MMIMacho =
775 MMI->getObjFileInfo<MachineModuleInfoMachO>();
777 MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetFnStubList();
779 EmitFunctionStubs(Stubs);
781 if (MAI->doesSupportExceptionHandling() && MMI) {
782 // Add the (possibly multiple) personalities to the set of global values.
783 // Only referenced functions get into the Personalities list.
784 const std::vector<Function *> &Personalities = MMI->getPersonalities();
785 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
786 E = Personalities.end(); I != E; ++I) {
788 MCSymbol *NLPSym = GetSymbolWithGlobalValueBase(*I, "$non_lazy_ptr");
789 MachineModuleInfoImpl::StubValueTy &StubSym =
790 MMIMacho.getGVStubEntry(NLPSym);
791 StubSym = MachineModuleInfoImpl::StubValueTy(Mang->getSymbol(*I), true);
796 // Output stubs for dynamically-linked functions.
797 Stubs = MMIMacho.GetGVStubList();
799 // Output macho stubs for external and common global variables.
800 if (!Stubs.empty()) {
801 // Switch with ".non_lazy_symbol_pointer" directive.
802 OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
803 EmitAlignment(isPPC64 ? 3 : 2);
805 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
807 OutStreamer.EmitLabel(Stubs[i].first);
808 // .indirect_symbol _foo
809 MachineModuleInfoImpl::StubValueTy &MCSym = Stubs[i].second;
810 OutStreamer.EmitSymbolAttribute(MCSym.getPointer(), MCSA_IndirectSymbol);
813 // External to current translation unit.
814 OutStreamer.EmitIntValue(0, isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
816 // Internal to current translation unit.
817 OutStreamer.EmitValue(MCSymbolRefExpr::Create(MCSym.getPointer(),
819 isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
823 OutStreamer.AddBlankLine();
826 Stubs = MMIMacho.GetHiddenGVStubList();
827 if (!Stubs.empty()) {
828 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
829 EmitAlignment(isPPC64 ? 3 : 2);
831 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
833 OutStreamer.EmitLabel(Stubs[i].first);
835 OutStreamer.EmitValue(MCSymbolRefExpr::
836 Create(Stubs[i].second.getPointer(),
838 isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
842 OutStreamer.AddBlankLine();
845 // Funny Darwin hack: This flag tells the linker that no global symbols
846 // contain code that falls through to other global symbols (e.g. the obvious
847 // implementation of multiple entry points). If this doesn't occur, the
848 // linker can safely perform dead code stripping. Since LLVM never generates
849 // code that does this, it is always safe to set.
850 OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
852 return AsmPrinter::doFinalization(M);
855 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
856 /// for a MachineFunction to the given output stream, in a format that the
857 /// Darwin assembler can deal with.
859 static AsmPrinter *createPPCAsmPrinterPass(formatted_raw_ostream &o,
861 MCContext &Ctx, MCStreamer &Streamer,
862 const MCAsmInfo *tai) {
863 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
865 if (Subtarget->isDarwin())
866 return new PPCDarwinAsmPrinter(o, tm, Ctx, Streamer, tai);
867 return new PPCLinuxAsmPrinter(o, tm, Ctx, Streamer, tai);
870 // Force static initialization.
871 extern "C" void LLVMInitializePowerPCAsmPrinter() {
872 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
873 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);