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/MCSectionMachO.h"
36 #include "llvm/MC/MCStreamer.h"
37 #include "llvm/MC/MCSymbol.h"
38 #include "llvm/Target/TargetLoweringObjectFile.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/Target/TargetRegistry.h"
43 #include "llvm/Support/Mangler.h"
44 #include "llvm/Support/MathExtras.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/FormattedStream.h"
49 #include "llvm/ADT/Statistic.h"
50 #include "llvm/ADT/StringExtras.h"
51 #include "llvm/ADT/StringSet.h"
52 #include "llvm/ADT/SmallString.h"
55 STATISTIC(EmittedInsts, "Number of machine instrs printed");
58 class PPCAsmPrinter : public AsmPrinter {
61 std::string Stub, LazyPtr, AnonSymbol;
65 void Init(const GlobalValue *GV, Mangler *Mang) {
66 // Already initialized.
67 if (!Stub.empty()) return;
68 Stub = Mang->getMangledName(GV, "$stub", true);
69 LazyPtr = Mang->getMangledName(GV, "$lazy_ptr", true);
70 AnonSymbol = Mang->getMangledName(GV, "$stub$tmp", true);
73 void Init(StringRef GVName, Mangler *Mang) {
74 // Already initialized.
75 if (!Stub.empty()) return;
76 SmallString<128> TmpStr;
77 Mang->makeNameProper(TmpStr, GVName + "$stub", Mangler::Private);
81 Mang->makeNameProper(TmpStr, GVName + "$lazy_ptr", Mangler::Private);
82 LazyPtr = TmpStr.str();
85 Mang->makeNameProper(TmpStr, GVName + "$stub$tmp", Mangler::Private);
86 AnonSymbol = TmpStr.str();
90 StringMap<FnStubInfo> FnStubs;
91 StringMap<std::string> GVStubs, HiddenGVStubs, TOC;
92 const PPCSubtarget &Subtarget;
95 explicit PPCAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
96 const MCAsmInfo *T, bool V)
97 : AsmPrinter(O, TM, T, V),
98 Subtarget(TM.getSubtarget<PPCSubtarget>()), LabelID(0) {}
100 virtual const char *getPassName() const {
101 return "PowerPC Assembly Printer";
104 PPCTargetMachine &getTM() {
105 return static_cast<PPCTargetMachine&>(TM);
108 unsigned enumRegToMachineReg(unsigned enumReg) {
110 default: llvm_unreachable("Unhandled register!");
111 case PPC::CR0: return 0;
112 case PPC::CR1: return 1;
113 case PPC::CR2: return 2;
114 case PPC::CR3: return 3;
115 case PPC::CR4: return 4;
116 case PPC::CR5: return 5;
117 case PPC::CR6: return 6;
118 case PPC::CR7: return 7;
123 /// printInstruction - This method is automatically generated by tablegen
124 /// from the instruction set description. This method returns true if the
125 /// machine instruction was sufficiently described to print it, otherwise it
127 void printInstruction(const MachineInstr *MI);
128 static const char *getRegisterName(unsigned RegNo);
131 void printMachineInstruction(const MachineInstr *MI);
132 void printOp(const MachineOperand &MO);
134 /// stripRegisterPrefix - This method strips the character prefix from a
135 /// register name so that only the number is left. Used by for linux asm.
136 const char *stripRegisterPrefix(const char *RegName) {
137 switch (RegName[0]) {
140 case 'v': return RegName + 1;
141 case 'c': if (RegName[1] == 'r') return RegName + 2;
147 /// printRegister - Print register according to target requirements.
149 void printRegister(const MachineOperand &MO, bool R0AsZero) {
150 unsigned RegNo = MO.getReg();
151 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
153 // If we should use 0 for R0.
154 if (R0AsZero && RegNo == PPC::R0) {
159 const char *RegName = getRegisterName(RegNo);
160 // Linux assembler (Others?) does not take register mnemonics.
161 // FIXME - What about special registers used in mfspr/mtspr?
162 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
166 void printOperand(const MachineInstr *MI, unsigned OpNo) {
167 const MachineOperand &MO = MI->getOperand(OpNo);
169 printRegister(MO, false);
170 } else if (MO.isImm()) {
177 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
178 unsigned AsmVariant, const char *ExtraCode);
179 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
180 unsigned AsmVariant, const char *ExtraCode);
183 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
184 char value = MI->getOperand(OpNo).getImm();
185 value = (value << (32-5)) >> (32-5);
188 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
189 unsigned char value = MI->getOperand(OpNo).getImm();
190 assert(value <= 31 && "Invalid u5imm argument!");
191 O << (unsigned int)value;
193 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
194 unsigned char value = MI->getOperand(OpNo).getImm();
195 assert(value <= 63 && "Invalid u6imm argument!");
196 O << (unsigned int)value;
198 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
199 O << (short)MI->getOperand(OpNo).getImm();
201 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
202 O << (unsigned short)MI->getOperand(OpNo).getImm();
204 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
205 if (MI->getOperand(OpNo).isImm()) {
206 O << (short)(MI->getOperand(OpNo).getImm()*4);
209 printOp(MI->getOperand(OpNo));
210 if (TM.getRelocationModel() == Reloc::PIC_)
211 O << "-\"L" << getFunctionNumber() << "$pb\")";
216 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
217 // Branches can take an immediate operand. This is used by the branch
218 // selection pass to print $+8, an eight byte displacement from the PC.
219 if (MI->getOperand(OpNo).isImm()) {
220 O << "$+" << MI->getOperand(OpNo).getImm()*4;
222 printOp(MI->getOperand(OpNo));
225 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
226 const MachineOperand &MO = MI->getOperand(OpNo);
227 if (TM.getRelocationModel() != Reloc::Static) {
228 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
229 GlobalValue *GV = MO.getGlobal();
230 if (GV->isDeclaration() || GV->isWeakForLinker()) {
231 // Dynamically-resolved functions need a stub for the function.
232 FnStubInfo &FnInfo = FnStubs[Mang->getMangledName(GV)];
233 FnInfo.Init(GV, Mang);
238 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
239 SmallString<128> MangledName;
240 Mang->makeNameProper(MangledName, MO.getSymbolName());
241 FnStubInfo &FnInfo = FnStubs[MangledName.str()];
242 FnInfo.Init(MO.getSymbolName(), Mang);
248 printOp(MI->getOperand(OpNo));
250 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
251 O << (int)MI->getOperand(OpNo).getImm()*4;
253 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
254 O << "\"L" << getFunctionNumber() << "$pb\"\n";
255 O << "\"L" << getFunctionNumber() << "$pb\":";
257 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
258 if (MI->getOperand(OpNo).isImm()) {
259 printS16ImmOperand(MI, OpNo);
261 if (Subtarget.isDarwin()) O << "ha16(";
262 printOp(MI->getOperand(OpNo));
263 if (TM.getRelocationModel() == Reloc::PIC_)
264 O << "-\"L" << getFunctionNumber() << "$pb\"";
265 if (Subtarget.isDarwin())
271 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
272 if (MI->getOperand(OpNo).isImm()) {
273 printS16ImmOperand(MI, OpNo);
275 if (Subtarget.isDarwin()) O << "lo16(";
276 printOp(MI->getOperand(OpNo));
277 if (TM.getRelocationModel() == Reloc::PIC_)
278 O << "-\"L" << getFunctionNumber() << "$pb\"";
279 if (Subtarget.isDarwin())
285 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
286 unsigned CCReg = MI->getOperand(OpNo).getReg();
287 unsigned RegNo = enumRegToMachineReg(CCReg);
288 O << (0x80 >> RegNo);
290 // The new addressing mode printers.
291 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
292 printSymbolLo(MI, OpNo);
294 if (MI->getOperand(OpNo+1).isReg() &&
295 MI->getOperand(OpNo+1).getReg() == PPC::R0)
298 printOperand(MI, OpNo+1);
301 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
302 if (MI->getOperand(OpNo).isImm())
303 printS16X4ImmOperand(MI, OpNo);
305 printSymbolLo(MI, OpNo);
307 if (MI->getOperand(OpNo+1).isReg() &&
308 MI->getOperand(OpNo+1).getReg() == PPC::R0)
311 printOperand(MI, OpNo+1);
315 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
316 // When used as the base register, r0 reads constant zero rather than
317 // the value contained in the register. For this reason, the darwin
318 // assembler requires that we print r0 as 0 (no r) when used as the base.
319 const MachineOperand &MO = MI->getOperand(OpNo);
320 printRegister(MO, true);
322 printOperand(MI, OpNo+1);
325 void printTOCEntryLabel(const MachineInstr *MI, unsigned OpNo) {
326 const MachineOperand &MO = MI->getOperand(OpNo);
328 assert(MO.getType() == MachineOperand::MO_GlobalAddress);
330 GlobalValue *GV = MO.getGlobal();
332 std::string Name = Mang->getMangledName(GV);
334 // Map symbol -> label of TOC entry.
335 if (TOC.count(Name) == 0) {
337 Label += MAI->getPrivateGlobalPrefix();
339 Label += utostr(LabelID++);
344 O << TOC[Name] << "@toc";
347 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
348 const char *Modifier);
350 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
353 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
354 class PPCLinuxAsmPrinter : public PPCAsmPrinter {
356 explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
357 const MCAsmInfo *T, bool V)
358 : PPCAsmPrinter(O, TM, T, V){}
360 virtual const char *getPassName() const {
361 return "Linux PPC Assembly Printer";
364 bool runOnMachineFunction(MachineFunction &F);
365 bool doFinalization(Module &M);
367 void getAnalysisUsage(AnalysisUsage &AU) const {
368 AU.setPreservesAll();
369 AU.addRequired<MachineModuleInfo>();
370 AU.addRequired<DwarfWriter>();
371 PPCAsmPrinter::getAnalysisUsage(AU);
374 void PrintGlobalVariable(const GlobalVariable *GVar);
377 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
379 class PPCDarwinAsmPrinter : public PPCAsmPrinter {
380 formatted_raw_ostream &OS;
382 explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
383 const MCAsmInfo *T, bool V)
384 : PPCAsmPrinter(O, TM, T, V), OS(O) {}
386 virtual const char *getPassName() const {
387 return "Darwin PPC Assembly Printer";
390 bool runOnMachineFunction(MachineFunction &F);
391 bool doFinalization(Module &M);
392 void EmitStartOfAsmFile(Module &M);
394 void getAnalysisUsage(AnalysisUsage &AU) const {
395 AU.setPreservesAll();
396 AU.addRequired<MachineModuleInfo>();
397 AU.addRequired<DwarfWriter>();
398 PPCAsmPrinter::getAnalysisUsage(AU);
401 void PrintGlobalVariable(const GlobalVariable *GVar);
403 } // end of anonymous namespace
405 // Include the auto-generated portion of the assembly writer
406 #include "PPCGenAsmWriter.inc"
408 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
409 switch (MO.getType()) {
410 case MachineOperand::MO_Immediate:
411 llvm_unreachable("printOp() does not handle immediate values");
413 case MachineOperand::MO_MachineBasicBlock:
414 GetMBBSymbol(MO.getMBB()->getNumber())->print(O, MAI);
416 case MachineOperand::MO_JumpTableIndex:
417 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
418 << '_' << MO.getIndex();
419 // FIXME: PIC relocation model
421 case MachineOperand::MO_ConstantPoolIndex:
422 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
423 << '_' << MO.getIndex();
425 case MachineOperand::MO_BlockAddress:
426 GetBlockAddressSymbol(MO.getBlockAddress())->print(O, MAI);
428 case MachineOperand::MO_ExternalSymbol: {
429 // Computing the address of an external symbol, not calling it.
430 std::string Name(MAI->getGlobalPrefix());
431 Name += MO.getSymbolName();
433 if (TM.getRelocationModel() != Reloc::Static) {
434 GVStubs[Name] = Name+"$non_lazy_ptr";
435 Name += "$non_lazy_ptr";
440 case MachineOperand::MO_GlobalAddress: {
441 // Computing the address of a global symbol, not calling it.
442 GlobalValue *GV = MO.getGlobal();
445 // External or weakly linked global variables need non-lazily-resolved stubs
446 if (TM.getRelocationModel() != Reloc::Static &&
447 (GV->isDeclaration() || GV->isWeakForLinker())) {
448 if (!GV->hasHiddenVisibility()) {
449 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
450 GVStubs[Mang->getMangledName(GV)] = Name;
451 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
452 GV->hasAvailableExternallyLinkage()) {
453 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
454 HiddenGVStubs[Mang->getMangledName(GV)] = Name;
456 Name = Mang->getMangledName(GV);
459 Name = Mang->getMangledName(GV);
463 printOffset(MO.getOffset());
468 O << "<unknown operand type: " << MO.getType() << ">";
473 /// PrintAsmOperand - Print out an operand for an inline asm expression.
475 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
477 const char *ExtraCode) {
478 // Does this asm operand have a single letter operand modifier?
479 if (ExtraCode && ExtraCode[0]) {
480 if (ExtraCode[1] != 0) return true; // Unknown modifier.
482 switch (ExtraCode[0]) {
483 default: return true; // Unknown modifier.
484 case 'c': // Don't print "$" before a global var name or constant.
485 // PPC never has a prefix.
486 printOperand(MI, OpNo);
488 case 'L': // Write second word of DImode reference.
489 // Verify that this operand has two consecutive registers.
490 if (!MI->getOperand(OpNo).isReg() ||
491 OpNo+1 == MI->getNumOperands() ||
492 !MI->getOperand(OpNo+1).isReg())
494 ++OpNo; // Return the high-part.
497 // Write 'i' if an integer constant, otherwise nothing. Used to print
499 if (MI->getOperand(OpNo).isImm())
505 printOperand(MI, OpNo);
509 // At the moment, all inline asm memory operands are a single register.
510 // In any case, the output of this routine should always be just one
511 // assembler operand.
513 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
515 const char *ExtraCode) {
516 if (ExtraCode && ExtraCode[0])
517 return true; // Unknown modifier.
518 assert (MI->getOperand(OpNo).isReg());
520 printOperand(MI, OpNo);
525 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
526 const char *Modifier) {
527 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
528 unsigned Code = MI->getOperand(OpNo).getImm();
529 if (!strcmp(Modifier, "cc")) {
530 switch ((PPC::Predicate)Code) {
531 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
532 case PPC::PRED_LT: O << "lt"; return;
533 case PPC::PRED_LE: O << "le"; return;
534 case PPC::PRED_EQ: O << "eq"; return;
535 case PPC::PRED_GE: O << "ge"; return;
536 case PPC::PRED_GT: O << "gt"; return;
537 case PPC::PRED_NE: O << "ne"; return;
538 case PPC::PRED_UN: O << "un"; return;
539 case PPC::PRED_NU: O << "nu"; return;
543 assert(!strcmp(Modifier, "reg") &&
544 "Need to specify 'cc' or 'reg' as predicate op modifier!");
545 // Don't print the register for 'always'.
546 if (Code == PPC::PRED_ALWAYS) return;
547 printOperand(MI, OpNo+1);
552 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
553 /// the current output stream.
555 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
558 processDebugLoc(MI, true);
560 // Check for slwi/srwi mnemonics.
561 bool useSubstituteMnemonic = false;
562 if (MI->getOpcode() == PPC::RLWINM) {
563 unsigned char SH = MI->getOperand(2).getImm();
564 unsigned char MB = MI->getOperand(3).getImm();
565 unsigned char ME = MI->getOperand(4).getImm();
566 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
567 O << "\tslwi "; useSubstituteMnemonic = true;
569 if (SH <= 31 && MB == (32-SH) && ME == 31) {
570 O << "\tsrwi "; useSubstituteMnemonic = true;
573 if (useSubstituteMnemonic) {
577 O << ", " << (unsigned int)SH;
579 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
580 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
581 useSubstituteMnemonic = true;
587 } else if (MI->getOpcode() == PPC::RLDICR) {
588 unsigned char SH = MI->getOperand(2).getImm();
589 unsigned char ME = MI->getOperand(3).getImm();
590 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
592 useSubstituteMnemonic = true;
597 O << ", " << (unsigned int)SH;
601 if (!useSubstituteMnemonic)
602 printInstruction(MI);
608 processDebugLoc(MI, false);
611 /// runOnMachineFunction - This uses the printMachineInstruction()
612 /// method to print assembly for each instruction.
614 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
617 SetupMachineFunction(MF);
620 // Print out constants referenced by the function
621 EmitConstantPool(MF.getConstantPool());
623 // Print out labels for the function.
624 const Function *F = MF.getFunction();
625 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
627 switch (F->getLinkage()) {
628 default: llvm_unreachable("Unknown linkage type!");
629 case Function::PrivateLinkage:
630 case Function::InternalLinkage: // Symbols default to internal.
632 case Function::ExternalLinkage:
633 O << "\t.global\t" << CurrentFnName << '\n'
634 << "\t.type\t" << CurrentFnName << ", @function\n";
636 case Function::LinkerPrivateLinkage:
637 case Function::WeakAnyLinkage:
638 case Function::WeakODRLinkage:
639 case Function::LinkOnceAnyLinkage:
640 case Function::LinkOnceODRLinkage:
641 O << "\t.global\t" << CurrentFnName << '\n';
642 O << "\t.weak\t" << CurrentFnName << '\n';
646 printVisibility(CurrentFnName, F->getVisibility());
648 EmitAlignment(MF.getAlignment(), F);
650 if (Subtarget.isPPC64()) {
651 // Emit an official procedure descriptor.
652 // FIXME 64-bit SVR4: Use MCSection here?
653 O << "\t.section\t\".opd\",\"aw\"\n";
655 O << CurrentFnName << ":\n";
656 O << "\t.quad .L." << CurrentFnName << ",.TOC.@tocbase\n";
657 O << "\t.previous\n";
658 O << ".L." << CurrentFnName << ":\n";
660 O << CurrentFnName << ":\n";
663 // Emit pre-function debug information.
664 DW->BeginFunction(&MF);
666 // Print out code for the function.
667 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
669 // Print a label for the basic block.
670 if (I != MF.begin()) {
671 EmitBasicBlockStart(I);
673 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
675 // Print the assembly for the instruction.
676 printMachineInstruction(II);
680 O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << '\n';
682 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
684 // Emit post-function debug information.
685 DW->EndFunction(&MF);
687 // Print out jump tables referenced by the function.
688 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
690 // We didn't modify anything.
694 void PPCLinuxAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
695 const TargetData *TD = TM.getTargetData();
697 if (!GVar->hasInitializer())
698 return; // External global require no code
700 // Check to see if this is a special global used by LLVM, if so, emit it.
701 if (EmitSpecialLLVMGlobal(GVar))
704 std::string name = Mang->getMangledName(GVar);
706 printVisibility(name, GVar->getVisibility());
708 Constant *C = GVar->getInitializer();
709 const Type *Type = C->getType();
710 unsigned Size = TD->getTypeAllocSize(Type);
711 unsigned Align = TD->getPreferredAlignmentLog(GVar);
713 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(GVar, Mang,
716 if (C->isNullValue() && /* FIXME: Verify correct */
717 !GVar->hasSection() &&
718 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
719 GVar->isWeakForLinker())) {
720 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
722 if (GVar->hasExternalLinkage()) {
723 O << "\t.global " << name << '\n';
724 O << "\t.type " << name << ", @object\n";
726 O << "\t.zero " << Size << '\n';
727 } else if (GVar->hasLocalLinkage()) {
728 O << MAI->getLCOMMDirective() << name << ',' << Size;
730 O << ".comm " << name << ',' << Size;
733 O << "\t\t" << MAI->getCommentString() << " '";
734 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
741 switch (GVar->getLinkage()) {
742 case GlobalValue::LinkOnceAnyLinkage:
743 case GlobalValue::LinkOnceODRLinkage:
744 case GlobalValue::WeakAnyLinkage:
745 case GlobalValue::WeakODRLinkage:
746 case GlobalValue::CommonLinkage:
747 case GlobalValue::LinkerPrivateLinkage:
748 O << "\t.global " << name << '\n'
749 << "\t.type " << name << ", @object\n"
750 << "\t.weak " << name << '\n';
752 case GlobalValue::AppendingLinkage:
753 // FIXME: appending linkage variables should go into a section of
754 // their name or something. For now, just emit them as external.
755 case GlobalValue::ExternalLinkage:
756 // If external or appending, declare as a global symbol
757 O << "\t.global " << name << '\n'
758 << "\t.type " << name << ", @object\n";
760 case GlobalValue::InternalLinkage:
761 case GlobalValue::PrivateLinkage:
764 llvm_unreachable("Unknown linkage type!");
767 EmitAlignment(Align, GVar);
770 O << "\t\t\t\t" << MAI->getCommentString() << " '";
771 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
776 EmitGlobalConstant(C);
780 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
781 const TargetData *TD = TM.getTargetData();
783 bool isPPC64 = TD->getPointerSizeInBits() == 64;
785 if (isPPC64 && !TOC.empty()) {
786 // FIXME 64-bit SVR4: Use MCSection here?
787 O << "\t.section\t\".toc\",\"aw\"\n";
789 for (StringMap<std::string>::iterator I = TOC.begin(), E = TOC.end();
791 O << I->second << ":\n";
792 O << "\t.tc " << I->getKeyData() << "[TC]," << I->getKeyData() << '\n';
796 return AsmPrinter::doFinalization(M);
799 /// runOnMachineFunction - This uses the printMachineInstruction()
800 /// method to print assembly for each instruction.
802 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
805 SetupMachineFunction(MF);
808 // Print out constants referenced by the function
809 EmitConstantPool(MF.getConstantPool());
811 // Print out labels for the function.
812 const Function *F = MF.getFunction();
813 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
815 switch (F->getLinkage()) {
816 default: llvm_unreachable("Unknown linkage type!");
817 case Function::PrivateLinkage:
818 case Function::InternalLinkage: // Symbols default to internal.
820 case Function::ExternalLinkage:
821 O << "\t.globl\t" << CurrentFnName << '\n';
823 case Function::WeakAnyLinkage:
824 case Function::WeakODRLinkage:
825 case Function::LinkOnceAnyLinkage:
826 case Function::LinkOnceODRLinkage:
827 case Function::LinkerPrivateLinkage:
828 O << "\t.globl\t" << CurrentFnName << '\n';
829 O << "\t.weak_definition\t" << CurrentFnName << '\n';
833 printVisibility(CurrentFnName, F->getVisibility());
835 EmitAlignment(MF.getAlignment(), F);
836 O << CurrentFnName << ":\n";
838 // Emit pre-function debug information.
839 DW->BeginFunction(&MF);
841 // If the function is empty, then we need to emit *something*. Otherwise, the
842 // function's label might be associated with something that it wasn't meant to
843 // be associated with. We emit a noop in this situation.
844 MachineFunction::iterator I = MF.begin();
846 if (++I == MF.end() && MF.front().empty())
849 // Print out code for the function.
850 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
852 // Print a label for the basic block.
853 if (I != MF.begin()) {
854 EmitBasicBlockStart(I);
856 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
858 // Print the assembly for the instruction.
859 printMachineInstruction(II);
863 // Emit post-function debug information.
864 DW->EndFunction(&MF);
866 // Print out jump tables referenced by the function.
867 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
869 // We didn't modify anything.
874 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
875 static const char *const CPUDirectives[] = {
887 unsigned Directive = Subtarget.getDarwinDirective();
888 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
889 Directive = PPC::DIR_970;
890 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
891 Directive = PPC::DIR_7400;
892 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
893 Directive = PPC::DIR_64;
894 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
895 O << "\t.machine " << CPUDirectives[Directive] << '\n';
897 // Prime text sections so they are adjacent. This reduces the likelihood a
898 // large data or debug section causes a branch to exceed 16M limit.
899 TargetLoweringObjectFileMachO &TLOFMacho =
900 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
901 OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
902 if (TM.getRelocationModel() == Reloc::PIC_) {
903 OutStreamer.SwitchSection(
904 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
905 MCSectionMachO::S_SYMBOL_STUBS |
906 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
907 32, SectionKind::getText()));
908 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
909 OutStreamer.SwitchSection(
910 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
911 MCSectionMachO::S_SYMBOL_STUBS |
912 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
913 16, SectionKind::getText()));
915 OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
918 void PPCDarwinAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
919 const TargetData *TD = TM.getTargetData();
921 if (!GVar->hasInitializer())
922 return; // External global require no code
924 // Check to see if this is a special global used by LLVM, if so, emit it.
925 if (EmitSpecialLLVMGlobal(GVar)) {
926 if (TM.getRelocationModel() == Reloc::Static) {
927 if (GVar->getName() == "llvm.global_ctors")
928 O << ".reference .constructors_used\n";
929 else if (GVar->getName() == "llvm.global_dtors")
930 O << ".reference .destructors_used\n";
935 std::string name = Mang->getMangledName(GVar);
936 printVisibility(name, GVar->getVisibility());
938 Constant *C = GVar->getInitializer();
939 const Type *Type = C->getType();
940 unsigned Size = TD->getTypeAllocSize(Type);
941 unsigned Align = TD->getPreferredAlignmentLog(GVar);
943 const MCSection *TheSection =
944 getObjFileLowering().SectionForGlobal(GVar, Mang, TM);
945 OutStreamer.SwitchSection(TheSection);
947 /// FIXME: Drive this off the section!
948 if (C->isNullValue() && /* FIXME: Verify correct */
949 !GVar->hasSection() &&
950 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
951 GVar->isWeakForLinker()) &&
952 // Don't put things that should go in the cstring section into "comm".
953 !TheSection->getKind().isMergeableCString()) {
954 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
956 if (GVar->hasExternalLinkage()) {
957 O << "\t.globl " << name << '\n';
958 O << "\t.zerofill __DATA, __common, " << name << ", "
959 << Size << ", " << Align;
960 } else if (GVar->hasLocalLinkage()) {
961 O << MAI->getLCOMMDirective() << name << ',' << Size << ',' << Align;
962 } else if (!GVar->hasCommonLinkage()) {
963 O << "\t.globl " << name << '\n'
964 << MAI->getWeakDefDirective() << name << '\n';
965 EmitAlignment(Align, GVar);
968 O << "\t\t\t\t" << MAI->getCommentString() << " ";
969 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
972 EmitGlobalConstant(C);
975 O << ".comm " << name << ',' << Size;
976 // Darwin 9 and above support aligned common data.
977 if (Subtarget.isDarwin9())
981 O << "\t\t" << MAI->getCommentString() << " '";
982 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
989 switch (GVar->getLinkage()) {
990 case GlobalValue::LinkOnceAnyLinkage:
991 case GlobalValue::LinkOnceODRLinkage:
992 case GlobalValue::WeakAnyLinkage:
993 case GlobalValue::WeakODRLinkage:
994 case GlobalValue::CommonLinkage:
995 case GlobalValue::LinkerPrivateLinkage:
996 O << "\t.globl " << name << '\n'
997 << "\t.weak_definition " << name << '\n';
999 case GlobalValue::AppendingLinkage:
1000 // FIXME: appending linkage variables should go into a section of
1001 // their name or something. For now, just emit them as external.
1002 case GlobalValue::ExternalLinkage:
1003 // If external or appending, declare as a global symbol
1004 O << "\t.globl " << name << '\n';
1006 case GlobalValue::InternalLinkage:
1007 case GlobalValue::PrivateLinkage:
1010 llvm_unreachable("Unknown linkage type!");
1013 EmitAlignment(Align, GVar);
1016 O << "\t\t\t\t" << MAI->getCommentString() << " '";
1017 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1022 EmitGlobalConstant(C);
1026 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
1027 const TargetData *TD = TM.getTargetData();
1029 bool isPPC64 = TD->getPointerSizeInBits() == 64;
1031 // Darwin/PPC always uses mach-o.
1032 TargetLoweringObjectFileMachO &TLOFMacho =
1033 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
1036 const MCSection *LSPSection = 0;
1037 if (!FnStubs.empty()) // .lazy_symbol_pointer
1038 LSPSection = TLOFMacho.getLazySymbolPointerSection();
1041 // Output stubs for dynamically-linked functions
1042 if (TM.getRelocationModel() == Reloc::PIC_ && !FnStubs.empty()) {
1043 const MCSection *StubSection =
1044 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
1045 MCSectionMachO::S_SYMBOL_STUBS |
1046 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1047 32, SectionKind::getText());
1048 for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1050 OutStreamer.SwitchSection(StubSection);
1052 const FnStubInfo &Info = I->second;
1053 O << Info.Stub << ":\n";
1054 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1056 O << "\tbcl 20,31," << Info.AnonSymbol << '\n';
1057 O << Info.AnonSymbol << ":\n";
1058 O << "\tmflr r11\n";
1059 O << "\taddis r11,r11,ha16(" << Info.LazyPtr << "-" << Info.AnonSymbol;
1062 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1063 O << Info.LazyPtr << "-" << Info.AnonSymbol << ")(r11)\n";
1064 O << "\tmtctr r12\n";
1067 OutStreamer.SwitchSection(LSPSection);
1068 O << Info.LazyPtr << ":\n";
1069 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1070 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1072 } else if (!FnStubs.empty()) {
1073 const MCSection *StubSection =
1074 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
1075 MCSectionMachO::S_SYMBOL_STUBS |
1076 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1077 16, SectionKind::getText());
1079 for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1081 OutStreamer.SwitchSection(StubSection);
1083 const FnStubInfo &Info = I->second;
1084 O << Info.Stub << ":\n";
1085 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1086 O << "\tlis r11,ha16(" << Info.LazyPtr << ")\n";
1087 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1088 O << Info.LazyPtr << ")(r11)\n";
1089 O << "\tmtctr r12\n";
1091 OutStreamer.SwitchSection(LSPSection);
1092 O << Info.LazyPtr << ":\n";
1093 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1094 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1100 if (MAI->doesSupportExceptionHandling() && MMI) {
1101 // Add the (possibly multiple) personalities to the set of global values.
1102 // Only referenced functions get into the Personalities list.
1103 const std::vector<Function *> &Personalities = MMI->getPersonalities();
1104 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1105 E = Personalities.end(); I != E; ++I) {
1107 GVStubs[Mang->getMangledName(*I)] =
1108 Mang->getMangledName(*I, "$non_lazy_ptr", true);
1112 // Output macho stubs for external and common global variables.
1113 if (!GVStubs.empty()) {
1114 // Switch with ".non_lazy_symbol_pointer" directive.
1115 OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
1116 EmitAlignment(isPPC64 ? 3 : 2);
1118 for (StringMap<std::string>::iterator I = GVStubs.begin(),
1119 E = GVStubs.end(); I != E; ++I) {
1120 O << I->second << ":\n";
1121 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1122 O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
1126 if (!HiddenGVStubs.empty()) {
1127 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
1128 EmitAlignment(isPPC64 ? 3 : 2);
1129 for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
1130 E = HiddenGVStubs.end(); I != E; ++I) {
1131 O << I->second << ":\n";
1132 O << (isPPC64 ? "\t.quad\t" : "\t.long\t") << I->getKeyData() << '\n';
1136 // Funny Darwin hack: This flag tells the linker that no global symbols
1137 // contain code that falls through to other global symbols (e.g. the obvious
1138 // implementation of multiple entry points). If this doesn't occur, the
1139 // linker can safely perform dead code stripping. Since LLVM never generates
1140 // code that does this, it is always safe to set.
1141 OutStreamer.EmitAssemblerFlag(MCStreamer::SubsectionsViaSymbols);
1143 return AsmPrinter::doFinalization(M);
1148 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1149 /// for a MachineFunction to the given output stream, in a format that the
1150 /// Darwin assembler can deal with.
1152 static AsmPrinter *createPPCAsmPrinterPass(formatted_raw_ostream &o,
1154 const MCAsmInfo *tai,
1156 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1158 if (Subtarget->isDarwin())
1159 return new PPCDarwinAsmPrinter(o, tm, tai, verbose);
1160 return new PPCLinuxAsmPrinter(o, tm, tai, verbose);
1163 // Force static initialization.
1164 extern "C" void LLVMInitializePowerPCAsmPrinter() {
1165 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
1166 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);