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/MCSectionMachO.h"
35 #include "llvm/Target/TargetAsmInfo.h"
36 #include "llvm/Target/TargetLoweringObjectFile.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/Target/TargetRegistry.h"
41 #include "llvm/Support/Mangler.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/Compiler.h"
47 #include "llvm/Support/FormattedStream.h"
48 #include "llvm/ADT/Statistic.h"
49 #include "llvm/ADT/StringExtras.h"
50 #include "llvm/ADT/StringSet.h"
53 STATISTIC(EmittedInsts, "Number of machine instrs printed");
56 class VISIBILITY_HIDDEN PPCAsmPrinter : public AsmPrinter {
59 std::string Stub, LazyPtr, AnonSymbol;
63 void Init(const GlobalValue *GV, Mangler *Mang) {
64 // Already initialized.
65 if (!Stub.empty()) return;
66 Stub = Mang->getMangledName(GV, "$stub", true);
67 LazyPtr = Mang->getMangledName(GV, "$lazy_ptr", true);
68 AnonSymbol = Mang->getMangledName(GV, "$stub$tmp", true);
71 void Init(const std::string &GV, Mangler *Mang) {
72 // Already initialized.
73 if (!Stub.empty()) return;
74 Stub = Mang->makeNameProper(GV + "$stub",
76 LazyPtr = Mang->makeNameProper(GV + "$lazy_ptr",
78 AnonSymbol = Mang->makeNameProper(GV + "$stub$tmp",
83 StringMap<FnStubInfo> FnStubs;
84 StringMap<std::string> GVStubs, HiddenGVStubs, TOC;
85 const PPCSubtarget &Subtarget;
88 explicit PPCAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
89 const TargetAsmInfo *T, bool V)
90 : AsmPrinter(O, TM, T, V),
91 Subtarget(TM.getSubtarget<PPCSubtarget>()), LabelID(0) {}
93 virtual const char *getPassName() const {
94 return "PowerPC Assembly Printer";
97 PPCTargetMachine &getTM() {
98 return static_cast<PPCTargetMachine&>(TM);
101 unsigned enumRegToMachineReg(unsigned enumReg) {
103 default: llvm_unreachable("Unhandled register!");
104 case PPC::CR0: return 0;
105 case PPC::CR1: return 1;
106 case PPC::CR2: return 2;
107 case PPC::CR3: return 3;
108 case PPC::CR4: return 4;
109 case PPC::CR5: return 5;
110 case PPC::CR6: return 6;
111 case PPC::CR7: return 7;
116 /// printInstruction - This method is automatically generated by tablegen
117 /// from the instruction set description. This method returns true if the
118 /// machine instruction was sufficiently described to print it, otherwise it
120 void printInstruction(const MachineInstr *MI);
122 void printMachineInstruction(const MachineInstr *MI);
123 void printOp(const MachineOperand &MO);
125 /// stripRegisterPrefix - This method strips the character prefix from a
126 /// register name so that only the number is left. Used by for linux asm.
127 const char *stripRegisterPrefix(const char *RegName) {
128 switch (RegName[0]) {
131 case 'v': return RegName + 1;
132 case 'c': if (RegName[1] == 'r') return RegName + 2;
138 /// printRegister - Print register according to target requirements.
140 void printRegister(const MachineOperand &MO, bool R0AsZero) {
141 unsigned RegNo = MO.getReg();
142 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
144 // If we should use 0 for R0.
145 if (R0AsZero && RegNo == PPC::R0) {
150 const char *RegName = TM.getRegisterInfo()->get(RegNo).AsmName;
151 // Linux assembler (Others?) does not take register mnemonics.
152 // FIXME - What about special registers used in mfspr/mtspr?
153 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
157 void printOperand(const MachineInstr *MI, unsigned OpNo) {
158 const MachineOperand &MO = MI->getOperand(OpNo);
160 printRegister(MO, false);
161 } else if (MO.isImm()) {
168 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
169 unsigned AsmVariant, const char *ExtraCode);
170 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
171 unsigned AsmVariant, const char *ExtraCode);
174 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
175 char value = MI->getOperand(OpNo).getImm();
176 value = (value << (32-5)) >> (32-5);
179 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
180 unsigned char value = MI->getOperand(OpNo).getImm();
181 assert(value <= 31 && "Invalid u5imm argument!");
182 O << (unsigned int)value;
184 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
185 unsigned char value = MI->getOperand(OpNo).getImm();
186 assert(value <= 63 && "Invalid u6imm argument!");
187 O << (unsigned int)value;
189 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
190 O << (short)MI->getOperand(OpNo).getImm();
192 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
193 O << (unsigned short)MI->getOperand(OpNo).getImm();
195 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
196 if (MI->getOperand(OpNo).isImm()) {
197 O << (short)(MI->getOperand(OpNo).getImm()*4);
200 printOp(MI->getOperand(OpNo));
201 if (TM.getRelocationModel() == Reloc::PIC_)
202 O << "-\"L" << getFunctionNumber() << "$pb\")";
207 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
208 // Branches can take an immediate operand. This is used by the branch
209 // selection pass to print $+8, an eight byte displacement from the PC.
210 if (MI->getOperand(OpNo).isImm()) {
211 O << "$+" << MI->getOperand(OpNo).getImm()*4;
213 printOp(MI->getOperand(OpNo));
216 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
217 const MachineOperand &MO = MI->getOperand(OpNo);
218 if (TM.getRelocationModel() != Reloc::Static) {
219 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
220 GlobalValue *GV = MO.getGlobal();
221 if (GV->isDeclaration() || GV->isWeakForLinker()) {
222 // Dynamically-resolved functions need a stub for the function.
223 FnStubInfo &FnInfo = FnStubs[Mang->getMangledName(GV)];
224 FnInfo.Init(GV, Mang);
229 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
230 FnStubInfo &FnInfo =FnStubs[Mang->makeNameProper(MO.getSymbolName())];
231 FnInfo.Init(MO.getSymbolName(), Mang);
237 printOp(MI->getOperand(OpNo));
239 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
240 O << (int)MI->getOperand(OpNo).getImm()*4;
242 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
243 O << "\"L" << getFunctionNumber() << "$pb\"\n";
244 O << "\"L" << getFunctionNumber() << "$pb\":";
246 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
247 if (MI->getOperand(OpNo).isImm()) {
248 printS16ImmOperand(MI, OpNo);
250 if (Subtarget.isDarwin()) O << "ha16(";
251 printOp(MI->getOperand(OpNo));
252 if (TM.getRelocationModel() == Reloc::PIC_)
253 O << "-\"L" << getFunctionNumber() << "$pb\"";
254 if (Subtarget.isDarwin())
260 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
261 if (MI->getOperand(OpNo).isImm()) {
262 printS16ImmOperand(MI, OpNo);
264 if (Subtarget.isDarwin()) O << "lo16(";
265 printOp(MI->getOperand(OpNo));
266 if (TM.getRelocationModel() == Reloc::PIC_)
267 O << "-\"L" << getFunctionNumber() << "$pb\"";
268 if (Subtarget.isDarwin())
274 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
275 unsigned CCReg = MI->getOperand(OpNo).getReg();
276 unsigned RegNo = enumRegToMachineReg(CCReg);
277 O << (0x80 >> RegNo);
279 // The new addressing mode printers.
280 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
281 printSymbolLo(MI, OpNo);
283 if (MI->getOperand(OpNo+1).isReg() &&
284 MI->getOperand(OpNo+1).getReg() == PPC::R0)
287 printOperand(MI, OpNo+1);
290 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
291 if (MI->getOperand(OpNo).isImm())
292 printS16X4ImmOperand(MI, OpNo);
294 printSymbolLo(MI, OpNo);
296 if (MI->getOperand(OpNo+1).isReg() &&
297 MI->getOperand(OpNo+1).getReg() == PPC::R0)
300 printOperand(MI, OpNo+1);
304 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
305 // When used as the base register, r0 reads constant zero rather than
306 // the value contained in the register. For this reason, the darwin
307 // assembler requires that we print r0 as 0 (no r) when used as the base.
308 const MachineOperand &MO = MI->getOperand(OpNo);
309 printRegister(MO, true);
311 printOperand(MI, OpNo+1);
314 void printTOCEntryLabel(const MachineInstr *MI, unsigned OpNo) {
315 const MachineOperand &MO = MI->getOperand(OpNo);
317 assert(MO.getType() == MachineOperand::MO_GlobalAddress);
319 GlobalValue *GV = MO.getGlobal();
321 std::string Name = Mang->getMangledName(GV);
323 // Map symbol -> label of TOC entry.
324 if (TOC.count(Name) == 0) {
326 Label += TAI->getPrivateGlobalPrefix();
328 Label += utostr(LabelID++);
333 O << TOC[Name] << "@toc";
336 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
337 const char *Modifier);
339 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
341 virtual void EmitExternalGlobal(const GlobalVariable *GV);
344 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
345 class VISIBILITY_HIDDEN PPCLinuxAsmPrinter : public PPCAsmPrinter {
347 explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
348 const TargetAsmInfo *T, bool V)
349 : PPCAsmPrinter(O, TM, T, V){}
351 virtual const char *getPassName() const {
352 return "Linux PPC Assembly Printer";
355 bool runOnMachineFunction(MachineFunction &F);
356 bool doFinalization(Module &M);
358 void getAnalysisUsage(AnalysisUsage &AU) const {
359 AU.setPreservesAll();
360 AU.addRequired<MachineModuleInfo>();
361 AU.addRequired<DwarfWriter>();
362 PPCAsmPrinter::getAnalysisUsage(AU);
365 void PrintGlobalVariable(const GlobalVariable *GVar);
368 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
370 class VISIBILITY_HIDDEN PPCDarwinAsmPrinter : public PPCAsmPrinter {
371 formatted_raw_ostream &OS;
373 explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
374 const TargetAsmInfo *T, bool V)
375 : PPCAsmPrinter(O, TM, T, V), OS(O) {}
377 virtual const char *getPassName() const {
378 return "Darwin PPC Assembly Printer";
381 bool runOnMachineFunction(MachineFunction &F);
382 bool doInitialization(Module &M);
383 bool doFinalization(Module &M);
385 void getAnalysisUsage(AnalysisUsage &AU) const {
386 AU.setPreservesAll();
387 AU.addRequired<MachineModuleInfo>();
388 AU.addRequired<DwarfWriter>();
389 PPCAsmPrinter::getAnalysisUsage(AU);
392 void PrintGlobalVariable(const GlobalVariable *GVar);
394 } // end of anonymous namespace
396 // Include the auto-generated portion of the assembly writer
397 #include "PPCGenAsmWriter.inc"
399 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
400 switch (MO.getType()) {
401 case MachineOperand::MO_Immediate:
402 llvm_unreachable("printOp() does not handle immediate values");
404 case MachineOperand::MO_MachineBasicBlock:
405 printBasicBlockLabel(MO.getMBB());
407 case MachineOperand::MO_JumpTableIndex:
408 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
409 << '_' << MO.getIndex();
410 // FIXME: PIC relocation model
412 case MachineOperand::MO_ConstantPoolIndex:
413 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
414 << '_' << MO.getIndex();
416 case MachineOperand::MO_ExternalSymbol: {
417 // Computing the address of an external symbol, not calling it.
418 std::string Name(TAI->getGlobalPrefix());
419 Name += MO.getSymbolName();
421 if (TM.getRelocationModel() != Reloc::Static) {
422 GVStubs[Name] = Name+"$non_lazy_ptr";
423 Name += "$non_lazy_ptr";
428 case MachineOperand::MO_GlobalAddress: {
429 // Computing the address of a global symbol, not calling it.
430 GlobalValue *GV = MO.getGlobal();
433 // External or weakly linked global variables need non-lazily-resolved stubs
434 if (TM.getRelocationModel() != Reloc::Static &&
435 (GV->isDeclaration() || GV->isWeakForLinker())) {
436 if (!GV->hasHiddenVisibility()) {
437 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
438 GVStubs[Mang->getMangledName(GV)] = Name;
439 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
440 GV->hasAvailableExternallyLinkage()) {
441 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
442 HiddenGVStubs[Mang->getMangledName(GV)] = Name;
444 Name = Mang->getMangledName(GV);
447 Name = Mang->getMangledName(GV);
451 printOffset(MO.getOffset());
456 O << "<unknown operand type: " << MO.getType() << ">";
461 /// EmitExternalGlobal - In this case we need to use the indirect symbol.
463 void PPCAsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
466 if (TM.getRelocationModel() != Reloc::Static) {
467 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
469 Name = Mang->getMangledName(GV);
474 /// PrintAsmOperand - Print out an operand for an inline asm expression.
476 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
478 const char *ExtraCode) {
479 // Does this asm operand have a single letter operand modifier?
480 if (ExtraCode && ExtraCode[0]) {
481 if (ExtraCode[1] != 0) return true; // Unknown modifier.
483 switch (ExtraCode[0]) {
484 default: return true; // Unknown modifier.
485 case 'c': // Don't print "$" before a global var name or constant.
486 // PPC never has a prefix.
487 printOperand(MI, OpNo);
489 case 'L': // Write second word of DImode reference.
490 // Verify that this operand has two consecutive registers.
491 if (!MI->getOperand(OpNo).isReg() ||
492 OpNo+1 == MI->getNumOperands() ||
493 !MI->getOperand(OpNo+1).isReg())
495 ++OpNo; // Return the high-part.
498 // Write 'i' if an integer constant, otherwise nothing. Used to print
500 if (MI->getOperand(OpNo).isImm())
506 printOperand(MI, OpNo);
510 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
512 const char *ExtraCode) {
513 if (ExtraCode && ExtraCode[0])
514 return true; // Unknown modifier.
515 if (MI->getOperand(OpNo).isReg())
516 printMemRegReg(MI, OpNo);
518 printMemRegImm(MI, OpNo);
522 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
523 const char *Modifier) {
524 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
525 unsigned Code = MI->getOperand(OpNo).getImm();
526 if (!strcmp(Modifier, "cc")) {
527 switch ((PPC::Predicate)Code) {
528 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
529 case PPC::PRED_LT: O << "lt"; return;
530 case PPC::PRED_LE: O << "le"; return;
531 case PPC::PRED_EQ: O << "eq"; return;
532 case PPC::PRED_GE: O << "ge"; return;
533 case PPC::PRED_GT: O << "gt"; return;
534 case PPC::PRED_NE: O << "ne"; return;
535 case PPC::PRED_UN: O << "un"; return;
536 case PPC::PRED_NU: O << "nu"; return;
540 assert(!strcmp(Modifier, "reg") &&
541 "Need to specify 'cc' or 'reg' as predicate op modifier!");
542 // Don't print the register for 'always'.
543 if (Code == PPC::PRED_ALWAYS) return;
544 printOperand(MI, OpNo+1);
549 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
550 /// the current output stream.
552 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
555 // Check for slwi/srwi mnemonics.
556 if (MI->getOpcode() == PPC::RLWINM) {
557 bool FoundMnemonic = false;
558 unsigned char SH = MI->getOperand(2).getImm();
559 unsigned char MB = MI->getOperand(3).getImm();
560 unsigned char ME = MI->getOperand(4).getImm();
561 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
562 O << "\tslwi "; FoundMnemonic = true;
564 if (SH <= 31 && MB == (32-SH) && ME == 31) {
565 O << "\tsrwi "; FoundMnemonic = true;
572 O << ", " << (unsigned int)SH << '\n';
575 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
576 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
584 } else if (MI->getOpcode() == PPC::RLDICR) {
585 unsigned char SH = MI->getOperand(2).getImm();
586 unsigned char ME = MI->getOperand(3).getImm();
587 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
593 O << ", " << (unsigned int)SH << '\n';
598 printInstruction(MI);
601 /// runOnMachineFunction - This uses the printMachineInstruction()
602 /// method to print assembly for each instruction.
604 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
607 SetupMachineFunction(MF);
610 // Print out constants referenced by the function
611 EmitConstantPool(MF.getConstantPool());
613 // Print out labels for the function.
614 const Function *F = MF.getFunction();
615 SwitchToSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
617 switch (F->getLinkage()) {
618 default: llvm_unreachable("Unknown linkage type!");
619 case Function::PrivateLinkage:
620 case Function::LinkerPrivateLinkage:
621 case Function::InternalLinkage: // Symbols default to internal.
623 case Function::ExternalLinkage:
624 O << "\t.global\t" << CurrentFnName << '\n'
625 << "\t.type\t" << CurrentFnName << ", @function\n";
627 case Function::WeakAnyLinkage:
628 case Function::WeakODRLinkage:
629 case Function::LinkOnceAnyLinkage:
630 case Function::LinkOnceODRLinkage:
631 O << "\t.global\t" << CurrentFnName << '\n';
632 O << "\t.weak\t" << CurrentFnName << '\n';
636 printVisibility(CurrentFnName, F->getVisibility());
638 EmitAlignment(MF.getAlignment(), F);
640 if (Subtarget.isPPC64()) {
641 // Emit an official procedure descriptor.
642 // FIXME 64-bit SVR4: Use MCSection here?
643 O << "\t.section\t\".opd\",\"aw\"\n";
645 O << CurrentFnName << ":\n";
646 O << "\t.quad .L." << CurrentFnName << ",.TOC.@tocbase\n";
647 O << "\t.previous\n";
648 O << ".L." << CurrentFnName << ":\n";
650 O << CurrentFnName << ":\n";
653 // Emit pre-function debug information.
654 DW->BeginFunction(&MF);
656 // Print out code for the function.
657 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
659 // Print a label for the basic block.
660 if (I != MF.begin()) {
661 printBasicBlockLabel(I, true, true);
664 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
666 // Print the assembly for the instruction.
667 printMachineInstruction(II);
671 O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << '\n';
673 // Print out jump tables referenced by the function.
674 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
676 SwitchToSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
678 // Emit post-function debug information.
679 DW->EndFunction(&MF);
681 // We didn't modify anything.
685 void PPCLinuxAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
686 const TargetData *TD = TM.getTargetData();
688 if (!GVar->hasInitializer())
689 return; // External global require no code
691 // Check to see if this is a special global used by LLVM, if so, emit it.
692 if (EmitSpecialLLVMGlobal(GVar))
695 std::string name = Mang->getMangledName(GVar);
697 printVisibility(name, GVar->getVisibility());
699 Constant *C = GVar->getInitializer();
700 const Type *Type = C->getType();
701 unsigned Size = TD->getTypeAllocSize(Type);
702 unsigned Align = TD->getPreferredAlignmentLog(GVar);
704 SwitchToSection(getObjFileLowering().SectionForGlobal(GVar, Mang, TM));
706 if (C->isNullValue() && /* FIXME: Verify correct */
707 !GVar->hasSection() &&
708 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
709 GVar->isWeakForLinker())) {
710 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
712 if (GVar->hasExternalLinkage()) {
713 O << "\t.global " << name << '\n';
714 O << "\t.type " << name << ", @object\n";
716 O << "\t.zero " << Size << '\n';
717 } else if (GVar->hasLocalLinkage()) {
718 O << TAI->getLCOMMDirective() << name << ',' << Size;
720 O << ".comm " << name << ',' << Size;
723 O << "\t\t" << TAI->getCommentString() << " '";
724 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
731 switch (GVar->getLinkage()) {
732 case GlobalValue::LinkOnceAnyLinkage:
733 case GlobalValue::LinkOnceODRLinkage:
734 case GlobalValue::WeakAnyLinkage:
735 case GlobalValue::WeakODRLinkage:
736 case GlobalValue::CommonLinkage:
737 O << "\t.global " << name << '\n'
738 << "\t.type " << name << ", @object\n"
739 << "\t.weak " << name << '\n';
741 case GlobalValue::AppendingLinkage:
742 // FIXME: appending linkage variables should go into a section of
743 // their name or something. For now, just emit them as external.
744 case GlobalValue::ExternalLinkage:
745 // If external or appending, declare as a global symbol
746 O << "\t.global " << name << '\n'
747 << "\t.type " << name << ", @object\n";
749 case GlobalValue::InternalLinkage:
750 case GlobalValue::PrivateLinkage:
751 case GlobalValue::LinkerPrivateLinkage:
754 llvm_unreachable("Unknown linkage type!");
757 EmitAlignment(Align, GVar);
760 O << "\t\t\t\t" << TAI->getCommentString() << " '";
761 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
766 EmitGlobalConstant(C);
770 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
771 const TargetData *TD = TM.getTargetData();
773 bool isPPC64 = TD->getPointerSizeInBits() == 64;
775 if (isPPC64 && !TOC.empty()) {
776 // FIXME 64-bit SVR4: Use MCSection here?
777 O << "\t.section\t\".toc\",\"aw\"\n";
779 for (StringMap<std::string>::iterator I = TOC.begin(), E = TOC.end();
781 O << I->second << ":\n";
782 O << "\t.tc " << I->getKeyData() << "[TC]," << I->getKeyData() << '\n';
786 return AsmPrinter::doFinalization(M);
789 /// runOnMachineFunction - This uses the printMachineInstruction()
790 /// method to print assembly for each instruction.
792 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
795 SetupMachineFunction(MF);
798 // Print out constants referenced by the function
799 EmitConstantPool(MF.getConstantPool());
801 // Print out labels for the function.
802 const Function *F = MF.getFunction();
803 SwitchToSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
805 switch (F->getLinkage()) {
806 default: llvm_unreachable("Unknown linkage type!");
807 case Function::PrivateLinkage:
808 case Function::LinkerPrivateLinkage:
809 case Function::InternalLinkage: // Symbols default to internal.
811 case Function::ExternalLinkage:
812 O << "\t.globl\t" << CurrentFnName << '\n';
814 case Function::WeakAnyLinkage:
815 case Function::WeakODRLinkage:
816 case Function::LinkOnceAnyLinkage:
817 case Function::LinkOnceODRLinkage:
818 O << "\t.globl\t" << CurrentFnName << '\n';
819 O << "\t.weak_definition\t" << CurrentFnName << '\n';
823 printVisibility(CurrentFnName, F->getVisibility());
825 EmitAlignment(MF.getAlignment(), F);
826 O << CurrentFnName << ":\n";
828 // Emit pre-function debug information.
829 DW->BeginFunction(&MF);
831 // If the function is empty, then we need to emit *something*. Otherwise, the
832 // function's label might be associated with something that it wasn't meant to
833 // be associated with. We emit a noop in this situation.
834 MachineFunction::iterator I = MF.begin();
836 if (++I == MF.end() && MF.front().empty())
839 // Print out code for the function.
840 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
842 // Print a label for the basic block.
843 if (I != MF.begin()) {
844 printBasicBlockLabel(I, true, true, VerboseAsm);
847 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
849 // Print the assembly for the instruction.
850 printMachineInstruction(II);
854 // Print out jump tables referenced by the function.
855 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
857 // Emit post-function debug information.
858 DW->EndFunction(&MF);
860 // We didn't modify anything.
865 bool PPCDarwinAsmPrinter::doInitialization(Module &M) {
866 static const char *const CPUDirectives[] = {
878 unsigned Directive = Subtarget.getDarwinDirective();
879 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
880 Directive = PPC::DIR_970;
881 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
882 Directive = PPC::DIR_7400;
883 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
884 Directive = PPC::DIR_64;
885 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
886 O << "\t.machine " << CPUDirectives[Directive] << '\n';
888 bool Result = AsmPrinter::doInitialization(M);
891 // Prime text sections so they are adjacent. This reduces the likelihood a
892 // large data or debug section causes a branch to exceed 16M limit.
893 TargetLoweringObjectFileMachO &TLOFMacho =
894 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
895 SwitchToSection(TLOFMacho.getTextCoalSection());
896 if (TM.getRelocationModel() == Reloc::PIC_) {
897 SwitchToSection(TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
898 MCSectionMachO::S_SYMBOL_STUBS |
899 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
900 32, SectionKind::getText()));
901 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
902 SwitchToSection(TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
903 MCSectionMachO::S_SYMBOL_STUBS |
904 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
905 16, SectionKind::getText()));
907 SwitchToSection(getObjFileLowering().getTextSection());
912 void PPCDarwinAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
913 const TargetData *TD = TM.getTargetData();
915 if (!GVar->hasInitializer())
916 return; // External global require no code
918 // Check to see if this is a special global used by LLVM, if so, emit it.
919 if (EmitSpecialLLVMGlobal(GVar)) {
920 if (TM.getRelocationModel() == Reloc::Static) {
921 if (GVar->getName() == "llvm.global_ctors")
922 O << ".reference .constructors_used\n";
923 else if (GVar->getName() == "llvm.global_dtors")
924 O << ".reference .destructors_used\n";
929 std::string name = Mang->getMangledName(GVar);
930 printVisibility(name, GVar->getVisibility());
932 Constant *C = GVar->getInitializer();
933 const Type *Type = C->getType();
934 unsigned Size = TD->getTypeAllocSize(Type);
935 unsigned Align = TD->getPreferredAlignmentLog(GVar);
937 const MCSection *TheSection =
938 getObjFileLowering().SectionForGlobal(GVar, Mang, TM);
939 SwitchToSection(TheSection);
941 /// FIXME: Drive this off the section!
942 if (C->isNullValue() && /* FIXME: Verify correct */
943 !GVar->hasSection() &&
944 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
945 GVar->isWeakForLinker()) &&
946 // Don't put things that should go in the cstring section into "comm".
947 !TheSection->getKind().isMergeableCString()) {
948 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
950 if (GVar->hasExternalLinkage()) {
951 O << "\t.globl " << name << '\n';
952 O << "\t.zerofill __DATA, __common, " << name << ", "
953 << Size << ", " << Align;
954 } else if (GVar->hasLocalLinkage()) {
955 O << TAI->getLCOMMDirective() << name << ',' << Size << ',' << Align;
956 } else if (!GVar->hasCommonLinkage()) {
957 O << "\t.globl " << name << '\n'
958 << TAI->getWeakDefDirective() << name << '\n';
959 EmitAlignment(Align, GVar);
962 O << "\t\t\t\t" << TAI->getCommentString() << " ";
963 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
966 EmitGlobalConstant(C);
969 O << ".comm " << name << ',' << Size;
970 // Darwin 9 and above support aligned common data.
971 if (Subtarget.isDarwin9())
975 O << "\t\t" << TAI->getCommentString() << " '";
976 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
983 switch (GVar->getLinkage()) {
984 case GlobalValue::LinkOnceAnyLinkage:
985 case GlobalValue::LinkOnceODRLinkage:
986 case GlobalValue::WeakAnyLinkage:
987 case GlobalValue::WeakODRLinkage:
988 case GlobalValue::CommonLinkage:
989 O << "\t.globl " << name << '\n'
990 << "\t.weak_definition " << name << '\n';
992 case GlobalValue::AppendingLinkage:
993 // FIXME: appending linkage variables should go into a section of
994 // their name or something. For now, just emit them as external.
995 case GlobalValue::ExternalLinkage:
996 // If external or appending, declare as a global symbol
997 O << "\t.globl " << name << '\n';
999 case GlobalValue::InternalLinkage:
1000 case GlobalValue::PrivateLinkage:
1001 case GlobalValue::LinkerPrivateLinkage:
1004 llvm_unreachable("Unknown linkage type!");
1007 EmitAlignment(Align, GVar);
1010 O << "\t\t\t\t" << TAI->getCommentString() << " '";
1011 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1016 EmitGlobalConstant(C);
1020 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
1021 const TargetData *TD = TM.getTargetData();
1023 bool isPPC64 = TD->getPointerSizeInBits() == 64;
1025 // Darwin/PPC always uses mach-o.
1026 TargetLoweringObjectFileMachO &TLOFMacho =
1027 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
1030 const MCSection *LSPSection = 0;
1031 if (!FnStubs.empty()) // .lazy_symbol_pointer
1032 LSPSection = TLOFMacho.getLazySymbolPointerSection();
1035 // Output stubs for dynamically-linked functions
1036 if (TM.getRelocationModel() == Reloc::PIC_ && !FnStubs.empty()) {
1037 const MCSection *StubSection =
1038 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
1039 MCSectionMachO::S_SYMBOL_STUBS |
1040 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1041 32, SectionKind::getText());
1042 for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1044 SwitchToSection(StubSection);
1046 const FnStubInfo &Info = I->second;
1047 O << Info.Stub << ":\n";
1048 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1050 O << "\tbcl 20,31," << Info.AnonSymbol << '\n';
1051 O << Info.AnonSymbol << ":\n";
1052 O << "\tmflr r11\n";
1053 O << "\taddis r11,r11,ha16(" << Info.LazyPtr << "-" << Info.AnonSymbol;
1056 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1057 O << Info.LazyPtr << "-" << Info.AnonSymbol << ")(r11)\n";
1058 O << "\tmtctr r12\n";
1061 SwitchToSection(LSPSection);
1062 O << Info.LazyPtr << ":\n";
1063 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1064 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1066 } else if (!FnStubs.empty()) {
1067 const MCSection *StubSection =
1068 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
1069 MCSectionMachO::S_SYMBOL_STUBS |
1070 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1071 16, SectionKind::getText());
1073 for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1075 SwitchToSection(StubSection);
1077 const FnStubInfo &Info = I->second;
1078 O << Info.Stub << ":\n";
1079 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1080 O << "\tlis r11,ha16(" << Info.LazyPtr << ")\n";
1081 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1082 O << Info.LazyPtr << ")(r11)\n";
1083 O << "\tmtctr r12\n";
1085 SwitchToSection(LSPSection);
1086 O << Info.LazyPtr << ":\n";
1087 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1088 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1094 if (TAI->doesSupportExceptionHandling() && MMI) {
1095 // Add the (possibly multiple) personalities to the set of global values.
1096 // Only referenced functions get into the Personalities list.
1097 const std::vector<Function *> &Personalities = MMI->getPersonalities();
1098 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1099 E = Personalities.end(); I != E; ++I) {
1101 GVStubs[Mang->getMangledName(*I)] =
1102 Mang->getMangledName(*I, "$non_lazy_ptr", true);
1106 // Output macho stubs for external and common global variables.
1107 if (!GVStubs.empty()) {
1108 // Switch with ".non_lazy_symbol_pointer" directive.
1109 SwitchToSection(TLOFMacho.getNonLazySymbolPointerSection());
1110 EmitAlignment(isPPC64 ? 3 : 2);
1112 for (StringMap<std::string>::iterator I = GVStubs.begin(),
1113 E = GVStubs.end(); I != E; ++I) {
1114 O << I->second << ":\n";
1115 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1116 O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
1120 if (!HiddenGVStubs.empty()) {
1121 SwitchToSection(getObjFileLowering().getDataSection());
1122 EmitAlignment(isPPC64 ? 3 : 2);
1123 for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
1124 E = HiddenGVStubs.end(); I != E; ++I) {
1125 O << I->second << ":\n";
1126 O << (isPPC64 ? "\t.quad\t" : "\t.long\t") << I->getKeyData() << '\n';
1130 // Funny Darwin hack: This flag tells the linker that no global symbols
1131 // contain code that falls through to other global symbols (e.g. the obvious
1132 // implementation of multiple entry points). If this doesn't occur, the
1133 // linker can safely perform dead code stripping. Since LLVM never generates
1134 // code that does this, it is always safe to set.
1135 O << "\t.subsections_via_symbols\n";
1137 return AsmPrinter::doFinalization(M);
1142 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1143 /// for a MachineFunction to the given output stream, in a format that the
1144 /// Darwin assembler can deal with.
1146 static AsmPrinter *createPPCAsmPrinterPass(formatted_raw_ostream &o,
1148 const TargetAsmInfo *tai,
1150 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1152 if (Subtarget->isDarwin())
1153 return new PPCDarwinAsmPrinter(o, tm, tai, verbose);
1154 return new PPCLinuxAsmPrinter(o, tm, tai, verbose);
1157 // Force static initialization.
1158 extern "C" void LLVMInitializePowerPCAsmPrinter() {
1159 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
1160 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);