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/MachineConstantPool.h"
29 #include "llvm/CodeGen/MachineFunctionPass.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/CodeGen/ValueTypes.h"
32 #include "llvm/Support/Mangler.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Target/MRegisterInfo.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/ADT/Statistic.h"
39 #include "llvm/ADT/StringExtras.h"
44 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
46 class PPCAsmPrinter : public AsmPrinter {
48 std::set<std::string> FnStubs, GVStubs, LinkOnceStubs;
50 PPCAsmPrinter(std::ostream &O, TargetMachine &TM)
51 : AsmPrinter(O, TM) {}
53 virtual const char *getPassName() const {
54 return "PowerPC Assembly Printer";
57 PPCTargetMachine &getTM() {
58 return static_cast<PPCTargetMachine&>(TM);
61 void printConstantPool(MachineConstantPool *MCP);
63 unsigned enumRegToMachineReg(unsigned enumReg) {
65 default: assert(0 && "Unhandled register!"); break;
66 case PPC::CR0: return 0;
67 case PPC::CR1: return 1;
68 case PPC::CR2: return 2;
69 case PPC::CR3: return 3;
70 case PPC::CR4: return 4;
71 case PPC::CR5: return 5;
72 case PPC::CR6: return 6;
73 case PPC::CR7: return 7;
78 /// printInstruction - This method is automatically generated by tablegen
79 /// from the instruction set description. This method returns true if the
80 /// machine instruction was sufficiently described to print it, otherwise it
82 bool printInstruction(const MachineInstr *MI);
84 void printMachineInstruction(const MachineInstr *MI);
85 void printOp(const MachineOperand &MO);
87 void printOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT){
88 const MachineOperand &MO = MI->getOperand(OpNo);
89 if (MO.getType() == MachineOperand::MO_MachineRegister) {
90 assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??");
91 O << TM.getRegisterInfo()->get(MO.getReg()).Name;
92 } else if (MO.isImmediate()) {
93 O << MO.getImmedValue();
99 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo,
101 unsigned char value = MI->getOperand(OpNo).getImmedValue();
102 assert(value <= 31 && "Invalid u5imm argument!");
103 O << (unsigned int)value;
105 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo,
107 unsigned char value = MI->getOperand(OpNo).getImmedValue();
108 assert(value <= 63 && "Invalid u6imm argument!");
109 O << (unsigned int)value;
111 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo,
113 O << (short)MI->getOperand(OpNo).getImmedValue();
115 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo,
117 O << (unsigned short)MI->getOperand(OpNo).getImmedValue();
119 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo,
121 O << (short)MI->getOperand(OpNo).getImmedValue()*4;
123 void printBranchOperand(const MachineInstr *MI, unsigned OpNo,
125 // Branches can take an immediate operand. This is used by the branch
126 // selection pass to print $+8, an eight byte displacement from the PC.
127 if (MI->getOperand(OpNo).isImmediate()) {
128 O << "$+" << MI->getOperand(OpNo).getImmedValue();
130 printOp(MI->getOperand(OpNo));
133 void printCallOperand(const MachineInstr *MI, unsigned OpNo,
135 const MachineOperand &MO = MI->getOperand(OpNo);
136 if (!PPCGenerateStaticCode) {
137 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
138 std::string Name(GlobalPrefix); Name += MO.getSymbolName();
139 FnStubs.insert(Name);
140 O << "L" << Name << "$stub";
142 } else if (MO.getType() == MachineOperand::MO_GlobalAddress &&
143 isa<Function>(MO.getGlobal()) &&
144 cast<Function>(MO.getGlobal())->isExternal()) {
145 // Dynamically-resolved functions need a stub for the function.
146 std::string Name = Mang->getValueName(MO.getGlobal());
147 FnStubs.insert(Name);
148 O << "L" << Name << "$stub";
153 printOp(MI->getOperand(OpNo));
155 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo,
157 O << (int)MI->getOperand(OpNo).getImmedValue()*4;
159 void printPICLabel(const MachineInstr *MI, unsigned OpNo,
161 // FIXME: should probably be converted to cout.width and cout.fill
162 O << "\"L0000" << getFunctionNumber() << "$pb\"\n";
163 O << "\"L0000" << getFunctionNumber() << "$pb\":";
165 void printSymbolHi(const MachineInstr *MI, unsigned OpNo,
167 if (MI->getOperand(OpNo).isImmediate()) {
168 printS16ImmOperand(MI, OpNo, VT);
171 printOp(MI->getOperand(OpNo));
173 O << "-\"L0000" << getFunctionNumber() << "$pb\")";
178 void printSymbolLo(const MachineInstr *MI, unsigned OpNo,
180 if (MI->getOperand(OpNo).isImmediate()) {
181 printS16ImmOperand(MI, OpNo, VT);
184 printOp(MI->getOperand(OpNo));
186 O << "-\"L0000" << getFunctionNumber() << "$pb\")";
191 void printcrbitm(const MachineInstr *MI, unsigned OpNo,
193 unsigned CCReg = MI->getOperand(OpNo).getReg();
194 unsigned RegNo = enumRegToMachineReg(CCReg);
195 O << (0x80 >> RegNo);
198 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
199 virtual bool doFinalization(Module &M) = 0;
202 /// DarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac OS
205 struct DarwinAsmPrinter : public PPCAsmPrinter {
207 DarwinAsmPrinter(std::ostream &O, TargetMachine &TM)
208 : PPCAsmPrinter(O, TM) {
211 PrivateGlobalPrefix = "L"; // Marker for constant pool idxs
212 ZeroDirective = "\t.space\t"; // ".space N" emits N zeros.
213 Data64bitsDirective = 0; // we can't emit a 64-bit unit
214 AlignmentIsInBytes = false; // Alignment is by power of 2.
217 virtual const char *getPassName() const {
218 return "Darwin PPC Assembly Printer";
221 bool runOnMachineFunction(MachineFunction &F);
222 bool doInitialization(Module &M);
223 bool doFinalization(Module &M);
226 /// AIXAsmPrinter - PowerPC assembly printer, customized for AIX
228 struct AIXAsmPrinter : public PPCAsmPrinter {
229 /// Map for labels corresponding to global variables
231 std::map<const GlobalVariable*,std::string> GVToLabelMap;
233 AIXAsmPrinter(std::ostream &O, TargetMachine &TM)
234 : PPCAsmPrinter(O, TM) {
237 ZeroDirective = "\t.space\t"; // ".space N" emits N zeros.
238 Data64bitsDirective = 0; // we can't emit a 64-bit unit
239 AlignmentIsInBytes = false; // Alignment is by power of 2.
242 virtual const char *getPassName() const {
243 return "AIX PPC Assembly Printer";
246 bool runOnMachineFunction(MachineFunction &F);
247 bool doInitialization(Module &M);
248 bool doFinalization(Module &M);
250 } // end of anonymous namespace
252 /// createDarwinAsmPrinterPass - Returns a pass that prints the PPC assembly
253 /// code for a MachineFunction to the given output stream, in a format that the
254 /// Darwin assembler can deal with.
256 FunctionPass *llvm::createDarwinAsmPrinter(std::ostream &o, TargetMachine &tm) {
257 return new DarwinAsmPrinter(o, tm);
260 /// createAIXAsmPrinterPass - Returns a pass that prints the PPC assembly code
261 /// for a MachineFunction to the given output stream, in a format that the
262 /// AIX 5L assembler can deal with.
264 FunctionPass *llvm::createAIXAsmPrinter(std::ostream &o, TargetMachine &tm) {
265 return new AIXAsmPrinter(o, tm);
268 // Include the auto-generated portion of the assembly writer
269 #include "PPCGenAsmWriter.inc"
271 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
272 const MRegisterInfo &RI = *TM.getRegisterInfo();
275 switch (MO.getType()) {
276 case MachineOperand::MO_VirtualRegister:
277 if (Value *V = MO.getVRegValueOrNull()) {
278 O << "<" << V->getName() << ">";
282 case MachineOperand::MO_MachineRegister:
283 case MachineOperand::MO_CCRegister:
284 O << RI.get(MO.getReg()).Name;
287 case MachineOperand::MO_SignExtendedImmed:
288 case MachineOperand::MO_UnextendedImmed:
289 std::cerr << "printOp() does not handle immediate values\n";
293 case MachineOperand::MO_PCRelativeDisp:
294 std::cerr << "Shouldn't use addPCDisp() when building PPC MachineInstrs";
298 case MachineOperand::MO_MachineBasicBlock: {
299 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
300 O << PrivateGlobalPrefix << "BB" << getFunctionNumber() << "_"
301 << MBBOp->getNumber() << "\t; " << MBBOp->getBasicBlock()->getName();
305 case MachineOperand::MO_ConstantPoolIndex:
306 O << PrivateGlobalPrefix << "CPI" << getFunctionNumber()
307 << '_' << MO.getConstantPoolIndex();
310 case MachineOperand::MO_ExternalSymbol:
311 O << GlobalPrefix << MO.getSymbolName();
314 case MachineOperand::MO_GlobalAddress: {
315 GlobalValue *GV = MO.getGlobal();
316 std::string Name = Mang->getValueName(GV);
318 // External or weakly linked global variables need non-lazily-resolved stubs
319 if (!PPCGenerateStaticCode &&
320 ((GV->isExternal() || GV->hasWeakLinkage() ||
321 GV->hasLinkOnceLinkage()))) {
322 if (GV->hasLinkOnceLinkage())
323 LinkOnceStubs.insert(Name);
325 GVStubs.insert(Name);
326 O << "L" << Name << "$non_lazy_ptr";
335 O << "<unknown operand type: " << MO.getType() << ">";
340 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
341 /// the current output stream.
343 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
346 // Check for slwi/srwi mnemonics.
347 if (MI->getOpcode() == PPC::RLWINM) {
348 bool FoundMnemonic = false;
349 unsigned char SH = MI->getOperand(2).getImmedValue();
350 unsigned char MB = MI->getOperand(3).getImmedValue();
351 unsigned char ME = MI->getOperand(4).getImmedValue();
352 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
353 O << "slwi "; FoundMnemonic = true;
355 if (SH <= 31 && MB == (32-SH) && ME == 31) {
356 O << "srwi "; FoundMnemonic = true;
360 printOperand(MI, 0, MVT::i64);
362 printOperand(MI, 1, MVT::i64);
363 O << ", " << (unsigned int)SH << "\n";
368 if (printInstruction(MI))
369 return; // Printer was automatically generated
371 assert(0 && "Unhandled instruction in asm writer!");
376 /// printConstantPool - Print to the current output stream assembly
377 /// representations of the constants in the constant pool MCP. This is
378 /// used to print out constants which have been "spilled to memory" by
379 /// the code generator.
381 void PPCAsmPrinter::printConstantPool(MachineConstantPool *MCP) {
382 const std::vector<Constant*> &CP = MCP->getConstants();
383 const TargetData &TD = TM.getTargetData();
385 if (CP.empty()) return;
387 SwitchSection(".const", 0);
388 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
389 // FIXME: force doubles to be naturally aligned. We should handle this
390 // more correctly in the future.
391 unsigned Alignment = TD.getTypeAlignmentShift(CP[i]->getType());
392 if (CP[i]->getType() == Type::DoubleTy && Alignment < 3) Alignment = 3;
394 EmitAlignment(Alignment);
395 O << PrivateGlobalPrefix << "CPI" << getFunctionNumber() << '_' << i
396 << ":\t\t\t\t\t" << CommentString << *CP[i] << '\n';
397 EmitGlobalConstant(CP[i]);
402 /// runOnMachineFunction - This uses the printMachineInstruction()
403 /// method to print assembly for each instruction.
405 bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
406 SetupMachineFunction(MF);
409 // Print out constants referenced by the function
410 printConstantPool(MF.getConstantPool());
412 // Print out labels for the function.
413 const Function *F = MF.getFunction();
414 SwitchSection(".text", F);
416 if (!F->hasInternalLinkage())
417 O << "\t.globl\t" << CurrentFnName << "\n";
418 O << CurrentFnName << ":\n";
420 // Print out code for the function.
421 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
423 // Print a label for the basic block.
424 if (I != MF.begin()) {
425 O << PrivateGlobalPrefix << "BB" << getFunctionNumber() << '_'
426 << I->getNumber() << ":\t";
427 if (!I->getBasicBlock()->getName().empty())
428 O << CommentString << " " << I->getBasicBlock()->getName();
431 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
433 // Print the assembly for the instruction.
435 printMachineInstruction(II);
439 // We didn't modify anything.
444 bool DarwinAsmPrinter::doInitialization(Module &M) {
445 if (TM.getSubtarget<PPCSubtarget>().isGigaProcessor())
446 O << "\t.machine ppc970\n";
447 AsmPrinter::doInitialization(M);
449 // Darwin wants symbols to be quoted if they have complex names.
450 Mang->setUseQuotes(true);
454 bool DarwinAsmPrinter::doFinalization(Module &M) {
455 const TargetData &TD = TM.getTargetData();
457 // Print out module-level global variables here.
458 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
460 if (I->hasInitializer()) { // External global require no code
462 std::string name = Mang->getValueName(I);
463 Constant *C = I->getInitializer();
464 unsigned Size = TD.getTypeSize(C->getType());
465 unsigned Align = TD.getTypeAlignmentShift(C->getType());
467 if (C->isNullValue() && /* FIXME: Verify correct */
468 (I->hasInternalLinkage() || I->hasWeakLinkage() ||
469 I->hasLinkOnceLinkage())) {
470 SwitchSection(".data", I);
471 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
472 if (I->hasInternalLinkage())
473 O << ".lcomm " << name << "," << Size << "," << Align;
475 O << ".comm " << name << "," << Size;
476 O << "\t\t; '" << I->getName() << "'\n";
478 switch (I->getLinkage()) {
479 case GlobalValue::LinkOnceLinkage:
480 SwitchSection("", 0);
481 O << ".section __TEXT,__textcoal_nt,coalesced,no_toc\n"
482 << ".weak_definition " << name << '\n'
483 << ".private_extern " << name << '\n'
484 << ".section __DATA,__datacoal_nt,coalesced,no_toc\n";
485 LinkOnceStubs.insert(name);
487 case GlobalValue::WeakLinkage:
488 O << ".weak_definition " << name << '\n'
489 << ".private_extern " << name << '\n';
491 case GlobalValue::AppendingLinkage:
492 // FIXME: appending linkage variables should go into a section of
493 // their name or something. For now, just emit them as external.
494 case GlobalValue::ExternalLinkage:
495 // If external or appending, declare as a global symbol
496 O << "\t.globl " << name << "\n";
498 case GlobalValue::InternalLinkage:
499 SwitchSection(".data", I);
502 std::cerr << "Unknown linkage type!";
506 EmitAlignment(Align, I);
507 O << name << ":\t\t\t\t; '" << I->getName() << "'\n";
508 EmitGlobalConstant(C);
512 // Output stubs for dynamically-linked functions
513 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
518 O << ".section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32\n";
520 O << "L" << *i << "$stub:\n";
521 O << "\t.indirect_symbol " << *i << "\n";
523 O << "\tbcl 20,31,L0$" << *i << "\n";
524 O << "L0$" << *i << ":\n";
526 O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
528 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
529 O << "\tmtctr r12\n";
532 O << ".lazy_symbol_pointer\n";
533 O << "L" << *i << "$lazy_ptr:\n";
534 O << "\t.indirect_symbol " << *i << "\n";
535 O << "\t.long dyld_stub_binding_helper\n";
537 O << "\t.section __TEXT,__symbol_stub1,symbol_stubs,pure_instructions,16\n";
539 O << "L" << *i << "$stub:\n";
540 O << "\t.indirect_symbol " << *i << "\n";
541 O << "\tlis r11,ha16(L" << *i << "$lazy_ptr)\n";
542 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
543 O << "\tmtctr r12\n";
545 O << "\t.lazy_symbol_pointer\n";
546 O << "L" << *i << "$lazy_ptr:\n";
547 O << "\t.indirect_symbol " << *i << "\n";
548 O << "\t.long dyld_stub_binding_helper\n";
554 // Output stubs for external global variables
555 if (GVStubs.begin() != GVStubs.end())
556 O << ".data\n.non_lazy_symbol_pointer\n";
557 for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
559 O << "L" << *i << "$non_lazy_ptr:\n";
560 O << "\t.indirect_symbol " << *i << "\n";
564 // Output stubs for link-once variables
565 if (LinkOnceStubs.begin() != LinkOnceStubs.end())
566 O << ".data\n.align 2\n";
567 for (std::set<std::string>::iterator i = LinkOnceStubs.begin(),
568 e = LinkOnceStubs.end(); i != e; ++i) {
569 O << "L" << *i << "$non_lazy_ptr:\n"
570 << "\t.long\t" << *i << '\n';
573 // Funny Darwin hack: This flag tells the linker that no global symbols
574 // contain code that falls through to other global symbols (e.g. the obvious
575 // implementation of multiple entry points). If this doesn't occur, the
576 // linker can safely perform dead code stripping. Since LLVM never generates
577 // code that does this, it is always safe to set.
578 O << "\t.subsections_via_symbols\n";
580 AsmPrinter::doFinalization(M);
581 return false; // success
584 /// runOnMachineFunction - This uses the printMachineInstruction()
585 /// method to print assembly for each instruction.
587 bool AIXAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
588 SetupMachineFunction(MF);
590 // Print out constants referenced by the function
591 printConstantPool(MF.getConstantPool());
593 // Print out header for the function.
594 O << "\t.csect .text[PR]\n"
596 << "\t.globl " << CurrentFnName << '\n'
597 << "\t.globl ." << CurrentFnName << '\n'
598 << "\t.csect " << CurrentFnName << "[DS],3\n"
599 << CurrentFnName << ":\n"
600 << "\t.llong ." << CurrentFnName << ", TOC[tc0], 0\n"
601 << "\t.csect .text[PR]\n"
602 << '.' << CurrentFnName << ":\n";
604 // Print out code for the function.
605 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
607 // Print a label for the basic block.
608 O << PrivateGlobalPrefix << "BB" << getFunctionNumber() << '_'
610 << ":\t" << CommentString << I->getBasicBlock()->getName() << '\n';
611 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
613 // Print the assembly for the instruction.
615 printMachineInstruction(II);
619 O << "LT.." << CurrentFnName << ":\n"
621 << "\t.byte 0,0,32,65,128,0,0,0\n"
622 << "\t.long LT.." << CurrentFnName << "-." << CurrentFnName << '\n'
624 << "\t.byte \"" << CurrentFnName << "\"\n"
627 // We didn't modify anything.
631 bool AIXAsmPrinter::doInitialization(Module &M) {
632 SwitchSection("", 0);
633 const TargetData &TD = TM.getTargetData();
635 O << "\t.machine \"ppc64\"\n"
637 << "\t.csect .text[PR]\n";
639 // Print out module-level global variables
640 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
642 if (!I->hasInitializer())
645 std::string Name = I->getName();
646 Constant *C = I->getInitializer();
647 // N.B.: We are defaulting to writable strings
648 if (I->hasExternalLinkage()) {
649 O << "\t.globl " << Name << '\n'
650 << "\t.csect .data[RW],3\n";
652 O << "\t.csect _global.rw_c[RW],3\n";
655 EmitGlobalConstant(C);
658 // Output labels for globals
659 if (M.global_begin() != M.global_end()) O << "\t.toc\n";
660 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
662 const GlobalVariable *GV = I;
663 // Do not output labels for unused variables
664 if (GV->isExternal() && GV->use_begin() == GV->use_end())
667 IncrementFunctionNumber();
668 std::string Name = GV->getName();
669 std::string Label = "LC.." + utostr(getFunctionNumber());
670 GVToLabelMap[GV] = Label;
672 << "\t.tc " << Name << "[TC]," << Name;
673 if (GV->isExternal()) O << "[RW]";
677 AsmPrinter::doInitialization(M);
678 return false; // success
681 bool AIXAsmPrinter::doFinalization(Module &M) {
682 const TargetData &TD = TM.getTargetData();
683 // Print out module-level global variables
684 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
686 if (I->hasInitializer() || I->hasExternalLinkage())
689 std::string Name = I->getName();
690 if (I->hasInternalLinkage()) {
691 O << "\t.lcomm " << Name << ",16,_global.bss_c";
693 O << "\t.comm " << Name << "," << TD.getTypeSize(I->getType())
694 << "," << Log2_32((unsigned)TD.getTypeAlignment(I->getType()));
696 O << "\t\t" << CommentString << " ";
697 WriteAsOperand(O, I, false, true, &M);
701 O << "_section_.text:\n"
702 << "\t.csect .data[RW],3\n"
703 << "\t.llong _section_.text\n";
704 AsmPrinter::doFinalization(M);
705 return false; // success