make tblgen produce a function that returns the name for a physreg.
[llvm/avr.git] / lib / Target / PowerPC / AsmPrinter / PPCAsmPrinter.cpp
blob658ac317e0007772eabf093fb72fa82ca67b1c34
1 //===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly --------=//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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"
20 #include "PPC.h"
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/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCSectionMachO.h"
36 #include "llvm/MC/MCStreamer.h"
37 #include "llvm/MC/MCSymbol.h"
38 #include "llvm/Target/TargetLoweringObjectFile.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/Target/TargetRegistry.h"
43 #include "llvm/Support/Mangler.h"
44 #include "llvm/Support/MathExtras.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/Compiler.h"
49 #include "llvm/Support/FormattedStream.h"
50 #include "llvm/ADT/Statistic.h"
51 #include "llvm/ADT/StringExtras.h"
52 #include "llvm/ADT/StringSet.h"
53 using namespace llvm;
55 STATISTIC(EmittedInsts, "Number of machine instrs printed");
57 namespace {
58 class VISIBILITY_HIDDEN PPCAsmPrinter : public AsmPrinter {
59 protected:
60 struct FnStubInfo {
61 std::string Stub, LazyPtr, AnonSymbol;
63 FnStubInfo() {}
65 void Init(const GlobalValue *GV, Mangler *Mang) {
66 // Already initialized.
67 if (!Stub.empty()) return;
68 Stub = Mang->getMangledName(GV, "$stub", true);
69 LazyPtr = Mang->getMangledName(GV, "$lazy_ptr", true);
70 AnonSymbol = Mang->getMangledName(GV, "$stub$tmp", true);
73 void Init(const std::string &GV, Mangler *Mang) {
74 // Already initialized.
75 if (!Stub.empty()) return;
76 Stub = Mang->makeNameProper(GV + "$stub",
77 Mangler::Private);
78 LazyPtr = Mang->makeNameProper(GV + "$lazy_ptr",
79 Mangler::Private);
80 AnonSymbol = Mang->makeNameProper(GV + "$stub$tmp",
81 Mangler::Private);
85 StringMap<FnStubInfo> FnStubs;
86 StringMap<std::string> GVStubs, HiddenGVStubs, TOC;
87 const PPCSubtarget &Subtarget;
88 uint64_t LabelID;
89 public:
90 explicit PPCAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
91 const MCAsmInfo *T, bool V)
92 : AsmPrinter(O, TM, T, V),
93 Subtarget(TM.getSubtarget<PPCSubtarget>()), LabelID(0) {}
95 virtual const char *getPassName() const {
96 return "PowerPC Assembly Printer";
99 PPCTargetMachine &getTM() {
100 return static_cast<PPCTargetMachine&>(TM);
103 unsigned enumRegToMachineReg(unsigned enumReg) {
104 switch (enumReg) {
105 default: llvm_unreachable("Unhandled register!");
106 case PPC::CR0: return 0;
107 case PPC::CR1: return 1;
108 case PPC::CR2: return 2;
109 case PPC::CR3: return 3;
110 case PPC::CR4: return 4;
111 case PPC::CR5: return 5;
112 case PPC::CR6: return 6;
113 case PPC::CR7: return 7;
115 llvm_unreachable(0);
118 /// printInstruction - This method is automatically generated by tablegen
119 /// from the instruction set description. This method returns true if the
120 /// machine instruction was sufficiently described to print it, otherwise it
121 /// returns false.
122 void printInstruction(const MachineInstr *MI);
123 const char *getRegisterName(unsigned RegNo) const;
126 void printMachineInstruction(const MachineInstr *MI);
127 void printOp(const MachineOperand &MO);
129 /// stripRegisterPrefix - This method strips the character prefix from a
130 /// register name so that only the number is left. Used by for linux asm.
131 const char *stripRegisterPrefix(const char *RegName) {
132 switch (RegName[0]) {
133 case 'r':
134 case 'f':
135 case 'v': return RegName + 1;
136 case 'c': if (RegName[1] == 'r') return RegName + 2;
139 return RegName;
142 /// printRegister - Print register according to target requirements.
144 void printRegister(const MachineOperand &MO, bool R0AsZero) {
145 unsigned RegNo = MO.getReg();
146 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
148 // If we should use 0 for R0.
149 if (R0AsZero && RegNo == PPC::R0) {
150 O << "0";
151 return;
154 const char *RegName = TM.getRegisterInfo()->get(RegNo).AsmName;
155 // Linux assembler (Others?) does not take register mnemonics.
156 // FIXME - What about special registers used in mfspr/mtspr?
157 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
158 O << RegName;
161 void printOperand(const MachineInstr *MI, unsigned OpNo) {
162 const MachineOperand &MO = MI->getOperand(OpNo);
163 if (MO.isReg()) {
164 printRegister(MO, false);
165 } else if (MO.isImm()) {
166 O << MO.getImm();
167 } else {
168 printOp(MO);
172 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
173 unsigned AsmVariant, const char *ExtraCode);
174 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
175 unsigned AsmVariant, const char *ExtraCode);
178 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
179 char value = MI->getOperand(OpNo).getImm();
180 value = (value << (32-5)) >> (32-5);
181 O << (int)value;
183 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
184 unsigned char value = MI->getOperand(OpNo).getImm();
185 assert(value <= 31 && "Invalid u5imm argument!");
186 O << (unsigned int)value;
188 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
189 unsigned char value = MI->getOperand(OpNo).getImm();
190 assert(value <= 63 && "Invalid u6imm argument!");
191 O << (unsigned int)value;
193 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
194 O << (short)MI->getOperand(OpNo).getImm();
196 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
197 O << (unsigned short)MI->getOperand(OpNo).getImm();
199 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
200 if (MI->getOperand(OpNo).isImm()) {
201 O << (short)(MI->getOperand(OpNo).getImm()*4);
202 } else {
203 O << "lo16(";
204 printOp(MI->getOperand(OpNo));
205 if (TM.getRelocationModel() == Reloc::PIC_)
206 O << "-\"L" << getFunctionNumber() << "$pb\")";
207 else
208 O << ')';
211 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
212 // Branches can take an immediate operand. This is used by the branch
213 // selection pass to print $+8, an eight byte displacement from the PC.
214 if (MI->getOperand(OpNo).isImm()) {
215 O << "$+" << MI->getOperand(OpNo).getImm()*4;
216 } else {
217 printOp(MI->getOperand(OpNo));
220 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
221 const MachineOperand &MO = MI->getOperand(OpNo);
222 if (TM.getRelocationModel() != Reloc::Static) {
223 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
224 GlobalValue *GV = MO.getGlobal();
225 if (GV->isDeclaration() || GV->isWeakForLinker()) {
226 // Dynamically-resolved functions need a stub for the function.
227 FnStubInfo &FnInfo = FnStubs[Mang->getMangledName(GV)];
228 FnInfo.Init(GV, Mang);
229 O << FnInfo.Stub;
230 return;
233 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
234 FnStubInfo &FnInfo =FnStubs[Mang->makeNameProper(MO.getSymbolName())];
235 FnInfo.Init(MO.getSymbolName(), Mang);
236 O << FnInfo.Stub;
237 return;
241 printOp(MI->getOperand(OpNo));
243 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
244 O << (int)MI->getOperand(OpNo).getImm()*4;
246 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
247 O << "\"L" << getFunctionNumber() << "$pb\"\n";
248 O << "\"L" << getFunctionNumber() << "$pb\":";
250 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
251 if (MI->getOperand(OpNo).isImm()) {
252 printS16ImmOperand(MI, OpNo);
253 } else {
254 if (Subtarget.isDarwin()) O << "ha16(";
255 printOp(MI->getOperand(OpNo));
256 if (TM.getRelocationModel() == Reloc::PIC_)
257 O << "-\"L" << getFunctionNumber() << "$pb\"";
258 if (Subtarget.isDarwin())
259 O << ')';
260 else
261 O << "@ha";
264 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
265 if (MI->getOperand(OpNo).isImm()) {
266 printS16ImmOperand(MI, OpNo);
267 } else {
268 if (Subtarget.isDarwin()) O << "lo16(";
269 printOp(MI->getOperand(OpNo));
270 if (TM.getRelocationModel() == Reloc::PIC_)
271 O << "-\"L" << getFunctionNumber() << "$pb\"";
272 if (Subtarget.isDarwin())
273 O << ')';
274 else
275 O << "@l";
278 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
279 unsigned CCReg = MI->getOperand(OpNo).getReg();
280 unsigned RegNo = enumRegToMachineReg(CCReg);
281 O << (0x80 >> RegNo);
283 // The new addressing mode printers.
284 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
285 printSymbolLo(MI, OpNo);
286 O << '(';
287 if (MI->getOperand(OpNo+1).isReg() &&
288 MI->getOperand(OpNo+1).getReg() == PPC::R0)
289 O << "0";
290 else
291 printOperand(MI, OpNo+1);
292 O << ')';
294 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
295 if (MI->getOperand(OpNo).isImm())
296 printS16X4ImmOperand(MI, OpNo);
297 else
298 printSymbolLo(MI, OpNo);
299 O << '(';
300 if (MI->getOperand(OpNo+1).isReg() &&
301 MI->getOperand(OpNo+1).getReg() == PPC::R0)
302 O << "0";
303 else
304 printOperand(MI, OpNo+1);
305 O << ')';
308 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
309 // When used as the base register, r0 reads constant zero rather than
310 // the value contained in the register. For this reason, the darwin
311 // assembler requires that we print r0 as 0 (no r) when used as the base.
312 const MachineOperand &MO = MI->getOperand(OpNo);
313 printRegister(MO, true);
314 O << ", ";
315 printOperand(MI, OpNo+1);
318 void printTOCEntryLabel(const MachineInstr *MI, unsigned OpNo) {
319 const MachineOperand &MO = MI->getOperand(OpNo);
321 assert(MO.getType() == MachineOperand::MO_GlobalAddress);
323 GlobalValue *GV = MO.getGlobal();
325 std::string Name = Mang->getMangledName(GV);
327 // Map symbol -> label of TOC entry.
328 if (TOC.count(Name) == 0) {
329 std::string Label;
330 Label += MAI->getPrivateGlobalPrefix();
331 Label += "C";
332 Label += utostr(LabelID++);
334 TOC[Name] = Label;
337 O << TOC[Name] << "@toc";
340 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
341 const char *Modifier);
343 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
345 virtual void EmitExternalGlobal(const GlobalVariable *GV);
348 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
349 class VISIBILITY_HIDDEN PPCLinuxAsmPrinter : public PPCAsmPrinter {
350 public:
351 explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
352 const MCAsmInfo *T, bool V)
353 : PPCAsmPrinter(O, TM, T, V){}
355 virtual const char *getPassName() const {
356 return "Linux PPC Assembly Printer";
359 bool runOnMachineFunction(MachineFunction &F);
360 bool doFinalization(Module &M);
362 void getAnalysisUsage(AnalysisUsage &AU) const {
363 AU.setPreservesAll();
364 AU.addRequired<MachineModuleInfo>();
365 AU.addRequired<DwarfWriter>();
366 PPCAsmPrinter::getAnalysisUsage(AU);
369 void PrintGlobalVariable(const GlobalVariable *GVar);
372 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
373 /// OS X
374 class VISIBILITY_HIDDEN PPCDarwinAsmPrinter : public PPCAsmPrinter {
375 formatted_raw_ostream &OS;
376 public:
377 explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
378 const MCAsmInfo *T, bool V)
379 : PPCAsmPrinter(O, TM, T, V), OS(O) {}
381 virtual const char *getPassName() const {
382 return "Darwin PPC Assembly Printer";
385 bool runOnMachineFunction(MachineFunction &F);
386 bool doInitialization(Module &M);
387 bool doFinalization(Module &M);
389 void getAnalysisUsage(AnalysisUsage &AU) const {
390 AU.setPreservesAll();
391 AU.addRequired<MachineModuleInfo>();
392 AU.addRequired<DwarfWriter>();
393 PPCAsmPrinter::getAnalysisUsage(AU);
396 void PrintGlobalVariable(const GlobalVariable *GVar);
398 } // end of anonymous namespace
400 // Include the auto-generated portion of the assembly writer
401 #include "PPCGenAsmWriter.inc"
403 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
404 switch (MO.getType()) {
405 case MachineOperand::MO_Immediate:
406 llvm_unreachable("printOp() does not handle immediate values");
408 case MachineOperand::MO_MachineBasicBlock:
409 GetMBBSymbol(MO.getMBB()->getNumber())->print(O, MAI);
410 return;
411 case MachineOperand::MO_JumpTableIndex:
412 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
413 << '_' << MO.getIndex();
414 // FIXME: PIC relocation model
415 return;
416 case MachineOperand::MO_ConstantPoolIndex:
417 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
418 << '_' << MO.getIndex();
419 return;
420 case MachineOperand::MO_ExternalSymbol: {
421 // Computing the address of an external symbol, not calling it.
422 std::string Name(MAI->getGlobalPrefix());
423 Name += MO.getSymbolName();
425 if (TM.getRelocationModel() != Reloc::Static) {
426 GVStubs[Name] = Name+"$non_lazy_ptr";
427 Name += "$non_lazy_ptr";
429 O << Name;
430 return;
432 case MachineOperand::MO_GlobalAddress: {
433 // Computing the address of a global symbol, not calling it.
434 GlobalValue *GV = MO.getGlobal();
435 std::string Name;
437 // External or weakly linked global variables need non-lazily-resolved stubs
438 if (TM.getRelocationModel() != Reloc::Static &&
439 (GV->isDeclaration() || GV->isWeakForLinker())) {
440 if (!GV->hasHiddenVisibility()) {
441 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
442 GVStubs[Mang->getMangledName(GV)] = Name;
443 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
444 GV->hasAvailableExternallyLinkage()) {
445 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
446 HiddenGVStubs[Mang->getMangledName(GV)] = Name;
447 } else {
448 Name = Mang->getMangledName(GV);
450 } else {
451 Name = Mang->getMangledName(GV);
453 O << Name;
455 printOffset(MO.getOffset());
456 return;
459 default:
460 O << "<unknown operand type: " << MO.getType() << ">";
461 return;
465 /// EmitExternalGlobal - In this case we need to use the indirect symbol.
467 void PPCAsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
468 std::string Name;
470 if (TM.getRelocationModel() != Reloc::Static) {
471 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
472 } else {
473 Name = Mang->getMangledName(GV);
475 O << Name;
478 /// PrintAsmOperand - Print out an operand for an inline asm expression.
480 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
481 unsigned AsmVariant,
482 const char *ExtraCode) {
483 // Does this asm operand have a single letter operand modifier?
484 if (ExtraCode && ExtraCode[0]) {
485 if (ExtraCode[1] != 0) return true; // Unknown modifier.
487 switch (ExtraCode[0]) {
488 default: return true; // Unknown modifier.
489 case 'c': // Don't print "$" before a global var name or constant.
490 // PPC never has a prefix.
491 printOperand(MI, OpNo);
492 return false;
493 case 'L': // Write second word of DImode reference.
494 // Verify that this operand has two consecutive registers.
495 if (!MI->getOperand(OpNo).isReg() ||
496 OpNo+1 == MI->getNumOperands() ||
497 !MI->getOperand(OpNo+1).isReg())
498 return true;
499 ++OpNo; // Return the high-part.
500 break;
501 case 'I':
502 // Write 'i' if an integer constant, otherwise nothing. Used to print
503 // addi vs add, etc.
504 if (MI->getOperand(OpNo).isImm())
505 O << "i";
506 return false;
510 printOperand(MI, OpNo);
511 return false;
514 // At the moment, all inline asm memory operands are a single register.
515 // In any case, the output of this routine should always be just one
516 // assembler operand.
518 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
519 unsigned AsmVariant,
520 const char *ExtraCode) {
521 if (ExtraCode && ExtraCode[0])
522 return true; // Unknown modifier.
523 assert (MI->getOperand(OpNo).isReg());
524 O << "0(";
525 printOperand(MI, OpNo);
526 O << ")";
527 return false;
530 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
531 const char *Modifier) {
532 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
533 unsigned Code = MI->getOperand(OpNo).getImm();
534 if (!strcmp(Modifier, "cc")) {
535 switch ((PPC::Predicate)Code) {
536 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
537 case PPC::PRED_LT: O << "lt"; return;
538 case PPC::PRED_LE: O << "le"; return;
539 case PPC::PRED_EQ: O << "eq"; return;
540 case PPC::PRED_GE: O << "ge"; return;
541 case PPC::PRED_GT: O << "gt"; return;
542 case PPC::PRED_NE: O << "ne"; return;
543 case PPC::PRED_UN: O << "un"; return;
544 case PPC::PRED_NU: O << "nu"; return;
547 } else {
548 assert(!strcmp(Modifier, "reg") &&
549 "Need to specify 'cc' or 'reg' as predicate op modifier!");
550 // Don't print the register for 'always'.
551 if (Code == PPC::PRED_ALWAYS) return;
552 printOperand(MI, OpNo+1);
557 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
558 /// the current output stream.
560 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
561 ++EmittedInsts;
563 processDebugLoc(MI->getDebugLoc());
565 // Check for slwi/srwi mnemonics.
566 if (MI->getOpcode() == PPC::RLWINM) {
567 bool FoundMnemonic = false;
568 unsigned char SH = MI->getOperand(2).getImm();
569 unsigned char MB = MI->getOperand(3).getImm();
570 unsigned char ME = MI->getOperand(4).getImm();
571 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
572 O << "\tslwi "; FoundMnemonic = true;
574 if (SH <= 31 && MB == (32-SH) && ME == 31) {
575 O << "\tsrwi "; FoundMnemonic = true;
576 SH = 32-SH;
578 if (FoundMnemonic) {
579 printOperand(MI, 0);
580 O << ", ";
581 printOperand(MI, 1);
582 O << ", " << (unsigned int)SH << '\n';
583 return;
585 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
586 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
587 O << "\tmr ";
588 printOperand(MI, 0);
589 O << ", ";
590 printOperand(MI, 1);
591 O << '\n';
592 return;
594 } else if (MI->getOpcode() == PPC::RLDICR) {
595 unsigned char SH = MI->getOperand(2).getImm();
596 unsigned char ME = MI->getOperand(3).getImm();
597 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
598 if (63-SH == ME) {
599 O << "\tsldi ";
600 printOperand(MI, 0);
601 O << ", ";
602 printOperand(MI, 1);
603 O << ", " << (unsigned int)SH << '\n';
604 return;
608 printInstruction(MI);
610 if (VerboseAsm && !MI->getDebugLoc().isUnknown())
611 EmitComments(*MI);
612 O << '\n';
615 /// runOnMachineFunction - This uses the printMachineInstruction()
616 /// method to print assembly for each instruction.
618 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
619 this->MF = &MF;
621 SetupMachineFunction(MF);
622 O << "\n\n";
624 // Print out constants referenced by the function
625 EmitConstantPool(MF.getConstantPool());
627 // Print out labels for the function.
628 const Function *F = MF.getFunction();
629 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
631 switch (F->getLinkage()) {
632 default: llvm_unreachable("Unknown linkage type!");
633 case Function::PrivateLinkage:
634 case Function::InternalLinkage: // Symbols default to internal.
635 break;
636 case Function::ExternalLinkage:
637 O << "\t.global\t" << CurrentFnName << '\n'
638 << "\t.type\t" << CurrentFnName << ", @function\n";
639 break;
640 case Function::LinkerPrivateLinkage:
641 case Function::WeakAnyLinkage:
642 case Function::WeakODRLinkage:
643 case Function::LinkOnceAnyLinkage:
644 case Function::LinkOnceODRLinkage:
645 O << "\t.global\t" << CurrentFnName << '\n';
646 O << "\t.weak\t" << CurrentFnName << '\n';
647 break;
650 printVisibility(CurrentFnName, F->getVisibility());
652 EmitAlignment(MF.getAlignment(), F);
654 if (Subtarget.isPPC64()) {
655 // Emit an official procedure descriptor.
656 // FIXME 64-bit SVR4: Use MCSection here?
657 O << "\t.section\t\".opd\",\"aw\"\n";
658 O << "\t.align 3\n";
659 O << CurrentFnName << ":\n";
660 O << "\t.quad .L." << CurrentFnName << ",.TOC.@tocbase\n";
661 O << "\t.previous\n";
662 O << ".L." << CurrentFnName << ":\n";
663 } else {
664 O << CurrentFnName << ":\n";
667 // Emit pre-function debug information.
668 DW->BeginFunction(&MF);
670 // Print out code for the function.
671 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
672 I != E; ++I) {
673 // Print a label for the basic block.
674 if (I != MF.begin()) {
675 EmitBasicBlockStart(I);
676 O << '\n';
678 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
679 II != E; ++II) {
680 // Print the assembly for the instruction.
681 printMachineInstruction(II);
685 O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << '\n';
687 // Print out jump tables referenced by the function.
688 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
690 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
692 // Emit post-function debug information.
693 DW->EndFunction(&MF);
695 // We didn't modify anything.
696 return false;
699 void PPCLinuxAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
700 const TargetData *TD = TM.getTargetData();
702 if (!GVar->hasInitializer())
703 return; // External global require no code
705 // Check to see if this is a special global used by LLVM, if so, emit it.
706 if (EmitSpecialLLVMGlobal(GVar))
707 return;
709 std::string name = Mang->getMangledName(GVar);
711 printVisibility(name, GVar->getVisibility());
713 Constant *C = GVar->getInitializer();
714 const Type *Type = C->getType();
715 unsigned Size = TD->getTypeAllocSize(Type);
716 unsigned Align = TD->getPreferredAlignmentLog(GVar);
718 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(GVar, Mang,
719 TM));
721 if (C->isNullValue() && /* FIXME: Verify correct */
722 !GVar->hasSection() &&
723 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
724 GVar->isWeakForLinker())) {
725 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
727 if (GVar->hasExternalLinkage()) {
728 O << "\t.global " << name << '\n';
729 O << "\t.type " << name << ", @object\n";
730 O << name << ":\n";
731 O << "\t.zero " << Size << '\n';
732 } else if (GVar->hasLocalLinkage()) {
733 O << MAI->getLCOMMDirective() << name << ',' << Size;
734 } else {
735 O << ".comm " << name << ',' << Size;
737 if (VerboseAsm) {
738 O << "\t\t" << MAI->getCommentString() << " '";
739 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
740 O << "'";
742 O << '\n';
743 return;
746 switch (GVar->getLinkage()) {
747 case GlobalValue::LinkOnceAnyLinkage:
748 case GlobalValue::LinkOnceODRLinkage:
749 case GlobalValue::WeakAnyLinkage:
750 case GlobalValue::WeakODRLinkage:
751 case GlobalValue::CommonLinkage:
752 case GlobalValue::LinkerPrivateLinkage:
753 O << "\t.global " << name << '\n'
754 << "\t.type " << name << ", @object\n"
755 << "\t.weak " << name << '\n';
756 break;
757 case GlobalValue::AppendingLinkage:
758 // FIXME: appending linkage variables should go into a section of
759 // their name or something. For now, just emit them as external.
760 case GlobalValue::ExternalLinkage:
761 // If external or appending, declare as a global symbol
762 O << "\t.global " << name << '\n'
763 << "\t.type " << name << ", @object\n";
764 // FALL THROUGH
765 case GlobalValue::InternalLinkage:
766 case GlobalValue::PrivateLinkage:
767 break;
768 default:
769 llvm_unreachable("Unknown linkage type!");
772 EmitAlignment(Align, GVar);
773 O << name << ":";
774 if (VerboseAsm) {
775 O << "\t\t\t\t" << MAI->getCommentString() << " '";
776 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
777 O << "'";
779 O << '\n';
781 EmitGlobalConstant(C);
782 O << '\n';
785 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
786 const TargetData *TD = TM.getTargetData();
788 bool isPPC64 = TD->getPointerSizeInBits() == 64;
790 if (isPPC64 && !TOC.empty()) {
791 // FIXME 64-bit SVR4: Use MCSection here?
792 O << "\t.section\t\".toc\",\"aw\"\n";
794 for (StringMap<std::string>::iterator I = TOC.begin(), E = TOC.end();
795 I != E; ++I) {
796 O << I->second << ":\n";
797 O << "\t.tc " << I->getKeyData() << "[TC]," << I->getKeyData() << '\n';
801 return AsmPrinter::doFinalization(M);
804 /// runOnMachineFunction - This uses the printMachineInstruction()
805 /// method to print assembly for each instruction.
807 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
808 this->MF = &MF;
810 SetupMachineFunction(MF);
811 O << "\n\n";
813 // Print out constants referenced by the function
814 EmitConstantPool(MF.getConstantPool());
816 // Print out labels for the function.
817 const Function *F = MF.getFunction();
818 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
820 switch (F->getLinkage()) {
821 default: llvm_unreachable("Unknown linkage type!");
822 case Function::PrivateLinkage:
823 case Function::InternalLinkage: // Symbols default to internal.
824 break;
825 case Function::ExternalLinkage:
826 O << "\t.globl\t" << CurrentFnName << '\n';
827 break;
828 case Function::WeakAnyLinkage:
829 case Function::WeakODRLinkage:
830 case Function::LinkOnceAnyLinkage:
831 case Function::LinkOnceODRLinkage:
832 case Function::LinkerPrivateLinkage:
833 O << "\t.globl\t" << CurrentFnName << '\n';
834 O << "\t.weak_definition\t" << CurrentFnName << '\n';
835 break;
838 printVisibility(CurrentFnName, F->getVisibility());
840 EmitAlignment(MF.getAlignment(), F);
841 O << CurrentFnName << ":\n";
843 // Emit pre-function debug information.
844 DW->BeginFunction(&MF);
846 // If the function is empty, then we need to emit *something*. Otherwise, the
847 // function's label might be associated with something that it wasn't meant to
848 // be associated with. We emit a noop in this situation.
849 MachineFunction::iterator I = MF.begin();
851 if (++I == MF.end() && MF.front().empty())
852 O << "\tnop\n";
854 // Print out code for the function.
855 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
856 I != E; ++I) {
857 // Print a label for the basic block.
858 if (I != MF.begin()) {
859 EmitBasicBlockStart(I);
860 O << '\n';
862 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
863 II != IE; ++II) {
864 // Print the assembly for the instruction.
865 printMachineInstruction(II);
869 // Print out jump tables referenced by the function.
870 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
872 // Emit post-function debug information.
873 DW->EndFunction(&MF);
875 // We didn't modify anything.
876 return false;
880 bool PPCDarwinAsmPrinter::doInitialization(Module &M) {
881 static const char *const CPUDirectives[] = {
883 "ppc",
884 "ppc601",
885 "ppc602",
886 "ppc603",
887 "ppc7400",
888 "ppc750",
889 "ppc970",
890 "ppc64"
893 unsigned Directive = Subtarget.getDarwinDirective();
894 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
895 Directive = PPC::DIR_970;
896 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
897 Directive = PPC::DIR_7400;
898 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
899 Directive = PPC::DIR_64;
900 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
901 O << "\t.machine " << CPUDirectives[Directive] << '\n';
903 bool Result = AsmPrinter::doInitialization(M);
904 assert(MMI);
906 // Prime text sections so they are adjacent. This reduces the likelihood a
907 // large data or debug section causes a branch to exceed 16M limit.
908 TargetLoweringObjectFileMachO &TLOFMacho =
909 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
910 OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
911 if (TM.getRelocationModel() == Reloc::PIC_) {
912 OutStreamer.SwitchSection(
913 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
914 MCSectionMachO::S_SYMBOL_STUBS |
915 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
916 32, SectionKind::getText()));
917 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
918 OutStreamer.SwitchSection(
919 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
920 MCSectionMachO::S_SYMBOL_STUBS |
921 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
922 16, SectionKind::getText()));
924 OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
926 return Result;
929 void PPCDarwinAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
930 const TargetData *TD = TM.getTargetData();
932 if (!GVar->hasInitializer())
933 return; // External global require no code
935 // Check to see if this is a special global used by LLVM, if so, emit it.
936 if (EmitSpecialLLVMGlobal(GVar)) {
937 if (TM.getRelocationModel() == Reloc::Static) {
938 if (GVar->getName() == "llvm.global_ctors")
939 O << ".reference .constructors_used\n";
940 else if (GVar->getName() == "llvm.global_dtors")
941 O << ".reference .destructors_used\n";
943 return;
946 std::string name = Mang->getMangledName(GVar);
947 printVisibility(name, GVar->getVisibility());
949 Constant *C = GVar->getInitializer();
950 const Type *Type = C->getType();
951 unsigned Size = TD->getTypeAllocSize(Type);
952 unsigned Align = TD->getPreferredAlignmentLog(GVar);
954 const MCSection *TheSection =
955 getObjFileLowering().SectionForGlobal(GVar, Mang, TM);
956 OutStreamer.SwitchSection(TheSection);
958 /// FIXME: Drive this off the section!
959 if (C->isNullValue() && /* FIXME: Verify correct */
960 !GVar->hasSection() &&
961 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
962 GVar->isWeakForLinker()) &&
963 // Don't put things that should go in the cstring section into "comm".
964 !TheSection->getKind().isMergeableCString()) {
965 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
967 if (GVar->hasExternalLinkage()) {
968 O << "\t.globl " << name << '\n';
969 O << "\t.zerofill __DATA, __common, " << name << ", "
970 << Size << ", " << Align;
971 } else if (GVar->hasLocalLinkage()) {
972 O << MAI->getLCOMMDirective() << name << ',' << Size << ',' << Align;
973 } else if (!GVar->hasCommonLinkage()) {
974 O << "\t.globl " << name << '\n'
975 << MAI->getWeakDefDirective() << name << '\n';
976 EmitAlignment(Align, GVar);
977 O << name << ":";
978 if (VerboseAsm) {
979 O << "\t\t\t\t" << MAI->getCommentString() << " ";
980 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
982 O << '\n';
983 EmitGlobalConstant(C);
984 return;
985 } else {
986 O << ".comm " << name << ',' << Size;
987 // Darwin 9 and above support aligned common data.
988 if (Subtarget.isDarwin9())
989 O << ',' << Align;
991 if (VerboseAsm) {
992 O << "\t\t" << MAI->getCommentString() << " '";
993 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
994 O << "'";
996 O << '\n';
997 return;
1000 switch (GVar->getLinkage()) {
1001 case GlobalValue::LinkOnceAnyLinkage:
1002 case GlobalValue::LinkOnceODRLinkage:
1003 case GlobalValue::WeakAnyLinkage:
1004 case GlobalValue::WeakODRLinkage:
1005 case GlobalValue::CommonLinkage:
1006 case GlobalValue::LinkerPrivateLinkage:
1007 O << "\t.globl " << name << '\n'
1008 << "\t.weak_definition " << name << '\n';
1009 break;
1010 case GlobalValue::AppendingLinkage:
1011 // FIXME: appending linkage variables should go into a section of
1012 // their name or something. For now, just emit them as external.
1013 case GlobalValue::ExternalLinkage:
1014 // If external or appending, declare as a global symbol
1015 O << "\t.globl " << name << '\n';
1016 // FALL THROUGH
1017 case GlobalValue::InternalLinkage:
1018 case GlobalValue::PrivateLinkage:
1019 break;
1020 default:
1021 llvm_unreachable("Unknown linkage type!");
1024 EmitAlignment(Align, GVar);
1025 O << name << ":";
1026 if (VerboseAsm) {
1027 O << "\t\t\t\t" << MAI->getCommentString() << " '";
1028 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1029 O << "'";
1031 O << '\n';
1033 EmitGlobalConstant(C);
1034 O << '\n';
1037 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
1038 const TargetData *TD = TM.getTargetData();
1040 bool isPPC64 = TD->getPointerSizeInBits() == 64;
1042 // Darwin/PPC always uses mach-o.
1043 TargetLoweringObjectFileMachO &TLOFMacho =
1044 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
1047 const MCSection *LSPSection = 0;
1048 if (!FnStubs.empty()) // .lazy_symbol_pointer
1049 LSPSection = TLOFMacho.getLazySymbolPointerSection();
1052 // Output stubs for dynamically-linked functions
1053 if (TM.getRelocationModel() == Reloc::PIC_ && !FnStubs.empty()) {
1054 const MCSection *StubSection =
1055 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
1056 MCSectionMachO::S_SYMBOL_STUBS |
1057 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1058 32, SectionKind::getText());
1059 for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1060 I != E; ++I) {
1061 OutStreamer.SwitchSection(StubSection);
1062 EmitAlignment(4);
1063 const FnStubInfo &Info = I->second;
1064 O << Info.Stub << ":\n";
1065 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1066 O << "\tmflr r0\n";
1067 O << "\tbcl 20,31," << Info.AnonSymbol << '\n';
1068 O << Info.AnonSymbol << ":\n";
1069 O << "\tmflr r11\n";
1070 O << "\taddis r11,r11,ha16(" << Info.LazyPtr << "-" << Info.AnonSymbol;
1071 O << ")\n";
1072 O << "\tmtlr r0\n";
1073 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1074 O << Info.LazyPtr << "-" << Info.AnonSymbol << ")(r11)\n";
1075 O << "\tmtctr r12\n";
1076 O << "\tbctr\n";
1078 OutStreamer.SwitchSection(LSPSection);
1079 O << Info.LazyPtr << ":\n";
1080 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1081 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1083 } else if (!FnStubs.empty()) {
1084 const MCSection *StubSection =
1085 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
1086 MCSectionMachO::S_SYMBOL_STUBS |
1087 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1088 16, SectionKind::getText());
1090 for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1091 I != E; ++I) {
1092 OutStreamer.SwitchSection(StubSection);
1093 EmitAlignment(4);
1094 const FnStubInfo &Info = I->second;
1095 O << Info.Stub << ":\n";
1096 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1097 O << "\tlis r11,ha16(" << Info.LazyPtr << ")\n";
1098 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1099 O << Info.LazyPtr << ")(r11)\n";
1100 O << "\tmtctr r12\n";
1101 O << "\tbctr\n";
1102 OutStreamer.SwitchSection(LSPSection);
1103 O << Info.LazyPtr << ":\n";
1104 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1105 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1109 O << '\n';
1111 if (MAI->doesSupportExceptionHandling() && MMI) {
1112 // Add the (possibly multiple) personalities to the set of global values.
1113 // Only referenced functions get into the Personalities list.
1114 const std::vector<Function *> &Personalities = MMI->getPersonalities();
1115 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1116 E = Personalities.end(); I != E; ++I) {
1117 if (*I)
1118 GVStubs[Mang->getMangledName(*I)] =
1119 Mang->getMangledName(*I, "$non_lazy_ptr", true);
1123 // Output macho stubs for external and common global variables.
1124 if (!GVStubs.empty()) {
1125 // Switch with ".non_lazy_symbol_pointer" directive.
1126 OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
1127 EmitAlignment(isPPC64 ? 3 : 2);
1129 for (StringMap<std::string>::iterator I = GVStubs.begin(),
1130 E = GVStubs.end(); I != E; ++I) {
1131 O << I->second << ":\n";
1132 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1133 O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
1137 if (!HiddenGVStubs.empty()) {
1138 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
1139 EmitAlignment(isPPC64 ? 3 : 2);
1140 for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
1141 E = HiddenGVStubs.end(); I != E; ++I) {
1142 O << I->second << ":\n";
1143 O << (isPPC64 ? "\t.quad\t" : "\t.long\t") << I->getKeyData() << '\n';
1147 // Funny Darwin hack: This flag tells the linker that no global symbols
1148 // contain code that falls through to other global symbols (e.g. the obvious
1149 // implementation of multiple entry points). If this doesn't occur, the
1150 // linker can safely perform dead code stripping. Since LLVM never generates
1151 // code that does this, it is always safe to set.
1152 O << "\t.subsections_via_symbols\n";
1154 return AsmPrinter::doFinalization(M);
1159 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1160 /// for a MachineFunction to the given output stream, in a format that the
1161 /// Darwin assembler can deal with.
1163 static AsmPrinter *createPPCAsmPrinterPass(formatted_raw_ostream &o,
1164 TargetMachine &tm,
1165 const MCAsmInfo *tai,
1166 bool verbose) {
1167 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1169 if (Subtarget->isDarwin())
1170 return new PPCDarwinAsmPrinter(o, tm, tai, verbose);
1171 return new PPCLinuxAsmPrinter(o, tm, tai, verbose);
1174 // Force static initialization.
1175 extern "C" void LLVMInitializePowerPCAsmPrinter() {
1176 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
1177 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);