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/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCContext.h"
36 #include "llvm/MC/MCSectionMachO.h"
37 #include "llvm/MC/MCStreamer.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/Target/Mangler.h"
40 #include "llvm/Target/TargetLoweringObjectFile.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetInstrInfo.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include "llvm/Target/TargetRegistry.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/FormattedStream.h"
50 #include "llvm/ADT/Statistic.h"
51 #include "llvm/ADT/StringExtras.h"
52 #include "llvm/ADT/StringSet.h"
53 #include "llvm/ADT/SmallString.h"
56 STATISTIC(EmittedInsts, "Number of machine instrs printed");
59 class PPCAsmPrinter : public AsmPrinter {
61 DenseMap<const MCSymbol*, const MCSymbol*> TOC;
62 const PPCSubtarget &Subtarget;
65 explicit PPCAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
66 const MCAsmInfo *T, bool V)
67 : AsmPrinter(O, TM, T, V),
68 Subtarget(TM.getSubtarget<PPCSubtarget>()), LabelID(0) {}
70 virtual const char *getPassName() const {
71 return "PowerPC Assembly Printer";
74 PPCTargetMachine &getTM() {
75 return static_cast<PPCTargetMachine&>(TM);
78 unsigned enumRegToMachineReg(unsigned enumReg) {
80 default: llvm_unreachable("Unhandled register!");
81 case PPC::CR0: return 0;
82 case PPC::CR1: return 1;
83 case PPC::CR2: return 2;
84 case PPC::CR3: return 3;
85 case PPC::CR4: return 4;
86 case PPC::CR5: return 5;
87 case PPC::CR6: return 6;
88 case PPC::CR7: return 7;
93 /// printInstruction - This method is automatically generated by tablegen
94 /// from the instruction set description. This method returns true if the
95 /// machine instruction was sufficiently described to print it, otherwise it
97 void printInstruction(const MachineInstr *MI);
98 static const char *getRegisterName(unsigned RegNo);
101 void printMachineInstruction(const MachineInstr *MI);
102 void printOp(const MachineOperand &MO);
104 /// stripRegisterPrefix - This method strips the character prefix from a
105 /// register name so that only the number is left. Used by for linux asm.
106 const char *stripRegisterPrefix(const char *RegName) {
107 switch (RegName[0]) {
110 case 'v': return RegName + 1;
111 case 'c': if (RegName[1] == 'r') return RegName + 2;
117 /// printRegister - Print register according to target requirements.
119 void printRegister(const MachineOperand &MO, bool R0AsZero) {
120 unsigned RegNo = MO.getReg();
121 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
123 // If we should use 0 for R0.
124 if (R0AsZero && RegNo == PPC::R0) {
129 const char *RegName = getRegisterName(RegNo);
130 // Linux assembler (Others?) does not take register mnemonics.
131 // FIXME - What about special registers used in mfspr/mtspr?
132 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
136 void printOperand(const MachineInstr *MI, unsigned OpNo) {
137 const MachineOperand &MO = MI->getOperand(OpNo);
139 printRegister(MO, false);
140 } else if (MO.isImm()) {
147 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
148 unsigned AsmVariant, const char *ExtraCode);
149 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
150 unsigned AsmVariant, const char *ExtraCode);
153 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
154 char value = MI->getOperand(OpNo).getImm();
155 value = (value << (32-5)) >> (32-5);
158 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
159 unsigned char value = MI->getOperand(OpNo).getImm();
160 assert(value <= 31 && "Invalid u5imm argument!");
161 O << (unsigned int)value;
163 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) {
169 O << (short)MI->getOperand(OpNo).getImm();
171 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
172 O << (unsigned short)MI->getOperand(OpNo).getImm();
174 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
175 if (MI->getOperand(OpNo).isImm()) {
176 O << (short)(MI->getOperand(OpNo).getImm()*4);
179 printOp(MI->getOperand(OpNo));
180 if (TM.getRelocationModel() == Reloc::PIC_)
181 O << "-\"L" << getFunctionNumber() << "$pb\")";
186 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
187 // Branches can take an immediate operand. This is used by the branch
188 // selection pass to print $+8, an eight byte displacement from the PC.
189 if (MI->getOperand(OpNo).isImm()) {
190 O << "$+" << MI->getOperand(OpNo).getImm()*4;
192 printOp(MI->getOperand(OpNo));
195 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
196 const MachineOperand &MO = MI->getOperand(OpNo);
197 if (TM.getRelocationModel() != Reloc::Static) {
198 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
199 GlobalValue *GV = MO.getGlobal();
200 if (GV->isDeclaration() || GV->isWeakForLinker()) {
201 // Dynamically-resolved functions need a stub for the function.
202 MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$stub");
203 const MCSymbol *&StubSym =
204 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
206 StubSym = GetGlobalValueSymbol(GV);
211 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
212 SmallString<128> TempNameStr;
213 TempNameStr += StringRef(MO.getSymbolName());
214 TempNameStr += StringRef("$stub");
216 const MCSymbol *Sym = GetExternalSymbolSymbol(TempNameStr.str());
217 const MCSymbol *&StubSym =
218 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
220 TempNameStr.erase(TempNameStr.end()-5, TempNameStr.end());
221 StubSym = OutContext.GetOrCreateSymbol(TempNameStr.str());
228 printOp(MI->getOperand(OpNo));
230 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
231 O << (int)MI->getOperand(OpNo).getImm()*4;
233 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
234 O << "\"L" << getFunctionNumber() << "$pb\"\n";
235 O << "\"L" << getFunctionNumber() << "$pb\":";
237 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
238 if (MI->getOperand(OpNo).isImm()) {
239 printS16ImmOperand(MI, OpNo);
241 if (Subtarget.isDarwin()) O << "ha16(";
242 printOp(MI->getOperand(OpNo));
243 if (TM.getRelocationModel() == Reloc::PIC_)
244 O << "-\"L" << getFunctionNumber() << "$pb\"";
245 if (Subtarget.isDarwin())
251 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
252 if (MI->getOperand(OpNo).isImm()) {
253 printS16ImmOperand(MI, OpNo);
255 if (Subtarget.isDarwin()) O << "lo16(";
256 printOp(MI->getOperand(OpNo));
257 if (TM.getRelocationModel() == Reloc::PIC_)
258 O << "-\"L" << getFunctionNumber() << "$pb\"";
259 if (Subtarget.isDarwin())
265 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
266 unsigned CCReg = MI->getOperand(OpNo).getReg();
267 unsigned RegNo = enumRegToMachineReg(CCReg);
268 O << (0x80 >> RegNo);
270 // The new addressing mode printers.
271 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
272 printSymbolLo(MI, OpNo);
274 if (MI->getOperand(OpNo+1).isReg() &&
275 MI->getOperand(OpNo+1).getReg() == PPC::R0)
278 printOperand(MI, OpNo+1);
281 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
282 if (MI->getOperand(OpNo).isImm())
283 printS16X4ImmOperand(MI, OpNo);
285 printSymbolLo(MI, OpNo);
287 if (MI->getOperand(OpNo+1).isReg() &&
288 MI->getOperand(OpNo+1).getReg() == PPC::R0)
291 printOperand(MI, OpNo+1);
295 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
296 // When used as the base register, r0 reads constant zero rather than
297 // the value contained in the register. For this reason, the darwin
298 // assembler requires that we print r0 as 0 (no r) when used as the base.
299 const MachineOperand &MO = MI->getOperand(OpNo);
300 printRegister(MO, true);
302 printOperand(MI, OpNo+1);
305 void printTOCEntryLabel(const MachineInstr *MI, unsigned OpNo) {
306 const MachineOperand &MO = MI->getOperand(OpNo);
308 assert(MO.getType() == MachineOperand::MO_GlobalAddress);
310 const MCSymbol *Sym = GetGlobalValueSymbol(MO.getGlobal());
312 // Map symbol -> label of TOC entry.
313 const MCSymbol *&TOCEntry = TOC[Sym];
315 TOCEntry = OutContext.
316 GetOrCreateSymbol(StringRef(MAI->getPrivateGlobalPrefix()) + "C" +
319 O << *TOCEntry << "@toc";
322 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
323 const char *Modifier);
325 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
328 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
329 class PPCLinuxAsmPrinter : public PPCAsmPrinter {
331 explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
332 const MCAsmInfo *T, bool V)
333 : PPCAsmPrinter(O, TM, T, V){}
335 virtual const char *getPassName() const {
336 return "Linux PPC Assembly Printer";
339 bool runOnMachineFunction(MachineFunction &F);
340 bool doFinalization(Module &M);
342 void getAnalysisUsage(AnalysisUsage &AU) const {
343 AU.setPreservesAll();
344 AU.addRequired<MachineModuleInfo>();
345 AU.addRequired<DwarfWriter>();
346 PPCAsmPrinter::getAnalysisUsage(AU);
350 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
352 class PPCDarwinAsmPrinter : public PPCAsmPrinter {
353 formatted_raw_ostream &OS;
355 explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
356 const MCAsmInfo *T, bool V)
357 : PPCAsmPrinter(O, TM, T, V), OS(O) {}
359 virtual const char *getPassName() const {
360 return "Darwin PPC Assembly Printer";
363 bool runOnMachineFunction(MachineFunction &F);
364 bool doFinalization(Module &M);
365 void EmitStartOfAsmFile(Module &M);
367 void EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs);
369 void getAnalysisUsage(AnalysisUsage &AU) const {
370 AU.setPreservesAll();
371 AU.addRequired<MachineModuleInfo>();
372 AU.addRequired<DwarfWriter>();
373 PPCAsmPrinter::getAnalysisUsage(AU);
376 } // end of anonymous namespace
378 // Include the auto-generated portion of the assembly writer
379 #include "PPCGenAsmWriter.inc"
381 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
382 switch (MO.getType()) {
383 case MachineOperand::MO_Immediate:
384 llvm_unreachable("printOp() does not handle immediate values");
386 case MachineOperand::MO_MachineBasicBlock:
387 O << *GetMBBSymbol(MO.getMBB()->getNumber());
389 case MachineOperand::MO_JumpTableIndex:
390 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
391 << '_' << MO.getIndex();
392 // FIXME: PIC relocation model
394 case MachineOperand::MO_ConstantPoolIndex:
395 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
396 << '_' << MO.getIndex();
398 case MachineOperand::MO_BlockAddress:
399 O << *GetBlockAddressSymbol(MO.getBlockAddress());
401 case MachineOperand::MO_ExternalSymbol: {
402 // Computing the address of an external symbol, not calling it.
403 if (TM.getRelocationModel() == Reloc::Static) {
404 O << *GetExternalSymbolSymbol(MO.getSymbolName());
408 const MCSymbol *NLPSym =
409 OutContext.GetOrCreateSymbol(StringRef(MAI->getGlobalPrefix())+
410 MO.getSymbolName()+"$non_lazy_ptr");
411 const MCSymbol *&StubSym =
412 MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(NLPSym);
414 StubSym = GetExternalSymbolSymbol(MO.getSymbolName());
419 case MachineOperand::MO_GlobalAddress: {
420 // Computing the address of a global symbol, not calling it.
421 GlobalValue *GV = MO.getGlobal();
422 MCSymbol *SymToPrint;
424 // External or weakly linked global variables need non-lazily-resolved stubs
425 if (TM.getRelocationModel() != Reloc::Static &&
426 (GV->isDeclaration() || GV->isWeakForLinker())) {
427 if (!GV->hasHiddenVisibility()) {
428 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
429 const MCSymbol *&StubSym =
430 MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(SymToPrint);
432 StubSym = GetGlobalValueSymbol(GV);
433 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
434 GV->hasAvailableExternallyLinkage()) {
435 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
437 const MCSymbol *&StubSym =
438 MMI->getObjFileInfo<MachineModuleInfoMachO>().
439 getHiddenGVStubEntry(SymToPrint);
441 StubSym = GetGlobalValueSymbol(GV);
443 SymToPrint = GetGlobalValueSymbol(GV);
446 SymToPrint = GetGlobalValueSymbol(GV);
451 printOffset(MO.getOffset());
456 O << "<unknown operand type: " << MO.getType() << ">";
461 /// PrintAsmOperand - Print out an operand for an inline asm expression.
463 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
465 const char *ExtraCode) {
466 // Does this asm operand have a single letter operand modifier?
467 if (ExtraCode && ExtraCode[0]) {
468 if (ExtraCode[1] != 0) return true; // Unknown modifier.
470 switch (ExtraCode[0]) {
471 default: return true; // Unknown modifier.
472 case 'c': // Don't print "$" before a global var name or constant.
473 // PPC never has a prefix.
474 printOperand(MI, OpNo);
476 case 'L': // Write second word of DImode reference.
477 // Verify that this operand has two consecutive registers.
478 if (!MI->getOperand(OpNo).isReg() ||
479 OpNo+1 == MI->getNumOperands() ||
480 !MI->getOperand(OpNo+1).isReg())
482 ++OpNo; // Return the high-part.
485 // Write 'i' if an integer constant, otherwise nothing. Used to print
487 if (MI->getOperand(OpNo).isImm())
493 printOperand(MI, OpNo);
497 // At the moment, all inline asm memory operands are a single register.
498 // In any case, the output of this routine should always be just one
499 // assembler operand.
501 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
503 const char *ExtraCode) {
504 if (ExtraCode && ExtraCode[0])
505 return true; // Unknown modifier.
506 assert (MI->getOperand(OpNo).isReg());
508 printOperand(MI, OpNo);
513 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
514 const char *Modifier) {
515 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
516 unsigned Code = MI->getOperand(OpNo).getImm();
517 if (!strcmp(Modifier, "cc")) {
518 switch ((PPC::Predicate)Code) {
519 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
520 case PPC::PRED_LT: O << "lt"; return;
521 case PPC::PRED_LE: O << "le"; return;
522 case PPC::PRED_EQ: O << "eq"; return;
523 case PPC::PRED_GE: O << "ge"; return;
524 case PPC::PRED_GT: O << "gt"; return;
525 case PPC::PRED_NE: O << "ne"; return;
526 case PPC::PRED_UN: O << "un"; return;
527 case PPC::PRED_NU: O << "nu"; return;
531 assert(!strcmp(Modifier, "reg") &&
532 "Need to specify 'cc' or 'reg' as predicate op modifier!");
533 // Don't print the register for 'always'.
534 if (Code == PPC::PRED_ALWAYS) return;
535 printOperand(MI, OpNo+1);
540 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
541 /// the current output stream.
543 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
546 processDebugLoc(MI, true);
548 // Check for slwi/srwi mnemonics.
549 bool useSubstituteMnemonic = false;
550 if (MI->getOpcode() == PPC::RLWINM) {
551 unsigned char SH = MI->getOperand(2).getImm();
552 unsigned char MB = MI->getOperand(3).getImm();
553 unsigned char ME = MI->getOperand(4).getImm();
554 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
555 O << "\tslwi "; useSubstituteMnemonic = true;
557 if (SH <= 31 && MB == (32-SH) && ME == 31) {
558 O << "\tsrwi "; useSubstituteMnemonic = true;
561 if (useSubstituteMnemonic) {
565 O << ", " << (unsigned int)SH;
567 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
568 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
569 useSubstituteMnemonic = true;
575 } else 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
580 useSubstituteMnemonic = true;
585 O << ", " << (unsigned int)SH;
589 if (!useSubstituteMnemonic)
590 printInstruction(MI);
596 processDebugLoc(MI, false);
599 /// runOnMachineFunction - This uses the printMachineInstruction()
600 /// method to print assembly for each instruction.
602 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
605 SetupMachineFunction(MF);
608 // Print out constants referenced by the function
609 EmitConstantPool(MF.getConstantPool());
611 // Print out labels for the function.
612 const Function *F = MF.getFunction();
613 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
615 switch (F->getLinkage()) {
616 default: llvm_unreachable("Unknown linkage type!");
617 case Function::PrivateLinkage:
618 case Function::InternalLinkage: // Symbols default to internal.
620 case Function::ExternalLinkage:
621 O << "\t.global\t" << *CurrentFnSym << '\n' << "\t.type\t";
622 O << *CurrentFnSym << ", @function\n";
624 case Function::LinkerPrivateLinkage:
625 case Function::WeakAnyLinkage:
626 case Function::WeakODRLinkage:
627 case Function::LinkOnceAnyLinkage:
628 case Function::LinkOnceODRLinkage:
629 O << "\t.global\t" << *CurrentFnSym << '\n';
630 O << "\t.weak\t" << *CurrentFnSym << '\n';
634 printVisibility(CurrentFnSym, F->getVisibility());
636 EmitAlignment(MF.getAlignment(), F);
638 if (Subtarget.isPPC64()) {
639 // Emit an official procedure descriptor.
640 // FIXME 64-bit SVR4: Use MCSection here!
641 O << "\t.section\t\".opd\",\"aw\"\n";
643 O << *CurrentFnSym << ":\n";
644 O << "\t.quad .L." << *CurrentFnSym << ",.TOC.@tocbase\n";
645 O << "\t.previous\n";
646 O << ".L." << *CurrentFnSym << ":\n";
648 O << *CurrentFnSym << ":\n";
651 // Emit pre-function debug information.
652 DW->BeginFunction(&MF);
654 // Print out code for the function.
655 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
657 // Print a label for the basic block.
658 if (I != MF.begin()) {
659 EmitBasicBlockStart(I);
661 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
663 // Print the assembly for the instruction.
664 printMachineInstruction(II);
668 O << "\t.size\t" << *CurrentFnSym << ",.-" << *CurrentFnSym << '\n';
670 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
672 // Emit post-function debug information.
673 DW->EndFunction(&MF);
675 // Print out jump tables referenced by the function.
676 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
678 // We didn't modify anything.
682 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
683 const TargetData *TD = TM.getTargetData();
685 bool isPPC64 = TD->getPointerSizeInBits() == 64;
687 if (isPPC64 && !TOC.empty()) {
688 // FIXME 64-bit SVR4: Use MCSection here?
689 O << "\t.section\t\".toc\",\"aw\"\n";
691 // FIXME: This is nondeterminstic!
692 for (DenseMap<const MCSymbol*, const MCSymbol*>::iterator I = TOC.begin(),
693 E = TOC.end(); I != E; ++I) {
694 O << *I->second << ":\n";
695 O << "\t.tc " << *I->first << "[TC]," << *I->first << '\n';
699 return AsmPrinter::doFinalization(M);
702 /// runOnMachineFunction - This uses the printMachineInstruction()
703 /// method to print assembly for each instruction.
705 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
708 SetupMachineFunction(MF);
711 // Print out constants referenced by the function
712 EmitConstantPool(MF.getConstantPool());
714 // Print out labels for the function.
715 const Function *F = MF.getFunction();
716 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
718 switch (F->getLinkage()) {
719 default: llvm_unreachable("Unknown linkage type!");
720 case Function::PrivateLinkage:
721 case Function::InternalLinkage: // Symbols default to internal.
723 case Function::ExternalLinkage:
724 O << "\t.globl\t" << *CurrentFnSym << '\n';
726 case Function::WeakAnyLinkage:
727 case Function::WeakODRLinkage:
728 case Function::LinkOnceAnyLinkage:
729 case Function::LinkOnceODRLinkage:
730 case Function::LinkerPrivateLinkage:
731 O << "\t.globl\t" << *CurrentFnSym << '\n';
732 O << "\t.weak_definition\t" << *CurrentFnSym << '\n';
736 printVisibility(CurrentFnSym, F->getVisibility());
738 EmitAlignment(MF.getAlignment(), F);
739 O << *CurrentFnSym << ":\n";
741 // Emit pre-function debug information.
742 DW->BeginFunction(&MF);
744 // If the function is empty, then we need to emit *something*. Otherwise, the
745 // function's label might be associated with something that it wasn't meant to
746 // be associated with. We emit a noop in this situation.
747 MachineFunction::iterator I = MF.begin();
749 if (++I == MF.end() && MF.front().empty())
752 // Print out code for the function.
753 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
755 // Print a label for the basic block.
756 if (I != MF.begin()) {
757 EmitBasicBlockStart(I);
759 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
761 // Print the assembly for the instruction.
762 printMachineInstruction(II);
766 // Emit post-function debug information.
767 DW->EndFunction(&MF);
769 // Print out jump tables referenced by the function.
770 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
772 // We didn't modify anything.
777 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
778 static const char *const CPUDirectives[] = {
790 unsigned Directive = Subtarget.getDarwinDirective();
791 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
792 Directive = PPC::DIR_970;
793 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
794 Directive = PPC::DIR_7400;
795 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
796 Directive = PPC::DIR_64;
797 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
798 O << "\t.machine " << CPUDirectives[Directive] << '\n';
800 // Prime text sections so they are adjacent. This reduces the likelihood a
801 // large data or debug section causes a branch to exceed 16M limit.
802 TargetLoweringObjectFileMachO &TLOFMacho =
803 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
804 OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
805 if (TM.getRelocationModel() == Reloc::PIC_) {
806 OutStreamer.SwitchSection(
807 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
808 MCSectionMachO::S_SYMBOL_STUBS |
809 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
810 32, SectionKind::getText()));
811 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
812 OutStreamer.SwitchSection(
813 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
814 MCSectionMachO::S_SYMBOL_STUBS |
815 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
816 16, SectionKind::getText()));
818 OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
821 static const MCSymbol *GetLazyPtr(const MCSymbol *Sym, MCContext &Ctx) {
822 // Remove $stub suffix, add $lazy_ptr.
823 SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end()-5);
824 TmpStr += "$lazy_ptr";
825 return Ctx.GetOrCreateSymbol(TmpStr.str());
828 static const MCSymbol *GetAnonSym(const MCSymbol *Sym, MCContext &Ctx) {
829 // Add $tmp suffix to $stub, yielding $stub$tmp.
830 SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end());
832 return Ctx.GetOrCreateSymbol(TmpStr.str());
835 void PPCDarwinAsmPrinter::
836 EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs) {
837 bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
839 TargetLoweringObjectFileMachO &TLOFMacho =
840 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
842 // .lazy_symbol_pointer
843 const MCSection *LSPSection = TLOFMacho.getLazySymbolPointerSection();
845 // Output stubs for dynamically-linked functions
846 if (TM.getRelocationModel() == Reloc::PIC_) {
847 const MCSection *StubSection =
848 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
849 MCSectionMachO::S_SYMBOL_STUBS |
850 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
851 32, SectionKind::getText());
852 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
853 OutStreamer.SwitchSection(StubSection);
856 const MCSymbol *Stub = Stubs[i].first;
857 const MCSymbol *RawSym = Stubs[i].second;
858 const MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
859 const MCSymbol *AnonSymbol = GetAnonSym(Stub, OutContext);
862 O << "\t.indirect_symbol " << *RawSym << '\n';
864 O << "\tbcl 20,31," << *AnonSymbol << '\n';
865 O << *AnonSymbol << ":\n";
867 O << "\taddis r11,r11,ha16(" << *LazyPtr << '-' << *AnonSymbol
870 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(" << *LazyPtr
871 << '-' << *AnonSymbol << ")(r11)\n";
872 O << "\tmtctr r12\n";
875 OutStreamer.SwitchSection(LSPSection);
876 O << *LazyPtr << ":\n";
877 O << "\t.indirect_symbol " << *RawSym << '\n';
878 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
884 const MCSection *StubSection =
885 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
886 MCSectionMachO::S_SYMBOL_STUBS |
887 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
888 16, SectionKind::getText());
889 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
890 const MCSymbol *Stub = Stubs[i].first;
891 const MCSymbol *RawSym = Stubs[i].second;
892 const MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
894 OutStreamer.SwitchSection(StubSection);
897 O << "\t.indirect_symbol " << *RawSym << '\n';
898 O << "\tlis r11,ha16(" << *LazyPtr << ")\n";
899 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(" << *LazyPtr
901 O << "\tmtctr r12\n";
903 OutStreamer.SwitchSection(LSPSection);
904 O << *LazyPtr << ":\n";
905 O << "\t.indirect_symbol " << *RawSym << '\n';
906 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
913 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
914 bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
916 // Darwin/PPC always uses mach-o.
917 TargetLoweringObjectFileMachO &TLOFMacho =
918 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
919 MachineModuleInfoMachO &MMIMacho =
920 MMI->getObjFileInfo<MachineModuleInfoMachO>();
922 MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetFnStubList();
924 EmitFunctionStubs(Stubs);
926 if (MAI->doesSupportExceptionHandling() && MMI) {
927 // Add the (possibly multiple) personalities to the set of global values.
928 // Only referenced functions get into the Personalities list.
929 const std::vector<Function *> &Personalities = MMI->getPersonalities();
930 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
931 E = Personalities.end(); I != E; ++I) {
933 const MCSymbol *NLPSym =
934 GetSymbolWithGlobalValueBase(*I, "$non_lazy_ptr");
935 const MCSymbol *&StubSym = MMIMacho.getGVStubEntry(NLPSym);
936 StubSym = GetGlobalValueSymbol(*I);
941 // Output stubs for dynamically-linked functions.
942 Stubs = MMIMacho.GetGVStubList();
944 // Output macho stubs for external and common global variables.
945 if (!Stubs.empty()) {
946 // Switch with ".non_lazy_symbol_pointer" directive.
947 OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
948 EmitAlignment(isPPC64 ? 3 : 2);
950 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
951 O << *Stubs[i].first << ":\n";
952 O << "\t.indirect_symbol " << *Stubs[i].second << '\n';
953 O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
957 Stubs = MMIMacho.GetHiddenGVStubList();
958 if (!Stubs.empty()) {
959 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
960 EmitAlignment(isPPC64 ? 3 : 2);
962 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
963 O << *Stubs[i].first << ":\n";
964 O << (isPPC64 ? "\t.quad\t" : "\t.long\t") << *Stubs[i].second << '\n';
968 // Funny Darwin hack: This flag tells the linker that no global symbols
969 // contain code that falls through to other global symbols (e.g. the obvious
970 // implementation of multiple entry points). If this doesn't occur, the
971 // linker can safely perform dead code stripping. Since LLVM never generates
972 // code that does this, it is always safe to set.
973 OutStreamer.EmitAssemblerFlag(MCStreamer::SubsectionsViaSymbols);
975 return AsmPrinter::doFinalization(M);
980 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
981 /// for a MachineFunction to the given output stream, in a format that the
982 /// Darwin assembler can deal with.
984 static AsmPrinter *createPPCAsmPrinterPass(formatted_raw_ostream &o,
986 const MCAsmInfo *tai,
988 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
990 if (Subtarget->isDarwin())
991 return new PPCDarwinAsmPrinter(o, tm, tai, verbose);
992 return new PPCLinuxAsmPrinter(o, tm, tai, verbose);
995 // Force static initialization.
996 extern "C" void LLVMInitializePowerPCAsmPrinter() {
997 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
998 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);