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,
65 : AsmPrinter(O, TM, Streamer),
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, raw_ostream &O);
96 static const char *getRegisterName(unsigned RegNo);
99 virtual void EmitInstruction(const MachineInstr *MI);
100 void printOp(const MachineOperand &MO, raw_ostream &O);
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, raw_ostream &O){
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, raw_ostream &O) {
135 const MachineOperand &MO = MI->getOperand(OpNo);
137 printRegister(MO, false, O);
138 } else if (MO.isImm()) {
145 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
146 unsigned AsmVariant, const char *ExtraCode,
148 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
149 unsigned AsmVariant, const char *ExtraCode,
153 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo,
155 char value = MI->getOperand(OpNo).getImm();
156 value = (value << (32-5)) >> (32-5);
159 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo,
161 unsigned char value = MI->getOperand(OpNo).getImm();
162 assert(value <= 31 && "Invalid u5imm argument!");
163 O << (unsigned int)value;
165 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo,
167 unsigned char value = MI->getOperand(OpNo).getImm();
168 assert(value <= 63 && "Invalid u6imm argument!");
169 O << (unsigned int)value;
171 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo,
173 O << (short)MI->getOperand(OpNo).getImm();
175 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo,
177 O << (unsigned short)MI->getOperand(OpNo).getImm();
179 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo,
181 if (MI->getOperand(OpNo).isImm()) {
182 O << (short)(MI->getOperand(OpNo).getImm()*4);
185 printOp(MI->getOperand(OpNo), O);
186 if (TM.getRelocationModel() == Reloc::PIC_)
187 O << "-\"L" << getFunctionNumber() << "$pb\")";
192 void printBranchOperand(const MachineInstr *MI, unsigned OpNo,
194 // Branches can take an immediate operand. This is used by the branch
195 // selection pass to print $+8, an eight byte displacement from the PC.
196 if (MI->getOperand(OpNo).isImm()) {
197 O << "$+" << MI->getOperand(OpNo).getImm()*4;
199 printOp(MI->getOperand(OpNo), O);
202 void printCallOperand(const MachineInstr *MI, unsigned OpNo,
204 const MachineOperand &MO = MI->getOperand(OpNo);
205 if (TM.getRelocationModel() != Reloc::Static) {
206 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
207 GlobalValue *GV = MO.getGlobal();
208 if (GV->isDeclaration() || GV->isWeakForLinker()) {
209 // Dynamically-resolved functions need a stub for the function.
210 MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$stub");
211 MachineModuleInfoImpl::StubValueTy &StubSym =
212 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
213 if (StubSym.getPointer() == 0)
214 StubSym = MachineModuleInfoImpl::
215 StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
220 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
221 SmallString<128> TempNameStr;
222 TempNameStr += StringRef(MO.getSymbolName());
223 TempNameStr += StringRef("$stub");
225 MCSymbol *Sym = GetExternalSymbolSymbol(TempNameStr.str());
226 MachineModuleInfoImpl::StubValueTy &StubSym =
227 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
228 if (StubSym.getPointer() == 0)
229 StubSym = MachineModuleInfoImpl::
230 StubValueTy(GetExternalSymbolSymbol(MO.getSymbolName()), true);
236 printOp(MI->getOperand(OpNo), O);
238 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo,
240 O << (int)MI->getOperand(OpNo).getImm()*4;
242 void printPICLabel(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
243 O << "\"L" << getFunctionNumber() << "$pb\"\n";
244 O << "\"L" << getFunctionNumber() << "$pb\":";
246 void printSymbolHi(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
247 if (MI->getOperand(OpNo).isImm()) {
248 printS16ImmOperand(MI, OpNo, O);
250 if (Subtarget.isDarwin()) O << "ha16(";
251 printOp(MI->getOperand(OpNo), O);
252 if (TM.getRelocationModel() == Reloc::PIC_)
253 O << "-\"L" << getFunctionNumber() << "$pb\"";
254 if (Subtarget.isDarwin())
260 void printSymbolLo(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
261 if (MI->getOperand(OpNo).isImm()) {
262 printS16ImmOperand(MI, OpNo, O);
264 if (Subtarget.isDarwin()) O << "lo16(";
265 printOp(MI->getOperand(OpNo), O);
266 if (TM.getRelocationModel() == Reloc::PIC_)
267 O << "-\"L" << getFunctionNumber() << "$pb\"";
268 if (Subtarget.isDarwin())
274 void printcrbitm(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
275 unsigned CCReg = MI->getOperand(OpNo).getReg();
276 unsigned RegNo = enumRegToMachineReg(CCReg);
277 O << (0x80 >> RegNo);
279 // The new addressing mode printers.
280 void printMemRegImm(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
281 printSymbolLo(MI, OpNo, O);
283 if (MI->getOperand(OpNo+1).isReg() &&
284 MI->getOperand(OpNo+1).getReg() == PPC::R0)
287 printOperand(MI, OpNo+1, O);
290 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo,
292 if (MI->getOperand(OpNo).isImm())
293 printS16X4ImmOperand(MI, OpNo, O);
295 printSymbolLo(MI, OpNo, O);
297 if (MI->getOperand(OpNo+1).isReg() &&
298 MI->getOperand(OpNo+1).getReg() == PPC::R0)
301 printOperand(MI, OpNo+1, O);
305 void printMemRegReg(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
306 // When used as the base register, r0 reads constant zero rather than
307 // the value contained in the register. For this reason, the darwin
308 // assembler requires that we print r0 as 0 (no r) when used as the base.
309 const MachineOperand &MO = MI->getOperand(OpNo);
310 printRegister(MO, true, O);
312 printOperand(MI, OpNo+1, O);
315 void printTOCEntryLabel(const MachineInstr *MI, unsigned OpNo,
317 const MachineOperand &MO = MI->getOperand(OpNo);
318 assert(MO.getType() == MachineOperand::MO_GlobalAddress);
319 const MCSymbol *Sym = Mang->getSymbol(MO.getGlobal());
321 // Map symbol -> label of TOC entry.
322 const MCSymbol *&TOCEntry = TOC[Sym];
324 TOCEntry = OutContext.
325 GetOrCreateSymbol(StringRef(MAI->getPrivateGlobalPrefix()) +
326 "C" + Twine(LabelID++));
328 O << *TOCEntry << "@toc";
331 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
332 raw_ostream &O, const char *Modifier);
335 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
336 class PPCLinuxAsmPrinter : public PPCAsmPrinter {
338 explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
339 MCStreamer &Streamer)
340 : PPCAsmPrinter(O, TM, Streamer) {}
342 virtual const char *getPassName() const {
343 return "Linux PPC Assembly Printer";
346 bool doFinalization(Module &M);
348 virtual void EmitFunctionEntryLabel();
350 void getAnalysisUsage(AnalysisUsage &AU) const {
351 AU.setPreservesAll();
352 AU.addRequired<MachineModuleInfo>();
353 AU.addRequired<DwarfWriter>();
354 PPCAsmPrinter::getAnalysisUsage(AU);
358 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
360 class PPCDarwinAsmPrinter : public PPCAsmPrinter {
361 formatted_raw_ostream &OS;
363 explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
364 MCStreamer &Streamer)
365 : PPCAsmPrinter(O, TM, Streamer), OS(O) {}
367 virtual const char *getPassName() const {
368 return "Darwin PPC Assembly Printer";
371 bool doFinalization(Module &M);
372 void EmitStartOfAsmFile(Module &M);
374 void EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs);
376 void getAnalysisUsage(AnalysisUsage &AU) const {
377 AU.setPreservesAll();
378 AU.addRequired<MachineModuleInfo>();
379 AU.addRequired<DwarfWriter>();
380 PPCAsmPrinter::getAnalysisUsage(AU);
383 } // end of anonymous namespace
385 // Include the auto-generated portion of the assembly writer
386 #include "PPCGenAsmWriter.inc"
388 void PPCAsmPrinter::printOp(const MachineOperand &MO, raw_ostream &O) {
389 switch (MO.getType()) {
390 case MachineOperand::MO_Immediate:
391 llvm_unreachable("printOp() does not handle immediate values");
393 case MachineOperand::MO_MachineBasicBlock:
394 O << *MO.getMBB()->getSymbol();
396 case MachineOperand::MO_JumpTableIndex:
397 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
398 << '_' << MO.getIndex();
399 // FIXME: PIC relocation model
401 case MachineOperand::MO_ConstantPoolIndex:
402 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
403 << '_' << MO.getIndex();
405 case MachineOperand::MO_BlockAddress:
406 O << *GetBlockAddressSymbol(MO.getBlockAddress());
408 case MachineOperand::MO_ExternalSymbol: {
409 // Computing the address of an external symbol, not calling it.
410 if (TM.getRelocationModel() == Reloc::Static) {
411 O << *GetExternalSymbolSymbol(MO.getSymbolName());
416 OutContext.GetOrCreateSymbol(StringRef(MAI->getGlobalPrefix())+
417 MO.getSymbolName()+"$non_lazy_ptr");
418 MachineModuleInfoImpl::StubValueTy &StubSym =
419 MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(NLPSym);
420 if (StubSym.getPointer() == 0)
421 StubSym = MachineModuleInfoImpl::
422 StubValueTy(GetExternalSymbolSymbol(MO.getSymbolName()), true);
427 case MachineOperand::MO_GlobalAddress: {
428 // Computing the address of a global symbol, not calling it.
429 GlobalValue *GV = MO.getGlobal();
430 MCSymbol *SymToPrint;
432 // External or weakly linked global variables need non-lazily-resolved stubs
433 if (TM.getRelocationModel() != Reloc::Static &&
434 (GV->isDeclaration() || GV->isWeakForLinker())) {
435 if (!GV->hasHiddenVisibility()) {
436 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
437 MachineModuleInfoImpl::StubValueTy &StubSym =
438 MMI->getObjFileInfo<MachineModuleInfoMachO>()
439 .getGVStubEntry(SymToPrint);
440 if (StubSym.getPointer() == 0)
441 StubSym = MachineModuleInfoImpl::
442 StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
443 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
444 GV->hasAvailableExternallyLinkage()) {
445 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
447 MachineModuleInfoImpl::StubValueTy &StubSym =
448 MMI->getObjFileInfo<MachineModuleInfoMachO>().
449 getHiddenGVStubEntry(SymToPrint);
450 if (StubSym.getPointer() == 0)
451 StubSym = MachineModuleInfoImpl::
452 StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
454 SymToPrint = Mang->getSymbol(GV);
457 SymToPrint = Mang->getSymbol(GV);
462 printOffset(MO.getOffset(), O);
467 O << "<unknown operand type: " << MO.getType() << ">";
472 /// PrintAsmOperand - Print out an operand for an inline asm expression.
474 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
476 const char *ExtraCode, raw_ostream &O) {
477 // Does this asm operand have a single letter operand modifier?
478 if (ExtraCode && ExtraCode[0]) {
479 if (ExtraCode[1] != 0) return true; // Unknown modifier.
481 switch (ExtraCode[0]) {
482 default: return true; // Unknown modifier.
483 case 'c': // Don't print "$" before a global var name or constant.
484 // PPC never has a prefix.
485 printOperand(MI, OpNo, O);
487 case 'L': // Write second word of DImode reference.
488 // Verify that this operand has two consecutive registers.
489 if (!MI->getOperand(OpNo).isReg() ||
490 OpNo+1 == MI->getNumOperands() ||
491 !MI->getOperand(OpNo+1).isReg())
493 ++OpNo; // Return the high-part.
496 // Write 'i' if an integer constant, otherwise nothing. Used to print
498 if (MI->getOperand(OpNo).isImm())
504 printOperand(MI, OpNo, O);
508 // At the moment, all inline asm memory operands are a single register.
509 // In any case, the output of this routine should always be just one
510 // assembler operand.
512 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
514 const char *ExtraCode,
516 if (ExtraCode && ExtraCode[0])
517 return true; // Unknown modifier.
518 assert (MI->getOperand(OpNo).isReg());
520 printOperand(MI, OpNo, O);
525 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
526 raw_ostream &O, const char *Modifier){
527 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
528 unsigned Code = MI->getOperand(OpNo).getImm();
529 if (!strcmp(Modifier, "cc")) {
530 switch ((PPC::Predicate)Code) {
531 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
532 case PPC::PRED_LT: O << "lt"; return;
533 case PPC::PRED_LE: O << "le"; return;
534 case PPC::PRED_EQ: O << "eq"; return;
535 case PPC::PRED_GE: O << "ge"; return;
536 case PPC::PRED_GT: O << "gt"; return;
537 case PPC::PRED_NE: O << "ne"; return;
538 case PPC::PRED_UN: O << "un"; return;
539 case PPC::PRED_NU: O << "nu"; return;
543 assert(!strcmp(Modifier, "reg") &&
544 "Need to specify 'cc' or 'reg' as predicate op modifier!");
545 // Don't print the register for 'always'.
546 if (Code == PPC::PRED_ALWAYS) return;
547 printOperand(MI, OpNo+1, O);
552 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
553 /// the current output stream.
555 void PPCAsmPrinter::EmitInstruction(const MachineInstr *MI) {
556 // Check for slwi/srwi mnemonics.
557 if (MI->getOpcode() == PPC::RLWINM) {
558 unsigned char SH = MI->getOperand(2).getImm();
559 unsigned char MB = MI->getOperand(3).getImm();
560 unsigned char ME = MI->getOperand(4).getImm();
561 bool useSubstituteMnemonic = false;
562 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
563 O << "\tslwi "; useSubstituteMnemonic = true;
565 if (SH <= 31 && MB == (32-SH) && ME == 31) {
566 O << "\tsrwi "; useSubstituteMnemonic = true;
569 if (useSubstituteMnemonic) {
570 printOperand(MI, 0, O);
572 printOperand(MI, 1, O);
573 O << ", " << (unsigned int)SH;
574 OutStreamer.AddBlankLine();
579 if ((MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) &&
580 MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
582 printOperand(MI, 0, O);
584 printOperand(MI, 1, O);
585 OutStreamer.AddBlankLine();
589 if (MI->getOpcode() == PPC::RLDICR) {
590 unsigned char SH = MI->getOperand(2).getImm();
591 unsigned char ME = MI->getOperand(3).getImm();
592 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
595 printOperand(MI, 0, O);
597 printOperand(MI, 1, O);
598 O << ", " << (unsigned int)SH;
599 OutStreamer.AddBlankLine();
604 SmallString<128> Str;
605 raw_svector_ostream OS(Str);
606 printInstruction(MI, OS);
607 OutStreamer.EmitRawText(OS.str());
610 void PPCLinuxAsmPrinter::EmitFunctionEntryLabel() {
611 if (!Subtarget.isPPC64()) // linux/ppc32 - Normal entry label.
612 return AsmPrinter::EmitFunctionEntryLabel();
614 // Emit an official procedure descriptor.
615 // FIXME 64-bit SVR4: Use MCSection here!
616 O << "\t.section\t\".opd\",\"aw\"\n";
618 OutStreamer.EmitLabel(CurrentFnSym);
619 O << "\t.quad .L." << *CurrentFnSym << ",.TOC.@tocbase\n";
620 O << "\t.previous\n";
621 O << ".L." << *CurrentFnSym << ":\n";
625 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
626 const TargetData *TD = TM.getTargetData();
628 bool isPPC64 = TD->getPointerSizeInBits() == 64;
630 if (isPPC64 && !TOC.empty()) {
631 // FIXME 64-bit SVR4: Use MCSection here?
632 O << "\t.section\t\".toc\",\"aw\"\n";
634 // FIXME: This is nondeterminstic!
635 for (DenseMap<const MCSymbol*, const MCSymbol*>::iterator I = TOC.begin(),
636 E = TOC.end(); I != E; ++I) {
637 O << *I->second << ":\n";
638 O << "\t.tc " << *I->first << "[TC]," << *I->first << '\n';
642 return AsmPrinter::doFinalization(M);
645 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
646 static const char *const CPUDirectives[] = {
658 unsigned Directive = Subtarget.getDarwinDirective();
659 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
660 Directive = PPC::DIR_970;
661 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
662 Directive = PPC::DIR_7400;
663 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
664 Directive = PPC::DIR_64;
665 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
666 O << "\t.machine " << CPUDirectives[Directive] << '\n';
668 // Prime text sections so they are adjacent. This reduces the likelihood a
669 // large data or debug section causes a branch to exceed 16M limit.
670 TargetLoweringObjectFileMachO &TLOFMacho =
671 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
672 OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
673 if (TM.getRelocationModel() == Reloc::PIC_) {
674 OutStreamer.SwitchSection(
675 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
676 MCSectionMachO::S_SYMBOL_STUBS |
677 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
678 32, SectionKind::getText()));
679 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
680 OutStreamer.SwitchSection(
681 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
682 MCSectionMachO::S_SYMBOL_STUBS |
683 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
684 16, SectionKind::getText()));
686 OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
689 static const MCSymbol *GetLazyPtr(const MCSymbol *Sym, MCContext &Ctx) {
690 // Remove $stub suffix, add $lazy_ptr.
691 SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end()-5);
692 TmpStr += "$lazy_ptr";
693 return Ctx.GetOrCreateSymbol(TmpStr.str());
696 static const MCSymbol *GetAnonSym(const MCSymbol *Sym, MCContext &Ctx) {
697 // Add $tmp suffix to $stub, yielding $stub$tmp.
698 SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end());
700 return Ctx.GetOrCreateSymbol(TmpStr.str());
703 void PPCDarwinAsmPrinter::
704 EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs) {
705 bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
707 TargetLoweringObjectFileMachO &TLOFMacho =
708 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
710 // .lazy_symbol_pointer
711 const MCSection *LSPSection = TLOFMacho.getLazySymbolPointerSection();
713 // Output stubs for dynamically-linked functions
714 if (TM.getRelocationModel() == Reloc::PIC_) {
715 const MCSection *StubSection =
716 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
717 MCSectionMachO::S_SYMBOL_STUBS |
718 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
719 32, SectionKind::getText());
720 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
721 OutStreamer.SwitchSection(StubSection);
724 const MCSymbol *Stub = Stubs[i].first;
725 const MCSymbol *RawSym = Stubs[i].second.getPointer();
726 const MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
727 const MCSymbol *AnonSymbol = GetAnonSym(Stub, OutContext);
730 O << "\t.indirect_symbol " << *RawSym << '\n';
732 O << "\tbcl 20,31," << *AnonSymbol << '\n';
733 O << *AnonSymbol << ":\n";
735 O << "\taddis r11,r11,ha16(" << *LazyPtr << '-' << *AnonSymbol
738 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(" << *LazyPtr
739 << '-' << *AnonSymbol << ")(r11)\n";
740 O << "\tmtctr r12\n";
743 OutStreamer.SwitchSection(LSPSection);
744 O << *LazyPtr << ":\n";
745 O << "\t.indirect_symbol " << *RawSym << '\n';
746 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
752 const MCSection *StubSection =
753 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
754 MCSectionMachO::S_SYMBOL_STUBS |
755 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
756 16, SectionKind::getText());
757 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
758 const MCSymbol *Stub = Stubs[i].first;
759 const MCSymbol *RawSym = Stubs[i].second.getPointer();
760 const MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
762 OutStreamer.SwitchSection(StubSection);
765 O << "\t.indirect_symbol " << *RawSym << '\n';
766 O << "\tlis r11,ha16(" << *LazyPtr << ")\n";
767 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(" << *LazyPtr
769 O << "\tmtctr r12\n";
771 OutStreamer.SwitchSection(LSPSection);
772 O << *LazyPtr << ":\n";
773 O << "\t.indirect_symbol " << *RawSym << '\n';
774 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
781 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
782 bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
784 // Darwin/PPC always uses mach-o.
785 TargetLoweringObjectFileMachO &TLOFMacho =
786 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
787 MachineModuleInfoMachO &MMIMacho =
788 MMI->getObjFileInfo<MachineModuleInfoMachO>();
790 MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetFnStubList();
792 EmitFunctionStubs(Stubs);
794 if (MAI->doesSupportExceptionHandling() && MMI) {
795 // Add the (possibly multiple) personalities to the set of global values.
796 // Only referenced functions get into the Personalities list.
797 const std::vector<Function *> &Personalities = MMI->getPersonalities();
798 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
799 E = Personalities.end(); I != E; ++I) {
801 MCSymbol *NLPSym = GetSymbolWithGlobalValueBase(*I, "$non_lazy_ptr");
802 MachineModuleInfoImpl::StubValueTy &StubSym =
803 MMIMacho.getGVStubEntry(NLPSym);
804 StubSym = MachineModuleInfoImpl::StubValueTy(Mang->getSymbol(*I), true);
809 // Output stubs for dynamically-linked functions.
810 Stubs = MMIMacho.GetGVStubList();
812 // Output macho stubs for external and common global variables.
813 if (!Stubs.empty()) {
814 // Switch with ".non_lazy_symbol_pointer" directive.
815 OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
816 EmitAlignment(isPPC64 ? 3 : 2);
818 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
820 OutStreamer.EmitLabel(Stubs[i].first);
821 // .indirect_symbol _foo
822 MachineModuleInfoImpl::StubValueTy &MCSym = Stubs[i].second;
823 OutStreamer.EmitSymbolAttribute(MCSym.getPointer(), MCSA_IndirectSymbol);
826 // External to current translation unit.
827 OutStreamer.EmitIntValue(0, isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
829 // Internal to current translation unit.
831 // When we place the LSDA into the TEXT section, the type info pointers
832 // need to be indirect and pc-rel. We accomplish this by using NLPs.
833 // However, sometimes the types are local to the file. So we need to
834 // fill in the value for the NLP in those cases.
835 OutStreamer.EmitValue(MCSymbolRefExpr::Create(MCSym.getPointer(),
837 isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
841 OutStreamer.AddBlankLine();
844 Stubs = MMIMacho.GetHiddenGVStubList();
845 if (!Stubs.empty()) {
846 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
847 EmitAlignment(isPPC64 ? 3 : 2);
849 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
851 OutStreamer.EmitLabel(Stubs[i].first);
853 OutStreamer.EmitValue(MCSymbolRefExpr::
854 Create(Stubs[i].second.getPointer(),
856 isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
860 OutStreamer.AddBlankLine();
863 // Funny Darwin hack: This flag tells the linker that no global symbols
864 // contain code that falls through to other global symbols (e.g. the obvious
865 // implementation of multiple entry points). If this doesn't occur, the
866 // linker can safely perform dead code stripping. Since LLVM never generates
867 // code that does this, it is always safe to set.
868 OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
870 return AsmPrinter::doFinalization(M);
873 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
874 /// for a MachineFunction to the given output stream, in a format that the
875 /// Darwin assembler can deal with.
877 static AsmPrinter *createPPCAsmPrinterPass(formatted_raw_ostream &o,
879 MCStreamer &Streamer) {
880 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
882 if (Subtarget->isDarwin())
883 return new PPCDarwinAsmPrinter(o, tm, Streamer);
884 return new PPCLinuxAsmPrinter(o, tm, Streamer);
887 // Force static initialization.
888 extern "C" void LLVMInitializePowerPCAsmPrinter() {
889 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
890 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);