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 void EmitXXStructorList(Constant *List);
208 bool runOnMachineFunction(MachineFunction &F);
209 bool doInitialization(Module &M);
210 bool doFinalization(Module &M);
213 /// AIXAsmPrinter - PowerPC assembly printer, customized for AIX
215 struct AIXAsmPrinter : public PPCAsmPrinter {
216 /// Map for labels corresponding to global variables
218 std::map<const GlobalVariable*,std::string> GVToLabelMap;
220 AIXAsmPrinter(std::ostream &O, TargetMachine &TM)
221 : PPCAsmPrinter(O, TM) {
224 ZeroDirective = "\t.space\t"; // ".space N" emits N zeros.
225 Data64bitsDirective = 0; // we can't emit a 64-bit unit
226 AlignmentIsInBytes = false; // Alignment is by power of 2.
227 ConstantPoolSection = "\t.const\t";
230 virtual const char *getPassName() const {
231 return "AIX PPC Assembly Printer";
234 bool runOnMachineFunction(MachineFunction &F);
235 bool doInitialization(Module &M);
236 bool doFinalization(Module &M);
238 } // end of anonymous namespace
240 /// createDarwinAsmPrinterPass - Returns a pass that prints the PPC assembly
241 /// code for a MachineFunction to the given output stream, in a format that the
242 /// Darwin assembler can deal with.
244 FunctionPass *llvm::createDarwinAsmPrinter(std::ostream &o, TargetMachine &tm) {
245 return new DarwinAsmPrinter(o, tm);
248 /// createAIXAsmPrinterPass - Returns a pass that prints the PPC assembly code
249 /// for a MachineFunction to the given output stream, in a format that the
250 /// AIX 5L assembler can deal with.
252 FunctionPass *llvm::createAIXAsmPrinter(std::ostream &o, TargetMachine &tm) {
253 return new AIXAsmPrinter(o, tm);
256 // Include the auto-generated portion of the assembly writer
257 #include "PPCGenAsmWriter.inc"
259 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
260 const MRegisterInfo &RI = *TM.getRegisterInfo();
263 switch (MO.getType()) {
264 case MachineOperand::MO_VirtualRegister:
265 if (Value *V = MO.getVRegValueOrNull()) {
266 O << "<" << V->getName() << ">";
270 case MachineOperand::MO_MachineRegister:
271 case MachineOperand::MO_CCRegister:
272 O << RI.get(MO.getReg()).Name;
275 case MachineOperand::MO_SignExtendedImmed:
276 case MachineOperand::MO_UnextendedImmed:
277 std::cerr << "printOp() does not handle immediate values\n";
281 case MachineOperand::MO_PCRelativeDisp:
282 std::cerr << "Shouldn't use addPCDisp() when building PPC MachineInstrs";
286 case MachineOperand::MO_MachineBasicBlock: {
287 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
288 O << PrivateGlobalPrefix << "BB" << getFunctionNumber() << "_"
289 << MBBOp->getNumber() << "\t; " << MBBOp->getBasicBlock()->getName();
293 case MachineOperand::MO_ConstantPoolIndex:
294 O << PrivateGlobalPrefix << "CPI" << getFunctionNumber()
295 << '_' << MO.getConstantPoolIndex();
298 case MachineOperand::MO_ExternalSymbol:
299 O << GlobalPrefix << MO.getSymbolName();
302 case MachineOperand::MO_GlobalAddress: {
303 GlobalValue *GV = MO.getGlobal();
304 std::string Name = Mang->getValueName(GV);
306 // External or weakly linked global variables need non-lazily-resolved stubs
307 if (!PPCGenerateStaticCode &&
308 ((GV->isExternal() || GV->hasWeakLinkage() ||
309 GV->hasLinkOnceLinkage()))) {
310 if (GV->hasLinkOnceLinkage())
311 LinkOnceStubs.insert(Name);
313 GVStubs.insert(Name);
314 O << "L" << Name << "$non_lazy_ptr";
323 O << "<unknown operand type: " << MO.getType() << ">";
328 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
329 /// the current output stream.
331 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
334 // Check for slwi/srwi mnemonics.
335 if (MI->getOpcode() == PPC::RLWINM) {
336 bool FoundMnemonic = false;
337 unsigned char SH = MI->getOperand(2).getImmedValue();
338 unsigned char MB = MI->getOperand(3).getImmedValue();
339 unsigned char ME = MI->getOperand(4).getImmedValue();
340 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
341 O << "slwi "; FoundMnemonic = true;
343 if (SH <= 31 && MB == (32-SH) && ME == 31) {
344 O << "srwi "; FoundMnemonic = true;
351 O << ", " << (unsigned int)SH << "\n";
356 if (printInstruction(MI))
357 return; // Printer was automatically generated
359 assert(0 && "Unhandled instruction in asm writer!");
365 /// runOnMachineFunction - This uses the printMachineInstruction()
366 /// method to print assembly for each instruction.
368 bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
369 SetupMachineFunction(MF);
372 // Print out constants referenced by the function
373 EmitConstantPool(MF.getConstantPool());
375 // Print out labels for the function.
376 const Function *F = MF.getFunction();
377 SwitchSection(".text", F);
379 if (!F->hasInternalLinkage())
380 O << "\t.globl\t" << CurrentFnName << "\n";
381 O << CurrentFnName << ":\n";
383 // Print out code for the function.
384 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
386 // Print a label for the basic block.
387 if (I != MF.begin()) {
388 O << PrivateGlobalPrefix << "BB" << getFunctionNumber() << '_'
389 << I->getNumber() << ":\t";
390 if (!I->getBasicBlock()->getName().empty())
391 O << CommentString << " " << I->getBasicBlock()->getName();
394 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
396 // Print the assembly for the instruction.
398 printMachineInstruction(II);
402 // We didn't modify anything.
407 bool DarwinAsmPrinter::doInitialization(Module &M) {
408 if (TM.getSubtarget<PPCSubtarget>().isGigaProcessor())
409 O << "\t.machine ppc970\n";
410 AsmPrinter::doInitialization(M);
412 // Darwin wants symbols to be quoted if they have complex names.
413 Mang->setUseQuotes(true);
417 /// EmitXXStructorList - Emit the ctor or dtor list. On darwin, this just
418 /// prints out the function pointers.
419 void DarwinAsmPrinter::EmitXXStructorList(Constant *List) {
420 // Should be an array of '{ int, void ()* }' structs. The first value is the
421 // init priority, which we ignore.
422 if (!isa<ConstantArray>(List)) return;
423 ConstantArray *InitList = cast<ConstantArray>(List);
424 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
425 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
426 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
427 // Emit the function pointer.
428 EmitGlobalConstant(CS->getOperand(1));
432 bool DarwinAsmPrinter::doFinalization(Module &M) {
433 const TargetData &TD = TM.getTargetData();
435 // Print out module-level global variables here.
436 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
438 if (I->hasInitializer()) { // External global require no code
439 // Check to see if this is a special global used by LLVM.
440 if (I->hasAppendingLinkage()) {
441 if (I->getName() == "llvm.used")
442 continue; // No need to emit this at all.
443 if (I->getName() == "llvm.global_ctors") {
444 SwitchSection(".mod_init_func", 0);
446 EmitXXStructorList(I->getInitializer());
448 } else if (I->getName() == "llvm.global_dtors") {
449 SwitchSection(".mod_term_func", 0);
451 EmitXXStructorList(I->getInitializer());
457 std::string name = Mang->getValueName(I);
458 Constant *C = I->getInitializer();
459 unsigned Size = TD.getTypeSize(C->getType());
460 unsigned Align = TD.getTypeAlignmentShift(C->getType());
462 if (C->isNullValue() && /* FIXME: Verify correct */
463 (I->hasInternalLinkage() || I->hasWeakLinkage() ||
464 I->hasLinkOnceLinkage())) {
465 SwitchSection(".data", I);
466 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
467 if (I->hasInternalLinkage())
468 O << ".lcomm " << name << "," << Size << "," << Align;
470 O << ".comm " << name << "," << Size;
471 O << "\t\t; '" << I->getName() << "'\n";
473 switch (I->getLinkage()) {
474 case GlobalValue::LinkOnceLinkage:
475 SwitchSection("", 0);
476 O << ".section __TEXT,__textcoal_nt,coalesced,no_toc\n"
477 << ".weak_definition " << name << '\n'
478 << ".private_extern " << name << '\n'
479 << ".section __DATA,__datacoal_nt,coalesced,no_toc\n";
480 LinkOnceStubs.insert(name);
482 case GlobalValue::WeakLinkage:
483 O << ".weak_definition " << name << '\n'
484 << ".private_extern " << name << '\n';
486 case GlobalValue::AppendingLinkage:
487 // FIXME: appending linkage variables should go into a section of
488 // their name or something. For now, just emit them as external.
489 case GlobalValue::ExternalLinkage:
490 // If external or appending, declare as a global symbol
491 O << "\t.globl " << name << "\n";
493 case GlobalValue::InternalLinkage:
494 SwitchSection(".data", I);
497 std::cerr << "Unknown linkage type!";
501 EmitAlignment(Align, I);
502 O << name << ":\t\t\t\t; '" << I->getName() << "'\n";
503 EmitGlobalConstant(C);
507 // Output stubs for dynamically-linked functions
508 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
513 O << ".section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32\n";
515 O << "L" << *i << "$stub:\n";
516 O << "\t.indirect_symbol " << *i << "\n";
518 O << "\tbcl 20,31,L0$" << *i << "\n";
519 O << "L0$" << *i << ":\n";
521 O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
523 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
524 O << "\tmtctr r12\n";
527 O << ".lazy_symbol_pointer\n";
528 O << "L" << *i << "$lazy_ptr:\n";
529 O << "\t.indirect_symbol " << *i << "\n";
530 O << "\t.long dyld_stub_binding_helper\n";
532 O << "\t.section __TEXT,__symbol_stub1,symbol_stubs,pure_instructions,16\n";
534 O << "L" << *i << "$stub:\n";
535 O << "\t.indirect_symbol " << *i << "\n";
536 O << "\tlis r11,ha16(L" << *i << "$lazy_ptr)\n";
537 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
538 O << "\tmtctr r12\n";
540 O << "\t.lazy_symbol_pointer\n";
541 O << "L" << *i << "$lazy_ptr:\n";
542 O << "\t.indirect_symbol " << *i << "\n";
543 O << "\t.long dyld_stub_binding_helper\n";
549 // Output stubs for external global variables
550 if (GVStubs.begin() != GVStubs.end())
551 O << ".data\n.non_lazy_symbol_pointer\n";
552 for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
554 O << "L" << *i << "$non_lazy_ptr:\n";
555 O << "\t.indirect_symbol " << *i << "\n";
559 // Output stubs for link-once variables
560 if (LinkOnceStubs.begin() != LinkOnceStubs.end())
561 O << ".data\n.align 2\n";
562 for (std::set<std::string>::iterator i = LinkOnceStubs.begin(),
563 e = LinkOnceStubs.end(); i != e; ++i) {
564 O << "L" << *i << "$non_lazy_ptr:\n"
565 << "\t.long\t" << *i << '\n';
568 // Funny Darwin hack: This flag tells the linker that no global symbols
569 // contain code that falls through to other global symbols (e.g. the obvious
570 // implementation of multiple entry points). If this doesn't occur, the
571 // linker can safely perform dead code stripping. Since LLVM never generates
572 // code that does this, it is always safe to set.
573 O << "\t.subsections_via_symbols\n";
575 AsmPrinter::doFinalization(M);
576 return false; // success
579 /// runOnMachineFunction - This uses the printMachineInstruction()
580 /// method to print assembly for each instruction.
582 bool AIXAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
583 SetupMachineFunction(MF);
585 // Print out constants referenced by the function
586 EmitConstantPool(MF.getConstantPool());
588 // Print out header for the function.
589 O << "\t.csect .text[PR]\n"
591 << "\t.globl " << CurrentFnName << '\n'
592 << "\t.globl ." << CurrentFnName << '\n'
593 << "\t.csect " << CurrentFnName << "[DS],3\n"
594 << CurrentFnName << ":\n"
595 << "\t.llong ." << CurrentFnName << ", TOC[tc0], 0\n"
596 << "\t.csect .text[PR]\n"
597 << '.' << CurrentFnName << ":\n";
599 // Print out code for the function.
600 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
602 // Print a label for the basic block.
603 O << PrivateGlobalPrefix << "BB" << getFunctionNumber() << '_'
605 << ":\t" << CommentString << I->getBasicBlock()->getName() << '\n';
606 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
608 // Print the assembly for the instruction.
610 printMachineInstruction(II);
614 O << "LT.." << CurrentFnName << ":\n"
616 << "\t.byte 0,0,32,65,128,0,0,0\n"
617 << "\t.long LT.." << CurrentFnName << "-." << CurrentFnName << '\n'
619 << "\t.byte \"" << CurrentFnName << "\"\n"
622 // We didn't modify anything.
626 bool AIXAsmPrinter::doInitialization(Module &M) {
627 SwitchSection("", 0);
628 const TargetData &TD = TM.getTargetData();
630 O << "\t.machine \"ppc64\"\n"
632 << "\t.csect .text[PR]\n";
634 // Print out module-level global variables
635 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
637 if (!I->hasInitializer())
640 std::string Name = I->getName();
641 Constant *C = I->getInitializer();
642 // N.B.: We are defaulting to writable strings
643 if (I->hasExternalLinkage()) {
644 O << "\t.globl " << Name << '\n'
645 << "\t.csect .data[RW],3\n";
647 O << "\t.csect _global.rw_c[RW],3\n";
650 EmitGlobalConstant(C);
653 // Output labels for globals
654 if (M.global_begin() != M.global_end()) O << "\t.toc\n";
655 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
657 const GlobalVariable *GV = I;
658 // Do not output labels for unused variables
659 if (GV->isExternal() && GV->use_begin() == GV->use_end())
662 IncrementFunctionNumber();
663 std::string Name = GV->getName();
664 std::string Label = "LC.." + utostr(getFunctionNumber());
665 GVToLabelMap[GV] = Label;
667 << "\t.tc " << Name << "[TC]," << Name;
668 if (GV->isExternal()) O << "[RW]";
672 AsmPrinter::doInitialization(M);
673 return false; // success
676 bool AIXAsmPrinter::doFinalization(Module &M) {
677 const TargetData &TD = TM.getTargetData();
678 // Print out module-level global variables
679 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
681 if (I->hasInitializer() || I->hasExternalLinkage())
684 std::string Name = I->getName();
685 if (I->hasInternalLinkage()) {
686 O << "\t.lcomm " << Name << ",16,_global.bss_c";
688 O << "\t.comm " << Name << "," << TD.getTypeSize(I->getType())
689 << "," << Log2_32((unsigned)TD.getTypeAlignment(I->getType()));
691 O << "\t\t" << CommentString << " ";
692 WriteAsOperand(O, I, false, true, &M);
696 O << "_section_.text:\n"
697 << "\t.csect .data[RW],3\n"
698 << "\t.llong _section_.text\n";
699 AsmPrinter::doFinalization(M);
700 return false; // success