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/MDNode.h"
28 #include "llvm/Assembly/Writer.h"
29 #include "llvm/CodeGen/AsmPrinter.h"
30 #include "llvm/CodeGen/DwarfWriter.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineFunctionPass.h"
33 #include "llvm/CodeGen/MachineInstr.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/Support/Mangler.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/Compiler.h"
41 #include "llvm/Support/FormattedStream.h"
42 #include "llvm/Target/TargetAsmInfo.h"
43 #include "llvm/Target/TargetRegisterInfo.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/Target/TargetOptions.h"
46 #include "llvm/Target/TargetRegistry.h"
47 #include "llvm/ADT/Statistic.h"
48 #include "llvm/ADT/StringExtras.h"
49 #include "llvm/ADT/StringSet.h"
52 STATISTIC(EmittedInsts, "Number of machine instrs printed");
55 class VISIBILITY_HIDDEN PPCAsmPrinter : public AsmPrinter {
58 std::string Stub, LazyPtr, AnonSymbol;
62 void Init(const GlobalValue *GV, Mangler *Mang) {
63 // Already initialized.
64 if (!Stub.empty()) return;
65 Stub = Mang->getMangledName(GV, "$stub", true);
66 LazyPtr = Mang->getMangledName(GV, "$lazy_ptr", true);
67 AnonSymbol = Mang->getMangledName(GV, "$stub$tmp", true);
70 void Init(const std::string &GV, Mangler *Mang) {
71 // Already initialized.
72 if (!Stub.empty()) return;
73 Stub = Mang->makeNameProper(GV + "$stub",
75 LazyPtr = Mang->makeNameProper(GV + "$lazy_ptr",
77 AnonSymbol = Mang->makeNameProper(GV + "$stub$tmp",
82 StringMap<FnStubInfo> FnStubs;
83 StringMap<std::string> GVStubs, HiddenGVStubs;
84 const PPCSubtarget &Subtarget;
86 explicit PPCAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
87 const TargetAsmInfo *T, bool V)
88 : AsmPrinter(O, TM, T, V),
89 Subtarget(TM.getSubtarget<PPCSubtarget>()) {}
91 virtual const char *getPassName() const {
92 return "PowerPC Assembly Printer";
95 PPCTargetMachine &getTM() {
96 return static_cast<PPCTargetMachine&>(TM);
99 unsigned enumRegToMachineReg(unsigned enumReg) {
101 default: llvm_unreachable("Unhandled register!");
102 case PPC::CR0: return 0;
103 case PPC::CR1: return 1;
104 case PPC::CR2: return 2;
105 case PPC::CR3: return 3;
106 case PPC::CR4: return 4;
107 case PPC::CR5: return 5;
108 case PPC::CR6: return 6;
109 case PPC::CR7: return 7;
114 /// printInstruction - This method is automatically generated by tablegen
115 /// from the instruction set description. This method returns true if the
116 /// machine instruction was sufficiently described to print it, otherwise it
118 bool printInstruction(const MachineInstr *MI);
120 void printMachineInstruction(const MachineInstr *MI);
121 void printOp(const MachineOperand &MO);
123 /// stripRegisterPrefix - This method strips the character prefix from a
124 /// register name so that only the number is left. Used by for linux asm.
125 const char *stripRegisterPrefix(const char *RegName) {
126 switch (RegName[0]) {
129 case 'v': return RegName + 1;
130 case 'c': if (RegName[1] == 'r') return RegName + 2;
136 /// printRegister - Print register according to target requirements.
138 void printRegister(const MachineOperand &MO, bool R0AsZero) {
139 unsigned RegNo = MO.getReg();
140 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
142 // If we should use 0 for R0.
143 if (R0AsZero && RegNo == PPC::R0) {
148 const char *RegName = TM.getRegisterInfo()->get(RegNo).AsmName;
149 // Linux assembler (Others?) does not take register mnemonics.
150 // FIXME - What about special registers used in mfspr/mtspr?
151 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
155 void printOperand(const MachineInstr *MI, unsigned OpNo) {
156 const MachineOperand &MO = MI->getOperand(OpNo);
158 printRegister(MO, false);
159 } else if (MO.isImm()) {
166 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
167 unsigned AsmVariant, const char *ExtraCode);
168 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
169 unsigned AsmVariant, const char *ExtraCode);
172 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
173 char value = MI->getOperand(OpNo).getImm();
174 value = (value << (32-5)) >> (32-5);
177 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
178 unsigned char value = MI->getOperand(OpNo).getImm();
179 assert(value <= 31 && "Invalid u5imm argument!");
180 O << (unsigned int)value;
182 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
183 unsigned char value = MI->getOperand(OpNo).getImm();
184 assert(value <= 63 && "Invalid u6imm argument!");
185 O << (unsigned int)value;
187 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
188 O << (short)MI->getOperand(OpNo).getImm();
190 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
191 O << (unsigned short)MI->getOperand(OpNo).getImm();
193 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
194 if (MI->getOperand(OpNo).isImm()) {
195 O << (short)(MI->getOperand(OpNo).getImm()*4);
198 printOp(MI->getOperand(OpNo));
199 if (TM.getRelocationModel() == Reloc::PIC_)
200 O << "-\"L" << getFunctionNumber() << "$pb\")";
205 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
206 // Branches can take an immediate operand. This is used by the branch
207 // selection pass to print $+8, an eight byte displacement from the PC.
208 if (MI->getOperand(OpNo).isImm()) {
209 O << "$+" << MI->getOperand(OpNo).getImm()*4;
211 printOp(MI->getOperand(OpNo));
214 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
215 const MachineOperand &MO = MI->getOperand(OpNo);
216 if (TM.getRelocationModel() != Reloc::Static) {
217 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
218 GlobalValue *GV = MO.getGlobal();
219 if (GV->isDeclaration() || GV->isWeakForLinker()) {
220 // Dynamically-resolved functions need a stub for the function.
221 FnStubInfo &FnInfo = FnStubs[Mang->getMangledName(GV)];
222 FnInfo.Init(GV, Mang);
227 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
228 FnStubInfo &FnInfo =FnStubs[Mang->makeNameProper(MO.getSymbolName())];
229 FnInfo.Init(MO.getSymbolName(), Mang);
235 printOp(MI->getOperand(OpNo));
237 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
238 O << (int)MI->getOperand(OpNo).getImm()*4;
240 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
241 O << "\"L" << getFunctionNumber() << "$pb\"\n";
242 O << "\"L" << getFunctionNumber() << "$pb\":";
244 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
245 if (MI->getOperand(OpNo).isImm()) {
246 printS16ImmOperand(MI, OpNo);
248 if (Subtarget.isDarwin()) O << "ha16(";
249 printOp(MI->getOperand(OpNo));
250 if (TM.getRelocationModel() == Reloc::PIC_)
251 O << "-\"L" << getFunctionNumber() << "$pb\"";
252 if (Subtarget.isDarwin())
258 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
259 if (MI->getOperand(OpNo).isImm()) {
260 printS16ImmOperand(MI, OpNo);
262 if (Subtarget.isDarwin()) O << "lo16(";
263 printOp(MI->getOperand(OpNo));
264 if (TM.getRelocationModel() == Reloc::PIC_)
265 O << "-\"L" << getFunctionNumber() << "$pb\"";
266 if (Subtarget.isDarwin())
272 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
273 unsigned CCReg = MI->getOperand(OpNo).getReg();
274 unsigned RegNo = enumRegToMachineReg(CCReg);
275 O << (0x80 >> RegNo);
277 // The new addressing mode printers.
278 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
279 printSymbolLo(MI, OpNo);
281 if (MI->getOperand(OpNo+1).isReg() &&
282 MI->getOperand(OpNo+1).getReg() == PPC::R0)
285 printOperand(MI, OpNo+1);
288 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
289 if (MI->getOperand(OpNo).isImm())
290 printS16X4ImmOperand(MI, OpNo);
292 printSymbolLo(MI, OpNo);
294 if (MI->getOperand(OpNo+1).isReg() &&
295 MI->getOperand(OpNo+1).getReg() == PPC::R0)
298 printOperand(MI, OpNo+1);
302 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
303 // When used as the base register, r0 reads constant zero rather than
304 // the value contained in the register. For this reason, the darwin
305 // assembler requires that we print r0 as 0 (no r) when used as the base.
306 const MachineOperand &MO = MI->getOperand(OpNo);
307 printRegister(MO, true);
309 printOperand(MI, OpNo+1);
312 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
313 const char *Modifier);
315 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
317 virtual void EmitExternalGlobal(const GlobalVariable *GV);
320 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
321 class VISIBILITY_HIDDEN PPCLinuxAsmPrinter : public PPCAsmPrinter {
323 explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
324 const TargetAsmInfo *T, bool V)
325 : PPCAsmPrinter(O, TM, T, V){}
327 virtual const char *getPassName() const {
328 return "Linux PPC Assembly Printer";
331 bool runOnMachineFunction(MachineFunction &F);
333 void getAnalysisUsage(AnalysisUsage &AU) const {
334 AU.setPreservesAll();
335 AU.addRequired<MachineModuleInfo>();
336 AU.addRequired<DwarfWriter>();
337 PPCAsmPrinter::getAnalysisUsage(AU);
340 void PrintGlobalVariable(const GlobalVariable *GVar);
343 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
345 class VISIBILITY_HIDDEN PPCDarwinAsmPrinter : public PPCAsmPrinter {
346 formatted_raw_ostream &OS;
348 explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
349 const TargetAsmInfo *T, bool V)
350 : PPCAsmPrinter(O, TM, T, V), OS(O) {}
352 virtual const char *getPassName() const {
353 return "Darwin PPC Assembly Printer";
356 bool runOnMachineFunction(MachineFunction &F);
357 bool doInitialization(Module &M);
358 bool doFinalization(Module &M);
360 void getAnalysisUsage(AnalysisUsage &AU) const {
361 AU.setPreservesAll();
362 AU.addRequired<MachineModuleInfo>();
363 AU.addRequired<DwarfWriter>();
364 PPCAsmPrinter::getAnalysisUsage(AU);
367 void PrintGlobalVariable(const GlobalVariable *GVar);
369 } // end of anonymous namespace
371 // Include the auto-generated portion of the assembly writer
372 #include "PPCGenAsmWriter.inc"
374 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
375 switch (MO.getType()) {
376 case MachineOperand::MO_Immediate:
377 llvm_unreachable("printOp() does not handle immediate values");
379 case MachineOperand::MO_MachineBasicBlock:
380 printBasicBlockLabel(MO.getMBB());
382 case MachineOperand::MO_JumpTableIndex:
383 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
384 << '_' << MO.getIndex();
385 // FIXME: PIC relocation model
387 case MachineOperand::MO_ConstantPoolIndex:
388 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
389 << '_' << MO.getIndex();
391 case MachineOperand::MO_ExternalSymbol: {
392 // Computing the address of an external symbol, not calling it.
393 std::string Name(TAI->getGlobalPrefix());
394 Name += MO.getSymbolName();
396 if (TM.getRelocationModel() != Reloc::Static) {
397 GVStubs[Name] = Name+"$non_lazy_ptr";
398 Name += "$non_lazy_ptr";
403 case MachineOperand::MO_GlobalAddress: {
404 // Computing the address of a global symbol, not calling it.
405 GlobalValue *GV = MO.getGlobal();
408 // External or weakly linked global variables need non-lazily-resolved stubs
409 if (TM.getRelocationModel() != Reloc::Static &&
410 (GV->isDeclaration() || GV->isWeakForLinker())) {
411 if (!GV->hasHiddenVisibility()) {
412 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
413 GVStubs[Mang->getMangledName(GV)] = Name;
414 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
415 GV->hasAvailableExternallyLinkage()) {
416 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
417 HiddenGVStubs[Mang->getMangledName(GV)] = Name;
419 Name = Mang->getMangledName(GV);
422 Name = Mang->getMangledName(GV);
426 printOffset(MO.getOffset());
431 O << "<unknown operand type: " << MO.getType() << ">";
436 /// EmitExternalGlobal - In this case we need to use the indirect symbol.
438 void PPCAsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
441 if (TM.getRelocationModel() != Reloc::Static) {
442 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
444 Name = Mang->getMangledName(GV);
449 /// PrintAsmOperand - Print out an operand for an inline asm expression.
451 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
453 const char *ExtraCode) {
454 // Does this asm operand have a single letter operand modifier?
455 if (ExtraCode && ExtraCode[0]) {
456 if (ExtraCode[1] != 0) return true; // Unknown modifier.
458 switch (ExtraCode[0]) {
459 default: return true; // Unknown modifier.
460 case 'c': // Don't print "$" before a global var name or constant.
461 // PPC never has a prefix.
462 printOperand(MI, OpNo);
464 case 'L': // Write second word of DImode reference.
465 // Verify that this operand has two consecutive registers.
466 if (!MI->getOperand(OpNo).isReg() ||
467 OpNo+1 == MI->getNumOperands() ||
468 !MI->getOperand(OpNo+1).isReg())
470 ++OpNo; // Return the high-part.
473 // Write 'i' if an integer constant, otherwise nothing. Used to print
475 if (MI->getOperand(OpNo).isImm())
481 printOperand(MI, OpNo);
485 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
487 const char *ExtraCode) {
488 if (ExtraCode && ExtraCode[0])
489 return true; // Unknown modifier.
490 if (MI->getOperand(OpNo).isReg())
491 printMemRegReg(MI, OpNo);
493 printMemRegImm(MI, OpNo);
497 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
498 const char *Modifier) {
499 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
500 unsigned Code = MI->getOperand(OpNo).getImm();
501 if (!strcmp(Modifier, "cc")) {
502 switch ((PPC::Predicate)Code) {
503 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
504 case PPC::PRED_LT: O << "lt"; return;
505 case PPC::PRED_LE: O << "le"; return;
506 case PPC::PRED_EQ: O << "eq"; return;
507 case PPC::PRED_GE: O << "ge"; return;
508 case PPC::PRED_GT: O << "gt"; return;
509 case PPC::PRED_NE: O << "ne"; return;
510 case PPC::PRED_UN: O << "un"; return;
511 case PPC::PRED_NU: O << "nu"; return;
515 assert(!strcmp(Modifier, "reg") &&
516 "Need to specify 'cc' or 'reg' as predicate op modifier!");
517 // Don't print the register for 'always'.
518 if (Code == PPC::PRED_ALWAYS) return;
519 printOperand(MI, OpNo+1);
524 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
525 /// the current output stream.
527 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
530 // Check for slwi/srwi mnemonics.
531 if (MI->getOpcode() == PPC::RLWINM) {
532 bool FoundMnemonic = false;
533 unsigned char SH = MI->getOperand(2).getImm();
534 unsigned char MB = MI->getOperand(3).getImm();
535 unsigned char ME = MI->getOperand(4).getImm();
536 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
537 O << "\tslwi "; FoundMnemonic = true;
539 if (SH <= 31 && MB == (32-SH) && ME == 31) {
540 O << "\tsrwi "; FoundMnemonic = true;
547 O << ", " << (unsigned int)SH << '\n';
550 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
551 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
559 } else if (MI->getOpcode() == PPC::RLDICR) {
560 unsigned char SH = MI->getOperand(2).getImm();
561 unsigned char ME = MI->getOperand(3).getImm();
562 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
568 O << ", " << (unsigned int)SH << '\n';
573 if (printInstruction(MI))
574 return; // Printer was automatically generated
576 llvm_unreachable("Unhandled instruction in asm writer!");
579 /// runOnMachineFunction - This uses the printMachineInstruction()
580 /// method to print assembly for each instruction.
582 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
585 SetupMachineFunction(MF);
588 // Print out constants referenced by the function
589 EmitConstantPool(MF.getConstantPool());
591 // Print out labels for the function.
592 const Function *F = MF.getFunction();
593 SwitchToSection(TAI->SectionForGlobal(F));
595 switch (F->getLinkage()) {
596 default: llvm_unreachable("Unknown linkage type!");
597 case Function::PrivateLinkage:
598 case Function::LinkerPrivateLinkage:
599 case Function::InternalLinkage: // Symbols default to internal.
601 case Function::ExternalLinkage:
602 O << "\t.global\t" << CurrentFnName << '\n'
603 << "\t.type\t" << CurrentFnName << ", @function\n";
605 case Function::WeakAnyLinkage:
606 case Function::WeakODRLinkage:
607 case Function::LinkOnceAnyLinkage:
608 case Function::LinkOnceODRLinkage:
609 O << "\t.global\t" << CurrentFnName << '\n';
610 O << "\t.weak\t" << CurrentFnName << '\n';
614 printVisibility(CurrentFnName, F->getVisibility());
616 EmitAlignment(MF.getAlignment(), F);
617 O << CurrentFnName << ":\n";
619 // Emit pre-function debug information.
620 DW->BeginFunction(&MF);
622 // Print out code for the function.
623 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
625 // Print a label for the basic block.
626 if (I != MF.begin()) {
627 printBasicBlockLabel(I, true, true);
630 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
632 // Print the assembly for the instruction.
633 printMachineInstruction(II);
637 O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << '\n';
639 // Print out jump tables referenced by the function.
640 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
642 SwitchToSection(TAI->SectionForGlobal(F));
644 // Emit post-function debug information.
645 DW->EndFunction(&MF);
649 // We didn't modify anything.
653 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
654 /// Don't print things like \\n or \\0.
655 static void PrintUnmangledNameSafely(const Value *V,
656 formatted_raw_ostream &OS) {
657 for (StringRef::iterator it = V->getName().begin(),
658 ie = V->getName().end(); it != ie; ++it)
663 void PPCLinuxAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
664 const TargetData *TD = TM.getTargetData();
666 if (!GVar->hasInitializer())
667 return; // External global require no code
669 // Check to see if this is a special global used by LLVM, if so, emit it.
670 if (EmitSpecialLLVMGlobal(GVar))
673 std::string name = Mang->getMangledName(GVar);
675 printVisibility(name, GVar->getVisibility());
677 Constant *C = GVar->getInitializer();
678 if (isa<MDNode>(C) || isa<MDString>(C))
680 const Type *Type = C->getType();
681 unsigned Size = TD->getTypeAllocSize(Type);
682 unsigned Align = TD->getPreferredAlignmentLog(GVar);
684 SwitchToSection(TAI->SectionForGlobal(GVar));
686 if (C->isNullValue() && /* FIXME: Verify correct */
687 !GVar->hasSection() &&
688 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
689 GVar->isWeakForLinker())) {
690 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
692 if (GVar->hasExternalLinkage()) {
693 O << "\t.global " << name << '\n';
694 O << "\t.type " << name << ", @object\n";
696 O << "\t.zero " << Size << '\n';
697 } else if (GVar->hasLocalLinkage()) {
698 O << TAI->getLCOMMDirective() << name << ',' << Size;
700 O << ".comm " << name << ',' << Size;
703 O << "\t\t" << TAI->getCommentString() << " '";
704 PrintUnmangledNameSafely(GVar, O);
711 switch (GVar->getLinkage()) {
712 case GlobalValue::LinkOnceAnyLinkage:
713 case GlobalValue::LinkOnceODRLinkage:
714 case GlobalValue::WeakAnyLinkage:
715 case GlobalValue::WeakODRLinkage:
716 case GlobalValue::CommonLinkage:
717 O << "\t.global " << name << '\n'
718 << "\t.type " << name << ", @object\n"
719 << "\t.weak " << name << '\n';
721 case GlobalValue::AppendingLinkage:
722 // FIXME: appending linkage variables should go into a section of
723 // their name or something. For now, just emit them as external.
724 case GlobalValue::ExternalLinkage:
725 // If external or appending, declare as a global symbol
726 O << "\t.global " << name << '\n'
727 << "\t.type " << name << ", @object\n";
729 case GlobalValue::InternalLinkage:
730 case GlobalValue::PrivateLinkage:
731 case GlobalValue::LinkerPrivateLinkage:
734 llvm_unreachable("Unknown linkage type!");
737 EmitAlignment(Align, GVar);
740 O << "\t\t\t\t" << TAI->getCommentString() << " '";
741 PrintUnmangledNameSafely(GVar, O);
746 EmitGlobalConstant(C);
751 /// runOnMachineFunction - This uses the printMachineInstruction()
752 /// method to print assembly for each instruction.
754 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
757 SetupMachineFunction(MF);
760 // Print out constants referenced by the function
761 EmitConstantPool(MF.getConstantPool());
763 // Print out labels for the function.
764 const Function *F = MF.getFunction();
765 SwitchToSection(TAI->SectionForGlobal(F));
767 switch (F->getLinkage()) {
768 default: llvm_unreachable("Unknown linkage type!");
769 case Function::PrivateLinkage:
770 case Function::LinkerPrivateLinkage:
771 case Function::InternalLinkage: // Symbols default to internal.
773 case Function::ExternalLinkage:
774 O << "\t.globl\t" << CurrentFnName << '\n';
776 case Function::WeakAnyLinkage:
777 case Function::WeakODRLinkage:
778 case Function::LinkOnceAnyLinkage:
779 case Function::LinkOnceODRLinkage:
780 O << "\t.globl\t" << CurrentFnName << '\n';
781 O << "\t.weak_definition\t" << CurrentFnName << '\n';
785 printVisibility(CurrentFnName, F->getVisibility());
787 EmitAlignment(MF.getAlignment(), F);
788 O << CurrentFnName << ":\n";
790 // Emit pre-function debug information.
791 DW->BeginFunction(&MF);
793 // If the function is empty, then we need to emit *something*. Otherwise, the
794 // function's label might be associated with something that it wasn't meant to
795 // be associated with. We emit a noop in this situation.
796 MachineFunction::iterator I = MF.begin();
798 if (++I == MF.end() && MF.front().empty())
801 // Print out code for the function.
802 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
804 // Print a label for the basic block.
805 if (I != MF.begin()) {
806 printBasicBlockLabel(I, true, true, VerboseAsm);
809 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
811 // Print the assembly for the instruction.
812 printMachineInstruction(II);
816 // Print out jump tables referenced by the function.
817 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
819 // Emit post-function debug information.
820 DW->EndFunction(&MF);
822 // We didn't modify anything.
827 bool PPCDarwinAsmPrinter::doInitialization(Module &M) {
828 static const char *const CPUDirectives[] = {
840 unsigned Directive = Subtarget.getDarwinDirective();
841 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
842 Directive = PPC::DIR_970;
843 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
844 Directive = PPC::DIR_7400;
845 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
846 Directive = PPC::DIR_64;
847 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
848 O << "\t.machine " << CPUDirectives[Directive] << '\n';
850 bool Result = AsmPrinter::doInitialization(M);
853 // Prime text sections so they are adjacent. This reduces the likelihood a
854 // large data or debug section causes a branch to exceed 16M limit.
855 SwitchToTextSection("\t.section __TEXT,__textcoal_nt,coalesced,"
856 "pure_instructions");
857 if (TM.getRelocationModel() == Reloc::PIC_) {
858 SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
859 "pure_instructions,32");
860 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
861 SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
862 "pure_instructions,16");
864 SwitchToSection(TAI->getTextSection());
869 void PPCDarwinAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
870 const TargetData *TD = TM.getTargetData();
872 if (!GVar->hasInitializer())
873 return; // External global require no code
875 // Check to see if this is a special global used by LLVM, if so, emit it.
876 if (EmitSpecialLLVMGlobal(GVar)) {
877 if (TM.getRelocationModel() == Reloc::Static) {
878 if (GVar->getName() == "llvm.global_ctors")
879 O << ".reference .constructors_used\n";
880 else if (GVar->getName() == "llvm.global_dtors")
881 O << ".reference .destructors_used\n";
886 std::string name = Mang->getMangledName(GVar);
887 printVisibility(name, GVar->getVisibility());
889 Constant *C = GVar->getInitializer();
890 const Type *Type = C->getType();
891 unsigned Size = TD->getTypeAllocSize(Type);
892 unsigned Align = TD->getPreferredAlignmentLog(GVar);
894 const Section *TheSection = TAI->SectionForGlobal(GVar);
895 SwitchToSection(TheSection);
897 if (C->isNullValue() && /* FIXME: Verify correct */
898 !GVar->hasSection() &&
899 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
900 GVar->isWeakForLinker()) &&
901 // Don't put things that should go in the cstring section into "comm".
902 !TheSection->hasFlag(SectionFlags::Strings)) {
903 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
905 if (GVar->hasExternalLinkage()) {
906 O << "\t.globl " << name << '\n';
907 O << "\t.zerofill __DATA, __common, " << name << ", "
908 << Size << ", " << Align;
909 } else if (GVar->hasLocalLinkage()) {
910 O << TAI->getLCOMMDirective() << name << ',' << Size << ',' << Align;
911 } else if (!GVar->hasCommonLinkage()) {
912 O << "\t.globl " << name << '\n'
913 << TAI->getWeakDefDirective() << name << '\n';
914 EmitAlignment(Align, GVar);
917 O << "\t\t\t\t" << TAI->getCommentString() << " ";
918 PrintUnmangledNameSafely(GVar, O);
921 EmitGlobalConstant(C);
924 O << ".comm " << name << ',' << Size;
925 // Darwin 9 and above support aligned common data.
926 if (Subtarget.isDarwin9())
930 O << "\t\t" << TAI->getCommentString() << " '";
931 PrintUnmangledNameSafely(GVar, O);
938 switch (GVar->getLinkage()) {
939 case GlobalValue::LinkOnceAnyLinkage:
940 case GlobalValue::LinkOnceODRLinkage:
941 case GlobalValue::WeakAnyLinkage:
942 case GlobalValue::WeakODRLinkage:
943 case GlobalValue::CommonLinkage:
944 O << "\t.globl " << name << '\n'
945 << "\t.weak_definition " << name << '\n';
947 case GlobalValue::AppendingLinkage:
948 // FIXME: appending linkage variables should go into a section of
949 // their name or something. For now, just emit them as external.
950 case GlobalValue::ExternalLinkage:
951 // If external or appending, declare as a global symbol
952 O << "\t.globl " << name << '\n';
954 case GlobalValue::InternalLinkage:
955 case GlobalValue::PrivateLinkage:
956 case GlobalValue::LinkerPrivateLinkage:
959 llvm_unreachable("Unknown linkage type!");
962 EmitAlignment(Align, GVar);
965 O << "\t\t\t\t" << TAI->getCommentString() << " '";
966 PrintUnmangledNameSafely(GVar, O);
971 EmitGlobalConstant(C);
975 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
976 const TargetData *TD = TM.getTargetData();
978 bool isPPC64 = TD->getPointerSizeInBits() == 64;
980 // Output stubs for dynamically-linked functions
981 if (TM.getRelocationModel() == Reloc::PIC_ && !FnStubs.empty()) {
982 for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
984 SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
985 "pure_instructions,32");
987 const FnStubInfo &Info = I->second;
988 O << Info.Stub << ":\n";
989 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
991 O << "\tbcl 20,31," << Info.AnonSymbol << '\n';
992 O << Info.AnonSymbol << ":\n";
994 O << "\taddis r11,r11,ha16(" << Info.LazyPtr << "-" << Info.AnonSymbol;
997 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
998 O << Info.LazyPtr << "-" << Info.AnonSymbol << ")(r11)\n";
999 O << "\tmtctr r12\n";
1002 SwitchToDataSection(".lazy_symbol_pointer");
1003 O << Info.LazyPtr << ":\n";
1004 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1005 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1007 } else if (!FnStubs.empty()) {
1008 for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1010 SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
1011 "pure_instructions,16");
1013 const FnStubInfo &Info = I->second;
1014 O << Info.Stub << ":\n";
1015 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1016 O << "\tlis r11,ha16(" << Info.LazyPtr << ")\n";
1017 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1018 O << Info.LazyPtr << ")(r11)\n";
1019 O << "\tmtctr r12\n";
1021 SwitchToDataSection(".lazy_symbol_pointer");
1022 O << Info.LazyPtr << ":\n";
1023 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1024 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1030 if (TAI->doesSupportExceptionHandling() && MMI) {
1031 // Add the (possibly multiple) personalities to the set of global values.
1032 // Only referenced functions get into the Personalities list.
1033 const std::vector<Function *> &Personalities = MMI->getPersonalities();
1034 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1035 E = Personalities.end(); I != E; ++I) {
1037 GVStubs[Mang->getMangledName(*I)] =
1038 Mang->getMangledName(*I, "$non_lazy_ptr", true);
1042 // Output stubs for external and common global variables.
1043 if (!GVStubs.empty()) {
1044 SwitchToDataSection(".non_lazy_symbol_pointer");
1045 for (StringMap<std::string>::iterator I = GVStubs.begin(),
1046 E = GVStubs.end(); I != E; ++I) {
1047 O << I->second << ":\n";
1048 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1049 O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
1053 if (!HiddenGVStubs.empty()) {
1054 SwitchToSection(TAI->getDataSection());
1055 EmitAlignment(isPPC64 ? 3 : 2);
1056 for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
1057 E = HiddenGVStubs.end(); I != E; ++I) {
1058 O << I->second << ":\n";
1059 O << (isPPC64 ? "\t.quad\t" : "\t.long\t") << I->getKeyData() << '\n';
1063 // Funny Darwin hack: This flag tells the linker that no global symbols
1064 // contain code that falls through to other global symbols (e.g. the obvious
1065 // implementation of multiple entry points). If this doesn't occur, the
1066 // linker can safely perform dead code stripping. Since LLVM never generates
1067 // code that does this, it is always safe to set.
1068 O << "\t.subsections_via_symbols\n";
1070 return AsmPrinter::doFinalization(M);
1075 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1076 /// for a MachineFunction to the given output stream, in a format that the
1077 /// Darwin assembler can deal with.
1079 static FunctionPass *createPPCAsmPrinterPass(formatted_raw_ostream &o,
1082 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1084 if (Subtarget->isDarwin())
1085 return new PPCDarwinAsmPrinter(o, tm, tm.getTargetAsmInfo(), verbose);
1086 return new PPCLinuxAsmPrinter(o, tm, tm.getTargetAsmInfo(), verbose);
1089 // Force static initialization.
1090 extern "C" void LLVMInitializePowerPCAsmPrinter() {
1091 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
1093 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);