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);
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(Mang->getSymbol(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);
305 assert(MO.getType() == MachineOperand::MO_GlobalAddress);
306 const MCSymbol *Sym = Mang->getSymbol(MO.getGlobal());
308 // Map symbol -> label of TOC entry.
309 const MCSymbol *&TOCEntry = TOC[Sym];
311 TOCEntry = OutContext.
312 GetOrCreateTemporarySymbol(StringRef(MAI->getPrivateGlobalPrefix()) +
313 "C" + Twine(LabelID++));
315 O << *TOCEntry << "@toc";
318 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
319 const char *Modifier);
322 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
323 class PPCLinuxAsmPrinter : public PPCAsmPrinter {
325 explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
326 MCStreamer &Streamer)
327 : PPCAsmPrinter(O, TM, Streamer) {}
329 virtual const char *getPassName() const {
330 return "Linux PPC Assembly Printer";
333 bool doFinalization(Module &M);
335 virtual void EmitFunctionEntryLabel();
337 void getAnalysisUsage(AnalysisUsage &AU) const {
338 AU.setPreservesAll();
339 AU.addRequired<MachineModuleInfo>();
340 AU.addRequired<DwarfWriter>();
341 PPCAsmPrinter::getAnalysisUsage(AU);
345 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
347 class PPCDarwinAsmPrinter : public PPCAsmPrinter {
348 formatted_raw_ostream &OS;
350 explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
351 MCStreamer &Streamer)
352 : PPCAsmPrinter(O, TM, Streamer), OS(O) {}
354 virtual const char *getPassName() const {
355 return "Darwin PPC Assembly Printer";
358 bool doFinalization(Module &M);
359 void EmitStartOfAsmFile(Module &M);
361 void EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs);
363 void getAnalysisUsage(AnalysisUsage &AU) const {
364 AU.setPreservesAll();
365 AU.addRequired<MachineModuleInfo>();
366 AU.addRequired<DwarfWriter>();
367 PPCAsmPrinter::getAnalysisUsage(AU);
370 } // end of anonymous namespace
372 // Include the auto-generated portion of the assembly writer
373 #include "PPCGenAsmWriter.inc"
375 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
376 switch (MO.getType()) {
377 case MachineOperand::MO_Immediate:
378 llvm_unreachable("printOp() does not handle immediate values");
380 case MachineOperand::MO_MachineBasicBlock:
381 O << *MO.getMBB()->getSymbol();
383 case MachineOperand::MO_JumpTableIndex:
384 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
385 << '_' << MO.getIndex();
386 // FIXME: PIC relocation model
388 case MachineOperand::MO_ConstantPoolIndex:
389 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
390 << '_' << MO.getIndex();
392 case MachineOperand::MO_BlockAddress:
393 O << *GetBlockAddressSymbol(MO.getBlockAddress());
395 case MachineOperand::MO_ExternalSymbol: {
396 // Computing the address of an external symbol, not calling it.
397 if (TM.getRelocationModel() == Reloc::Static) {
398 O << *GetExternalSymbolSymbol(MO.getSymbolName());
403 OutContext.GetOrCreateSymbol(StringRef(MAI->getGlobalPrefix())+
404 MO.getSymbolName()+"$non_lazy_ptr");
405 MachineModuleInfoImpl::StubValueTy &StubSym =
406 MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(NLPSym);
407 if (StubSym.getPointer() == 0)
408 StubSym = MachineModuleInfoImpl::
409 StubValueTy(GetExternalSymbolSymbol(MO.getSymbolName()), true);
414 case MachineOperand::MO_GlobalAddress: {
415 // Computing the address of a global symbol, not calling it.
416 GlobalValue *GV = MO.getGlobal();
417 MCSymbol *SymToPrint;
419 // External or weakly linked global variables need non-lazily-resolved stubs
420 if (TM.getRelocationModel() != Reloc::Static &&
421 (GV->isDeclaration() || GV->isWeakForLinker())) {
422 if (!GV->hasHiddenVisibility()) {
423 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
424 MachineModuleInfoImpl::StubValueTy &StubSym =
425 MMI->getObjFileInfo<MachineModuleInfoMachO>()
426 .getGVStubEntry(SymToPrint);
427 if (StubSym.getPointer() == 0)
428 StubSym = MachineModuleInfoImpl::
429 StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
430 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
431 GV->hasAvailableExternallyLinkage()) {
432 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
434 MachineModuleInfoImpl::StubValueTy &StubSym =
435 MMI->getObjFileInfo<MachineModuleInfoMachO>().
436 getHiddenGVStubEntry(SymToPrint);
437 if (StubSym.getPointer() == 0)
438 StubSym = MachineModuleInfoImpl::
439 StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
441 SymToPrint = Mang->getSymbol(GV);
444 SymToPrint = Mang->getSymbol(GV);
449 printOffset(MO.getOffset());
454 O << "<unknown operand type: " << MO.getType() << ">";
459 /// PrintAsmOperand - Print out an operand for an inline asm expression.
461 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
463 const char *ExtraCode) {
464 // Does this asm operand have a single letter operand modifier?
465 if (ExtraCode && ExtraCode[0]) {
466 if (ExtraCode[1] != 0) return true; // Unknown modifier.
468 switch (ExtraCode[0]) {
469 default: return true; // Unknown modifier.
470 case 'c': // Don't print "$" before a global var name or constant.
471 // PPC never has a prefix.
472 printOperand(MI, OpNo);
474 case 'L': // Write second word of DImode reference.
475 // Verify that this operand has two consecutive registers.
476 if (!MI->getOperand(OpNo).isReg() ||
477 OpNo+1 == MI->getNumOperands() ||
478 !MI->getOperand(OpNo+1).isReg())
480 ++OpNo; // Return the high-part.
483 // Write 'i' if an integer constant, otherwise nothing. Used to print
485 if (MI->getOperand(OpNo).isImm())
491 printOperand(MI, OpNo);
495 // At the moment, all inline asm memory operands are a single register.
496 // In any case, the output of this routine should always be just one
497 // assembler operand.
499 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
501 const char *ExtraCode) {
502 if (ExtraCode && ExtraCode[0])
503 return true; // Unknown modifier.
504 assert (MI->getOperand(OpNo).isReg());
506 printOperand(MI, OpNo);
511 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
512 const char *Modifier) {
513 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
514 unsigned Code = MI->getOperand(OpNo).getImm();
515 if (!strcmp(Modifier, "cc")) {
516 switch ((PPC::Predicate)Code) {
517 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
518 case PPC::PRED_LT: O << "lt"; return;
519 case PPC::PRED_LE: O << "le"; return;
520 case PPC::PRED_EQ: O << "eq"; return;
521 case PPC::PRED_GE: O << "ge"; return;
522 case PPC::PRED_GT: O << "gt"; return;
523 case PPC::PRED_NE: O << "ne"; return;
524 case PPC::PRED_UN: O << "un"; return;
525 case PPC::PRED_NU: O << "nu"; return;
529 assert(!strcmp(Modifier, "reg") &&
530 "Need to specify 'cc' or 'reg' as predicate op modifier!");
531 // Don't print the register for 'always'.
532 if (Code == PPC::PRED_ALWAYS) return;
533 printOperand(MI, OpNo+1);
538 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
539 /// the current output stream.
541 void PPCAsmPrinter::EmitInstruction(const MachineInstr *MI) {
542 // Check for slwi/srwi mnemonics.
543 if (MI->getOpcode() == PPC::RLWINM) {
544 unsigned char SH = MI->getOperand(2).getImm();
545 unsigned char MB = MI->getOperand(3).getImm();
546 unsigned char ME = MI->getOperand(4).getImm();
547 bool useSubstituteMnemonic = false;
548 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
549 O << "\tslwi "; useSubstituteMnemonic = true;
551 if (SH <= 31 && MB == (32-SH) && ME == 31) {
552 O << "\tsrwi "; useSubstituteMnemonic = true;
555 if (useSubstituteMnemonic) {
559 O << ", " << (unsigned int)SH;
560 OutStreamer.AddBlankLine();
565 if ((MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) &&
566 MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
571 OutStreamer.AddBlankLine();
575 if (MI->getOpcode() == PPC::RLDICR) {
576 unsigned char SH = MI->getOperand(2).getImm();
577 unsigned char ME = MI->getOperand(3).getImm();
578 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
584 O << ", " << (unsigned int)SH;
585 OutStreamer.AddBlankLine();
590 printInstruction(MI);
591 OutStreamer.AddBlankLine();
594 void PPCLinuxAsmPrinter::EmitFunctionEntryLabel() {
595 if (!Subtarget.isPPC64()) // linux/ppc32 - Normal entry label.
596 return AsmPrinter::EmitFunctionEntryLabel();
598 // Emit an official procedure descriptor.
599 // FIXME 64-bit SVR4: Use MCSection here!
600 O << "\t.section\t\".opd\",\"aw\"\n";
602 OutStreamer.EmitLabel(CurrentFnSym);
603 O << "\t.quad .L." << *CurrentFnSym << ",.TOC.@tocbase\n";
604 O << "\t.previous\n";
605 O << ".L." << *CurrentFnSym << ":\n";
609 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
610 const TargetData *TD = TM.getTargetData();
612 bool isPPC64 = TD->getPointerSizeInBits() == 64;
614 if (isPPC64 && !TOC.empty()) {
615 // FIXME 64-bit SVR4: Use MCSection here?
616 O << "\t.section\t\".toc\",\"aw\"\n";
618 // FIXME: This is nondeterminstic!
619 for (DenseMap<const MCSymbol*, const MCSymbol*>::iterator I = TOC.begin(),
620 E = TOC.end(); I != E; ++I) {
621 O << *I->second << ":\n";
622 O << "\t.tc " << *I->first << "[TC]," << *I->first << '\n';
626 return AsmPrinter::doFinalization(M);
629 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
630 static const char *const CPUDirectives[] = {
642 unsigned Directive = Subtarget.getDarwinDirective();
643 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
644 Directive = PPC::DIR_970;
645 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
646 Directive = PPC::DIR_7400;
647 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
648 Directive = PPC::DIR_64;
649 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
650 O << "\t.machine " << CPUDirectives[Directive] << '\n';
652 // Prime text sections so they are adjacent. This reduces the likelihood a
653 // large data or debug section causes a branch to exceed 16M limit.
654 TargetLoweringObjectFileMachO &TLOFMacho =
655 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
656 OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
657 if (TM.getRelocationModel() == Reloc::PIC_) {
658 OutStreamer.SwitchSection(
659 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
660 MCSectionMachO::S_SYMBOL_STUBS |
661 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
662 32, SectionKind::getText()));
663 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
664 OutStreamer.SwitchSection(
665 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
666 MCSectionMachO::S_SYMBOL_STUBS |
667 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
668 16, SectionKind::getText()));
670 OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
673 static const MCSymbol *GetLazyPtr(const MCSymbol *Sym, MCContext &Ctx) {
674 // Remove $stub suffix, add $lazy_ptr.
675 SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end()-5);
676 TmpStr += "$lazy_ptr";
677 return Ctx.GetOrCreateTemporarySymbol(TmpStr.str());
680 static const MCSymbol *GetAnonSym(const MCSymbol *Sym, MCContext &Ctx) {
681 // Add $tmp suffix to $stub, yielding $stub$tmp.
682 SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end());
684 return Ctx.GetOrCreateTemporarySymbol(TmpStr.str());
687 void PPCDarwinAsmPrinter::
688 EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs) {
689 bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
691 TargetLoweringObjectFileMachO &TLOFMacho =
692 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
694 // .lazy_symbol_pointer
695 const MCSection *LSPSection = TLOFMacho.getLazySymbolPointerSection();
697 // Output stubs for dynamically-linked functions
698 if (TM.getRelocationModel() == Reloc::PIC_) {
699 const MCSection *StubSection =
700 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
701 MCSectionMachO::S_SYMBOL_STUBS |
702 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
703 32, SectionKind::getText());
704 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
705 OutStreamer.SwitchSection(StubSection);
708 const MCSymbol *Stub = Stubs[i].first;
709 const MCSymbol *RawSym = Stubs[i].second.getPointer();
710 const MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
711 const MCSymbol *AnonSymbol = GetAnonSym(Stub, OutContext);
714 O << "\t.indirect_symbol " << *RawSym << '\n';
716 O << "\tbcl 20,31," << *AnonSymbol << '\n';
717 O << *AnonSymbol << ":\n";
719 O << "\taddis r11,r11,ha16(" << *LazyPtr << '-' << *AnonSymbol
722 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(" << *LazyPtr
723 << '-' << *AnonSymbol << ")(r11)\n";
724 O << "\tmtctr r12\n";
727 OutStreamer.SwitchSection(LSPSection);
728 O << *LazyPtr << ":\n";
729 O << "\t.indirect_symbol " << *RawSym << '\n';
730 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
736 const MCSection *StubSection =
737 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
738 MCSectionMachO::S_SYMBOL_STUBS |
739 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
740 16, SectionKind::getText());
741 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
742 const MCSymbol *Stub = Stubs[i].first;
743 const MCSymbol *RawSym = Stubs[i].second.getPointer();
744 const MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
746 OutStreamer.SwitchSection(StubSection);
749 O << "\t.indirect_symbol " << *RawSym << '\n';
750 O << "\tlis r11,ha16(" << *LazyPtr << ")\n";
751 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(" << *LazyPtr
753 O << "\tmtctr r12\n";
755 OutStreamer.SwitchSection(LSPSection);
756 O << *LazyPtr << ":\n";
757 O << "\t.indirect_symbol " << *RawSym << '\n';
758 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
765 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
766 bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
768 // Darwin/PPC always uses mach-o.
769 TargetLoweringObjectFileMachO &TLOFMacho =
770 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
771 MachineModuleInfoMachO &MMIMacho =
772 MMI->getObjFileInfo<MachineModuleInfoMachO>();
774 MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetFnStubList();
776 EmitFunctionStubs(Stubs);
778 if (MAI->doesSupportExceptionHandling() && MMI) {
779 // Add the (possibly multiple) personalities to the set of global values.
780 // Only referenced functions get into the Personalities list.
781 const std::vector<Function *> &Personalities = MMI->getPersonalities();
782 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
783 E = Personalities.end(); I != E; ++I) {
785 MCSymbol *NLPSym = GetSymbolWithGlobalValueBase(*I, "$non_lazy_ptr");
786 MachineModuleInfoImpl::StubValueTy &StubSym =
787 MMIMacho.getGVStubEntry(NLPSym);
788 StubSym = MachineModuleInfoImpl::StubValueTy(Mang->getSymbol(*I), true);
793 // Output stubs for dynamically-linked functions.
794 Stubs = MMIMacho.GetGVStubList();
796 // Output macho stubs for external and common global variables.
797 if (!Stubs.empty()) {
798 // Switch with ".non_lazy_symbol_pointer" directive.
799 OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
800 EmitAlignment(isPPC64 ? 3 : 2);
802 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
804 OutStreamer.EmitLabel(Stubs[i].first);
805 // .indirect_symbol _foo
806 MachineModuleInfoImpl::StubValueTy &MCSym = Stubs[i].second;
807 OutStreamer.EmitSymbolAttribute(MCSym.getPointer(), MCSA_IndirectSymbol);
810 // External to current translation unit.
811 OutStreamer.EmitIntValue(0, isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
813 // Internal to current translation unit.
814 OutStreamer.EmitValue(MCSymbolRefExpr::Create(MCSym.getPointer(),
816 isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
820 OutStreamer.AddBlankLine();
823 Stubs = MMIMacho.GetHiddenGVStubList();
824 if (!Stubs.empty()) {
825 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
826 EmitAlignment(isPPC64 ? 3 : 2);
828 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
830 OutStreamer.EmitLabel(Stubs[i].first);
832 OutStreamer.EmitValue(MCSymbolRefExpr::
833 Create(Stubs[i].second.getPointer(),
835 isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
839 OutStreamer.AddBlankLine();
842 // Funny Darwin hack: This flag tells the linker that no global symbols
843 // contain code that falls through to other global symbols (e.g. the obvious
844 // implementation of multiple entry points). If this doesn't occur, the
845 // linker can safely perform dead code stripping. Since LLVM never generates
846 // code that does this, it is always safe to set.
847 OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
849 return AsmPrinter::doFinalization(M);
852 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
853 /// for a MachineFunction to the given output stream, in a format that the
854 /// Darwin assembler can deal with.
856 static AsmPrinter *createPPCAsmPrinterPass(formatted_raw_ostream &o,
858 MCStreamer &Streamer) {
859 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
861 if (Subtarget->isDarwin())
862 return new PPCDarwinAsmPrinter(o, tm, Streamer);
863 return new PPCLinuxAsmPrinter(o, tm, Streamer);
866 // Force static initialization.
867 extern "C" void LLVMInitializePowerPCAsmPrinter() {
868 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
869 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);