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/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()) {
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->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).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;
284 virtual void EmitExternalGlobal(const GlobalVariable *GV);
287 /// LinuxAsmPrinter - PowerPC assembly printer, customized for Linux
288 struct VISIBILITY_HIDDEN LinuxAsmPrinter : public PPCAsmPrinter {
292 LinuxAsmPrinter(std::ostream &O, PPCTargetMachine &TM,
293 const TargetAsmInfo *T)
294 : PPCAsmPrinter(O, TM, T), DW(O, this, T) {
297 virtual const char *getPassName() const {
298 return "Linux PPC Assembly Printer";
301 bool runOnMachineFunction(MachineFunction &F);
302 bool doInitialization(Module &M);
303 bool doFinalization(Module &M);
305 void getAnalysisUsage(AnalysisUsage &AU) const {
306 AU.setPreservesAll();
307 AU.addRequired<MachineModuleInfo>();
308 PPCAsmPrinter::getAnalysisUsage(AU);
311 /// getSectionForFunction - Return the section that we should emit the
312 /// specified function body into.
313 virtual std::string getSectionForFunction(const Function &F) const;
316 /// DarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac OS
318 struct VISIBILITY_HIDDEN DarwinAsmPrinter : public PPCAsmPrinter {
322 DarwinAsmPrinter(std::ostream &O, PPCTargetMachine &TM,
323 const TargetAsmInfo *T)
324 : PPCAsmPrinter(O, TM, T), DW(O, this, T) {
327 virtual const char *getPassName() const {
328 return "Darwin PPC Assembly Printer";
331 bool runOnMachineFunction(MachineFunction &F);
332 bool doInitialization(Module &M);
333 bool doFinalization(Module &M);
335 void getAnalysisUsage(AnalysisUsage &AU) const {
336 AU.setPreservesAll();
337 AU.addRequired<MachineModuleInfo>();
338 PPCAsmPrinter::getAnalysisUsage(AU);
341 /// getSectionForFunction - Return the section that we should emit the
342 /// specified function body into.
343 virtual std::string getSectionForFunction(const Function &F) const;
345 } // end of anonymous namespace
347 // Include the auto-generated portion of the assembly writer
348 #include "PPCGenAsmWriter.inc"
350 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
351 switch (MO.getType()) {
352 case MachineOperand::MO_Immediate:
353 cerr << "printOp() does not handle immediate values\n";
357 case MachineOperand::MO_MachineBasicBlock:
358 printBasicBlockLabel(MO.getMachineBasicBlock());
360 case MachineOperand::MO_JumpTableIndex:
361 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
362 << '_' << MO.getJumpTableIndex();
363 // FIXME: PIC relocation model
365 case MachineOperand::MO_ConstantPoolIndex:
366 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
367 << '_' << MO.getConstantPoolIndex();
369 case MachineOperand::MO_ExternalSymbol:
370 // Computing the address of an external symbol, not calling it.
371 if (TM.getRelocationModel() != Reloc::Static) {
372 std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
373 GVStubs.insert(Name);
374 O << "L" << Name << "$non_lazy_ptr";
377 O << TAI->getGlobalPrefix() << MO.getSymbolName();
379 case MachineOperand::MO_GlobalAddress: {
380 // Computing the address of a global symbol, not calling it.
381 GlobalValue *GV = MO.getGlobal();
382 std::string Name = Mang->getValueName(GV);
384 // External or weakly linked global variables need non-lazily-resolved stubs
385 if (TM.getRelocationModel() != Reloc::Static) {
386 if (((GV->isDeclaration() || GV->hasWeakLinkage() ||
387 GV->hasLinkOnceLinkage()))) {
388 GVStubs.insert(Name);
389 O << "L" << Name << "$non_lazy_ptr";
395 if (GV->hasExternalWeakLinkage())
396 ExtWeakSymbols.insert(GV);
401 O << "<unknown operand type: " << MO.getType() << ">";
406 /// EmitExternalGlobal - In this case we need to use the indirect symbol.
408 void PPCAsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
409 std::string Name = getGlobalLinkName(GV);
410 if (TM.getRelocationModel() != Reloc::Static) {
411 GVStubs.insert(Name);
412 O << "L" << Name << "$non_lazy_ptr";
418 /// PrintAsmOperand - Print out an operand for an inline asm expression.
420 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
422 const char *ExtraCode) {
423 // Does this asm operand have a single letter operand modifier?
424 if (ExtraCode && ExtraCode[0]) {
425 if (ExtraCode[1] != 0) return true; // Unknown modifier.
427 switch (ExtraCode[0]) {
428 default: return true; // Unknown modifier.
429 case 'c': // Don't print "$" before a global var name or constant.
430 // PPC never has a prefix.
431 printOperand(MI, OpNo);
433 case 'L': // Write second word of DImode reference.
434 // Verify that this operand has two consecutive registers.
435 if (!MI->getOperand(OpNo).isRegister() ||
436 OpNo+1 == MI->getNumOperands() ||
437 !MI->getOperand(OpNo+1).isRegister())
439 ++OpNo; // Return the high-part.
444 printOperand(MI, OpNo);
448 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
450 const char *ExtraCode) {
451 if (ExtraCode && ExtraCode[0])
452 return true; // Unknown modifier.
453 if (MI->getOperand(OpNo).isRegister())
454 printMemRegReg(MI, OpNo);
456 printMemRegImm(MI, OpNo);
460 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
461 const char *Modifier) {
462 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
463 unsigned Code = MI->getOperand(OpNo).getImm();
464 if (!strcmp(Modifier, "cc")) {
465 switch ((PPC::Predicate)Code) {
466 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
467 case PPC::PRED_LT: O << "lt"; return;
468 case PPC::PRED_LE: O << "le"; return;
469 case PPC::PRED_EQ: O << "eq"; return;
470 case PPC::PRED_GE: O << "ge"; return;
471 case PPC::PRED_GT: O << "gt"; return;
472 case PPC::PRED_NE: O << "ne"; return;
473 case PPC::PRED_UN: O << "un"; return;
474 case PPC::PRED_NU: O << "nu"; return;
478 assert(!strcmp(Modifier, "reg") &&
479 "Need to specify 'cc' or 'reg' as predicate op modifier!");
480 // Don't print the register for 'always'.
481 if (Code == PPC::PRED_ALWAYS) return;
482 printOperand(MI, OpNo+1);
487 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
488 /// the current output stream.
490 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
493 // Check for slwi/srwi mnemonics.
494 if (MI->getOpcode() == PPC::RLWINM) {
495 bool FoundMnemonic = false;
496 unsigned char SH = MI->getOperand(2).getImmedValue();
497 unsigned char MB = MI->getOperand(3).getImmedValue();
498 unsigned char ME = MI->getOperand(4).getImmedValue();
499 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
500 O << "slwi "; FoundMnemonic = true;
502 if (SH <= 31 && MB == (32-SH) && ME == 31) {
503 O << "srwi "; FoundMnemonic = true;
510 O << ", " << (unsigned int)SH << "\n";
513 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
514 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
522 } else if (MI->getOpcode() == PPC::RLDICR) {
523 unsigned char SH = MI->getOperand(2).getImmedValue();
524 unsigned char ME = MI->getOperand(3).getImmedValue();
525 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
531 O << ", " << (unsigned int)SH << "\n";
536 if (printInstruction(MI))
537 return; // Printer was automatically generated
539 assert(0 && "Unhandled instruction in asm writer!");
544 /// runOnMachineFunction - This uses the printMachineInstruction()
545 /// method to print assembly for each instruction.
547 bool LinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
548 DW.SetModuleInfo(&getAnalysis<MachineModuleInfo>());
550 SetupMachineFunction(MF);
553 // Print out constants referenced by the function
554 EmitConstantPool(MF.getConstantPool());
556 // Print out labels for the function.
557 const Function *F = MF.getFunction();
558 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
560 switch (F->getLinkage()) {
561 default: assert(0 && "Unknown linkage type!");
562 case Function::InternalLinkage: // Symbols default to internal.
564 case Function::ExternalLinkage:
565 O << "\t.global\t" << CurrentFnName << '\n'
566 << "\t.type\t" << CurrentFnName << ", @function\n";
568 case Function::WeakLinkage:
569 case Function::LinkOnceLinkage:
570 O << "\t.global\t" << CurrentFnName << '\n';
571 O << "\t.weak\t" << CurrentFnName << '\n';
575 if (F->hasHiddenVisibility())
576 if (const char *Directive = TAI->getHiddenDirective())
577 O << Directive << CurrentFnName << "\n";
580 O << CurrentFnName << ":\n";
582 // Emit pre-function debug information.
583 DW.BeginFunction(&MF);
585 // Print out code for the function.
586 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
588 // Print a label for the basic block.
589 if (I != MF.begin()) {
590 printBasicBlockLabel(I, true);
593 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
595 // Print the assembly for the instruction.
597 printMachineInstruction(II);
601 O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << "\n";
603 // Print out jump tables referenced by the function.
604 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
606 // Emit post-function debug information.
609 // We didn't modify anything.
613 bool LinuxAsmPrinter::doInitialization(Module &M) {
614 AsmPrinter::doInitialization(M);
616 // GNU as handles section names wrapped in quotes
617 Mang->setUseQuotes(true);
619 SwitchToTextSection(TAI->getTextSection());
621 // Emit initial debug information.
626 bool LinuxAsmPrinter::doFinalization(Module &M) {
627 const TargetData *TD = TM.getTargetData();
629 // Print out module-level global variables here.
630 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
632 if (!I->hasInitializer()) continue; // External global require no code
634 // Check to see if this is a special global used by LLVM, if so, emit it.
635 if (EmitSpecialLLVMGlobal(I))
638 std::string name = Mang->getValueName(I);
640 if (I->hasHiddenVisibility())
641 if (const char *Directive = TAI->getHiddenDirective())
642 O << Directive << name << "\n";
644 Constant *C = I->getInitializer();
645 unsigned Size = TD->getTypeSize(C->getType());
646 unsigned Align = TD->getPreferredAlignmentLog(I);
648 if (C->isNullValue() && /* FIXME: Verify correct */
649 (I->hasInternalLinkage() || I->hasWeakLinkage() ||
650 I->hasLinkOnceLinkage() ||
651 (I->hasExternalLinkage() && !I->hasSection()))) {
652 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
653 if (I->hasExternalLinkage()) {
654 O << "\t.global " << name << '\n';
655 O << "\t.type " << name << ", @object\n";
656 //O << "\t.zerofill __DATA, __common, " << name << ", "
657 // << Size << ", " << Align;
658 } else if (I->hasInternalLinkage()) {
659 SwitchToDataSection("\t.data", I);
660 O << TAI->getLCOMMDirective() << name << "," << Size;
662 SwitchToDataSection("\t.data", I);
663 O << ".comm " << name << "," << Size;
665 O << "\t\t" << TAI->getCommentString() << " '" << I->getName() << "'\n";
667 switch (I->getLinkage()) {
668 case GlobalValue::LinkOnceLinkage:
669 case GlobalValue::WeakLinkage:
670 O << "\t.global " << name << '\n'
671 << "\t.type " << name << ", @object\n"
672 << "\t.weak " << name << '\n';
673 SwitchToDataSection("\t.data", I);
675 case GlobalValue::AppendingLinkage:
676 // FIXME: appending linkage variables should go into a section of
677 // their name or something. For now, just emit them as external.
678 case GlobalValue::ExternalLinkage:
679 // If external or appending, declare as a global symbol
680 O << "\t.global " << name << "\n"
681 << "\t.type " << name << ", @object\n";
683 case GlobalValue::InternalLinkage:
684 if (I->isConstant()) {
685 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
686 if (TAI->getCStringSection() && CVA && CVA->isCString()) {
687 SwitchToDataSection(TAI->getCStringSection(), I);
692 // FIXME: special handling for ".ctors" & ".dtors" sections
693 if (I->hasSection() &&
694 (I->getSection() == ".ctors" ||
695 I->getSection() == ".dtors")) {
696 std::string SectionName = ".section " + I->getSection()
697 + ",\"aw\",@progbits";
698 SwitchToDataSection(SectionName.c_str());
700 SwitchToDataSection(TAI->getDataSection(), I);
704 cerr << "Unknown linkage type!";
708 EmitAlignment(Align, I);
709 O << name << ":\t\t\t\t" << TAI->getCommentString() << " '"
710 << I->getName() << "'\n";
712 // If the initializer is a extern weak symbol, remember to emit the weak
714 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
715 if (GV->hasExternalWeakLinkage())
716 ExtWeakSymbols.insert(GV);
718 EmitGlobalConstant(C);
725 // Emit initial debug information.
728 AsmPrinter::doFinalization(M);
729 return false; // success
732 std::string LinuxAsmPrinter::getSectionForFunction(const Function &F) const {
733 switch (F.getLinkage()) {
734 default: assert(0 && "Unknown linkage type!");
735 case Function::ExternalLinkage:
736 case Function::InternalLinkage: return TAI->getTextSection();
737 case Function::WeakLinkage:
738 case Function::LinkOnceLinkage:
743 std::string DarwinAsmPrinter::getSectionForFunction(const Function &F) const {
744 switch (F.getLinkage()) {
745 default: assert(0 && "Unknown linkage type!");
746 case Function::ExternalLinkage:
747 case Function::InternalLinkage: return TAI->getTextSection();
748 case Function::WeakLinkage:
749 case Function::LinkOnceLinkage:
750 return ".section __TEXT,__textcoal_nt,coalesced,pure_instructions";
754 /// runOnMachineFunction - This uses the printMachineInstruction()
755 /// method to print assembly for each instruction.
757 bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
758 DW.SetModuleInfo(&getAnalysis<MachineModuleInfo>());
760 SetupMachineFunction(MF);
763 // Print out constants referenced by the function
764 EmitConstantPool(MF.getConstantPool());
766 // Print out labels for the function.
767 const Function *F = MF.getFunction();
768 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
770 switch (F->getLinkage()) {
771 default: assert(0 && "Unknown linkage type!");
772 case Function::InternalLinkage: // Symbols default to internal.
774 case Function::ExternalLinkage:
775 O << "\t.globl\t" << CurrentFnName << "\n";
777 case Function::WeakLinkage:
778 case Function::LinkOnceLinkage:
779 O << "\t.globl\t" << CurrentFnName << "\n";
780 O << "\t.weak_definition\t" << CurrentFnName << "\n";
784 if (F->hasHiddenVisibility())
785 if (const char *Directive = TAI->getHiddenDirective())
786 O << Directive << CurrentFnName << "\n";
789 O << CurrentFnName << ":\n";
791 // Emit pre-function debug information.
792 DW.BeginFunction(&MF);
794 // Print out code for the function.
795 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
797 // Print a label for the basic block.
798 if (I != MF.begin()) {
799 printBasicBlockLabel(I, true);
802 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
804 // Print the assembly for the instruction.
806 printMachineInstruction(II);
810 // Print out jump tables referenced by the function.
811 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
813 // Emit post-function debug information.
816 // We didn't modify anything.
821 bool DarwinAsmPrinter::doInitialization(Module &M) {
822 static const char *CPUDirectives[] = {
833 unsigned Directive = Subtarget.getDarwinDirective();
834 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
835 Directive = PPC::DIR_970;
836 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
837 Directive = PPC::DIR_7400;
838 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
839 Directive = PPC::DIR_64;
840 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
841 O << "\t.machine " << CPUDirectives[Directive] << "\n";
843 AsmPrinter::doInitialization(M);
845 // Darwin wants symbols to be quoted if they have complex names.
846 Mang->setUseQuotes(true);
848 // Prime text sections so they are adjacent. This reduces the likelihood a
849 // large data or debug section causes a branch to exceed 16M limit.
850 SwitchToTextSection(".section __TEXT,__textcoal_nt,coalesced,"
851 "pure_instructions");
852 if (TM.getRelocationModel() == Reloc::PIC_) {
853 SwitchToTextSection(".section __TEXT,__picsymbolstub1,symbol_stubs,"
854 "pure_instructions,32");
855 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
856 SwitchToTextSection(".section __TEXT,__symbol_stub1,symbol_stubs,"
857 "pure_instructions,16");
859 SwitchToTextSection(TAI->getTextSection());
861 // Emit initial debug information.
866 bool DarwinAsmPrinter::doFinalization(Module &M) {
867 const TargetData *TD = TM.getTargetData();
869 // Print out module-level global variables here.
870 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
872 if (!I->hasInitializer()) continue; // External global require no code
874 // Check to see if this is a special global used by LLVM, if so, emit it.
875 if (EmitSpecialLLVMGlobal(I)) {
876 if (TM.getRelocationModel() == Reloc::Static) {
877 if (I->getName() == "llvm.global_ctors")
878 O << ".reference .constructors_used\n";
879 else if (I->getName() == "llvm.global_dtors")
880 O << ".reference .destructors_used\n";
885 std::string name = Mang->getValueName(I);
887 if (I->hasHiddenVisibility())
888 if (const char *Directive = TAI->getHiddenDirective())
889 O << Directive << name << "\n";
891 Constant *C = I->getInitializer();
892 unsigned Size = TD->getTypeSize(C->getType());
893 unsigned Align = TD->getPreferredAlignmentLog(I);
895 if (C->isNullValue() && /* FIXME: Verify correct */
896 (I->hasInternalLinkage() || I->hasWeakLinkage() ||
897 I->hasLinkOnceLinkage() ||
898 (I->hasExternalLinkage() && !I->hasSection()))) {
899 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
900 if (I->hasExternalLinkage()) {
901 O << "\t.globl " << name << '\n';
902 O << "\t.zerofill __DATA, __common, " << name << ", "
903 << Size << ", " << Align;
904 } else if (I->hasInternalLinkage()) {
905 SwitchToDataSection("\t.data", I);
906 O << TAI->getLCOMMDirective() << name << "," << Size << "," << Align;
908 SwitchToDataSection("\t.data", I);
909 O << ".comm " << name << "," << Size;
911 O << "\t\t" << TAI->getCommentString() << " '" << I->getName() << "'\n";
913 switch (I->getLinkage()) {
914 case GlobalValue::LinkOnceLinkage:
915 case GlobalValue::WeakLinkage:
916 O << "\t.globl " << name << '\n'
917 << "\t.weak_definition " << name << '\n';
918 SwitchToDataSection(".section __DATA,__datacoal_nt,coalesced", I);
920 case GlobalValue::AppendingLinkage:
921 // FIXME: appending linkage variables should go into a section of
922 // their name or something. For now, just emit them as external.
923 case GlobalValue::ExternalLinkage:
924 // If external or appending, declare as a global symbol
925 O << "\t.globl " << name << "\n";
927 case GlobalValue::InternalLinkage:
928 if (I->isConstant()) {
929 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
930 if (TAI->getCStringSection() && CVA && CVA->isCString()) {
931 SwitchToDataSection(TAI->getCStringSection(), I);
936 SwitchToDataSection("\t.data", I);
939 cerr << "Unknown linkage type!";
943 EmitAlignment(Align, I);
944 O << name << ":\t\t\t\t" << TAI->getCommentString() << " '"
945 << I->getName() << "'\n";
947 // If the initializer is a extern weak symbol, remember to emit the weak
949 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
950 if (GV->hasExternalWeakLinkage())
951 ExtWeakSymbols.insert(GV);
953 EmitGlobalConstant(C);
958 bool isPPC64 = TD->getPointerSizeInBits() == 64;
960 // Output stubs for dynamically-linked functions
961 if (TM.getRelocationModel() == Reloc::PIC_) {
962 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
964 SwitchToTextSection(".section __TEXT,__picsymbolstub1,symbol_stubs,"
965 "pure_instructions,32");
967 O << "L" << *i << "$stub:\n";
968 O << "\t.indirect_symbol " << *i << "\n";
970 O << "\tbcl 20,31,L0$" << *i << "\n";
971 O << "L0$" << *i << ":\n";
973 O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
976 O << "\tldu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
978 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
979 O << "\tmtctr r12\n";
981 SwitchToDataSection(".lazy_symbol_pointer");
982 O << "L" << *i << "$lazy_ptr:\n";
983 O << "\t.indirect_symbol " << *i << "\n";
985 O << "\t.quad dyld_stub_binding_helper\n";
987 O << "\t.long dyld_stub_binding_helper\n";
990 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
992 SwitchToTextSection(".section __TEXT,__symbol_stub1,symbol_stubs,"
993 "pure_instructions,16");
995 O << "L" << *i << "$stub:\n";
996 O << "\t.indirect_symbol " << *i << "\n";
997 O << "\tlis r11,ha16(L" << *i << "$lazy_ptr)\n";
999 O << "\tldu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
1001 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
1002 O << "\tmtctr r12\n";
1004 SwitchToDataSection(".lazy_symbol_pointer");
1005 O << "L" << *i << "$lazy_ptr:\n";
1006 O << "\t.indirect_symbol " << *i << "\n";
1008 O << "\t.quad dyld_stub_binding_helper\n";
1010 O << "\t.long dyld_stub_binding_helper\n";
1016 // Output stubs for external and common global variables.
1017 if (GVStubs.begin() != GVStubs.end()) {
1018 SwitchToDataSection(".non_lazy_symbol_pointer");
1019 for (std::set<std::string>::iterator I = GVStubs.begin(),
1020 E = GVStubs.end(); I != E; ++I) {
1021 O << "L" << *I << "$non_lazy_ptr:\n";
1022 O << "\t.indirect_symbol " << *I << "\n";
1024 O << "\t.quad\t0\n";
1026 O << "\t.long\t0\n";
1031 // Emit initial debug information.
1034 // Funny Darwin hack: This flag tells the linker that no global symbols
1035 // contain code that falls through to other global symbols (e.g. the obvious
1036 // implementation of multiple entry points). If this doesn't occur, the
1037 // linker can safely perform dead code stripping. Since LLVM never generates
1038 // code that does this, it is always safe to set.
1039 O << "\t.subsections_via_symbols\n";
1041 AsmPrinter::doFinalization(M);
1042 return false; // success
1047 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1048 /// for a MachineFunction to the given output stream, in a format that the
1049 /// Darwin assembler can deal with.
1051 FunctionPass *llvm::createPPCAsmPrinterPass(std::ostream &o,
1052 PPCTargetMachine &tm) {
1053 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1055 if (Subtarget->isDarwin()) {
1056 return new DarwinAsmPrinter(o, tm, tm.getTargetAsmInfo());
1058 return new LinuxAsmPrinter(o, tm, tm.getTargetAsmInfo());