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/MDNode.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/Support/Mangler.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/Compiler.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetAsmInfo.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #include "llvm/Target/TargetInstrInfo.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/ADT/StringSet.h"
50 STATISTIC(EmittedInsts, "Number of machine instrs printed");
53 class VISIBILITY_HIDDEN PPCAsmPrinter : public AsmPrinter {
55 StringSet<> FnStubs, GVStubs, HiddenGVStubs;
56 const PPCSubtarget &Subtarget;
58 explicit PPCAsmPrinter(raw_ostream &O, TargetMachine &TM,
59 const TargetAsmInfo *T, CodeGenOpt::Level OL,
61 : AsmPrinter(O, TM, T, OL, V),
62 Subtarget(TM.getSubtarget<PPCSubtarget>()) {}
64 virtual const char *getPassName() const {
65 return "PowerPC Assembly Printer";
68 PPCTargetMachine &getTM() {
69 return static_cast<PPCTargetMachine&>(TM);
72 unsigned enumRegToMachineReg(unsigned enumReg) {
74 default: assert(0 && "Unhandled register!"); break;
75 case PPC::CR0: return 0;
76 case PPC::CR1: return 1;
77 case PPC::CR2: return 2;
78 case PPC::CR3: return 3;
79 case PPC::CR4: return 4;
80 case PPC::CR5: return 5;
81 case PPC::CR6: return 6;
82 case PPC::CR7: return 7;
87 /// printInstruction - This method is automatically generated by tablegen
88 /// from the instruction set description. This method returns true if the
89 /// machine instruction was sufficiently described to print it, otherwise it
91 bool printInstruction(const MachineInstr *MI);
93 void printMachineInstruction(const MachineInstr *MI);
94 void printOp(const MachineOperand &MO);
96 /// stripRegisterPrefix - This method strips the character prefix from a
97 /// register name so that only the number is left. Used by for linux asm.
98 const char *stripRegisterPrefix(const char *RegName) {
102 case 'v': return RegName + 1;
103 case 'c': if (RegName[1] == 'r') return RegName + 2;
109 /// printRegister - Print register according to target requirements.
111 void printRegister(const MachineOperand &MO, bool R0AsZero) {
112 unsigned RegNo = MO.getReg();
113 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
115 // If we should use 0 for R0.
116 if (R0AsZero && RegNo == PPC::R0) {
121 const char *RegName = TM.getRegisterInfo()->get(RegNo).AsmName;
122 // Linux assembler (Others?) does not take register mnemonics.
123 // FIXME - What about special registers used in mfspr/mtspr?
124 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
128 void printOperand(const MachineInstr *MI, unsigned OpNo) {
129 const MachineOperand &MO = MI->getOperand(OpNo);
131 printRegister(MO, false);
132 } else if (MO.isImm()) {
139 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
140 unsigned AsmVariant, const char *ExtraCode);
141 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
142 unsigned AsmVariant, const char *ExtraCode);
145 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
146 char value = MI->getOperand(OpNo).getImm();
147 value = (value << (32-5)) >> (32-5);
150 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
151 unsigned char value = MI->getOperand(OpNo).getImm();
152 assert(value <= 31 && "Invalid u5imm argument!");
153 O << (unsigned int)value;
155 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
156 unsigned char value = MI->getOperand(OpNo).getImm();
157 assert(value <= 63 && "Invalid u6imm argument!");
158 O << (unsigned int)value;
160 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
161 O << (short)MI->getOperand(OpNo).getImm();
163 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
164 O << (unsigned short)MI->getOperand(OpNo).getImm();
166 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
167 if (MI->getOperand(OpNo).isImm()) {
168 O << (short)(MI->getOperand(OpNo).getImm()*4);
171 printOp(MI->getOperand(OpNo));
172 if (TM.getRelocationModel() == Reloc::PIC_)
173 O << "-\"L" << getFunctionNumber() << "$pb\")";
178 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
179 // Branches can take an immediate operand. This is used by the branch
180 // selection pass to print $+8, an eight byte displacement from the PC.
181 if (MI->getOperand(OpNo).isImm()) {
182 O << "$+" << MI->getOperand(OpNo).getImm()*4;
184 printOp(MI->getOperand(OpNo));
187 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
188 const MachineOperand &MO = MI->getOperand(OpNo);
189 if (TM.getRelocationModel() != Reloc::Static) {
190 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
191 GlobalValue *GV = MO.getGlobal();
192 if (((GV->isDeclaration() || GV->hasWeakLinkage() ||
193 GV->hasLinkOnceLinkage() || GV->hasCommonLinkage()))) {
194 // Dynamically-resolved functions need a stub for the function.
195 std::string Name = Mang->getValueName(GV);
196 FnStubs.insert(Name);
197 printSuffixedName(Name, "$stub");
201 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
202 std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
203 FnStubs.insert(Name);
204 printSuffixedName(Name, "$stub");
209 printOp(MI->getOperand(OpNo));
211 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
212 O << (int)MI->getOperand(OpNo).getImm()*4;
214 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
215 O << "\"L" << getFunctionNumber() << "$pb\"\n";
216 O << "\"L" << getFunctionNumber() << "$pb\":";
218 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
219 if (MI->getOperand(OpNo).isImm()) {
220 printS16ImmOperand(MI, OpNo);
222 if (Subtarget.isDarwin()) O << "ha16(";
223 printOp(MI->getOperand(OpNo));
224 if (TM.getRelocationModel() == Reloc::PIC_)
225 O << "-\"L" << getFunctionNumber() << "$pb\"";
226 if (Subtarget.isDarwin())
232 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
233 if (MI->getOperand(OpNo).isImm()) {
234 printS16ImmOperand(MI, OpNo);
236 if (Subtarget.isDarwin()) O << "lo16(";
237 printOp(MI->getOperand(OpNo));
238 if (TM.getRelocationModel() == Reloc::PIC_)
239 O << "-\"L" << getFunctionNumber() << "$pb\"";
240 if (Subtarget.isDarwin())
246 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
247 unsigned CCReg = MI->getOperand(OpNo).getReg();
248 unsigned RegNo = enumRegToMachineReg(CCReg);
249 O << (0x80 >> RegNo);
251 // The new addressing mode printers.
252 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
253 printSymbolLo(MI, OpNo);
255 if (MI->getOperand(OpNo+1).isReg() &&
256 MI->getOperand(OpNo+1).getReg() == PPC::R0)
259 printOperand(MI, OpNo+1);
262 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
263 if (MI->getOperand(OpNo).isImm())
264 printS16X4ImmOperand(MI, OpNo);
266 printSymbolLo(MI, OpNo);
268 if (MI->getOperand(OpNo+1).isReg() &&
269 MI->getOperand(OpNo+1).getReg() == PPC::R0)
272 printOperand(MI, OpNo+1);
276 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
277 // When used as the base register, r0 reads constant zero rather than
278 // the value contained in the register. For this reason, the darwin
279 // assembler requires that we print r0 as 0 (no r) when used as the base.
280 const MachineOperand &MO = MI->getOperand(OpNo);
281 printRegister(MO, true);
283 printOperand(MI, OpNo+1);
286 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
287 const char *Modifier);
289 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
290 virtual bool doFinalization(Module &M) = 0;
292 virtual void EmitExternalGlobal(const GlobalVariable *GV);
295 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
296 class VISIBILITY_HIDDEN PPCLinuxAsmPrinter : public PPCAsmPrinter {
298 explicit PPCLinuxAsmPrinter(raw_ostream &O, PPCTargetMachine &TM,
299 const TargetAsmInfo *T, CodeGenOpt::Level OL,
301 : PPCAsmPrinter(O, TM, T, OL, V){}
303 virtual const char *getPassName() const {
304 return "Linux PPC Assembly Printer";
307 bool runOnMachineFunction(MachineFunction &F);
308 bool doFinalization(Module &M);
310 void getAnalysisUsage(AnalysisUsage &AU) const {
311 AU.setPreservesAll();
312 AU.addRequired<MachineModuleInfo>();
313 AU.addRequired<DwarfWriter>();
314 PPCAsmPrinter::getAnalysisUsage(AU);
317 void printModuleLevelGV(const GlobalVariable* GVar);
320 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
322 class VISIBILITY_HIDDEN PPCDarwinAsmPrinter : public PPCAsmPrinter {
325 explicit PPCDarwinAsmPrinter(raw_ostream &O, PPCTargetMachine &TM,
326 const TargetAsmInfo *T, CodeGenOpt::Level OL,
328 : PPCAsmPrinter(O, TM, T, OL, V), OS(O) {}
330 virtual const char *getPassName() const {
331 return "Darwin PPC Assembly Printer";
334 bool runOnMachineFunction(MachineFunction &F);
335 bool doInitialization(Module &M);
336 bool doFinalization(Module &M);
338 void getAnalysisUsage(AnalysisUsage &AU) const {
339 AU.setPreservesAll();
340 AU.addRequired<MachineModuleInfo>();
341 AU.addRequired<DwarfWriter>();
342 PPCAsmPrinter::getAnalysisUsage(AU);
345 void printModuleLevelGV(const GlobalVariable* GVar);
347 } // end of anonymous namespace
349 // Include the auto-generated portion of the assembly writer
350 #include "PPCGenAsmWriter.inc"
352 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
353 switch (MO.getType()) {
354 case MachineOperand::MO_Immediate:
355 cerr << "printOp() does not handle immediate values\n";
359 case MachineOperand::MO_MachineBasicBlock:
360 printBasicBlockLabel(MO.getMBB());
362 case MachineOperand::MO_JumpTableIndex:
363 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
364 << '_' << MO.getIndex();
365 // FIXME: PIC relocation model
367 case MachineOperand::MO_ConstantPoolIndex:
368 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
369 << '_' << MO.getIndex();
371 case MachineOperand::MO_ExternalSymbol:
372 // Computing the address of an external symbol, not calling it.
373 if (TM.getRelocationModel() != Reloc::Static) {
374 std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
375 GVStubs.insert(Name);
376 printSuffixedName(Name, "$non_lazy_ptr");
379 O << TAI->getGlobalPrefix() << MO.getSymbolName();
381 case MachineOperand::MO_GlobalAddress: {
382 // Computing the address of a global symbol, not calling it.
383 GlobalValue *GV = MO.getGlobal();
384 std::string Name = Mang->getValueName(GV);
386 // External or weakly linked global variables need non-lazily-resolved stubs
387 if (TM.getRelocationModel() != Reloc::Static) {
388 if (GV->isDeclaration() || GV->isWeakForLinker()) {
389 if (GV->hasHiddenVisibility()) {
390 if (!GV->isDeclaration() && !GV->hasCommonLinkage())
393 HiddenGVStubs.insert(Name);
394 printSuffixedName(Name, "$non_lazy_ptr");
397 GVStubs.insert(Name);
398 printSuffixedName(Name, "$non_lazy_ptr");
405 printOffset(MO.getOffset());
410 O << "<unknown operand type: " << MO.getType() << ">";
415 /// EmitExternalGlobal - In this case we need to use the indirect symbol.
417 void PPCAsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
419 getGlobalLinkName(GV, Name);
420 if (TM.getRelocationModel() != Reloc::Static) {
421 if (GV->hasHiddenVisibility())
422 HiddenGVStubs.insert(Name);
424 GVStubs.insert(Name);
425 printSuffixedName(Name, "$non_lazy_ptr");
431 /// PrintAsmOperand - Print out an operand for an inline asm expression.
433 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
435 const char *ExtraCode) {
436 // Does this asm operand have a single letter operand modifier?
437 if (ExtraCode && ExtraCode[0]) {
438 if (ExtraCode[1] != 0) return true; // Unknown modifier.
440 switch (ExtraCode[0]) {
441 default: return true; // Unknown modifier.
442 case 'c': // Don't print "$" before a global var name or constant.
443 // PPC never has a prefix.
444 printOperand(MI, OpNo);
446 case 'L': // Write second word of DImode reference.
447 // Verify that this operand has two consecutive registers.
448 if (!MI->getOperand(OpNo).isReg() ||
449 OpNo+1 == MI->getNumOperands() ||
450 !MI->getOperand(OpNo+1).isReg())
452 ++OpNo; // Return the high-part.
455 // Write 'i' if an integer constant, otherwise nothing. Used to print
457 if (MI->getOperand(OpNo).isImm())
463 printOperand(MI, OpNo);
467 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
469 const char *ExtraCode) {
470 if (ExtraCode && ExtraCode[0])
471 return true; // Unknown modifier.
472 if (MI->getOperand(OpNo).isReg())
473 printMemRegReg(MI, OpNo);
475 printMemRegImm(MI, OpNo);
479 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
480 const char *Modifier) {
481 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
482 unsigned Code = MI->getOperand(OpNo).getImm();
483 if (!strcmp(Modifier, "cc")) {
484 switch ((PPC::Predicate)Code) {
485 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
486 case PPC::PRED_LT: O << "lt"; return;
487 case PPC::PRED_LE: O << "le"; return;
488 case PPC::PRED_EQ: O << "eq"; return;
489 case PPC::PRED_GE: O << "ge"; return;
490 case PPC::PRED_GT: O << "gt"; return;
491 case PPC::PRED_NE: O << "ne"; return;
492 case PPC::PRED_UN: O << "un"; return;
493 case PPC::PRED_NU: O << "nu"; return;
497 assert(!strcmp(Modifier, "reg") &&
498 "Need to specify 'cc' or 'reg' as predicate op modifier!");
499 // Don't print the register for 'always'.
500 if (Code == PPC::PRED_ALWAYS) return;
501 printOperand(MI, OpNo+1);
506 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
507 /// the current output stream.
509 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
512 // Check for slwi/srwi mnemonics.
513 if (MI->getOpcode() == PPC::RLWINM) {
514 bool FoundMnemonic = false;
515 unsigned char SH = MI->getOperand(2).getImm();
516 unsigned char MB = MI->getOperand(3).getImm();
517 unsigned char ME = MI->getOperand(4).getImm();
518 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
519 O << "\tslwi "; FoundMnemonic = true;
521 if (SH <= 31 && MB == (32-SH) && ME == 31) {
522 O << "\tsrwi "; FoundMnemonic = true;
529 O << ", " << (unsigned int)SH << '\n';
532 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
533 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
541 } else if (MI->getOpcode() == PPC::RLDICR) {
542 unsigned char SH = MI->getOperand(2).getImm();
543 unsigned char ME = MI->getOperand(3).getImm();
544 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
550 O << ", " << (unsigned int)SH << '\n';
555 if (printInstruction(MI))
556 return; // Printer was automatically generated
558 assert(0 && "Unhandled instruction in asm writer!");
563 /// runOnMachineFunction - This uses the printMachineInstruction()
564 /// method to print assembly for each instruction.
566 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
569 SetupMachineFunction(MF);
572 // Print out constants referenced by the function
573 EmitConstantPool(MF.getConstantPool());
575 // Print out labels for the function.
576 const Function *F = MF.getFunction();
577 SwitchToSection(TAI->SectionForGlobal(F));
579 switch (F->getLinkage()) {
580 default: assert(0 && "Unknown linkage type!");
581 case Function::PrivateLinkage:
582 case Function::InternalLinkage: // Symbols default to internal.
584 case Function::ExternalLinkage:
585 O << "\t.global\t" << CurrentFnName << '\n'
586 << "\t.type\t" << CurrentFnName << ", @function\n";
588 case Function::WeakAnyLinkage:
589 case Function::WeakODRLinkage:
590 case Function::LinkOnceAnyLinkage:
591 case Function::LinkOnceODRLinkage:
592 O << "\t.global\t" << CurrentFnName << '\n';
593 O << "\t.weak\t" << CurrentFnName << '\n';
597 printVisibility(CurrentFnName, F->getVisibility());
600 O << CurrentFnName << ":\n";
602 // Emit pre-function debug information.
603 DW->BeginFunction(&MF);
605 // Print out code for the function.
606 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
608 // Print a label for the basic block.
609 if (I != MF.begin()) {
610 printBasicBlockLabel(I, true, true);
613 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
615 // Print the assembly for the instruction.
616 printMachineInstruction(II);
620 O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << '\n';
622 // Print out jump tables referenced by the function.
623 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
625 SwitchToSection(TAI->SectionForGlobal(F));
627 // Emit post-function debug information.
628 DW->EndFunction(&MF);
632 // We didn't modify anything.
636 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
637 /// Don't print things like \\n or \\0.
638 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
639 for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
645 void PPCLinuxAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
646 const TargetData *TD = TM.getTargetData();
648 if (!GVar->hasInitializer())
649 return; // External global require no code
651 // Check to see if this is a special global used by LLVM, if so, emit it.
652 if (EmitSpecialLLVMGlobal(GVar))
655 std::string name = Mang->getValueName(GVar);
657 printVisibility(name, GVar->getVisibility());
659 Constant *C = GVar->getInitializer();
660 if (isa<MDNode>(C) || isa<MDString>(C))
662 const Type *Type = C->getType();
663 unsigned Size = TD->getTypeAllocSize(Type);
664 unsigned Align = TD->getPreferredAlignmentLog(GVar);
666 SwitchToSection(TAI->SectionForGlobal(GVar));
668 if (C->isNullValue() && /* FIXME: Verify correct */
669 !GVar->hasSection() &&
670 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
671 GVar->isWeakForLinker())) {
672 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
674 if (GVar->hasExternalLinkage()) {
675 O << "\t.global " << name << '\n';
676 O << "\t.type " << name << ", @object\n";
678 O << "\t.zero " << Size << '\n';
679 } else if (GVar->hasLocalLinkage()) {
680 O << TAI->getLCOMMDirective() << name << ',' << Size;
682 O << ".comm " << name << ',' << Size;
685 O << "\t\t" << TAI->getCommentString() << " '";
686 PrintUnmangledNameSafely(GVar, O);
693 switch (GVar->getLinkage()) {
694 case GlobalValue::LinkOnceAnyLinkage:
695 case GlobalValue::LinkOnceODRLinkage:
696 case GlobalValue::WeakAnyLinkage:
697 case GlobalValue::WeakODRLinkage:
698 case GlobalValue::CommonLinkage:
699 O << "\t.global " << name << '\n'
700 << "\t.type " << name << ", @object\n"
701 << "\t.weak " << name << '\n';
703 case GlobalValue::AppendingLinkage:
704 // FIXME: appending linkage variables should go into a section of
705 // their name or something. For now, just emit them as external.
706 case GlobalValue::ExternalLinkage:
707 // If external or appending, declare as a global symbol
708 O << "\t.global " << name << '\n'
709 << "\t.type " << name << ", @object\n";
711 case GlobalValue::InternalLinkage:
712 case GlobalValue::PrivateLinkage:
715 cerr << "Unknown linkage type!";
719 EmitAlignment(Align, GVar);
722 O << "\t\t\t\t" << TAI->getCommentString() << " '";
723 PrintUnmangledNameSafely(GVar, O);
728 EmitGlobalConstant(C);
732 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
733 // Print out module-level global variables here.
734 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
736 printModuleLevelGV(I);
738 return AsmPrinter::doFinalization(M);
741 /// runOnMachineFunction - This uses the printMachineInstruction()
742 /// method to print assembly for each instruction.
744 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
747 SetupMachineFunction(MF);
750 // Print out constants referenced by the function
751 EmitConstantPool(MF.getConstantPool());
753 // Print out labels for the function.
754 const Function *F = MF.getFunction();
755 SwitchToSection(TAI->SectionForGlobal(F));
757 switch (F->getLinkage()) {
758 default: assert(0 && "Unknown linkage type!");
759 case Function::PrivateLinkage:
760 case Function::InternalLinkage: // Symbols default to internal.
762 case Function::ExternalLinkage:
763 O << "\t.globl\t" << CurrentFnName << '\n';
765 case Function::WeakAnyLinkage:
766 case Function::WeakODRLinkage:
767 case Function::LinkOnceAnyLinkage:
768 case Function::LinkOnceODRLinkage:
769 O << "\t.globl\t" << CurrentFnName << '\n';
770 O << "\t.weak_definition\t" << CurrentFnName << '\n';
774 printVisibility(CurrentFnName, F->getVisibility());
776 EmitAlignment(F->hasFnAttr(Attribute::OptimizeForSize) ? 2 : 4, F);
777 O << CurrentFnName << ":\n";
779 // Emit pre-function debug information.
780 DW->BeginFunction(&MF);
782 // If the function is empty, then we need to emit *something*. Otherwise, the
783 // function's label might be associated with something that it wasn't meant to
784 // be associated with. We emit a noop in this situation.
785 MachineFunction::iterator I = MF.begin();
787 if (++I == MF.end() && MF.front().empty())
790 // Print out code for the function.
791 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
793 // Print a label for the basic block.
794 if (I != MF.begin()) {
795 printBasicBlockLabel(I, true, true, VerboseAsm);
798 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
800 // Print the assembly for the instruction.
801 printMachineInstruction(II);
805 // Print out jump tables referenced by the function.
806 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
808 // Emit post-function debug information.
809 DW->EndFunction(&MF);
811 // We didn't modify anything.
816 bool PPCDarwinAsmPrinter::doInitialization(Module &M) {
817 static const char *const CPUDirectives[] = {
829 unsigned Directive = Subtarget.getDarwinDirective();
830 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
831 Directive = PPC::DIR_970;
832 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
833 Directive = PPC::DIR_7400;
834 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
835 Directive = PPC::DIR_64;
836 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
837 O << "\t.machine " << CPUDirectives[Directive] << '\n';
839 bool Result = AsmPrinter::doInitialization(M);
842 // Prime text sections so they are adjacent. This reduces the likelihood a
843 // large data or debug section causes a branch to exceed 16M limit.
844 SwitchToTextSection("\t.section __TEXT,__textcoal_nt,coalesced,"
845 "pure_instructions");
846 if (TM.getRelocationModel() == Reloc::PIC_) {
847 SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
848 "pure_instructions,32");
849 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
850 SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
851 "pure_instructions,16");
853 SwitchToSection(TAI->getTextSection());
858 void PPCDarwinAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
859 const TargetData *TD = TM.getTargetData();
861 if (!GVar->hasInitializer())
862 return; // External global require no code
864 // Check to see if this is a special global used by LLVM, if so, emit it.
865 if (EmitSpecialLLVMGlobal(GVar)) {
866 if (TM.getRelocationModel() == Reloc::Static) {
867 if (GVar->getName() == "llvm.global_ctors")
868 O << ".reference .constructors_used\n";
869 else if (GVar->getName() == "llvm.global_dtors")
870 O << ".reference .destructors_used\n";
875 std::string name = Mang->getValueName(GVar);
877 printVisibility(name, GVar->getVisibility());
879 Constant *C = GVar->getInitializer();
880 const Type *Type = C->getType();
881 unsigned Size = TD->getTypeAllocSize(Type);
882 unsigned Align = TD->getPreferredAlignmentLog(GVar);
884 SwitchToSection(TAI->SectionForGlobal(GVar));
886 if (C->isNullValue() && /* FIXME: Verify correct */
887 !GVar->hasSection() &&
888 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
889 GVar->isWeakForLinker()) &&
890 TAI->SectionKindForGlobal(GVar) != SectionKind::RODataMergeStr) {
891 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
893 if (GVar->hasExternalLinkage()) {
894 O << "\t.globl " << name << '\n';
895 O << "\t.zerofill __DATA, __common, " << name << ", "
896 << Size << ", " << Align;
897 } else if (GVar->hasLocalLinkage()) {
898 O << TAI->getLCOMMDirective() << name << ',' << Size << ',' << Align;
899 } else if (!GVar->hasCommonLinkage()) {
900 O << "\t.globl " << name << '\n'
901 << TAI->getWeakDefDirective() << name << '\n';
902 EmitAlignment(Align, GVar);
905 O << "\t\t\t\t" << TAI->getCommentString() << " ";
906 PrintUnmangledNameSafely(GVar, O);
909 EmitGlobalConstant(C);
912 O << ".comm " << name << ',' << Size;
913 // Darwin 9 and above support aligned common data.
914 if (Subtarget.isDarwin9())
918 O << "\t\t" << TAI->getCommentString() << " '";
919 PrintUnmangledNameSafely(GVar, O);
926 switch (GVar->getLinkage()) {
927 case GlobalValue::LinkOnceAnyLinkage:
928 case GlobalValue::LinkOnceODRLinkage:
929 case GlobalValue::WeakAnyLinkage:
930 case GlobalValue::WeakODRLinkage:
931 case GlobalValue::CommonLinkage:
932 O << "\t.globl " << name << '\n'
933 << "\t.weak_definition " << name << '\n';
935 case GlobalValue::AppendingLinkage:
936 // FIXME: appending linkage variables should go into a section of
937 // their name or something. For now, just emit them as external.
938 case GlobalValue::ExternalLinkage:
939 // If external or appending, declare as a global symbol
940 O << "\t.globl " << name << '\n';
942 case GlobalValue::InternalLinkage:
943 case GlobalValue::PrivateLinkage:
946 cerr << "Unknown linkage type!";
950 EmitAlignment(Align, GVar);
953 O << "\t\t\t\t" << TAI->getCommentString() << " '";
954 PrintUnmangledNameSafely(GVar, O);
959 EmitGlobalConstant(C);
963 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
964 const TargetData *TD = TM.getTargetData();
966 // Print out module-level global variables here.
967 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
969 printModuleLevelGV(I);
971 bool isPPC64 = TD->getPointerSizeInBits() == 64;
973 // Output stubs for dynamically-linked functions
974 if (TM.getRelocationModel() == Reloc::PIC_) {
975 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
977 SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
978 "pure_instructions,32");
980 const char *p = i->getKeyData();
981 bool hasQuote = p[0]=='\"';
982 printSuffixedName(p, "$stub");
984 O << "\t.indirect_symbol " << p << '\n';
988 O << "\"L0$" << &p[1];
993 O << "\"L0$" << &p[1];
998 O << "\taddis r11,r11,ha16(";
999 printSuffixedName(p, "$lazy_ptr");
1002 O << "\"L0$" << &p[1];
1008 O << "\tldu r12,lo16(";
1010 O << "\tlwzu r12,lo16(";
1011 printSuffixedName(p, "$lazy_ptr");
1014 O << "\"L0$" << &p[1];
1018 O << "\tmtctr r12\n";
1020 SwitchToDataSection(".lazy_symbol_pointer");
1021 printSuffixedName(p, "$lazy_ptr");
1023 O << "\t.indirect_symbol " << p << '\n';
1025 O << "\t.quad dyld_stub_binding_helper\n";
1027 O << "\t.long dyld_stub_binding_helper\n";
1030 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1032 SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
1033 "pure_instructions,16");
1035 const char *p = i->getKeyData();
1036 printSuffixedName(p, "$stub");
1038 O << "\t.indirect_symbol " << p << '\n';
1039 O << "\tlis r11,ha16(";
1040 printSuffixedName(p, "$lazy_ptr");
1043 O << "\tldu r12,lo16(";
1045 O << "\tlwzu r12,lo16(";
1046 printSuffixedName(p, "$lazy_ptr");
1048 O << "\tmtctr r12\n";
1050 SwitchToDataSection(".lazy_symbol_pointer");
1051 printSuffixedName(p, "$lazy_ptr");
1053 O << "\t.indirect_symbol " << p << '\n';
1055 O << "\t.quad dyld_stub_binding_helper\n";
1057 O << "\t.long dyld_stub_binding_helper\n";
1063 if (TAI->doesSupportExceptionHandling() && MMI) {
1064 // Add the (possibly multiple) personalities to the set of global values.
1065 // Only referenced functions get into the Personalities list.
1066 const std::vector<Function *> &Personalities = MMI->getPersonalities();
1067 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1068 E = Personalities.end(); I != E; ++I)
1069 if (*I) GVStubs.insert("_" + (*I)->getName());
1072 // Output stubs for external and common global variables.
1073 if (!GVStubs.empty()) {
1074 SwitchToDataSection(".non_lazy_symbol_pointer");
1075 for (StringSet<>::iterator i = GVStubs.begin(), e = GVStubs.end();
1077 std::string p = i->getKeyData();
1078 printSuffixedName(p, "$non_lazy_ptr");
1080 O << "\t.indirect_symbol " << p << '\n';
1082 O << "\t.quad\t0\n";
1084 O << "\t.long\t0\n";
1088 if (!HiddenGVStubs.empty()) {
1089 SwitchToSection(TAI->getDataSection());
1090 for (StringSet<>::iterator i = HiddenGVStubs.begin(), e = HiddenGVStubs.end();
1092 std::string p = i->getKeyData();
1093 EmitAlignment(isPPC64 ? 3 : 2);
1094 printSuffixedName(p, "$non_lazy_ptr");
1104 // Funny Darwin hack: This flag tells the linker that no global symbols
1105 // contain code that falls through to other global symbols (e.g. the obvious
1106 // implementation of multiple entry points). If this doesn't occur, the
1107 // linker can safely perform dead code stripping. Since LLVM never generates
1108 // code that does this, it is always safe to set.
1109 O << "\t.subsections_via_symbols\n";
1111 return AsmPrinter::doFinalization(M);
1116 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1117 /// for a MachineFunction to the given output stream, in a format that the
1118 /// Darwin assembler can deal with.
1120 FunctionPass *llvm::createPPCAsmPrinterPass(raw_ostream &o,
1121 PPCTargetMachine &tm,
1122 CodeGenOpt::Level OptLevel,
1124 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1126 if (Subtarget->isDarwin()) {
1127 return new PPCDarwinAsmPrinter(o, tm, tm.getTargetAsmInfo(),
1130 return new PPCLinuxAsmPrinter(o, tm, tm.getTargetAsmInfo(),
1136 static struct Register {
1138 PPCTargetMachine::registerAsmPrinter(createPPCAsmPrinterPass);
1143 extern "C" int PowerPCAsmPrinterForceLink;
1144 int PowerPCAsmPrinterForceLink = 0;
1146 // Force static initialization.
1147 extern "C" void LLVMInitializePowerPCAsmPrinter() { }