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/Analysis/DebugInfo.h"
25 #include "llvm/Constants.h"
26 #include "llvm/DerivedTypes.h"
27 #include "llvm/Module.h"
28 #include "llvm/Assembly/Writer.h"
29 #include "llvm/CodeGen/AsmPrinter.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 const 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();
347 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
349 class PPCDarwinAsmPrinter : public PPCAsmPrinter {
351 explicit PPCDarwinAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
352 : PPCAsmPrinter(TM, Streamer) {}
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 } // end of anonymous namespace
365 // Include the auto-generated portion of the assembly writer
366 #include "PPCGenAsmWriter.inc"
368 void PPCAsmPrinter::printOp(const MachineOperand &MO, raw_ostream &O) {
369 switch (MO.getType()) {
370 case MachineOperand::MO_Immediate:
371 llvm_unreachable("printOp() does not handle immediate values");
373 case MachineOperand::MO_MachineBasicBlock:
374 O << *MO.getMBB()->getSymbol();
376 case MachineOperand::MO_JumpTableIndex:
377 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
378 << '_' << MO.getIndex();
379 // FIXME: PIC relocation model
381 case MachineOperand::MO_ConstantPoolIndex:
382 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
383 << '_' << MO.getIndex();
385 case MachineOperand::MO_BlockAddress:
386 O << *GetBlockAddressSymbol(MO.getBlockAddress());
388 case MachineOperand::MO_ExternalSymbol: {
389 // Computing the address of an external symbol, not calling it.
390 if (TM.getRelocationModel() == Reloc::Static) {
391 O << *GetExternalSymbolSymbol(MO.getSymbolName());
396 OutContext.GetOrCreateSymbol(StringRef(MAI->getGlobalPrefix())+
397 MO.getSymbolName()+"$non_lazy_ptr");
398 MachineModuleInfoImpl::StubValueTy &StubSym =
399 MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(NLPSym);
400 if (StubSym.getPointer() == 0)
401 StubSym = MachineModuleInfoImpl::
402 StubValueTy(GetExternalSymbolSymbol(MO.getSymbolName()), true);
407 case MachineOperand::MO_GlobalAddress: {
408 // Computing the address of a global symbol, not calling it.
409 const GlobalValue *GV = MO.getGlobal();
410 MCSymbol *SymToPrint;
412 // External or weakly linked global variables need non-lazily-resolved stubs
413 if (TM.getRelocationModel() != Reloc::Static &&
414 (GV->isDeclaration() || GV->isWeakForLinker())) {
415 if (!GV->hasHiddenVisibility()) {
416 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
417 MachineModuleInfoImpl::StubValueTy &StubSym =
418 MMI->getObjFileInfo<MachineModuleInfoMachO>()
419 .getGVStubEntry(SymToPrint);
420 if (StubSym.getPointer() == 0)
421 StubSym = MachineModuleInfoImpl::
422 StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
423 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
424 GV->hasAvailableExternallyLinkage()) {
425 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
427 MachineModuleInfoImpl::StubValueTy &StubSym =
428 MMI->getObjFileInfo<MachineModuleInfoMachO>().
429 getHiddenGVStubEntry(SymToPrint);
430 if (StubSym.getPointer() == 0)
431 StubSym = MachineModuleInfoImpl::
432 StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
434 SymToPrint = Mang->getSymbol(GV);
437 SymToPrint = Mang->getSymbol(GV);
442 printOffset(MO.getOffset(), O);
447 O << "<unknown operand type: " << MO.getType() << ">";
452 /// PrintAsmOperand - Print out an operand for an inline asm expression.
454 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
456 const char *ExtraCode, raw_ostream &O) {
457 // Does this asm operand have a single letter operand modifier?
458 if (ExtraCode && ExtraCode[0]) {
459 if (ExtraCode[1] != 0) return true; // Unknown modifier.
461 switch (ExtraCode[0]) {
462 default: return true; // Unknown modifier.
463 case 'c': // Don't print "$" before a global var name or constant.
464 // PPC never has a prefix.
465 printOperand(MI, OpNo, O);
467 case 'L': // Write second word of DImode reference.
468 // Verify that this operand has two consecutive registers.
469 if (!MI->getOperand(OpNo).isReg() ||
470 OpNo+1 == MI->getNumOperands() ||
471 !MI->getOperand(OpNo+1).isReg())
473 ++OpNo; // Return the high-part.
476 // Write 'i' if an integer constant, otherwise nothing. Used to print
478 if (MI->getOperand(OpNo).isImm())
484 printOperand(MI, OpNo, O);
488 // At the moment, all inline asm memory operands are a single register.
489 // In any case, the output of this routine should always be just one
490 // assembler operand.
492 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
494 const char *ExtraCode,
496 if (ExtraCode && ExtraCode[0])
497 return true; // Unknown modifier.
498 assert (MI->getOperand(OpNo).isReg());
500 printOperand(MI, OpNo, O);
505 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
506 raw_ostream &O, const char *Modifier){
507 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
508 unsigned Code = MI->getOperand(OpNo).getImm();
509 if (!strcmp(Modifier, "cc")) {
510 switch ((PPC::Predicate)Code) {
511 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
512 case PPC::PRED_LT: O << "lt"; return;
513 case PPC::PRED_LE: O << "le"; return;
514 case PPC::PRED_EQ: O << "eq"; return;
515 case PPC::PRED_GE: O << "ge"; return;
516 case PPC::PRED_GT: O << "gt"; return;
517 case PPC::PRED_NE: O << "ne"; return;
518 case PPC::PRED_UN: O << "un"; return;
519 case PPC::PRED_NU: O << "nu"; return;
523 assert(!strcmp(Modifier, "reg") &&
524 "Need to specify 'cc' or 'reg' as predicate op modifier!");
525 // Don't print the register for 'always'.
526 if (Code == PPC::PRED_ALWAYS) return;
527 printOperand(MI, OpNo+1, O);
532 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
533 /// the current output stream.
535 void PPCAsmPrinter::EmitInstruction(const MachineInstr *MI) {
536 SmallString<128> Str;
537 raw_svector_ostream O(Str);
539 if (MI->getOpcode() == TargetOpcode::DBG_VALUE) {
540 unsigned NOps = MI->getNumOperands();
542 O << '\t' << MAI->getCommentString() << "DEBUG_VALUE: ";
543 // cast away const; DIetc do not take const operands for some reason.
544 DIVariable V(const_cast<MDNode *>(MI->getOperand(NOps-1).getMetadata()));
547 // Frame address. Currently handles register +- offset only.
548 assert(MI->getOperand(0).isReg() && MI->getOperand(1).isImm());
549 O << '['; printOperand(MI, 0, O); O << '+'; printOperand(MI, 1, O);
552 printOperand(MI, NOps-2, O);
553 OutStreamer.EmitRawText(O.str());
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.EmitRawText(O.str());
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.EmitRawText(O.str());
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.EmitRawText(O.str());
604 printInstruction(MI, O);
605 OutStreamer.EmitRawText(O.str());
608 void PPCLinuxAsmPrinter::EmitFunctionEntryLabel() {
609 if (!Subtarget.isPPC64()) // linux/ppc32 - Normal entry label.
610 return AsmPrinter::EmitFunctionEntryLabel();
612 // Emit an official procedure descriptor.
613 // FIXME 64-bit SVR4: Use MCSection here!
614 OutStreamer.EmitRawText(StringRef("\t.section\t\".opd\",\"aw\""));
615 OutStreamer.EmitRawText(StringRef("\t.align 3"));
616 OutStreamer.EmitLabel(CurrentFnSym);
617 OutStreamer.EmitRawText("\t.quad .L." + Twine(CurrentFnSym->getName()) +
619 OutStreamer.EmitRawText(StringRef("\t.previous"));
620 OutStreamer.EmitRawText(".L." + Twine(CurrentFnSym->getName()) + ":");
624 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
625 const TargetData *TD = TM.getTargetData();
627 bool isPPC64 = TD->getPointerSizeInBits() == 64;
629 if (isPPC64 && !TOC.empty()) {
630 // FIXME 64-bit SVR4: Use MCSection here?
631 OutStreamer.EmitRawText(StringRef("\t.section\t\".toc\",\"aw\""));
633 // FIXME: This is nondeterminstic!
634 for (DenseMap<MCSymbol*, MCSymbol*>::iterator I = TOC.begin(),
635 E = TOC.end(); I != E; ++I) {
636 OutStreamer.EmitLabel(I->second);
637 OutStreamer.EmitRawText("\t.tc " + Twine(I->first->getName()) +
638 "[TC]," + I->first->getName());
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 OutStreamer.EmitRawText("\t.machine " + Twine(CPUDirectives[Directive]));
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 const TargetLoweringObjectFileMachO &TLOFMacho =
671 static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
672 OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
673 if (TM.getRelocationModel() == Reloc::PIC_) {
674 OutStreamer.SwitchSection(
675 OutContext.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 OutContext.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 MCSymbol *GetLazyPtr(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 MCSymbol *GetAnonSym(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 const TargetLoweringObjectFileMachO &TLOFMacho =
708 static_cast<const 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 OutContext.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 MCSymbol *Stub = Stubs[i].first;
725 MCSymbol *RawSym = Stubs[i].second.getPointer();
726 MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
727 MCSymbol *AnonSymbol = GetAnonSym(Stub, OutContext);
729 OutStreamer.EmitLabel(Stub);
730 OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
731 // FIXME: MCize this.
732 OutStreamer.EmitRawText(StringRef("\tmflr r0"));
733 OutStreamer.EmitRawText("\tbcl 20,31," + Twine(AnonSymbol->getName()));
734 OutStreamer.EmitLabel(AnonSymbol);
735 OutStreamer.EmitRawText(StringRef("\tmflr r11"));
736 OutStreamer.EmitRawText("\taddis r11,r11,ha16("+Twine(LazyPtr->getName())+
737 "-" + AnonSymbol->getName() + ")");
738 OutStreamer.EmitRawText(StringRef("\tmtlr r0"));
741 OutStreamer.EmitRawText("\tldu r12,lo16(" + Twine(LazyPtr->getName()) +
742 "-" + AnonSymbol->getName() + ")(r11)");
744 OutStreamer.EmitRawText("\tlwzu r12,lo16(" + Twine(LazyPtr->getName()) +
745 "-" + AnonSymbol->getName() + ")(r11)");
746 OutStreamer.EmitRawText(StringRef("\tmtctr r12"));
747 OutStreamer.EmitRawText(StringRef("\tbctr"));
749 OutStreamer.SwitchSection(LSPSection);
750 OutStreamer.EmitLabel(LazyPtr);
751 OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
754 OutStreamer.EmitRawText(StringRef("\t.quad dyld_stub_binding_helper"));
756 OutStreamer.EmitRawText(StringRef("\t.long dyld_stub_binding_helper"));
758 OutStreamer.AddBlankLine();
762 const MCSection *StubSection =
763 OutContext.getMachOSection("__TEXT","__symbol_stub1",
764 MCSectionMachO::S_SYMBOL_STUBS |
765 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
766 16, SectionKind::getText());
767 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
768 MCSymbol *Stub = Stubs[i].first;
769 MCSymbol *RawSym = Stubs[i].second.getPointer();
770 MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
772 OutStreamer.SwitchSection(StubSection);
774 OutStreamer.EmitLabel(Stub);
775 OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
776 OutStreamer.EmitRawText("\tlis r11,ha16(" + Twine(LazyPtr->getName()) +")");
778 OutStreamer.EmitRawText("\tldu r12,lo16(" + Twine(LazyPtr->getName()) +
781 OutStreamer.EmitRawText("\tlwzu r12,lo16(" + Twine(LazyPtr->getName()) +
783 OutStreamer.EmitRawText(StringRef("\tmtctr r12"));
784 OutStreamer.EmitRawText(StringRef("\tbctr"));
785 OutStreamer.SwitchSection(LSPSection);
786 OutStreamer.EmitLabel(LazyPtr);
787 OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
790 OutStreamer.EmitRawText(StringRef("\t.quad dyld_stub_binding_helper"));
792 OutStreamer.EmitRawText(StringRef("\t.long dyld_stub_binding_helper"));
795 OutStreamer.AddBlankLine();
799 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
800 bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
802 // Darwin/PPC always uses mach-o.
803 const TargetLoweringObjectFileMachO &TLOFMacho =
804 static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
805 MachineModuleInfoMachO &MMIMacho =
806 MMI->getObjFileInfo<MachineModuleInfoMachO>();
808 MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetFnStubList();
810 EmitFunctionStubs(Stubs);
812 if (MAI->doesSupportExceptionHandling() && MMI) {
813 // Add the (possibly multiple) personalities to the set of global values.
814 // Only referenced functions get into the Personalities list.
815 const std::vector<const Function*> &Personalities = MMI->getPersonalities();
816 for (std::vector<const Function*>::const_iterator I = Personalities.begin(),
817 E = Personalities.end(); I != E; ++I) {
819 MCSymbol *NLPSym = GetSymbolWithGlobalValueBase(*I, "$non_lazy_ptr");
820 MachineModuleInfoImpl::StubValueTy &StubSym =
821 MMIMacho.getGVStubEntry(NLPSym);
822 StubSym = MachineModuleInfoImpl::StubValueTy(Mang->getSymbol(*I), true);
827 // Output stubs for dynamically-linked functions.
828 Stubs = MMIMacho.GetGVStubList();
830 // Output macho stubs for external and common global variables.
831 if (!Stubs.empty()) {
832 // Switch with ".non_lazy_symbol_pointer" directive.
833 OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
834 EmitAlignment(isPPC64 ? 3 : 2);
836 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
838 OutStreamer.EmitLabel(Stubs[i].first);
839 // .indirect_symbol _foo
840 MachineModuleInfoImpl::StubValueTy &MCSym = Stubs[i].second;
841 OutStreamer.EmitSymbolAttribute(MCSym.getPointer(), MCSA_IndirectSymbol);
844 // External to current translation unit.
845 OutStreamer.EmitIntValue(0, isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
847 // Internal to current translation unit.
849 // When we place the LSDA into the TEXT section, the type info pointers
850 // need to be indirect and pc-rel. We accomplish this by using NLPs.
851 // However, sometimes the types are local to the file. So we need to
852 // fill in the value for the NLP in those cases.
853 OutStreamer.EmitValue(MCSymbolRefExpr::Create(MCSym.getPointer(),
855 isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
859 OutStreamer.AddBlankLine();
862 Stubs = MMIMacho.GetHiddenGVStubList();
863 if (!Stubs.empty()) {
864 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
865 EmitAlignment(isPPC64 ? 3 : 2);
867 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
869 OutStreamer.EmitLabel(Stubs[i].first);
871 OutStreamer.EmitValue(MCSymbolRefExpr::
872 Create(Stubs[i].second.getPointer(),
874 isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
878 OutStreamer.AddBlankLine();
881 // Funny Darwin hack: This flag tells the linker that no global symbols
882 // contain code that falls through to other global symbols (e.g. the obvious
883 // implementation of multiple entry points). If this doesn't occur, the
884 // linker can safely perform dead code stripping. Since LLVM never generates
885 // code that does this, it is always safe to set.
886 OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
888 return AsmPrinter::doFinalization(M);
891 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
892 /// for a MachineFunction to the given output stream, in a format that the
893 /// Darwin assembler can deal with.
895 static AsmPrinter *createPPCAsmPrinterPass(TargetMachine &tm,
896 MCStreamer &Streamer) {
897 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
899 if (Subtarget->isDarwin())
900 return new PPCDarwinAsmPrinter(tm, Streamer);
901 return new PPCLinuxAsmPrinter(tm, Streamer);
904 // Force static initialization.
905 extern "C" void LLVMInitializePowerPCAsmPrinter() {
906 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
907 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);