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 "PPCMCInstLower.h"
24 #include "PPCSubtarget.h"
25 #include "llvm/Analysis/DebugInfo.h"
26 #include "llvm/Constants.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/MCSectionMachO.h"
41 #include "llvm/MC/MCStreamer.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/Target/Mangler.h"
44 #include "llvm/Target/TargetRegisterInfo.h"
45 #include "llvm/Target/TargetInstrInfo.h"
46 #include "llvm/Target/TargetOptions.h"
47 #include "llvm/Target/TargetRegistry.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/ADT/StringExtras.h"
54 #include "llvm/ADT/StringSet.h"
55 #include "llvm/ADT/SmallString.h"
56 #include "InstPrinter/PPCInstPrinter.h"
59 // This option tells the asmprinter to use the new (experimental) MCInstPrinter
61 static cl::opt<bool> UseInstPrinter("enable-ppc-inst-printer",
65 class PPCAsmPrinter : public AsmPrinter {
67 DenseMap<MCSymbol*, MCSymbol*> TOC;
68 const PPCSubtarget &Subtarget;
71 explicit PPCAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
72 : AsmPrinter(TM, Streamer),
73 Subtarget(TM.getSubtarget<PPCSubtarget>()), LabelID(0) {}
75 virtual const char *getPassName() const {
76 return "PowerPC Assembly Printer";
79 unsigned enumRegToMachineReg(unsigned enumReg) {
81 default: llvm_unreachable("Unhandled register!");
82 case PPC::CR0: return 0;
83 case PPC::CR1: return 1;
84 case PPC::CR2: return 2;
85 case PPC::CR3: return 3;
86 case PPC::CR4: return 4;
87 case PPC::CR5: return 5;
88 case PPC::CR6: return 6;
89 case PPC::CR7: return 7;
94 /// printInstruction - This method is automatically generated by tablegen
95 /// from the instruction set description. This method returns true if the
96 /// machine instruction was sufficiently described to print it, otherwise it
98 void printInstruction(const MachineInstr *MI, raw_ostream &O);
99 static const char *getRegisterName(unsigned RegNo);
102 virtual void EmitInstruction(const MachineInstr *MI);
103 void printOp(const MachineOperand &MO, raw_ostream &O);
105 /// stripRegisterPrefix - This method strips the character prefix from a
106 /// register name so that only the number is left. Used by for linux asm.
107 const char *stripRegisterPrefix(const char *RegName) {
108 switch (RegName[0]) {
111 case 'v': return RegName + 1;
112 case 'c': if (RegName[1] == 'r') return RegName + 2;
118 /// printRegister - Print register according to target requirements.
120 void printRegister(const MachineOperand &MO, bool R0AsZero, raw_ostream &O){
121 unsigned RegNo = MO.getReg();
122 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
124 // If we should use 0 for R0.
125 if (R0AsZero && RegNo == PPC::R0) {
130 const char *RegName = getRegisterName(RegNo);
131 // Linux assembler (Others?) does not take register mnemonics.
132 // FIXME - What about special registers used in mfspr/mtspr?
133 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
137 void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
138 const MachineOperand &MO = MI->getOperand(OpNo);
140 printRegister(MO, false, O);
141 } else if (MO.isImm()) {
148 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
149 unsigned AsmVariant, const char *ExtraCode,
151 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
152 unsigned AsmVariant, const char *ExtraCode,
156 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo,
158 char value = MI->getOperand(OpNo).getImm();
159 value = (value << (32-5)) >> (32-5);
162 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo,
164 unsigned char value = MI->getOperand(OpNo).getImm();
165 assert(value <= 31 && "Invalid u5imm argument!");
166 O << (unsigned int)value;
168 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo,
170 unsigned char value = MI->getOperand(OpNo).getImm();
171 assert(value <= 63 && "Invalid u6imm argument!");
172 O << (unsigned int)value;
174 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo,
176 O << (short)MI->getOperand(OpNo).getImm();
178 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo,
180 O << (unsigned short)MI->getOperand(OpNo).getImm();
182 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo,
184 if (MI->getOperand(OpNo).isImm()) {
185 O << (short)(MI->getOperand(OpNo).getImm()*4);
188 printOp(MI->getOperand(OpNo), O);
189 if (TM.getRelocationModel() == Reloc::PIC_)
190 O << "-\"L" << getFunctionNumber() << "$pb\")";
195 void printBranchOperand(const MachineInstr *MI, unsigned OpNo,
197 // Branches can take an immediate operand. This is used by the branch
198 // selection pass to print $+8, an eight byte displacement from the PC.
199 if (MI->getOperand(OpNo).isImm()) {
200 O << "$+" << MI->getOperand(OpNo).getImm()*4;
202 printOp(MI->getOperand(OpNo), O);
205 void printCallOperand(const MachineInstr *MI, unsigned OpNo,
207 const MachineOperand &MO = MI->getOperand(OpNo);
208 if (TM.getRelocationModel() != Reloc::Static) {
210 const GlobalValue *GV = MO.getGlobal();
211 if (GV->isDeclaration() || GV->isWeakForLinker()) {
212 // Dynamically-resolved functions need a stub for the function.
213 MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$stub");
214 MachineModuleInfoImpl::StubValueTy &StubSym =
215 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
216 if (StubSym.getPointer() == 0)
217 StubSym = MachineModuleInfoImpl::
218 StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
224 SmallString<128> TempNameStr;
225 TempNameStr += StringRef(MO.getSymbolName());
226 TempNameStr += StringRef("$stub");
228 MCSymbol *Sym = GetExternalSymbolSymbol(TempNameStr.str());
229 MachineModuleInfoImpl::StubValueTy &StubSym =
230 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
231 if (StubSym.getPointer() == 0)
232 StubSym = MachineModuleInfoImpl::
233 StubValueTy(GetExternalSymbolSymbol(MO.getSymbolName()), true);
239 printOp(MI->getOperand(OpNo), O);
241 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo,
243 O << (int)MI->getOperand(OpNo).getImm()*4;
245 void printPICLabel(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
246 O << "\"L" << getFunctionNumber() << "$pb\"\n";
247 O << "\"L" << getFunctionNumber() << "$pb\":";
249 void printSymbolHi(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
250 if (MI->getOperand(OpNo).isImm()) {
251 printS16ImmOperand(MI, OpNo, O);
253 if (Subtarget.isDarwin()) O << "ha16(";
254 printOp(MI->getOperand(OpNo), O);
255 if (TM.getRelocationModel() == Reloc::PIC_)
256 O << "-\"L" << getFunctionNumber() << "$pb\"";
257 if (Subtarget.isDarwin())
263 void printSymbolLo(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
264 if (MI->getOperand(OpNo).isImm()) {
265 printS16ImmOperand(MI, OpNo, O);
267 if (Subtarget.isDarwin()) O << "lo16(";
268 printOp(MI->getOperand(OpNo), O);
269 if (TM.getRelocationModel() == Reloc::PIC_)
270 O << "-\"L" << getFunctionNumber() << "$pb\"";
271 if (Subtarget.isDarwin())
277 void printcrbitm(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
278 unsigned CCReg = MI->getOperand(OpNo).getReg();
279 unsigned RegNo = enumRegToMachineReg(CCReg);
280 O << (0x80 >> RegNo);
282 // The new addressing mode printers.
283 void printMemRegImm(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
284 printSymbolLo(MI, OpNo, O);
286 if (MI->getOperand(OpNo+1).isReg() &&
287 MI->getOperand(OpNo+1).getReg() == PPC::R0)
290 printOperand(MI, OpNo+1, O);
293 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo,
295 if (MI->getOperand(OpNo).isImm())
296 printS16X4ImmOperand(MI, OpNo, O);
298 printSymbolLo(MI, OpNo, O);
300 if (MI->getOperand(OpNo+1).isReg() &&
301 MI->getOperand(OpNo+1).getReg() == PPC::R0)
304 printOperand(MI, OpNo+1, O);
308 void printMemRegReg(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
309 // When used as the base register, r0 reads constant zero rather than
310 // the value contained in the register. For this reason, the darwin
311 // assembler requires that we print r0 as 0 (no r) when used as the base.
312 const MachineOperand &MO = MI->getOperand(OpNo);
313 printRegister(MO, true, O);
315 printOperand(MI, OpNo+1, O);
318 void printTOCEntryLabel(const MachineInstr *MI, unsigned OpNo,
320 const MachineOperand &MO = MI->getOperand(OpNo);
321 assert(MO.isGlobal());
322 MCSymbol *Sym = Mang->getSymbol(MO.getGlobal());
324 // Map symbol -> label of TOC entry.
325 MCSymbol *&TOCEntry = TOC[Sym];
327 TOCEntry = OutContext.
328 GetOrCreateSymbol(StringRef(MAI->getPrivateGlobalPrefix()) +
329 "C" + Twine(LabelID++));
331 O << *TOCEntry << "@toc";
334 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
335 raw_ostream &O, const char *Modifier);
337 MachineLocation getDebugValueLocation(const MachineInstr *MI) const {
339 MachineLocation Location;
340 assert (MI->getNumOperands() == 4 && "Invalid no. of machine operands!");
341 // Frame address. Currently handles register +- offset only.
342 if (MI->getOperand(0).isReg() && MI->getOperand(2).isImm())
343 Location.set(MI->getOperand(0).getReg(), MI->getOperand(2).getImm());
345 DEBUG(dbgs() << "DBG_VALUE instruction ignored! " << *MI << "\n");
351 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
352 class PPCLinuxAsmPrinter : public PPCAsmPrinter {
354 explicit PPCLinuxAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
355 : PPCAsmPrinter(TM, Streamer) {}
357 virtual const char *getPassName() const {
358 return "Linux PPC Assembly Printer";
361 bool doFinalization(Module &M);
363 virtual void EmitFunctionEntryLabel();
366 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
368 class PPCDarwinAsmPrinter : public PPCAsmPrinter {
370 explicit PPCDarwinAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
371 : PPCAsmPrinter(TM, Streamer) {}
373 virtual const char *getPassName() const {
374 return "Darwin PPC Assembly Printer";
377 bool doFinalization(Module &M);
378 void EmitStartOfAsmFile(Module &M);
380 void EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs);
382 } // end of anonymous namespace
384 // Include the auto-generated portion of the assembly writer
385 #include "PPCGenAsmWriter.inc"
387 void PPCAsmPrinter::printOp(const MachineOperand &MO, raw_ostream &O) {
388 switch (MO.getType()) {
389 case MachineOperand::MO_Immediate:
390 llvm_unreachable("printOp() does not handle immediate values");
392 case MachineOperand::MO_MachineBasicBlock:
393 O << *MO.getMBB()->getSymbol();
395 case MachineOperand::MO_JumpTableIndex:
396 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
397 << '_' << MO.getIndex();
398 // FIXME: PIC relocation model
400 case MachineOperand::MO_ConstantPoolIndex:
401 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
402 << '_' << MO.getIndex();
404 case MachineOperand::MO_BlockAddress:
405 O << *GetBlockAddressSymbol(MO.getBlockAddress());
407 case MachineOperand::MO_ExternalSymbol: {
408 // Computing the address of an external symbol, not calling it.
409 if (TM.getRelocationModel() == Reloc::Static) {
410 O << *GetExternalSymbolSymbol(MO.getSymbolName());
415 OutContext.GetOrCreateSymbol(StringRef(MAI->getGlobalPrefix())+
416 MO.getSymbolName()+"$non_lazy_ptr");
417 MachineModuleInfoImpl::StubValueTy &StubSym =
418 MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(NLPSym);
419 if (StubSym.getPointer() == 0)
420 StubSym = MachineModuleInfoImpl::
421 StubValueTy(GetExternalSymbolSymbol(MO.getSymbolName()), true);
426 case MachineOperand::MO_GlobalAddress: {
427 // Computing the address of a global symbol, not calling it.
428 const GlobalValue *GV = MO.getGlobal();
429 MCSymbol *SymToPrint;
431 // External or weakly linked global variables need non-lazily-resolved stubs
432 if (TM.getRelocationModel() != Reloc::Static &&
433 (GV->isDeclaration() || GV->isWeakForLinker())) {
434 if (!GV->hasHiddenVisibility()) {
435 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
436 MachineModuleInfoImpl::StubValueTy &StubSym =
437 MMI->getObjFileInfo<MachineModuleInfoMachO>()
438 .getGVStubEntry(SymToPrint);
439 if (StubSym.getPointer() == 0)
440 StubSym = MachineModuleInfoImpl::
441 StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
442 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
443 GV->hasAvailableExternallyLinkage()) {
444 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
446 MachineModuleInfoImpl::StubValueTy &StubSym =
447 MMI->getObjFileInfo<MachineModuleInfoMachO>().
448 getHiddenGVStubEntry(SymToPrint);
449 if (StubSym.getPointer() == 0)
450 StubSym = MachineModuleInfoImpl::
451 StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
453 SymToPrint = Mang->getSymbol(GV);
456 SymToPrint = Mang->getSymbol(GV);
461 printOffset(MO.getOffset(), O);
466 O << "<unknown operand type: " << MO.getType() << ">";
471 /// PrintAsmOperand - Print out an operand for an inline asm expression.
473 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
475 const char *ExtraCode, raw_ostream &O) {
476 // Does this asm operand have a single letter operand modifier?
477 if (ExtraCode && ExtraCode[0]) {
478 if (ExtraCode[1] != 0) return true; // Unknown modifier.
480 switch (ExtraCode[0]) {
481 default: return true; // Unknown modifier.
482 case 'c': // Don't print "$" before a global var name or constant.
483 // PPC never has a prefix.
484 printOperand(MI, OpNo, O);
486 case 'L': // Write second word of DImode reference.
487 // Verify that this operand has two consecutive registers.
488 if (!MI->getOperand(OpNo).isReg() ||
489 OpNo+1 == MI->getNumOperands() ||
490 !MI->getOperand(OpNo+1).isReg())
492 ++OpNo; // Return the high-part.
495 // Write 'i' if an integer constant, otherwise nothing. Used to print
497 if (MI->getOperand(OpNo).isImm())
503 printOperand(MI, OpNo, O);
507 // At the moment, all inline asm memory operands are a single register.
508 // In any case, the output of this routine should always be just one
509 // assembler operand.
511 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
513 const char *ExtraCode,
515 if (ExtraCode && ExtraCode[0])
516 return true; // Unknown modifier.
517 assert (MI->getOperand(OpNo).isReg());
519 printOperand(MI, OpNo, O);
524 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
525 raw_ostream &O, const char *Modifier){
526 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
527 unsigned Code = MI->getOperand(OpNo).getImm();
528 if (!strcmp(Modifier, "cc")) {
529 switch ((PPC::Predicate)Code) {
530 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
531 case PPC::PRED_LT: O << "lt"; return;
532 case PPC::PRED_LE: O << "le"; return;
533 case PPC::PRED_EQ: O << "eq"; return;
534 case PPC::PRED_GE: O << "ge"; return;
535 case PPC::PRED_GT: O << "gt"; return;
536 case PPC::PRED_NE: O << "ne"; return;
537 case PPC::PRED_UN: O << "un"; return;
538 case PPC::PRED_NU: O << "nu"; return;
542 assert(!strcmp(Modifier, "reg") &&
543 "Need to specify 'cc' or 'reg' as predicate op modifier!");
544 // Don't print the register for 'always'.
545 if (Code == PPC::PRED_ALWAYS) return;
546 printOperand(MI, OpNo+1, O);
551 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
552 /// the current output stream.
554 void PPCAsmPrinter::EmitInstruction(const MachineInstr *MI) {
555 if (UseInstPrinter) {
556 PPCMCInstLower MCInstLowering(OutContext, *Mang, *this);
558 // Lower multi-instruction pseudo operations.
559 switch (MI->getOpcode()) {
561 // TODO: implement me.
565 MCInstLowering.Lower(MI, TmpInst);
566 OutStreamer.EmitInstruction(TmpInst);
571 SmallString<128> Str;
572 raw_svector_ostream O(Str);
574 if (MI->getOpcode() == TargetOpcode::DBG_VALUE) {
575 unsigned NOps = MI->getNumOperands();
577 O << '\t' << MAI->getCommentString() << "DEBUG_VALUE: ";
578 // cast away const; DIetc do not take const operands for some reason.
579 DIVariable V(const_cast<MDNode *>(MI->getOperand(NOps-1).getMetadata()));
582 // Frame address. Currently handles register +- offset only.
583 assert(MI->getOperand(0).isReg() && MI->getOperand(1).isImm());
584 O << '['; printOperand(MI, 0, O); O << '+'; printOperand(MI, 1, O);
587 printOperand(MI, NOps-2, O);
588 OutStreamer.EmitRawText(O.str());
591 // Check for slwi/srwi mnemonics.
592 if (MI->getOpcode() == PPC::RLWINM) {
593 unsigned char SH = MI->getOperand(2).getImm();
594 unsigned char MB = MI->getOperand(3).getImm();
595 unsigned char ME = MI->getOperand(4).getImm();
596 bool useSubstituteMnemonic = false;
597 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
598 O << "\tslwi "; useSubstituteMnemonic = true;
600 if (SH <= 31 && MB == (32-SH) && ME == 31) {
601 O << "\tsrwi "; useSubstituteMnemonic = true;
604 if (useSubstituteMnemonic) {
605 printOperand(MI, 0, O);
607 printOperand(MI, 1, O);
608 O << ", " << (unsigned int)SH;
609 OutStreamer.EmitRawText(O.str());
614 if ((MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) &&
615 MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
617 printOperand(MI, 0, O);
619 printOperand(MI, 1, O);
620 OutStreamer.EmitRawText(O.str());
624 if (MI->getOpcode() == PPC::RLDICR) {
625 unsigned char SH = MI->getOperand(2).getImm();
626 unsigned char ME = MI->getOperand(3).getImm();
627 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
630 printOperand(MI, 0, O);
632 printOperand(MI, 1, O);
633 O << ", " << (unsigned int)SH;
634 OutStreamer.EmitRawText(O.str());
639 printInstruction(MI, O);
640 OutStreamer.EmitRawText(O.str());
643 void PPCLinuxAsmPrinter::EmitFunctionEntryLabel() {
644 if (!Subtarget.isPPC64()) // linux/ppc32 - Normal entry label.
645 return AsmPrinter::EmitFunctionEntryLabel();
647 // Emit an official procedure descriptor.
648 // FIXME 64-bit SVR4: Use MCSection here!
649 OutStreamer.EmitRawText(StringRef("\t.section\t\".opd\",\"aw\""));
650 OutStreamer.EmitRawText(StringRef("\t.align 3"));
651 OutStreamer.EmitLabel(CurrentFnSym);
652 OutStreamer.EmitRawText("\t.quad .L." + Twine(CurrentFnSym->getName()) +
654 OutStreamer.EmitRawText(StringRef("\t.previous"));
655 OutStreamer.EmitRawText(".L." + Twine(CurrentFnSym->getName()) + ":");
659 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
660 const TargetData *TD = TM.getTargetData();
662 bool isPPC64 = TD->getPointerSizeInBits() == 64;
664 if (isPPC64 && !TOC.empty()) {
665 // FIXME 64-bit SVR4: Use MCSection here?
666 OutStreamer.EmitRawText(StringRef("\t.section\t\".toc\",\"aw\""));
668 // FIXME: This is nondeterminstic!
669 for (DenseMap<MCSymbol*, MCSymbol*>::iterator I = TOC.begin(),
670 E = TOC.end(); I != E; ++I) {
671 OutStreamer.EmitLabel(I->second);
672 OutStreamer.EmitRawText("\t.tc " + Twine(I->first->getName()) +
673 "[TC]," + I->first->getName());
677 return AsmPrinter::doFinalization(M);
680 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
681 static const char *const CPUDirectives[] = {
693 unsigned Directive = Subtarget.getDarwinDirective();
694 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
695 Directive = PPC::DIR_970;
696 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
697 Directive = PPC::DIR_7400;
698 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
699 Directive = PPC::DIR_64;
700 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
701 OutStreamer.EmitRawText("\t.machine " + Twine(CPUDirectives[Directive]));
703 // Prime text sections so they are adjacent. This reduces the likelihood a
704 // large data or debug section causes a branch to exceed 16M limit.
705 const TargetLoweringObjectFileMachO &TLOFMacho =
706 static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
707 OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
708 if (TM.getRelocationModel() == Reloc::PIC_) {
709 OutStreamer.SwitchSection(
710 OutContext.getMachOSection("__TEXT", "__picsymbolstub1",
711 MCSectionMachO::S_SYMBOL_STUBS |
712 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
713 32, SectionKind::getText()));
714 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
715 OutStreamer.SwitchSection(
716 OutContext.getMachOSection("__TEXT","__symbol_stub1",
717 MCSectionMachO::S_SYMBOL_STUBS |
718 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
719 16, SectionKind::getText()));
721 OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
724 static MCSymbol *GetLazyPtr(MCSymbol *Sym, MCContext &Ctx) {
725 // Remove $stub suffix, add $lazy_ptr.
726 SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end()-5);
727 TmpStr += "$lazy_ptr";
728 return Ctx.GetOrCreateSymbol(TmpStr.str());
731 static MCSymbol *GetAnonSym(MCSymbol *Sym, MCContext &Ctx) {
732 // Add $tmp suffix to $stub, yielding $stub$tmp.
733 SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end());
735 return Ctx.GetOrCreateSymbol(TmpStr.str());
738 void PPCDarwinAsmPrinter::
739 EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs) {
740 bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
742 const TargetLoweringObjectFileMachO &TLOFMacho =
743 static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
745 // .lazy_symbol_pointer
746 const MCSection *LSPSection = TLOFMacho.getLazySymbolPointerSection();
748 // Output stubs for dynamically-linked functions
749 if (TM.getRelocationModel() == Reloc::PIC_) {
750 const MCSection *StubSection =
751 OutContext.getMachOSection("__TEXT", "__picsymbolstub1",
752 MCSectionMachO::S_SYMBOL_STUBS |
753 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
754 32, SectionKind::getText());
755 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
756 OutStreamer.SwitchSection(StubSection);
759 MCSymbol *Stub = Stubs[i].first;
760 MCSymbol *RawSym = Stubs[i].second.getPointer();
761 MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
762 MCSymbol *AnonSymbol = GetAnonSym(Stub, OutContext);
764 OutStreamer.EmitLabel(Stub);
765 OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
766 // FIXME: MCize this.
767 OutStreamer.EmitRawText(StringRef("\tmflr r0"));
768 OutStreamer.EmitRawText("\tbcl 20,31," + Twine(AnonSymbol->getName()));
769 OutStreamer.EmitLabel(AnonSymbol);
770 OutStreamer.EmitRawText(StringRef("\tmflr r11"));
771 OutStreamer.EmitRawText("\taddis r11,r11,ha16("+Twine(LazyPtr->getName())+
772 "-" + AnonSymbol->getName() + ")");
773 OutStreamer.EmitRawText(StringRef("\tmtlr r0"));
776 OutStreamer.EmitRawText("\tldu r12,lo16(" + Twine(LazyPtr->getName()) +
777 "-" + AnonSymbol->getName() + ")(r11)");
779 OutStreamer.EmitRawText("\tlwzu r12,lo16(" + Twine(LazyPtr->getName()) +
780 "-" + AnonSymbol->getName() + ")(r11)");
781 OutStreamer.EmitRawText(StringRef("\tmtctr r12"));
782 OutStreamer.EmitRawText(StringRef("\tbctr"));
784 OutStreamer.SwitchSection(LSPSection);
785 OutStreamer.EmitLabel(LazyPtr);
786 OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
789 OutStreamer.EmitRawText(StringRef("\t.quad dyld_stub_binding_helper"));
791 OutStreamer.EmitRawText(StringRef("\t.long dyld_stub_binding_helper"));
793 OutStreamer.AddBlankLine();
797 const MCSection *StubSection =
798 OutContext.getMachOSection("__TEXT","__symbol_stub1",
799 MCSectionMachO::S_SYMBOL_STUBS |
800 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
801 16, SectionKind::getText());
802 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
803 MCSymbol *Stub = Stubs[i].first;
804 MCSymbol *RawSym = Stubs[i].second.getPointer();
805 MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
807 OutStreamer.SwitchSection(StubSection);
809 OutStreamer.EmitLabel(Stub);
810 OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
811 OutStreamer.EmitRawText("\tlis r11,ha16(" + Twine(LazyPtr->getName()) +")");
813 OutStreamer.EmitRawText("\tldu r12,lo16(" + Twine(LazyPtr->getName()) +
816 OutStreamer.EmitRawText("\tlwzu r12,lo16(" + Twine(LazyPtr->getName()) +
818 OutStreamer.EmitRawText(StringRef("\tmtctr r12"));
819 OutStreamer.EmitRawText(StringRef("\tbctr"));
820 OutStreamer.SwitchSection(LSPSection);
821 OutStreamer.EmitLabel(LazyPtr);
822 OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
825 OutStreamer.EmitRawText(StringRef("\t.quad dyld_stub_binding_helper"));
827 OutStreamer.EmitRawText(StringRef("\t.long dyld_stub_binding_helper"));
830 OutStreamer.AddBlankLine();
834 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
835 bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
837 // Darwin/PPC always uses mach-o.
838 const TargetLoweringObjectFileMachO &TLOFMacho =
839 static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
840 MachineModuleInfoMachO &MMIMacho =
841 MMI->getObjFileInfo<MachineModuleInfoMachO>();
843 MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetFnStubList();
845 EmitFunctionStubs(Stubs);
847 if (MAI->doesSupportExceptionHandling() && MMI) {
848 // Add the (possibly multiple) personalities to the set of global values.
849 // Only referenced functions get into the Personalities list.
850 const std::vector<const Function*> &Personalities = MMI->getPersonalities();
851 for (std::vector<const Function*>::const_iterator I = Personalities.begin(),
852 E = Personalities.end(); I != E; ++I) {
854 MCSymbol *NLPSym = GetSymbolWithGlobalValueBase(*I, "$non_lazy_ptr");
855 MachineModuleInfoImpl::StubValueTy &StubSym =
856 MMIMacho.getGVStubEntry(NLPSym);
857 StubSym = MachineModuleInfoImpl::StubValueTy(Mang->getSymbol(*I), true);
862 // Output stubs for dynamically-linked functions.
863 Stubs = MMIMacho.GetGVStubList();
865 // Output macho stubs for external and common global variables.
866 if (!Stubs.empty()) {
867 // Switch with ".non_lazy_symbol_pointer" directive.
868 OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
869 EmitAlignment(isPPC64 ? 3 : 2);
871 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
873 OutStreamer.EmitLabel(Stubs[i].first);
874 // .indirect_symbol _foo
875 MachineModuleInfoImpl::StubValueTy &MCSym = Stubs[i].second;
876 OutStreamer.EmitSymbolAttribute(MCSym.getPointer(), MCSA_IndirectSymbol);
879 // External to current translation unit.
880 OutStreamer.EmitIntValue(0, isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
882 // Internal to current translation unit.
884 // When we place the LSDA into the TEXT section, the type info pointers
885 // need to be indirect and pc-rel. We accomplish this by using NLPs.
886 // However, sometimes the types are local to the file. So we need to
887 // fill in the value for the NLP in those cases.
888 OutStreamer.EmitValue(MCSymbolRefExpr::Create(MCSym.getPointer(),
890 isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
894 OutStreamer.AddBlankLine();
897 Stubs = MMIMacho.GetHiddenGVStubList();
898 if (!Stubs.empty()) {
899 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
900 EmitAlignment(isPPC64 ? 3 : 2);
902 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
904 OutStreamer.EmitLabel(Stubs[i].first);
906 OutStreamer.EmitValue(MCSymbolRefExpr::
907 Create(Stubs[i].second.getPointer(),
909 isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
913 OutStreamer.AddBlankLine();
916 // Funny Darwin hack: This flag tells the linker that no global symbols
917 // contain code that falls through to other global symbols (e.g. the obvious
918 // implementation of multiple entry points). If this doesn't occur, the
919 // linker can safely perform dead code stripping. Since LLVM never generates
920 // code that does this, it is always safe to set.
921 OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
923 return AsmPrinter::doFinalization(M);
926 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
927 /// for a MachineFunction to the given output stream, in a format that the
928 /// Darwin assembler can deal with.
930 static AsmPrinter *createPPCAsmPrinterPass(TargetMachine &tm,
931 MCStreamer &Streamer) {
932 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
934 if (Subtarget->isDarwin())
935 return new PPCDarwinAsmPrinter(tm, Streamer);
936 return new PPCLinuxAsmPrinter(tm, Streamer);
939 static MCInstPrinter *createPPCMCInstPrinter(const Target &T,
940 unsigned SyntaxVariant,
941 const MCAsmInfo &MAI) {
942 if (SyntaxVariant == 0)
943 return new PPCInstPrinter(MAI);
948 // Force static initialization.
949 extern "C" void LLVMInitializePowerPCAsmPrinter() {
950 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
951 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);
953 TargetRegistry::RegisterMCInstPrinter(ThePPC32Target, createPPCMCInstPrinter);
954 TargetRegistry::RegisterMCInstPrinter(ThePPC32Target, createPPCMCInstPrinter);