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;
85 const PPCSubtarget &Subtarget;
87 explicit PPCAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
88 const TargetAsmInfo *T, bool V)
89 : AsmPrinter(O, TM, T, V),
90 Subtarget(TM.getSubtarget<PPCSubtarget>()) {}
92 virtual const char *getPassName() const {
93 return "PowerPC Assembly Printer";
96 PPCTargetMachine &getTM() {
97 return static_cast<PPCTargetMachine&>(TM);
100 unsigned enumRegToMachineReg(unsigned enumReg) {
102 default: llvm_unreachable("Unhandled register!");
103 case PPC::CR0: return 0;
104 case PPC::CR1: return 1;
105 case PPC::CR2: return 2;
106 case PPC::CR3: return 3;
107 case PPC::CR4: return 4;
108 case PPC::CR5: return 5;
109 case PPC::CR6: return 6;
110 case PPC::CR7: return 7;
115 /// printInstruction - This method is automatically generated by tablegen
116 /// from the instruction set description. This method returns true if the
117 /// machine instruction was sufficiently described to print it, otherwise it
119 void printInstruction(const MachineInstr *MI);
121 void printMachineInstruction(const MachineInstr *MI);
122 void printOp(const MachineOperand &MO);
124 /// stripRegisterPrefix - This method strips the character prefix from a
125 /// register name so that only the number is left. Used by for linux asm.
126 const char *stripRegisterPrefix(const char *RegName) {
127 switch (RegName[0]) {
130 case 'v': return RegName + 1;
131 case 'c': if (RegName[1] == 'r') return RegName + 2;
137 /// printRegister - Print register according to target requirements.
139 void printRegister(const MachineOperand &MO, bool R0AsZero) {
140 unsigned RegNo = MO.getReg();
141 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
143 // If we should use 0 for R0.
144 if (R0AsZero && RegNo == PPC::R0) {
149 const char *RegName = TM.getRegisterInfo()->get(RegNo).AsmName;
150 // Linux assembler (Others?) does not take register mnemonics.
151 // FIXME - What about special registers used in mfspr/mtspr?
152 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
156 void printOperand(const MachineInstr *MI, unsigned OpNo) {
157 const MachineOperand &MO = MI->getOperand(OpNo);
159 printRegister(MO, false);
160 } else if (MO.isImm()) {
167 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
168 unsigned AsmVariant, const char *ExtraCode);
169 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
170 unsigned AsmVariant, const char *ExtraCode);
173 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
174 char value = MI->getOperand(OpNo).getImm();
175 value = (value << (32-5)) >> (32-5);
178 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
179 unsigned char value = MI->getOperand(OpNo).getImm();
180 assert(value <= 31 && "Invalid u5imm argument!");
181 O << (unsigned int)value;
183 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
184 unsigned char value = MI->getOperand(OpNo).getImm();
185 assert(value <= 63 && "Invalid u6imm argument!");
186 O << (unsigned int)value;
188 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
189 O << (short)MI->getOperand(OpNo).getImm();
191 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
192 O << (unsigned short)MI->getOperand(OpNo).getImm();
194 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
195 if (MI->getOperand(OpNo).isImm()) {
196 O << (short)(MI->getOperand(OpNo).getImm()*4);
199 printOp(MI->getOperand(OpNo));
200 if (TM.getRelocationModel() == Reloc::PIC_)
201 O << "-\"L" << getFunctionNumber() << "$pb\")";
206 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
207 // Branches can take an immediate operand. This is used by the branch
208 // selection pass to print $+8, an eight byte displacement from the PC.
209 if (MI->getOperand(OpNo).isImm()) {
210 O << "$+" << MI->getOperand(OpNo).getImm()*4;
212 printOp(MI->getOperand(OpNo));
215 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
216 const MachineOperand &MO = MI->getOperand(OpNo);
217 if (TM.getRelocationModel() != Reloc::Static) {
218 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
219 GlobalValue *GV = MO.getGlobal();
220 if (GV->isDeclaration() || GV->isWeakForLinker()) {
221 // Dynamically-resolved functions need a stub for the function.
222 FnStubInfo &FnInfo = FnStubs[Mang->getMangledName(GV)];
223 FnInfo.Init(GV, Mang);
228 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
229 FnStubInfo &FnInfo =FnStubs[Mang->makeNameProper(MO.getSymbolName())];
230 FnInfo.Init(MO.getSymbolName(), Mang);
236 printOp(MI->getOperand(OpNo));
238 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
239 O << (int)MI->getOperand(OpNo).getImm()*4;
241 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
242 O << "\"L" << getFunctionNumber() << "$pb\"\n";
243 O << "\"L" << getFunctionNumber() << "$pb\":";
245 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
246 if (MI->getOperand(OpNo).isImm()) {
247 printS16ImmOperand(MI, OpNo);
249 if (Subtarget.isDarwin()) O << "ha16(";
250 printOp(MI->getOperand(OpNo));
251 if (TM.getRelocationModel() == Reloc::PIC_)
252 O << "-\"L" << getFunctionNumber() << "$pb\"";
253 if (Subtarget.isDarwin())
259 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
260 if (MI->getOperand(OpNo).isImm()) {
261 printS16ImmOperand(MI, OpNo);
263 if (Subtarget.isDarwin()) O << "lo16(";
264 printOp(MI->getOperand(OpNo));
265 if (TM.getRelocationModel() == Reloc::PIC_)
266 O << "-\"L" << getFunctionNumber() << "$pb\"";
267 if (Subtarget.isDarwin())
273 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
274 unsigned CCReg = MI->getOperand(OpNo).getReg();
275 unsigned RegNo = enumRegToMachineReg(CCReg);
276 O << (0x80 >> RegNo);
278 // The new addressing mode printers.
279 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
280 printSymbolLo(MI, OpNo);
282 if (MI->getOperand(OpNo+1).isReg() &&
283 MI->getOperand(OpNo+1).getReg() == PPC::R0)
286 printOperand(MI, OpNo+1);
289 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
290 if (MI->getOperand(OpNo).isImm())
291 printS16X4ImmOperand(MI, OpNo);
293 printSymbolLo(MI, OpNo);
295 if (MI->getOperand(OpNo+1).isReg() &&
296 MI->getOperand(OpNo+1).getReg() == PPC::R0)
299 printOperand(MI, OpNo+1);
303 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
304 // When used as the base register, r0 reads constant zero rather than
305 // the value contained in the register. For this reason, the darwin
306 // assembler requires that we print r0 as 0 (no r) when used as the base.
307 const MachineOperand &MO = MI->getOperand(OpNo);
308 printRegister(MO, true);
310 printOperand(MI, OpNo+1);
313 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
314 const char *Modifier);
316 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
318 virtual void EmitExternalGlobal(const GlobalVariable *GV);
321 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
322 class VISIBILITY_HIDDEN PPCLinuxAsmPrinter : public PPCAsmPrinter {
324 explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
325 const TargetAsmInfo *T, bool V)
326 : PPCAsmPrinter(O, TM, T, V){}
328 virtual const char *getPassName() const {
329 return "Linux PPC Assembly Printer";
332 bool runOnMachineFunction(MachineFunction &F);
334 void getAnalysisUsage(AnalysisUsage &AU) const {
335 AU.setPreservesAll();
336 AU.addRequired<MachineModuleInfo>();
337 AU.addRequired<DwarfWriter>();
338 PPCAsmPrinter::getAnalysisUsage(AU);
341 void PrintGlobalVariable(const GlobalVariable *GVar);
344 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
346 class VISIBILITY_HIDDEN PPCDarwinAsmPrinter : public PPCAsmPrinter {
347 formatted_raw_ostream &OS;
349 explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
350 const TargetAsmInfo *T, bool V)
351 : PPCAsmPrinter(O, TM, T, V), OS(O) {}
353 virtual const char *getPassName() const {
354 return "Darwin PPC Assembly Printer";
357 bool runOnMachineFunction(MachineFunction &F);
358 bool doInitialization(Module &M);
359 bool doFinalization(Module &M);
361 void getAnalysisUsage(AnalysisUsage &AU) const {
362 AU.setPreservesAll();
363 AU.addRequired<MachineModuleInfo>();
364 AU.addRequired<DwarfWriter>();
365 PPCAsmPrinter::getAnalysisUsage(AU);
368 void PrintGlobalVariable(const GlobalVariable *GVar);
370 } // end of anonymous namespace
372 // Include the auto-generated portion of the assembly writer
373 #include "PPCGenAsmWriter.inc"
375 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
376 switch (MO.getType()) {
377 case MachineOperand::MO_Immediate:
378 llvm_unreachable("printOp() does not handle immediate values");
380 case MachineOperand::MO_MachineBasicBlock:
381 printBasicBlockLabel(MO.getMBB());
383 case MachineOperand::MO_JumpTableIndex:
384 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
385 << '_' << MO.getIndex();
386 // FIXME: PIC relocation model
388 case MachineOperand::MO_ConstantPoolIndex:
389 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
390 << '_' << MO.getIndex();
392 case MachineOperand::MO_ExternalSymbol: {
393 // Computing the address of an external symbol, not calling it.
394 std::string Name(TAI->getGlobalPrefix());
395 Name += MO.getSymbolName();
397 if (TM.getRelocationModel() != Reloc::Static) {
398 GVStubs[Name] = Name+"$non_lazy_ptr";
399 Name += "$non_lazy_ptr";
404 case MachineOperand::MO_GlobalAddress: {
405 // Computing the address of a global symbol, not calling it.
406 GlobalValue *GV = MO.getGlobal();
409 // External or weakly linked global variables need non-lazily-resolved stubs
410 if (TM.getRelocationModel() != Reloc::Static &&
411 (GV->isDeclaration() || GV->isWeakForLinker())) {
412 if (!GV->hasHiddenVisibility()) {
413 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
414 GVStubs[Mang->getMangledName(GV)] = Name;
415 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
416 GV->hasAvailableExternallyLinkage()) {
417 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
418 HiddenGVStubs[Mang->getMangledName(GV)] = Name;
420 Name = Mang->getMangledName(GV);
423 Name = Mang->getMangledName(GV);
427 printOffset(MO.getOffset());
432 O << "<unknown operand type: " << MO.getType() << ">";
437 /// EmitExternalGlobal - In this case we need to use the indirect symbol.
439 void PPCAsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
442 if (TM.getRelocationModel() != Reloc::Static) {
443 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
445 Name = Mang->getMangledName(GV);
450 /// PrintAsmOperand - Print out an operand for an inline asm expression.
452 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
454 const char *ExtraCode) {
455 // Does this asm operand have a single letter operand modifier?
456 if (ExtraCode && ExtraCode[0]) {
457 if (ExtraCode[1] != 0) return true; // Unknown modifier.
459 switch (ExtraCode[0]) {
460 default: return true; // Unknown modifier.
461 case 'c': // Don't print "$" before a global var name or constant.
462 // PPC never has a prefix.
463 printOperand(MI, OpNo);
465 case 'L': // Write second word of DImode reference.
466 // Verify that this operand has two consecutive registers.
467 if (!MI->getOperand(OpNo).isReg() ||
468 OpNo+1 == MI->getNumOperands() ||
469 !MI->getOperand(OpNo+1).isReg())
471 ++OpNo; // Return the high-part.
474 // Write 'i' if an integer constant, otherwise nothing. Used to print
476 if (MI->getOperand(OpNo).isImm())
482 printOperand(MI, OpNo);
486 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
488 const char *ExtraCode) {
489 if (ExtraCode && ExtraCode[0])
490 return true; // Unknown modifier.
491 if (MI->getOperand(OpNo).isReg())
492 printMemRegReg(MI, OpNo);
494 printMemRegImm(MI, OpNo);
498 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
499 const char *Modifier) {
500 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
501 unsigned Code = MI->getOperand(OpNo).getImm();
502 if (!strcmp(Modifier, "cc")) {
503 switch ((PPC::Predicate)Code) {
504 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
505 case PPC::PRED_LT: O << "lt"; return;
506 case PPC::PRED_LE: O << "le"; return;
507 case PPC::PRED_EQ: O << "eq"; return;
508 case PPC::PRED_GE: O << "ge"; return;
509 case PPC::PRED_GT: O << "gt"; return;
510 case PPC::PRED_NE: O << "ne"; return;
511 case PPC::PRED_UN: O << "un"; return;
512 case PPC::PRED_NU: O << "nu"; return;
516 assert(!strcmp(Modifier, "reg") &&
517 "Need to specify 'cc' or 'reg' as predicate op modifier!");
518 // Don't print the register for 'always'.
519 if (Code == PPC::PRED_ALWAYS) return;
520 printOperand(MI, OpNo+1);
525 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
526 /// the current output stream.
528 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
531 // Check for slwi/srwi mnemonics.
532 if (MI->getOpcode() == PPC::RLWINM) {
533 bool FoundMnemonic = false;
534 unsigned char SH = MI->getOperand(2).getImm();
535 unsigned char MB = MI->getOperand(3).getImm();
536 unsigned char ME = MI->getOperand(4).getImm();
537 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
538 O << "\tslwi "; FoundMnemonic = true;
540 if (SH <= 31 && MB == (32-SH) && ME == 31) {
541 O << "\tsrwi "; FoundMnemonic = true;
548 O << ", " << (unsigned int)SH << '\n';
551 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
552 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
560 } else if (MI->getOpcode() == PPC::RLDICR) {
561 unsigned char SH = MI->getOperand(2).getImm();
562 unsigned char ME = MI->getOperand(3).getImm();
563 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
569 O << ", " << (unsigned int)SH << '\n';
574 printInstruction(MI);
577 /// runOnMachineFunction - This uses the printMachineInstruction()
578 /// method to print assembly for each instruction.
580 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
583 SetupMachineFunction(MF);
586 // Print out constants referenced by the function
587 EmitConstantPool(MF.getConstantPool());
589 // Print out labels for the function.
590 const Function *F = MF.getFunction();
591 SwitchToSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
593 switch (F->getLinkage()) {
594 default: llvm_unreachable("Unknown linkage type!");
595 case Function::PrivateLinkage:
596 case Function::LinkerPrivateLinkage:
597 case Function::InternalLinkage: // Symbols default to internal.
599 case Function::ExternalLinkage:
600 O << "\t.global\t" << CurrentFnName << '\n'
601 << "\t.type\t" << CurrentFnName << ", @function\n";
603 case Function::WeakAnyLinkage:
604 case Function::WeakODRLinkage:
605 case Function::LinkOnceAnyLinkage:
606 case Function::LinkOnceODRLinkage:
607 O << "\t.global\t" << CurrentFnName << '\n';
608 O << "\t.weak\t" << CurrentFnName << '\n';
612 printVisibility(CurrentFnName, F->getVisibility());
614 EmitAlignment(MF.getAlignment(), F);
615 O << CurrentFnName << ":\n";
617 // Emit pre-function debug information.
618 DW->BeginFunction(&MF);
620 // Print out code for the function.
621 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
623 // Print a label for the basic block.
624 if (I != MF.begin()) {
625 printBasicBlockLabel(I, true, true);
628 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
630 // Print the assembly for the instruction.
631 printMachineInstruction(II);
635 O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << '\n';
637 // Print out jump tables referenced by the function.
638 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
640 SwitchToSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
642 // Emit post-function debug information.
643 DW->EndFunction(&MF);
645 // We didn't modify anything.
649 void PPCLinuxAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
650 const TargetData *TD = TM.getTargetData();
652 if (!GVar->hasInitializer())
653 return; // External global require no code
655 // Check to see if this is a special global used by LLVM, if so, emit it.
656 if (EmitSpecialLLVMGlobal(GVar))
659 std::string name = Mang->getMangledName(GVar);
661 printVisibility(name, GVar->getVisibility());
663 Constant *C = GVar->getInitializer();
664 const Type *Type = C->getType();
665 unsigned Size = TD->getTypeAllocSize(Type);
666 unsigned Align = TD->getPreferredAlignmentLog(GVar);
668 SwitchToSection(getObjFileLowering().SectionForGlobal(GVar, Mang, TM));
670 if (C->isNullValue() && /* FIXME: Verify correct */
671 !GVar->hasSection() &&
672 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
673 GVar->isWeakForLinker())) {
674 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
676 if (GVar->hasExternalLinkage()) {
677 O << "\t.global " << name << '\n';
678 O << "\t.type " << name << ", @object\n";
680 O << "\t.zero " << Size << '\n';
681 } else if (GVar->hasLocalLinkage()) {
682 O << TAI->getLCOMMDirective() << name << ',' << Size;
684 O << ".comm " << name << ',' << Size;
687 O << "\t\t" << TAI->getCommentString() << " '";
688 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
695 switch (GVar->getLinkage()) {
696 case GlobalValue::LinkOnceAnyLinkage:
697 case GlobalValue::LinkOnceODRLinkage:
698 case GlobalValue::WeakAnyLinkage:
699 case GlobalValue::WeakODRLinkage:
700 case GlobalValue::CommonLinkage:
701 O << "\t.global " << name << '\n'
702 << "\t.type " << name << ", @object\n"
703 << "\t.weak " << name << '\n';
705 case GlobalValue::AppendingLinkage:
706 // FIXME: appending linkage variables should go into a section of
707 // their name or something. For now, just emit them as external.
708 case GlobalValue::ExternalLinkage:
709 // If external or appending, declare as a global symbol
710 O << "\t.global " << name << '\n'
711 << "\t.type " << name << ", @object\n";
713 case GlobalValue::InternalLinkage:
714 case GlobalValue::PrivateLinkage:
715 case GlobalValue::LinkerPrivateLinkage:
718 llvm_unreachable("Unknown linkage type!");
721 EmitAlignment(Align, GVar);
724 O << "\t\t\t\t" << TAI->getCommentString() << " '";
725 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
730 EmitGlobalConstant(C);
735 /// runOnMachineFunction - This uses the printMachineInstruction()
736 /// method to print assembly for each instruction.
738 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
741 SetupMachineFunction(MF);
744 // Print out constants referenced by the function
745 EmitConstantPool(MF.getConstantPool());
747 // Print out labels for the function.
748 const Function *F = MF.getFunction();
749 SwitchToSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
751 switch (F->getLinkage()) {
752 default: llvm_unreachable("Unknown linkage type!");
753 case Function::PrivateLinkage:
754 case Function::LinkerPrivateLinkage:
755 case Function::InternalLinkage: // Symbols default to internal.
757 case Function::ExternalLinkage:
758 O << "\t.globl\t" << CurrentFnName << '\n';
760 case Function::WeakAnyLinkage:
761 case Function::WeakODRLinkage:
762 case Function::LinkOnceAnyLinkage:
763 case Function::LinkOnceODRLinkage:
764 O << "\t.globl\t" << CurrentFnName << '\n';
765 O << "\t.weak_definition\t" << CurrentFnName << '\n';
769 printVisibility(CurrentFnName, F->getVisibility());
771 EmitAlignment(MF.getAlignment(), F);
772 O << CurrentFnName << ":\n";
774 // Emit pre-function debug information.
775 DW->BeginFunction(&MF);
777 // If the function is empty, then we need to emit *something*. Otherwise, the
778 // function's label might be associated with something that it wasn't meant to
779 // be associated with. We emit a noop in this situation.
780 MachineFunction::iterator I = MF.begin();
782 if (++I == MF.end() && MF.front().empty())
785 // Print out code for the function.
786 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
788 // Print a label for the basic block.
789 if (I != MF.begin()) {
790 printBasicBlockLabel(I, true, true, VerboseAsm);
793 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
795 // Print the assembly for the instruction.
796 printMachineInstruction(II);
800 // Print out jump tables referenced by the function.
801 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
803 // Emit post-function debug information.
804 DW->EndFunction(&MF);
806 // We didn't modify anything.
811 bool PPCDarwinAsmPrinter::doInitialization(Module &M) {
812 static const char *const CPUDirectives[] = {
824 unsigned Directive = Subtarget.getDarwinDirective();
825 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
826 Directive = PPC::DIR_970;
827 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
828 Directive = PPC::DIR_7400;
829 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
830 Directive = PPC::DIR_64;
831 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
832 O << "\t.machine " << CPUDirectives[Directive] << '\n';
834 bool Result = AsmPrinter::doInitialization(M);
837 // Prime text sections so they are adjacent. This reduces the likelihood a
838 // large data or debug section causes a branch to exceed 16M limit.
839 TargetLoweringObjectFileMachO &TLOFMacho =
840 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
841 SwitchToSection(TLOFMacho.getTextCoalSection());
842 if (TM.getRelocationModel() == Reloc::PIC_) {
843 SwitchToSection(TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
844 MCSectionMachO::S_SYMBOL_STUBS |
845 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
846 32, SectionKind::getText()));
847 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
848 SwitchToSection(TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
849 MCSectionMachO::S_SYMBOL_STUBS |
850 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
851 16, SectionKind::getText()));
853 SwitchToSection(getObjFileLowering().getTextSection());
858 void PPCDarwinAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
859 const TargetData *TD = TM.getTargetData();
861 if (!GVar->hasInitializer())
862 return; // External global require no code
864 // Check to see if this is a special global used by LLVM, if so, emit it.
865 if (EmitSpecialLLVMGlobal(GVar)) {
866 if (TM.getRelocationModel() == Reloc::Static) {
867 if (GVar->getName() == "llvm.global_ctors")
868 O << ".reference .constructors_used\n";
869 else if (GVar->getName() == "llvm.global_dtors")
870 O << ".reference .destructors_used\n";
875 std::string name = Mang->getMangledName(GVar);
876 printVisibility(name, GVar->getVisibility());
878 Constant *C = GVar->getInitializer();
879 const Type *Type = C->getType();
880 unsigned Size = TD->getTypeAllocSize(Type);
881 unsigned Align = TD->getPreferredAlignmentLog(GVar);
883 const MCSection *TheSection =
884 getObjFileLowering().SectionForGlobal(GVar, Mang, TM);
885 SwitchToSection(TheSection);
887 /// FIXME: Drive this off the section!
888 if (C->isNullValue() && /* FIXME: Verify correct */
889 !GVar->hasSection() &&
890 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
891 GVar->isWeakForLinker()) &&
892 // Don't put things that should go in the cstring section into "comm".
893 !TheSection->getKind().isMergeableCString()) {
894 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
896 if (GVar->hasExternalLinkage()) {
897 O << "\t.globl " << name << '\n';
898 O << "\t.zerofill __DATA, __common, " << name << ", "
899 << Size << ", " << Align;
900 } else if (GVar->hasLocalLinkage()) {
901 O << TAI->getLCOMMDirective() << name << ',' << Size << ',' << Align;
902 } else if (!GVar->hasCommonLinkage()) {
903 O << "\t.globl " << name << '\n'
904 << TAI->getWeakDefDirective() << name << '\n';
905 EmitAlignment(Align, GVar);
908 O << "\t\t\t\t" << TAI->getCommentString() << " ";
909 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
912 EmitGlobalConstant(C);
915 O << ".comm " << name << ',' << Size;
916 // Darwin 9 and above support aligned common data.
917 if (Subtarget.isDarwin9())
921 O << "\t\t" << TAI->getCommentString() << " '";
922 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
929 switch (GVar->getLinkage()) {
930 case GlobalValue::LinkOnceAnyLinkage:
931 case GlobalValue::LinkOnceODRLinkage:
932 case GlobalValue::WeakAnyLinkage:
933 case GlobalValue::WeakODRLinkage:
934 case GlobalValue::CommonLinkage:
935 O << "\t.globl " << name << '\n'
936 << "\t.weak_definition " << name << '\n';
938 case GlobalValue::AppendingLinkage:
939 // FIXME: appending linkage variables should go into a section of
940 // their name or something. For now, just emit them as external.
941 case GlobalValue::ExternalLinkage:
942 // If external or appending, declare as a global symbol
943 O << "\t.globl " << name << '\n';
945 case GlobalValue::InternalLinkage:
946 case GlobalValue::PrivateLinkage:
947 case GlobalValue::LinkerPrivateLinkage:
950 llvm_unreachable("Unknown linkage type!");
953 EmitAlignment(Align, GVar);
956 O << "\t\t\t\t" << TAI->getCommentString() << " '";
957 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
962 EmitGlobalConstant(C);
966 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
967 const TargetData *TD = TM.getTargetData();
969 bool isPPC64 = TD->getPointerSizeInBits() == 64;
971 // Darwin/PPC always uses mach-o.
972 TargetLoweringObjectFileMachO &TLOFMacho =
973 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
976 const MCSection *LSPSection = 0;
977 if (!FnStubs.empty()) // .lazy_symbol_pointer
978 LSPSection = TLOFMacho.getLazySymbolPointerSection();
981 // Output stubs for dynamically-linked functions
982 if (TM.getRelocationModel() == Reloc::PIC_ && !FnStubs.empty()) {
983 const MCSection *StubSection =
984 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
985 MCSectionMachO::S_SYMBOL_STUBS |
986 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
987 32, SectionKind::getText());
988 for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
990 SwitchToSection(StubSection);
992 const FnStubInfo &Info = I->second;
993 O << Info.Stub << ":\n";
994 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
996 O << "\tbcl 20,31," << Info.AnonSymbol << '\n';
997 O << Info.AnonSymbol << ":\n";
999 O << "\taddis r11,r11,ha16(" << Info.LazyPtr << "-" << Info.AnonSymbol;
1002 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1003 O << Info.LazyPtr << "-" << Info.AnonSymbol << ")(r11)\n";
1004 O << "\tmtctr r12\n";
1007 SwitchToSection(LSPSection);
1008 O << Info.LazyPtr << ":\n";
1009 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1010 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1012 } else if (!FnStubs.empty()) {
1013 const MCSection *StubSection =
1014 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
1015 MCSectionMachO::S_SYMBOL_STUBS |
1016 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1017 16, SectionKind::getText());
1019 for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1021 SwitchToSection(StubSection);
1023 const FnStubInfo &Info = I->second;
1024 O << Info.Stub << ":\n";
1025 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1026 O << "\tlis r11,ha16(" << Info.LazyPtr << ")\n";
1027 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1028 O << Info.LazyPtr << ")(r11)\n";
1029 O << "\tmtctr r12\n";
1031 SwitchToSection(LSPSection);
1032 O << Info.LazyPtr << ":\n";
1033 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1034 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1040 if (TAI->doesSupportExceptionHandling() && MMI) {
1041 // Add the (possibly multiple) personalities to the set of global values.
1042 // Only referenced functions get into the Personalities list.
1043 const std::vector<Function *> &Personalities = MMI->getPersonalities();
1044 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1045 E = Personalities.end(); I != E; ++I) {
1047 GVStubs[Mang->getMangledName(*I)] =
1048 Mang->getMangledName(*I, "$non_lazy_ptr", true);
1052 // Output macho stubs for external and common global variables.
1053 if (!GVStubs.empty()) {
1054 // Switch with ".non_lazy_symbol_pointer" directive.
1055 SwitchToSection(TLOFMacho.getNonLazySymbolPointerSection());
1056 EmitAlignment(isPPC64 ? 3 : 2);
1058 for (StringMap<std::string>::iterator I = GVStubs.begin(),
1059 E = GVStubs.end(); I != E; ++I) {
1060 O << I->second << ":\n";
1061 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1062 O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
1066 if (!HiddenGVStubs.empty()) {
1067 SwitchToSection(getObjFileLowering().getDataSection());
1068 EmitAlignment(isPPC64 ? 3 : 2);
1069 for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
1070 E = HiddenGVStubs.end(); I != E; ++I) {
1071 O << I->second << ":\n";
1072 O << (isPPC64 ? "\t.quad\t" : "\t.long\t") << I->getKeyData() << '\n';
1076 // Funny Darwin hack: This flag tells the linker that no global symbols
1077 // contain code that falls through to other global symbols (e.g. the obvious
1078 // implementation of multiple entry points). If this doesn't occur, the
1079 // linker can safely perform dead code stripping. Since LLVM never generates
1080 // code that does this, it is always safe to set.
1081 O << "\t.subsections_via_symbols\n";
1083 return AsmPrinter::doFinalization(M);
1088 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1089 /// for a MachineFunction to the given output stream, in a format that the
1090 /// Darwin assembler can deal with.
1092 static FunctionPass *createPPCAsmPrinterPass(formatted_raw_ostream &o,
1094 const TargetAsmInfo *tai,
1096 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1098 if (Subtarget->isDarwin())
1099 return new PPCDarwinAsmPrinter(o, tm, tai, verbose);
1100 return new PPCLinuxAsmPrinter(o, tm, tai, verbose);
1103 // Force static initialization.
1104 extern "C" void LLVMInitializePowerPCAsmPrinter() {
1105 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
1106 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);