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/Metadata.h"
28 #include "llvm/Assembly/Writer.h"
29 #include "llvm/CodeGen/AsmPrinter.h"
30 #include "llvm/CodeGen/DwarfWriter.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineFunctionPass.h"
33 #include "llvm/CodeGen/MachineInstr.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/MC/MCSection.h"
36 #include "llvm/Target/TargetAsmInfo.h"
37 #include "llvm/Target/TargetLoweringObjectFile.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/Target/TargetRegistry.h"
42 #include "llvm/Support/Mangler.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/Compiler.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"
54 STATISTIC(EmittedInsts, "Number of machine instrs printed");
57 class VISIBILITY_HIDDEN PPCAsmPrinter : public AsmPrinter {
60 std::string Stub, LazyPtr, AnonSymbol;
64 void Init(const GlobalValue *GV, Mangler *Mang) {
65 // Already initialized.
66 if (!Stub.empty()) return;
67 Stub = Mang->getMangledName(GV, "$stub", true);
68 LazyPtr = Mang->getMangledName(GV, "$lazy_ptr", true);
69 AnonSymbol = Mang->getMangledName(GV, "$stub$tmp", true);
72 void Init(const std::string &GV, Mangler *Mang) {
73 // Already initialized.
74 if (!Stub.empty()) return;
75 Stub = Mang->makeNameProper(GV + "$stub",
77 LazyPtr = Mang->makeNameProper(GV + "$lazy_ptr",
79 AnonSymbol = Mang->makeNameProper(GV + "$stub$tmp",
84 StringMap<FnStubInfo> FnStubs;
85 StringMap<std::string> GVStubs, HiddenGVStubs;
86 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>()) {}
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 bool 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 printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
315 const char *Modifier);
317 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
319 virtual void EmitExternalGlobal(const GlobalVariable *GV);
322 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
323 class VISIBILITY_HIDDEN PPCLinuxAsmPrinter : public PPCAsmPrinter {
325 explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
326 const TargetAsmInfo *T, bool V)
327 : PPCAsmPrinter(O, TM, T, V){}
329 virtual const char *getPassName() const {
330 return "Linux PPC Assembly Printer";
333 bool runOnMachineFunction(MachineFunction &F);
335 void getAnalysisUsage(AnalysisUsage &AU) const {
336 AU.setPreservesAll();
337 AU.addRequired<MachineModuleInfo>();
338 AU.addRequired<DwarfWriter>();
339 PPCAsmPrinter::getAnalysisUsage(AU);
342 void PrintGlobalVariable(const GlobalVariable *GVar);
345 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
347 class VISIBILITY_HIDDEN PPCDarwinAsmPrinter : public PPCAsmPrinter {
348 formatted_raw_ostream &OS;
350 explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
351 const TargetAsmInfo *T, bool V)
352 : PPCAsmPrinter(O, TM, T, V), OS(O) {}
354 virtual const char *getPassName() const {
355 return "Darwin PPC Assembly Printer";
358 bool runOnMachineFunction(MachineFunction &F);
359 bool doInitialization(Module &M);
360 bool doFinalization(Module &M);
362 void getAnalysisUsage(AnalysisUsage &AU) const {
363 AU.setPreservesAll();
364 AU.addRequired<MachineModuleInfo>();
365 AU.addRequired<DwarfWriter>();
366 PPCAsmPrinter::getAnalysisUsage(AU);
369 void PrintGlobalVariable(const GlobalVariable *GVar);
371 } // end of anonymous namespace
373 // Include the auto-generated portion of the assembly writer
374 #include "PPCGenAsmWriter.inc"
376 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
377 switch (MO.getType()) {
378 case MachineOperand::MO_Immediate:
379 llvm_unreachable("printOp() does not handle immediate values");
381 case MachineOperand::MO_MachineBasicBlock:
382 printBasicBlockLabel(MO.getMBB());
384 case MachineOperand::MO_JumpTableIndex:
385 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
386 << '_' << MO.getIndex();
387 // FIXME: PIC relocation model
389 case MachineOperand::MO_ConstantPoolIndex:
390 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
391 << '_' << MO.getIndex();
393 case MachineOperand::MO_ExternalSymbol: {
394 // Computing the address of an external symbol, not calling it.
395 std::string Name(TAI->getGlobalPrefix());
396 Name += MO.getSymbolName();
398 if (TM.getRelocationModel() != Reloc::Static) {
399 GVStubs[Name] = Name+"$non_lazy_ptr";
400 Name += "$non_lazy_ptr";
405 case MachineOperand::MO_GlobalAddress: {
406 // Computing the address of a global symbol, not calling it.
407 GlobalValue *GV = MO.getGlobal();
410 // External or weakly linked global variables need non-lazily-resolved stubs
411 if (TM.getRelocationModel() != Reloc::Static &&
412 (GV->isDeclaration() || GV->isWeakForLinker())) {
413 if (!GV->hasHiddenVisibility()) {
414 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
415 GVStubs[Mang->getMangledName(GV)] = Name;
416 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
417 GV->hasAvailableExternallyLinkage()) {
418 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
419 HiddenGVStubs[Mang->getMangledName(GV)] = Name;
421 Name = Mang->getMangledName(GV);
424 Name = Mang->getMangledName(GV);
428 printOffset(MO.getOffset());
433 O << "<unknown operand type: " << MO.getType() << ">";
438 /// EmitExternalGlobal - In this case we need to use the indirect symbol.
440 void PPCAsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
443 if (TM.getRelocationModel() != Reloc::Static) {
444 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
446 Name = Mang->getMangledName(GV);
451 /// PrintAsmOperand - Print out an operand for an inline asm expression.
453 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
455 const char *ExtraCode) {
456 // Does this asm operand have a single letter operand modifier?
457 if (ExtraCode && ExtraCode[0]) {
458 if (ExtraCode[1] != 0) return true; // Unknown modifier.
460 switch (ExtraCode[0]) {
461 default: return true; // Unknown modifier.
462 case 'c': // Don't print "$" before a global var name or constant.
463 // PPC never has a prefix.
464 printOperand(MI, OpNo);
466 case 'L': // Write second word of DImode reference.
467 // Verify that this operand has two consecutive registers.
468 if (!MI->getOperand(OpNo).isReg() ||
469 OpNo+1 == MI->getNumOperands() ||
470 !MI->getOperand(OpNo+1).isReg())
472 ++OpNo; // Return the high-part.
475 // Write 'i' if an integer constant, otherwise nothing. Used to print
477 if (MI->getOperand(OpNo).isImm())
483 printOperand(MI, OpNo);
487 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
489 const char *ExtraCode) {
490 if (ExtraCode && ExtraCode[0])
491 return true; // Unknown modifier.
492 if (MI->getOperand(OpNo).isReg())
493 printMemRegReg(MI, OpNo);
495 printMemRegImm(MI, OpNo);
499 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
500 const char *Modifier) {
501 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
502 unsigned Code = MI->getOperand(OpNo).getImm();
503 if (!strcmp(Modifier, "cc")) {
504 switch ((PPC::Predicate)Code) {
505 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
506 case PPC::PRED_LT: O << "lt"; return;
507 case PPC::PRED_LE: O << "le"; return;
508 case PPC::PRED_EQ: O << "eq"; return;
509 case PPC::PRED_GE: O << "ge"; return;
510 case PPC::PRED_GT: O << "gt"; return;
511 case PPC::PRED_NE: O << "ne"; return;
512 case PPC::PRED_UN: O << "un"; return;
513 case PPC::PRED_NU: O << "nu"; return;
517 assert(!strcmp(Modifier, "reg") &&
518 "Need to specify 'cc' or 'reg' as predicate op modifier!");
519 // Don't print the register for 'always'.
520 if (Code == PPC::PRED_ALWAYS) return;
521 printOperand(MI, OpNo+1);
526 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
527 /// the current output stream.
529 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
532 // Check for slwi/srwi mnemonics.
533 if (MI->getOpcode() == PPC::RLWINM) {
534 bool FoundMnemonic = false;
535 unsigned char SH = MI->getOperand(2).getImm();
536 unsigned char MB = MI->getOperand(3).getImm();
537 unsigned char ME = MI->getOperand(4).getImm();
538 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
539 O << "\tslwi "; FoundMnemonic = true;
541 if (SH <= 31 && MB == (32-SH) && ME == 31) {
542 O << "\tsrwi "; FoundMnemonic = true;
549 O << ", " << (unsigned int)SH << '\n';
552 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
553 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
561 } else if (MI->getOpcode() == PPC::RLDICR) {
562 unsigned char SH = MI->getOperand(2).getImm();
563 unsigned char ME = MI->getOperand(3).getImm();
564 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
570 O << ", " << (unsigned int)SH << '\n';
575 if (printInstruction(MI))
576 return; // Printer was automatically generated
578 llvm_unreachable("Unhandled instruction in asm writer!");
581 /// runOnMachineFunction - This uses the printMachineInstruction()
582 /// method to print assembly for each instruction.
584 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
587 SetupMachineFunction(MF);
590 // Print out constants referenced by the function
591 EmitConstantPool(MF.getConstantPool());
593 // Print out labels for the function.
594 const Function *F = MF.getFunction();
595 SwitchToSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
597 switch (F->getLinkage()) {
598 default: llvm_unreachable("Unknown linkage type!");
599 case Function::PrivateLinkage:
600 case Function::LinkerPrivateLinkage:
601 case Function::InternalLinkage: // Symbols default to internal.
603 case Function::ExternalLinkage:
604 O << "\t.global\t" << CurrentFnName << '\n'
605 << "\t.type\t" << CurrentFnName << ", @function\n";
607 case Function::WeakAnyLinkage:
608 case Function::WeakODRLinkage:
609 case Function::LinkOnceAnyLinkage:
610 case Function::LinkOnceODRLinkage:
611 O << "\t.global\t" << CurrentFnName << '\n';
612 O << "\t.weak\t" << CurrentFnName << '\n';
616 printVisibility(CurrentFnName, F->getVisibility());
618 EmitAlignment(MF.getAlignment(), F);
619 O << CurrentFnName << ":\n";
621 // Emit pre-function debug information.
622 DW->BeginFunction(&MF);
624 // Print out code for the function.
625 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
627 // Print a label for the basic block.
628 if (I != MF.begin()) {
629 printBasicBlockLabel(I, true, true);
632 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
634 // Print the assembly for the instruction.
635 printMachineInstruction(II);
639 O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << '\n';
641 // Print out jump tables referenced by the function.
642 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
644 SwitchToSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
646 // Emit post-function debug information.
647 DW->EndFunction(&MF);
651 // We didn't modify anything.
655 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
656 /// Don't print things like \\n or \\0.
657 static void PrintUnmangledNameSafely(const Value *V,
658 formatted_raw_ostream &OS) {
659 for (StringRef::iterator it = V->getName().begin(),
660 ie = V->getName().end(); it != ie; ++it)
665 void PPCLinuxAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
666 const TargetData *TD = TM.getTargetData();
668 if (!GVar->hasInitializer())
669 return; // External global require no code
671 // Check to see if this is a special global used by LLVM, if so, emit it.
672 if (EmitSpecialLLVMGlobal(GVar))
675 std::string name = Mang->getMangledName(GVar);
677 printVisibility(name, GVar->getVisibility());
679 Constant *C = GVar->getInitializer();
680 if (isa<MDNode>(C) || isa<MDString>(C))
682 const Type *Type = C->getType();
683 unsigned Size = TD->getTypeAllocSize(Type);
684 unsigned Align = TD->getPreferredAlignmentLog(GVar);
686 SwitchToSection(getObjFileLowering().SectionForGlobal(GVar, Mang, TM));
688 if (C->isNullValue() && /* FIXME: Verify correct */
689 !GVar->hasSection() &&
690 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
691 GVar->isWeakForLinker())) {
692 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
694 if (GVar->hasExternalLinkage()) {
695 O << "\t.global " << name << '\n';
696 O << "\t.type " << name << ", @object\n";
698 O << "\t.zero " << Size << '\n';
699 } else if (GVar->hasLocalLinkage()) {
700 O << TAI->getLCOMMDirective() << name << ',' << Size;
702 O << ".comm " << name << ',' << Size;
705 O << "\t\t" << TAI->getCommentString() << " '";
706 PrintUnmangledNameSafely(GVar, O);
713 switch (GVar->getLinkage()) {
714 case GlobalValue::LinkOnceAnyLinkage:
715 case GlobalValue::LinkOnceODRLinkage:
716 case GlobalValue::WeakAnyLinkage:
717 case GlobalValue::WeakODRLinkage:
718 case GlobalValue::CommonLinkage:
719 O << "\t.global " << name << '\n'
720 << "\t.type " << name << ", @object\n"
721 << "\t.weak " << name << '\n';
723 case GlobalValue::AppendingLinkage:
724 // FIXME: appending linkage variables should go into a section of
725 // their name or something. For now, just emit them as external.
726 case GlobalValue::ExternalLinkage:
727 // If external or appending, declare as a global symbol
728 O << "\t.global " << name << '\n'
729 << "\t.type " << name << ", @object\n";
731 case GlobalValue::InternalLinkage:
732 case GlobalValue::PrivateLinkage:
733 case GlobalValue::LinkerPrivateLinkage:
736 llvm_unreachable("Unknown linkage type!");
739 EmitAlignment(Align, GVar);
742 O << "\t\t\t\t" << TAI->getCommentString() << " '";
743 PrintUnmangledNameSafely(GVar, O);
748 EmitGlobalConstant(C);
753 /// runOnMachineFunction - This uses the printMachineInstruction()
754 /// method to print assembly for each instruction.
756 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
759 SetupMachineFunction(MF);
762 // Print out constants referenced by the function
763 EmitConstantPool(MF.getConstantPool());
765 // Print out labels for the function.
766 const Function *F = MF.getFunction();
767 SwitchToSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
769 switch (F->getLinkage()) {
770 default: llvm_unreachable("Unknown linkage type!");
771 case Function::PrivateLinkage:
772 case Function::LinkerPrivateLinkage:
773 case Function::InternalLinkage: // Symbols default to internal.
775 case Function::ExternalLinkage:
776 O << "\t.globl\t" << CurrentFnName << '\n';
778 case Function::WeakAnyLinkage:
779 case Function::WeakODRLinkage:
780 case Function::LinkOnceAnyLinkage:
781 case Function::LinkOnceODRLinkage:
782 O << "\t.globl\t" << CurrentFnName << '\n';
783 O << "\t.weak_definition\t" << CurrentFnName << '\n';
787 printVisibility(CurrentFnName, F->getVisibility());
789 EmitAlignment(MF.getAlignment(), F);
790 O << CurrentFnName << ":\n";
792 // Emit pre-function debug information.
793 DW->BeginFunction(&MF);
795 // If the function is empty, then we need to emit *something*. Otherwise, the
796 // function's label might be associated with something that it wasn't meant to
797 // be associated with. We emit a noop in this situation.
798 MachineFunction::iterator I = MF.begin();
800 if (++I == MF.end() && MF.front().empty())
803 // Print out code for the function.
804 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
806 // Print a label for the basic block.
807 if (I != MF.begin()) {
808 printBasicBlockLabel(I, true, true, VerboseAsm);
811 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
813 // Print the assembly for the instruction.
814 printMachineInstruction(II);
818 // Print out jump tables referenced by the function.
819 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
821 // Emit post-function debug information.
822 DW->EndFunction(&MF);
824 // We didn't modify anything.
829 bool PPCDarwinAsmPrinter::doInitialization(Module &M) {
830 static const char *const CPUDirectives[] = {
842 unsigned Directive = Subtarget.getDarwinDirective();
843 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
844 Directive = PPC::DIR_970;
845 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
846 Directive = PPC::DIR_7400;
847 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
848 Directive = PPC::DIR_64;
849 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
850 O << "\t.machine " << CPUDirectives[Directive] << '\n';
852 bool Result = AsmPrinter::doInitialization(M);
855 // Prime text sections so they are adjacent. This reduces the likelihood a
856 // large data or debug section causes a branch to exceed 16M limit.
857 SwitchToTextSection("\t.section __TEXT,__textcoal_nt,coalesced,"
858 "pure_instructions");
859 if (TM.getRelocationModel() == Reloc::PIC_) {
860 SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
861 "pure_instructions,32");
862 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
863 SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
864 "pure_instructions,16");
866 SwitchToSection(getObjFileLowering().getTextSection());
871 void PPCDarwinAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
872 const TargetData *TD = TM.getTargetData();
874 if (!GVar->hasInitializer())
875 return; // External global require no code
877 // Check to see if this is a special global used by LLVM, if so, emit it.
878 if (EmitSpecialLLVMGlobal(GVar)) {
879 if (TM.getRelocationModel() == Reloc::Static) {
880 if (GVar->getName() == "llvm.global_ctors")
881 O << ".reference .constructors_used\n";
882 else if (GVar->getName() == "llvm.global_dtors")
883 O << ".reference .destructors_used\n";
888 std::string name = Mang->getMangledName(GVar);
889 printVisibility(name, GVar->getVisibility());
891 Constant *C = GVar->getInitializer();
892 const Type *Type = C->getType();
893 unsigned Size = TD->getTypeAllocSize(Type);
894 unsigned Align = TD->getPreferredAlignmentLog(GVar);
896 const MCSection *TheSection =
897 getObjFileLowering().SectionForGlobal(GVar, Mang, TM);
898 SwitchToSection(TheSection);
900 if (C->isNullValue() && /* FIXME: Verify correct */
901 !GVar->hasSection() &&
902 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
903 GVar->isWeakForLinker()) &&
904 // Don't put things that should go in the cstring section into "comm".
905 !TheSection->getKind().isMergeableCString()) {
906 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
908 if (GVar->hasExternalLinkage()) {
909 O << "\t.globl " << name << '\n';
910 O << "\t.zerofill __DATA, __common, " << name << ", "
911 << Size << ", " << Align;
912 } else if (GVar->hasLocalLinkage()) {
913 O << TAI->getLCOMMDirective() << name << ',' << Size << ',' << Align;
914 } else if (!GVar->hasCommonLinkage()) {
915 O << "\t.globl " << name << '\n'
916 << TAI->getWeakDefDirective() << name << '\n';
917 EmitAlignment(Align, GVar);
920 O << "\t\t\t\t" << TAI->getCommentString() << " ";
921 PrintUnmangledNameSafely(GVar, O);
924 EmitGlobalConstant(C);
927 O << ".comm " << name << ',' << Size;
928 // Darwin 9 and above support aligned common data.
929 if (Subtarget.isDarwin9())
933 O << "\t\t" << TAI->getCommentString() << " '";
934 PrintUnmangledNameSafely(GVar, O);
941 switch (GVar->getLinkage()) {
942 case GlobalValue::LinkOnceAnyLinkage:
943 case GlobalValue::LinkOnceODRLinkage:
944 case GlobalValue::WeakAnyLinkage:
945 case GlobalValue::WeakODRLinkage:
946 case GlobalValue::CommonLinkage:
947 O << "\t.globl " << name << '\n'
948 << "\t.weak_definition " << name << '\n';
950 case GlobalValue::AppendingLinkage:
951 // FIXME: appending linkage variables should go into a section of
952 // their name or something. For now, just emit them as external.
953 case GlobalValue::ExternalLinkage:
954 // If external or appending, declare as a global symbol
955 O << "\t.globl " << name << '\n';
957 case GlobalValue::InternalLinkage:
958 case GlobalValue::PrivateLinkage:
959 case GlobalValue::LinkerPrivateLinkage:
962 llvm_unreachable("Unknown linkage type!");
965 EmitAlignment(Align, GVar);
968 O << "\t\t\t\t" << TAI->getCommentString() << " '";
969 PrintUnmangledNameSafely(GVar, O);
974 EmitGlobalConstant(C);
978 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
979 const TargetData *TD = TM.getTargetData();
981 bool isPPC64 = TD->getPointerSizeInBits() == 64;
983 // Output stubs for dynamically-linked functions
984 if (TM.getRelocationModel() == Reloc::PIC_ && !FnStubs.empty()) {
985 for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
987 SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
988 "pure_instructions,32");
990 const FnStubInfo &Info = I->second;
991 O << Info.Stub << ":\n";
992 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
994 O << "\tbcl 20,31," << Info.AnonSymbol << '\n';
995 O << Info.AnonSymbol << ":\n";
997 O << "\taddis r11,r11,ha16(" << Info.LazyPtr << "-" << Info.AnonSymbol;
1000 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1001 O << Info.LazyPtr << "-" << Info.AnonSymbol << ")(r11)\n";
1002 O << "\tmtctr r12\n";
1005 SwitchToDataSection(".lazy_symbol_pointer");
1006 O << Info.LazyPtr << ":\n";
1007 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1008 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1010 } else if (!FnStubs.empty()) {
1011 for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1013 SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
1014 "pure_instructions,16");
1016 const FnStubInfo &Info = I->second;
1017 O << Info.Stub << ":\n";
1018 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1019 O << "\tlis r11,ha16(" << Info.LazyPtr << ")\n";
1020 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1021 O << Info.LazyPtr << ")(r11)\n";
1022 O << "\tmtctr r12\n";
1024 SwitchToDataSection(".lazy_symbol_pointer");
1025 O << Info.LazyPtr << ":\n";
1026 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1027 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1033 if (TAI->doesSupportExceptionHandling() && MMI) {
1034 // Add the (possibly multiple) personalities to the set of global values.
1035 // Only referenced functions get into the Personalities list.
1036 const std::vector<Function *> &Personalities = MMI->getPersonalities();
1037 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1038 E = Personalities.end(); I != E; ++I) {
1040 GVStubs[Mang->getMangledName(*I)] =
1041 Mang->getMangledName(*I, "$non_lazy_ptr", true);
1045 // Output stubs for external and common global variables.
1046 if (!GVStubs.empty()) {
1047 SwitchToDataSection(".non_lazy_symbol_pointer");
1048 for (StringMap<std::string>::iterator I = GVStubs.begin(),
1049 E = GVStubs.end(); I != E; ++I) {
1050 O << I->second << ":\n";
1051 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1052 O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
1056 if (!HiddenGVStubs.empty()) {
1057 SwitchToSection(getObjFileLowering().getDataSection());
1058 EmitAlignment(isPPC64 ? 3 : 2);
1059 for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
1060 E = HiddenGVStubs.end(); I != E; ++I) {
1061 O << I->second << ":\n";
1062 O << (isPPC64 ? "\t.quad\t" : "\t.long\t") << I->getKeyData() << '\n';
1066 // Funny Darwin hack: This flag tells the linker that no global symbols
1067 // contain code that falls through to other global symbols (e.g. the obvious
1068 // implementation of multiple entry points). If this doesn't occur, the
1069 // linker can safely perform dead code stripping. Since LLVM never generates
1070 // code that does this, it is always safe to set.
1071 O << "\t.subsections_via_symbols\n";
1073 return AsmPrinter::doFinalization(M);
1078 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1079 /// for a MachineFunction to the given output stream, in a format that the
1080 /// Darwin assembler can deal with.
1082 static FunctionPass *createPPCAsmPrinterPass(formatted_raw_ostream &o,
1085 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1087 if (Subtarget->isDarwin())
1088 return new PPCDarwinAsmPrinter(o, tm, tm.getTargetAsmInfo(), verbose);
1089 return new PPCLinuxAsmPrinter(o, tm, tm.getTargetAsmInfo(), verbose);
1092 // Force static initialization.
1093 extern "C" void LLVMInitializePowerPCAsmPrinter() {
1094 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
1096 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);