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/Support/raw_ostream.h"
40 #include "llvm/Target/TargetAsmInfo.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetInstrInfo.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/StringSet.h"
49 STATISTIC(EmittedInsts, "Number of machine instrs printed");
52 class VISIBILITY_HIDDEN PPCAsmPrinter : public AsmPrinter {
54 StringSet<> FnStubs, GVStubs, HiddenGVStubs;
55 const PPCSubtarget &Subtarget;
57 explicit PPCAsmPrinter(raw_ostream &O, TargetMachine &TM,
58 const TargetAsmInfo *T, CodeGenOpt::Level OL,
60 : AsmPrinter(O, TM, T, OL, V),
61 Subtarget(TM.getSubtarget<PPCSubtarget>()) {}
63 virtual const char *getPassName() const {
64 return "PowerPC Assembly Printer";
67 PPCTargetMachine &getTM() {
68 return static_cast<PPCTargetMachine&>(TM);
71 unsigned enumRegToMachineReg(unsigned enumReg) {
73 default: assert(0 && "Unhandled register!"); break;
74 case PPC::CR0: return 0;
75 case PPC::CR1: return 1;
76 case PPC::CR2: return 2;
77 case PPC::CR3: return 3;
78 case PPC::CR4: return 4;
79 case PPC::CR5: return 5;
80 case PPC::CR6: return 6;
81 case PPC::CR7: return 7;
86 /// printInstruction - This method is automatically generated by tablegen
87 /// from the instruction set description. This method returns true if the
88 /// machine instruction was sufficiently described to print it, otherwise it
90 bool printInstruction(const MachineInstr *MI);
92 void printMachineInstruction(const MachineInstr *MI);
93 void printOp(const MachineOperand &MO);
95 /// stripRegisterPrefix - This method strips the character prefix from a
96 /// register name so that only the number is left. Used by for linux asm.
97 const char *stripRegisterPrefix(const char *RegName) {
101 case 'v': return RegName + 1;
102 case 'c': if (RegName[1] == 'r') return RegName + 2;
108 /// printRegister - Print register according to target requirements.
110 void printRegister(const MachineOperand &MO, bool R0AsZero) {
111 unsigned RegNo = MO.getReg();
112 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
114 // If we should use 0 for R0.
115 if (R0AsZero && RegNo == PPC::R0) {
120 const char *RegName = TM.getRegisterInfo()->get(RegNo).AsmName;
121 // Linux assembler (Others?) does not take register mnemonics.
122 // FIXME - What about special registers used in mfspr/mtspr?
123 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
127 void printOperand(const MachineInstr *MI, unsigned OpNo) {
128 const MachineOperand &MO = MI->getOperand(OpNo);
130 printRegister(MO, false);
131 } else if (MO.isImm()) {
138 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
139 unsigned AsmVariant, const char *ExtraCode);
140 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
141 unsigned AsmVariant, const char *ExtraCode);
144 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
145 char value = MI->getOperand(OpNo).getImm();
146 value = (value << (32-5)) >> (32-5);
149 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
150 unsigned char value = MI->getOperand(OpNo).getImm();
151 assert(value <= 31 && "Invalid u5imm argument!");
152 O << (unsigned int)value;
154 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
155 unsigned char value = MI->getOperand(OpNo).getImm();
156 assert(value <= 63 && "Invalid u6imm argument!");
157 O << (unsigned int)value;
159 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
160 O << (short)MI->getOperand(OpNo).getImm();
162 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
163 O << (unsigned short)MI->getOperand(OpNo).getImm();
165 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
166 if (MI->getOperand(OpNo).isImm()) {
167 O << (short)(MI->getOperand(OpNo).getImm()*4);
170 printOp(MI->getOperand(OpNo));
171 if (TM.getRelocationModel() == Reloc::PIC_)
172 O << "-\"L" << getFunctionNumber() << "$pb\")";
177 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
178 // Branches can take an immediate operand. This is used by the branch
179 // selection pass to print $+8, an eight byte displacement from the PC.
180 if (MI->getOperand(OpNo).isImm()) {
181 O << "$+" << MI->getOperand(OpNo).getImm()*4;
183 printOp(MI->getOperand(OpNo));
186 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
187 const MachineOperand &MO = MI->getOperand(OpNo);
188 if (TM.getRelocationModel() != Reloc::Static) {
189 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
190 GlobalValue *GV = MO.getGlobal();
191 if (((GV->isDeclaration() || GV->hasWeakLinkage() ||
192 GV->hasLinkOnceLinkage() || GV->hasCommonLinkage()))) {
193 // Dynamically-resolved functions need a stub for the function.
194 std::string Name = Mang->getValueName(GV);
195 FnStubs.insert(Name);
196 printSuffixedName(Name, "$stub");
197 if (GV->hasExternalWeakLinkage())
198 ExtWeakSymbols.insert(GV);
202 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
203 std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
204 FnStubs.insert(Name);
205 printSuffixedName(Name, "$stub");
210 printOp(MI->getOperand(OpNo));
212 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
213 O << (int)MI->getOperand(OpNo).getImm()*4;
215 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
216 O << "\"L" << getFunctionNumber() << "$pb\"\n";
217 O << "\"L" << getFunctionNumber() << "$pb\":";
219 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
220 if (MI->getOperand(OpNo).isImm()) {
221 printS16ImmOperand(MI, OpNo);
223 if (Subtarget.isDarwin()) O << "ha16(";
224 printOp(MI->getOperand(OpNo));
225 if (TM.getRelocationModel() == Reloc::PIC_)
226 O << "-\"L" << getFunctionNumber() << "$pb\"";
227 if (Subtarget.isDarwin())
233 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
234 if (MI->getOperand(OpNo).isImm()) {
235 printS16ImmOperand(MI, OpNo);
237 if (Subtarget.isDarwin()) O << "lo16(";
238 printOp(MI->getOperand(OpNo));
239 if (TM.getRelocationModel() == Reloc::PIC_)
240 O << "-\"L" << getFunctionNumber() << "$pb\"";
241 if (Subtarget.isDarwin())
247 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
248 unsigned CCReg = MI->getOperand(OpNo).getReg();
249 unsigned RegNo = enumRegToMachineReg(CCReg);
250 O << (0x80 >> RegNo);
252 // The new addressing mode printers.
253 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
254 printSymbolLo(MI, OpNo);
256 if (MI->getOperand(OpNo+1).isReg() &&
257 MI->getOperand(OpNo+1).getReg() == PPC::R0)
260 printOperand(MI, OpNo+1);
263 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
264 if (MI->getOperand(OpNo).isImm())
265 printS16X4ImmOperand(MI, OpNo);
267 printSymbolLo(MI, OpNo);
269 if (MI->getOperand(OpNo+1).isReg() &&
270 MI->getOperand(OpNo+1).getReg() == PPC::R0)
273 printOperand(MI, OpNo+1);
277 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
278 // When used as the base register, r0 reads constant zero rather than
279 // the value contained in the register. For this reason, the darwin
280 // assembler requires that we print r0 as 0 (no r) when used as the base.
281 const MachineOperand &MO = MI->getOperand(OpNo);
282 printRegister(MO, true);
284 printOperand(MI, OpNo+1);
287 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
288 const char *Modifier);
290 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
291 virtual bool doFinalization(Module &M) = 0;
293 virtual void EmitExternalGlobal(const GlobalVariable *GV);
296 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
297 class VISIBILITY_HIDDEN PPCLinuxAsmPrinter : public PPCAsmPrinter {
299 MachineModuleInfo *MMI;
301 explicit PPCLinuxAsmPrinter(raw_ostream &O, PPCTargetMachine &TM,
302 const TargetAsmInfo *T, CodeGenOpt::Level OL,
304 : PPCAsmPrinter(O, TM, T, OL, V), DW(0), MMI(0) {}
306 virtual const char *getPassName() const {
307 return "Linux PPC Assembly Printer";
310 bool runOnMachineFunction(MachineFunction &F);
311 bool doInitialization(Module &M);
312 bool doFinalization(Module &M);
314 void getAnalysisUsage(AnalysisUsage &AU) const {
315 AU.setPreservesAll();
316 AU.addRequired<MachineModuleInfo>();
317 AU.addRequired<DwarfWriter>();
318 PPCAsmPrinter::getAnalysisUsage(AU);
321 void printModuleLevelGV(const GlobalVariable* GVar);
324 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
326 class VISIBILITY_HIDDEN PPCDarwinAsmPrinter : public PPCAsmPrinter {
328 MachineModuleInfo *MMI;
331 explicit PPCDarwinAsmPrinter(raw_ostream &O, PPCTargetMachine &TM,
332 const TargetAsmInfo *T, CodeGenOpt::Level OL,
334 : PPCAsmPrinter(O, TM, T, OL, V), DW(0), MMI(0), OS(O) {}
336 virtual const char *getPassName() const {
337 return "Darwin PPC Assembly Printer";
340 bool runOnMachineFunction(MachineFunction &F);
341 bool doInitialization(Module &M);
342 bool doFinalization(Module &M);
344 void getAnalysisUsage(AnalysisUsage &AU) const {
345 AU.setPreservesAll();
346 AU.addRequired<MachineModuleInfo>();
347 AU.addRequired<DwarfWriter>();
348 PPCAsmPrinter::getAnalysisUsage(AU);
351 void printModuleLevelGV(const GlobalVariable* GVar);
353 } // end of anonymous namespace
355 // Include the auto-generated portion of the assembly writer
356 #include "PPCGenAsmWriter.inc"
358 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
359 switch (MO.getType()) {
360 case MachineOperand::MO_Immediate:
361 cerr << "printOp() does not handle immediate values\n";
365 case MachineOperand::MO_MachineBasicBlock:
366 printBasicBlockLabel(MO.getMBB());
368 case MachineOperand::MO_JumpTableIndex:
369 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
370 << '_' << MO.getIndex();
371 // FIXME: PIC relocation model
373 case MachineOperand::MO_ConstantPoolIndex:
374 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
375 << '_' << MO.getIndex();
377 case MachineOperand::MO_ExternalSymbol:
378 // Computing the address of an external symbol, not calling it.
379 if (TM.getRelocationModel() != Reloc::Static) {
380 std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
381 GVStubs.insert(Name);
382 printSuffixedName(Name, "$non_lazy_ptr");
385 O << TAI->getGlobalPrefix() << MO.getSymbolName();
387 case MachineOperand::MO_GlobalAddress: {
388 // Computing the address of a global symbol, not calling it.
389 GlobalValue *GV = MO.getGlobal();
390 std::string Name = Mang->getValueName(GV);
392 // External or weakly linked global variables need non-lazily-resolved stubs
393 if (TM.getRelocationModel() != Reloc::Static) {
394 if (GV->isDeclaration() || GV->isWeakForLinker()) {
395 if (GV->hasHiddenVisibility()) {
396 if (!GV->isDeclaration() && !GV->hasCommonLinkage())
399 HiddenGVStubs.insert(Name);
400 printSuffixedName(Name, "$non_lazy_ptr");
403 GVStubs.insert(Name);
404 printSuffixedName(Name, "$non_lazy_ptr");
406 if (GV->hasExternalWeakLinkage())
407 ExtWeakSymbols.insert(GV);
413 printOffset(MO.getOffset());
415 if (GV->hasExternalWeakLinkage())
416 ExtWeakSymbols.insert(GV);
421 O << "<unknown operand type: " << MO.getType() << ">";
426 /// EmitExternalGlobal - In this case we need to use the indirect symbol.
428 void PPCAsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
430 getGlobalLinkName(GV, Name);
431 if (TM.getRelocationModel() != Reloc::Static) {
432 if (GV->hasHiddenVisibility())
433 HiddenGVStubs.insert(Name);
435 GVStubs.insert(Name);
436 printSuffixedName(Name, "$non_lazy_ptr");
442 /// PrintAsmOperand - Print out an operand for an inline asm expression.
444 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
446 const char *ExtraCode) {
447 // Does this asm operand have a single letter operand modifier?
448 if (ExtraCode && ExtraCode[0]) {
449 if (ExtraCode[1] != 0) return true; // Unknown modifier.
451 switch (ExtraCode[0]) {
452 default: return true; // Unknown modifier.
453 case 'c': // Don't print "$" before a global var name or constant.
454 // PPC never has a prefix.
455 printOperand(MI, OpNo);
457 case 'L': // Write second word of DImode reference.
458 // Verify that this operand has two consecutive registers.
459 if (!MI->getOperand(OpNo).isReg() ||
460 OpNo+1 == MI->getNumOperands() ||
461 !MI->getOperand(OpNo+1).isReg())
463 ++OpNo; // Return the high-part.
466 // Write 'i' if an integer constant, otherwise nothing. Used to print
468 if (MI->getOperand(OpNo).isImm())
474 printOperand(MI, OpNo);
478 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
480 const char *ExtraCode) {
481 if (ExtraCode && ExtraCode[0])
482 return true; // Unknown modifier.
483 if (MI->getOperand(OpNo).isReg())
484 printMemRegReg(MI, OpNo);
486 printMemRegImm(MI, OpNo);
490 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
491 const char *Modifier) {
492 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
493 unsigned Code = MI->getOperand(OpNo).getImm();
494 if (!strcmp(Modifier, "cc")) {
495 switch ((PPC::Predicate)Code) {
496 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
497 case PPC::PRED_LT: O << "lt"; return;
498 case PPC::PRED_LE: O << "le"; return;
499 case PPC::PRED_EQ: O << "eq"; return;
500 case PPC::PRED_GE: O << "ge"; return;
501 case PPC::PRED_GT: O << "gt"; return;
502 case PPC::PRED_NE: O << "ne"; return;
503 case PPC::PRED_UN: O << "un"; return;
504 case PPC::PRED_NU: O << "nu"; return;
508 assert(!strcmp(Modifier, "reg") &&
509 "Need to specify 'cc' or 'reg' as predicate op modifier!");
510 // Don't print the register for 'always'.
511 if (Code == PPC::PRED_ALWAYS) return;
512 printOperand(MI, OpNo+1);
517 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
518 /// the current output stream.
520 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
523 // Check for slwi/srwi mnemonics.
524 if (MI->getOpcode() == PPC::RLWINM) {
525 bool FoundMnemonic = false;
526 unsigned char SH = MI->getOperand(2).getImm();
527 unsigned char MB = MI->getOperand(3).getImm();
528 unsigned char ME = MI->getOperand(4).getImm();
529 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
530 O << "\tslwi "; FoundMnemonic = true;
532 if (SH <= 31 && MB == (32-SH) && ME == 31) {
533 O << "\tsrwi "; FoundMnemonic = true;
540 O << ", " << (unsigned int)SH << '\n';
543 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
544 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
552 } else if (MI->getOpcode() == PPC::RLDICR) {
553 unsigned char SH = MI->getOperand(2).getImm();
554 unsigned char ME = MI->getOperand(3).getImm();
555 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
561 O << ", " << (unsigned int)SH << '\n';
566 if (printInstruction(MI))
567 return; // Printer was automatically generated
569 assert(0 && "Unhandled instruction in asm writer!");
574 /// runOnMachineFunction - This uses the printMachineInstruction()
575 /// method to print assembly for each instruction.
577 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
580 SetupMachineFunction(MF);
583 // Print out constants referenced by the function
584 EmitConstantPool(MF.getConstantPool());
586 // Print out labels for the function.
587 const Function *F = MF.getFunction();
588 SwitchToSection(TAI->SectionForGlobal(F));
590 switch (F->getLinkage()) {
591 default: assert(0 && "Unknown linkage type!");
592 case Function::PrivateLinkage:
593 case Function::InternalLinkage: // Symbols default to internal.
595 case Function::ExternalLinkage:
596 O << "\t.global\t" << CurrentFnName << '\n'
597 << "\t.type\t" << CurrentFnName << ", @function\n";
599 case Function::WeakAnyLinkage:
600 case Function::WeakODRLinkage:
601 case Function::LinkOnceAnyLinkage:
602 case Function::LinkOnceODRLinkage:
603 O << "\t.global\t" << CurrentFnName << '\n';
604 O << "\t.weak\t" << CurrentFnName << '\n';
608 printVisibility(CurrentFnName, F->getVisibility());
611 O << CurrentFnName << ":\n";
613 // Emit pre-function debug information.
614 DW->BeginFunction(&MF);
616 // Print out code for the function.
617 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
619 // Print a label for the basic block.
620 if (I != MF.begin()) {
621 printBasicBlockLabel(I, true, true);
624 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
626 // Print the assembly for the instruction.
627 printMachineInstruction(II);
631 O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << '\n';
633 // Print out jump tables referenced by the function.
634 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
636 SwitchToSection(TAI->SectionForGlobal(F));
638 // Emit post-function debug information.
639 DW->EndFunction(&MF);
643 // We didn't modify anything.
647 bool PPCLinuxAsmPrinter::doInitialization(Module &M) {
648 bool Result = AsmPrinter::doInitialization(M);
650 // Emit initial debug information.
651 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
653 DW = getAnalysisIfAvailable<DwarfWriter>();
654 assert(DW && "DwarfWriter is not available");
655 DW->BeginModule(&M, MMI, O, this, TAI);
657 // GNU as handles section names wrapped in quotes
658 Mang->setUseQuotes(true);
660 SwitchToSection(TAI->getTextSection());
665 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
666 /// Don't print things like \\n or \\0.
667 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
668 for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
674 void PPCLinuxAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
675 const TargetData *TD = TM.getTargetData();
677 if (!GVar->hasInitializer())
678 return; // External global require no code
680 // Check to see if this is a special global used by LLVM, if so, emit it.
681 if (EmitSpecialLLVMGlobal(GVar))
684 std::string name = Mang->getValueName(GVar);
686 printVisibility(name, GVar->getVisibility());
688 Constant *C = GVar->getInitializer();
689 const Type *Type = C->getType();
690 unsigned Size = TD->getTypeAllocSize(Type);
691 unsigned Align = TD->getPreferredAlignmentLog(GVar);
693 SwitchToSection(TAI->SectionForGlobal(GVar));
695 if (C->isNullValue() && /* FIXME: Verify correct */
696 !GVar->hasSection() &&
697 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
698 GVar->isWeakForLinker())) {
699 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
701 if (GVar->hasExternalLinkage()) {
702 O << "\t.global " << name << '\n';
703 O << "\t.type " << name << ", @object\n";
705 O << "\t.zero " << Size << '\n';
706 } else if (GVar->hasLocalLinkage()) {
707 O << TAI->getLCOMMDirective() << name << ',' << Size;
709 O << ".comm " << name << ',' << Size;
712 O << "\t\t" << TAI->getCommentString() << " '";
713 PrintUnmangledNameSafely(GVar, O);
720 switch (GVar->getLinkage()) {
721 case GlobalValue::LinkOnceAnyLinkage:
722 case GlobalValue::LinkOnceODRLinkage:
723 case GlobalValue::WeakAnyLinkage:
724 case GlobalValue::WeakODRLinkage:
725 case GlobalValue::CommonLinkage:
726 O << "\t.global " << name << '\n'
727 << "\t.type " << name << ", @object\n"
728 << "\t.weak " << name << '\n';
730 case GlobalValue::AppendingLinkage:
731 // FIXME: appending linkage variables should go into a section of
732 // their name or something. For now, just emit them as external.
733 case GlobalValue::ExternalLinkage:
734 // If external or appending, declare as a global symbol
735 O << "\t.global " << name << '\n'
736 << "\t.type " << name << ", @object\n";
738 case GlobalValue::InternalLinkage:
739 case GlobalValue::PrivateLinkage:
742 cerr << "Unknown linkage type!";
746 EmitAlignment(Align, GVar);
749 O << "\t\t\t\t" << TAI->getCommentString() << " '";
750 PrintUnmangledNameSafely(GVar, O);
755 // If the initializer is a extern weak symbol, remember to emit the weak
757 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
758 if (GV->hasExternalWeakLinkage())
759 ExtWeakSymbols.insert(GV);
761 EmitGlobalConstant(C);
765 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
766 // Print out module-level global variables here.
767 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
769 printModuleLevelGV(I);
773 // Emit initial debug information.
776 return AsmPrinter::doFinalization(M);
779 /// runOnMachineFunction - This uses the printMachineInstruction()
780 /// method to print assembly for each instruction.
782 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
785 SetupMachineFunction(MF);
788 // Print out constants referenced by the function
789 EmitConstantPool(MF.getConstantPool());
791 // Print out labels for the function.
792 const Function *F = MF.getFunction();
793 SwitchToSection(TAI->SectionForGlobal(F));
795 switch (F->getLinkage()) {
796 default: assert(0 && "Unknown linkage type!");
797 case Function::PrivateLinkage:
798 case Function::InternalLinkage: // Symbols default to internal.
800 case Function::ExternalLinkage:
801 O << "\t.globl\t" << CurrentFnName << '\n';
803 case Function::WeakAnyLinkage:
804 case Function::WeakODRLinkage:
805 case Function::LinkOnceAnyLinkage:
806 case Function::LinkOnceODRLinkage:
807 O << "\t.globl\t" << CurrentFnName << '\n';
808 O << "\t.weak_definition\t" << CurrentFnName << '\n';
812 printVisibility(CurrentFnName, F->getVisibility());
814 EmitAlignment(F->hasFnAttr(Attribute::OptimizeForSize) ? 2 : 4, F);
815 O << CurrentFnName << ":\n";
817 // Emit pre-function debug information.
818 DW->BeginFunction(&MF);
820 // If the function is empty, then we need to emit *something*. Otherwise, the
821 // function's label might be associated with something that it wasn't meant to
822 // be associated with. We emit a noop in this situation.
823 MachineFunction::iterator I = MF.begin();
825 if (++I == MF.end() && MF.front().empty())
828 // Print out code for the function.
829 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
831 // Print a label for the basic block.
832 if (I != MF.begin()) {
833 printBasicBlockLabel(I, true, true, VerboseAsm);
836 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
838 // Print the assembly for the instruction.
839 printMachineInstruction(II);
843 // Print out jump tables referenced by the function.
844 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
846 // Emit post-function debug information.
847 DW->EndFunction(&MF);
849 // We didn't modify anything.
854 bool PPCDarwinAsmPrinter::doInitialization(Module &M) {
855 static const char *const CPUDirectives[] = {
867 unsigned Directive = Subtarget.getDarwinDirective();
868 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
869 Directive = PPC::DIR_970;
870 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
871 Directive = PPC::DIR_7400;
872 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
873 Directive = PPC::DIR_64;
874 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
875 O << "\t.machine " << CPUDirectives[Directive] << '\n';
877 bool Result = AsmPrinter::doInitialization(M);
879 // Emit initial debug information.
880 // We need this for Personality functions.
881 // AsmPrinter::doInitialization should have done this analysis.
882 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
884 DW = getAnalysisIfAvailable<DwarfWriter>();
885 assert(DW && "DwarfWriter is not available");
886 DW->BeginModule(&M, MMI, O, this, TAI);
888 // Darwin wants symbols to be quoted if they have complex names.
889 Mang->setUseQuotes(true);
891 // Prime text sections so they are adjacent. This reduces the likelihood a
892 // large data or debug section causes a branch to exceed 16M limit.
893 SwitchToTextSection("\t.section __TEXT,__textcoal_nt,coalesced,"
894 "pure_instructions");
895 if (TM.getRelocationModel() == Reloc::PIC_) {
896 SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
897 "pure_instructions,32");
898 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
899 SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
900 "pure_instructions,16");
902 SwitchToSection(TAI->getTextSection());
907 void PPCDarwinAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
908 const TargetData *TD = TM.getTargetData();
910 if (!GVar->hasInitializer())
911 return; // External global require no code
913 // Check to see if this is a special global used by LLVM, if so, emit it.
914 if (EmitSpecialLLVMGlobal(GVar)) {
915 if (TM.getRelocationModel() == Reloc::Static) {
916 if (GVar->getName() == "llvm.global_ctors")
917 O << ".reference .constructors_used\n";
918 else if (GVar->getName() == "llvm.global_dtors")
919 O << ".reference .destructors_used\n";
924 std::string name = Mang->getValueName(GVar);
926 printVisibility(name, GVar->getVisibility());
928 Constant *C = GVar->getInitializer();
929 const Type *Type = C->getType();
930 unsigned Size = TD->getTypeAllocSize(Type);
931 unsigned Align = TD->getPreferredAlignmentLog(GVar);
933 SwitchToSection(TAI->SectionForGlobal(GVar));
935 if (C->isNullValue() && /* FIXME: Verify correct */
936 !GVar->hasSection() &&
937 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
938 GVar->isWeakForLinker()) &&
939 TAI->SectionKindForGlobal(GVar) != SectionKind::RODataMergeStr) {
940 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
942 if (GVar->hasExternalLinkage()) {
943 O << "\t.globl " << name << '\n';
944 O << "\t.zerofill __DATA, __common, " << name << ", "
945 << Size << ", " << Align;
946 } else if (GVar->hasLocalLinkage()) {
947 O << TAI->getLCOMMDirective() << name << ',' << Size << ',' << Align;
948 } else if (!GVar->hasCommonLinkage()) {
949 O << "\t.globl " << name << '\n'
950 << TAI->getWeakDefDirective() << name << '\n';
951 EmitAlignment(Align, GVar);
954 O << "\t\t\t\t" << TAI->getCommentString() << " ";
955 PrintUnmangledNameSafely(GVar, O);
958 EmitGlobalConstant(C);
961 O << ".comm " << name << ',' << Size;
962 // Darwin 9 and above support aligned common data.
963 if (Subtarget.isDarwin9())
967 O << "\t\t" << TAI->getCommentString() << " '";
968 PrintUnmangledNameSafely(GVar, O);
975 switch (GVar->getLinkage()) {
976 case GlobalValue::LinkOnceAnyLinkage:
977 case GlobalValue::LinkOnceODRLinkage:
978 case GlobalValue::WeakAnyLinkage:
979 case GlobalValue::WeakODRLinkage:
980 case GlobalValue::CommonLinkage:
981 O << "\t.globl " << name << '\n'
982 << "\t.weak_definition " << name << '\n';
984 case GlobalValue::AppendingLinkage:
985 // FIXME: appending linkage variables should go into a section of
986 // their name or something. For now, just emit them as external.
987 case GlobalValue::ExternalLinkage:
988 // If external or appending, declare as a global symbol
989 O << "\t.globl " << name << '\n';
991 case GlobalValue::InternalLinkage:
992 case GlobalValue::PrivateLinkage:
995 cerr << "Unknown linkage type!";
999 EmitAlignment(Align, GVar);
1002 O << "\t\t\t\t" << TAI->getCommentString() << " '";
1003 PrintUnmangledNameSafely(GVar, O);
1008 // If the initializer is a extern weak symbol, remember to emit the weak
1010 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1011 if (GV->hasExternalWeakLinkage())
1012 ExtWeakSymbols.insert(GV);
1014 EmitGlobalConstant(C);
1018 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
1019 const TargetData *TD = TM.getTargetData();
1021 // Print out module-level global variables here.
1022 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1024 printModuleLevelGV(I);
1026 bool isPPC64 = TD->getPointerSizeInBits() == 64;
1028 // Output stubs for dynamically-linked functions
1029 if (TM.getRelocationModel() == Reloc::PIC_) {
1030 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1032 SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
1033 "pure_instructions,32");
1035 const char *p = i->getKeyData();
1036 bool hasQuote = p[0]=='\"';
1037 printSuffixedName(p, "$stub");
1039 O << "\t.indirect_symbol " << p << '\n';
1041 O << "\tbcl 20,31,";
1043 O << "\"L0$" << &p[1];
1048 O << "\"L0$" << &p[1];
1052 O << "\tmflr r11\n";
1053 O << "\taddis r11,r11,ha16(";
1054 printSuffixedName(p, "$lazy_ptr");
1057 O << "\"L0$" << &p[1];
1063 O << "\tldu r12,lo16(";
1065 O << "\tlwzu r12,lo16(";
1066 printSuffixedName(p, "$lazy_ptr");
1069 O << "\"L0$" << &p[1];
1073 O << "\tmtctr r12\n";
1075 SwitchToDataSection(".lazy_symbol_pointer");
1076 printSuffixedName(p, "$lazy_ptr");
1078 O << "\t.indirect_symbol " << p << '\n';
1080 O << "\t.quad dyld_stub_binding_helper\n";
1082 O << "\t.long dyld_stub_binding_helper\n";
1085 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1087 SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
1088 "pure_instructions,16");
1090 const char *p = i->getKeyData();
1091 printSuffixedName(p, "$stub");
1093 O << "\t.indirect_symbol " << p << '\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 " << p << '\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 (StringSet<>::iterator i = GVStubs.begin(), e = GVStubs.end();
1133 std::string p = i->getKeyData();
1134 printSuffixedName(p, "$non_lazy_ptr");
1136 O << "\t.indirect_symbol " << p << '\n';
1138 O << "\t.quad\t0\n";
1140 O << "\t.long\t0\n";
1144 if (!HiddenGVStubs.empty()) {
1145 SwitchToSection(TAI->getDataSection());
1146 for (StringSet<>::iterator i = HiddenGVStubs.begin(), e = HiddenGVStubs.end();
1148 std::string p = i->getKeyData();
1149 EmitAlignment(isPPC64 ? 3 : 2);
1150 printSuffixedName(p, "$non_lazy_ptr");
1161 // Emit initial debug information.
1164 // Funny Darwin hack: This flag tells the linker that no global symbols
1165 // contain code that falls through to other global symbols (e.g. the obvious
1166 // implementation of multiple entry points). If this doesn't occur, the
1167 // linker can safely perform dead code stripping. Since LLVM never generates
1168 // code that does this, it is always safe to set.
1169 O << "\t.subsections_via_symbols\n";
1171 return AsmPrinter::doFinalization(M);
1176 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1177 /// for a MachineFunction to the given output stream, in a format that the
1178 /// Darwin assembler can deal with.
1180 FunctionPass *llvm::createPPCAsmPrinterPass(raw_ostream &o,
1181 PPCTargetMachine &tm,
1182 CodeGenOpt::Level OptLevel,
1184 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1186 if (Subtarget->isDarwin()) {
1187 return new PPCDarwinAsmPrinter(o, tm, tm.getTargetAsmInfo(),
1190 return new PPCLinuxAsmPrinter(o, tm, tm.getTargetAsmInfo(),
1196 static struct Register {
1198 PPCTargetMachine::registerAsmPrinter(createPPCAsmPrinterPass);
1203 extern "C" int PowerPCAsmPrinterForceLink;
1204 int PowerPCAsmPrinterForceLink = 0;