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/MachineModuleInfo.h"
31 #include "llvm/CodeGen/MachineFunctionPass.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.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/TargetLoweringObjectFile.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetOptions.h"
43 #include "llvm/Target/TargetRegistry.h"
44 #include "llvm/Support/Mangler.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 {
62 std::string StubName, LazyPtrName, AnonSymbolName;
63 MCSymbol *StubSym, *LazyPtrSym, *AnonSymbolSym;
66 StubSym = LazyPtrSym = AnonSymbolSym = 0;
69 void Init(const GlobalValue *GV, Mangler *Mang) {
70 // Already initialized.
71 if (!StubName.empty()) return;
72 StubName = Mang->getMangledName(GV, "$stub", true);
73 LazyPtrName = Mang->getMangledName(GV, "$lazy_ptr", true);
74 AnonSymbolName = Mang->getMangledName(GV, "$stub$tmp", true);
77 void Init(StringRef GVName, Mangler *Mang, MCContext &Ctx) {
78 assert(!GVName.empty());
79 if (StubSym != 0) return; // Already initialized.
80 // Get the names for the external symbol name.
81 SmallString<128> TmpStr;
82 Mang->getNameWithPrefix(TmpStr, GVName + "$stub", Mangler::Private);
83 StubSym = Ctx.GetOrCreateSymbol(TmpStr.str());
86 Mang->getNameWithPrefix(TmpStr, GVName + "$lazy_ptr", Mangler::Private);
87 LazyPtrSym = Ctx.GetOrCreateSymbol(TmpStr.str());
90 Mang->getNameWithPrefix(TmpStr, GVName + "$stub$tmp", Mangler::Private);
91 AnonSymbolSym = Ctx.GetOrCreateSymbol(TmpStr.str());
94 void printStub(raw_ostream &OS, const MCAsmInfo *MAI) const {
96 StubSym->print(OS, MAI);
100 void printLazyPtr(raw_ostream &OS, const MCAsmInfo *MAI) const {
102 LazyPtrSym->print(OS, MAI);
106 void printAnonSymbol(raw_ostream &OS, const MCAsmInfo *MAI) const {
108 AnonSymbolSym->print(OS, MAI);
110 OS << AnonSymbolName;
114 StringMap<FnStubInfo> FnStubs;
115 StringMap<std::string> GVStubs, HiddenGVStubs, TOC;
116 const PPCSubtarget &Subtarget;
119 explicit PPCAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
120 const MCAsmInfo *T, bool V)
121 : AsmPrinter(O, TM, T, V),
122 Subtarget(TM.getSubtarget<PPCSubtarget>()), LabelID(0) {}
124 virtual const char *getPassName() const {
125 return "PowerPC Assembly Printer";
128 PPCTargetMachine &getTM() {
129 return static_cast<PPCTargetMachine&>(TM);
132 unsigned enumRegToMachineReg(unsigned enumReg) {
134 default: llvm_unreachable("Unhandled register!");
135 case PPC::CR0: return 0;
136 case PPC::CR1: return 1;
137 case PPC::CR2: return 2;
138 case PPC::CR3: return 3;
139 case PPC::CR4: return 4;
140 case PPC::CR5: return 5;
141 case PPC::CR6: return 6;
142 case PPC::CR7: return 7;
147 /// printInstruction - This method is automatically generated by tablegen
148 /// from the instruction set description. This method returns true if the
149 /// machine instruction was sufficiently described to print it, otherwise it
151 void printInstruction(const MachineInstr *MI);
152 static const char *getRegisterName(unsigned RegNo);
155 void printMachineInstruction(const MachineInstr *MI);
156 void printOp(const MachineOperand &MO);
158 /// stripRegisterPrefix - This method strips the character prefix from a
159 /// register name so that only the number is left. Used by for linux asm.
160 const char *stripRegisterPrefix(const char *RegName) {
161 switch (RegName[0]) {
164 case 'v': return RegName + 1;
165 case 'c': if (RegName[1] == 'r') return RegName + 2;
171 /// printRegister - Print register according to target requirements.
173 void printRegister(const MachineOperand &MO, bool R0AsZero) {
174 unsigned RegNo = MO.getReg();
175 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
177 // If we should use 0 for R0.
178 if (R0AsZero && RegNo == PPC::R0) {
183 const char *RegName = getRegisterName(RegNo);
184 // Linux assembler (Others?) does not take register mnemonics.
185 // FIXME - What about special registers used in mfspr/mtspr?
186 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
190 void printOperand(const MachineInstr *MI, unsigned OpNo) {
191 const MachineOperand &MO = MI->getOperand(OpNo);
193 printRegister(MO, false);
194 } else if (MO.isImm()) {
201 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
202 unsigned AsmVariant, const char *ExtraCode);
203 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
204 unsigned AsmVariant, const char *ExtraCode);
207 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
208 char value = MI->getOperand(OpNo).getImm();
209 value = (value << (32-5)) >> (32-5);
212 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
213 unsigned char value = MI->getOperand(OpNo).getImm();
214 assert(value <= 31 && "Invalid u5imm argument!");
215 O << (unsigned int)value;
217 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
218 unsigned char value = MI->getOperand(OpNo).getImm();
219 assert(value <= 63 && "Invalid u6imm argument!");
220 O << (unsigned int)value;
222 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
223 O << (short)MI->getOperand(OpNo).getImm();
225 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
226 O << (unsigned short)MI->getOperand(OpNo).getImm();
228 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
229 if (MI->getOperand(OpNo).isImm()) {
230 O << (short)(MI->getOperand(OpNo).getImm()*4);
233 printOp(MI->getOperand(OpNo));
234 if (TM.getRelocationModel() == Reloc::PIC_)
235 O << "-\"L" << getFunctionNumber() << "$pb\")";
240 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
241 // Branches can take an immediate operand. This is used by the branch
242 // selection pass to print $+8, an eight byte displacement from the PC.
243 if (MI->getOperand(OpNo).isImm()) {
244 O << "$+" << MI->getOperand(OpNo).getImm()*4;
246 printOp(MI->getOperand(OpNo));
249 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
250 const MachineOperand &MO = MI->getOperand(OpNo);
251 if (TM.getRelocationModel() != Reloc::Static) {
252 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
253 GlobalValue *GV = MO.getGlobal();
254 if (GV->isDeclaration() || GV->isWeakForLinker()) {
255 // Dynamically-resolved functions need a stub for the function.
256 FnStubInfo &FnInfo = FnStubs[Mang->getMangledName(GV)];
257 FnInfo.Init(GV, Mang);
258 FnInfo.printStub(O, MAI);
262 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
263 SmallString<128> MangledName;
264 Mang->getNameWithPrefix(MangledName, MO.getSymbolName());
265 FnStubInfo &FnInfo = FnStubs[MangledName.str()];
266 FnInfo.Init(MO.getSymbolName(), Mang, OutContext);
267 FnInfo.printStub(O, MAI);
272 printOp(MI->getOperand(OpNo));
274 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
275 O << (int)MI->getOperand(OpNo).getImm()*4;
277 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
278 O << "\"L" << getFunctionNumber() << "$pb\"\n";
279 O << "\"L" << getFunctionNumber() << "$pb\":";
281 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
282 if (MI->getOperand(OpNo).isImm()) {
283 printS16ImmOperand(MI, OpNo);
285 if (Subtarget.isDarwin()) O << "ha16(";
286 printOp(MI->getOperand(OpNo));
287 if (TM.getRelocationModel() == Reloc::PIC_)
288 O << "-\"L" << getFunctionNumber() << "$pb\"";
289 if (Subtarget.isDarwin())
295 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
296 if (MI->getOperand(OpNo).isImm()) {
297 printS16ImmOperand(MI, OpNo);
299 if (Subtarget.isDarwin()) O << "lo16(";
300 printOp(MI->getOperand(OpNo));
301 if (TM.getRelocationModel() == Reloc::PIC_)
302 O << "-\"L" << getFunctionNumber() << "$pb\"";
303 if (Subtarget.isDarwin())
309 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
310 unsigned CCReg = MI->getOperand(OpNo).getReg();
311 unsigned RegNo = enumRegToMachineReg(CCReg);
312 O << (0x80 >> RegNo);
314 // The new addressing mode printers.
315 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
316 printSymbolLo(MI, OpNo);
318 if (MI->getOperand(OpNo+1).isReg() &&
319 MI->getOperand(OpNo+1).getReg() == PPC::R0)
322 printOperand(MI, OpNo+1);
325 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
326 if (MI->getOperand(OpNo).isImm())
327 printS16X4ImmOperand(MI, OpNo);
329 printSymbolLo(MI, OpNo);
331 if (MI->getOperand(OpNo+1).isReg() &&
332 MI->getOperand(OpNo+1).getReg() == PPC::R0)
335 printOperand(MI, OpNo+1);
339 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
340 // When used as the base register, r0 reads constant zero rather than
341 // the value contained in the register. For this reason, the darwin
342 // assembler requires that we print r0 as 0 (no r) when used as the base.
343 const MachineOperand &MO = MI->getOperand(OpNo);
344 printRegister(MO, true);
346 printOperand(MI, OpNo+1);
349 void printTOCEntryLabel(const MachineInstr *MI, unsigned OpNo) {
350 const MachineOperand &MO = MI->getOperand(OpNo);
352 assert(MO.getType() == MachineOperand::MO_GlobalAddress);
354 GlobalValue *GV = MO.getGlobal();
356 std::string Name = Mang->getMangledName(GV);
358 // Map symbol -> label of TOC entry.
359 if (TOC.count(Name) == 0) {
361 Label += MAI->getPrivateGlobalPrefix();
363 Label += utostr(LabelID++);
368 O << TOC[Name] << "@toc";
371 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
372 const char *Modifier);
374 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
377 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
378 class PPCLinuxAsmPrinter : public PPCAsmPrinter {
380 explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
381 const MCAsmInfo *T, bool V)
382 : PPCAsmPrinter(O, TM, T, V){}
384 virtual const char *getPassName() const {
385 return "Linux PPC Assembly Printer";
388 bool runOnMachineFunction(MachineFunction &F);
389 bool doFinalization(Module &M);
391 void getAnalysisUsage(AnalysisUsage &AU) const {
392 AU.setPreservesAll();
393 AU.addRequired<MachineModuleInfo>();
394 AU.addRequired<DwarfWriter>();
395 PPCAsmPrinter::getAnalysisUsage(AU);
398 void PrintGlobalVariable(const GlobalVariable *GVar);
401 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
403 class PPCDarwinAsmPrinter : public PPCAsmPrinter {
404 formatted_raw_ostream &OS;
406 explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
407 const MCAsmInfo *T, bool V)
408 : PPCAsmPrinter(O, TM, T, V), OS(O) {}
410 virtual const char *getPassName() const {
411 return "Darwin PPC Assembly Printer";
414 bool runOnMachineFunction(MachineFunction &F);
415 bool doFinalization(Module &M);
416 void EmitStartOfAsmFile(Module &M);
418 void getAnalysisUsage(AnalysisUsage &AU) const {
419 AU.setPreservesAll();
420 AU.addRequired<MachineModuleInfo>();
421 AU.addRequired<DwarfWriter>();
422 PPCAsmPrinter::getAnalysisUsage(AU);
425 void PrintGlobalVariable(const GlobalVariable *GVar);
427 } // end of anonymous namespace
429 // Include the auto-generated portion of the assembly writer
430 #include "PPCGenAsmWriter.inc"
432 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
433 switch (MO.getType()) {
434 case MachineOperand::MO_Immediate:
435 llvm_unreachable("printOp() does not handle immediate values");
437 case MachineOperand::MO_MachineBasicBlock:
438 GetMBBSymbol(MO.getMBB()->getNumber())->print(O, MAI);
440 case MachineOperand::MO_JumpTableIndex:
441 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
442 << '_' << MO.getIndex();
443 // FIXME: PIC relocation model
445 case MachineOperand::MO_ConstantPoolIndex:
446 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
447 << '_' << MO.getIndex();
449 case MachineOperand::MO_BlockAddress:
450 GetBlockAddressSymbol(MO.getBlockAddress())->print(O, MAI);
452 case MachineOperand::MO_ExternalSymbol: {
453 // Computing the address of an external symbol, not calling it.
454 std::string Name(MAI->getGlobalPrefix());
455 Name += MO.getSymbolName();
457 if (TM.getRelocationModel() != Reloc::Static) {
458 GVStubs[Name] = Name+"$non_lazy_ptr";
459 Name += "$non_lazy_ptr";
464 case MachineOperand::MO_GlobalAddress: {
465 // Computing the address of a global symbol, not calling it.
466 GlobalValue *GV = MO.getGlobal();
469 // External or weakly linked global variables need non-lazily-resolved stubs
470 if (TM.getRelocationModel() != Reloc::Static &&
471 (GV->isDeclaration() || GV->isWeakForLinker())) {
472 if (!GV->hasHiddenVisibility()) {
473 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
474 GVStubs[Mang->getMangledName(GV)] = Name;
475 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
476 GV->hasAvailableExternallyLinkage()) {
477 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
478 HiddenGVStubs[Mang->getMangledName(GV)] = Name;
480 Name = Mang->getMangledName(GV);
483 Name = Mang->getMangledName(GV);
487 printOffset(MO.getOffset());
492 O << "<unknown operand type: " << MO.getType() << ">";
497 /// PrintAsmOperand - Print out an operand for an inline asm expression.
499 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
501 const char *ExtraCode) {
502 // Does this asm operand have a single letter operand modifier?
503 if (ExtraCode && ExtraCode[0]) {
504 if (ExtraCode[1] != 0) return true; // Unknown modifier.
506 switch (ExtraCode[0]) {
507 default: return true; // Unknown modifier.
508 case 'c': // Don't print "$" before a global var name or constant.
509 // PPC never has a prefix.
510 printOperand(MI, OpNo);
512 case 'L': // Write second word of DImode reference.
513 // Verify that this operand has two consecutive registers.
514 if (!MI->getOperand(OpNo).isReg() ||
515 OpNo+1 == MI->getNumOperands() ||
516 !MI->getOperand(OpNo+1).isReg())
518 ++OpNo; // Return the high-part.
521 // Write 'i' if an integer constant, otherwise nothing. Used to print
523 if (MI->getOperand(OpNo).isImm())
529 printOperand(MI, OpNo);
533 // At the moment, all inline asm memory operands are a single register.
534 // In any case, the output of this routine should always be just one
535 // assembler operand.
537 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
539 const char *ExtraCode) {
540 if (ExtraCode && ExtraCode[0])
541 return true; // Unknown modifier.
542 assert (MI->getOperand(OpNo).isReg());
544 printOperand(MI, OpNo);
549 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
550 const char *Modifier) {
551 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
552 unsigned Code = MI->getOperand(OpNo).getImm();
553 if (!strcmp(Modifier, "cc")) {
554 switch ((PPC::Predicate)Code) {
555 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
556 case PPC::PRED_LT: O << "lt"; return;
557 case PPC::PRED_LE: O << "le"; return;
558 case PPC::PRED_EQ: O << "eq"; return;
559 case PPC::PRED_GE: O << "ge"; return;
560 case PPC::PRED_GT: O << "gt"; return;
561 case PPC::PRED_NE: O << "ne"; return;
562 case PPC::PRED_UN: O << "un"; return;
563 case PPC::PRED_NU: O << "nu"; return;
567 assert(!strcmp(Modifier, "reg") &&
568 "Need to specify 'cc' or 'reg' as predicate op modifier!");
569 // Don't print the register for 'always'.
570 if (Code == PPC::PRED_ALWAYS) return;
571 printOperand(MI, OpNo+1);
576 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
577 /// the current output stream.
579 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
582 processDebugLoc(MI, true);
584 // Check for slwi/srwi mnemonics.
585 bool useSubstituteMnemonic = false;
586 if (MI->getOpcode() == PPC::RLWINM) {
587 unsigned char SH = MI->getOperand(2).getImm();
588 unsigned char MB = MI->getOperand(3).getImm();
589 unsigned char ME = MI->getOperand(4).getImm();
590 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
591 O << "\tslwi "; useSubstituteMnemonic = true;
593 if (SH <= 31 && MB == (32-SH) && ME == 31) {
594 O << "\tsrwi "; useSubstituteMnemonic = true;
597 if (useSubstituteMnemonic) {
601 O << ", " << (unsigned int)SH;
603 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
604 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
605 useSubstituteMnemonic = true;
611 } else if (MI->getOpcode() == PPC::RLDICR) {
612 unsigned char SH = MI->getOperand(2).getImm();
613 unsigned char ME = MI->getOperand(3).getImm();
614 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
616 useSubstituteMnemonic = true;
621 O << ", " << (unsigned int)SH;
625 if (!useSubstituteMnemonic)
626 printInstruction(MI);
632 processDebugLoc(MI, false);
635 /// runOnMachineFunction - This uses the printMachineInstruction()
636 /// method to print assembly for each instruction.
638 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
641 SetupMachineFunction(MF);
644 // Print out constants referenced by the function
645 EmitConstantPool(MF.getConstantPool());
647 // Print out labels for the function.
648 const Function *F = MF.getFunction();
649 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
651 switch (F->getLinkage()) {
652 default: llvm_unreachable("Unknown linkage type!");
653 case Function::PrivateLinkage:
654 case Function::InternalLinkage: // Symbols default to internal.
656 case Function::ExternalLinkage:
657 O << "\t.global\t" << CurrentFnName << '\n'
658 << "\t.type\t" << CurrentFnName << ", @function\n";
660 case Function::LinkerPrivateLinkage:
661 case Function::WeakAnyLinkage:
662 case Function::WeakODRLinkage:
663 case Function::LinkOnceAnyLinkage:
664 case Function::LinkOnceODRLinkage:
665 O << "\t.global\t" << CurrentFnName << '\n';
666 O << "\t.weak\t" << CurrentFnName << '\n';
670 printVisibility(CurrentFnName, F->getVisibility());
672 EmitAlignment(MF.getAlignment(), F);
674 if (Subtarget.isPPC64()) {
675 // Emit an official procedure descriptor.
676 // FIXME 64-bit SVR4: Use MCSection here?
677 O << "\t.section\t\".opd\",\"aw\"\n";
679 O << CurrentFnName << ":\n";
680 O << "\t.quad .L." << CurrentFnName << ",.TOC.@tocbase\n";
681 O << "\t.previous\n";
682 O << ".L." << CurrentFnName << ":\n";
684 O << CurrentFnName << ":\n";
687 // Emit pre-function debug information.
688 DW->BeginFunction(&MF);
690 // Print out code for the function.
691 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
693 // Print a label for the basic block.
694 if (I != MF.begin()) {
695 EmitBasicBlockStart(I);
697 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
699 // Print the assembly for the instruction.
700 printMachineInstruction(II);
704 O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << '\n';
706 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
708 // Emit post-function debug information.
709 DW->EndFunction(&MF);
711 // Print out jump tables referenced by the function.
712 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
714 // We didn't modify anything.
718 void PPCLinuxAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
719 const TargetData *TD = TM.getTargetData();
721 if (!GVar->hasInitializer())
722 return; // External global require no code
724 // Check to see if this is a special global used by LLVM, if so, emit it.
725 if (EmitSpecialLLVMGlobal(GVar))
728 std::string name = Mang->getMangledName(GVar);
730 printVisibility(name, GVar->getVisibility());
732 Constant *C = GVar->getInitializer();
733 const Type *Type = C->getType();
734 unsigned Size = TD->getTypeAllocSize(Type);
735 unsigned Align = TD->getPreferredAlignmentLog(GVar);
737 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(GVar, Mang,
740 if (C->isNullValue() && /* FIXME: Verify correct */
741 !GVar->hasSection() &&
742 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
743 GVar->isWeakForLinker())) {
744 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
746 if (GVar->hasExternalLinkage()) {
747 O << "\t.global " << name << '\n';
748 O << "\t.type " << name << ", @object\n";
750 O << "\t.zero " << Size << '\n';
751 } else if (GVar->hasLocalLinkage()) {
752 O << MAI->getLCOMMDirective() << name << ',' << Size;
754 O << ".comm " << name << ',' << Size;
757 O << "\t\t" << MAI->getCommentString() << " '";
758 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
765 switch (GVar->getLinkage()) {
766 case GlobalValue::LinkOnceAnyLinkage:
767 case GlobalValue::LinkOnceODRLinkage:
768 case GlobalValue::WeakAnyLinkage:
769 case GlobalValue::WeakODRLinkage:
770 case GlobalValue::CommonLinkage:
771 case GlobalValue::LinkerPrivateLinkage:
772 O << "\t.global " << name << '\n'
773 << "\t.type " << name << ", @object\n"
774 << "\t.weak " << name << '\n';
776 case GlobalValue::AppendingLinkage:
777 // FIXME: appending linkage variables should go into a section of
778 // their name or something. For now, just emit them as external.
779 case GlobalValue::ExternalLinkage:
780 // If external or appending, declare as a global symbol
781 O << "\t.global " << name << '\n'
782 << "\t.type " << name << ", @object\n";
784 case GlobalValue::InternalLinkage:
785 case GlobalValue::PrivateLinkage:
788 llvm_unreachable("Unknown linkage type!");
791 EmitAlignment(Align, GVar);
794 O << "\t\t\t\t" << MAI->getCommentString() << " '";
795 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
800 EmitGlobalConstant(C);
804 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
805 const TargetData *TD = TM.getTargetData();
807 bool isPPC64 = TD->getPointerSizeInBits() == 64;
809 if (isPPC64 && !TOC.empty()) {
810 // FIXME 64-bit SVR4: Use MCSection here?
811 O << "\t.section\t\".toc\",\"aw\"\n";
813 for (StringMap<std::string>::iterator I = TOC.begin(), E = TOC.end();
815 O << I->second << ":\n";
816 O << "\t.tc " << I->getKeyData() << "[TC]," << I->getKeyData() << '\n';
820 return AsmPrinter::doFinalization(M);
823 /// runOnMachineFunction - This uses the printMachineInstruction()
824 /// method to print assembly for each instruction.
826 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
829 SetupMachineFunction(MF);
832 // Print out constants referenced by the function
833 EmitConstantPool(MF.getConstantPool());
835 // Print out labels for the function.
836 const Function *F = MF.getFunction();
837 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
839 switch (F->getLinkage()) {
840 default: llvm_unreachable("Unknown linkage type!");
841 case Function::PrivateLinkage:
842 case Function::InternalLinkage: // Symbols default to internal.
844 case Function::ExternalLinkage:
845 O << "\t.globl\t" << CurrentFnName << '\n';
847 case Function::WeakAnyLinkage:
848 case Function::WeakODRLinkage:
849 case Function::LinkOnceAnyLinkage:
850 case Function::LinkOnceODRLinkage:
851 case Function::LinkerPrivateLinkage:
852 O << "\t.globl\t" << CurrentFnName << '\n';
853 O << "\t.weak_definition\t" << CurrentFnName << '\n';
857 printVisibility(CurrentFnName, F->getVisibility());
859 EmitAlignment(MF.getAlignment(), F);
860 O << CurrentFnName << ":\n";
862 // Emit pre-function debug information.
863 DW->BeginFunction(&MF);
865 // If the function is empty, then we need to emit *something*. Otherwise, the
866 // function's label might be associated with something that it wasn't meant to
867 // be associated with. We emit a noop in this situation.
868 MachineFunction::iterator I = MF.begin();
870 if (++I == MF.end() && MF.front().empty())
873 // Print out code for the function.
874 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
876 // Print a label for the basic block.
877 if (I != MF.begin()) {
878 EmitBasicBlockStart(I);
880 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
882 // Print the assembly for the instruction.
883 printMachineInstruction(II);
887 // Emit post-function debug information.
888 DW->EndFunction(&MF);
890 // Print out jump tables referenced by the function.
891 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
893 // We didn't modify anything.
898 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
899 static const char *const CPUDirectives[] = {
911 unsigned Directive = Subtarget.getDarwinDirective();
912 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
913 Directive = PPC::DIR_970;
914 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
915 Directive = PPC::DIR_7400;
916 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
917 Directive = PPC::DIR_64;
918 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
919 O << "\t.machine " << CPUDirectives[Directive] << '\n';
921 // Prime text sections so they are adjacent. This reduces the likelihood a
922 // large data or debug section causes a branch to exceed 16M limit.
923 TargetLoweringObjectFileMachO &TLOFMacho =
924 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
925 OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
926 if (TM.getRelocationModel() == Reloc::PIC_) {
927 OutStreamer.SwitchSection(
928 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
929 MCSectionMachO::S_SYMBOL_STUBS |
930 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
931 32, SectionKind::getText()));
932 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
933 OutStreamer.SwitchSection(
934 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
935 MCSectionMachO::S_SYMBOL_STUBS |
936 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
937 16, SectionKind::getText()));
939 OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
942 void PPCDarwinAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
943 const TargetData *TD = TM.getTargetData();
945 if (!GVar->hasInitializer())
946 return; // External global require no code
948 // Check to see if this is a special global used by LLVM, if so, emit it.
949 if (EmitSpecialLLVMGlobal(GVar)) {
950 if (TM.getRelocationModel() == Reloc::Static) {
951 if (GVar->getName() == "llvm.global_ctors")
952 O << ".reference .constructors_used\n";
953 else if (GVar->getName() == "llvm.global_dtors")
954 O << ".reference .destructors_used\n";
959 std::string name = Mang->getMangledName(GVar);
960 printVisibility(name, GVar->getVisibility());
962 Constant *C = GVar->getInitializer();
963 const Type *Type = C->getType();
964 unsigned Size = TD->getTypeAllocSize(Type);
965 unsigned Align = TD->getPreferredAlignmentLog(GVar);
967 const MCSection *TheSection =
968 getObjFileLowering().SectionForGlobal(GVar, Mang, TM);
969 OutStreamer.SwitchSection(TheSection);
971 /// FIXME: Drive this off the section!
972 if (C->isNullValue() && /* FIXME: Verify correct */
973 !GVar->hasSection() &&
974 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
975 GVar->isWeakForLinker()) &&
976 // Don't put things that should go in the cstring section into "comm".
977 !TheSection->getKind().isMergeableCString()) {
978 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
980 if (GVar->hasExternalLinkage()) {
981 O << "\t.globl " << name << '\n';
982 O << "\t.zerofill __DATA, __common, " << name << ", "
983 << Size << ", " << Align;
984 } else if (GVar->hasLocalLinkage()) {
985 O << MAI->getLCOMMDirective() << name << ',' << Size << ',' << Align;
986 } else if (!GVar->hasCommonLinkage()) {
987 O << "\t.globl " << name << '\n'
988 << MAI->getWeakDefDirective() << name << '\n';
989 EmitAlignment(Align, GVar);
992 O << "\t\t\t\t" << MAI->getCommentString() << " ";
993 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
996 EmitGlobalConstant(C);
999 O << ".comm " << name << ',' << Size;
1000 // Darwin 9 and above support aligned common data.
1001 if (Subtarget.isDarwin9())
1005 O << "\t\t" << MAI->getCommentString() << " '";
1006 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1013 switch (GVar->getLinkage()) {
1014 case GlobalValue::LinkOnceAnyLinkage:
1015 case GlobalValue::LinkOnceODRLinkage:
1016 case GlobalValue::WeakAnyLinkage:
1017 case GlobalValue::WeakODRLinkage:
1018 case GlobalValue::CommonLinkage:
1019 case GlobalValue::LinkerPrivateLinkage:
1020 O << "\t.globl " << name << '\n'
1021 << "\t.weak_definition " << name << '\n';
1023 case GlobalValue::AppendingLinkage:
1024 // FIXME: appending linkage variables should go into a section of
1025 // their name or something. For now, just emit them as external.
1026 case GlobalValue::ExternalLinkage:
1027 // If external or appending, declare as a global symbol
1028 O << "\t.globl " << name << '\n';
1030 case GlobalValue::InternalLinkage:
1031 case GlobalValue::PrivateLinkage:
1034 llvm_unreachable("Unknown linkage type!");
1037 EmitAlignment(Align, GVar);
1040 O << "\t\t\t\t" << MAI->getCommentString() << " '";
1041 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1046 EmitGlobalConstant(C);
1050 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
1051 const TargetData *TD = TM.getTargetData();
1053 bool isPPC64 = TD->getPointerSizeInBits() == 64;
1055 // Darwin/PPC always uses mach-o.
1056 TargetLoweringObjectFileMachO &TLOFMacho =
1057 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
1060 const MCSection *LSPSection = 0;
1061 if (!FnStubs.empty()) // .lazy_symbol_pointer
1062 LSPSection = TLOFMacho.getLazySymbolPointerSection();
1065 // Output stubs for dynamically-linked functions
1066 if (TM.getRelocationModel() == Reloc::PIC_ && !FnStubs.empty()) {
1067 const MCSection *StubSection =
1068 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
1069 MCSectionMachO::S_SYMBOL_STUBS |
1070 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1071 32, SectionKind::getText());
1072 for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1074 OutStreamer.SwitchSection(StubSection);
1076 const FnStubInfo &Info = I->second;
1077 Info.printStub(O, MAI);
1079 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1081 O << "\tbcl 20,31,";
1082 Info.printAnonSymbol(O, MAI);
1084 Info.printAnonSymbol(O, MAI);
1086 O << "\tmflr r11\n";
1087 O << "\taddis r11,r11,ha16(";
1088 Info.printLazyPtr(O, MAI);
1090 Info.printAnonSymbol(O, MAI);
1093 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1094 Info.printLazyPtr(O, MAI);
1096 Info.printAnonSymbol(O, MAI);
1098 O << "\tmtctr r12\n";
1101 OutStreamer.SwitchSection(LSPSection);
1102 Info.printLazyPtr(O, MAI);
1104 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1105 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1107 } else if (!FnStubs.empty()) {
1108 const MCSection *StubSection =
1109 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
1110 MCSectionMachO::S_SYMBOL_STUBS |
1111 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1112 16, SectionKind::getText());
1114 for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1116 OutStreamer.SwitchSection(StubSection);
1118 const FnStubInfo &Info = I->second;
1119 Info.printStub(O, MAI);
1121 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1122 O << "\tlis r11,ha16(";
1123 Info.printLazyPtr(O, MAI);
1125 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1126 Info.printLazyPtr(O, MAI);
1128 O << "\tmtctr r12\n";
1130 OutStreamer.SwitchSection(LSPSection);
1131 Info.printLazyPtr(O, MAI);
1133 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1134 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1140 if (MAI->doesSupportExceptionHandling() && MMI) {
1141 // Add the (possibly multiple) personalities to the set of global values.
1142 // Only referenced functions get into the Personalities list.
1143 const std::vector<Function *> &Personalities = MMI->getPersonalities();
1144 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1145 E = Personalities.end(); I != E; ++I) {
1147 GVStubs[Mang->getMangledName(*I)] =
1148 Mang->getMangledName(*I, "$non_lazy_ptr", true);
1152 // Output macho stubs for external and common global variables.
1153 if (!GVStubs.empty()) {
1154 // Switch with ".non_lazy_symbol_pointer" directive.
1155 OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
1156 EmitAlignment(isPPC64 ? 3 : 2);
1158 for (StringMap<std::string>::iterator I = GVStubs.begin(),
1159 E = GVStubs.end(); I != E; ++I) {
1160 O << I->second << ":\n";
1161 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1162 O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
1166 if (!HiddenGVStubs.empty()) {
1167 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
1168 EmitAlignment(isPPC64 ? 3 : 2);
1169 for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
1170 E = HiddenGVStubs.end(); I != E; ++I) {
1171 O << I->second << ":\n";
1172 O << (isPPC64 ? "\t.quad\t" : "\t.long\t") << I->getKeyData() << '\n';
1176 // Funny Darwin hack: This flag tells the linker that no global symbols
1177 // contain code that falls through to other global symbols (e.g. the obvious
1178 // implementation of multiple entry points). If this doesn't occur, the
1179 // linker can safely perform dead code stripping. Since LLVM never generates
1180 // code that does this, it is always safe to set.
1181 OutStreamer.EmitAssemblerFlag(MCStreamer::SubsectionsViaSymbols);
1183 return AsmPrinter::doFinalization(M);
1188 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1189 /// for a MachineFunction to the given output stream, in a format that the
1190 /// Darwin assembler can deal with.
1192 static AsmPrinter *createPPCAsmPrinterPass(formatted_raw_ostream &o,
1194 const MCAsmInfo *tai,
1196 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1198 if (Subtarget->isDarwin())
1199 return new PPCDarwinAsmPrinter(o, tm, tai, verbose);
1200 return new PPCLinuxAsmPrinter(o, tm, tai, verbose);
1203 // Force static initialization.
1204 extern "C" void LLVMInitializePowerPCAsmPrinter() {
1205 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
1206 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);