1 //===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly --------=//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/MachineDebugInfo.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()) {
127 O << MO.getImmedValue();
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).getImmedValue();
141 value = (value << (32-5)) >> (32-5);
144 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
145 unsigned char value = MI->getOperand(OpNo).getImmedValue();
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).getImmedValue();
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).getImmedValue();
157 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
158 O << (unsigned short)MI->getOperand(OpNo).getImmedValue();
160 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
161 if (MI->getOperand(OpNo).isImmediate()) {
162 O << (short)(MI->getOperand(OpNo).getImmedValue()*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).getImmedValue()*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->isExternal() || 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).getImmedValue()*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);
219 printOp(MI->getOperand(OpNo));
220 if (TM.getRelocationModel() == Reloc::PIC_)
221 O << "-\"L" << getFunctionNumber() << "$pb\")";
226 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
227 if (MI->getOperand(OpNo).isImmediate()) {
228 printS16ImmOperand(MI, OpNo);
231 printOp(MI->getOperand(OpNo));
232 if (TM.getRelocationModel() == Reloc::PIC_)
233 O << "-\"L" << getFunctionNumber() << "$pb\")";
238 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
239 unsigned CCReg = MI->getOperand(OpNo).getReg();
240 unsigned RegNo = enumRegToMachineReg(CCReg);
241 O << (0x80 >> RegNo);
243 // The new addressing mode printers.
244 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
245 printSymbolLo(MI, OpNo);
247 if (MI->getOperand(OpNo+1).isRegister() &&
248 MI->getOperand(OpNo+1).getReg() == PPC::R0)
251 printOperand(MI, OpNo+1);
254 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
255 if (MI->getOperand(OpNo).isImmediate())
256 printS16X4ImmOperand(MI, OpNo);
258 printSymbolLo(MI, OpNo);
260 if (MI->getOperand(OpNo+1).isRegister() &&
261 MI->getOperand(OpNo+1).getReg() == PPC::R0)
264 printOperand(MI, OpNo+1);
268 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
269 // When used as the base register, r0 reads constant zero rather than
270 // the value contained in the register. For this reason, the darwin
271 // assembler requires that we print r0 as 0 (no r) when used as the base.
272 const MachineOperand &MO = MI->getOperand(OpNo);
273 printRegister(MO, true);
275 printOperand(MI, OpNo+1);
278 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
279 const char *Modifier);
281 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
282 virtual bool doFinalization(Module &M) = 0;
285 /// LinuxAsmPrinter - PowerPC assembly printer, customized for Linux
286 struct VISIBILITY_HIDDEN LinuxAsmPrinter : public PPCAsmPrinter {
290 LinuxAsmPrinter(std::ostream &O, PPCTargetMachine &TM,
291 const TargetAsmInfo *T)
292 : PPCAsmPrinter(O, TM, T), DW(O, this, T) {
295 virtual const char *getPassName() const {
296 return "Linux PPC Assembly Printer";
299 bool runOnMachineFunction(MachineFunction &F);
300 bool doInitialization(Module &M);
301 bool doFinalization(Module &M);
303 void getAnalysisUsage(AnalysisUsage &AU) const {
304 AU.setPreservesAll();
305 AU.addRequired<MachineDebugInfo>();
306 PPCAsmPrinter::getAnalysisUsage(AU);
309 /// getSectionForFunction - Return the section that we should emit the
310 /// specified function body into.
311 virtual std::string getSectionForFunction(const Function &F) const;
314 /// DarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac OS
316 struct VISIBILITY_HIDDEN DarwinAsmPrinter : public PPCAsmPrinter {
320 DarwinAsmPrinter(std::ostream &O, PPCTargetMachine &TM,
321 const TargetAsmInfo *T)
322 : PPCAsmPrinter(O, TM, T), DW(O, this, T) {
325 virtual const char *getPassName() const {
326 return "Darwin PPC Assembly Printer";
329 bool runOnMachineFunction(MachineFunction &F);
330 bool doInitialization(Module &M);
331 bool doFinalization(Module &M);
333 void getAnalysisUsage(AnalysisUsage &AU) const {
334 AU.setPreservesAll();
335 AU.addRequired<MachineDebugInfo>();
336 PPCAsmPrinter::getAnalysisUsage(AU);
339 /// getSectionForFunction - Return the section that we should emit the
340 /// specified function body into.
341 virtual std::string getSectionForFunction(const Function &F) const;
343 } // end of anonymous namespace
345 // Include the auto-generated portion of the assembly writer
346 #include "PPCGenAsmWriter.inc"
348 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
349 switch (MO.getType()) {
350 case MachineOperand::MO_Immediate:
351 cerr << "printOp() does not handle immediate values\n";
355 case MachineOperand::MO_MachineBasicBlock:
356 printBasicBlockLabel(MO.getMachineBasicBlock());
358 case MachineOperand::MO_JumpTableIndex:
359 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
360 << '_' << MO.getJumpTableIndex();
361 // FIXME: PIC relocation model
363 case MachineOperand::MO_ConstantPoolIndex:
364 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
365 << '_' << MO.getConstantPoolIndex();
367 case MachineOperand::MO_ExternalSymbol:
368 // Computing the address of an external symbol, not calling it.
369 if (TM.getRelocationModel() != Reloc::Static) {
370 std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
371 GVStubs.insert(Name);
372 O << "L" << Name << "$non_lazy_ptr";
375 O << TAI->getGlobalPrefix() << MO.getSymbolName();
377 case MachineOperand::MO_GlobalAddress: {
378 // Computing the address of a global symbol, not calling it.
379 GlobalValue *GV = MO.getGlobal();
380 std::string Name = Mang->getValueName(GV);
382 // External or weakly linked global variables need non-lazily-resolved stubs
383 if (TM.getRelocationModel() != Reloc::Static) {
384 if (((GV->isExternal() || GV->hasWeakLinkage() ||
385 GV->hasLinkOnceLinkage()))) {
386 GVStubs.insert(Name);
387 O << "L" << Name << "$non_lazy_ptr";
393 if (GV->hasExternalWeakLinkage())
394 ExtWeakSymbols.insert(GV);
399 O << "<unknown operand type: " << MO.getType() << ">";
404 /// PrintAsmOperand - Print out an operand for an inline asm expression.
406 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
408 const char *ExtraCode) {
409 // Does this asm operand have a single letter operand modifier?
410 if (ExtraCode && ExtraCode[0]) {
411 if (ExtraCode[1] != 0) return true; // Unknown modifier.
413 switch (ExtraCode[0]) {
414 default: return true; // Unknown modifier.
415 case 'L': // Write second word of DImode reference.
416 // Verify that this operand has two consecutive registers.
417 if (!MI->getOperand(OpNo).isRegister() ||
418 OpNo+1 == MI->getNumOperands() ||
419 !MI->getOperand(OpNo+1).isRegister())
421 ++OpNo; // Return the high-part.
426 printOperand(MI, OpNo);
430 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
432 const char *ExtraCode) {
433 if (ExtraCode && ExtraCode[0])
434 return true; // Unknown modifier.
435 printMemRegReg(MI, OpNo);
439 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
440 const char *Modifier) {
441 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
442 unsigned Code = MI->getOperand(OpNo).getImm();
443 if (!strcmp(Modifier, "cc")) {
444 switch ((PPC::Predicate)Code) {
445 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
446 case PPC::PRED_LT: O << "lt"; return;
447 case PPC::PRED_LE: O << "le"; return;
448 case PPC::PRED_EQ: O << "eq"; return;
449 case PPC::PRED_GE: O << "ge"; return;
450 case PPC::PRED_GT: O << "gt"; return;
451 case PPC::PRED_NE: O << "ne"; return;
452 case PPC::PRED_UN: O << "un"; return;
453 case PPC::PRED_NU: O << "nu"; return;
457 assert(!strcmp(Modifier, "reg") &&
458 "Need to specify 'cc' or 'reg' as predicate op modifier!");
459 // Don't print the register for 'always'.
460 if (Code == PPC::PRED_ALWAYS) return;
461 printOperand(MI, OpNo+1);
466 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
467 /// the current output stream.
469 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
472 // Check for slwi/srwi mnemonics.
473 if (MI->getOpcode() == PPC::RLWINM) {
474 bool FoundMnemonic = false;
475 unsigned char SH = MI->getOperand(2).getImmedValue();
476 unsigned char MB = MI->getOperand(3).getImmedValue();
477 unsigned char ME = MI->getOperand(4).getImmedValue();
478 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
479 O << "slwi "; FoundMnemonic = true;
481 if (SH <= 31 && MB == (32-SH) && ME == 31) {
482 O << "srwi "; FoundMnemonic = true;
489 O << ", " << (unsigned int)SH << "\n";
492 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
493 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
501 } else if (MI->getOpcode() == PPC::RLDICR) {
502 unsigned char SH = MI->getOperand(2).getImmedValue();
503 unsigned char ME = MI->getOperand(3).getImmedValue();
504 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
510 O << ", " << (unsigned int)SH << "\n";
515 if (printInstruction(MI))
516 return; // Printer was automatically generated
518 assert(0 && "Unhandled instruction in asm writer!");
523 /// runOnMachineFunction - This uses the printMachineInstruction()
524 /// method to print assembly for each instruction.
526 bool LinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
527 DW.SetDebugInfo(&getAnalysis<MachineDebugInfo>());
529 SetupMachineFunction(MF);
532 // Print out constants referenced by the function
533 EmitConstantPool(MF.getConstantPool());
535 // Print out labels for the function.
536 const Function *F = MF.getFunction();
537 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
539 switch (F->getLinkage()) {
540 default: assert(0 && "Unknown linkage type!");
541 case Function::InternalLinkage: // Symbols default to internal.
543 case Function::ExternalLinkage:
544 O << "\t.global\t" << CurrentFnName << '\n'
545 << "\t.type\t" << CurrentFnName << ", @function\n";
547 case Function::WeakLinkage:
548 case Function::LinkOnceLinkage:
549 O << "\t.global\t" << CurrentFnName << '\n';
550 O << "\t.weak\t" << CurrentFnName << '\n';
554 if (F->hasHiddenVisibility())
555 if (const char *Directive = TAI->getHiddenDirective())
556 O << Directive << CurrentFnName << "\n";
559 O << CurrentFnName << ":\n";
561 // Emit pre-function debug information.
562 DW.BeginFunction(&MF);
564 // Print out code for the function.
565 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
567 // Print a label for the basic block.
568 if (I != MF.begin()) {
569 printBasicBlockLabel(I, true);
572 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
574 // Print the assembly for the instruction.
576 printMachineInstruction(II);
580 O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << "\n";
582 // Print out jump tables referenced by the function.
583 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
585 // Emit post-function debug information.
588 // We didn't modify anything.
592 bool LinuxAsmPrinter::doInitialization(Module &M) {
593 AsmPrinter::doInitialization(M);
595 // GNU as handles section names wrapped in quotes
596 Mang->setUseQuotes(true);
598 SwitchToTextSection(TAI->getTextSection());
600 // Emit initial debug information.
605 bool LinuxAsmPrinter::doFinalization(Module &M) {
606 const TargetData *TD = TM.getTargetData();
608 // Print out module-level global variables here.
609 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
611 if (!I->hasInitializer()) continue; // External global require no code
613 // Check to see if this is a special global used by LLVM, if so, emit it.
614 if (EmitSpecialLLVMGlobal(I))
617 std::string name = Mang->getValueName(I);
619 if (I->hasHiddenVisibility())
620 if (const char *Directive = TAI->getHiddenDirective())
621 O << Directive << name << "\n";
623 Constant *C = I->getInitializer();
624 unsigned Size = TD->getTypeSize(C->getType());
625 unsigned Align = TD->getPreferredAlignmentLog(I);
627 if (C->isNullValue() && /* FIXME: Verify correct */
628 (I->hasInternalLinkage() || I->hasWeakLinkage() ||
629 I->hasLinkOnceLinkage() ||
630 (I->hasExternalLinkage() && !I->hasSection()))) {
631 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
632 if (I->hasExternalLinkage()) {
633 O << "\t.global " << name << '\n';
634 O << "\t.type " << name << ", @object\n";
635 //O << "\t.zerofill __DATA, __common, " << name << ", "
636 // << Size << ", " << Align;
637 } else if (I->hasInternalLinkage()) {
638 SwitchToDataSection("\t.data", I);
639 O << TAI->getLCOMMDirective() << name << "," << Size;
641 SwitchToDataSection("\t.data", I);
642 O << ".comm " << name << "," << Size;
644 O << "\t\t" << TAI->getCommentString() << " '" << I->getName() << "'\n";
646 switch (I->getLinkage()) {
647 case GlobalValue::LinkOnceLinkage:
648 case GlobalValue::WeakLinkage:
649 O << "\t.global " << name << '\n'
650 << "\t.type " << name << ", @object\n"
651 << "\t.weak " << name << '\n';
652 SwitchToDataSection("\t.data", I);
654 case GlobalValue::AppendingLinkage:
655 // FIXME: appending linkage variables should go into a section of
656 // their name or something. For now, just emit them as external.
657 case GlobalValue::ExternalLinkage:
658 // If external or appending, declare as a global symbol
659 O << "\t.global " << name << "\n"
660 << "\t.type " << name << ", @object\n";
662 case GlobalValue::InternalLinkage:
663 if (I->isConstant()) {
664 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
665 if (TAI->getCStringSection() && CVA && CVA->isCString()) {
666 SwitchToDataSection(TAI->getCStringSection(), I);
671 // FIXME: special handling for ".ctors" & ".dtors" sections
672 if (I->hasSection() &&
673 (I->getSection() == ".ctors" ||
674 I->getSection() == ".dtors")) {
675 std::string SectionName = ".section " + I->getSection()
676 + ",\"aw\",@progbits";
677 SwitchToDataSection(SectionName.c_str());
679 SwitchToDataSection(TAI->getDataSection(), I);
683 cerr << "Unknown linkage type!";
687 EmitAlignment(Align, I);
688 O << name << ":\t\t\t\t" << TAI->getCommentString() << " '"
689 << I->getName() << "'\n";
691 // If the initializer is a extern weak symbol, remember to emit the weak
693 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
694 if (GV->hasExternalWeakLinkage())
695 ExtWeakSymbols.insert(GV);
697 EmitGlobalConstant(C);
704 // Emit initial debug information.
707 AsmPrinter::doFinalization(M);
708 return false; // success
711 std::string LinuxAsmPrinter::getSectionForFunction(const Function &F) const {
712 switch (F.getLinkage()) {
713 default: assert(0 && "Unknown linkage type!");
714 case Function::ExternalLinkage:
715 case Function::InternalLinkage: return TAI->getTextSection();
716 case Function::WeakLinkage:
717 case Function::LinkOnceLinkage:
722 std::string DarwinAsmPrinter::getSectionForFunction(const Function &F) const {
723 switch (F.getLinkage()) {
724 default: assert(0 && "Unknown linkage type!");
725 case Function::ExternalLinkage:
726 case Function::InternalLinkage: return TAI->getTextSection();
727 case Function::WeakLinkage:
728 case Function::LinkOnceLinkage:
729 return ".section __TEXT,__textcoal_nt,coalesced,pure_instructions";
733 /// runOnMachineFunction - This uses the printMachineInstruction()
734 /// method to print assembly for each instruction.
736 bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
737 DW.SetDebugInfo(&getAnalysis<MachineDebugInfo>());
739 SetupMachineFunction(MF);
742 // Print out constants referenced by the function
743 EmitConstantPool(MF.getConstantPool());
745 // Print out labels for the function.
746 const Function *F = MF.getFunction();
747 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
749 switch (F->getLinkage()) {
750 default: assert(0 && "Unknown linkage type!");
751 case Function::InternalLinkage: // Symbols default to internal.
753 case Function::ExternalLinkage:
754 O << "\t.globl\t" << CurrentFnName << "\n";
756 case Function::WeakLinkage:
757 case Function::LinkOnceLinkage:
758 O << "\t.globl\t" << CurrentFnName << "\n";
759 O << "\t.weak_definition\t" << CurrentFnName << "\n";
763 if (F->hasHiddenVisibility())
764 if (const char *Directive = TAI->getHiddenDirective())
765 O << Directive << CurrentFnName << "\n";
768 O << CurrentFnName << ":\n";
770 // Emit pre-function debug information.
771 DW.BeginFunction(&MF);
773 // Print out code for the function.
774 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
776 // Print a label for the basic block.
777 if (I != MF.begin()) {
778 printBasicBlockLabel(I, true);
781 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
783 // Print the assembly for the instruction.
785 printMachineInstruction(II);
789 // Print out jump tables referenced by the function.
790 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
792 // Emit post-function debug information.
795 // We didn't modify anything.
800 bool DarwinAsmPrinter::doInitialization(Module &M) {
801 static const char *CPUDirectives[] = {
812 unsigned Directive = Subtarget.getDarwinDirective();
813 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
814 Directive = PPC::DIR_970;
815 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
816 Directive = PPC::DIR_7400;
817 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
818 Directive = PPC::DIR_64;
819 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
820 O << "\t.machine " << CPUDirectives[Directive] << "\n";
822 AsmPrinter::doInitialization(M);
824 // Darwin wants symbols to be quoted if they have complex names.
825 Mang->setUseQuotes(true);
827 // Prime text sections so they are adjacent. This reduces the likelihood a
828 // large data or debug section causes a branch to exceed 16M limit.
829 SwitchToTextSection(".section __TEXT,__textcoal_nt,coalesced,"
830 "pure_instructions");
831 if (TM.getRelocationModel() == Reloc::PIC_) {
832 SwitchToTextSection(".section __TEXT,__picsymbolstub1,symbol_stubs,"
833 "pure_instructions,32");
834 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
835 SwitchToTextSection(".section __TEXT,__symbol_stub1,symbol_stubs,"
836 "pure_instructions,16");
838 SwitchToTextSection(TAI->getTextSection());
840 // Emit initial debug information.
845 bool DarwinAsmPrinter::doFinalization(Module &M) {
846 const TargetData *TD = TM.getTargetData();
848 // Print out module-level global variables here.
849 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
851 if (!I->hasInitializer()) continue; // External global require no code
853 // Check to see if this is a special global used by LLVM, if so, emit it.
854 if (EmitSpecialLLVMGlobal(I))
857 std::string name = Mang->getValueName(I);
859 if (I->hasHiddenVisibility())
860 if (const char *Directive = TAI->getHiddenDirective())
861 O << Directive << name << "\n";
863 Constant *C = I->getInitializer();
864 unsigned Size = TD->getTypeSize(C->getType());
865 unsigned Align = TD->getPreferredAlignmentLog(I);
867 if (C->isNullValue() && /* FIXME: Verify correct */
868 (I->hasInternalLinkage() || I->hasWeakLinkage() ||
869 I->hasLinkOnceLinkage() ||
870 (I->hasExternalLinkage() && !I->hasSection()))) {
871 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
872 if (I->hasExternalLinkage()) {
873 O << "\t.globl " << name << '\n';
874 O << "\t.zerofill __DATA, __common, " << name << ", "
875 << Size << ", " << Align;
876 } else if (I->hasInternalLinkage()) {
877 SwitchToDataSection("\t.data", I);
878 O << TAI->getLCOMMDirective() << name << "," << Size << "," << Align;
880 SwitchToDataSection("\t.data", I);
881 O << ".comm " << name << "," << Size;
883 O << "\t\t" << TAI->getCommentString() << " '" << I->getName() << "'\n";
885 switch (I->getLinkage()) {
886 case GlobalValue::LinkOnceLinkage:
887 case GlobalValue::WeakLinkage:
888 O << "\t.globl " << name << '\n'
889 << "\t.weak_definition " << name << '\n';
890 SwitchToDataSection(".section __DATA,__datacoal_nt,coalesced", I);
892 case GlobalValue::AppendingLinkage:
893 // FIXME: appending linkage variables should go into a section of
894 // their name or something. For now, just emit them as external.
895 case GlobalValue::ExternalLinkage:
896 // If external or appending, declare as a global symbol
897 O << "\t.globl " << name << "\n";
899 case GlobalValue::InternalLinkage:
900 if (I->isConstant()) {
901 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
902 if (TAI->getCStringSection() && CVA && CVA->isCString()) {
903 SwitchToDataSection(TAI->getCStringSection(), I);
908 SwitchToDataSection("\t.data", I);
911 cerr << "Unknown linkage type!";
915 EmitAlignment(Align, I);
916 O << name << ":\t\t\t\t" << TAI->getCommentString() << " '"
917 << I->getName() << "'\n";
919 // If the initializer is a extern weak symbol, remember to emit the weak
921 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
922 if (GV->hasExternalWeakLinkage())
923 ExtWeakSymbols.insert(GV);
925 EmitGlobalConstant(C);
930 bool isPPC64 = TD->getPointerSizeInBits() == 64;
932 // Output stubs for dynamically-linked functions
933 if (TM.getRelocationModel() == Reloc::PIC_) {
934 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
936 SwitchToTextSection(".section __TEXT,__picsymbolstub1,symbol_stubs,"
937 "pure_instructions,32");
939 O << "L" << *i << "$stub:\n";
940 O << "\t.indirect_symbol " << *i << "\n";
942 O << "\tbcl 20,31,L0$" << *i << "\n";
943 O << "L0$" << *i << ":\n";
945 O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
948 O << "\tldu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
950 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
951 O << "\tmtctr r12\n";
953 SwitchToDataSection(".lazy_symbol_pointer");
954 O << "L" << *i << "$lazy_ptr:\n";
955 O << "\t.indirect_symbol " << *i << "\n";
957 O << "\t.quad dyld_stub_binding_helper\n";
959 O << "\t.long dyld_stub_binding_helper\n";
962 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
964 SwitchToTextSection(".section __TEXT,__symbol_stub1,symbol_stubs,"
965 "pure_instructions,16");
967 O << "L" << *i << "$stub:\n";
968 O << "\t.indirect_symbol " << *i << "\n";
969 O << "\tlis r11,ha16(L" << *i << "$lazy_ptr)\n";
971 O << "\tldu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
973 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
974 O << "\tmtctr r12\n";
976 SwitchToDataSection(".lazy_symbol_pointer");
977 O << "L" << *i << "$lazy_ptr:\n";
978 O << "\t.indirect_symbol " << *i << "\n";
980 O << "\t.quad dyld_stub_binding_helper\n";
982 O << "\t.long dyld_stub_binding_helper\n";
988 // Output stubs for external and common global variables.
989 if (GVStubs.begin() != GVStubs.end()) {
990 SwitchToDataSection(".non_lazy_symbol_pointer");
991 for (std::set<std::string>::iterator I = GVStubs.begin(),
992 E = GVStubs.end(); I != E; ++I) {
993 O << "L" << *I << "$non_lazy_ptr:\n";
994 O << "\t.indirect_symbol " << *I << "\n";
1003 // Emit initial debug information.
1006 // Funny Darwin hack: This flag tells the linker that no global symbols
1007 // contain code that falls through to other global symbols (e.g. the obvious
1008 // implementation of multiple entry points). If this doesn't occur, the
1009 // linker can safely perform dead code stripping. Since LLVM never generates
1010 // code that does this, it is always safe to set.
1011 O << "\t.subsections_via_symbols\n";
1013 AsmPrinter::doFinalization(M);
1014 return false; // success
1019 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1020 /// for a MachineFunction to the given output stream, in a format that the
1021 /// Darwin assembler can deal with.
1023 FunctionPass *llvm::createPPCAsmPrinterPass(std::ostream &o,
1024 PPCTargetMachine &tm) {
1025 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1027 if (Subtarget->isDarwin()) {
1028 return new DarwinAsmPrinter(o, tm, tm.getTargetAsmInfo());
1030 return new LinuxAsmPrinter(o, tm, tm.getTargetAsmInfo());