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/Support/Mangler.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/Compiler.h"
38 #include "llvm/Target/TargetAsmInfo.h"
39 #include "llvm/Target/MRegisterInfo.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/ADT/Statistic.h"
43 #include "llvm/ADT/StringExtras.h"
47 STATISTIC(EmittedInsts, "Number of machine instrs printed");
50 struct VISIBILITY_HIDDEN PPCAsmPrinter : public AsmPrinter {
51 std::set<std::string> FnStubs, GVStubs;
52 const PPCSubtarget &Subtarget;
54 PPCAsmPrinter(std::ostream &O, TargetMachine &TM, const TargetAsmInfo *T)
55 : AsmPrinter(O, TM, T), Subtarget(TM.getSubtarget<PPCSubtarget>()) {
58 virtual const char *getPassName() const {
59 return "PowerPC Assembly Printer";
62 PPCTargetMachine &getTM() {
63 return static_cast<PPCTargetMachine&>(TM);
66 unsigned enumRegToMachineReg(unsigned enumReg) {
68 default: assert(0 && "Unhandled register!"); break;
69 case PPC::CR0: return 0;
70 case PPC::CR1: return 1;
71 case PPC::CR2: return 2;
72 case PPC::CR3: return 3;
73 case PPC::CR4: return 4;
74 case PPC::CR5: return 5;
75 case PPC::CR6: return 6;
76 case PPC::CR7: return 7;
81 /// printInstruction - This method is automatically generated by tablegen
82 /// from the instruction set description. This method returns true if the
83 /// machine instruction was sufficiently described to print it, otherwise it
85 bool printInstruction(const MachineInstr *MI);
87 void printMachineInstruction(const MachineInstr *MI);
88 void printOp(const MachineOperand &MO);
90 /// stripRegisterPrefix - This method strips the character prefix from a
91 /// register name so that only the number is left. Used by for linux asm.
92 const char *stripRegisterPrefix(const char *RegName) {
96 case 'v': return RegName + 1;
97 case 'c': if (RegName[1] == 'r') return RegName + 2;
103 /// printRegister - Print register according to target requirements.
105 void printRegister(const MachineOperand &MO, bool R0AsZero) {
106 unsigned RegNo = MO.getReg();
107 assert(MRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
109 // If we should use 0 for R0.
110 if (R0AsZero && RegNo == PPC::R0) {
115 const char *RegName = TM.getRegisterInfo()->get(RegNo).Name;
116 // Linux assembler (Others?) does not take register mnemonics.
117 // FIXME - What about special registers used in mfspr/mtspr?
118 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
122 void printOperand(const MachineInstr *MI, unsigned OpNo) {
123 const MachineOperand &MO = MI->getOperand(OpNo);
124 if (MO.isRegister()) {
125 printRegister(MO, false);
126 } else if (MO.isImmediate()) {
133 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
134 unsigned AsmVariant, const char *ExtraCode);
135 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
136 unsigned AsmVariant, const char *ExtraCode);
139 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
140 char value = MI->getOperand(OpNo).getImm();
141 value = (value << (32-5)) >> (32-5);
144 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
145 unsigned char value = MI->getOperand(OpNo).getImm();
146 assert(value <= 31 && "Invalid u5imm argument!");
147 O << (unsigned int)value;
149 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
150 unsigned char value = MI->getOperand(OpNo).getImm();
151 assert(value <= 63 && "Invalid u6imm argument!");
152 O << (unsigned int)value;
154 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
155 O << (short)MI->getOperand(OpNo).getImm();
157 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
158 O << (unsigned short)MI->getOperand(OpNo).getImm();
160 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
161 if (MI->getOperand(OpNo).isImmediate()) {
162 O << (short)(MI->getOperand(OpNo).getImm()*4);
165 printOp(MI->getOperand(OpNo));
166 if (TM.getRelocationModel() == Reloc::PIC_)
167 O << "-\"L" << getFunctionNumber() << "$pb\")";
172 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
173 // Branches can take an immediate operand. This is used by the branch
174 // selection pass to print $+8, an eight byte displacement from the PC.
175 if (MI->getOperand(OpNo).isImmediate()) {
176 O << "$+" << MI->getOperand(OpNo).getImm()*4;
178 printOp(MI->getOperand(OpNo));
181 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
182 const MachineOperand &MO = MI->getOperand(OpNo);
183 if (TM.getRelocationModel() != Reloc::Static) {
184 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
185 GlobalValue *GV = MO.getGlobal();
186 if (((GV->isDeclaration() || GV->hasWeakLinkage() ||
187 GV->hasLinkOnceLinkage()))) {
188 // Dynamically-resolved functions need a stub for the function.
189 std::string Name = Mang->getValueName(GV);
190 FnStubs.insert(Name);
191 O << "L" << Name << "$stub";
192 if (GV->hasExternalWeakLinkage())
193 ExtWeakSymbols.insert(GV);
197 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
198 std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
199 FnStubs.insert(Name);
200 O << "L" << Name << "$stub";
205 printOp(MI->getOperand(OpNo));
207 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
208 O << (int)MI->getOperand(OpNo).getImm()*4;
210 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
211 O << "\"L" << getFunctionNumber() << "$pb\"\n";
212 O << "\"L" << getFunctionNumber() << "$pb\":";
214 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
215 if (MI->getOperand(OpNo).isImmediate()) {
216 printS16ImmOperand(MI, OpNo);
218 if (Subtarget.isDarwin()) O << "ha16(";
219 printOp(MI->getOperand(OpNo));
220 if (TM.getRelocationModel() == Reloc::PIC_)
221 O << "-\"L" << getFunctionNumber() << "$pb\"";
222 if (Subtarget.isDarwin())
228 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
229 if (MI->getOperand(OpNo).isImmediate()) {
230 printS16ImmOperand(MI, OpNo);
232 if (Subtarget.isDarwin()) O << "lo16(";
233 printOp(MI->getOperand(OpNo));
234 if (TM.getRelocationModel() == Reloc::PIC_)
235 O << "-\"L" << getFunctionNumber() << "$pb\"";
236 if (Subtarget.isDarwin())
242 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
243 unsigned CCReg = MI->getOperand(OpNo).getReg();
244 unsigned RegNo = enumRegToMachineReg(CCReg);
245 O << (0x80 >> RegNo);
247 // The new addressing mode printers.
248 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
249 printSymbolLo(MI, OpNo);
251 if (MI->getOperand(OpNo+1).isRegister() &&
252 MI->getOperand(OpNo+1).getReg() == PPC::R0)
255 printOperand(MI, OpNo+1);
258 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
259 if (MI->getOperand(OpNo).isImmediate())
260 printS16X4ImmOperand(MI, OpNo);
262 printSymbolLo(MI, OpNo);
264 if (MI->getOperand(OpNo+1).isRegister() &&
265 MI->getOperand(OpNo+1).getReg() == PPC::R0)
268 printOperand(MI, OpNo+1);
272 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
273 // When used as the base register, r0 reads constant zero rather than
274 // the value contained in the register. For this reason, the darwin
275 // assembler requires that we print r0 as 0 (no r) when used as the base.
276 const MachineOperand &MO = MI->getOperand(OpNo);
277 printRegister(MO, true);
279 printOperand(MI, OpNo+1);
282 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
283 const char *Modifier);
285 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
286 virtual bool doFinalization(Module &M) = 0;
288 virtual void EmitExternalGlobal(const GlobalVariable *GV);
291 /// LinuxAsmPrinter - PowerPC assembly printer, customized for Linux
292 struct VISIBILITY_HIDDEN LinuxAsmPrinter : public PPCAsmPrinter {
296 LinuxAsmPrinter(std::ostream &O, PPCTargetMachine &TM,
297 const TargetAsmInfo *T)
298 : PPCAsmPrinter(O, TM, T), DW(O, this, T) {
301 virtual const char *getPassName() const {
302 return "Linux PPC Assembly Printer";
305 bool runOnMachineFunction(MachineFunction &F);
306 bool doInitialization(Module &M);
307 bool doFinalization(Module &M);
309 void getAnalysisUsage(AnalysisUsage &AU) const {
310 AU.setPreservesAll();
311 AU.addRequired<MachineModuleInfo>();
312 PPCAsmPrinter::getAnalysisUsage(AU);
315 /// getSectionForFunction - Return the section that we should emit the
316 /// specified function body into.
317 virtual std::string getSectionForFunction(const Function &F) const;
320 /// DarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac OS
322 struct VISIBILITY_HIDDEN DarwinAsmPrinter : public PPCAsmPrinter {
325 MachineModuleInfo *MMI;
327 DarwinAsmPrinter(std::ostream &O, PPCTargetMachine &TM,
328 const TargetAsmInfo *T)
329 : PPCAsmPrinter(O, TM, T), DW(O, this, T), MMI(0) {
332 virtual const char *getPassName() const {
333 return "Darwin PPC Assembly Printer";
336 bool runOnMachineFunction(MachineFunction &F);
337 bool doInitialization(Module &M);
338 bool doFinalization(Module &M);
340 void getAnalysisUsage(AnalysisUsage &AU) const {
341 AU.setPreservesAll();
342 AU.addRequired<MachineModuleInfo>();
343 PPCAsmPrinter::getAnalysisUsage(AU);
346 /// getSectionForFunction - Return the section that we should emit the
347 /// specified function body into.
348 virtual std::string getSectionForFunction(const Function &F) const;
350 } // end of anonymous namespace
352 // Include the auto-generated portion of the assembly writer
353 #include "PPCGenAsmWriter.inc"
355 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
356 switch (MO.getType()) {
357 case MachineOperand::MO_Immediate:
358 cerr << "printOp() does not handle immediate values\n";
362 case MachineOperand::MO_MachineBasicBlock:
363 printBasicBlockLabel(MO.getMBB());
365 case MachineOperand::MO_JumpTableIndex:
366 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
367 << '_' << MO.getIndex();
368 // FIXME: PIC relocation model
370 case MachineOperand::MO_ConstantPoolIndex:
371 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
372 << '_' << MO.getIndex();
374 case MachineOperand::MO_ExternalSymbol:
375 // Computing the address of an external symbol, not calling it.
376 if (TM.getRelocationModel() != Reloc::Static) {
377 std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
378 GVStubs.insert(Name);
379 O << "L" << Name << "$non_lazy_ptr";
382 O << TAI->getGlobalPrefix() << MO.getSymbolName();
384 case MachineOperand::MO_GlobalAddress: {
385 // Computing the address of a global symbol, not calling it.
386 GlobalValue *GV = MO.getGlobal();
387 std::string Name = Mang->getValueName(GV);
389 // External or weakly linked global variables need non-lazily-resolved stubs
390 if (TM.getRelocationModel() != Reloc::Static) {
391 if (((GV->isDeclaration() || GV->hasWeakLinkage() ||
392 GV->hasLinkOnceLinkage()))) {
393 GVStubs.insert(Name);
394 O << "L" << Name << "$non_lazy_ptr";
400 if (MO.getOffset() > 0)
401 O << "+" << MO.getOffset();
402 else if (MO.getOffset() < 0)
405 if (GV->hasExternalWeakLinkage())
406 ExtWeakSymbols.insert(GV);
411 O << "<unknown operand type: " << MO.getType() << ">";
416 /// EmitExternalGlobal - In this case we need to use the indirect symbol.
418 void PPCAsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
419 std::string Name = getGlobalLinkName(GV);
420 if (TM.getRelocationModel() != Reloc::Static) {
421 GVStubs.insert(Name);
422 O << "L" << Name << "$non_lazy_ptr";
428 /// PrintAsmOperand - Print out an operand for an inline asm expression.
430 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
432 const char *ExtraCode) {
433 // Does this asm operand have a single letter operand modifier?
434 if (ExtraCode && ExtraCode[0]) {
435 if (ExtraCode[1] != 0) return true; // Unknown modifier.
437 switch (ExtraCode[0]) {
438 default: return true; // Unknown modifier.
439 case 'c': // Don't print "$" before a global var name or constant.
440 // PPC never has a prefix.
441 printOperand(MI, OpNo);
443 case 'L': // Write second word of DImode reference.
444 // Verify that this operand has two consecutive registers.
445 if (!MI->getOperand(OpNo).isRegister() ||
446 OpNo+1 == MI->getNumOperands() ||
447 !MI->getOperand(OpNo+1).isRegister())
449 ++OpNo; // Return the high-part.
452 // Write 'i' if an integer constant, otherwise nothing. Used to print
454 if (MI->getOperand(OpNo).isImmediate())
460 printOperand(MI, OpNo);
464 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
466 const char *ExtraCode) {
467 if (ExtraCode && ExtraCode[0])
468 return true; // Unknown modifier.
469 if (MI->getOperand(OpNo).isRegister())
470 printMemRegReg(MI, OpNo);
472 printMemRegImm(MI, OpNo);
476 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
477 const char *Modifier) {
478 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
479 unsigned Code = MI->getOperand(OpNo).getImm();
480 if (!strcmp(Modifier, "cc")) {
481 switch ((PPC::Predicate)Code) {
482 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
483 case PPC::PRED_LT: O << "lt"; return;
484 case PPC::PRED_LE: O << "le"; return;
485 case PPC::PRED_EQ: O << "eq"; return;
486 case PPC::PRED_GE: O << "ge"; return;
487 case PPC::PRED_GT: O << "gt"; return;
488 case PPC::PRED_NE: O << "ne"; return;
489 case PPC::PRED_UN: O << "un"; return;
490 case PPC::PRED_NU: O << "nu"; return;
494 assert(!strcmp(Modifier, "reg") &&
495 "Need to specify 'cc' or 'reg' as predicate op modifier!");
496 // Don't print the register for 'always'.
497 if (Code == PPC::PRED_ALWAYS) return;
498 printOperand(MI, OpNo+1);
503 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
504 /// the current output stream.
506 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
509 // Check for slwi/srwi mnemonics.
510 if (MI->getOpcode() == PPC::RLWINM) {
511 bool FoundMnemonic = false;
512 unsigned char SH = MI->getOperand(2).getImm();
513 unsigned char MB = MI->getOperand(3).getImm();
514 unsigned char ME = MI->getOperand(4).getImm();
515 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
516 O << "slwi "; FoundMnemonic = true;
518 if (SH <= 31 && MB == (32-SH) && ME == 31) {
519 O << "srwi "; FoundMnemonic = true;
526 O << ", " << (unsigned int)SH << "\n";
529 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
530 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
538 } else if (MI->getOpcode() == PPC::RLDICR) {
539 unsigned char SH = MI->getOperand(2).getImm();
540 unsigned char ME = MI->getOperand(3).getImm();
541 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
547 O << ", " << (unsigned int)SH << "\n";
552 if (printInstruction(MI))
553 return; // Printer was automatically generated
555 assert(0 && "Unhandled instruction in asm writer!");
560 /// runOnMachineFunction - This uses the printMachineInstruction()
561 /// method to print assembly for each instruction.
563 bool LinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
564 DW.SetModuleInfo(&getAnalysis<MachineModuleInfo>());
566 SetupMachineFunction(MF);
569 // Print out constants referenced by the function
570 EmitConstantPool(MF.getConstantPool());
572 // Print out labels for the function.
573 const Function *F = MF.getFunction();
574 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
576 switch (F->getLinkage()) {
577 default: assert(0 && "Unknown linkage type!");
578 case Function::InternalLinkage: // Symbols default to internal.
580 case Function::ExternalLinkage:
581 O << "\t.global\t" << CurrentFnName << '\n'
582 << "\t.type\t" << CurrentFnName << ", @function\n";
584 case Function::WeakLinkage:
585 case Function::LinkOnceLinkage:
586 O << "\t.global\t" << CurrentFnName << '\n';
587 O << "\t.weak\t" << CurrentFnName << '\n';
591 if (F->hasHiddenVisibility())
592 if (const char *Directive = TAI->getHiddenDirective())
593 O << Directive << CurrentFnName << "\n";
596 O << CurrentFnName << ":\n";
598 // Emit pre-function debug information.
599 DW.BeginFunction(&MF);
601 // Print out code for the function.
602 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
604 // Print a label for the basic block.
605 if (I != MF.begin()) {
606 printBasicBlockLabel(I, true);
609 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
611 // Print the assembly for the instruction.
613 printMachineInstruction(II);
617 O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << "\n";
619 // Print out jump tables referenced by the function.
620 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
622 // Emit post-function debug information.
625 // We didn't modify anything.
629 bool LinuxAsmPrinter::doInitialization(Module &M) {
630 bool Result = AsmPrinter::doInitialization(M);
632 // GNU as handles section names wrapped in quotes
633 Mang->setUseQuotes(true);
635 SwitchToTextSection(TAI->getTextSection());
637 // Emit initial debug information.
642 bool LinuxAsmPrinter::doFinalization(Module &M) {
643 const TargetData *TD = TM.getTargetData();
645 // Print out module-level global variables here.
646 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
648 if (!I->hasInitializer()) continue; // 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(I))
654 std::string name = Mang->getValueName(I);
656 if (I->hasHiddenVisibility())
657 if (const char *Directive = TAI->getHiddenDirective())
658 O << Directive << name << "\n";
660 Constant *C = I->getInitializer();
661 unsigned Size = TD->getABITypeSize(C->getType());
662 unsigned Align = TD->getPreferredAlignmentLog(I);
664 if (C->isNullValue() && /* FIXME: Verify correct */
666 (I->hasInternalLinkage() || I->hasWeakLinkage() ||
667 I->hasLinkOnceLinkage() || I->hasExternalLinkage())) {
668 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
669 if (I->hasExternalLinkage()) {
670 O << "\t.global " << name << '\n';
671 O << "\t.type " << name << ", @object\n";
672 if (TAI->getBSSSection())
673 SwitchToDataSection(TAI->getBSSSection(), I);
675 O << "\t.zero " << Size << "\n";
676 } else if (I->hasInternalLinkage()) {
677 SwitchToDataSection("\t.data", I);
678 O << TAI->getLCOMMDirective() << name << "," << Size;
680 SwitchToDataSection("\t.data", I);
681 O << ".comm " << name << "," << Size;
683 O << "\t\t" << TAI->getCommentString() << " '" << I->getName() << "'\n";
685 switch (I->getLinkage()) {
686 case GlobalValue::LinkOnceLinkage:
687 case GlobalValue::WeakLinkage:
688 O << "\t.global " << name << '\n'
689 << "\t.type " << name << ", @object\n"
690 << "\t.weak " << name << '\n';
691 SwitchToDataSection("\t.data", I);
693 case GlobalValue::AppendingLinkage:
694 // FIXME: appending linkage variables should go into a section of
695 // their name or something. For now, just emit them as external.
696 case GlobalValue::ExternalLinkage:
697 // If external or appending, declare as a global symbol
698 O << "\t.global " << name << "\n"
699 << "\t.type " << name << ", @object\n";
701 case GlobalValue::InternalLinkage:
702 if (I->isConstant()) {
703 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
704 if (TAI->getCStringSection() && CVA && CVA->isCString()) {
705 SwitchToDataSection(TAI->getCStringSection(), I);
710 // FIXME: special handling for ".ctors" & ".dtors" sections
711 if (I->hasSection() &&
712 (I->getSection() == ".ctors" ||
713 I->getSection() == ".dtors")) {
714 std::string SectionName = ".section " + I->getSection()
715 + ",\"aw\",@progbits";
716 SwitchToDataSection(SectionName.c_str());
718 if (I->isConstant() && TAI->getReadOnlySection())
719 SwitchToDataSection(TAI->getReadOnlySection(), I);
721 SwitchToDataSection(TAI->getDataSection(), I);
725 cerr << "Unknown linkage type!";
729 EmitAlignment(Align, I);
730 O << name << ":\t\t\t\t" << TAI->getCommentString() << " '"
731 << I->getName() << "'\n";
733 // If the initializer is a extern weak symbol, remember to emit the weak
735 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
736 if (GV->hasExternalWeakLinkage())
737 ExtWeakSymbols.insert(GV);
739 EmitGlobalConstant(C);
746 // Emit initial debug information.
749 return AsmPrinter::doFinalization(M);
752 std::string LinuxAsmPrinter::getSectionForFunction(const Function &F) const {
753 switch (F.getLinkage()) {
754 default: assert(0 && "Unknown linkage type!");
755 case Function::ExternalLinkage:
756 case Function::InternalLinkage: return TAI->getTextSection();
757 case Function::WeakLinkage:
758 case Function::LinkOnceLinkage:
763 std::string DarwinAsmPrinter::getSectionForFunction(const Function &F) const {
764 switch (F.getLinkage()) {
765 default: assert(0 && "Unknown linkage type!");
766 case Function::ExternalLinkage:
767 case Function::InternalLinkage: return TAI->getTextSection();
768 case Function::WeakLinkage:
769 case Function::LinkOnceLinkage:
770 return "\t.section __TEXT,__textcoal_nt,coalesced,pure_instructions";
774 /// runOnMachineFunction - This uses the printMachineInstruction()
775 /// method to print assembly for each instruction.
777 bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
778 // We need this for Personality functions.
779 MMI = &getAnalysis<MachineModuleInfo>();
780 DW.SetModuleInfo(MMI);
782 SetupMachineFunction(MF);
785 // Print out constants referenced by the function
786 EmitConstantPool(MF.getConstantPool());
788 // Print out labels for the function.
789 const Function *F = MF.getFunction();
790 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
792 switch (F->getLinkage()) {
793 default: assert(0 && "Unknown linkage type!");
794 case Function::InternalLinkage: // Symbols default to internal.
796 case Function::ExternalLinkage:
797 O << "\t.globl\t" << CurrentFnName << "\n";
799 case Function::WeakLinkage:
800 case Function::LinkOnceLinkage:
801 O << "\t.globl\t" << CurrentFnName << "\n";
802 O << "\t.weak_definition\t" << CurrentFnName << "\n";
806 if (F->hasHiddenVisibility())
807 if (const char *Directive = TAI->getHiddenDirective())
808 O << Directive << CurrentFnName << "\n";
811 O << CurrentFnName << ":\n";
813 // Emit pre-function debug information.
814 DW.BeginFunction(&MF);
816 // Print out code for the function.
817 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
819 // Print a label for the basic block.
820 if (I != MF.begin()) {
821 printBasicBlockLabel(I, true);
824 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
826 // Print the assembly for the instruction.
828 printMachineInstruction(II);
832 // Print out jump tables referenced by the function.
833 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
835 // Emit post-function debug information.
838 // We didn't modify anything.
843 bool DarwinAsmPrinter::doInitialization(Module &M) {
844 static const char *CPUDirectives[] = {
855 unsigned Directive = Subtarget.getDarwinDirective();
856 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
857 Directive = PPC::DIR_970;
858 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
859 Directive = PPC::DIR_7400;
860 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
861 Directive = PPC::DIR_64;
862 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
863 O << "\t.machine " << CPUDirectives[Directive] << "\n";
865 bool Result = AsmPrinter::doInitialization(M);
867 // Darwin wants symbols to be quoted if they have complex names.
868 Mang->setUseQuotes(true);
870 // Prime text sections so they are adjacent. This reduces the likelihood a
871 // large data or debug section causes a branch to exceed 16M limit.
872 SwitchToTextSection("\t.section __TEXT,__textcoal_nt,coalesced,"
873 "pure_instructions");
874 if (TM.getRelocationModel() == Reloc::PIC_) {
875 SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
876 "pure_instructions,32");
877 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
878 SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
879 "pure_instructions,16");
881 SwitchToTextSection(TAI->getTextSection());
883 // Emit initial debug information.
888 bool DarwinAsmPrinter::doFinalization(Module &M) {
889 const TargetData *TD = TM.getTargetData();
891 // Print out module-level global variables here.
892 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
894 if (!I->hasInitializer()) continue; // External global require no code
896 // Check to see if this is a special global used by LLVM, if so, emit it.
897 if (EmitSpecialLLVMGlobal(I)) {
898 if (TM.getRelocationModel() == Reloc::Static) {
899 if (I->getName() == "llvm.global_ctors")
900 O << ".reference .constructors_used\n";
901 else if (I->getName() == "llvm.global_dtors")
902 O << ".reference .destructors_used\n";
907 std::string name = Mang->getValueName(I);
909 if (I->hasHiddenVisibility())
910 if (const char *Directive = TAI->getHiddenDirective())
911 O << Directive << name << "\n";
913 Constant *C = I->getInitializer();
914 const Type *Type = C->getType();
915 unsigned Size = TD->getABITypeSize(Type);
916 unsigned Align = TD->getPreferredAlignmentLog(I);
918 if (C->isNullValue() && /* FIXME: Verify correct */
920 (I->hasInternalLinkage() || I->hasExternalLinkage())) {
921 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
922 if (I->hasExternalLinkage()) {
923 O << "\t.globl " << name << '\n';
924 O << "\t.zerofill __DATA, __common, " << name << ", "
925 << Size << ", " << Align;
926 } else if (I->hasInternalLinkage()) {
927 SwitchToDataSection("\t.data", I);
928 O << TAI->getLCOMMDirective() << name << "," << Size << "," << Align;
930 SwitchToDataSection("\t.data", I);
931 O << ".comm " << name << "," << Size;
932 // Darwin 9 and above support aligned common data.
933 if (Subtarget.isDarwin9())
936 O << "\t\t" << TAI->getCommentString() << " '" << I->getName() << "'\n";
938 switch (I->getLinkage()) {
939 case GlobalValue::LinkOnceLinkage:
940 case GlobalValue::WeakLinkage:
941 O << "\t.globl " << name << '\n'
942 << "\t.weak_definition " << name << '\n';
943 SwitchToDataSection("\t.section __DATA,__datacoal_nt,coalesced", I);
945 case GlobalValue::AppendingLinkage:
946 // FIXME: appending linkage variables should go into a section of
947 // their name or something. For now, just emit them as external.
948 case GlobalValue::ExternalLinkage:
949 // If external or appending, declare as a global symbol
950 O << "\t.globl " << name << "\n";
952 case GlobalValue::InternalLinkage:
953 if (I->isConstant()) {
954 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
955 if (TAI->getCStringSection() && CVA && CVA->isCString()) {
956 SwitchToDataSection(TAI->getCStringSection(), I);
961 if (!I->isConstant())
962 SwitchToDataSection(TAI->getDataSection(), I);
965 bool HasReloc = C->ContainsRelocations();
967 TM.getRelocationModel() != Reloc::Static)
968 SwitchToDataSection("\t.const_data\n");
969 else if (!HasReloc && Size == 4 &&
970 TAI->getFourByteConstantSection())
971 SwitchToDataSection(TAI->getFourByteConstantSection(), I);
972 else if (!HasReloc && Size == 8 &&
973 TAI->getEightByteConstantSection())
974 SwitchToDataSection(TAI->getEightByteConstantSection(), I);
975 else if (!HasReloc && Size == 16 &&
976 TAI->getSixteenByteConstantSection())
977 SwitchToDataSection(TAI->getSixteenByteConstantSection(), I);
978 else if (TAI->getReadOnlySection())
979 SwitchToDataSection(TAI->getReadOnlySection(), I);
981 SwitchToDataSection(TAI->getDataSection(), I);
985 cerr << "Unknown linkage type!";
989 EmitAlignment(Align, I);
990 O << name << ":\t\t\t\t" << TAI->getCommentString() << " '"
991 << I->getName() << "'\n";
993 // If the initializer is a extern weak symbol, remember to emit the weak
995 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
996 if (GV->hasExternalWeakLinkage())
997 ExtWeakSymbols.insert(GV);
999 EmitGlobalConstant(C);
1004 bool isPPC64 = TD->getPointerSizeInBits() == 64;
1006 // Output stubs for dynamically-linked functions
1007 if (TM.getRelocationModel() == Reloc::PIC_) {
1008 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
1010 SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
1011 "pure_instructions,32");
1013 O << "L" << *i << "$stub:\n";
1014 O << "\t.indirect_symbol " << *i << "\n";
1016 O << "\tbcl 20,31,L0$" << *i << "\n";
1017 O << "L0$" << *i << ":\n";
1018 O << "\tmflr r11\n";
1019 O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
1022 O << "\tldu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
1024 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
1025 O << "\tmtctr r12\n";
1027 SwitchToDataSection(".lazy_symbol_pointer");
1028 O << "L" << *i << "$lazy_ptr:\n";
1029 O << "\t.indirect_symbol " << *i << "\n";
1031 O << "\t.quad dyld_stub_binding_helper\n";
1033 O << "\t.long dyld_stub_binding_helper\n";
1036 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
1038 SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
1039 "pure_instructions,16");
1041 O << "L" << *i << "$stub:\n";
1042 O << "\t.indirect_symbol " << *i << "\n";
1043 O << "\tlis r11,ha16(L" << *i << "$lazy_ptr)\n";
1045 O << "\tldu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
1047 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
1048 O << "\tmtctr r12\n";
1050 SwitchToDataSection(".lazy_symbol_pointer");
1051 O << "L" << *i << "$lazy_ptr:\n";
1052 O << "\t.indirect_symbol " << *i << "\n";
1054 O << "\t.quad dyld_stub_binding_helper\n";
1056 O << "\t.long dyld_stub_binding_helper\n";
1062 if (ExceptionHandling && TAI->doesSupportExceptionHandling() && MMI) {
1063 // Add the (possibly multiple) personalities to the set of global values.
1064 const std::vector<Function *>& Personalities = MMI->getPersonalities();
1066 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1067 E = Personalities.end(); I != E; ++I)
1068 if (*I) GVStubs.insert("_" + (*I)->getName());
1071 // Output stubs for external and common global variables.
1072 if (!GVStubs.empty()) {
1073 SwitchToDataSection(".non_lazy_symbol_pointer");
1074 for (std::set<std::string>::iterator I = GVStubs.begin(),
1075 E = GVStubs.end(); I != E; ++I) {
1076 O << "L" << *I << "$non_lazy_ptr:\n";
1077 O << "\t.indirect_symbol " << *I << "\n";
1079 O << "\t.quad\t0\n";
1081 O << "\t.long\t0\n";
1086 // Emit initial debug information.
1089 // Funny Darwin hack: This flag tells the linker that no global symbols
1090 // contain code that falls through to other global symbols (e.g. the obvious
1091 // implementation of multiple entry points). If this doesn't occur, the
1092 // linker can safely perform dead code stripping. Since LLVM never generates
1093 // code that does this, it is always safe to set.
1094 O << "\t.subsections_via_symbols\n";
1096 return AsmPrinter::doFinalization(M);
1101 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1102 /// for a MachineFunction to the given output stream, in a format that the
1103 /// Darwin assembler can deal with.
1105 FunctionPass *llvm::createPPCAsmPrinterPass(std::ostream &o,
1106 PPCTargetMachine &tm) {
1107 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1109 if (Subtarget->isDarwin()) {
1110 return new DarwinAsmPrinter(o, tm, tm.getTargetAsmInfo());
1112 return new LinuxAsmPrinter(o, tm, tm.getTargetAsmInfo());