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/MC/MCStreamer.h"
36 #include "llvm/MC/MCAsmInfo.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, TOC;
86 const PPCSubtarget &Subtarget;
89 explicit PPCAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
90 const MCAsmInfo *T, bool V)
91 : AsmPrinter(O, TM, T, V),
92 Subtarget(TM.getSubtarget<PPCSubtarget>()), LabelID(0) {}
94 virtual const char *getPassName() const {
95 return "PowerPC Assembly Printer";
98 PPCTargetMachine &getTM() {
99 return static_cast<PPCTargetMachine&>(TM);
102 unsigned enumRegToMachineReg(unsigned enumReg) {
104 default: llvm_unreachable("Unhandled register!");
105 case PPC::CR0: return 0;
106 case PPC::CR1: return 1;
107 case PPC::CR2: return 2;
108 case PPC::CR3: return 3;
109 case PPC::CR4: return 4;
110 case PPC::CR5: return 5;
111 case PPC::CR6: return 6;
112 case PPC::CR7: return 7;
117 /// printInstruction - This method is automatically generated by tablegen
118 /// from the instruction set description. This method returns true if the
119 /// machine instruction was sufficiently described to print it, otherwise it
121 void printInstruction(const MachineInstr *MI);
123 void printMachineInstruction(const MachineInstr *MI);
124 void printOp(const MachineOperand &MO);
126 /// stripRegisterPrefix - This method strips the character prefix from a
127 /// register name so that only the number is left. Used by for linux asm.
128 const char *stripRegisterPrefix(const char *RegName) {
129 switch (RegName[0]) {
132 case 'v': return RegName + 1;
133 case 'c': if (RegName[1] == 'r') return RegName + 2;
139 /// printRegister - Print register according to target requirements.
141 void printRegister(const MachineOperand &MO, bool R0AsZero) {
142 unsigned RegNo = MO.getReg();
143 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
145 // If we should use 0 for R0.
146 if (R0AsZero && RegNo == PPC::R0) {
151 const char *RegName = TM.getRegisterInfo()->get(RegNo).AsmName;
152 // Linux assembler (Others?) does not take register mnemonics.
153 // FIXME - What about special registers used in mfspr/mtspr?
154 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
158 void printOperand(const MachineInstr *MI, unsigned OpNo) {
159 const MachineOperand &MO = MI->getOperand(OpNo);
161 printRegister(MO, false);
162 } else if (MO.isImm()) {
169 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
170 unsigned AsmVariant, const char *ExtraCode);
171 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
172 unsigned AsmVariant, const char *ExtraCode);
175 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
176 char value = MI->getOperand(OpNo).getImm();
177 value = (value << (32-5)) >> (32-5);
180 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
181 unsigned char value = MI->getOperand(OpNo).getImm();
182 assert(value <= 31 && "Invalid u5imm argument!");
183 O << (unsigned int)value;
185 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
186 unsigned char value = MI->getOperand(OpNo).getImm();
187 assert(value <= 63 && "Invalid u6imm argument!");
188 O << (unsigned int)value;
190 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
191 O << (short)MI->getOperand(OpNo).getImm();
193 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
194 O << (unsigned short)MI->getOperand(OpNo).getImm();
196 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
197 if (MI->getOperand(OpNo).isImm()) {
198 O << (short)(MI->getOperand(OpNo).getImm()*4);
201 printOp(MI->getOperand(OpNo));
202 if (TM.getRelocationModel() == Reloc::PIC_)
203 O << "-\"L" << getFunctionNumber() << "$pb\")";
208 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
209 // Branches can take an immediate operand. This is used by the branch
210 // selection pass to print $+8, an eight byte displacement from the PC.
211 if (MI->getOperand(OpNo).isImm()) {
212 O << "$+" << MI->getOperand(OpNo).getImm()*4;
214 printOp(MI->getOperand(OpNo));
217 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
218 const MachineOperand &MO = MI->getOperand(OpNo);
219 if (TM.getRelocationModel() != Reloc::Static) {
220 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
221 GlobalValue *GV = MO.getGlobal();
222 if (GV->isDeclaration() || GV->isWeakForLinker()) {
223 // Dynamically-resolved functions need a stub for the function.
224 FnStubInfo &FnInfo = FnStubs[Mang->getMangledName(GV)];
225 FnInfo.Init(GV, Mang);
230 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
231 FnStubInfo &FnInfo =FnStubs[Mang->makeNameProper(MO.getSymbolName())];
232 FnInfo.Init(MO.getSymbolName(), Mang);
238 printOp(MI->getOperand(OpNo));
240 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
241 O << (int)MI->getOperand(OpNo).getImm()*4;
243 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
244 O << "\"L" << getFunctionNumber() << "$pb\"\n";
245 O << "\"L" << getFunctionNumber() << "$pb\":";
247 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
248 if (MI->getOperand(OpNo).isImm()) {
249 printS16ImmOperand(MI, OpNo);
251 if (Subtarget.isDarwin()) O << "ha16(";
252 printOp(MI->getOperand(OpNo));
253 if (TM.getRelocationModel() == Reloc::PIC_)
254 O << "-\"L" << getFunctionNumber() << "$pb\"";
255 if (Subtarget.isDarwin())
261 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
262 if (MI->getOperand(OpNo).isImm()) {
263 printS16ImmOperand(MI, OpNo);
265 if (Subtarget.isDarwin()) O << "lo16(";
266 printOp(MI->getOperand(OpNo));
267 if (TM.getRelocationModel() == Reloc::PIC_)
268 O << "-\"L" << getFunctionNumber() << "$pb\"";
269 if (Subtarget.isDarwin())
275 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
276 unsigned CCReg = MI->getOperand(OpNo).getReg();
277 unsigned RegNo = enumRegToMachineReg(CCReg);
278 O << (0x80 >> RegNo);
280 // The new addressing mode printers.
281 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
282 printSymbolLo(MI, OpNo);
284 if (MI->getOperand(OpNo+1).isReg() &&
285 MI->getOperand(OpNo+1).getReg() == PPC::R0)
288 printOperand(MI, OpNo+1);
291 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
292 if (MI->getOperand(OpNo).isImm())
293 printS16X4ImmOperand(MI, OpNo);
295 printSymbolLo(MI, OpNo);
297 if (MI->getOperand(OpNo+1).isReg() &&
298 MI->getOperand(OpNo+1).getReg() == PPC::R0)
301 printOperand(MI, OpNo+1);
305 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
306 // When used as the base register, r0 reads constant zero rather than
307 // the value contained in the register. For this reason, the darwin
308 // assembler requires that we print r0 as 0 (no r) when used as the base.
309 const MachineOperand &MO = MI->getOperand(OpNo);
310 printRegister(MO, true);
312 printOperand(MI, OpNo+1);
315 void printTOCEntryLabel(const MachineInstr *MI, unsigned OpNo) {
316 const MachineOperand &MO = MI->getOperand(OpNo);
318 assert(MO.getType() == MachineOperand::MO_GlobalAddress);
320 GlobalValue *GV = MO.getGlobal();
322 std::string Name = Mang->getMangledName(GV);
324 // Map symbol -> label of TOC entry.
325 if (TOC.count(Name) == 0) {
327 Label += MAI->getPrivateGlobalPrefix();
329 Label += utostr(LabelID++);
334 O << TOC[Name] << "@toc";
337 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
338 const char *Modifier);
340 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
342 virtual void EmitExternalGlobal(const GlobalVariable *GV);
345 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
346 class VISIBILITY_HIDDEN PPCLinuxAsmPrinter : public PPCAsmPrinter {
348 explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
349 const MCAsmInfo *T, bool V)
350 : PPCAsmPrinter(O, TM, T, V){}
352 virtual const char *getPassName() const {
353 return "Linux PPC Assembly Printer";
356 bool runOnMachineFunction(MachineFunction &F);
357 bool doFinalization(Module &M);
359 void getAnalysisUsage(AnalysisUsage &AU) const {
360 AU.setPreservesAll();
361 AU.addRequired<MachineModuleInfo>();
362 AU.addRequired<DwarfWriter>();
363 PPCAsmPrinter::getAnalysisUsage(AU);
366 void PrintGlobalVariable(const GlobalVariable *GVar);
369 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
371 class VISIBILITY_HIDDEN PPCDarwinAsmPrinter : public PPCAsmPrinter {
372 formatted_raw_ostream &OS;
374 explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
375 const MCAsmInfo *T, bool V)
376 : PPCAsmPrinter(O, TM, T, V), OS(O) {}
378 virtual const char *getPassName() const {
379 return "Darwin PPC Assembly Printer";
382 bool runOnMachineFunction(MachineFunction &F);
383 bool doInitialization(Module &M);
384 bool doFinalization(Module &M);
386 void getAnalysisUsage(AnalysisUsage &AU) const {
387 AU.setPreservesAll();
388 AU.addRequired<MachineModuleInfo>();
389 AU.addRequired<DwarfWriter>();
390 PPCAsmPrinter::getAnalysisUsage(AU);
393 void PrintGlobalVariable(const GlobalVariable *GVar);
395 } // end of anonymous namespace
397 // Include the auto-generated portion of the assembly writer
398 #include "PPCGenAsmWriter.inc"
400 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
401 switch (MO.getType()) {
402 case MachineOperand::MO_Immediate:
403 llvm_unreachable("printOp() does not handle immediate values");
405 case MachineOperand::MO_MachineBasicBlock:
406 printBasicBlockLabel(MO.getMBB());
408 case MachineOperand::MO_JumpTableIndex:
409 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
410 << '_' << MO.getIndex();
411 // FIXME: PIC relocation model
413 case MachineOperand::MO_ConstantPoolIndex:
414 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
415 << '_' << MO.getIndex();
417 case MachineOperand::MO_ExternalSymbol: {
418 // Computing the address of an external symbol, not calling it.
419 std::string Name(MAI->getGlobalPrefix());
420 Name += MO.getSymbolName();
422 if (TM.getRelocationModel() != Reloc::Static) {
423 GVStubs[Name] = Name+"$non_lazy_ptr";
424 Name += "$non_lazy_ptr";
429 case MachineOperand::MO_GlobalAddress: {
430 // Computing the address of a global symbol, not calling it.
431 GlobalValue *GV = MO.getGlobal();
434 // External or weakly linked global variables need non-lazily-resolved stubs
435 if (TM.getRelocationModel() != Reloc::Static &&
436 (GV->isDeclaration() || GV->isWeakForLinker())) {
437 if (!GV->hasHiddenVisibility()) {
438 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
439 GVStubs[Mang->getMangledName(GV)] = Name;
440 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
441 GV->hasAvailableExternallyLinkage()) {
442 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
443 HiddenGVStubs[Mang->getMangledName(GV)] = Name;
445 Name = Mang->getMangledName(GV);
448 Name = Mang->getMangledName(GV);
452 printOffset(MO.getOffset());
457 O << "<unknown operand type: " << MO.getType() << ">";
462 /// EmitExternalGlobal - In this case we need to use the indirect symbol.
464 void PPCAsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
467 if (TM.getRelocationModel() != Reloc::Static) {
468 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
470 Name = Mang->getMangledName(GV);
475 /// PrintAsmOperand - Print out an operand for an inline asm expression.
477 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
479 const char *ExtraCode) {
480 // Does this asm operand have a single letter operand modifier?
481 if (ExtraCode && ExtraCode[0]) {
482 if (ExtraCode[1] != 0) return true; // Unknown modifier.
484 switch (ExtraCode[0]) {
485 default: return true; // Unknown modifier.
486 case 'c': // Don't print "$" before a global var name or constant.
487 // PPC never has a prefix.
488 printOperand(MI, OpNo);
490 case 'L': // Write second word of DImode reference.
491 // Verify that this operand has two consecutive registers.
492 if (!MI->getOperand(OpNo).isReg() ||
493 OpNo+1 == MI->getNumOperands() ||
494 !MI->getOperand(OpNo+1).isReg())
496 ++OpNo; // Return the high-part.
499 // Write 'i' if an integer constant, otherwise nothing. Used to print
501 if (MI->getOperand(OpNo).isImm())
507 printOperand(MI, OpNo);
511 // At the moment, all inline asm memory operands are a single register.
512 // In any case, the output of this routine should always be just one
513 // assembler operand.
515 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
517 const char *ExtraCode) {
518 if (ExtraCode && ExtraCode[0])
519 return true; // Unknown modifier.
520 assert (MI->getOperand(OpNo).isReg());
522 printOperand(MI, OpNo);
527 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
528 const char *Modifier) {
529 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
530 unsigned Code = MI->getOperand(OpNo).getImm();
531 if (!strcmp(Modifier, "cc")) {
532 switch ((PPC::Predicate)Code) {
533 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
534 case PPC::PRED_LT: O << "lt"; return;
535 case PPC::PRED_LE: O << "le"; return;
536 case PPC::PRED_EQ: O << "eq"; return;
537 case PPC::PRED_GE: O << "ge"; return;
538 case PPC::PRED_GT: O << "gt"; return;
539 case PPC::PRED_NE: O << "ne"; return;
540 case PPC::PRED_UN: O << "un"; return;
541 case PPC::PRED_NU: O << "nu"; return;
545 assert(!strcmp(Modifier, "reg") &&
546 "Need to specify 'cc' or 'reg' as predicate op modifier!");
547 // Don't print the register for 'always'.
548 if (Code == PPC::PRED_ALWAYS) return;
549 printOperand(MI, OpNo+1);
554 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
555 /// the current output stream.
557 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
560 processDebugLoc(MI->getDebugLoc());
562 // Check for slwi/srwi mnemonics.
563 if (MI->getOpcode() == PPC::RLWINM) {
564 bool FoundMnemonic = false;
565 unsigned char SH = MI->getOperand(2).getImm();
566 unsigned char MB = MI->getOperand(3).getImm();
567 unsigned char ME = MI->getOperand(4).getImm();
568 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
569 O << "\tslwi "; FoundMnemonic = true;
571 if (SH <= 31 && MB == (32-SH) && ME == 31) {
572 O << "\tsrwi "; FoundMnemonic = true;
579 O << ", " << (unsigned int)SH << '\n';
582 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
583 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
591 } else if (MI->getOpcode() == PPC::RLDICR) {
592 unsigned char SH = MI->getOperand(2).getImm();
593 unsigned char ME = MI->getOperand(3).getImm();
594 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
600 O << ", " << (unsigned int)SH << '\n';
605 printInstruction(MI);
607 if (VerboseAsm && !MI->getDebugLoc().isUnknown())
612 /// runOnMachineFunction - This uses the printMachineInstruction()
613 /// method to print assembly for each instruction.
615 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
618 SetupMachineFunction(MF);
621 // Print out constants referenced by the function
622 EmitConstantPool(MF.getConstantPool());
624 // Print out labels for the function.
625 const Function *F = MF.getFunction();
626 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
628 switch (F->getLinkage()) {
629 default: llvm_unreachable("Unknown linkage type!");
630 case Function::PrivateLinkage:
631 case Function::InternalLinkage: // Symbols default to internal.
633 case Function::ExternalLinkage:
634 O << "\t.global\t" << CurrentFnName << '\n'
635 << "\t.type\t" << CurrentFnName << ", @function\n";
637 case Function::LinkerPrivateLinkage:
638 case Function::WeakAnyLinkage:
639 case Function::WeakODRLinkage:
640 case Function::LinkOnceAnyLinkage:
641 case Function::LinkOnceODRLinkage:
642 O << "\t.global\t" << CurrentFnName << '\n';
643 O << "\t.weak\t" << CurrentFnName << '\n';
647 printVisibility(CurrentFnName, F->getVisibility());
649 EmitAlignment(MF.getAlignment(), F);
651 if (Subtarget.isPPC64()) {
652 // Emit an official procedure descriptor.
653 // FIXME 64-bit SVR4: Use MCSection here?
654 O << "\t.section\t\".opd\",\"aw\"\n";
656 O << CurrentFnName << ":\n";
657 O << "\t.quad .L." << CurrentFnName << ",.TOC.@tocbase\n";
658 O << "\t.previous\n";
659 O << ".L." << CurrentFnName << ":\n";
661 O << CurrentFnName << ":\n";
664 // Emit pre-function debug information.
665 DW->BeginFunction(&MF);
667 // Print out code for the function.
668 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
670 // Print a label for the basic block.
671 if (I != MF.begin()) {
672 printBasicBlockLabel(I, true, true);
675 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
677 // Print the assembly for the instruction.
678 printMachineInstruction(II);
682 O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << '\n';
684 // Print out jump tables referenced by the function.
685 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
687 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
689 // Emit post-function debug information.
690 DW->EndFunction(&MF);
692 // We didn't modify anything.
696 void PPCLinuxAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
697 const TargetData *TD = TM.getTargetData();
699 if (!GVar->hasInitializer())
700 return; // External global require no code
702 // Check to see if this is a special global used by LLVM, if so, emit it.
703 if (EmitSpecialLLVMGlobal(GVar))
706 std::string name = Mang->getMangledName(GVar);
708 printVisibility(name, GVar->getVisibility());
710 Constant *C = GVar->getInitializer();
711 const Type *Type = C->getType();
712 unsigned Size = TD->getTypeAllocSize(Type);
713 unsigned Align = TD->getPreferredAlignmentLog(GVar);
715 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(GVar, Mang,
718 if (C->isNullValue() && /* FIXME: Verify correct */
719 !GVar->hasSection() &&
720 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
721 GVar->isWeakForLinker())) {
722 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
724 if (GVar->hasExternalLinkage()) {
725 O << "\t.global " << name << '\n';
726 O << "\t.type " << name << ", @object\n";
728 O << "\t.zero " << Size << '\n';
729 } else if (GVar->hasLocalLinkage()) {
730 O << MAI->getLCOMMDirective() << name << ',' << Size;
732 O << ".comm " << name << ',' << Size;
735 O << "\t\t" << MAI->getCommentString() << " '";
736 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
743 switch (GVar->getLinkage()) {
744 case GlobalValue::LinkOnceAnyLinkage:
745 case GlobalValue::LinkOnceODRLinkage:
746 case GlobalValue::WeakAnyLinkage:
747 case GlobalValue::WeakODRLinkage:
748 case GlobalValue::CommonLinkage:
749 case GlobalValue::LinkerPrivateLinkage:
750 O << "\t.global " << name << '\n'
751 << "\t.type " << name << ", @object\n"
752 << "\t.weak " << name << '\n';
754 case GlobalValue::AppendingLinkage:
755 // FIXME: appending linkage variables should go into a section of
756 // their name or something. For now, just emit them as external.
757 case GlobalValue::ExternalLinkage:
758 // If external or appending, declare as a global symbol
759 O << "\t.global " << name << '\n'
760 << "\t.type " << name << ", @object\n";
762 case GlobalValue::InternalLinkage:
763 case GlobalValue::PrivateLinkage:
766 llvm_unreachable("Unknown linkage type!");
769 EmitAlignment(Align, GVar);
772 O << "\t\t\t\t" << MAI->getCommentString() << " '";
773 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
778 EmitGlobalConstant(C);
782 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
783 const TargetData *TD = TM.getTargetData();
785 bool isPPC64 = TD->getPointerSizeInBits() == 64;
787 if (isPPC64 && !TOC.empty()) {
788 // FIXME 64-bit SVR4: Use MCSection here?
789 O << "\t.section\t\".toc\",\"aw\"\n";
791 for (StringMap<std::string>::iterator I = TOC.begin(), E = TOC.end();
793 O << I->second << ":\n";
794 O << "\t.tc " << I->getKeyData() << "[TC]," << I->getKeyData() << '\n';
798 return AsmPrinter::doFinalization(M);
801 /// runOnMachineFunction - This uses the printMachineInstruction()
802 /// method to print assembly for each instruction.
804 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
807 SetupMachineFunction(MF);
810 // Print out constants referenced by the function
811 EmitConstantPool(MF.getConstantPool());
813 // Print out labels for the function.
814 const Function *F = MF.getFunction();
815 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
817 switch (F->getLinkage()) {
818 default: llvm_unreachable("Unknown linkage type!");
819 case Function::PrivateLinkage:
820 case Function::InternalLinkage: // Symbols default to internal.
822 case Function::ExternalLinkage:
823 O << "\t.globl\t" << CurrentFnName << '\n';
825 case Function::WeakAnyLinkage:
826 case Function::WeakODRLinkage:
827 case Function::LinkOnceAnyLinkage:
828 case Function::LinkOnceODRLinkage:
829 case Function::LinkerPrivateLinkage:
830 O << "\t.globl\t" << CurrentFnName << '\n';
831 O << "\t.weak_definition\t" << CurrentFnName << '\n';
835 printVisibility(CurrentFnName, F->getVisibility());
837 EmitAlignment(MF.getAlignment(), F);
838 O << CurrentFnName << ":\n";
840 // Emit pre-function debug information.
841 DW->BeginFunction(&MF);
843 // If the function is empty, then we need to emit *something*. Otherwise, the
844 // function's label might be associated with something that it wasn't meant to
845 // be associated with. We emit a noop in this situation.
846 MachineFunction::iterator I = MF.begin();
848 if (++I == MF.end() && MF.front().empty())
851 // Print out code for the function.
852 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
854 // Print a label for the basic block.
855 if (I != MF.begin()) {
856 printBasicBlockLabel(I, true, true, VerboseAsm);
859 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
861 // Print the assembly for the instruction.
862 printMachineInstruction(II);
866 // Print out jump tables referenced by the function.
867 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
869 // Emit post-function debug information.
870 DW->EndFunction(&MF);
872 // We didn't modify anything.
877 bool PPCDarwinAsmPrinter::doInitialization(Module &M) {
878 static const char *const CPUDirectives[] = {
890 unsigned Directive = Subtarget.getDarwinDirective();
891 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
892 Directive = PPC::DIR_970;
893 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
894 Directive = PPC::DIR_7400;
895 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
896 Directive = PPC::DIR_64;
897 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
898 O << "\t.machine " << CPUDirectives[Directive] << '\n';
900 bool Result = AsmPrinter::doInitialization(M);
903 // Prime text sections so they are adjacent. This reduces the likelihood a
904 // large data or debug section causes a branch to exceed 16M limit.
905 TargetLoweringObjectFileMachO &TLOFMacho =
906 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
907 OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
908 if (TM.getRelocationModel() == Reloc::PIC_) {
909 OutStreamer.SwitchSection(
910 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
911 MCSectionMachO::S_SYMBOL_STUBS |
912 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
913 32, SectionKind::getText()));
914 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
915 OutStreamer.SwitchSection(
916 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
917 MCSectionMachO::S_SYMBOL_STUBS |
918 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
919 16, SectionKind::getText()));
921 OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
926 void PPCDarwinAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
927 const TargetData *TD = TM.getTargetData();
929 if (!GVar->hasInitializer())
930 return; // External global require no code
932 // Check to see if this is a special global used by LLVM, if so, emit it.
933 if (EmitSpecialLLVMGlobal(GVar)) {
934 if (TM.getRelocationModel() == Reloc::Static) {
935 if (GVar->getName() == "llvm.global_ctors")
936 O << ".reference .constructors_used\n";
937 else if (GVar->getName() == "llvm.global_dtors")
938 O << ".reference .destructors_used\n";
943 std::string name = Mang->getMangledName(GVar);
944 printVisibility(name, GVar->getVisibility());
946 Constant *C = GVar->getInitializer();
947 const Type *Type = C->getType();
948 unsigned Size = TD->getTypeAllocSize(Type);
949 unsigned Align = TD->getPreferredAlignmentLog(GVar);
951 const MCSection *TheSection =
952 getObjFileLowering().SectionForGlobal(GVar, Mang, TM);
953 OutStreamer.SwitchSection(TheSection);
955 /// FIXME: Drive this off the section!
956 if (C->isNullValue() && /* FIXME: Verify correct */
957 !GVar->hasSection() &&
958 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
959 GVar->isWeakForLinker()) &&
960 // Don't put things that should go in the cstring section into "comm".
961 !TheSection->getKind().isMergeableCString()) {
962 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
964 if (GVar->hasExternalLinkage()) {
965 O << "\t.globl " << name << '\n';
966 O << "\t.zerofill __DATA, __common, " << name << ", "
967 << Size << ", " << Align;
968 } else if (GVar->hasLocalLinkage()) {
969 O << MAI->getLCOMMDirective() << name << ',' << Size << ',' << Align;
970 } else if (!GVar->hasCommonLinkage()) {
971 O << "\t.globl " << name << '\n'
972 << MAI->getWeakDefDirective() << name << '\n';
973 EmitAlignment(Align, GVar);
976 O << "\t\t\t\t" << MAI->getCommentString() << " ";
977 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
980 EmitGlobalConstant(C);
983 O << ".comm " << name << ',' << Size;
984 // Darwin 9 and above support aligned common data.
985 if (Subtarget.isDarwin9())
989 O << "\t\t" << MAI->getCommentString() << " '";
990 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
997 switch (GVar->getLinkage()) {
998 case GlobalValue::LinkOnceAnyLinkage:
999 case GlobalValue::LinkOnceODRLinkage:
1000 case GlobalValue::WeakAnyLinkage:
1001 case GlobalValue::WeakODRLinkage:
1002 case GlobalValue::CommonLinkage:
1003 case GlobalValue::LinkerPrivateLinkage:
1004 O << "\t.globl " << name << '\n'
1005 << "\t.weak_definition " << name << '\n';
1007 case GlobalValue::AppendingLinkage:
1008 // FIXME: appending linkage variables should go into a section of
1009 // their name or something. For now, just emit them as external.
1010 case GlobalValue::ExternalLinkage:
1011 // If external or appending, declare as a global symbol
1012 O << "\t.globl " << name << '\n';
1014 case GlobalValue::InternalLinkage:
1015 case GlobalValue::PrivateLinkage:
1018 llvm_unreachable("Unknown linkage type!");
1021 EmitAlignment(Align, GVar);
1024 O << "\t\t\t\t" << MAI->getCommentString() << " '";
1025 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1030 EmitGlobalConstant(C);
1034 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
1035 const TargetData *TD = TM.getTargetData();
1037 bool isPPC64 = TD->getPointerSizeInBits() == 64;
1039 // Darwin/PPC always uses mach-o.
1040 TargetLoweringObjectFileMachO &TLOFMacho =
1041 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
1044 const MCSection *LSPSection = 0;
1045 if (!FnStubs.empty()) // .lazy_symbol_pointer
1046 LSPSection = TLOFMacho.getLazySymbolPointerSection();
1049 // Output stubs for dynamically-linked functions
1050 if (TM.getRelocationModel() == Reloc::PIC_ && !FnStubs.empty()) {
1051 const MCSection *StubSection =
1052 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
1053 MCSectionMachO::S_SYMBOL_STUBS |
1054 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1055 32, SectionKind::getText());
1056 for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1058 OutStreamer.SwitchSection(StubSection);
1060 const FnStubInfo &Info = I->second;
1061 O << Info.Stub << ":\n";
1062 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1064 O << "\tbcl 20,31," << Info.AnonSymbol << '\n';
1065 O << Info.AnonSymbol << ":\n";
1066 O << "\tmflr r11\n";
1067 O << "\taddis r11,r11,ha16(" << Info.LazyPtr << "-" << Info.AnonSymbol;
1070 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1071 O << Info.LazyPtr << "-" << Info.AnonSymbol << ")(r11)\n";
1072 O << "\tmtctr r12\n";
1075 OutStreamer.SwitchSection(LSPSection);
1076 O << Info.LazyPtr << ":\n";
1077 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1078 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1080 } else if (!FnStubs.empty()) {
1081 const MCSection *StubSection =
1082 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
1083 MCSectionMachO::S_SYMBOL_STUBS |
1084 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1085 16, SectionKind::getText());
1087 for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1089 OutStreamer.SwitchSection(StubSection);
1091 const FnStubInfo &Info = I->second;
1092 O << Info.Stub << ":\n";
1093 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1094 O << "\tlis r11,ha16(" << Info.LazyPtr << ")\n";
1095 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1096 O << Info.LazyPtr << ")(r11)\n";
1097 O << "\tmtctr r12\n";
1099 OutStreamer.SwitchSection(LSPSection);
1100 O << Info.LazyPtr << ":\n";
1101 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1102 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1108 if (MAI->doesSupportExceptionHandling() && MMI) {
1109 // Add the (possibly multiple) personalities to the set of global values.
1110 // Only referenced functions get into the Personalities list.
1111 const std::vector<Function *> &Personalities = MMI->getPersonalities();
1112 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1113 E = Personalities.end(); I != E; ++I) {
1115 GVStubs[Mang->getMangledName(*I)] =
1116 Mang->getMangledName(*I, "$non_lazy_ptr", true);
1120 // Output macho stubs for external and common global variables.
1121 if (!GVStubs.empty()) {
1122 // Switch with ".non_lazy_symbol_pointer" directive.
1123 OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
1124 EmitAlignment(isPPC64 ? 3 : 2);
1126 for (StringMap<std::string>::iterator I = GVStubs.begin(),
1127 E = GVStubs.end(); I != E; ++I) {
1128 O << I->second << ":\n";
1129 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1130 O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
1134 if (!HiddenGVStubs.empty()) {
1135 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
1136 EmitAlignment(isPPC64 ? 3 : 2);
1137 for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
1138 E = HiddenGVStubs.end(); I != E; ++I) {
1139 O << I->second << ":\n";
1140 O << (isPPC64 ? "\t.quad\t" : "\t.long\t") << I->getKeyData() << '\n';
1144 // Funny Darwin hack: This flag tells the linker that no global symbols
1145 // contain code that falls through to other global symbols (e.g. the obvious
1146 // implementation of multiple entry points). If this doesn't occur, the
1147 // linker can safely perform dead code stripping. Since LLVM never generates
1148 // code that does this, it is always safe to set.
1149 O << "\t.subsections_via_symbols\n";
1151 return AsmPrinter::doFinalization(M);
1156 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1157 /// for a MachineFunction to the given output stream, in a format that the
1158 /// Darwin assembler can deal with.
1160 static AsmPrinter *createPPCAsmPrinterPass(formatted_raw_ostream &o,
1162 const MCAsmInfo *tai,
1164 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1166 if (Subtarget->isDarwin())
1167 return new PPCDarwinAsmPrinter(o, tm, tai, verbose);
1168 return new PPCLinuxAsmPrinter(o, tm, tai, verbose);
1171 // Force static initialization.
1172 extern "C" void LLVMInitializePowerPCAsmPrinter() {
1173 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
1174 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);