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/Support/Mangler.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/Compiler.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetAsmInfo.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetInstrInfo.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/StringSet.h"
49 STATISTIC(EmittedInsts, "Number of machine instrs printed");
52 class VISIBILITY_HIDDEN PPCAsmPrinter : public AsmPrinter {
54 StringSet<> FnStubs, GVStubs, HiddenGVStubs;
55 const PPCSubtarget &Subtarget;
57 explicit PPCAsmPrinter(raw_ostream &O, TargetMachine &TM,
58 const TargetAsmInfo *T, CodeGenOpt::Level OL,
60 : AsmPrinter(O, TM, T, OL, V),
61 Subtarget(TM.getSubtarget<PPCSubtarget>()) {}
63 virtual const char *getPassName() const {
64 return "PowerPC Assembly Printer";
67 PPCTargetMachine &getTM() {
68 return static_cast<PPCTargetMachine&>(TM);
71 unsigned enumRegToMachineReg(unsigned enumReg) {
73 default: assert(0 && "Unhandled register!"); break;
74 case PPC::CR0: return 0;
75 case PPC::CR1: return 1;
76 case PPC::CR2: return 2;
77 case PPC::CR3: return 3;
78 case PPC::CR4: return 4;
79 case PPC::CR5: return 5;
80 case PPC::CR6: return 6;
81 case PPC::CR7: return 7;
86 /// printInstruction - This method is automatically generated by tablegen
87 /// from the instruction set description. This method returns true if the
88 /// machine instruction was sufficiently described to print it, otherwise it
90 bool printInstruction(const MachineInstr *MI);
92 void printMachineInstruction(const MachineInstr *MI);
93 void printOp(const MachineOperand &MO);
95 /// stripRegisterPrefix - This method strips the character prefix from a
96 /// register name so that only the number is left. Used by for linux asm.
97 const char *stripRegisterPrefix(const char *RegName) {
101 case 'v': return RegName + 1;
102 case 'c': if (RegName[1] == 'r') return RegName + 2;
108 /// printRegister - Print register according to target requirements.
110 void printRegister(const MachineOperand &MO, bool R0AsZero) {
111 unsigned RegNo = MO.getReg();
112 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
114 // If we should use 0 for R0.
115 if (R0AsZero && RegNo == PPC::R0) {
120 const char *RegName = TM.getRegisterInfo()->get(RegNo).AsmName;
121 // Linux assembler (Others?) does not take register mnemonics.
122 // FIXME - What about special registers used in mfspr/mtspr?
123 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
127 void printOperand(const MachineInstr *MI, unsigned OpNo) {
128 const MachineOperand &MO = MI->getOperand(OpNo);
130 printRegister(MO, false);
131 } else if (MO.isImm()) {
138 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
139 unsigned AsmVariant, const char *ExtraCode);
140 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
141 unsigned AsmVariant, const char *ExtraCode);
144 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
145 char value = MI->getOperand(OpNo).getImm();
146 value = (value << (32-5)) >> (32-5);
149 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
150 unsigned char value = MI->getOperand(OpNo).getImm();
151 assert(value <= 31 && "Invalid u5imm argument!");
152 O << (unsigned int)value;
154 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
155 unsigned char value = MI->getOperand(OpNo).getImm();
156 assert(value <= 63 && "Invalid u6imm argument!");
157 O << (unsigned int)value;
159 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
160 O << (short)MI->getOperand(OpNo).getImm();
162 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
163 O << (unsigned short)MI->getOperand(OpNo).getImm();
165 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
166 if (MI->getOperand(OpNo).isImm()) {
167 O << (short)(MI->getOperand(OpNo).getImm()*4);
170 printOp(MI->getOperand(OpNo));
171 if (TM.getRelocationModel() == Reloc::PIC_)
172 O << "-\"L" << getFunctionNumber() << "$pb\")";
177 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
178 // Branches can take an immediate operand. This is used by the branch
179 // selection pass to print $+8, an eight byte displacement from the PC.
180 if (MI->getOperand(OpNo).isImm()) {
181 O << "$+" << MI->getOperand(OpNo).getImm()*4;
183 printOp(MI->getOperand(OpNo));
186 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
187 const MachineOperand &MO = MI->getOperand(OpNo);
188 if (TM.getRelocationModel() != Reloc::Static) {
189 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
190 GlobalValue *GV = MO.getGlobal();
191 if (((GV->isDeclaration() || GV->hasWeakLinkage() ||
192 GV->hasLinkOnceLinkage() || GV->hasCommonLinkage()))) {
193 // Dynamically-resolved functions need a stub for the function.
194 std::string Name = Mang->getValueName(GV);
195 FnStubs.insert(Name);
196 printSuffixedName(Name, "$stub");
200 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
201 std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
202 FnStubs.insert(Name);
203 printSuffixedName(Name, "$stub");
208 printOp(MI->getOperand(OpNo));
210 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
211 O << (int)MI->getOperand(OpNo).getImm()*4;
213 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
214 O << "\"L" << getFunctionNumber() << "$pb\"\n";
215 O << "\"L" << getFunctionNumber() << "$pb\":";
217 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
218 if (MI->getOperand(OpNo).isImm()) {
219 printS16ImmOperand(MI, OpNo);
221 if (Subtarget.isDarwin()) O << "ha16(";
222 printOp(MI->getOperand(OpNo));
223 if (TM.getRelocationModel() == Reloc::PIC_)
224 O << "-\"L" << getFunctionNumber() << "$pb\"";
225 if (Subtarget.isDarwin())
231 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
232 if (MI->getOperand(OpNo).isImm()) {
233 printS16ImmOperand(MI, OpNo);
235 if (Subtarget.isDarwin()) O << "lo16(";
236 printOp(MI->getOperand(OpNo));
237 if (TM.getRelocationModel() == Reloc::PIC_)
238 O << "-\"L" << getFunctionNumber() << "$pb\"";
239 if (Subtarget.isDarwin())
245 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
246 unsigned CCReg = MI->getOperand(OpNo).getReg();
247 unsigned RegNo = enumRegToMachineReg(CCReg);
248 O << (0x80 >> RegNo);
250 // The new addressing mode printers.
251 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
252 printSymbolLo(MI, OpNo);
254 if (MI->getOperand(OpNo+1).isReg() &&
255 MI->getOperand(OpNo+1).getReg() == PPC::R0)
258 printOperand(MI, OpNo+1);
261 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
262 if (MI->getOperand(OpNo).isImm())
263 printS16X4ImmOperand(MI, OpNo);
265 printSymbolLo(MI, OpNo);
267 if (MI->getOperand(OpNo+1).isReg() &&
268 MI->getOperand(OpNo+1).getReg() == PPC::R0)
271 printOperand(MI, OpNo+1);
275 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
276 // When used as the base register, r0 reads constant zero rather than
277 // the value contained in the register. For this reason, the darwin
278 // assembler requires that we print r0 as 0 (no r) when used as the base.
279 const MachineOperand &MO = MI->getOperand(OpNo);
280 printRegister(MO, true);
282 printOperand(MI, OpNo+1);
285 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
286 const char *Modifier);
288 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
289 virtual bool doFinalization(Module &M) = 0;
291 virtual void EmitExternalGlobal(const GlobalVariable *GV);
294 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
295 class VISIBILITY_HIDDEN PPCLinuxAsmPrinter : public PPCAsmPrinter {
297 explicit PPCLinuxAsmPrinter(raw_ostream &O, PPCTargetMachine &TM,
298 const TargetAsmInfo *T, CodeGenOpt::Level OL,
300 : PPCAsmPrinter(O, TM, T, OL, V){}
302 virtual const char *getPassName() const {
303 return "Linux PPC Assembly Printer";
306 bool runOnMachineFunction(MachineFunction &F);
307 bool doFinalization(Module &M);
309 void getAnalysisUsage(AnalysisUsage &AU) const {
310 AU.setPreservesAll();
311 AU.addRequired<MachineModuleInfo>();
312 AU.addRequired<DwarfWriter>();
313 PPCAsmPrinter::getAnalysisUsage(AU);
316 void printModuleLevelGV(const GlobalVariable* GVar);
319 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
321 class VISIBILITY_HIDDEN PPCDarwinAsmPrinter : public PPCAsmPrinter {
324 explicit PPCDarwinAsmPrinter(raw_ostream &O, PPCTargetMachine &TM,
325 const TargetAsmInfo *T, CodeGenOpt::Level OL,
327 : PPCAsmPrinter(O, TM, T, OL, V), OS(O) {}
329 virtual const char *getPassName() const {
330 return "Darwin PPC Assembly Printer";
333 bool runOnMachineFunction(MachineFunction &F);
334 bool doInitialization(Module &M);
335 bool doFinalization(Module &M);
337 void getAnalysisUsage(AnalysisUsage &AU) const {
338 AU.setPreservesAll();
339 AU.addRequired<MachineModuleInfo>();
340 AU.addRequired<DwarfWriter>();
341 PPCAsmPrinter::getAnalysisUsage(AU);
344 void printModuleLevelGV(const GlobalVariable* GVar);
346 } // end of anonymous namespace
348 // Include the auto-generated portion of the assembly writer
349 #include "PPCGenAsmWriter.inc"
351 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
352 switch (MO.getType()) {
353 case MachineOperand::MO_Immediate:
354 cerr << "printOp() does not handle immediate values\n";
358 case MachineOperand::MO_MachineBasicBlock:
359 printBasicBlockLabel(MO.getMBB());
361 case MachineOperand::MO_JumpTableIndex:
362 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
363 << '_' << MO.getIndex();
364 // FIXME: PIC relocation model
366 case MachineOperand::MO_ConstantPoolIndex:
367 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
368 << '_' << MO.getIndex();
370 case MachineOperand::MO_ExternalSymbol:
371 // Computing the address of an external symbol, not calling it.
372 if (TM.getRelocationModel() != Reloc::Static) {
373 std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
374 GVStubs.insert(Name);
375 printSuffixedName(Name, "$non_lazy_ptr");
378 O << TAI->getGlobalPrefix() << MO.getSymbolName();
380 case MachineOperand::MO_GlobalAddress: {
381 // Computing the address of a global symbol, not calling it.
382 GlobalValue *GV = MO.getGlobal();
383 std::string Name = Mang->getValueName(GV);
385 // External or weakly linked global variables need non-lazily-resolved stubs
386 if (TM.getRelocationModel() != Reloc::Static) {
387 if (GV->isDeclaration() || GV->isWeakForLinker()) {
388 if (GV->hasHiddenVisibility()) {
389 if (!GV->isDeclaration() && !GV->hasCommonLinkage())
392 HiddenGVStubs.insert(Name);
393 printSuffixedName(Name, "$non_lazy_ptr");
396 GVStubs.insert(Name);
397 printSuffixedName(Name, "$non_lazy_ptr");
404 printOffset(MO.getOffset());
409 O << "<unknown operand type: " << MO.getType() << ">";
414 /// EmitExternalGlobal - In this case we need to use the indirect symbol.
416 void PPCAsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
418 getGlobalLinkName(GV, Name);
419 if (TM.getRelocationModel() != Reloc::Static) {
420 if (GV->hasHiddenVisibility())
421 HiddenGVStubs.insert(Name);
423 GVStubs.insert(Name);
424 printSuffixedName(Name, "$non_lazy_ptr");
430 /// PrintAsmOperand - Print out an operand for an inline asm expression.
432 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
434 const char *ExtraCode) {
435 // Does this asm operand have a single letter operand modifier?
436 if (ExtraCode && ExtraCode[0]) {
437 if (ExtraCode[1] != 0) return true; // Unknown modifier.
439 switch (ExtraCode[0]) {
440 default: return true; // Unknown modifier.
441 case 'c': // Don't print "$" before a global var name or constant.
442 // PPC never has a prefix.
443 printOperand(MI, OpNo);
445 case 'L': // Write second word of DImode reference.
446 // Verify that this operand has two consecutive registers.
447 if (!MI->getOperand(OpNo).isReg() ||
448 OpNo+1 == MI->getNumOperands() ||
449 !MI->getOperand(OpNo+1).isReg())
451 ++OpNo; // Return the high-part.
454 // Write 'i' if an integer constant, otherwise nothing. Used to print
456 if (MI->getOperand(OpNo).isImm())
462 printOperand(MI, OpNo);
466 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
468 const char *ExtraCode) {
469 if (ExtraCode && ExtraCode[0])
470 return true; // Unknown modifier.
471 if (MI->getOperand(OpNo).isReg())
472 printMemRegReg(MI, OpNo);
474 printMemRegImm(MI, OpNo);
478 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
479 const char *Modifier) {
480 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
481 unsigned Code = MI->getOperand(OpNo).getImm();
482 if (!strcmp(Modifier, "cc")) {
483 switch ((PPC::Predicate)Code) {
484 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
485 case PPC::PRED_LT: O << "lt"; return;
486 case PPC::PRED_LE: O << "le"; return;
487 case PPC::PRED_EQ: O << "eq"; return;
488 case PPC::PRED_GE: O << "ge"; return;
489 case PPC::PRED_GT: O << "gt"; return;
490 case PPC::PRED_NE: O << "ne"; return;
491 case PPC::PRED_UN: O << "un"; return;
492 case PPC::PRED_NU: O << "nu"; return;
496 assert(!strcmp(Modifier, "reg") &&
497 "Need to specify 'cc' or 'reg' as predicate op modifier!");
498 // Don't print the register for 'always'.
499 if (Code == PPC::PRED_ALWAYS) return;
500 printOperand(MI, OpNo+1);
505 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
506 /// the current output stream.
508 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
511 // Check for slwi/srwi mnemonics.
512 if (MI->getOpcode() == PPC::RLWINM) {
513 bool FoundMnemonic = false;
514 unsigned char SH = MI->getOperand(2).getImm();
515 unsigned char MB = MI->getOperand(3).getImm();
516 unsigned char ME = MI->getOperand(4).getImm();
517 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
518 O << "\tslwi "; FoundMnemonic = true;
520 if (SH <= 31 && MB == (32-SH) && ME == 31) {
521 O << "\tsrwi "; FoundMnemonic = true;
528 O << ", " << (unsigned int)SH << '\n';
531 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
532 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
540 } else if (MI->getOpcode() == PPC::RLDICR) {
541 unsigned char SH = MI->getOperand(2).getImm();
542 unsigned char ME = MI->getOperand(3).getImm();
543 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
549 O << ", " << (unsigned int)SH << '\n';
554 if (printInstruction(MI))
555 return; // Printer was automatically generated
557 assert(0 && "Unhandled instruction in asm writer!");
562 /// runOnMachineFunction - This uses the printMachineInstruction()
563 /// method to print assembly for each instruction.
565 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
568 SetupMachineFunction(MF);
571 // Print out constants referenced by the function
572 EmitConstantPool(MF.getConstantPool());
574 // Print out labels for the function.
575 const Function *F = MF.getFunction();
576 SwitchToSection(TAI->SectionForGlobal(F));
578 switch (F->getLinkage()) {
579 default: assert(0 && "Unknown linkage type!");
580 case Function::PrivateLinkage:
581 case Function::InternalLinkage: // Symbols default to internal.
583 case Function::ExternalLinkage:
584 O << "\t.global\t" << CurrentFnName << '\n'
585 << "\t.type\t" << CurrentFnName << ", @function\n";
587 case Function::WeakAnyLinkage:
588 case Function::WeakODRLinkage:
589 case Function::LinkOnceAnyLinkage:
590 case Function::LinkOnceODRLinkage:
591 O << "\t.global\t" << CurrentFnName << '\n';
592 O << "\t.weak\t" << CurrentFnName << '\n';
596 printVisibility(CurrentFnName, F->getVisibility());
599 O << CurrentFnName << ":\n";
601 // Emit pre-function debug information.
602 DW->BeginFunction(&MF);
604 // Print out code for the function.
605 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
607 // Print a label for the basic block.
608 if (I != MF.begin()) {
609 printBasicBlockLabel(I, true, true);
612 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
614 // Print the assembly for the instruction.
615 printMachineInstruction(II);
619 O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << '\n';
621 // Print out jump tables referenced by the function.
622 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
624 SwitchToSection(TAI->SectionForGlobal(F));
626 // Emit post-function debug information.
627 DW->EndFunction(&MF);
631 // We didn't modify anything.
635 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
636 /// Don't print things like \\n or \\0.
637 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
638 for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
644 void PPCLinuxAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
645 const TargetData *TD = TM.getTargetData();
647 if (!GVar->hasInitializer())
648 return; // External global require no code
650 // Check to see if this is a special global used by LLVM, if so, emit it.
651 if (EmitSpecialLLVMGlobal(GVar))
654 std::string name = Mang->getValueName(GVar);
656 printVisibility(name, GVar->getVisibility());
658 Constant *C = GVar->getInitializer();
659 const Type *Type = C->getType();
660 unsigned Size = TD->getTypeAllocSize(Type);
661 unsigned Align = TD->getPreferredAlignmentLog(GVar);
663 SwitchToSection(TAI->SectionForGlobal(GVar));
665 if (C->isNullValue() && /* FIXME: Verify correct */
666 !GVar->hasSection() &&
667 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
668 GVar->isWeakForLinker())) {
669 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
671 if (GVar->hasExternalLinkage()) {
672 O << "\t.global " << name << '\n';
673 O << "\t.type " << name << ", @object\n";
675 O << "\t.zero " << Size << '\n';
676 } else if (GVar->hasLocalLinkage()) {
677 O << TAI->getLCOMMDirective() << name << ',' << Size;
679 O << ".comm " << name << ',' << Size;
682 O << "\t\t" << TAI->getCommentString() << " '";
683 PrintUnmangledNameSafely(GVar, O);
690 switch (GVar->getLinkage()) {
691 case GlobalValue::LinkOnceAnyLinkage:
692 case GlobalValue::LinkOnceODRLinkage:
693 case GlobalValue::WeakAnyLinkage:
694 case GlobalValue::WeakODRLinkage:
695 case GlobalValue::CommonLinkage:
696 O << "\t.global " << name << '\n'
697 << "\t.type " << name << ", @object\n"
698 << "\t.weak " << name << '\n';
700 case GlobalValue::AppendingLinkage:
701 // FIXME: appending linkage variables should go into a section of
702 // their name or something. For now, just emit them as external.
703 case GlobalValue::ExternalLinkage:
704 // If external or appending, declare as a global symbol
705 O << "\t.global " << name << '\n'
706 << "\t.type " << name << ", @object\n";
708 case GlobalValue::InternalLinkage:
709 case GlobalValue::PrivateLinkage:
712 cerr << "Unknown linkage type!";
716 EmitAlignment(Align, GVar);
719 O << "\t\t\t\t" << TAI->getCommentString() << " '";
720 PrintUnmangledNameSafely(GVar, O);
725 EmitGlobalConstant(C);
729 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
730 // Print out module-level global variables here.
731 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
733 printModuleLevelGV(I);
735 return AsmPrinter::doFinalization(M);
738 /// runOnMachineFunction - This uses the printMachineInstruction()
739 /// method to print assembly for each instruction.
741 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
744 SetupMachineFunction(MF);
747 // Print out constants referenced by the function
748 EmitConstantPool(MF.getConstantPool());
750 // Print out labels for the function.
751 const Function *F = MF.getFunction();
752 SwitchToSection(TAI->SectionForGlobal(F));
754 switch (F->getLinkage()) {
755 default: assert(0 && "Unknown linkage type!");
756 case Function::PrivateLinkage:
757 case Function::InternalLinkage: // Symbols default to internal.
759 case Function::ExternalLinkage:
760 O << "\t.globl\t" << CurrentFnName << '\n';
762 case Function::WeakAnyLinkage:
763 case Function::WeakODRLinkage:
764 case Function::LinkOnceAnyLinkage:
765 case Function::LinkOnceODRLinkage:
766 O << "\t.globl\t" << CurrentFnName << '\n';
767 O << "\t.weak_definition\t" << CurrentFnName << '\n';
771 printVisibility(CurrentFnName, F->getVisibility());
773 EmitAlignment(F->hasFnAttr(Attribute::OptimizeForSize) ? 2 : 4, F);
774 O << CurrentFnName << ":\n";
776 // Emit pre-function debug information.
777 DW->BeginFunction(&MF);
779 // If the function is empty, then we need to emit *something*. Otherwise, the
780 // function's label might be associated with something that it wasn't meant to
781 // be associated with. We emit a noop in this situation.
782 MachineFunction::iterator I = MF.begin();
784 if (++I == MF.end() && MF.front().empty())
787 // Print out code for the function.
788 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
790 // Print a label for the basic block.
791 if (I != MF.begin()) {
792 printBasicBlockLabel(I, true, true, VerboseAsm);
795 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
797 // Print the assembly for the instruction.
798 printMachineInstruction(II);
802 // Print out jump tables referenced by the function.
803 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
805 // Emit post-function debug information.
806 DW->EndFunction(&MF);
808 // We didn't modify anything.
813 bool PPCDarwinAsmPrinter::doInitialization(Module &M) {
814 static const char *const CPUDirectives[] = {
826 unsigned Directive = Subtarget.getDarwinDirective();
827 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
828 Directive = PPC::DIR_970;
829 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
830 Directive = PPC::DIR_7400;
831 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
832 Directive = PPC::DIR_64;
833 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
834 O << "\t.machine " << CPUDirectives[Directive] << '\n';
836 bool Result = AsmPrinter::doInitialization(M);
839 // Prime text sections so they are adjacent. This reduces the likelihood a
840 // large data or debug section causes a branch to exceed 16M limit.
841 SwitchToTextSection("\t.section __TEXT,__textcoal_nt,coalesced,"
842 "pure_instructions");
843 if (TM.getRelocationModel() == Reloc::PIC_) {
844 SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
845 "pure_instructions,32");
846 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
847 SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
848 "pure_instructions,16");
850 SwitchToSection(TAI->getTextSection());
855 void PPCDarwinAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
856 const TargetData *TD = TM.getTargetData();
858 if (!GVar->hasInitializer())
859 return; // External global require no code
861 // Check to see if this is a special global used by LLVM, if so, emit it.
862 if (EmitSpecialLLVMGlobal(GVar)) {
863 if (TM.getRelocationModel() == Reloc::Static) {
864 if (GVar->getName() == "llvm.global_ctors")
865 O << ".reference .constructors_used\n";
866 else if (GVar->getName() == "llvm.global_dtors")
867 O << ".reference .destructors_used\n";
872 std::string name = Mang->getValueName(GVar);
874 printVisibility(name, GVar->getVisibility());
876 Constant *C = GVar->getInitializer();
877 const Type *Type = C->getType();
878 unsigned Size = TD->getTypeAllocSize(Type);
879 unsigned Align = TD->getPreferredAlignmentLog(GVar);
881 SwitchToSection(TAI->SectionForGlobal(GVar));
883 if (C->isNullValue() && /* FIXME: Verify correct */
884 !GVar->hasSection() &&
885 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
886 GVar->isWeakForLinker()) &&
887 TAI->SectionKindForGlobal(GVar) != SectionKind::RODataMergeStr) {
888 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
890 if (GVar->hasExternalLinkage()) {
891 O << "\t.globl " << name << '\n';
892 O << "\t.zerofill __DATA, __common, " << name << ", "
893 << Size << ", " << Align;
894 } else if (GVar->hasLocalLinkage()) {
895 O << TAI->getLCOMMDirective() << name << ',' << Size << ',' << Align;
896 } else if (!GVar->hasCommonLinkage()) {
897 O << "\t.globl " << name << '\n'
898 << TAI->getWeakDefDirective() << name << '\n';
899 EmitAlignment(Align, GVar);
902 O << "\t\t\t\t" << TAI->getCommentString() << " ";
903 PrintUnmangledNameSafely(GVar, O);
906 EmitGlobalConstant(C);
909 O << ".comm " << name << ',' << Size;
910 // Darwin 9 and above support aligned common data.
911 if (Subtarget.isDarwin9())
915 O << "\t\t" << TAI->getCommentString() << " '";
916 PrintUnmangledNameSafely(GVar, O);
923 switch (GVar->getLinkage()) {
924 case GlobalValue::LinkOnceAnyLinkage:
925 case GlobalValue::LinkOnceODRLinkage:
926 case GlobalValue::WeakAnyLinkage:
927 case GlobalValue::WeakODRLinkage:
928 case GlobalValue::CommonLinkage:
929 O << "\t.globl " << name << '\n'
930 << "\t.weak_definition " << name << '\n';
932 case GlobalValue::AppendingLinkage:
933 // FIXME: appending linkage variables should go into a section of
934 // their name or something. For now, just emit them as external.
935 case GlobalValue::ExternalLinkage:
936 // If external or appending, declare as a global symbol
937 O << "\t.globl " << name << '\n';
939 case GlobalValue::InternalLinkage:
940 case GlobalValue::PrivateLinkage:
943 cerr << "Unknown linkage type!";
947 EmitAlignment(Align, GVar);
950 O << "\t\t\t\t" << TAI->getCommentString() << " '";
951 PrintUnmangledNameSafely(GVar, O);
956 EmitGlobalConstant(C);
960 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
961 const TargetData *TD = TM.getTargetData();
963 // Print out module-level global variables here.
964 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
966 printModuleLevelGV(I);
968 bool isPPC64 = TD->getPointerSizeInBits() == 64;
970 // Output stubs for dynamically-linked functions
971 if (TM.getRelocationModel() == Reloc::PIC_) {
972 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
974 SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
975 "pure_instructions,32");
977 const char *p = i->getKeyData();
978 bool hasQuote = p[0]=='\"';
979 printSuffixedName(p, "$stub");
981 O << "\t.indirect_symbol " << p << '\n';
985 O << "\"L0$" << &p[1];
990 O << "\"L0$" << &p[1];
995 O << "\taddis r11,r11,ha16(";
996 printSuffixedName(p, "$lazy_ptr");
999 O << "\"L0$" << &p[1];
1005 O << "\tldu r12,lo16(";
1007 O << "\tlwzu r12,lo16(";
1008 printSuffixedName(p, "$lazy_ptr");
1011 O << "\"L0$" << &p[1];
1015 O << "\tmtctr r12\n";
1017 SwitchToDataSection(".lazy_symbol_pointer");
1018 printSuffixedName(p, "$lazy_ptr");
1020 O << "\t.indirect_symbol " << p << '\n';
1022 O << "\t.quad dyld_stub_binding_helper\n";
1024 O << "\t.long dyld_stub_binding_helper\n";
1027 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1029 SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
1030 "pure_instructions,16");
1032 const char *p = i->getKeyData();
1033 printSuffixedName(p, "$stub");
1035 O << "\t.indirect_symbol " << p << '\n';
1036 O << "\tlis r11,ha16(";
1037 printSuffixedName(p, "$lazy_ptr");
1040 O << "\tldu r12,lo16(";
1042 O << "\tlwzu r12,lo16(";
1043 printSuffixedName(p, "$lazy_ptr");
1045 O << "\tmtctr r12\n";
1047 SwitchToDataSection(".lazy_symbol_pointer");
1048 printSuffixedName(p, "$lazy_ptr");
1050 O << "\t.indirect_symbol " << p << '\n';
1052 O << "\t.quad dyld_stub_binding_helper\n";
1054 O << "\t.long dyld_stub_binding_helper\n";
1060 if (TAI->doesSupportExceptionHandling() && MMI) {
1061 // Add the (possibly multiple) personalities to the set of global values.
1062 // Only referenced functions get into the Personalities list.
1063 const std::vector<Function *> &Personalities = MMI->getPersonalities();
1064 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1065 E = Personalities.end(); I != E; ++I)
1066 if (*I) GVStubs.insert("_" + (*I)->getName());
1069 // Output stubs for external and common global variables.
1070 if (!GVStubs.empty()) {
1071 SwitchToDataSection(".non_lazy_symbol_pointer");
1072 for (StringSet<>::iterator i = GVStubs.begin(), e = GVStubs.end();
1074 std::string p = i->getKeyData();
1075 printSuffixedName(p, "$non_lazy_ptr");
1077 O << "\t.indirect_symbol " << p << '\n';
1079 O << "\t.quad\t0\n";
1081 O << "\t.long\t0\n";
1085 if (!HiddenGVStubs.empty()) {
1086 SwitchToSection(TAI->getDataSection());
1087 for (StringSet<>::iterator i = HiddenGVStubs.begin(), e = HiddenGVStubs.end();
1089 std::string p = i->getKeyData();
1090 EmitAlignment(isPPC64 ? 3 : 2);
1091 printSuffixedName(p, "$non_lazy_ptr");
1101 // Funny Darwin hack: This flag tells the linker that no global symbols
1102 // contain code that falls through to other global symbols (e.g. the obvious
1103 // implementation of multiple entry points). If this doesn't occur, the
1104 // linker can safely perform dead code stripping. Since LLVM never generates
1105 // code that does this, it is always safe to set.
1106 O << "\t.subsections_via_symbols\n";
1108 return AsmPrinter::doFinalization(M);
1113 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1114 /// for a MachineFunction to the given output stream, in a format that the
1115 /// Darwin assembler can deal with.
1117 FunctionPass *llvm::createPPCAsmPrinterPass(raw_ostream &o,
1118 PPCTargetMachine &tm,
1119 CodeGenOpt::Level OptLevel,
1121 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1123 if (Subtarget->isDarwin()) {
1124 return new PPCDarwinAsmPrinter(o, tm, tm.getTargetAsmInfo(),
1127 return new PPCLinuxAsmPrinter(o, tm, tm.getTargetAsmInfo(),
1133 static struct Register {
1135 PPCTargetMachine::registerAsmPrinter(createPPCAsmPrinterPass);
1140 extern "C" int PowerPCAsmPrinterForceLink;
1141 int PowerPCAsmPrinterForceLink = 0;
1143 // Force static initialization.
1144 extern "C" void LLVMInitializePowerPCAsmPrinter() { }