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 "PPCTargetMachine.h"
22 #include "PPCSubtarget.h"
23 #include "InstPrinter/PPCInstPrinter.h"
24 #include "MCTargetDesc/PPCPredicates.h"
25 #include "llvm/Constants.h"
26 #include "llvm/DebugInfo.h"
27 #include "llvm/DerivedTypes.h"
28 #include "llvm/Module.h"
29 #include "llvm/Assembly/Writer.h"
30 #include "llvm/CodeGen/AsmPrinter.h"
31 #include "llvm/CodeGen/MachineFunctionPass.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
35 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/MC/MCContext.h"
38 #include "llvm/MC/MCExpr.h"
39 #include "llvm/MC/MCInst.h"
40 #include "llvm/MC/MCInstBuilder.h"
41 #include "llvm/MC/MCSectionMachO.h"
42 #include "llvm/MC/MCStreamer.h"
43 #include "llvm/MC/MCSymbol.h"
44 #include "llvm/MC/MCSectionELF.h"
45 #include "llvm/Target/Mangler.h"
46 #include "llvm/Target/TargetRegisterInfo.h"
47 #include "llvm/Target/TargetInstrInfo.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/TargetRegistry.h"
54 #include "llvm/Support/raw_ostream.h"
55 #include "llvm/Support/ELF.h"
56 #include "llvm/ADT/StringExtras.h"
57 #include "llvm/ADT/SmallString.h"
58 #include "llvm/ADT/MapVector.h"
62 class PPCAsmPrinter : public AsmPrinter {
64 MapVector<MCSymbol*, MCSymbol*> TOC;
65 const PPCSubtarget &Subtarget;
68 explicit PPCAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
69 : AsmPrinter(TM, Streamer),
70 Subtarget(TM.getSubtarget<PPCSubtarget>()), TOCLabelID(0) {}
72 virtual const char *getPassName() const {
73 return "PowerPC Assembly Printer";
76 MCSymbol *lookUpOrCreateTOCEntry(MCSymbol *Sym);
78 virtual void EmitInstruction(const MachineInstr *MI);
80 void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O);
82 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
83 unsigned AsmVariant, const char *ExtraCode,
85 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
86 unsigned AsmVariant, const char *ExtraCode,
89 MachineLocation getDebugValueLocation(const MachineInstr *MI) const {
90 MachineLocation Location;
91 assert(MI->getNumOperands() == 4 && "Invalid no. of machine operands!");
92 // Frame address. Currently handles register +- offset only.
93 if (MI->getOperand(0).isReg() && MI->getOperand(2).isImm())
94 Location.set(MI->getOperand(0).getReg(), MI->getOperand(2).getImm());
96 DEBUG(dbgs() << "DBG_VALUE instruction ignored! " << *MI << "\n");
102 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
103 class PPCLinuxAsmPrinter : public PPCAsmPrinter {
105 explicit PPCLinuxAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
106 : PPCAsmPrinter(TM, Streamer) {}
108 virtual const char *getPassName() const {
109 return "Linux PPC Assembly Printer";
112 bool doFinalization(Module &M);
114 virtual void EmitFunctionEntryLabel();
116 void EmitFunctionBodyEnd();
119 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
121 class PPCDarwinAsmPrinter : public PPCAsmPrinter {
123 explicit PPCDarwinAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
124 : PPCAsmPrinter(TM, Streamer) {}
126 virtual const char *getPassName() const {
127 return "Darwin PPC Assembly Printer";
130 bool doFinalization(Module &M);
131 void EmitStartOfAsmFile(Module &M);
133 void EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs);
135 } // end of anonymous namespace
137 /// stripRegisterPrefix - This method strips the character prefix from a
138 /// register name so that only the number is left. Used by for linux asm.
139 static const char *stripRegisterPrefix(const char *RegName) {
140 switch (RegName[0]) {
143 case 'v': return RegName + 1;
144 case 'c': if (RegName[1] == 'r') return RegName + 2;
150 void PPCAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
152 const MachineOperand &MO = MI->getOperand(OpNo);
154 switch (MO.getType()) {
155 case MachineOperand::MO_Register: {
156 const char *RegName = PPCInstPrinter::getRegisterName(MO.getReg());
157 // Linux assembler (Others?) does not take register mnemonics.
158 // FIXME - What about special registers used in mfspr/mtspr?
159 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
163 case MachineOperand::MO_Immediate:
167 case MachineOperand::MO_MachineBasicBlock:
168 O << *MO.getMBB()->getSymbol();
170 case MachineOperand::MO_JumpTableIndex:
171 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
172 << '_' << MO.getIndex();
173 // FIXME: PIC relocation model
175 case MachineOperand::MO_ConstantPoolIndex:
176 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
177 << '_' << MO.getIndex();
179 case MachineOperand::MO_BlockAddress:
180 O << *GetBlockAddressSymbol(MO.getBlockAddress());
182 case MachineOperand::MO_ExternalSymbol: {
183 // Computing the address of an external symbol, not calling it.
184 if (TM.getRelocationModel() == Reloc::Static) {
185 O << *GetExternalSymbolSymbol(MO.getSymbolName());
190 OutContext.GetOrCreateSymbol(StringRef(MAI->getGlobalPrefix())+
191 MO.getSymbolName()+"$non_lazy_ptr");
192 MachineModuleInfoImpl::StubValueTy &StubSym =
193 MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(NLPSym);
194 if (StubSym.getPointer() == 0)
195 StubSym = MachineModuleInfoImpl::
196 StubValueTy(GetExternalSymbolSymbol(MO.getSymbolName()), true);
201 case MachineOperand::MO_GlobalAddress: {
202 // Computing the address of a global symbol, not calling it.
203 const GlobalValue *GV = MO.getGlobal();
204 MCSymbol *SymToPrint;
206 // External or weakly linked global variables need non-lazily-resolved stubs
207 if (TM.getRelocationModel() != Reloc::Static &&
208 (GV->isDeclaration() || GV->isWeakForLinker())) {
209 if (!GV->hasHiddenVisibility()) {
210 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
211 MachineModuleInfoImpl::StubValueTy &StubSym =
212 MMI->getObjFileInfo<MachineModuleInfoMachO>()
213 .getGVStubEntry(SymToPrint);
214 if (StubSym.getPointer() == 0)
215 StubSym = MachineModuleInfoImpl::
216 StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
217 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
218 GV->hasAvailableExternallyLinkage()) {
219 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
221 MachineModuleInfoImpl::StubValueTy &StubSym =
222 MMI->getObjFileInfo<MachineModuleInfoMachO>().
223 getHiddenGVStubEntry(SymToPrint);
224 if (StubSym.getPointer() == 0)
225 StubSym = MachineModuleInfoImpl::
226 StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
228 SymToPrint = Mang->getSymbol(GV);
231 SymToPrint = Mang->getSymbol(GV);
236 printOffset(MO.getOffset(), O);
241 O << "<unknown operand type: " << MO.getType() << ">";
246 /// PrintAsmOperand - Print out an operand for an inline asm expression.
248 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
250 const char *ExtraCode, raw_ostream &O) {
251 // Does this asm operand have a single letter operand modifier?
252 if (ExtraCode && ExtraCode[0]) {
253 if (ExtraCode[1] != 0) return true; // Unknown modifier.
255 switch (ExtraCode[0]) {
257 // See if this is a generic print operand
258 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
259 case 'c': // Don't print "$" before a global var name or constant.
260 break; // PPC never has a prefix.
261 case 'L': // Write second word of DImode reference.
262 // Verify that this operand has two consecutive registers.
263 if (!MI->getOperand(OpNo).isReg() ||
264 OpNo+1 == MI->getNumOperands() ||
265 !MI->getOperand(OpNo+1).isReg())
267 ++OpNo; // Return the high-part.
270 // Write 'i' if an integer constant, otherwise nothing. Used to print
272 if (MI->getOperand(OpNo).isImm())
278 printOperand(MI, OpNo, O);
282 // At the moment, all inline asm memory operands are a single register.
283 // In any case, the output of this routine should always be just one
284 // assembler operand.
286 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
288 const char *ExtraCode,
290 if (ExtraCode && ExtraCode[0]) {
291 if (ExtraCode[1] != 0) return true; // Unknown modifier.
293 switch (ExtraCode[0]) {
294 default: return true; // Unknown modifier.
295 case 'y': // A memory reference for an X-form instruction
297 const char *RegName = "r0";
298 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
299 O << RegName << ", ";
300 printOperand(MI, OpNo, O);
306 assert(MI->getOperand(OpNo).isReg());
308 printOperand(MI, OpNo, O);
314 /// lookUpOrCreateTOCEntry -- Given a symbol, look up whether a TOC entry
315 /// exists for it. If not, create one. Then return a symbol that references
317 MCSymbol *PPCAsmPrinter::lookUpOrCreateTOCEntry(MCSymbol *Sym) {
319 MCSymbol *&TOCEntry = TOC[Sym];
321 // To avoid name clash check if the name already exists.
322 while (TOCEntry == 0) {
323 if (OutContext.LookupSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
324 "C" + Twine(TOCLabelID++)) == 0) {
325 TOCEntry = GetTempSymbol("C", TOCLabelID);
333 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
334 /// the current output stream.
336 void PPCAsmPrinter::EmitInstruction(const MachineInstr *MI) {
339 // Lower multi-instruction pseudo operations.
340 switch (MI->getOpcode()) {
342 case TargetOpcode::DBG_VALUE: {
343 if (!isVerbose() || !OutStreamer.hasRawTextSupport()) return;
346 raw_svector_ostream O(Str);
347 unsigned NOps = MI->getNumOperands();
349 O << '\t' << MAI->getCommentString() << "DEBUG_VALUE: ";
350 // cast away const; DIetc do not take const operands for some reason.
351 DIVariable V(const_cast<MDNode *>(MI->getOperand(NOps-1).getMetadata()));
354 // Frame address. Currently handles register +- offset only.
355 assert(MI->getOperand(0).isReg() && MI->getOperand(1).isImm());
356 O << '['; printOperand(MI, 0, O); O << '+'; printOperand(MI, 1, O);
359 printOperand(MI, NOps-2, O);
360 OutStreamer.EmitRawText(O.str());
364 case PPC::MovePCtoLR:
365 case PPC::MovePCtoLR8: {
366 // Transform %LR = MovePCtoLR
367 // Into this, where the label is the PIC base:
370 MCSymbol *PICBase = MF->getPICBaseSymbol();
373 OutStreamer.EmitInstruction(MCInstBuilder(PPC::BL_Darwin) // Darwin vs SVR4 doesn't matter here.
374 // FIXME: We would like an efficient form for this, so we don't have to do
375 // a lot of extra uniquing.
376 .addExpr(MCSymbolRefExpr::Create(PICBase, OutContext)));
379 OutStreamer.EmitLabel(PICBase);
385 // Transform %X3 = LDtoc <ga:@min1>, %X2
386 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, Subtarget.isDarwin());
388 // Change the opcode to LD, and the global address operand to be a
389 // reference to the TOC entry we will synthesize later.
390 TmpInst.setOpcode(PPC::LD);
391 const MachineOperand &MO = MI->getOperand(1);
393 // Map symbol -> label of TOC entry
394 assert(MO.isGlobal() || MO.isCPI() || MO.isJTI());
395 MCSymbol *MOSymbol = 0;
397 MOSymbol = Mang->getSymbol(MO.getGlobal());
399 MOSymbol = GetCPISymbol(MO.getIndex());
401 MOSymbol = GetJTISymbol(MO.getIndex());
403 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol);
406 MCSymbolRefExpr::Create(TOCEntry, MCSymbolRefExpr::VK_PPC_TOC_ENTRY,
408 TmpInst.getOperand(1) = MCOperand::CreateExpr(Exp);
409 OutStreamer.EmitInstruction(TmpInst);
413 case PPC::ADDIStocHA: {
414 // Transform %Xd = ADDIStocHA %X2, <ga:@sym>
415 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, Subtarget.isDarwin());
417 // Change the opcode to ADDIS8. If the global address is external,
418 // has common linkage, is a function address, or is a jump table
419 // address, then generate a TOC entry and reference that. Otherwise
420 // reference the symbol directly.
421 TmpInst.setOpcode(PPC::ADDIS8);
422 const MachineOperand &MO = MI->getOperand(2);
423 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI()) &&
424 "Invalid operand for ADDIStocHA!");
425 MCSymbol *MOSymbol = 0;
426 bool IsExternal = false;
427 bool IsFunction = false;
428 bool IsCommon = false;
431 const GlobalValue *GValue = MO.getGlobal();
432 MOSymbol = Mang->getSymbol(GValue);
433 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GValue);
434 IsExternal = GVar && !GVar->hasInitializer();
435 IsCommon = GVar && GValue->hasCommonLinkage();
437 } else if (MO.isCPI())
438 MOSymbol = GetCPISymbol(MO.getIndex());
440 MOSymbol = GetJTISymbol(MO.getIndex());
442 if (IsExternal || IsFunction || IsCommon || MO.isJTI())
443 MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
446 MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_TOC16_HA,
448 TmpInst.getOperand(2) = MCOperand::CreateExpr(Exp);
449 OutStreamer.EmitInstruction(TmpInst);
453 // Transform %Xd = LDtocL <ga:@sym>, %Xs
454 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, Subtarget.isDarwin());
456 // Change the opcode to LDrs, which is a form of LD with the offset
457 // specified by a SymbolLo. If the global address is external, has
458 // common linkage, or is a jump table address, then reference the
459 // associated TOC entry. Otherwise reference the symbol directly.
460 TmpInst.setOpcode(PPC::LDrs);
461 const MachineOperand &MO = MI->getOperand(1);
462 assert((MO.isGlobal() || MO.isJTI()) && "Invalid operand for LDtocL!");
463 MCSymbol *MOSymbol = 0;
466 MOSymbol = lookUpOrCreateTOCEntry(GetJTISymbol(MO.getIndex()));
468 const GlobalValue *GValue = MO.getGlobal();
469 MOSymbol = Mang->getSymbol(GValue);
470 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GValue);
472 if (!GVar || !GVar->hasInitializer() || GValue->hasCommonLinkage())
473 MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
477 MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_TOC16_LO,
479 TmpInst.getOperand(1) = MCOperand::CreateExpr(Exp);
480 OutStreamer.EmitInstruction(TmpInst);
483 case PPC::ADDItocL: {
484 // Transform %Xd = ADDItocL %Xs, <ga:@sym>
485 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, Subtarget.isDarwin());
487 // Change the opcode to ADDI8L. If the global address is external, then
488 // generate a TOC entry and reference that. Otherwise reference the
490 TmpInst.setOpcode(PPC::ADDI8L);
491 const MachineOperand &MO = MI->getOperand(2);
492 assert((MO.isGlobal() || MO.isCPI()) && "Invalid operand for ADDItocL");
493 MCSymbol *MOSymbol = 0;
494 bool IsExternal = false;
495 bool IsFunction = false;
498 const GlobalValue *GValue = MO.getGlobal();
499 MOSymbol = Mang->getSymbol(GValue);
500 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GValue);
501 IsExternal = GVar && !GVar->hasInitializer();
503 } else if (MO.isCPI())
504 MOSymbol = GetCPISymbol(MO.getIndex());
506 if (IsFunction || IsExternal)
507 MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
510 MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_TOC16_LO,
512 TmpInst.getOperand(2) = MCOperand::CreateExpr(Exp);
513 OutStreamer.EmitInstruction(TmpInst);
517 case PPC::MFCR8pseud:
518 // Transform: %R3 = MFCRpseud %CR7
519 // Into: %R3 = MFCR ;; cr7
520 OutStreamer.AddComment(PPCInstPrinter::
521 getRegisterName(MI->getOperand(1).getReg()));
522 OutStreamer.EmitInstruction(MCInstBuilder(Subtarget.isPPC64() ? PPC::MFCR8 : PPC::MFCR)
523 .addReg(MI->getOperand(0).getReg()));
526 // In Book E sync is called msync, handle this special case here...
527 if (Subtarget.isBookE()) {
528 OutStreamer.EmitRawText(StringRef("\tmsync"));
533 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, Subtarget.isDarwin());
534 OutStreamer.EmitInstruction(TmpInst);
537 void PPCLinuxAsmPrinter::EmitFunctionEntryLabel() {
538 if (!Subtarget.isPPC64()) // linux/ppc32 - Normal entry label.
539 return AsmPrinter::EmitFunctionEntryLabel();
541 // Emit an official procedure descriptor.
542 const MCSection *Current = OutStreamer.getCurrentSection();
543 const MCSectionELF *Section = OutStreamer.getContext().getELFSection(".opd",
544 ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC,
545 SectionKind::getReadOnly());
546 OutStreamer.SwitchSection(Section);
547 OutStreamer.EmitLabel(CurrentFnSym);
548 OutStreamer.EmitValueToAlignment(8);
550 OutContext.GetOrCreateSymbol(".L." + Twine(CurrentFnSym->getName()));
551 // Generates a R_PPC64_ADDR64 (from FK_DATA_8) relocation for the function
553 OutStreamer.EmitValue(MCSymbolRefExpr::Create(Symbol1, OutContext),
554 8/*size*/, 0/*addrspace*/);
555 MCSymbol *Symbol2 = OutContext.GetOrCreateSymbol(StringRef(".TOC."));
556 // Generates a R_PPC64_TOC relocation for TOC base insertion.
557 OutStreamer.EmitValue(MCSymbolRefExpr::Create(Symbol2,
558 MCSymbolRefExpr::VK_PPC_TOC, OutContext),
559 8/*size*/, 0/*addrspace*/);
560 // Emit a null environment pointer.
561 OutStreamer.EmitIntValue(0, 8 /* size */, 0 /* addrspace */);
562 OutStreamer.SwitchSection(Current);
564 MCSymbol *RealFnSym = OutContext.GetOrCreateSymbol(
565 ".L." + Twine(CurrentFnSym->getName()));
566 OutStreamer.EmitLabel(RealFnSym);
567 CurrentFnSymForSize = RealFnSym;
571 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
572 const DataLayout *TD = TM.getDataLayout();
574 bool isPPC64 = TD->getPointerSizeInBits() == 64;
576 if (isPPC64 && !TOC.empty()) {
577 const MCSectionELF *Section = OutStreamer.getContext().getELFSection(".toc",
578 ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC,
579 SectionKind::getReadOnly());
580 OutStreamer.SwitchSection(Section);
582 for (MapVector<MCSymbol*, MCSymbol*>::iterator I = TOC.begin(),
583 E = TOC.end(); I != E; ++I) {
584 OutStreamer.EmitLabel(I->second);
585 MCSymbol *S = OutContext.GetOrCreateSymbol(I->first->getName());
586 OutStreamer.EmitTCEntry(*S);
590 return AsmPrinter::doFinalization(M);
593 /// EmitFunctionBodyEnd - Print the traceback table before the .size
596 void PPCLinuxAsmPrinter::EmitFunctionBodyEnd() {
597 // Only the 64-bit target requires a traceback table. For now,
598 // we only emit the word of zeroes that GDB requires to find
599 // the end of the function, and zeroes for the eight-byte
601 // FIXME: We should fill in the eight-byte mandatory fields as described in
602 // the PPC64 ELF ABI (this is a low-priority item because GDB does not
603 // currently make use of these fields).
604 if (Subtarget.isPPC64()) {
605 OutStreamer.EmitIntValue(0, 4/*size*/);
606 OutStreamer.EmitIntValue(0, 8/*size*/);
610 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
611 static const char *const CPUDirectives[] = {
629 unsigned Directive = Subtarget.getDarwinDirective();
630 if (Subtarget.hasMFOCRF() && Directive < PPC::DIR_970)
631 Directive = PPC::DIR_970;
632 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
633 Directive = PPC::DIR_7400;
634 if (Subtarget.isPPC64() && Directive < PPC::DIR_64)
635 Directive = PPC::DIR_64;
636 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
638 // FIXME: This is a total hack, finish mc'izing the PPC backend.
639 if (OutStreamer.hasRawTextSupport())
640 OutStreamer.EmitRawText("\t.machine " + Twine(CPUDirectives[Directive]));
642 // Prime text sections so they are adjacent. This reduces the likelihood a
643 // large data or debug section causes a branch to exceed 16M limit.
644 const TargetLoweringObjectFileMachO &TLOFMacho =
645 static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
646 OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
647 if (TM.getRelocationModel() == Reloc::PIC_) {
648 OutStreamer.SwitchSection(
649 OutContext.getMachOSection("__TEXT", "__picsymbolstub1",
650 MCSectionMachO::S_SYMBOL_STUBS |
651 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
652 32, SectionKind::getText()));
653 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
654 OutStreamer.SwitchSection(
655 OutContext.getMachOSection("__TEXT","__symbol_stub1",
656 MCSectionMachO::S_SYMBOL_STUBS |
657 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
658 16, SectionKind::getText()));
660 OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
663 static MCSymbol *GetLazyPtr(MCSymbol *Sym, MCContext &Ctx) {
664 // Remove $stub suffix, add $lazy_ptr.
665 StringRef NoStub = Sym->getName().substr(0, Sym->getName().size()-5);
666 return Ctx.GetOrCreateSymbol(NoStub + "$lazy_ptr");
669 static MCSymbol *GetAnonSym(MCSymbol *Sym, MCContext &Ctx) {
670 // Add $tmp suffix to $stub, yielding $stub$tmp.
671 return Ctx.GetOrCreateSymbol(Sym->getName() + "$tmp");
674 void PPCDarwinAsmPrinter::
675 EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs) {
676 bool isPPC64 = TM.getDataLayout()->getPointerSizeInBits() == 64;
678 const TargetLoweringObjectFileMachO &TLOFMacho =
679 static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
681 // .lazy_symbol_pointer
682 const MCSection *LSPSection = TLOFMacho.getLazySymbolPointerSection();
684 // Output stubs for dynamically-linked functions
685 if (TM.getRelocationModel() == Reloc::PIC_) {
686 const MCSection *StubSection =
687 OutContext.getMachOSection("__TEXT", "__picsymbolstub1",
688 MCSectionMachO::S_SYMBOL_STUBS |
689 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
690 32, SectionKind::getText());
691 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
692 OutStreamer.SwitchSection(StubSection);
695 MCSymbol *Stub = Stubs[i].first;
696 MCSymbol *RawSym = Stubs[i].second.getPointer();
697 MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
698 MCSymbol *AnonSymbol = GetAnonSym(Stub, OutContext);
700 OutStreamer.EmitLabel(Stub);
701 OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
704 OutStreamer.EmitInstruction(MCInstBuilder(PPC::MFLR).addReg(PPC::R0));
705 // FIXME: MCize this.
706 OutStreamer.EmitRawText("\tbcl 20, 31, " + Twine(AnonSymbol->getName()));
707 OutStreamer.EmitLabel(AnonSymbol);
709 OutStreamer.EmitInstruction(MCInstBuilder(PPC::MFLR).addReg(PPC::R11));
710 // addis r11, r11, ha16(LazyPtr - AnonSymbol)
712 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(LazyPtr, OutContext),
713 MCSymbolRefExpr::Create(AnonSymbol, OutContext),
715 OutStreamer.EmitInstruction(MCInstBuilder(PPC::ADDIS)
720 OutStreamer.EmitInstruction(MCInstBuilder(PPC::MTLR).addReg(PPC::R0));
722 // ldu r12, lo16(LazyPtr - AnonSymbol)(r11)
723 // lwzu r12, lo16(LazyPtr - AnonSymbol)(r11)
724 OutStreamer.EmitInstruction(MCInstBuilder(isPPC64 ? PPC::LDU : PPC::LWZU)
726 .addExpr(Sub).addExpr(Sub)
729 OutStreamer.EmitInstruction(MCInstBuilder(PPC::MTCTR).addReg(PPC::R12));
731 OutStreamer.EmitInstruction(MCInstBuilder(PPC::BCTR));
733 OutStreamer.SwitchSection(LSPSection);
734 OutStreamer.EmitLabel(LazyPtr);
735 OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
737 MCSymbol *DyldStubBindingHelper =
738 OutContext.GetOrCreateSymbol(StringRef("dyld_stub_binding_helper"));
740 // .quad dyld_stub_binding_helper
741 OutStreamer.EmitSymbolValue(DyldStubBindingHelper, 8);
743 // .long dyld_stub_binding_helper
744 OutStreamer.EmitSymbolValue(DyldStubBindingHelper, 4);
747 OutStreamer.AddBlankLine();
751 const MCSection *StubSection =
752 OutContext.getMachOSection("__TEXT","__symbol_stub1",
753 MCSectionMachO::S_SYMBOL_STUBS |
754 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
755 16, SectionKind::getText());
756 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
757 MCSymbol *Stub = Stubs[i].first;
758 MCSymbol *RawSym = Stubs[i].second.getPointer();
759 MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
761 OutStreamer.SwitchSection(StubSection);
763 OutStreamer.EmitLabel(Stub);
764 OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
765 // lis r11, ha16(LazyPtr)
766 const MCExpr *LazyPtrHa16 =
767 MCSymbolRefExpr::Create(LazyPtr, MCSymbolRefExpr::VK_PPC_DARWIN_HA16,
769 OutStreamer.EmitInstruction(MCInstBuilder(PPC::LIS)
771 .addExpr(LazyPtrHa16));
773 const MCExpr *LazyPtrLo16 =
774 MCSymbolRefExpr::Create(LazyPtr, MCSymbolRefExpr::VK_PPC_DARWIN_LO16,
776 // ldu r12, lo16(LazyPtr)(r11)
777 // lwzu r12, lo16(LazyPtr)(r11)
778 OutStreamer.EmitInstruction(MCInstBuilder(isPPC64 ? PPC::LDU : PPC::LWZU)
780 .addExpr(LazyPtrLo16).addExpr(LazyPtrLo16)
784 OutStreamer.EmitInstruction(MCInstBuilder(PPC::MTCTR).addReg(PPC::R12));
786 OutStreamer.EmitInstruction(MCInstBuilder(PPC::BCTR));
788 OutStreamer.SwitchSection(LSPSection);
789 OutStreamer.EmitLabel(LazyPtr);
790 OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
792 MCSymbol *DyldStubBindingHelper =
793 OutContext.GetOrCreateSymbol(StringRef("dyld_stub_binding_helper"));
795 // .quad dyld_stub_binding_helper
796 OutStreamer.EmitSymbolValue(DyldStubBindingHelper, 8);
798 // .long dyld_stub_binding_helper
799 OutStreamer.EmitSymbolValue(DyldStubBindingHelper, 4);
803 OutStreamer.AddBlankLine();
807 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
808 bool isPPC64 = TM.getDataLayout()->getPointerSizeInBits() == 64;
810 // Darwin/PPC always uses mach-o.
811 const TargetLoweringObjectFileMachO &TLOFMacho =
812 static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
813 MachineModuleInfoMachO &MMIMacho =
814 MMI->getObjFileInfo<MachineModuleInfoMachO>();
816 MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetFnStubList();
818 EmitFunctionStubs(Stubs);
820 if (MAI->doesSupportExceptionHandling() && MMI) {
821 // Add the (possibly multiple) personalities to the set of global values.
822 // Only referenced functions get into the Personalities list.
823 const std::vector<const Function*> &Personalities = MMI->getPersonalities();
824 for (std::vector<const Function*>::const_iterator I = Personalities.begin(),
825 E = Personalities.end(); I != E; ++I) {
827 MCSymbol *NLPSym = GetSymbolWithGlobalValueBase(*I, "$non_lazy_ptr");
828 MachineModuleInfoImpl::StubValueTy &StubSym =
829 MMIMacho.getGVStubEntry(NLPSym);
830 StubSym = MachineModuleInfoImpl::StubValueTy(Mang->getSymbol(*I), true);
835 // Output stubs for dynamically-linked functions.
836 Stubs = MMIMacho.GetGVStubList();
838 // Output macho stubs for external and common global variables.
839 if (!Stubs.empty()) {
840 // Switch with ".non_lazy_symbol_pointer" directive.
841 OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
842 EmitAlignment(isPPC64 ? 3 : 2);
844 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
846 OutStreamer.EmitLabel(Stubs[i].first);
847 // .indirect_symbol _foo
848 MachineModuleInfoImpl::StubValueTy &MCSym = Stubs[i].second;
849 OutStreamer.EmitSymbolAttribute(MCSym.getPointer(), MCSA_IndirectSymbol);
852 // External to current translation unit.
853 OutStreamer.EmitIntValue(0, isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
855 // Internal to current translation unit.
857 // When we place the LSDA into the TEXT section, the type info pointers
858 // need to be indirect and pc-rel. We accomplish this by using NLPs.
859 // However, sometimes the types are local to the file. So we need to
860 // fill in the value for the NLP in those cases.
861 OutStreamer.EmitValue(MCSymbolRefExpr::Create(MCSym.getPointer(),
863 isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
867 OutStreamer.AddBlankLine();
870 Stubs = MMIMacho.GetHiddenGVStubList();
871 if (!Stubs.empty()) {
872 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
873 EmitAlignment(isPPC64 ? 3 : 2);
875 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
877 OutStreamer.EmitLabel(Stubs[i].first);
879 OutStreamer.EmitValue(MCSymbolRefExpr::
880 Create(Stubs[i].second.getPointer(),
882 isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
886 OutStreamer.AddBlankLine();
889 // Funny Darwin hack: This flag tells the linker that no global symbols
890 // contain code that falls through to other global symbols (e.g. the obvious
891 // implementation of multiple entry points). If this doesn't occur, the
892 // linker can safely perform dead code stripping. Since LLVM never generates
893 // code that does this, it is always safe to set.
894 OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
896 return AsmPrinter::doFinalization(M);
899 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
900 /// for a MachineFunction to the given output stream, in a format that the
901 /// Darwin assembler can deal with.
903 static AsmPrinter *createPPCAsmPrinterPass(TargetMachine &tm,
904 MCStreamer &Streamer) {
905 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
907 if (Subtarget->isDarwin())
908 return new PPCDarwinAsmPrinter(tm, Streamer);
909 return new PPCLinuxAsmPrinter(tm, Streamer);
912 // Force static initialization.
913 extern "C" void LLVMInitializePowerPCAsmPrinter() {
914 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
915 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);