1 //===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly --------=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to PowerPC assembly language. This printer is
12 // the output mechanism used by `llc'.
14 // Documentation at http://developer.apple.com/documentation/DeveloperTools/
15 // Reference/Assembler/ASMIntroduction/chapter_1_section_1.html
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "asmprinter"
21 #include "PPCPredicates.h"
22 #include "PPCTargetMachine.h"
23 #include "PPCSubtarget.h"
24 #include "llvm/Constants.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/Module.h"
27 #include "llvm/Assembly/Writer.h"
28 #include "llvm/CodeGen/AsmPrinter.h"
29 #include "llvm/CodeGen/DwarfWriter.h"
30 #include "llvm/CodeGen/MachineModuleInfo.h"
31 #include "llvm/CodeGen/MachineFunctionPass.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/Support/Mangler.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/Compiler.h"
39 #include "llvm/Target/TargetAsmInfo.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetOptions.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
48 STATISTIC(EmittedInsts, "Number of machine instrs printed");
51 struct VISIBILITY_HIDDEN PPCAsmPrinter : public AsmPrinter {
52 std::set<std::string> FnStubs, GVStubs;
53 const PPCSubtarget &Subtarget;
55 PPCAsmPrinter(std::ostream &O, TargetMachine &TM, const TargetAsmInfo *T)
56 : AsmPrinter(O, TM, T), Subtarget(TM.getSubtarget<PPCSubtarget>()) {
59 virtual const char *getPassName() const {
60 return "PowerPC Assembly Printer";
63 PPCTargetMachine &getTM() {
64 return static_cast<PPCTargetMachine&>(TM);
67 unsigned enumRegToMachineReg(unsigned enumReg) {
69 default: assert(0 && "Unhandled register!"); break;
70 case PPC::CR0: return 0;
71 case PPC::CR1: return 1;
72 case PPC::CR2: return 2;
73 case PPC::CR3: return 3;
74 case PPC::CR4: return 4;
75 case PPC::CR5: return 5;
76 case PPC::CR6: return 6;
77 case PPC::CR7: return 7;
82 /// printInstruction - This method is automatically generated by tablegen
83 /// from the instruction set description. This method returns true if the
84 /// machine instruction was sufficiently described to print it, otherwise it
86 bool printInstruction(const MachineInstr *MI);
88 void printMachineInstruction(const MachineInstr *MI);
89 void printOp(const MachineOperand &MO);
91 /// stripRegisterPrefix - This method strips the character prefix from a
92 /// register name so that only the number is left. Used by for linux asm.
93 const char *stripRegisterPrefix(const char *RegName) {
97 case 'v': return RegName + 1;
98 case 'c': if (RegName[1] == 'r') return RegName + 2;
104 /// printRegister - Print register according to target requirements.
106 void printRegister(const MachineOperand &MO, bool R0AsZero) {
107 unsigned RegNo = MO.getReg();
108 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
110 // If we should use 0 for R0.
111 if (R0AsZero && RegNo == PPC::R0) {
116 const char *RegName = TM.getRegisterInfo()->get(RegNo).AsmName;
117 // Linux assembler (Others?) does not take register mnemonics.
118 // FIXME - What about special registers used in mfspr/mtspr?
119 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
123 void printOperand(const MachineInstr *MI, unsigned OpNo) {
124 const MachineOperand &MO = MI->getOperand(OpNo);
125 if (MO.isRegister()) {
126 printRegister(MO, false);
127 } else if (MO.isImmediate()) {
134 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
135 unsigned AsmVariant, const char *ExtraCode);
136 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
137 unsigned AsmVariant, const char *ExtraCode);
140 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
141 char value = MI->getOperand(OpNo).getImm();
142 value = (value << (32-5)) >> (32-5);
145 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
146 unsigned char value = MI->getOperand(OpNo).getImm();
147 assert(value <= 31 && "Invalid u5imm argument!");
148 O << (unsigned int)value;
150 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
151 unsigned char value = MI->getOperand(OpNo).getImm();
152 assert(value <= 63 && "Invalid u6imm argument!");
153 O << (unsigned int)value;
155 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
156 O << (short)MI->getOperand(OpNo).getImm();
158 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
159 O << (unsigned short)MI->getOperand(OpNo).getImm();
161 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
162 if (MI->getOperand(OpNo).isImmediate()) {
163 O << (short)(MI->getOperand(OpNo).getImm()*4);
166 printOp(MI->getOperand(OpNo));
167 if (TM.getRelocationModel() == Reloc::PIC_)
168 O << "-\"L" << getFunctionNumber() << "$pb\")";
173 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
174 // Branches can take an immediate operand. This is used by the branch
175 // selection pass to print $+8, an eight byte displacement from the PC.
176 if (MI->getOperand(OpNo).isImmediate()) {
177 O << "$+" << MI->getOperand(OpNo).getImm()*4;
179 printOp(MI->getOperand(OpNo));
182 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
183 const MachineOperand &MO = MI->getOperand(OpNo);
184 if (TM.getRelocationModel() != Reloc::Static) {
185 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
186 GlobalValue *GV = MO.getGlobal();
187 if (((GV->isDeclaration() || GV->hasWeakLinkage() ||
188 GV->hasLinkOnceLinkage() || GV->hasCommonLinkage()))) {
189 // Dynamically-resolved functions need a stub for the function.
190 std::string Name = Mang->getValueName(GV);
191 FnStubs.insert(Name);
192 printSuffixedName(Name, "$stub");
193 if (GV->hasExternalWeakLinkage())
194 ExtWeakSymbols.insert(GV);
198 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
199 std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
200 FnStubs.insert(Name);
201 printSuffixedName(Name, "$stub");
206 printOp(MI->getOperand(OpNo));
208 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
209 O << (int)MI->getOperand(OpNo).getImm()*4;
211 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
212 O << "\"L" << getFunctionNumber() << "$pb\"\n";
213 O << "\"L" << getFunctionNumber() << "$pb\":";
215 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
216 if (MI->getOperand(OpNo).isImmediate()) {
217 printS16ImmOperand(MI, OpNo);
219 if (Subtarget.isDarwin()) O << "ha16(";
220 printOp(MI->getOperand(OpNo));
221 if (TM.getRelocationModel() == Reloc::PIC_)
222 O << "-\"L" << getFunctionNumber() << "$pb\"";
223 if (Subtarget.isDarwin())
229 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
230 if (MI->getOperand(OpNo).isImmediate()) {
231 printS16ImmOperand(MI, OpNo);
233 if (Subtarget.isDarwin()) O << "lo16(";
234 printOp(MI->getOperand(OpNo));
235 if (TM.getRelocationModel() == Reloc::PIC_)
236 O << "-\"L" << getFunctionNumber() << "$pb\"";
237 if (Subtarget.isDarwin())
243 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
244 unsigned CCReg = MI->getOperand(OpNo).getReg();
245 unsigned RegNo = enumRegToMachineReg(CCReg);
246 O << (0x80 >> RegNo);
248 // The new addressing mode printers.
249 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
250 printSymbolLo(MI, OpNo);
252 if (MI->getOperand(OpNo+1).isRegister() &&
253 MI->getOperand(OpNo+1).getReg() == PPC::R0)
256 printOperand(MI, OpNo+1);
259 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
260 if (MI->getOperand(OpNo).isImmediate())
261 printS16X4ImmOperand(MI, OpNo);
263 printSymbolLo(MI, OpNo);
265 if (MI->getOperand(OpNo+1).isRegister() &&
266 MI->getOperand(OpNo+1).getReg() == PPC::R0)
269 printOperand(MI, OpNo+1);
273 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
274 // When used as the base register, r0 reads constant zero rather than
275 // the value contained in the register. For this reason, the darwin
276 // assembler requires that we print r0 as 0 (no r) when used as the base.
277 const MachineOperand &MO = MI->getOperand(OpNo);
278 printRegister(MO, true);
280 printOperand(MI, OpNo+1);
283 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
284 const char *Modifier);
286 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
287 virtual bool doFinalization(Module &M) = 0;
289 virtual void EmitExternalGlobal(const GlobalVariable *GV);
292 /// LinuxAsmPrinter - PowerPC assembly printer, customized for Linux
293 struct VISIBILITY_HIDDEN LinuxAsmPrinter : public PPCAsmPrinter {
297 LinuxAsmPrinter(std::ostream &O, PPCTargetMachine &TM,
298 const TargetAsmInfo *T)
299 : PPCAsmPrinter(O, TM, T), DW(O, this, T) {
302 virtual const char *getPassName() const {
303 return "Linux PPC Assembly Printer";
306 bool runOnMachineFunction(MachineFunction &F);
307 bool doInitialization(Module &M);
308 bool doFinalization(Module &M);
310 void getAnalysisUsage(AnalysisUsage &AU) const {
311 AU.setPreservesAll();
312 AU.addRequired<MachineModuleInfo>();
313 PPCAsmPrinter::getAnalysisUsage(AU);
316 /// getSectionForFunction - Return the section that we should emit the
317 /// specified function body into.
318 virtual std::string getSectionForFunction(const Function &F) const;
321 /// DarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac OS
323 struct VISIBILITY_HIDDEN DarwinAsmPrinter : public PPCAsmPrinter {
326 MachineModuleInfo *MMI;
328 DarwinAsmPrinter(std::ostream &O, PPCTargetMachine &TM,
329 const TargetAsmInfo *T)
330 : PPCAsmPrinter(O, TM, T), DW(O, this, T), MMI(0) {
333 virtual const char *getPassName() const {
334 return "Darwin PPC Assembly Printer";
337 bool runOnMachineFunction(MachineFunction &F);
338 bool doInitialization(Module &M);
339 bool doFinalization(Module &M);
341 void getAnalysisUsage(AnalysisUsage &AU) const {
342 AU.setPreservesAll();
343 AU.addRequired<MachineModuleInfo>();
344 PPCAsmPrinter::getAnalysisUsage(AU);
347 /// getSectionForFunction - Return the section that we should emit the
348 /// specified function body into.
349 virtual std::string getSectionForFunction(const Function &F) const;
351 } // end of anonymous namespace
353 // Include the auto-generated portion of the assembly writer
354 #include "PPCGenAsmWriter.inc"
356 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
357 switch (MO.getType()) {
358 case MachineOperand::MO_Immediate:
359 cerr << "printOp() does not handle immediate values\n";
363 case MachineOperand::MO_MachineBasicBlock:
364 printBasicBlockLabel(MO.getMBB());
366 case MachineOperand::MO_JumpTableIndex:
367 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
368 << '_' << MO.getIndex();
369 // FIXME: PIC relocation model
371 case MachineOperand::MO_ConstantPoolIndex:
372 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
373 << '_' << MO.getIndex();
375 case MachineOperand::MO_ExternalSymbol:
376 // Computing the address of an external symbol, not calling it.
377 if (TM.getRelocationModel() != Reloc::Static) {
378 std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
379 GVStubs.insert(Name);
380 printSuffixedName(Name, "$non_lazy_ptr");
383 O << TAI->getGlobalPrefix() << MO.getSymbolName();
385 case MachineOperand::MO_GlobalAddress: {
386 // Computing the address of a global symbol, not calling it.
387 GlobalValue *GV = MO.getGlobal();
388 std::string Name = Mang->getValueName(GV);
390 // External or weakly linked global variables need non-lazily-resolved stubs
391 if (TM.getRelocationModel() != Reloc::Static) {
392 if (((GV->isDeclaration() || GV->hasWeakLinkage() ||
393 GV->hasLinkOnceLinkage() || GV->hasCommonLinkage()))) {
394 GVStubs.insert(Name);
395 printSuffixedName(Name, "$non_lazy_ptr");
396 if (GV->hasExternalWeakLinkage())
397 ExtWeakSymbols.insert(GV);
403 if (MO.getOffset() > 0)
404 O << "+" << MO.getOffset();
405 else if (MO.getOffset() < 0)
408 if (GV->hasExternalWeakLinkage())
409 ExtWeakSymbols.insert(GV);
414 O << "<unknown operand type: " << MO.getType() << ">";
419 /// EmitExternalGlobal - In this case we need to use the indirect symbol.
421 void PPCAsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
422 std::string Name = getGlobalLinkName(GV);
423 if (TM.getRelocationModel() != Reloc::Static) {
424 GVStubs.insert(Name);
425 printSuffixedName(Name, "$non_lazy_ptr");
431 /// PrintAsmOperand - Print out an operand for an inline asm expression.
433 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
435 const char *ExtraCode) {
436 // Does this asm operand have a single letter operand modifier?
437 if (ExtraCode && ExtraCode[0]) {
438 if (ExtraCode[1] != 0) return true; // Unknown modifier.
440 switch (ExtraCode[0]) {
441 default: return true; // Unknown modifier.
442 case 'c': // Don't print "$" before a global var name or constant.
443 // PPC never has a prefix.
444 printOperand(MI, OpNo);
446 case 'L': // Write second word of DImode reference.
447 // Verify that this operand has two consecutive registers.
448 if (!MI->getOperand(OpNo).isRegister() ||
449 OpNo+1 == MI->getNumOperands() ||
450 !MI->getOperand(OpNo+1).isRegister())
452 ++OpNo; // Return the high-part.
455 // Write 'i' if an integer constant, otherwise nothing. Used to print
457 if (MI->getOperand(OpNo).isImmediate())
463 printOperand(MI, OpNo);
467 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
469 const char *ExtraCode) {
470 if (ExtraCode && ExtraCode[0])
471 return true; // Unknown modifier.
472 if (MI->getOperand(OpNo).isRegister())
473 printMemRegReg(MI, OpNo);
475 printMemRegImm(MI, OpNo);
479 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
480 const char *Modifier) {
481 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
482 unsigned Code = MI->getOperand(OpNo).getImm();
483 if (!strcmp(Modifier, "cc")) {
484 switch ((PPC::Predicate)Code) {
485 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
486 case PPC::PRED_LT: O << "lt"; return;
487 case PPC::PRED_LE: O << "le"; return;
488 case PPC::PRED_EQ: O << "eq"; return;
489 case PPC::PRED_GE: O << "ge"; return;
490 case PPC::PRED_GT: O << "gt"; return;
491 case PPC::PRED_NE: O << "ne"; return;
492 case PPC::PRED_UN: O << "un"; return;
493 case PPC::PRED_NU: O << "nu"; return;
497 assert(!strcmp(Modifier, "reg") &&
498 "Need to specify 'cc' or 'reg' as predicate op modifier!");
499 // Don't print the register for 'always'.
500 if (Code == PPC::PRED_ALWAYS) return;
501 printOperand(MI, OpNo+1);
506 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
507 /// the current output stream.
509 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
512 // Check for slwi/srwi mnemonics.
513 if (MI->getOpcode() == PPC::RLWINM) {
514 bool FoundMnemonic = false;
515 unsigned char SH = MI->getOperand(2).getImm();
516 unsigned char MB = MI->getOperand(3).getImm();
517 unsigned char ME = MI->getOperand(4).getImm();
518 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
519 O << "\tslwi "; FoundMnemonic = true;
521 if (SH <= 31 && MB == (32-SH) && ME == 31) {
522 O << "\tsrwi "; FoundMnemonic = true;
529 O << ", " << (unsigned int)SH << "\n";
532 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
533 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
541 } else if (MI->getOpcode() == PPC::RLDICR) {
542 unsigned char SH = MI->getOperand(2).getImm();
543 unsigned char ME = MI->getOperand(3).getImm();
544 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
550 O << ", " << (unsigned int)SH << "\n";
555 if (printInstruction(MI))
556 return; // Printer was automatically generated
558 assert(0 && "Unhandled instruction in asm writer!");
563 /// runOnMachineFunction - This uses the printMachineInstruction()
564 /// method to print assembly for each instruction.
566 bool LinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
567 DW.SetModuleInfo(&getAnalysis<MachineModuleInfo>());
569 SetupMachineFunction(MF);
572 // Print out constants referenced by the function
573 EmitConstantPool(MF.getConstantPool());
575 // Print out labels for the function.
576 const Function *F = MF.getFunction();
577 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
579 switch (F->getLinkage()) {
580 default: assert(0 && "Unknown linkage type!");
581 case Function::InternalLinkage: // Symbols default to internal.
583 case Function::ExternalLinkage:
584 O << "\t.global\t" << CurrentFnName << '\n'
585 << "\t.type\t" << CurrentFnName << ", @function\n";
587 case Function::WeakLinkage:
588 case Function::LinkOnceLinkage:
589 O << "\t.global\t" << CurrentFnName << '\n';
590 O << "\t.weak\t" << CurrentFnName << '\n';
594 if (F->hasHiddenVisibility())
595 if (const char *Directive = TAI->getHiddenDirective())
596 O << Directive << CurrentFnName << "\n";
599 O << CurrentFnName << ":\n";
601 // Emit pre-function debug information.
602 DW.BeginFunction(&MF);
604 // Print out code for the function.
605 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
607 // Print a label for the basic block.
608 if (I != MF.begin()) {
609 printBasicBlockLabel(I, true, true);
612 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
614 // Print the assembly for the instruction.
615 printMachineInstruction(II);
619 O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << "\n";
621 // Print out jump tables referenced by the function.
622 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
624 // Emit post-function debug information.
627 // We didn't modify anything.
631 bool LinuxAsmPrinter::doInitialization(Module &M) {
632 bool Result = AsmPrinter::doInitialization(M);
634 // GNU as handles section names wrapped in quotes
635 Mang->setUseQuotes(true);
637 SwitchToTextSection(TAI->getTextSection());
639 // Emit initial debug information.
644 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
645 /// Don't print things like \n or \0.
646 static void PrintUnmangledNameSafely(const Value *V, std::ostream &OS) {
647 for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
653 bool LinuxAsmPrinter::doFinalization(Module &M) {
654 const TargetData *TD = TM.getTargetData();
656 // Print out module-level global variables here.
657 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
659 if (!I->hasInitializer()) continue; // External global require no code
661 // Check to see if this is a special global used by LLVM, if so, emit it.
662 if (EmitSpecialLLVMGlobal(I))
665 std::string name = Mang->getValueName(I);
667 if (I->hasHiddenVisibility())
668 if (const char *Directive = TAI->getHiddenDirective())
669 O << Directive << name << "\n";
671 Constant *C = I->getInitializer();
672 unsigned Size = TD->getABITypeSize(C->getType());
673 unsigned Align = TD->getPreferredAlignmentLog(I);
675 if (C->isNullValue() && /* FIXME: Verify correct */
676 !I->hasSection() && (I->hasCommonLinkage() ||
677 I->hasInternalLinkage() || I->hasWeakLinkage() ||
678 I->hasLinkOnceLinkage() || I->hasExternalLinkage())) {
679 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
680 if (I->hasExternalLinkage()) {
681 O << "\t.global " << name << '\n';
682 O << "\t.type " << name << ", @object\n";
683 if (TAI->getBSSSection())
684 SwitchToDataSection(TAI->getBSSSection(), I);
686 O << "\t.zero " << Size << "\n";
687 } else if (I->hasInternalLinkage()) {
688 SwitchToDataSection("\t.data", I);
689 O << TAI->getLCOMMDirective() << name << "," << Size;
691 SwitchToDataSection("\t.data", I);
692 O << ".comm " << name << "," << Size;
694 O << "\t\t" << TAI->getCommentString() << " '";
695 PrintUnmangledNameSafely(I, O);
698 switch (I->getLinkage()) {
699 case GlobalValue::LinkOnceLinkage:
700 case GlobalValue::WeakLinkage:
701 case GlobalValue::CommonLinkage:
702 O << "\t.global " << name << '\n'
703 << "\t.type " << name << ", @object\n"
704 << "\t.weak " << name << '\n';
705 SwitchToDataSection("\t.data", I);
707 case GlobalValue::AppendingLinkage:
708 // FIXME: appending linkage variables should go into a section of
709 // their name or something. For now, just emit them as external.
710 case GlobalValue::ExternalLinkage:
711 // If external or appending, declare as a global symbol
712 O << "\t.global " << name << "\n"
713 << "\t.type " << name << ", @object\n";
715 case GlobalValue::InternalLinkage:
716 if (I->isConstant()) {
717 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
718 if (TAI->getCStringSection() && CVA && CVA->isCString()) {
719 SwitchToDataSection(TAI->getCStringSection(), I);
724 // FIXME: special handling for ".ctors" & ".dtors" sections
725 if (I->hasSection() &&
726 (I->getSection() == ".ctors" ||
727 I->getSection() == ".dtors")) {
728 std::string SectionName = ".section " + I->getSection()
729 + ",\"aw\",@progbits";
730 SwitchToDataSection(SectionName.c_str());
732 if (I->isConstant() && TAI->getReadOnlySection())
733 SwitchToDataSection(TAI->getReadOnlySection(), I);
735 SwitchToDataSection(TAI->getDataSection(), I);
739 cerr << "Unknown linkage type!";
743 EmitAlignment(Align, I);
744 O << name << ":\t\t\t\t" << TAI->getCommentString() << " '";
745 PrintUnmangledNameSafely(I, O);
748 // If the initializer is a extern weak symbol, remember to emit the weak
750 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
751 if (GV->hasExternalWeakLinkage())
752 ExtWeakSymbols.insert(GV);
754 EmitGlobalConstant(C);
761 // Emit initial debug information.
764 return AsmPrinter::doFinalization(M);
767 std::string LinuxAsmPrinter::getSectionForFunction(const Function &F) const {
768 switch (F.getLinkage()) {
769 default: assert(0 && "Unknown linkage type!");
770 case Function::ExternalLinkage:
771 case Function::InternalLinkage: return TAI->getTextSection();
772 case Function::WeakLinkage:
773 case Function::LinkOnceLinkage:
778 std::string DarwinAsmPrinter::getSectionForFunction(const Function &F) const {
779 switch (F.getLinkage()) {
780 default: assert(0 && "Unknown linkage type!");
781 case Function::ExternalLinkage:
782 case Function::InternalLinkage: return TAI->getTextSection();
783 case Function::WeakLinkage:
784 case Function::LinkOnceLinkage:
785 return "\t.section __TEXT,__textcoal_nt,coalesced,pure_instructions";
789 /// runOnMachineFunction - This uses the printMachineInstruction()
790 /// method to print assembly for each instruction.
792 bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
793 // We need this for Personality functions.
794 MMI = &getAnalysis<MachineModuleInfo>();
795 DW.SetModuleInfo(MMI);
797 SetupMachineFunction(MF);
800 // Print out constants referenced by the function
801 EmitConstantPool(MF.getConstantPool());
803 // Print out labels for the function.
804 const Function *F = MF.getFunction();
805 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
807 switch (F->getLinkage()) {
808 default: assert(0 && "Unknown linkage type!");
809 case Function::InternalLinkage: // Symbols default to internal.
811 case Function::ExternalLinkage:
812 O << "\t.globl\t" << CurrentFnName << "\n";
814 case Function::WeakLinkage:
815 case Function::LinkOnceLinkage:
816 O << "\t.globl\t" << CurrentFnName << "\n";
817 O << "\t.weak_definition\t" << CurrentFnName << "\n";
821 if (F->hasHiddenVisibility())
822 if (const char *Directive = TAI->getHiddenDirective())
823 O << Directive << CurrentFnName << "\n";
825 EmitAlignment(OptimizeForSize ? 2 : 4, F);
826 O << CurrentFnName << ":\n";
828 // Emit pre-function debug information.
829 DW.BeginFunction(&MF);
831 // If the function is empty, then we need to emit *something*. Otherwise, the
832 // function's label might be associated with something that it wasn't meant to
833 // be associated with. We emit a noop in this situation.
834 MachineFunction::iterator I = MF.begin();
836 if (++I == MF.end() && MF.front().empty())
839 // Print out code for the function.
840 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
842 // Print a label for the basic block.
843 if (I != MF.begin()) {
844 printBasicBlockLabel(I, true, true);
847 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
849 // Print the assembly for the instruction.
850 printMachineInstruction(II);
854 // Print out jump tables referenced by the function.
855 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
857 // Emit post-function debug information.
860 // We didn't modify anything.
865 bool DarwinAsmPrinter::doInitialization(Module &M) {
866 static const char *const CPUDirectives[] = {
878 unsigned Directive = Subtarget.getDarwinDirective();
879 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
880 Directive = PPC::DIR_970;
881 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
882 Directive = PPC::DIR_7400;
883 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
884 Directive = PPC::DIR_64;
885 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
886 O << "\t.machine " << CPUDirectives[Directive] << "\n";
888 bool Result = AsmPrinter::doInitialization(M);
890 // Darwin wants symbols to be quoted if they have complex names.
891 Mang->setUseQuotes(true);
893 // Prime text sections so they are adjacent. This reduces the likelihood a
894 // large data or debug section causes a branch to exceed 16M limit.
895 SwitchToTextSection("\t.section __TEXT,__textcoal_nt,coalesced,"
896 "pure_instructions");
897 if (TM.getRelocationModel() == Reloc::PIC_) {
898 SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
899 "pure_instructions,32");
900 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
901 SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
902 "pure_instructions,16");
904 SwitchToTextSection(TAI->getTextSection());
906 // Emit initial debug information.
911 bool DarwinAsmPrinter::doFinalization(Module &M) {
912 const TargetData *TD = TM.getTargetData();
914 // Print out module-level global variables here.
915 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
917 if (!I->hasInitializer()) continue; // External global require no code
919 // Check to see if this is a special global used by LLVM, if so, emit it.
920 if (EmitSpecialLLVMGlobal(I)) {
921 if (TM.getRelocationModel() == Reloc::Static) {
922 if (I->getName() == "llvm.global_ctors")
923 O << ".reference .constructors_used\n";
924 else if (I->getName() == "llvm.global_dtors")
925 O << ".reference .destructors_used\n";
930 std::string name = Mang->getValueName(I);
932 if (I->hasHiddenVisibility())
933 if (const char *Directive = TAI->getHiddenDirective())
934 O << Directive << name << "\n";
936 Constant *C = I->getInitializer();
937 const Type *Type = C->getType();
938 unsigned Size = TD->getABITypeSize(Type);
939 unsigned Align = TD->getPreferredAlignmentLog(I);
941 if (C->isNullValue() && /* FIXME: Verify correct */
942 !I->hasSection() && (I->hasCommonLinkage() ||
943 I->hasInternalLinkage() || I->hasWeakLinkage() ||
944 I->hasLinkOnceLinkage() || I->hasExternalLinkage())) {
945 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
946 if (I->hasExternalLinkage()) {
947 O << "\t.globl " << name << '\n';
948 O << "\t.zerofill __DATA, __common, " << name << ", "
949 << Size << ", " << Align;
950 } else if (I->hasInternalLinkage()) {
951 SwitchToDataSection("\t.data", I);
952 O << TAI->getLCOMMDirective() << name << "," << Size << "," << Align;
953 } else if (!I->hasCommonLinkage()) {
954 O << "\t.globl " << name << "\n"
955 << TAI->getWeakDefDirective() << name << "\n";
956 SwitchToDataSection("\t.section __DATA,__datacoal_nt,coalesced", I);
957 EmitAlignment(Align, I);
958 O << name << ":\t\t\t\t" << TAI->getCommentString() << " ";
959 PrintUnmangledNameSafely(I, O);
961 EmitGlobalConstant(C);
964 SwitchToDataSection("\t.data", I);
965 O << ".comm " << name << "," << Size;
966 // Darwin 9 and above support aligned common data.
967 if (Subtarget.isDarwin9())
970 O << "\t\t" << TAI->getCommentString() << " '";
971 PrintUnmangledNameSafely(I, O);
974 switch (I->getLinkage()) {
975 case GlobalValue::LinkOnceLinkage:
976 case GlobalValue::WeakLinkage:
977 case GlobalValue::CommonLinkage:
978 O << "\t.globl " << name << '\n'
979 << "\t.weak_definition " << name << '\n';
980 SwitchToDataSection("\t.section __DATA,__datacoal_nt,coalesced", I);
982 case GlobalValue::AppendingLinkage:
983 // FIXME: appending linkage variables should go into a section of
984 // their name or something. For now, just emit them as external.
985 case GlobalValue::ExternalLinkage:
986 // If external or appending, declare as a global symbol
987 O << "\t.globl " << name << "\n";
989 case GlobalValue::InternalLinkage:
990 if (I->isConstant()) {
991 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
992 if (TAI->getCStringSection() && CVA && CVA->isCString()) {
993 SwitchToDataSection(TAI->getCStringSection(), I);
997 if (I->hasSection()) {
998 // Honor all section names on Darwin; ObjC uses this
999 std::string SectionName = ".section " + I->getSection();
1000 SwitchToDataSection(SectionName.c_str());
1001 } else if (!I->isConstant())
1002 SwitchToDataSection(TAI->getDataSection(), I);
1005 bool HasReloc = C->ContainsRelocations();
1007 TM.getRelocationModel() != Reloc::Static)
1008 SwitchToDataSection("\t.const_data\n");
1009 else if (!HasReloc && Size == 4 &&
1010 TAI->getFourByteConstantSection())
1011 SwitchToDataSection(TAI->getFourByteConstantSection(), I);
1012 else if (!HasReloc && Size == 8 &&
1013 TAI->getEightByteConstantSection())
1014 SwitchToDataSection(TAI->getEightByteConstantSection(), I);
1015 else if (!HasReloc && Size == 16 &&
1016 TAI->getSixteenByteConstantSection())
1017 SwitchToDataSection(TAI->getSixteenByteConstantSection(), I);
1018 else if (TAI->getReadOnlySection())
1019 SwitchToDataSection(TAI->getReadOnlySection(), I);
1021 SwitchToDataSection(TAI->getDataSection(), I);
1025 cerr << "Unknown linkage type!";
1029 EmitAlignment(Align, I);
1030 O << name << ":\t\t\t\t" << TAI->getCommentString() << " '";
1031 PrintUnmangledNameSafely(I, O);
1034 // If the initializer is a extern weak symbol, remember to emit the weak
1036 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1037 if (GV->hasExternalWeakLinkage())
1038 ExtWeakSymbols.insert(GV);
1040 EmitGlobalConstant(C);
1045 bool isPPC64 = TD->getPointerSizeInBits() == 64;
1047 // Output stubs for dynamically-linked functions
1048 if (TM.getRelocationModel() == Reloc::PIC_) {
1049 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
1051 SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
1052 "pure_instructions,32");
1055 std::string L0p = (p[0]=='\"') ? "\"L0$" + p.substr(1) : "L0$" + p ;
1056 printSuffixedName(p, "$stub");
1058 O << "\t.indirect_symbol " << *i << "\n";
1060 O << "\tbcl 20,31," << L0p << "\n";
1062 O << "\tmflr r11\n";
1063 O << "\taddis r11,r11,ha16(";
1064 printSuffixedName(p, "$lazy_ptr");
1065 O << "-" << L0p << ")\n";
1068 O << "\tldu r12,lo16(";
1070 O << "\tlwzu r12,lo16(";
1071 printSuffixedName(p, "$lazy_ptr");
1072 O << "-" << L0p << ")(r11)\n";
1073 O << "\tmtctr r12\n";
1075 SwitchToDataSection(".lazy_symbol_pointer");
1076 printSuffixedName(p, "$lazy_ptr");
1078 O << "\t.indirect_symbol " << *i << "\n";
1080 O << "\t.quad dyld_stub_binding_helper\n";
1082 O << "\t.long dyld_stub_binding_helper\n";
1085 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
1087 SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
1088 "pure_instructions,16");
1091 printSuffixedName(p, "$stub");
1093 O << "\t.indirect_symbol " << *i << "\n";
1094 O << "\tlis r11,ha16(";
1095 printSuffixedName(p, "$lazy_ptr");
1098 O << "\tldu r12,lo16(";
1100 O << "\tlwzu r12,lo16(";
1101 printSuffixedName(p, "$lazy_ptr");
1103 O << "\tmtctr r12\n";
1105 SwitchToDataSection(".lazy_symbol_pointer");
1106 printSuffixedName(p, "$lazy_ptr");
1108 O << "\t.indirect_symbol " << *i << "\n";
1110 O << "\t.quad dyld_stub_binding_helper\n";
1112 O << "\t.long dyld_stub_binding_helper\n";
1118 if (TAI->doesSupportExceptionHandling() && MMI) {
1119 // Add the (possibly multiple) personalities to the set of global values.
1120 // Only referenced functions get into the Personalities list.
1121 const std::vector<Function *>& Personalities = MMI->getPersonalities();
1123 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1124 E = Personalities.end(); I != E; ++I)
1125 if (*I) GVStubs.insert("_" + (*I)->getName());
1128 // Output stubs for external and common global variables.
1129 if (!GVStubs.empty()) {
1130 SwitchToDataSection(".non_lazy_symbol_pointer");
1131 for (std::set<std::string>::iterator I = GVStubs.begin(),
1132 E = GVStubs.end(); I != E; ++I) {
1134 printSuffixedName(p, "$non_lazy_ptr");
1136 O << "\t.indirect_symbol " << *I << "\n";
1138 O << "\t.quad\t0\n";
1140 O << "\t.long\t0\n";
1145 // Emit initial debug information.
1148 // Funny Darwin hack: This flag tells the linker that no global symbols
1149 // contain code that falls through to other global symbols (e.g. the obvious
1150 // implementation of multiple entry points). If this doesn't occur, the
1151 // linker can safely perform dead code stripping. Since LLVM never generates
1152 // code that does this, it is always safe to set.
1153 O << "\t.subsections_via_symbols\n";
1155 return AsmPrinter::doFinalization(M);
1160 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1161 /// for a MachineFunction to the given output stream, in a format that the
1162 /// Darwin assembler can deal with.
1164 FunctionPass *llvm::createPPCAsmPrinterPass(std::ostream &o,
1165 PPCTargetMachine &tm) {
1166 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1168 if (Subtarget->isDarwin()) {
1169 return new DarwinAsmPrinter(o, tm, tm.getTargetAsmInfo());
1171 return new LinuxAsmPrinter(o, tm, tm.getTargetAsmInfo());