1 //===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly --------=//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to PowerPC assembly language. This printer is
12 // the output mechanism used by `llc'.
14 // Documentation at http://developer.apple.com/documentation/DeveloperTools/
15 // Reference/Assembler/ASMIntroduction/chapter_1_section_1.html
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "asmprinter"
21 #include "PPCTargetMachine.h"
22 #include "PPCSubtarget.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Module.h"
26 #include "llvm/Assembly/Writer.h"
27 #include "llvm/CodeGen/AsmPrinter.h"
28 #include "llvm/CodeGen/MachineFunctionPass.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "llvm/Support/Mangler.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Target/MRegisterInfo.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/StringExtras.h"
42 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
44 class PPCAsmPrinter : public AsmPrinter {
46 std::set<std::string> FnStubs, GVStubs, LinkOnceStubs;
48 PPCAsmPrinter(std::ostream &O, TargetMachine &TM)
49 : AsmPrinter(O, TM) {}
51 virtual const char *getPassName() const {
52 return "PowerPC Assembly Printer";
55 PPCTargetMachine &getTM() {
56 return static_cast<PPCTargetMachine&>(TM);
59 unsigned enumRegToMachineReg(unsigned enumReg) {
61 default: assert(0 && "Unhandled register!"); break;
62 case PPC::CR0: return 0;
63 case PPC::CR1: return 1;
64 case PPC::CR2: return 2;
65 case PPC::CR3: return 3;
66 case PPC::CR4: return 4;
67 case PPC::CR5: return 5;
68 case PPC::CR6: return 6;
69 case PPC::CR7: return 7;
74 /// printInstruction - This method is automatically generated by tablegen
75 /// from the instruction set description. This method returns true if the
76 /// machine instruction was sufficiently described to print it, otherwise it
78 bool printInstruction(const MachineInstr *MI);
80 void printMachineInstruction(const MachineInstr *MI);
81 void printOp(const MachineOperand &MO);
83 void printOperand(const MachineInstr *MI, unsigned OpNo){
84 const MachineOperand &MO = MI->getOperand(OpNo);
85 if (MO.getType() == MachineOperand::MO_MachineRegister) {
86 assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??");
87 O << TM.getRegisterInfo()->get(MO.getReg()).Name;
88 } else if (MO.isImmediate()) {
89 O << MO.getImmedValue();
95 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
96 unsigned char value = MI->getOperand(OpNo).getImmedValue();
97 assert(value <= 31 && "Invalid u5imm argument!");
98 O << (unsigned int)value;
100 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
101 unsigned char value = MI->getOperand(OpNo).getImmedValue();
102 assert(value <= 63 && "Invalid u6imm argument!");
103 O << (unsigned int)value;
105 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
106 O << (short)MI->getOperand(OpNo).getImmedValue();
108 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
109 O << (unsigned short)MI->getOperand(OpNo).getImmedValue();
111 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
112 O << (short)MI->getOperand(OpNo).getImmedValue()*4;
114 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
115 // Branches can take an immediate operand. This is used by the branch
116 // selection pass to print $+8, an eight byte displacement from the PC.
117 if (MI->getOperand(OpNo).isImmediate()) {
118 O << "$+" << MI->getOperand(OpNo).getImmedValue();
120 printOp(MI->getOperand(OpNo));
123 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
124 const MachineOperand &MO = MI->getOperand(OpNo);
125 if (!PPCGenerateStaticCode) {
126 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
127 std::string Name(GlobalPrefix); Name += MO.getSymbolName();
128 FnStubs.insert(Name);
129 O << "L" << Name << "$stub";
131 } else if (MO.getType() == MachineOperand::MO_GlobalAddress &&
132 isa<Function>(MO.getGlobal()) &&
133 cast<Function>(MO.getGlobal())->isExternal()) {
134 // Dynamically-resolved functions need a stub for the function.
135 std::string Name = Mang->getValueName(MO.getGlobal());
136 FnStubs.insert(Name);
137 O << "L" << Name << "$stub";
142 printOp(MI->getOperand(OpNo));
144 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
145 O << (int)MI->getOperand(OpNo).getImmedValue()*4;
147 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
148 // FIXME: should probably be converted to cout.width and cout.fill
149 O << "\"L0000" << getFunctionNumber() << "$pb\"\n";
150 O << "\"L0000" << getFunctionNumber() << "$pb\":";
152 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
153 if (MI->getOperand(OpNo).isImmediate()) {
154 printS16ImmOperand(MI, OpNo);
157 printOp(MI->getOperand(OpNo));
159 O << "-\"L0000" << getFunctionNumber() << "$pb\")";
164 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
165 if (MI->getOperand(OpNo).isImmediate()) {
166 printS16ImmOperand(MI, OpNo);
169 printOp(MI->getOperand(OpNo));
171 O << "-\"L0000" << getFunctionNumber() << "$pb\")";
176 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
177 unsigned CCReg = MI->getOperand(OpNo).getReg();
178 unsigned RegNo = enumRegToMachineReg(CCReg);
179 O << (0x80 >> RegNo);
182 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
183 virtual bool doFinalization(Module &M) = 0;
186 /// DarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac OS
189 struct DarwinAsmPrinter : public PPCAsmPrinter {
191 DarwinAsmPrinter(std::ostream &O, TargetMachine &TM)
192 : PPCAsmPrinter(O, TM) {
195 PrivateGlobalPrefix = "L"; // Marker for constant pool idxs
196 ZeroDirective = "\t.space\t"; // ".space N" emits N zeros.
197 Data64bitsDirective = 0; // we can't emit a 64-bit unit
198 AlignmentIsInBytes = false; // Alignment is by power of 2.
199 ConstantPoolSection = "\t.const\t";
202 virtual const char *getPassName() const {
203 return "Darwin PPC Assembly Printer";
206 bool runOnMachineFunction(MachineFunction &F);
207 bool doInitialization(Module &M);
208 bool doFinalization(Module &M);
211 /// AIXAsmPrinter - PowerPC assembly printer, customized for AIX
213 struct AIXAsmPrinter : public PPCAsmPrinter {
214 /// Map for labels corresponding to global variables
216 std::map<const GlobalVariable*,std::string> GVToLabelMap;
218 AIXAsmPrinter(std::ostream &O, TargetMachine &TM)
219 : PPCAsmPrinter(O, TM) {
222 ZeroDirective = "\t.space\t"; // ".space N" emits N zeros.
223 Data64bitsDirective = 0; // we can't emit a 64-bit unit
224 AlignmentIsInBytes = false; // Alignment is by power of 2.
225 ConstantPoolSection = "\t.const\t";
228 virtual const char *getPassName() const {
229 return "AIX PPC Assembly Printer";
232 bool runOnMachineFunction(MachineFunction &F);
233 bool doInitialization(Module &M);
234 bool doFinalization(Module &M);
236 } // end of anonymous namespace
238 /// createDarwinAsmPrinterPass - Returns a pass that prints the PPC assembly
239 /// code for a MachineFunction to the given output stream, in a format that the
240 /// Darwin assembler can deal with.
242 FunctionPass *llvm::createDarwinAsmPrinter(std::ostream &o, TargetMachine &tm) {
243 return new DarwinAsmPrinter(o, tm);
246 /// createAIXAsmPrinterPass - Returns a pass that prints the PPC assembly code
247 /// for a MachineFunction to the given output stream, in a format that the
248 /// AIX 5L assembler can deal with.
250 FunctionPass *llvm::createAIXAsmPrinter(std::ostream &o, TargetMachine &tm) {
251 return new AIXAsmPrinter(o, tm);
254 // Include the auto-generated portion of the assembly writer
255 #include "PPCGenAsmWriter.inc"
257 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
258 const MRegisterInfo &RI = *TM.getRegisterInfo();
261 switch (MO.getType()) {
262 case MachineOperand::MO_VirtualRegister:
263 if (Value *V = MO.getVRegValueOrNull()) {
264 O << "<" << V->getName() << ">";
268 case MachineOperand::MO_MachineRegister:
269 case MachineOperand::MO_CCRegister:
270 O << RI.get(MO.getReg()).Name;
273 case MachineOperand::MO_SignExtendedImmed:
274 case MachineOperand::MO_UnextendedImmed:
275 std::cerr << "printOp() does not handle immediate values\n";
279 case MachineOperand::MO_PCRelativeDisp:
280 std::cerr << "Shouldn't use addPCDisp() when building PPC MachineInstrs";
284 case MachineOperand::MO_MachineBasicBlock: {
285 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
286 O << PrivateGlobalPrefix << "BB" << getFunctionNumber() << "_"
287 << MBBOp->getNumber() << "\t; " << MBBOp->getBasicBlock()->getName();
291 case MachineOperand::MO_ConstantPoolIndex:
292 O << PrivateGlobalPrefix << "CPI" << getFunctionNumber()
293 << '_' << MO.getConstantPoolIndex();
296 case MachineOperand::MO_ExternalSymbol:
297 O << GlobalPrefix << MO.getSymbolName();
300 case MachineOperand::MO_GlobalAddress: {
301 GlobalValue *GV = MO.getGlobal();
302 std::string Name = Mang->getValueName(GV);
304 // External or weakly linked global variables need non-lazily-resolved stubs
305 if (!PPCGenerateStaticCode &&
306 ((GV->isExternal() || GV->hasWeakLinkage() ||
307 GV->hasLinkOnceLinkage()))) {
308 if (GV->hasLinkOnceLinkage())
309 LinkOnceStubs.insert(Name);
311 GVStubs.insert(Name);
312 O << "L" << Name << "$non_lazy_ptr";
321 O << "<unknown operand type: " << MO.getType() << ">";
326 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
327 /// the current output stream.
329 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
332 // Check for slwi/srwi mnemonics.
333 if (MI->getOpcode() == PPC::RLWINM) {
334 bool FoundMnemonic = false;
335 unsigned char SH = MI->getOperand(2).getImmedValue();
336 unsigned char MB = MI->getOperand(3).getImmedValue();
337 unsigned char ME = MI->getOperand(4).getImmedValue();
338 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
339 O << "slwi "; FoundMnemonic = true;
341 if (SH <= 31 && MB == (32-SH) && ME == 31) {
342 O << "srwi "; FoundMnemonic = true;
349 O << ", " << (unsigned int)SH << "\n";
354 if (printInstruction(MI))
355 return; // Printer was automatically generated
357 assert(0 && "Unhandled instruction in asm writer!");
363 /// runOnMachineFunction - This uses the printMachineInstruction()
364 /// method to print assembly for each instruction.
366 bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
367 SetupMachineFunction(MF);
370 // Print out constants referenced by the function
371 EmitConstantPool(MF.getConstantPool());
373 // Print out labels for the function.
374 const Function *F = MF.getFunction();
375 SwitchSection(".text", F);
377 if (!F->hasInternalLinkage())
378 O << "\t.globl\t" << CurrentFnName << "\n";
379 O << CurrentFnName << ":\n";
381 // Print out code for the function.
382 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
384 // Print a label for the basic block.
385 if (I != MF.begin()) {
386 O << PrivateGlobalPrefix << "BB" << getFunctionNumber() << '_'
387 << I->getNumber() << ":\t";
388 if (!I->getBasicBlock()->getName().empty())
389 O << CommentString << " " << I->getBasicBlock()->getName();
392 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
394 // Print the assembly for the instruction.
396 printMachineInstruction(II);
400 // We didn't modify anything.
405 bool DarwinAsmPrinter::doInitialization(Module &M) {
406 if (TM.getSubtarget<PPCSubtarget>().isGigaProcessor())
407 O << "\t.machine ppc970\n";
408 AsmPrinter::doInitialization(M);
410 // Darwin wants symbols to be quoted if they have complex names.
411 Mang->setUseQuotes(true);
415 bool DarwinAsmPrinter::doFinalization(Module &M) {
416 const TargetData &TD = TM.getTargetData();
418 // Print out module-level global variables here.
419 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
421 if (I->hasInitializer()) { // External global require no code
423 std::string name = Mang->getValueName(I);
424 Constant *C = I->getInitializer();
425 unsigned Size = TD.getTypeSize(C->getType());
426 unsigned Align = TD.getTypeAlignmentShift(C->getType());
428 if (C->isNullValue() && /* FIXME: Verify correct */
429 (I->hasInternalLinkage() || I->hasWeakLinkage() ||
430 I->hasLinkOnceLinkage())) {
431 SwitchSection(".data", I);
432 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
433 if (I->hasInternalLinkage())
434 O << ".lcomm " << name << "," << Size << "," << Align;
436 O << ".comm " << name << "," << Size;
437 O << "\t\t; '" << I->getName() << "'\n";
439 switch (I->getLinkage()) {
440 case GlobalValue::LinkOnceLinkage:
441 SwitchSection("", 0);
442 O << ".section __TEXT,__textcoal_nt,coalesced,no_toc\n"
443 << ".weak_definition " << name << '\n'
444 << ".private_extern " << name << '\n'
445 << ".section __DATA,__datacoal_nt,coalesced,no_toc\n";
446 LinkOnceStubs.insert(name);
448 case GlobalValue::WeakLinkage:
449 O << ".weak_definition " << name << '\n'
450 << ".private_extern " << name << '\n';
452 case GlobalValue::AppendingLinkage:
453 // FIXME: appending linkage variables should go into a section of
454 // their name or something. For now, just emit them as external.
455 case GlobalValue::ExternalLinkage:
456 // If external or appending, declare as a global symbol
457 O << "\t.globl " << name << "\n";
459 case GlobalValue::InternalLinkage:
460 SwitchSection(".data", I);
463 std::cerr << "Unknown linkage type!";
467 EmitAlignment(Align, I);
468 O << name << ":\t\t\t\t; '" << I->getName() << "'\n";
469 EmitGlobalConstant(C);
473 // Output stubs for dynamically-linked functions
474 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
479 O << ".section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32\n";
481 O << "L" << *i << "$stub:\n";
482 O << "\t.indirect_symbol " << *i << "\n";
484 O << "\tbcl 20,31,L0$" << *i << "\n";
485 O << "L0$" << *i << ":\n";
487 O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
489 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
490 O << "\tmtctr r12\n";
493 O << ".lazy_symbol_pointer\n";
494 O << "L" << *i << "$lazy_ptr:\n";
495 O << "\t.indirect_symbol " << *i << "\n";
496 O << "\t.long dyld_stub_binding_helper\n";
498 O << "\t.section __TEXT,__symbol_stub1,symbol_stubs,pure_instructions,16\n";
500 O << "L" << *i << "$stub:\n";
501 O << "\t.indirect_symbol " << *i << "\n";
502 O << "\tlis r11,ha16(L" << *i << "$lazy_ptr)\n";
503 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
504 O << "\tmtctr r12\n";
506 O << "\t.lazy_symbol_pointer\n";
507 O << "L" << *i << "$lazy_ptr:\n";
508 O << "\t.indirect_symbol " << *i << "\n";
509 O << "\t.long dyld_stub_binding_helper\n";
515 // Output stubs for external global variables
516 if (GVStubs.begin() != GVStubs.end())
517 O << ".data\n.non_lazy_symbol_pointer\n";
518 for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
520 O << "L" << *i << "$non_lazy_ptr:\n";
521 O << "\t.indirect_symbol " << *i << "\n";
525 // Output stubs for link-once variables
526 if (LinkOnceStubs.begin() != LinkOnceStubs.end())
527 O << ".data\n.align 2\n";
528 for (std::set<std::string>::iterator i = LinkOnceStubs.begin(),
529 e = LinkOnceStubs.end(); i != e; ++i) {
530 O << "L" << *i << "$non_lazy_ptr:\n"
531 << "\t.long\t" << *i << '\n';
534 // Funny Darwin hack: This flag tells the linker that no global symbols
535 // contain code that falls through to other global symbols (e.g. the obvious
536 // implementation of multiple entry points). If this doesn't occur, the
537 // linker can safely perform dead code stripping. Since LLVM never generates
538 // code that does this, it is always safe to set.
539 O << "\t.subsections_via_symbols\n";
541 AsmPrinter::doFinalization(M);
542 return false; // success
545 /// runOnMachineFunction - This uses the printMachineInstruction()
546 /// method to print assembly for each instruction.
548 bool AIXAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
549 SetupMachineFunction(MF);
551 // Print out constants referenced by the function
552 EmitConstantPool(MF.getConstantPool());
554 // Print out header for the function.
555 O << "\t.csect .text[PR]\n"
557 << "\t.globl " << CurrentFnName << '\n'
558 << "\t.globl ." << CurrentFnName << '\n'
559 << "\t.csect " << CurrentFnName << "[DS],3\n"
560 << CurrentFnName << ":\n"
561 << "\t.llong ." << CurrentFnName << ", TOC[tc0], 0\n"
562 << "\t.csect .text[PR]\n"
563 << '.' << CurrentFnName << ":\n";
565 // Print out code for the function.
566 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
568 // Print a label for the basic block.
569 O << PrivateGlobalPrefix << "BB" << getFunctionNumber() << '_'
571 << ":\t" << CommentString << I->getBasicBlock()->getName() << '\n';
572 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
574 // Print the assembly for the instruction.
576 printMachineInstruction(II);
580 O << "LT.." << CurrentFnName << ":\n"
582 << "\t.byte 0,0,32,65,128,0,0,0\n"
583 << "\t.long LT.." << CurrentFnName << "-." << CurrentFnName << '\n'
585 << "\t.byte \"" << CurrentFnName << "\"\n"
588 // We didn't modify anything.
592 bool AIXAsmPrinter::doInitialization(Module &M) {
593 SwitchSection("", 0);
594 const TargetData &TD = TM.getTargetData();
596 O << "\t.machine \"ppc64\"\n"
598 << "\t.csect .text[PR]\n";
600 // Print out module-level global variables
601 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
603 if (!I->hasInitializer())
606 std::string Name = I->getName();
607 Constant *C = I->getInitializer();
608 // N.B.: We are defaulting to writable strings
609 if (I->hasExternalLinkage()) {
610 O << "\t.globl " << Name << '\n'
611 << "\t.csect .data[RW],3\n";
613 O << "\t.csect _global.rw_c[RW],3\n";
616 EmitGlobalConstant(C);
619 // Output labels for globals
620 if (M.global_begin() != M.global_end()) O << "\t.toc\n";
621 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
623 const GlobalVariable *GV = I;
624 // Do not output labels for unused variables
625 if (GV->isExternal() && GV->use_begin() == GV->use_end())
628 IncrementFunctionNumber();
629 std::string Name = GV->getName();
630 std::string Label = "LC.." + utostr(getFunctionNumber());
631 GVToLabelMap[GV] = Label;
633 << "\t.tc " << Name << "[TC]," << Name;
634 if (GV->isExternal()) O << "[RW]";
638 AsmPrinter::doInitialization(M);
639 return false; // success
642 bool AIXAsmPrinter::doFinalization(Module &M) {
643 const TargetData &TD = TM.getTargetData();
644 // Print out module-level global variables
645 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
647 if (I->hasInitializer() || I->hasExternalLinkage())
650 std::string Name = I->getName();
651 if (I->hasInternalLinkage()) {
652 O << "\t.lcomm " << Name << ",16,_global.bss_c";
654 O << "\t.comm " << Name << "," << TD.getTypeSize(I->getType())
655 << "," << Log2_32((unsigned)TD.getTypeAlignment(I->getType()));
657 O << "\t\t" << CommentString << " ";
658 WriteAsOperand(O, I, false, true, &M);
662 O << "_section_.text:\n"
663 << "\t.csect .data[RW],3\n"
664 << "\t.llong _section_.text\n";
665 AsmPrinter::doFinalization(M);
666 return false; // success